A full-featured CRM built with React, shadcn/ui, and Supabase.
feat(deals): allow multiple categories per deal
erwanMarmelab2d3b040587f4
diff --git a/doc/src/content/docs/users/import-data.mdx b/doc/src/content/docs/users/import-data.mdxindex 7ab68d41..c8cf4f12 100644--- a/doc/src/content/docs/users/import-data.mdx+++ b/doc/src/content/docs/users/import-data.mdx@@ -41,12 +41,12 @@ The `name` column is required. `sector` is matched against the company sectors c### Deals```csv-name,company,category,stage,amount,expected_closing_date,description-New website,Acme,Website design,Opportunity,12000,2026-09-30,Redesign of the public website+name,company,categories,stage,amount,expected_closing_date,description+New website,Acme,"Website design, UI Design",Opportunity,12000,2026-09-30,Redesign of the public websitePrint campaign,Globex,Print project,Proposal Sent,4500,2026-10-15,```-The `name` column is required. The `company` column holds a company name: an existing company is reused, an unknown one is created. `category` and `stage` are matched against the deal categories and stages configured in your CRM, by stored value or displayed label. Since a deal always belongs to a stage, an empty or unrecognized `stage` falls back to the first stage of your pipeline.+The `name` column is required. The `company` column holds a company name: an existing company is reused, an unknown one is created. `categories` and `stage` are matched against the deal categories and stages configured in your CRM, by stored value or displayed label. A deal can have several categories: separate them with commas (quote the cell) or semicolons; unrecognized ones are skipped. Since a deal always belongs to a stage, an empty or unrecognized `stage` falls back to the first stage of your pipeline.## Export Contacts To CSVdiff --git a/src/components/atomic-crm/companies/CompanyShow.tsx b/src/components/atomic-crm/companies/CompanyShow.tsxindex 6e538223..91dee228 100644--- a/src/components/atomic-crm/companies/CompanyShow.tsx+++ b/src/components/atomic-crm/companies/CompanyShow.tsx@@ -25,7 +25,7 @@ import { useIsMobile } from "@/hooks/use-mobile";import { ActivityLog } from "../activity/ActivityLog";import { Avatar } from "../contacts/Avatar";import { TagsList } from "../contacts/TagsList";-import { findDealLabel } from "../deals/dealUtils";+import { findDealLabel, formatDealCategories } from "../deals/dealUtils";import { MobileContent } from "../layout/MobileContent";import MobileHeader from "../layout/MobileHeader";import { MobileBackButton } from "../misc/MobileBackButton";@@ -284,8 +284,8 @@ const DealsIterator = () => {currencyDisplay: "narrowSymbol",minimumSignificantDigits: 3,})}- {deal.category- ? `, ${dealCategories.find((c) => c.value === deal.category)?.label ?? deal.category}`+ {deal.categories?.length+ ? `, ${formatDealCategories(dealCategories, deal.categories)}`: ""}</div></div>diff --git a/src/components/atomic-crm/dataImport/DataImportButton.test.tsx b/src/components/atomic-crm/dataImport/DataImportButton.test.tsxindex fd6c967c..80c87967 100644--- a/src/components/atomic-crm/dataImport/DataImportButton.test.tsx+++ b/src/components/atomic-crm/dataImport/DataImportButton.test.tsx@@ -198,7 +198,7 @@ describe("DataImportButton", () => {{name: "New website",company: "Acme",- category: "Website design",+ categories: "Website design; Copywriting",stage: "Proposal Sent",amount: "12000",expected_closing_date: "2026-09-30",@@ -217,7 +217,7 @@ describe("DataImportButton", () => {expect(deals).toHaveLength(2);expect(deals[0]).toMatchObject({amount: 12000,- category: "website-design",+ categories: ["website-design", "copywriting"],company_id: companies[0].id,name: "New website",stage: "proposal-sent",diff --git a/src/components/atomic-crm/dataImport/deals_sample.csv b/src/components/atomic-crm/dataImport/deals_sample.csvindex a62dd7d7..dce846f8 100644--- a/src/components/atomic-crm/dataImport/deals_sample.csv+++ b/src/components/atomic-crm/dataImport/deals_sample.csv@@ -1,3 +1,3 @@-name,company,category,stage,amount,expected_closing_date,description-New website,Acme,Website design,Opportunity,12000,2026-09-30,Redesign of the public website+name,company,categories,stage,amount,expected_closing_date,description+New website,Acme,"Website design, UI Design",Opportunity,12000,2026-09-30,Redesign of the public websitePrint campaign,Globex,Print project,Proposal Sent,4500,2026-10-15,diff --git a/src/components/atomic-crm/dataImport/parseCell.test.ts b/src/components/atomic-crm/dataImport/parseCell.test.tsindex f7f78e0a..976d82e8 100644--- a/src/components/atomic-crm/dataImport/parseCell.test.ts+++ b/src/components/atomic-crm/dataImport/parseCell.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";import {toConfiguredValue,+ toConfiguredValues,toInteger,toIsoDate,toNumber,@@ -92,3 +93,23 @@ describe("toConfiguredValue", () => {expect(toConfiguredValue(null, stages)).toBeUndefined();});});++describe("toConfiguredValues", () => {+ it("matches each comma or semicolon separated entry", () => {+ expect(toConfiguredValues("Proposal Sent; opportunity", stages)).toEqual([+ "proposal-sent",+ "opportunity",+ ]);+ expect(toConfiguredValues("opportunity,Proposal Sent", stages)).toEqual([+ "opportunity",+ "proposal-sent",+ ]);+ });++ it("drops unknown entries and returns [] for an empty cell", () => {+ expect(toConfiguredValues("opportunity, Archived", stages)).toEqual([+ "opportunity",+ ]);+ expect(toConfiguredValues(null, stages)).toEqual([]);+ });+});diff --git a/src/components/atomic-crm/dataImport/parseCell.ts b/src/components/atomic-crm/dataImport/parseCell.tsindex 49eaea7c..05403d56 100644--- a/src/components/atomic-crm/dataImport/parseCell.ts+++ b/src/components/atomic-crm/dataImport/parseCell.ts@@ -67,3 +67,15 @@ export const toConfiguredValue = (option.label.toLowerCase() === text,)?.value;};++/**+ * Cell holding several configured options separated by "," or ";" (the+ * separator the CSV export uses for arrays). Unknown entries are dropped.+ */+export const toConfiguredValues = (+ cell: ImportCell,+ options: LabeledValue[],+): string[] =>+ (toText(cell)?.split(/[,;]/) ?? [])+ .map((entry) => toConfiguredValue(entry, options))+ .filter((value): value is string => value !== undefined);diff --git a/src/components/atomic-crm/dataImport/useDealImport.ts b/src/components/atomic-crm/dataImport/useDealImport.tsindex 3bfe7a22..1829ae14 100644--- a/src/components/atomic-crm/dataImport/useDealImport.ts+++ b/src/components/atomic-crm/dataImport/useDealImport.ts@@ -4,7 +4,13 @@ import { useDataProvider, useGetIdentity, type DataProvider } from "ra-core";import { useConfigurationContext } from "../root/ConfigurationContext";import { useCompanyResolver } from "./useCompanyResolver";import { createEachRow } from "./createEachRow";-import { toConfiguredValue, toInteger, toIsoDate, toText } from "./parseCell";+import {+ toConfiguredValue,+ toConfiguredValues,+ toInteger,+ toIsoDate,+ toText,+} from "./parseCell";import type { ImportRow, ProcessImportBatch } from "./types";/** One CSV row, with the values needed before its deal can be created. */@@ -55,7 +61,7 @@ export function useDealImport(): ProcessImportBatch {? companies.get(companyName)?.id: undefined,contact_ids: [],- category: toConfiguredValue(row.category, dealCategories),+ categories: toConfiguredValues(row.categories, dealCategories),stage,description: toText(row.description),// amount lands in a bigint column, which rejects "4500.50"diff --git a/src/components/atomic-crm/deals/DealCard.tsx b/src/components/atomic-crm/deals/DealCard.tsxindex c10534fe..a85c92f0 100644--- a/src/components/atomic-crm/deals/DealCard.tsx+++ b/src/components/atomic-crm/deals/DealCard.tsx@@ -2,12 +2,12 @@ import { Draggable } from "@hello-pangea/dnd";import { useRedirect, RecordContextProvider } from "ra-core";import { ReferenceField } from "@/components/admin/reference-field";import { NumberField } from "@/components/admin/number-field";-import { SelectField } from "@/components/admin/select-field";import { Card, CardContent } from "@/components/ui/card";import { CompanyAvatar } from "../companies/CompanyAvatar";import { useConfigurationContext } from "../root/ConfigurationContext";import type { Deal } from "../types";+import { formatDealCategories } from "./dealUtils";export const DealCard = ({ deal, index }: { deal: Deal; index: number }) => {if (!deal) return null;@@ -84,13 +84,8 @@ export const DealCardContent = ({minimumSignificantDigits: 3,}}/>- {deal.category && ", "}- <SelectField- source="category"- choices={dealCategories}- optionText="label"- optionValue="value"- />+ {deal.categories?.length ? ", " : ""}+ {formatDealCategories(dealCategories, deal.categories)}</p></CardContent></Card>diff --git a/src/components/atomic-crm/deals/DealInputs.tsx b/src/components/atomic-crm/deals/DealInputs.tsxindex 82c148fb..768d6999 100644--- a/src/components/atomic-crm/deals/DealInputs.tsx+++ b/src/components/atomic-crm/deals/DealInputs.tsx@@ -72,8 +72,8 @@ const DealMiscInputs = () => {{translate("resources.deals.field_categories.misc")}</h3>- <SelectInput- source="category"+ <AutocompleteArrayInput+ source="categories"choices={dealCategories}optionText="label"optionValue="value"diff --git a/src/components/atomic-crm/deals/DealShow.tsx b/src/components/atomic-crm/deals/DealShow.tsxindex 8e422c38..6979fff0 100644--- a/src/components/atomic-crm/deals/DealShow.tsx+++ b/src/components/atomic-crm/deals/DealShow.tsx@@ -27,7 +27,11 @@ import { NotesIterator } from "../notes/NotesIterator";import { useConfigurationContext } from "../root/ConfigurationContext";import type { Deal } from "../types";import { ContactList } from "./ContactList";-import { findDealLabel, formatISODateString } from "./dealUtils";+import {+ findDealLabel,+ formatDealCategories,+ formatISODateString,+} from "./dealUtils";export const DealShow = ({ open, id }: { open: boolean; id?: string }) => {const redirect = useRedirect();@@ -119,14 +123,13 @@ const DealShowContent = () => {</span></div>- {record.category && (+ {!!record.categories?.length && (<div className="flex flex-col mr-10"><span className="text-xs text-muted-foreground tracking-wide">- {translate("resources.deals.fields.category")}+ {translate("resources.deals.fields.categories")}</span><span className="text-sm">- {dealCategories.find((c) => c.value === record.category)- ?.label ?? record.category}+ {formatDealCategories(dealCategories, record.categories)}</span></div>)}diff --git a/src/components/atomic-crm/deals/dealUtils.ts b/src/components/atomic-crm/deals/dealUtils.tsindex 91ba7582..a7d6f0e4 100644--- a/src/components/atomic-crm/deals/dealUtils.ts+++ b/src/components/atomic-crm/deals/dealUtils.ts@@ -1,12 +1,22 @@import { format } from "date-fns";-import type { DealStage } from "../types";+import type { DealStage, LabeledValue } from "../types";export const findDealLabel = (dealStages: DealStage[], dealValue: string) => {const dealStage = dealStages.find((stage) => stage.value === dealValue);return dealStage?.label;};+export const formatDealCategories = (+ dealCategories: LabeledValue[],+ categories: string[] | null | undefined,+): string =>+ (categories ?? [])+ .map(+ (value) => dealCategories.find((c) => c.value === value)?.label ?? value,+ )+ .join(", ");+export function getRelativeTimeString(dateString: string,locale = "en",diff --git a/src/components/atomic-crm/providers/commons/englishCrmMessages.ts b/src/components/atomic-crm/providers/commons/englishCrmMessages.tsindex c4d56672..df3be9a1 100644--- a/src/components/atomic-crm/providers/commons/englishCrmMessages.ts+++ b/src/components/atomic-crm/providers/commons/englishCrmMessages.ts@@ -182,7 +182,7 @@ export const englishCrmMessages = {description: "Description",company_id: "Company",contact_ids: "Contacts",- category: "Category",+ categories: "Categories",amount: "Budget",expected_closing_date: "Expected closing date",stage: "Stage",diff --git a/src/components/atomic-crm/providers/commons/frenchCrmMessages.ts b/src/components/atomic-crm/providers/commons/frenchCrmMessages.tsindex 95a7a6ad..a26421d9 100644--- a/src/components/atomic-crm/providers/commons/frenchCrmMessages.ts+++ b/src/components/atomic-crm/providers/commons/frenchCrmMessages.ts@@ -186,7 +186,7 @@ export const frenchCrmMessages = {description: "Description",company_id: "Entreprise",contact_ids: "Contacts",- category: "Catégorie",+ categories: "Catégories",amount: "Budget",expected_closing_date: "Date de clôture prévue",stage: "Étape",diff --git a/src/components/atomic-crm/providers/fakerest/dataGenerator/deals.ts b/src/components/atomic-crm/providers/fakerest/dataGenerator/deals.tsindex 440592c6..ca9ca69e 100644--- a/src/components/atomic-crm/providers/fakerest/dataGenerator/deals.ts+++ b/src/components/atomic-crm/providers/fakerest/dataGenerator/deals.ts@@ -32,7 +32,7 @@ export const generateDeals = (db: Db): Deal[] => {name: lowercaseName[0].toUpperCase() + lowercaseName.slice(1),company_id: company.id,contact_ids: contacts.map((contact) => contact.id),- category: random.arrayElement(defaultDealCategories).value,+ categories: [random.arrayElement(defaultDealCategories).value],stage: random.arrayElement(defaultDealStages).value,description: lorem.paragraphs(datatype.number({ min: 1, max: 4 })),amount: datatype.number(1000) * 100,diff --git a/src/components/atomic-crm/providers/supabase/dataProvider.ts b/src/components/atomic-crm/providers/supabase/dataProvider.tsindex c2f42f4f..cdecb402 100644--- a/src/components/atomic-crm/providers/supabase/dataProvider.ts+++ b/src/components/atomic-crm/providers/supabase/dataProvider.ts@@ -18,6 +18,7 @@ import type {import type { ConfigurationContextValue } from "../../root/ConfigurationContext";import { ATTACHMENTS_BUCKET } from "../commons/attachments";import { getIsInitialized } from "./authProvider";+import { searchDealCategories } from "./searchDealCategories";import { getSupabaseClient } from "./supabase";const getBaseDataProvider = () =>@@ -375,8 +376,12 @@ const lifeCycleCallbacks: ResourceCallbacks[] = [},{resource: "deals",- beforeGetList: async (params) => {- return applyFullTextSearch(["name", "category", "description"])(params);+ beforeGetList: async (params, dataProvider) => {+ return searchDealCategories(+ applyFullTextSearch(["name", "description"])(params),+ params.filter?.q,+ dataProvider,+ );},},];diff --git a/src/components/atomic-crm/providers/supabase/searchDealCategories.test.ts b/src/components/atomic-crm/providers/supabase/searchDealCategories.test.tsnew file mode 100644index 00000000..0ee8f805--- /dev/null+++ b/src/components/atomic-crm/providers/supabase/searchDealCategories.test.ts@@ -0,0 +1,56 @@+import type { DataProvider, GetListParams } from "ra-core";+import { describe, expect, it } from "vitest";++import { searchDealCategories } from "./searchDealCategories";++const dataProviderWithConfig = (config: object) =>+ ({+ getOne: async () => ({ data: { id: 1, config } }),+ }) as unknown as DataProvider;++const searchParams: GetListParams = {+ filter: { "@or": { "name@ilike": "design" } },+};++describe("searchDealCategories", () => {+ it("adds the categories whose label or value matches a search word", async () => {+ const dataProvider = dataProviderWithConfig({+ dealCategories: [+ { value: "ui-design", label: "UI Design" },+ { value: "web", label: "Website design" },+ { value: "print", label: "Print project" },+ ],+ });++ const result = await searchDealCategories(+ searchParams,+ "Design",+ dataProvider,+ );++ expect(result.filter["@or"]).toEqual({+ "name@ilike": "design",+ "categories@ov": '{"ui-design","web"}',+ });+ });++ it("falls back to the default categories when none are configured", async () => {+ const result = await searchDealCategories(+ searchParams,+ "copywriting",+ dataProviderWithConfig({}),+ );++ expect(result.filter["@or"]["categories@ov"]).toBe('{"copywriting"}');+ });++ it("leaves the search unchanged when no category matches", async () => {+ const result = await searchDealCategories(+ searchParams,+ "acme",+ dataProviderWithConfig({}),+ );++ expect(result).toBe(searchParams);+ });+});diff --git a/src/components/atomic-crm/providers/supabase/searchDealCategories.ts b/src/components/atomic-crm/providers/supabase/searchDealCategories.tsnew file mode 100644index 00000000..e4780d76--- /dev/null+++ b/src/components/atomic-crm/providers/supabase/searchDealCategories.ts@@ -0,0 +1,39 @@+import type { DataProvider, GetListParams } from "ra-core";++import { defaultDealCategories } from "../../root/defaultConfiguration";+import type { LabeledValue } from "../../types";++/**+ * ilike can't search inside the categories array, so the search words are+ * matched against the configured category labels and values instead, and the+ * matching categories are added to the full-text search as an overlap filter.+ */+export const searchDealCategories = async (+ params: GetListParams,+ q: string | undefined,+ dataProvider: DataProvider,+): Promise<GetListParams> => {+ if (!q) return params;+ const { data } = await dataProvider.getOne("configuration", { id: 1 });+ const categories: LabeledValue[] =+ data?.config?.dealCategories ?? defaultDealCategories;+ const words = q.toLowerCase().trim().split(/\s+/);+ const matches = categories.filter(({ value, label }) =>+ words.some(+ (word) =>+ value.toLowerCase().includes(word) ||+ label.toLowerCase().includes(word),+ ),+ );+ if (matches.length === 0) return params;+ return {+ ...params,+ filter: {+ ...params.filter,+ "@or": {+ ...params.filter["@or"],+ "categories@ov": `{${matches.map(({ value }) => `"${value}"`).join(",")}}`,+ },+ },+ };+};diff --git a/src/components/atomic-crm/settings/SettingsPage.test.ts b/src/components/atomic-crm/settings/SettingsPage.test.tsindex 712a3f42..f3c2c76f 100644--- a/src/components/atomic-crm/settings/SettingsPage.test.ts+++ b/src/components/atomic-crm/settings/SettingsPage.test.ts@@ -4,9 +4,9 @@ import { validateItemsInUse } from "./SettingsPage";describe("validateItemsInUse", () => {const deals: RaRecord[] = [- { id: 1, stage: "won", category: "ui-design" },- { id: 2, stage: "lost", category: "copywriting" },- { id: 3, stage: "opportunity", category: "ui-design" },+ { id: 1, stage: "won", categories: ["ui-design"] },+ { id: 2, stage: "lost", categories: ["copywriting", "ui-design"] },+ { id: 3, stage: "opportunity", categories: ["ui-design"] },];it("returns undefined when items is undefined", () => {@@ -74,19 +74,19 @@ describe("validateItemsInUse", () => {it("ignores deals with a falsy value for the checked field", () => {const dealsWithEmpty: RaRecord[] = [- { id: 1, stage: "won", category: "" },- { id: 2, stage: "won", category: null },+ { id: 1, stage: "won", categories: [] },+ { id: 2, stage: "won", categories: null },];const items = [{ value: "other", label: "Other" }];expect(- validateItemsInUse(items, dealsWithEmpty, "category", "categories"),+ validateItemsInUse(items, dealsWithEmpty, "categories", "categories"),).toBe(undefined);});- it("works with the category field", () => {+ it("works with the categories array field", () => {const items = [{ value: "ui-design", label: "UI Design" }];expect(- validateItemsInUse(items, deals, "category", "categories"),+ validateItemsInUse(items, deals, "categories", "categories"),).toContain("copywriting");});});diff --git a/src/components/atomic-crm/settings/SettingsPage.tsx b/src/components/atomic-crm/settings/SettingsPage.tsxindex 2ee4ba64..dc8d7d8e 100644--- a/src/components/atomic-crm/settings/SettingsPage.tsx+++ b/src/components/atomic-crm/settings/SettingsPage.tsx@@ -90,10 +90,8 @@ export const validateItemsInUse = (const inUse = [...new Set(deals- .filter(- (deal) => deal[fieldName] && !values.has(deal[fieldName] as string),- )- .map((deal) => deal[fieldName] as string),+ .flatMap((deal) => [deal[fieldName]].flat() as string[])+ .filter((value) => value && !values.has(value)),),];if (inUse.length > 0) {@@ -230,7 +228,7 @@ const SettingsFormFields = () => {const validateDealCategories = useCallback((categories: { value: string; label: string }[] | undefined) =>- validateItemsInUse(categories, deals, "category", categoryDisplayName, {+ validateItemsInUse(categories, deals, "categories", categoryDisplayName, {duplicate: (displayName, duplicates) =>translate("crm.settings.validation.duplicate", {display_name: displayName,diff --git a/src/components/atomic-crm/types.ts b/src/components/atomic-crm/types.tsindex 8c8c70d5..90d88cf3 100644--- a/src/components/atomic-crm/types.ts+++ b/src/components/atomic-crm/types.ts@@ -118,7 +118,7 @@ export type Deal = {name: string;company_id: Identifier;contact_ids: Identifier[];- category: string;+ categories: string[];stage: string;description: string;amount: number;diff --git a/src/test/StoryWrapper.tsx b/src/test/StoryWrapper.tsxindex ee7e4421..dbb0c8bd 100644--- a/src/test/StoryWrapper.tsx+++ b/src/test/StoryWrapper.tsx@@ -111,7 +111,7 @@ export const buildContact = (overrides: Partial<Contact> = {}): Contact => ({export const buildDeal = (overrides: Partial<Deal> = {}): Deal => ({amount: 1000,archived_at: undefined,- category: "Other",+ categories: ["other"],company_id: 1,contact_ids: [],created_at: "2025-01-01T09:00:00.000Z",diff --git a/supabase/functions/_shared/db.ts b/supabase/functions/_shared/db.tsindex ce02afa1..7c339a11 100644--- a/supabase/functions/_shared/db.ts+++ b/supabase/functions/_shared/db.ts@@ -62,7 +62,7 @@ interface DealsTable {name: string;company_id: number | null;contact_ids: number[];- category: string | null;+ categories: string[] | null;stage: string;description: string | null;amount: number | null;diff --git a/supabase/migrations/20261009120000_deal_categories.sql b/supabase/migrations/20261009120000_deal_categories.sqlnew file mode 100644index 00000000..b707c784--- /dev/null+++ b/supabase/migrations/20261009120000_deal_categories.sql@@ -0,0 +1,5 @@+alter table "public"."deals" add column "categories" text[];++update "public"."deals" set "categories" = array["category"] where "category" is not null;++alter table "public"."deals" drop column "category";diff --git a/supabase/schemas/01_tables.sql b/supabase/schemas/01_tables.sqlindex bdb383c4..45cfed90 100644--- a/supabase/schemas/01_tables.sql+++ b/supabase/schemas/01_tables.sql@@ -67,7 +67,7 @@ create table public.deals (name text not null,company_id bigint,contact_ids bigint[],- category text,+ categories text[],stage text not null,description text,amount bigint,