A full-featured CRM built with React, shadcn/ui, and Supabase.
Add Export to vCard button
François Zaninottoff74d5e5a8de
diff --git a/registry.json b/registry.jsonindex f1ed2a9c..c3f5e33c 100644--- a/registry.json+++ b/registry.json@@ -502,6 +502,10 @@"path": "src/components/atomic-crm/contacts/index.tsx","type": "registry:component"},+ {+ "path": "src/components/atomic-crm/contacts/exportToVCard.ts",+ "type": "registry:component"+ },{"path": "src/components/atomic-crm/contacts/TagsListEdit.tsx","type": "registry:component"@@ -510,6 +514,10 @@"path": "src/components/atomic-crm/contacts/TagsList.tsx","type": "registry:component"},+ {+ "path": "src/components/atomic-crm/contacts/ExportVCardButton.tsx",+ "type": "registry:component"+ },{"path": "src/components/atomic-crm/contacts/ContactShow.tsx","type": "registry:component"@@ -518,6 +526,10 @@"path": "src/components/atomic-crm/contacts/ContactMergeDialog.tsx","type": "registry:component"},+ {+ "path": "src/components/atomic-crm/contacts/ContactMergeButton.tsx",+ "type": "registry:component"+ },{"path": "src/components/atomic-crm/contacts/ContactListFilter.tsx","type": "registry:component"diff --git a/src/components/atomic-crm/contacts/ContactAside.tsx b/src/components/atomic-crm/contacts/ContactAside.tsxindex c5d51824..de816eaa 100644--- a/src/components/atomic-crm/contacts/ContactAside.tsx+++ b/src/components/atomic-crm/contacts/ContactAside.tsx@@ -1,6 +1,5 @@-import { Linkedin, Mail, Phone, Merge } from "lucide-react";+import { Linkedin, Mail, Phone } 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";@@ -11,7 +10,6 @@ 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";@@ -20,12 +18,12 @@ import { AsideSection } from "../misc/AsideSection";import { useConfigurationContext } from "../root/ConfigurationContext";import { SaleName } from "../sales/SaleName";import type { Contact } from "../types";-import { ContactMergeDialog } from "./ContactMergeDialog";+import { ContactMergeButton } from "./ContactMergeButton";+import { ExportVCardButton } from "./ExportVCardButton";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 (@@ -144,20 +142,9 @@ export const ContactAside = ({ link = "edit" }: { link?: "edit" | "show" }) => {</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 className="mt-6 pt-6 border-t hidden sm:flex flex-col gap-2 items-start">+ <ExportVCardButton />+ <ContactMergeButton /></div>)}</div>diff --git a/src/components/atomic-crm/contacts/ContactMergeButton.tsx b/src/components/atomic-crm/contacts/ContactMergeButton.tsxnew file mode 100644index 00000000..6aee9a83--- /dev/null+++ b/src/components/atomic-crm/contacts/ContactMergeButton.tsx@@ -0,0 +1,26 @@+import { Merge } from "lucide-react";+import { useState } from "react";+import { Button } from "@/components/ui/button";++import { ContactMergeDialog } from "./ContactMergeDialog";++export const ContactMergeButton = () => {+ const [mergeDialogOpen, setMergeDialogOpen] = useState(false);+ return (+ <>+ <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)}+ />+ </>+ );+};diff --git a/src/components/atomic-crm/contacts/ExportVCardButton.tsx b/src/components/atomic-crm/contacts/ExportVCardButton.tsxnew file mode 100644index 00000000..53867b95--- /dev/null+++ b/src/components/atomic-crm/contacts/ExportVCardButton.tsx@@ -0,0 +1,79 @@+import { Download } from "lucide-react";+import { useGetOne, useRecordContext } from "ra-core";+import { Button } from "@/components/ui/button";+import type { Contact, Company } from "../types";+import { exportToVCard } from "./exportToVCard";++export const ExportVCardButton = () => {+ const contact = useRecordContext<Contact>();++ // Fetch the company data on mount+ const { data: company } = useGetOne<Company>(+ "companies",+ { id: contact?.company_id },+ { enabled: !!contact?.company_id },+ );++ const handleExport = async () => {+ if (!contact) return;++ // Fetch and convert avatar to base64 if it exists+ let photoData: { base64: string; mimeType: string } | undefined = undefined;++ if (contact.avatar?.src) {+ try {+ const response = await fetch(contact.avatar.src);+ const blob = await response.blob();+ const mimeType = blob.type || "image/png";++ // Convert blob to base64+ const base64 = await new Promise<string>((resolve, reject) => {+ const reader = new FileReader();+ reader.onloadend = () => {+ const result = reader.result as string;+ // Remove the data URL prefix (data:image/png;base64,)+ const base64Data = result.split(",")[1];+ resolve(base64Data);+ };+ reader.onerror = reject;+ reader.readAsDataURL(blob);+ });++ photoData = { base64, mimeType };+ } catch (error) {+ console.error("Failed to fetch avatar image:", error);+ // Continue without the photo+ }+ }++ // Generate vCard content+ const vCardContent = exportToVCard(contact, company, photoData);++ // Create blob and download+ const blob = new Blob([vCardContent], {+ type: "text/vcard;charset=utf-8",+ });+ const url = URL.createObjectURL(blob);+ const link = document.createElement("a");+ link.href = url;+ link.download = `${contact.first_name}_${contact.last_name}.vcf`;+ document.body.appendChild(link);+ link.click();+ document.body.removeChild(link);+ URL.revokeObjectURL(url);+ };++ if (!contact) return null;++ return (+ <Button+ variant="outline"+ size="sm"+ onClick={handleExport}+ className="h-6 cursor-pointer"+ >+ <Download className="w-4 h-4" />+ Export to vCard+ </Button>+ );+};diff --git a/src/components/atomic-crm/contacts/exportToVCard.ts b/src/components/atomic-crm/contacts/exportToVCard.tsnew file mode 100644index 00000000..6ef75ab9--- /dev/null+++ b/src/components/atomic-crm/contacts/exportToVCard.ts@@ -0,0 +1,104 @@+import type { Contact, Company } from "../types";++/**+ * Folds a long line according to vCard specification (max 75 chars per line)+ * Continuation lines start with a space+ */+function foldLine(line: string): string {+ const maxLength = 75;+ if (line.length <= maxLength) return line;++ const result: string[] = [];+ let currentLine = line.substring(0, maxLength);+ let remaining = line.substring(maxLength);++ result.push(currentLine);++ while (remaining.length > 0) {+ // Continuation lines start with a space and can have 74 more chars+ const chunkSize = maxLength - 1;+ currentLine = " " + remaining.substring(0, chunkSize);+ remaining = remaining.substring(chunkSize);+ result.push(currentLine);+ }++ return result.join("\r\n");+}++/**+ * Converts a contact and their company to vCard 3.0 format+ */+export function exportToVCard(+ contact: Contact,+ company?: Company,+ photoData?: { base64: string; mimeType: string },+): string {+ const lines: string[] = [];++ // vCard header+ lines.push("BEGIN:VCARD");+ lines.push("VERSION:3.0");++ // Name (N: Family Name;Given Name;Additional Names;Honorific Prefixes;Honorific Suffixes)+ lines.push(`N:${contact.last_name};${contact.first_name};;;`);++ // Formatted name+ lines.push(`FN:${contact.first_name} ${contact.last_name}`);++ // Title/Job position+ if (contact.title) {+ lines.push(`TITLE:${contact.title}`);+ }++ // Organization+ if (company?.name) {+ lines.push(`ORG:${company.name}`);+ }++ // Emails+ if (contact.email_jsonb && contact.email_jsonb.length > 0) {+ contact.email_jsonb.forEach((emailObj) => {+ const type = emailObj.type.toUpperCase();+ lines.push(`EMAIL;TYPE=${type}:${emailObj.email}`);+ });+ }++ // Phone numbers+ if (contact.phone_jsonb && contact.phone_jsonb.length > 0) {+ contact.phone_jsonb.forEach((phoneObj) => {+ const type = phoneObj.type.toUpperCase();+ lines.push(`TEL;TYPE=${type}:${phoneObj.number}`);+ });+ }++ // LinkedIn URL+ if (contact.linkedin_url) {+ lines.push(`URL:${contact.linkedin_url}`);+ }++ // Background/Note+ if (contact.background) {+ // Escape newlines and special characters in notes+ const escapedNote = contact.background+ .replace(/\\/g, "\\\\")+ .replace(/\n/g, "\\n")+ .replace(/,/g, "\\,")+ .replace(/;/g, "\\;");+ lines.push(`NOTE:${escapedNote}`);+ }++ // Photo/Avatar - vCard 3.0 format with base64 encoding+ if (photoData) {+ // Extract image type from MIME type (e.g., "image/png" -> "PNG")+ const imageType = photoData.mimeType.split("/")[1]?.toUpperCase() || "PNG";++ // vCard 3.0 format: PHOTO;ENCODING=b;TYPE=PNG:+ const photoLine = `PHOTO;ENCODING=b;TYPE=${imageType}:${photoData.base64}`;+ lines.push(foldLine(photoLine));+ }++ // vCard footer+ lines.push("END:VCARD");++ return lines.join("\r\n");+}