A full-featured CRM built with React, shadcn/ui, and Supabase.
Add contact merge
François Zaninotto250269fe2495
diff --git a/makefile b/makefileindex 49381e71..813653d0 100644--- a/makefile+++ b/makefile@@ -61,8 +61,8 @@ test-ci:CI=1 npm testlint:- npm run lint:check- npm run prettier:check+ npm run lint+ npm run prettierpublish:npm run build-libdiff --git a/package.json b/package.jsonindex 055fefb9..3259036d 100644--- a/package.json+++ b/package.json@@ -8,11 +8,12 @@"dev:demo": "vite --config vite.demo.config --force","build": "tsc && vite build","build:demo": "tsc && vite build --config vite.demo.config",+ "typecheck": "tsc --noEmit","preview": "vite preview","lint:apply": "eslint **/*.{mjs,ts,tsx} --fix",- "lint:check": "eslint **/*.{mjs,ts,tsx}",+ "lint": "eslint **/*.{mjs,ts,tsx}","prettier:apply": "prettier --config ./.prettierrc.json --write --list-different \"**/*.{js,json,ts,tsx,css,md,html}\"",- "prettier:check": "prettier --config ./.prettierrc.json --check \"**/*.{js,json,ts,tsx,css,md,html}\"",+ "prettier": "prettier --config ./.prettierrc.json --check \"**/*.{js,json,ts,tsx,css,md,html}\"","registry:build": "npx shadcn build","registry:gen": "node ./scripts/generate-registry.mjs","ghpages:deploy": "node ./scripts/ghpages-deploy.mjs",diff --git a/src/components/atomic-crm/contacts/ContactAside.tsx b/src/components/atomic-crm/contacts/ContactAside.tsxindex 15e13e9d..c5d51824 100644--- a/src/components/atomic-crm/contacts/ContactAside.tsx+++ b/src/components/atomic-crm/contacts/ContactAside.tsx@@ -1,5 +1,6 @@-import { Linkedin, Mail, Phone } from "lucide-react";+import { Linkedin, Mail, Phone, Merge } from "lucide-react";import { useRecordContext, WithRecord } from "ra-core";+import { useState } from "react";import type { ReactNode } from "react";import { ArrayField } from "@/components/admin/array-field";import { EditButton } from "@/components/admin/edit-button";@@ -10,6 +11,7 @@ import { SingleFieldList } from "@/components/admin/single-field-list";import { TextField } from "@/components/admin/text-field";import { DateField } from "@/components/admin/date-field";import { EmailField } from "@/components/admin/email-field";+import { Button } from "@/components/ui/button";import { AddTask } from "../tasks/AddTask";import { TasksIterator } from "../tasks/TasksIterator";@@ -18,10 +20,13 @@ import { AsideSection } from "../misc/AsideSection";import { useConfigurationContext } from "../root/ConfigurationContext";import { SaleName } from "../sales/SaleName";import type { Contact } from "../types";+import { ContactMergeDialog } from "./ContactMergeDialog";export const ContactAside = ({ link = "edit" }: { link?: "edit" | "show" }) => {const { contactGender } = useConfigurationContext();const record = useRecordContext<Contact>();+ const [mergeDialogOpen, setMergeDialogOpen] = useState(false);+if (!record) return null;return (<div className="hidden sm:block w-64 min-w-64 text-sm">@@ -137,6 +142,24 @@ export const ContactAside = ({ link = "edit" }: { link?: "edit" | "show" }) => {</ReferenceManyField><AddTask /></AsideSection>++ {link !== "edit" && (+ <div className="mt-6 pt-6 border-t hidden sm:block">+ <Button+ variant="outline"+ className="h-6 cursor-pointer"+ size="sm"+ onClick={() => setMergeDialogOpen(true)}+ >+ <Merge className="w-4 h-4" />+ Merge with another contact+ </Button>+ <ContactMergeDialog+ open={mergeDialogOpen}+ onClose={() => setMergeDialogOpen(false)}+ />+ </div>+ )}</div>);};diff --git a/src/components/atomic-crm/contacts/ContactMergeDialog.tsx b/src/components/atomic-crm/contacts/ContactMergeDialog.tsxnew file mode 100644index 00000000..5fedeeb6--- /dev/null+++ b/src/components/atomic-crm/contacts/ContactMergeDialog.tsx@@ -0,0 +1,236 @@+import { useState, useEffect } from "react";+import { Merge, CircleX } from "lucide-react";+import {+ useRecordContext,+ useGetList,+ useGetManyReference,+ required,+ Form,+ useNotify,+ useRedirect,+} from "ra-core";+import type { Identifier } from "ra-core";+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogDescription,+ DialogFooter,+} from "@/components/ui/dialog";+import { Button } from "@/components/ui/button";+import { ReferenceInput } from "@/components/admin/reference-input";+import { AutocompleteInput } from "@/components/admin/autocomplete-input";+import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";+import { AlertTriangle, ArrowDown } from "lucide-react";+import type { Contact } from "../types";+import { contactOptionText } from "../misc/ContactOption";+import { useContactMerge } from "./useContactMerge";++interface ContactMergeDialogProps {+ open: boolean;+ onClose: () => void;+}++export const ContactMergeDialog = ({+ open,+ onClose,+}: ContactMergeDialogProps) => {+ const loserContact = useRecordContext<Contact>();+ const notify = useNotify();+ const redirect = useRedirect();+ const [winnerId, setWinnerId] = useState<Identifier | null>(null);+ const [suggestedWinnerId, setSuggestedWinnerId] = useState<Identifier | null>(+ null,+ );++ const { mergeContacts, isMerging } = useContactMerge();++ // Find potential contacts with matching first and last name+ const { data: matchingContacts } = useGetList(+ "contacts",+ {+ filter: {+ first_name: loserContact?.first_name,+ last_name: loserContact?.last_name,+ "id@neq": loserContact?.id, // Exclude current contact+ },+ pagination: { page: 1, perPage: 10 },+ },+ { enabled: open && !!loserContact },+ );++ // Get counts of items to be merged+ const canFetchCounts = open && !!loserContact && !!winnerId;+ const { total: tasksCount } = useGetManyReference(+ "tasks",+ {+ target: "contact_id",+ id: loserContact?.id,+ pagination: { page: 1, perPage: 1 },+ },+ { enabled: canFetchCounts },+ );++ const { total: notesCount } = useGetManyReference(+ "contactNotes",+ {+ target: "contact_id",+ id: loserContact?.id,+ pagination: { page: 1, perPage: 1 },+ },+ { enabled: canFetchCounts },+ );++ const { total: dealsCount } = useGetList(+ "deals",+ {+ filter: { "contact_ids@cs": `{${loserContact?.id}}` },+ pagination: { page: 1, perPage: 1 },+ },+ { enabled: canFetchCounts },+ );++ useEffect(() => {+ if (matchingContacts && matchingContacts.length > 0) {+ const suggestedWinnerId = matchingContacts[0].id;+ setSuggestedWinnerId(suggestedWinnerId);+ setWinnerId(suggestedWinnerId);+ }+ }, [matchingContacts]);++ const handleMerge = async () => {+ if (!winnerId || !loserContact) {+ notify("Please select a contact to merge with", { type: "warning" });+ return;+ }++ try {+ await mergeContacts(loserContact.id, winnerId);+ notify("Contacts merged successfully", { type: "success" });+ redirect(`/contacts/${winnerId}/show`);+ onClose();+ } catch (error) {+ notify("Failed to merge contacts", { type: "error" });+ console.error("Merge failed:", error);+ }+ };++ if (!loserContact) return null;++ return (+ <Dialog open={open} onOpenChange={onClose}>+ <DialogContent className="md:min-w-lg max-w-2xl">+ <DialogHeader>+ <DialogTitle>Merge Contact</DialogTitle>+ <DialogDescription>+ Merge this contact with another one.+ </DialogDescription>+ </DialogHeader>++ <div className="space-y-4">+ <div className="p-4 bg-primary/5 rounded-lg border border-primary/20">+ <p className="font-medium text-sm">+ Current Contact (will be deleted)+ </p>+ <div className="font-medium text-sm mt-4">{contactOptionText}</div>++ <div className="flex justify-center my-4">+ <ArrowDown className="h-5 w-5 text-muted-foreground" />+ </div>++ <p className="font-medium text-sm mb-2">+ Target Contact (will be kept)+ </p>+ <Form>+ <ReferenceInput+ source="winner_id"+ reference="contacts"+ filter={{ id_neq: loserContact.id }}+ >+ <AutocompleteInput+ label=""+ optionText={contactOptionText}+ validate={required()}+ onChange={setWinnerId}+ defaultValue={suggestedWinnerId}+ helperText={false}+ />+ </ReferenceInput>+ </Form>+ </div>++ {winnerId && (+ <>+ <div className="space-y-2">+ <p className="font-medium text-sm">What will be merged:</p>+ <ul className="text-sm text-muted-foreground space-y-1 ml-4">+ {notesCount != null && notesCount > 0 && (+ <li>+ • {notesCount} note+ {notesCount !== 1 ? "s" : ""} will be reassigned+ </li>+ )}+ {tasksCount != null && tasksCount > 0 && (+ <li>+ • {tasksCount} task+ {tasksCount !== 1 ? "s" : ""} will be reassigned+ </li>+ )}+ {dealsCount != null && dealsCount > 0 && (+ <li>+ • {dealsCount} deal+ {dealsCount !== 1 ? "s" : ""} will be updated+ </li>+ )}+ {loserContact.email_jsonb?.length > 0 && (+ <li>+ • {loserContact.email_jsonb.length} email address+ {loserContact.email_jsonb.length !== 1 ? "es" : ""} will+ be added+ </li>+ )}+ {loserContact.phone_jsonb?.length > 0 && (+ <li>+ • {loserContact.phone_jsonb.length} phone number+ {loserContact.phone_jsonb.length !== 1 ? "s" : ""} will be+ added+ </li>+ )}+ {!notesCount &&+ !tasksCount &&+ !dealsCount &&+ !loserContact.email_jsonb?.length &&+ !loserContact.phone_jsonb?.length && (+ <li className="text-muted-foreground/60">+ No additional data to merge+ </li>+ )}+ </ul>+ </div>+ <Alert variant="destructive">+ <AlertTriangle className="h-4 w-4" />+ <AlertTitle>Warning: Destructive Operation</AlertTitle>+ <AlertDescription>+ All data will be transferred to the second contact. This+ action cannot be undone.+ </AlertDescription>+ </Alert>+ </>+ )}+ </div>++ <DialogFooter>+ <Button variant="ghost" onClick={onClose} disabled={isMerging}>+ <CircleX />+ Cancel+ </Button>+ <Button onClick={handleMerge} disabled={!winnerId || isMerging}>+ <Merge />+ {isMerging ? "Merging..." : "Merge Contacts"}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+};diff --git a/src/components/atomic-crm/contacts/useContactMerge.ts b/src/components/atomic-crm/contacts/useContactMerge.tsnew file mode 100644index 00000000..8fd4be9a--- /dev/null+++ b/src/components/atomic-crm/contacts/useContactMerge.ts@@ -0,0 +1,203 @@+import { useState } from "react";+import { useUpdate, useDelete, useDataProvider } from "ra-core";+import type { Identifier } from "ra-core";++import type { Contact } from "../types";++export const useContactMerge = () => {+ const [isMerging, setIsMerging] = useState(false);+ const dataProvider = useDataProvider();+ // use update hooks to refresh cache after updates+ const [updateTask] = useUpdate("tasks", undefined, { returnPromise: true });+ const [updateNote] = useUpdate("contactNotes", undefined, {+ returnPromise: true,+ });+ const [updateDeal] = useUpdate("deals", undefined, { returnPromise: true });+ const [updateContact] = useUpdate("contacts", undefined, {+ returnPromise: true,+ });+ const [deleteContact] = useDelete("contacts", undefined, {+ returnPromise: true,+ });++ const mergeContacts = async (loserId: Identifier, winnerId: Identifier) => {+ setIsMerging(true);++ try {+ // Fetch both contacts using dataProvider to get fresh data+ const { data: winnerContact } = await dataProvider.getOne<Contact>(+ "contacts",+ { id: winnerId },+ );+ const { data: loserContact } = await dataProvider.getOne<Contact>(+ "contacts",+ { id: loserId },+ );++ if (!winnerContact || !loserContact) {+ throw new Error("Could not fetch contacts");+ }++ // 1. Update all tasks from loser to winner+ const { data: loserTasks } = await dataProvider.getManyReference(+ "tasks",+ {+ target: "contact_id",+ id: loserId,+ pagination: { page: 1, perPage: 1000 },+ sort: { field: "id", order: "ASC" },+ filter: {},+ },+ );++ const taskUpdates =+ loserTasks?.map((task) =>+ updateTask("tasks", {+ id: task.id,+ data: { contact_id: winnerId },+ previousData: task,+ }),+ ) || [];++ // 2. Update all notes from loser to winner+ const { data: loserNotes } = await dataProvider.getManyReference(+ "contactNotes",+ {+ target: "contact_id",+ id: loserId,+ pagination: { page: 1, perPage: 1000 },+ sort: { field: "id", order: "ASC" },+ filter: {},+ },+ );++ const noteUpdates =+ loserNotes?.map((note) =>+ updateNote("contactNotes", {+ id: note.id,+ data: { contact_id: winnerId },+ previousData: note,+ }),+ ) || [];++ // 3. Update deals - replace loser ID with winner ID in contact_ids array+ const { data: loserDeals } = await dataProvider.getList("deals", {+ filter: { "contact_ids@cs": `{${loserId}}` },+ pagination: { page: 1, perPage: 1000 },+ sort: { field: "id", order: "ASC" },+ });++ const dealUpdates =+ loserDeals?.map((deal) => {+ const newContactIds = deal.contact_ids+ .filter((id: string) => id !== loserId)+ .concat(winnerId)+ .filter(+ (id: string, index: number, self: string[]) =>+ self.indexOf(id) === index,+ ); // Remove duplicates++ return updateDeal("deals", {+ id: deal.id,+ data: { contact_ids: newContactIds },+ previousData: deal,+ });+ }) || [];++ // 4. Merge contact properties+ const mergedEmails = mergeObjectArraysUnique(+ winnerContact.email_jsonb || [],+ loserContact.email_jsonb || [],+ (email) => email.email,+ );++ const mergedPhones = mergeObjectArraysUnique(+ winnerContact.phone_jsonb || [],+ loserContact.phone_jsonb || [],+ (phone) => phone.number,+ );++ // Update winner contact with merged data+ const winnerUpdate = updateContact("contacts", {+ id: winnerId,+ data: {+ avatar: winnerContact.avatar ?? loserContact.avatar,+ gender: winnerContact.gender ?? loserContact.gender,+ first_name: winnerContact.first_name ?? loserContact.first_name,+ last_name: winnerContact.last_name ?? loserContact.last_name,+ title: winnerContact.title ?? loserContact.title,+ company_id: winnerContact.company_id ?? loserContact.company_id,+ email_jsonb: mergedEmails,+ phone_jsonb: mergedPhones,+ linkedin_url: winnerContact.linkedin_url || loserContact.linkedin_url,+ background: winnerContact.background ?? loserContact.background,+ has_newsletter:+ winnerContact.has_newsletter ?? loserContact.has_newsletter,+ first_seen: winnerContact.first_seen ?? loserContact.first_seen,+ last_seen:+ winnerContact.last_seen > loserContact.last_seen+ ? winnerContact.last_seen+ : loserContact.last_seen,+ sales_id: winnerContact.sales_id ?? loserContact.sales_id,+ tags: mergeArraysUnique(+ winnerContact.tags || [],+ loserContact.tags || [],+ ),+ },+ previousData: winnerContact,+ });++ // Execute all updates+ await Promise.all([+ ...taskUpdates,+ ...noteUpdates,+ ...dealUpdates,+ winnerUpdate,+ ]);++ // 5. Delete the loser contact+ await deleteContact("contacts", {+ id: loserId,+ previousData: loserContact,+ });++ setIsMerging(false);+ return true;+ } catch (error) {+ setIsMerging(false);+ throw error;+ }+ };++ return { mergeContacts, isMerging };+};++// Helper functions to merge arrays and remove duplicates++// For primitive arrays like tags+const mergeArraysUnique = <T>(arr1: T[], arr2: T[]): T[] => [+ ...new Set([...arr1, ...arr2]),+];++// For object arrays like emails and phones+function mergeObjectArraysUnique<T>(+ arr1: T[],+ arr2: T[],+ getKey: (item: T) => string,+): T[] {+ const map = new Map<string, T>();++ arr1.forEach((item) => {+ const key = getKey(item);+ if (key) map.set(key, item);+ });++ arr2.forEach((item) => {+ const key = getKey(item);+ if (key && !map.has(key)) {+ map.set(key, item);+ }+ });++ return Array.from(map.values());+}diff --git a/src/components/atomic-crm/deals/DealInputs.tsx b/src/components/atomic-crm/deals/DealInputs.tsxindex 457bb893..22b03d33 100644--- a/src/components/atomic-crm/deals/DealInputs.tsx+++ b/src/components/atomic-crm/deals/DealInputs.tsx@@ -55,7 +55,6 @@ const DealLinkedToInputs = () => {label="Contacts"optionText={contactOptionText}helperText={false}- validate={required()}/></ReferenceArrayInput></div>