Skip to content

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

Make contact merge logic independent of the UI

François Zaninottod772bab41fa9
diff --git a/registry.json b/registry.json
index 0f17a9ff..246f9355 100644
--- a/registry.json
+++ b/registry.json
@@ -493,11 +493,11 @@
"type": "registry:component"
},
{
- "path": "src/components/atomic-crm/contacts/useContactMerge.ts",
+ "path": "src/components/atomic-crm/contacts/useContactImport.tsx",
"type": "registry:component"
},
{
- "path": "src/components/atomic-crm/contacts/useContactImport.tsx",
+ "path": "src/components/atomic-crm/contacts/mergeContacts.ts",
"type": "registry:component"
},
{
diff --git a/src/components/atomic-crm/contacts/ContactMergeButton.tsx b/src/components/atomic-crm/contacts/ContactMergeButton.tsx
index 8eebebee..1d195a07 100644
--- a/src/components/atomic-crm/contacts/ContactMergeButton.tsx
+++ b/src/components/atomic-crm/contacts/ContactMergeButton.tsx
@@ -1,6 +1,7 @@
import { useState, useEffect } from "react";
import { Merge, CircleX, AlertTriangle, ArrowDown } from "lucide-react";
import {
+ useDataProvider,
useRecordContext,
useGetList,
useGetManyReference,
@@ -24,7 +25,7 @@ import { AutocompleteInput } from "@/components/admin/autocomplete-input";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import type { Contact } from "../types";
import { contactOptionText } from "../misc/ContactOption";
-import { useContactMerge } from "./useContactMerge";
+import { mergeContacts } from "./mergeContacts";
export const ContactMergeButton = () => {
const [mergeDialogOpen, setMergeDialogOpen] = useState(false);
@@ -56,12 +57,12 @@ const ContactMergeDialog = ({ open, onClose }: ContactMergeDialogProps) => {
const loserContact = useRecordContext<Contact>();
const notify = useNotify();
const redirect = useRedirect();
+ const dataProvider = useDataProvider();
const [winnerId, setWinnerId] = useState<Identifier | null>(null);
const [suggestedWinnerId, setSuggestedWinnerId] = useState<Identifier | null>(
null,
);
-
- const { mergeContacts, isMerging } = useContactMerge();
+ const [isMerging, setIsMerging] = useState(false);
// Find potential contacts with matching first and last name
const { data: matchingContacts } = useGetList(
@@ -123,11 +124,14 @@ const ContactMergeDialog = ({ open, onClose }: ContactMergeDialogProps) => {
}
try {
- await mergeContacts(loserContact.id, winnerId);
+ setIsMerging(true);
+ await mergeContacts(loserContact.id, winnerId, dataProvider);
+ setIsMerging(false);
notify("Contacts merged successfully", { type: "success" });
redirect(`/contacts/${winnerId}/show`);
onClose();
} catch (error) {
+ setIsMerging(false);
notify("Failed to merge contacts", { type: "error" });
console.error("Merge failed:", error);
}
diff --git a/src/components/atomic-crm/contacts/mergeContacts.ts b/src/components/atomic-crm/contacts/mergeContacts.ts
new file mode 100644
index 00000000..2dc0be21
--- /dev/null
+++ b/src/components/atomic-crm/contacts/mergeContacts.ts
@@ -0,0 +1,185 @@
+import type { Identifier, DataProvider } from "ra-core";
+
+import type { Contact, Task, Deal, ContactNote } from "../types";
+
+/**
+ * Merge one contact (loser) into another contact (winner).
+ *
+ * This function copies properties from the loser to the winner contact,
+ * transfers all associated data (tasks, notes, deals) from the loser to the winner,
+ * and deletes the loser contact.
+ */
+export const mergeContacts = async (
+ loserId: Identifier,
+ winnerId: Identifier,
+ dataProvider: DataProvider,
+) => {
+ // 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. Reassign all tasks from loser to winner
+ const { data: loserTasks } = await dataProvider.getManyReference<Task>(
+ "tasks",
+ {
+ target: "contact_id",
+ id: loserId,
+ pagination: { page: 1, perPage: 1000 },
+ sort: { field: "id", order: "ASC" },
+ filter: {},
+ },
+ );
+
+ const taskUpdates =
+ loserTasks?.map((task) =>
+ dataProvider.update("tasks", {
+ id: task.id,
+ data: { contact_id: winnerId },
+ previousData: task,
+ }),
+ ) || [];
+
+ // 2. Reassign all notes from loser to winner
+ const { data: loserNotes } = await dataProvider.getManyReference<ContactNote>(
+ "contactNotes",
+ {
+ target: "contact_id",
+ id: loserId,
+ pagination: { page: 1, perPage: 1000 },
+ sort: { field: "id", order: "ASC" },
+ filter: {},
+ },
+ );
+
+ const noteUpdates =
+ loserNotes?.map((note) =>
+ dataProvider.update<ContactNote>("contactNotes", {
+ id: note.id,
+ data: { contact_id: winnerId },
+ previousData: note,
+ }),
+ ) || [];
+
+ // 3. Change contact in deals - replace loser ID with winner ID in contact_ids array
+ const { data: loserDeals } = await dataProvider.getList<Deal>("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) => id !== loserId)
+ .concat(winnerId)
+ .filter(
+ (id: Identifier, index: number, self: Identifier[]) =>
+ self.indexOf(id) === index,
+ ); // Remove duplicates
+
+ return dataProvider.update<Deal>("deals", {
+ id: deal.id,
+ data: { contact_ids: newContactIds },
+ previousData: deal,
+ });
+ }) || [];
+
+ // 4. Update winner contact with loser data
+ const mergedEmails = mergeObjectArraysUnique(
+ winnerContact.email_jsonb || [],
+ loserContact.email_jsonb || [],
+ (email) => email.email,
+ );
+
+ const mergedPhones = mergeObjectArraysUnique(
+ winnerContact.phone_jsonb || [],
+ loserContact.phone_jsonb || [],
+ (phone) => phone.number,
+ );
+
+ const winnerUpdate = dataProvider.update<Contact>("contacts", {
+ id: winnerId,
+ data: {
+ avatar:
+ winnerContact.avatar && winnerContact.avatar.src
+ ? 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 dataProvider.delete<Contact>("contacts", {
+ id: loserId,
+ previousData: loserContact,
+ });
+};
+
+// 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/contacts/useContactMerge.ts b/src/components/atomic-crm/contacts/useContactMerge.ts
deleted file mode 100644
index 0a9de146..00000000
--- a/src/components/atomic-crm/contacts/useContactMerge.ts
+++ /dev/null
@@ -1,206 +0,0 @@
-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 && winnerContact.avatar.src
- ? 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());
-}