A full-featured CRM built with React, shadcn/ui, and Supabase.
feat: Create contact from deal
erwanMarmelab409312b3871e
diff --git a/e2e/createContactFromDeal.spec.ts b/e2e/createContactFromDeal.spec.tsnew file mode 100644index 00000000..958530a8--- /dev/null+++ b/e2e/createContactFromDeal.spec.ts@@ -0,0 +1,80 @@+import { expect, test } from "./fixtures";++test.describe("user creating a contact from the deal form", () => {+ test.beforeEach(async ({ createSales, createCompany, createContact }) => {+ const sales = await createSales({+ first_name: "John",+ last_name: "Doe",+ email: "[email protected]",+ password: "password",+ });++ const company = await createCompany({+ name: "Smith Corp",+ salesId: sales.id,+ });++ // the deal list only offers to create a deal once a contact exists+ await createContact({+ first_name: "Jane",+ last_name: "Smith",+ title: "CEO",+ sales_id: sales.id,+ company_id: company.id,+ });+ });++ test("creates the missing contact without leaving the deal form", async ({+ page,+ }) => {+ await page.goto("/");+ await page.getByLabel("Email").fill("[email protected]");+ await page.getByLabel("Password").fill("password");+ await page.getByRole("button", { name: "Sign in" }).click();+ await expect(page).toHaveTitle(/Atomic CRM/);++ await page.getByRole("link", { name: "Deals" }).click();+ await page.waitForLoadState("networkidle");++ await page.getByRole("button", { name: "Create deal" }).click();++ // "Linked to" keeps this scoped to the deal form once the contact sheet opens+ const dealForm = page.getByRole("dialog").filter({ hasText: "Linked to" });+ await dealForm.getByLabel("Name", { exact: true }).fill("Big opportunity");+ await dealForm.getByRole("combobox", { name: "Company" }).click();+ await page.getByRole("option", { name: "Smith Corp" }).click();++ // Grace is not in the contact list yet+ const contactInput = dealForm.getByPlaceholder("Search");+ await contactInput.click();+ await contactInput.fill("Grace Hopper");+ await expect(+ page.getByRole("option", { name: "Create Grace Hopper" }),+ ).toBeVisible();+ await page.getByRole("option", { name: "Create Grace Hopper" }).click();++ // the creation form opens, prefilled from what was typed and from the deal+ const contactSheet = page.getByRole("dialog", { name: "New Contact" });+ await expect(contactSheet.getByLabel("First name")).toHaveValue("Grace");+ await expect(contactSheet.getByLabel("Last name")).toHaveValue("Hopper");+ await expect(+ contactSheet.getByRole("combobox", { name: "Company" }),+ ).toContainText("Smith Corp");++ await contactSheet+ .getByRole("button", { name: "Save", exact: true })+ .click();++ // the deal form is still there, with the new contact selected+ await expect(contactSheet).toBeHidden();+ await expect(dealForm.getByText("Grace Hopper")).toBeVisible();++ await dealForm.getByRole("button", { name: "Save", exact: true }).click();+ await page.waitForLoadState("networkidle");++ // the link survives the deal being saved+ await page.getByText("Big opportunity").click();+ await page.waitForLoadState("networkidle");+ await expect(page.getByText("Grace Hopper")).toBeVisible();+ });+});diff --git a/registry.json b/registry.jsonindex a8337a71..8d33afdb 100644--- a/registry.json+++ b/registry.json@@ -481,6 +481,10 @@"path": "src/components/atomic-crm/misc/ActiveFilterButton.tsx","type": "registry:component"},+ {+ "path": "src/components/atomic-crm/login/authConfig.ts",+ "type": "registry:component"+ },{"path": "src/components/atomic-crm/login/StartPage.tsx","type": "registry:component"@@ -737,6 +741,10 @@"path": "src/components/atomic-crm/contacts/Avatar.tsx","type": "registry:component"},+ {+ "path": "src/components/atomic-crm/contacts/AutocompleteContactInput.tsx",+ "type": "registry:component"+ },{"path": "src/components/atomic-crm/companies/sizes.ts","type": "registry:component"diff --git a/src/components/admin/autocomplete-array-input.tsx b/src/components/admin/autocomplete-array-input.tsxindex d86fe789..fcee81d7 100644--- a/src/components/admin/autocomplete-array-input.tsx+++ b/src/components/admin/autocomplete-array-input.tsx@@ -15,7 +15,11 @@ import {FormLabel,} from "@/components/admin/form";import { Command as CommandPrimitive } from "cmdk";-import type { ChoicesProps, InputProps } from "ra-core";+import type {+ ChoicesProps,+ InputProps,+ SupportCreateSuggestionOptions,+} from "ra-core";import {useChoices,useChoicesContext,@@ -24,6 +28,7 @@ import {useTranslate,FieldTitle,useEvent,+ useSupportCreateSuggestion,} from "ra-core";import { InputHelperText } from "./input-helper-text";import { useCallback } from "react";@@ -32,7 +37,7 @@ import { useCallback } from "react";* Form control that lets users choose multiple values from a list using a dropdown with autocompletion.** This input allows editing array values with a searchable dropdown interface and displays selected items as removable badges.- * Works seamlessly inside ReferenceArrayInput for editing many-to-many relationships.+ * Works seamlessly inside ReferenceArrayInput for creating and editing many-to-many relationships.** @see {@link https://marmelab.com/shadcn-admin-kit/docs/autocompletearrayinput/ AutocompleteArrayInput documentation}*@@ -64,6 +69,7 @@ import { useCallback } from "react";*/export const AutocompleteArrayInput = (props: Omit<InputProps, "source"> &+ Omit<SupportCreateSuggestionOptions, "handleChange" | "filter"> &Partial<Pick<InputProps, "source">> &ChoicesProps & {className?: string;@@ -76,7 +82,17 @@ export const AutocompleteArrayInput = (| ((option: any | undefined) => React.ReactNode);},) => {- const { filterToQuery = DefaultFilterToQuery, inputText } = props;+ const {+ filterToQuery = DefaultFilterToQuery,+ inputText,+ create,+ createValue,+ createLabel,+ createHintValue,+ createItemLabel,+ onCreate,+ optionText,+ } = props;const {allChoices = [],source,@@ -96,6 +112,8 @@ export const AutocompleteArrayInput = (optionValue: props.optionValue ?? "id",disableValue: props.disableValue,translateChoice: props.translateChoice ?? !isFromReference,+ createValue,+ createHintValue,});const inputRef = React.useRef<HTMLInputElement>(null);@@ -144,122 +162,162 @@ export const AutocompleteArrayInput = ([inputText, getChoiceText],);+ const handleChange = useEvent((choice: any) => {+ setFilterValue("");+ if (isFromReference) {+ setFilters(filterToQuery(""));+ }+ const value = getChoiceValue(choice);+ if (field.value.includes(value)) {+ return;+ }+ field.onChange([...field.value, value]);+ });++ const {+ getCreateItem,+ handleChange: handleChangeWithCreateSupport,+ createElement,+ getOptionDisabled,+ } = useSupportCreateSuggestion({+ create,+ createLabel,+ createValue,+ createHintValue,+ createItemLabel,+ onCreate,+ handleChange,+ optionText,+ filter: filterValue,+ });++ const createItem =+ (create || onCreate) && (filterValue !== "" || createLabel)+ ? getCreateItem(filterValue)+ : null;+ const finalChoices = createItem+ ? [...availableChoices, createItem]+ : availableChoices;+return (- <FormField className={props.className} id={id} name={field.name}>- {props.label !== false && (- <FormLabel>- <FieldTitle- label={props.label}- source={props.source ?? source}- resource={resource}- isRequired={isRequired}- />- </FormLabel>- )}- <FormControl>- <Command- onKeyDown={handleKeyDown}- shouldFilter={!isFromReference}- className="overflow-visible bg-transparent"- >- <div className="group rounded-md bg-transparent dark:bg-input/30 border border-input px-3 py-1.75 text-sm transition-all ring-offset-background focus-within:border-ring focus-within:ring-ring/50 focus-within:ring-[3px]">- <div className="flex flex-wrap gap-1">- {selectedChoices.map((choice) => (- <Badge key={getChoiceValue(choice)} variant="outline">- {getInputText(choice)}- <button- className="ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2"- onKeyDown={(e) => {- if (e.key === "Enter") {+ <>+ <FormField className={props.className} id={id} name={field.name}>+ {props.label !== false && (+ <FormLabel>+ <FieldTitle+ label={props.label}+ source={props.source ?? source}+ resource={resource}+ isRequired={isRequired}+ />+ </FormLabel>+ )}+ <FormControl>+ <Command+ onKeyDown={handleKeyDown}+ shouldFilter={!isFromReference}+ className="overflow-visible bg-transparent"+ >+ <div className="group rounded-md bg-transparent dark:bg-input/30 border border-input px-3 py-1.75 text-sm transition-all ring-offset-background focus-within:border-ring focus-within:ring-ring/50 focus-within:ring-[3px]">+ <div className="flex flex-wrap gap-1">+ {selectedChoices.map((choice) => (+ <Badge key={getChoiceValue(choice)} variant="outline">+ {getInputText(choice)}+ <button+ className="ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2"+ onKeyDown={(e) => {+ if (e.key === "Enter") {+ handleUnselect(choice);+ }+ }}+ onMouseDown={(e) => {+ e.preventDefault();+ e.stopPropagation();+ }}+ onClick={(e) => {+ e.preventDefault();handleUnselect(choice);- }- }}- onMouseDown={(e) => {- e.preventDefault();- e.stopPropagation();- }}- onClick={(e) => {- e.preventDefault();- handleUnselect(choice);- }}- >- <span className="sr-only">- {translate("ra.action.remove", {- _: "Remove",- })}- </span>- <X className="h-3 w-3" />- </button>- </Badge>- ))}- {/* Avoid having the "Search" Icon by not using CommandInput */}- <CommandPrimitive.Input- ref={inputRef}- value={filterValue}- onValueChange={(filter) => {- setFilterValue(filter);- requestAnimationFrame(() => {- listRef.current?.scrollTo(0, 0);- });- // We don't want the ChoicesContext to filter the choices if the input- // is not from a reference as it would also filter out the selected values- if (isFromReference) {- setFilters(filterToQuery(filter), undefined, true);- }- }}- onBlur={() => setOpen(false)}- onFocus={() => setOpen(true)}- placeholder={placeholder}- className="ml-2 flex-1 bg-transparent outline-none placeholder:text-muted-foreground"- />+ }}+ >+ <span className="sr-only">+ {translate("ra.action.remove", {+ _: "Remove",+ })}+ </span>+ <X className="h-3 w-3" />+ </button>+ </Badge>+ ))}+ {/* Avoid having the "Search" Icon by not using CommandInput */}+ <CommandPrimitive.Input+ ref={inputRef}+ value={filterValue}+ onValueChange={(filter) => {+ setFilterValue(filter);+ requestAnimationFrame(() => {+ listRef.current?.scrollTo(0, 0);+ });+ // We don't want the ChoicesContext to filter the choices if the input+ // is not from a reference as it would also filter out the selected values+ if (isFromReference) {+ setFilters(filterToQuery(filter), undefined, true);+ }+ }}+ onBlur={() => setOpen(false)}+ onFocus={() => setOpen(true)}+ placeholder={placeholder}+ className="ml-2 flex-1 bg-transparent outline-none placeholder:text-muted-foreground"+ />+ </div></div>- </div>- <div className="relative">- <CommandList ref={listRef}>- {open && availableChoices.length > 0 ? (- <div className="absolute top-2 z-10 w-full rounded-md border bg-popover text-popover-foreground shadow-md outline-none animate-in">- <CommandGroup className="h-full overflow-auto">- {availableChoices.map((choice) => {- const choiceText = getChoiceText(choice);- return (- <CommandItem- key={getChoiceValue(choice)}- value={getChoiceValue(choice)}- keywords={- React.isValidElement(choiceText)- ? undefined- : [choiceText]- }- onMouseDown={(e) => {- e.preventDefault();- e.stopPropagation();- }}- onSelect={() => {- setFilterValue("");- if (isFromReference) {- setFilters(filterToQuery(""));+ <div className="relative">+ <CommandList ref={listRef}>+ {open && finalChoices.length > 0 ? (+ <div className="absolute top-2 z-10 w-full rounded-md border bg-popover text-popover-foreground shadow-md outline-none animate-in">+ <CommandGroup className="h-full overflow-auto">+ {finalChoices.map((choice) => {+ const isCreateItem =+ !!createItem && choice?.id === createItem.id;+ const choiceText = getChoiceText(choice);+ return (+ <CommandItem+ key={getChoiceValue(choice)}+ value={+ isCreateItem+ ? `?${filterValue}?`+ : getChoiceValue(choice)+ }+ keywords={+ isCreateItem || React.isValidElement(choiceText)+ ? undefined+ : [choiceText]}- field.onChange([- ...field.value,- getChoiceValue(choice),- ]);- }}- className="cursor-pointer"- >- {choiceText}- </CommandItem>- );- })}- </CommandGroup>- </div>- ) : null}- </CommandList>- </div>- </Command>- </FormControl>- <InputHelperText helperText={props.helperText} />- <FormError />- </FormField>+ disabled={getOptionDisabled(choice)}+ onMouseDown={(e) => {+ e.preventDefault();+ e.stopPropagation();+ }}+ onSelect={() =>+ handleChangeWithCreateSupport(choice)+ }+ className="cursor-pointer"+ >+ {choiceText}+ </CommandItem>+ );+ })}+ </CommandGroup>+ </div>+ ) : null}+ </CommandList>+ </div>+ </Command>+ </FormControl>+ <InputHelperText helperText={props.helperText} />+ <FormError />+ </FormField>+ {createElement}+ </>);};diff --git a/src/components/atomic-crm/contacts/AutocompleteContactInput.tsx b/src/components/atomic-crm/contacts/AutocompleteContactInput.tsxnew file mode 100644index 00000000..50efa626--- /dev/null+++ b/src/components/atomic-crm/contacts/AutocompleteContactInput.tsx@@ -0,0 +1,58 @@+import { useCreateSuggestionContext } from "ra-core";+import type { InputProps, RaRecord } from "ra-core";+import { useQueryClient } from "@tanstack/react-query";+import { useWatch } from "react-hook-form";+import { AutocompleteArrayInput } from "@/components/admin/autocomplete-array-input";++import { contactOptionText } from "../misc/ContactOption";+import { ContactCreateSheet } from "./ContactCreateSheet";++/**+ * Autocomplete input to pick several contacts, with on the fly creation.+ *+ * Unlike a company — which a name is enough to create — a contact needs a form,+ * so picking "Create ..." opens the contact creation sheet rather than creating+ * the record silently.+ */+export const AutocompleteContactInput = ({+ validate,+ label,+}: Pick<InputProps, "validate" | "label">) => (+ <AutocompleteArrayInput+ label={label}+ validate={validate}+ optionText={contactOptionText}+ helperText={false}+ create={<CreateContact />}+ createItemLabel="resources.contacts.autocomplete.create_item"+ createLabel="resources.contacts.autocomplete.create_label"+ />+);++const splitFullName = (fullName: string | undefined) => {+ const [first_name, ...rest] = (fullName ?? "").trim().split(/\s+/);+ return { first_name, last_name: rest.join(" ") };+};++const CreateContact = () => {+ const { filter, onCancel, onCreate } = useCreateSuggestionContext();+ const queryClient = useQueryClient();+ const company_id = useWatch({ name: "company_id" });++ const handleSuccess = (contact: RaRecord) => {+ queryClient.invalidateQueries({ queryKey: ["contacts_summary"] });+ onCreate(contact);+ };++ return (+ <ContactCreateSheet+ open+ onOpenChange={(open) => {+ if (!open) onCancel();+ }}+ defaultValues={{ ...splitFullName(filter), company_id }}+ mutationOptions={{ onSuccess: handleSuccess }}+ redirect={false}+ />+ );+};diff --git a/src/components/atomic-crm/contacts/ContactCreateSheet.tsx b/src/components/atomic-crm/contacts/ContactCreateSheet.tsxindex 224aa036..d7b53812 100644--- a/src/components/atomic-crm/contacts/ContactCreateSheet.tsx+++ b/src/components/atomic-crm/contacts/ContactCreateSheet.tsx@@ -1,5 +1,5 @@import { useGetIdentity, useTranslate } from "ra-core";-import { CreateSheet } from "../misc/CreateSheet";+import { CreateSheet, type CreateSheetProps } from "../misc/CreateSheet";import { ContactInputs } from "./ContactInputs";import {cleanupContactForCreate,@@ -7,14 +7,19 @@ import {defaultPhoneJsonb,} from "./contactModel";-export interface ContactCreateSheetProps {+export interface ContactCreateSheetProps+ extends Pick<CreateSheetProps, "mutationOptions" | "redirect"> {open: boolean;onOpenChange: (open: boolean) => void;+ defaultValues?: CreateSheetProps["defaultValues"];}export const ContactCreateSheet = ({open,onOpenChange,+ defaultValues,+ mutationOptions,+ redirect,}: ContactCreateSheetProps) => {const { identity } = useGetIdentity();const translate = useTranslate();@@ -26,10 +31,13 @@ export const ContactCreateSheet = ({sales_id: identity?.id,email_jsonb: defaultEmailJsonb,phone_jsonb: defaultPhoneJsonb,+ ...defaultValues,}}transform={cleanupContactForCreate}open={open}onOpenChange={onOpenChange}+ mutationOptions={mutationOptions}+ redirect={redirect}><ContactInputs /></CreateSheet>diff --git a/src/components/atomic-crm/deals/DealInputs.stories.tsx b/src/components/atomic-crm/deals/DealInputs.stories.tsxnew file mode 100644index 00000000..0d155490--- /dev/null+++ b/src/components/atomic-crm/deals/DealInputs.stories.tsx@@ -0,0 +1,49 @@+import type { Meta } from "@storybook/react-vite";+import type { ReactNode } from "react";+import { Form } from "ra-core";+import { Create } from "@/components/admin/create";+import { SaveButton } from "@/components/admin/form";+import { FormToolbar } from "@/components/admin/simple-form";+import { StoryWrapper, buildContact } from "@/test/StoryWrapper";+import { DealInputs } from "./DealInputs";++const meta = {+ title: "Atomic CRM/Deals/DealInputs",+ parameters: {+ layout: "fullscreen",+ },+} satisfies Meta;++export default meta;++const defaultData = {+ companies: [{ id: 1, name: "Smith Corp", sales_id: 0 }],+ contacts: [+ buildContact({+ company_id: 1,+ first_name: "Ada",+ id: 1,+ last_name: "Lovelace",+ }),+ ],+};++export const CreateForm = ({+ children,+ data = defaultData,+}: {+ children?: ReactNode;+ data?: any;+}) => (+ <StoryWrapper data={data}>+ <Create resource="deals">+ <Form defaultValues={{ contact_ids: [], index: 0, sales_id: 0 }}>+ <DealInputs />+ <FormToolbar>+ <SaveButton />+ </FormToolbar>+ </Form>+ </Create>+ {children}+ </StoryWrapper>+);diff --git a/src/components/atomic-crm/deals/DealInputs.test.tsx b/src/components/atomic-crm/deals/DealInputs.test.tsxnew file mode 100644index 00000000..3608503c--- /dev/null+++ b/src/components/atomic-crm/deals/DealInputs.test.tsx@@ -0,0 +1,56 @@+import { describe, expect, it } from "vitest";+import { render } from "vitest-browser-react";+import { page, userEvent } from "vitest/browser";++import { CreateForm } from "./DealInputs.stories";++describe("DealInputs", () => {+ beforeAll(() => {+ page.viewport(1600, 900);+ });++ it("creates a contact missing from the list and selects it", async () => {+ const screen = await render(<CreateForm />);++ // pick the company first: the contact created from this form should inherit it+ await screen.getByRole("combobox", { name: /company/i }).click();+ await screen.getByRole("option", { name: /Smith Corp/ }).click();++ const contactInput = screen.getByPlaceholder("Search");+ await contactInput.click();+ await userEvent.type(contactInput, "Grace Hopper");++ // no contact matches, so creating one is the only option left+ await screen.getByRole("option", { name: /Create Grace Hopper/ }).click();++ // the creation form opens, prefilled from what was typed and from the deal+ const sheet = screen.getByRole("dialog");+ await expect+ .element(sheet.getByLabelText(/first name/i))+ .toHaveValue("Grace");+ await expect+ .element(sheet.getByLabelText(/last name/i))+ .toHaveValue("Hopper");+ await expect+ .element(sheet.getByRole("combobox", { name: /company/i }))+ .toHaveTextContent("Smith Corp");++ await sheet.getByRole("button", { name: /^save$/i }).click();++ // back on the deal form, the new contact is selected+ await expect.element(screen.getByRole("dialog")).not.toBeInTheDocument();+ await expect.element(screen.getByText("Grace Hopper")).toBeInTheDocument();+ });++ it("does not offer to create a contact before anything is typed", async () => {+ const screen = await render(<CreateForm />);++ await screen.getByPlaceholder("Search").click();++ // the hint is shown instead, and cannot be selected+ const hint = screen.getByRole("option", {+ name: /Start typing to create a new contact/,+ });+ await expect.element(hint).toHaveAttribute("aria-disabled", "true");+ });+});diff --git a/src/components/atomic-crm/deals/DealInputs.tsx b/src/components/atomic-crm/deals/DealInputs.tsxindex 82c148fb..705ef743 100644--- a/src/components/atomic-crm/deals/DealInputs.tsx+++ b/src/components/atomic-crm/deals/DealInputs.tsx@@ -1,5 +1,4 @@import { required, useTranslate } from "ra-core";-import { AutocompleteArrayInput } from "@/components/admin/autocomplete-array-input";import { ReferenceArrayInput } from "@/components/admin/reference-array-input";import { ReferenceInput } from "@/components/admin/reference-input";import { TextInput } from "@/components/admin/text-input";@@ -9,9 +8,9 @@ import { SelectInput } from "@/components/admin/select-input";import { Separator } from "@/components/ui/separator";import { useIsMobile } from "@/hooks/use-mobile";-import { contactOptionText } from "../misc/ContactOption";import { useConfigurationContext } from "../root/ConfigurationContext";import { AutocompleteCompanyInput } from "../companies/AutocompleteCompanyInput.tsx";+import { AutocompleteContactInput } from "../contacts/AutocompleteContactInput.tsx";export const DealInputs = () => {const isMobile = useIsMobile();@@ -53,11 +52,7 @@ const DealLinkedToInputs = () => {</ReferenceInput><ReferenceArrayInput source="contact_ids" reference="contacts_summary">- <AutocompleteArrayInput- label="resources.deals.fields.contact_ids"- optionText={contactOptionText}- helperText={false}- />+ <AutocompleteContactInput label="resources.deals.fields.contact_ids" /></ReferenceArrayInput></div>);diff --git a/src/components/atomic-crm/providers/commons/englishCrmMessages.ts b/src/components/atomic-crm/providers/commons/englishCrmMessages.tsindex de9e8443..31170f0c 100644--- a/src/components/atomic-crm/providers/commons/englishCrmMessages.ts+++ b/src/components/atomic-crm/providers/commons/englishCrmMessages.ts@@ -95,6 +95,10 @@ export const englishCrmMessages = {new: "New Contact",show: "Show contact",},+ autocomplete: {+ create_item: "Create %{item}",+ create_label: "Start typing to create a new contact",+ },background: {last_activity_on: "Last activity on %{date}",added_on: "Added on %{date}",diff --git a/src/components/atomic-crm/providers/commons/frenchCrmMessages.ts b/src/components/atomic-crm/providers/commons/frenchCrmMessages.tsindex 5d30e91f..ae20b0f0 100644--- a/src/components/atomic-crm/providers/commons/frenchCrmMessages.ts+++ b/src/components/atomic-crm/providers/commons/frenchCrmMessages.ts@@ -98,6 +98,10 @@ export const frenchCrmMessages = {new: "Nouveau contact",show: "Afficher le contact",},+ autocomplete: {+ create_item: "Créer %{item}",+ create_label: "Saisissez du texte pour créer un contact",+ },background: {last_activity_on: "Dernière activité le %{date}",added_on: "Ajouté le %{date}",