Skip to content

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

Attach forwarded emails sent from a sale's secondary address

Jeromed6b243f3ebb9
diff --git a/src/components/atomic-crm/providers/commons/englishCrmMessages.ts b/src/components/atomic-crm/providers/commons/englishCrmMessages.ts
index de9e8443..9260f23d 100644
--- a/src/components/atomic-crm/providers/commons/englishCrmMessages.ts
+++ b/src/components/atomic-crm/providers/commons/englishCrmMessages.ts
@@ -289,6 +289,8 @@ export const englishCrmMessages = {
first_name: "First name",
last_name: "Last name",
email: "Email",
+ secondary_email: "Secondary email",
+ secondary_emails: "Secondary emails",
administrator: "Admin",
disabled: "Disabled",
},
@@ -528,6 +530,10 @@ export const englishCrmMessages = {
label: "CRM navigation",
},
profile: {
+ add_secondary_email: "Add an email",
+ no_secondary_emails: "None",
+ secondary_emails_help:
+ "Other addresses you send emails from. Leave one empty to remove it.",
inbound: {
description:
"You can start sending emails to your server's inbound email address, e.g. by adding it to the %{field} field. Atomic CRM will process the emails and add notes to the corresponding contacts.",
diff --git a/src/components/atomic-crm/providers/commons/frenchCrmMessages.ts b/src/components/atomic-crm/providers/commons/frenchCrmMessages.ts
index 5d30e91f..5577df0c 100644
--- a/src/components/atomic-crm/providers/commons/frenchCrmMessages.ts
+++ b/src/components/atomic-crm/providers/commons/frenchCrmMessages.ts
@@ -294,6 +294,8 @@ export const frenchCrmMessages = {
first_name: "Prénom",
last_name: "Nom",
email: "E-mail",
+ secondary_email: "E-mail secondaire",
+ secondary_emails: "E-mails secondaires",
administrator: "Admin",
disabled: "Désactivé",
},
@@ -535,6 +537,10 @@ export const frenchCrmMessages = {
label: "Navigation CRM",
},
profile: {
+ add_secondary_email: "Ajouter un e-mail",
+ no_secondary_emails: "Aucun",
+ secondary_emails_help:
+ "Autres adresses depuis lesquelles vous envoyez des e-mails. Laissez-en une vide pour la supprimer.",
inbound: {
description:
"Vous pouvez commencer à envoyer des e-mails vers l'adresse de réception de votre serveur, par exemple en l'ajoutant au champ %{field}. Atomic CRM traitera les e-mails et ajoutera des notes aux contacts correspondants.",
diff --git a/src/components/atomic-crm/providers/fakerest/dataGenerator/sales.ts b/src/components/atomic-crm/providers/fakerest/dataGenerator/sales.ts
index 6b8571ec..a7a4c1ea 100644
--- a/src/components/atomic-crm/providers/fakerest/dataGenerator/sales.ts
+++ b/src/components/atomic-crm/providers/fakerest/dataGenerator/sales.ts
@@ -15,6 +15,7 @@ export const generateSales = (_: Db): Sale[] => {
first_name,
last_name,
email,
+ secondary_emails: [],
password: "demo",
administrator: false,
disabled: false,
@@ -27,6 +28,7 @@ export const generateSales = (_: Db): Sale[] => {
first_name: "Jane",
last_name: "Doe",
+ secondary_emails: [],
password: "demo",
administrator: true,
disabled: false,
diff --git a/src/components/atomic-crm/providers/supabase/dataProvider.ts b/src/components/atomic-crm/providers/supabase/dataProvider.ts
index 664943d8..374c7083 100644
--- a/src/components/atomic-crm/providers/supabase/dataProvider.ts
+++ b/src/components/atomic-crm/providers/supabase/dataProvider.ts
@@ -139,8 +139,15 @@ const getDataProviderWithCustomMethods = () => {
id: Identifier,
data: Partial<Omit<SalesFormData, "password">>,
) {
- const { email, first_name, last_name, administrator, avatar, disabled } =
- data;
+ const {
+ email,
+ secondary_emails,
+ first_name,
+ last_name,
+ administrator,
+ avatar,
+ disabled,
+ } = data;
const { data: updatedData, error } =
await getSupabaseClient().functions.invoke<{
@@ -150,6 +157,7 @@ const getDataProviderWithCustomMethods = () => {
body: {
sales_id: id,
email,
+ secondary_emails,
first_name,
last_name,
administrator,
diff --git a/src/components/atomic-crm/settings/ProfilePage.tsx b/src/components/atomic-crm/settings/ProfilePage.tsx
index 4aae578d..5cea2177 100644
--- a/src/components/atomic-crm/settings/ProfilePage.tsx
+++ b/src/components/atomic-crm/settings/ProfilePage.tsx
@@ -1,6 +1,7 @@
import { useMutation } from "@tanstack/react-query";
import { Check, CircleX, Copy, Pencil, Save } from "lucide-react";
import {
+ email,
Form,
useDataProvider,
useGetIdentity,
@@ -13,7 +14,9 @@ import {
} from "ra-core";
import { useState } from "react";
import { useFormState } from "react-hook-form";
+import { ArrayInput } from "@/components/admin/array-input";
import { RecordField } from "@/components/admin/record-field";
+import { SimpleFormIterator } from "@/components/admin/simple-form-iterator";
import { TextInput } from "@/components/admin/text-input";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
@@ -193,6 +196,7 @@ const ProfileForm = ({
<TextRender source="last_name" isEditMode={isEditMode} />
</div>
<TextRender source="email" isEditMode={isEditMode} />
+ <SecondaryEmailsRender isEditMode={isEditMode} />
<LanguageSelector />
</div>
@@ -328,6 +332,41 @@ const TextRender = ({
);
};
+const SecondaryEmailsRender = ({ isEditMode }: { isEditMode: boolean }) => {
+ const translate = useTranslate();
+ const label = "resources.sales.fields.secondary_emails";
+
+ if (isEditMode) {
+ return (
+ <ArrayInput source="secondary_emails" label={label} helperText={false}>
+ <SimpleFormIterator
+ resource="sales"
+ disableReordering
+ fullWidth
+ getItemLabel={false}
+ >
+ <TextInput
+ source=""
+ label={false}
+ helperText={false}
+ validate={email()}
+ placeholder={translate("resources.sales.fields.email")}
+ />
+ </SimpleFormIterator>
+ </ArrayInput>
+ );
+ }
+
+ return (
+ <RecordField
+ source="secondary_emails"
+ label={label}
+ render={(record: Sale) => record.secondary_emails?.join(", ")}
+ empty={translate("crm.profile.no_secondary_emails")}
+ />
+ );
+};
+
const CopyPaste = ({ value }: { value: string }) => {
const translate = useTranslate();
const [copied, setCopied] = useState(false);
diff --git a/src/components/atomic-crm/settings/SettingsPageMobile.tsx b/src/components/atomic-crm/settings/SettingsPageMobile.tsx
index 5320d5d4..7e4f2baf 100644
--- a/src/components/atomic-crm/settings/SettingsPageMobile.tsx
+++ b/src/components/atomic-crm/settings/SettingsPageMobile.tsx
@@ -33,7 +33,7 @@ import {
useNotify,
useTranslate,
} from "ra-core";
-import { useCallback, useEffect, useRef, useState } from "react";
+import { Fragment, useCallback, useEffect, useRef, useState } from "react";
import {
Tooltip,
TooltipContent,
@@ -150,10 +150,10 @@ const ProfileSection = () => {
const queryClient = useQueryClient();
const saveField = useCallback(
- async (field: string, value: string) => {
+ async (field: string, value: string | string[]) => {
if (!identity || !data) return;
const current = data[field as keyof typeof data];
- if (value === current) return;
+ if (JSON.stringify(value) === JSON.stringify(current)) return;
const queryKey = [
"sales",
@@ -257,20 +257,72 @@ const ProfileSection = () => {
label={translate("resources.sales.fields.email")}
value={data.email ?? ""}
onSave={(v) => saveField("email", v)}
+ type="email"
+ />
+
+ <SecondaryEmailRows
+ emails={data.secondary_emails ?? []}
+ onSave={(emails) => saveField("secondary_emails", emails)}
/>
</ItemGroup>
+ <p className="text-xs text-muted-foreground px-1 mt-1.5">
+ {translate("crm.profile.secondary_emails_help")}
+ </p>
</div>
);
};
+const SecondaryEmailRows = ({
+ emails,
+ onSave,
+}: {
+ emails: string[];
+ onSave: (emails: string[]) => void;
+}) => {
+ const translate = useTranslate();
+ const label = translate("resources.sales.fields.secondary_email");
+
+ return (
+ <>
+ {emails.map((email, index) => (
+ <Fragment key={index}>
+ <ItemSeparator />
+ <InlineEditRow
+ label={`${label} ${index + 1}`}
+ value={email}
+ type="email"
+ onSave={(value) =>
+ onSave(
+ value
+ ? emails.map((current, i) => (i === index ? value : current))
+ : emails.filter((_, i) => i !== index),
+ )
+ }
+ />
+ </Fragment>
+ ))}
+ <ItemSeparator />
+ <InlineEditRow
+ key={`add-${emails.length}`}
+ label={translate("crm.profile.add_secondary_email")}
+ value=""
+ type="email"
+ onSave={(value) => onSave([...emails, value])}
+ />
+ </>
+ );
+};
+
const InlineEditRow = ({
label,
value,
onSave,
+ type = "text",
}: {
label: string;
value: string;
onSave: (value: string) => void;
+ type?: string;
}) => {
const [isEditing, setIsEditing] = useState(false);
const [editValue, setEditValue] = useState(value);
@@ -324,6 +376,7 @@ const InlineEditRow = ({
<ItemActions>
<input
ref={inputRef}
+ type={type}
value={editValue}
onChange={(e) => setEditValue(e.target.value)}
onBlur={handleSave}
diff --git a/src/components/atomic-crm/types.ts b/src/components/atomic-crm/types.ts
index 6d1d6ff6..8c8c70d5 100644
--- a/src/components/atomic-crm/types.ts
+++ b/src/components/atomic-crm/types.ts
@@ -19,6 +19,7 @@ export type SignUpData = {
export type SalesFormData = {
avatar?: string;
email: string;
+ secondary_emails?: string[];
password?: string;
first_name: string;
last_name: string;
@@ -40,6 +41,8 @@ export type Sale = {
*/
email: string;
+ secondary_emails?: string[];
+
/**
* This is used by the fake rest provider to store the password
* DO NOT USE this field in your code besides the fake rest provider
diff --git a/supabase/functions/postmark/addNoteToContact.test.ts b/supabase/functions/postmark/addNoteToContact.test.ts
index f5b57bb2..e63ea199 100644
--- a/supabase/functions/postmark/addNoteToContact.test.ts
+++ b/supabase/functions/postmark/addNoteToContact.test.ts
@@ -2,6 +2,7 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import {
addNoteToContact,
+ findActiveSaleByEmail,
getOrCreateCompanyFromDomain,
getOrCreateContactFromEmailInfo,
} from "./addNoteToContact";
@@ -324,6 +325,79 @@ describe("addNoteToContact", () => {
});
});
+ describe("findActiveSaleByEmail", () => {
+ it("returns the active sale whose primary email matches the sender", async () => {
+ const salesRecord = { id: 1, email: "[email protected]" };
+ mockFrom.mockReturnValueOnce({
+ select: () => ({
+ eq: () => ({
+ neq: () => ({
+ maybeSingle: () =>
+ Promise.resolve({ data: salesRecord, error: null }),
+ }),
+ }),
+ }),
+ });
+
+ const result = await findActiveSaleByEmail("[email protected]");
+
+ expect(result.data).toEqual(salesRecord);
+ expect(mockFrom).toHaveBeenCalledTimes(1);
+ });
+
+ it("looks up the secondary emails when no primary email matches", async () => {
+ const salesRecord = {
+ id: 1,
+ email: "[email protected]",
+ secondary_emails: ["[email protected]"],
+ };
+ const contains = vi.fn().mockReturnValue({
+ neq: () => ({
+ maybeSingle: () =>
+ Promise.resolve({ data: salesRecord, error: null }),
+ }),
+ });
+
+ mockFrom
+ .mockReturnValueOnce({
+ select: () => ({
+ eq: () => ({
+ neq: () => ({
+ maybeSingle: () => Promise.resolve({ data: null, error: null }),
+ }),
+ }),
+ }),
+ })
+ .mockReturnValueOnce({ select: () => ({ contains }) });
+
+ const result = await findActiveSaleByEmail("[email protected]");
+
+ expect(result.data).toEqual(salesRecord);
+ expect(contains).toHaveBeenCalledWith(
+ "secondary_emails",
+ );
+ });
+
+ it("does not look up the secondary emails when the first query fails", async () => {
+ mockFrom.mockReturnValueOnce({
+ select: () => ({
+ eq: () => ({
+ neq: () => ({
+ maybeSingle: () =>
+ Promise.resolve({ data: null, error: { message: "DB error" } }),
+ }),
+ }),
+ }),
+ });
+
+ const result = await findActiveSaleByEmail("[email protected]");
+
+ expect(result.error).toEqual({ message: "DB error" });
+ expect(mockFrom).toHaveBeenCalledTimes(1);
+ });
+ });
+
describe("addNoteToContact", () => {
const baseParams = {
salesEmail: "[email protected]",
@@ -385,6 +459,72 @@ describe("addNoteToContact", () => {
expect(mockFrom).toHaveBeenNthCalledWith(4, "contacts");
});
+ it("attaches the note to the sale when the sender only matches a secondary email", async () => {
+ const salesRecord = {
+ id: 7,
+ email: "[email protected]",
+ secondary_emails: ["[email protected]"],
+ };
+ const existingContact = {
+ id: 10,
+ first_name: "Alice",
+ last_name: "Smith",
+ };
+ const insertNote = vi.fn().mockResolvedValue({ error: null });
+
+ mockFrom
+ .mockReturnValueOnce({
+ // 1st call: fetch sales by primary email → not found
+ select: () => ({
+ eq: () => ({
+ neq: () => ({
+ maybeSingle: () => Promise.resolve({ data: null, error: null }),
+ }),
+ }),
+ }),
+ })
+ .mockReturnValueOnce({
+ // 2nd call: fetch sales by secondary emails → found
+ select: () => ({
+ contains: () => ({
+ neq: () => ({
+ maybeSingle: () =>
+ Promise.resolve({ data: salesRecord, error: null }),
+ }),
+ }),
+ }),
+ })
+ .mockReturnValueOnce({
+ // 3rd call: fetch contact → found
+ select: () => ({
+ contains: () => ({
+ maybeSingle: () =>
+ Promise.resolve({ data: existingContact, error: null }),
+ }),
+ }),
+ })
+ .mockReturnValueOnce({
+ // 4th call: insert note into contact_notes → success
+ insert: insertNote,
+ })
+ .mockReturnValueOnce({
+ // 5th call: update contacts.last_seen
+ update: () => ({
+ eq: () => Promise.resolve({ error: null }),
+ }),
+ });
+
+ const result = await addNoteToContact({
+ ...baseParams,
+ salesEmail: "[email protected]",
+ });
+
+ expect(result).toBeUndefined();
+ expect(insertNote).toHaveBeenCalledWith(
+ expect.objectContaining({ sales_id: 7, contact_id: 10 }),
+ );
+ });
+
it("returns 500 when inserting the note into contact_notes fails", async () => {
const salesRecord = { id: 1, email: "[email protected]" };
const existingContact = {
diff --git a/supabase/functions/postmark/addNoteToContact.ts b/supabase/functions/postmark/addNoteToContact.ts
index a4abfb52..a5615f57 100644
--- a/supabase/functions/postmark/addNoteToContact.ts
+++ b/supabase/functions/postmark/addNoteToContact.ts
@@ -110,6 +110,26 @@ export const getOrCreateContactFromEmailInfo = async ({
return newContacts[0];
};
+export const findActiveSaleByEmail = async (salesEmail: string) => {
+ const byPrimaryEmail = await supabaseAdmin
+ .from("sales")
+ .select("*")
+ .eq("email", salesEmail)
+ .neq("disabled", true)
+ .maybeSingle();
+
+ if (byPrimaryEmail.error || byPrimaryEmail.data) {
+ return byPrimaryEmail;
+ }
+
+ return await supabaseAdmin
+ .from("sales")
+ .select("*")
+ .contains("secondary_emails", JSON.stringify([salesEmail]))
+ .neq("disabled", true)
+ .maybeSingle();
+};
+
export const addNoteToContact = async ({
salesEmail,
email,
@@ -131,12 +151,8 @@ export const addNoteToContact = async ({
companyName: string;
website: string;
}) => {
- const { data: sales, error: fetchSalesError } = await supabaseAdmin
- .from("sales")
- .select("*")
- .eq("email", salesEmail)
- .neq("disabled", true)
- .maybeSingle();
+ const { data: sales, error: fetchSalesError } =
+ await findActiveSaleByEmail(salesEmail);
if (fetchSalesError) {
return new Response(
diff --git a/supabase/functions/postmark/index.ts b/supabase/functions/postmark/index.ts
index 50eeee13..9a24255e 100644
--- a/supabase/functions/postmark/index.ts
+++ b/supabase/functions/postmark/index.ts
@@ -52,9 +52,16 @@ Deno.serve(async (req) => {
);
}
- const allSales = await supabaseAdmin.from("sales").select("email");
+ const allSales = await supabaseAdmin
+ .from("sales")
+ .select("email, secondary_emails");
const salesEmails =
- allSales.data?.map((s: { email: string }) => s.email) ?? [];
+ allSales.data
+ ?.flatMap((s: { email: string; secondary_emails: string[] | null }) => [
+ s.email,
+ ...(s.secondary_emails ?? []),
+ ])
+ .map((email: string) => email.toLowerCase()) ?? [];
const firstToEmail = (ToFull[0]?.Email || "").toLowerCase();
diff --git a/supabase/functions/users/index.ts b/supabase/functions/users/index.ts
index 5db864a3..9c666653 100644
--- a/supabase/functions/users/index.ts
+++ b/supabase/functions/users/index.ts
@@ -4,6 +4,7 @@ import { corsHeaders, OptionsMiddleware } from "../_shared/cors.ts";
import { createErrorResponse } from "../_shared/utils.ts";
import { AuthMiddleware, UserMiddleware } from "../_shared/authentication.ts";
import { getUserSale } from "../_shared/getUserSale.ts";
+import { normalizeSecondaryEmails } from "./normalizeSecondaryEmails.ts";
async function updateSaleDisabled(user_id: string, disabled: boolean) {
return await supabaseAdmin
@@ -52,6 +53,21 @@ async function createSale(
return sales.at(0);
}
+async function updateSaleSecondaryEmails(
+ user_id: string,
+ secondary_emails: unknown,
+) {
+ const { error: salesError } = await supabaseAdmin
+ .from("sales")
+ .update({ secondary_emails: normalizeSecondaryEmails(secondary_emails) })
+ .eq("user_id", user_id);
+
+ if (salesError) {
+ console.error("Error updating user:", salesError);
+ throw salesError;
+ }
+}
+
async function updateSaleAvatar(user_id: string, avatar: string) {
const { data: sales, error: salesError } = await supabaseAdmin
.from("sales")
@@ -182,6 +198,7 @@ async function patchUser(req: Request, currentUserSale: any) {
const {
sales_id,
email,
+ secondary_emails,
first_name,
last_name,
avatar,
@@ -219,6 +236,10 @@ async function patchUser(req: Request, currentUserSale: any) {
await updateSaleAvatar(data.user.id, avatar);
}
+ if (secondary_emails !== undefined) {
+ await updateSaleSecondaryEmails(data.user.id, secondary_emails);
+ }
+
// Only administrators can update the administrator and disabled status
if (!currentUserSale.administrator) {
const { data: new_sale } = await supabaseAdmin
diff --git a/supabase/functions/users/normalizeSecondaryEmails.test.ts b/supabase/functions/users/normalizeSecondaryEmails.test.ts
new file mode 100644
index 00000000..8f2f2599
--- /dev/null
+++ b/supabase/functions/users/normalizeSecondaryEmails.test.ts
@@ -0,0 +1,35 @@
+// @vitest-environment node
+import { describe, it, expect } from "vitest";
+import { normalizeSecondaryEmails } from "./normalizeSecondaryEmails";
+
+describe("normalizeSecondaryEmails", () => {
+ it("returns an empty array when the value is not an array", () => {
+ expect(normalizeSecondaryEmails(undefined)).toEqual([]);
+ expect(normalizeSecondaryEmails(null)).toEqual([]);
+ expect(normalizeSecondaryEmails("[email protected]")).toEqual([]);
+ });
+
+ it("trims and lowercases every address", () => {
+ expect(normalizeSecondaryEmails([" [email protected] "])).toEqual([
+ ]);
+ });
+
+ it("removes addresses that differ only by case or spacing", () => {
+ expect(
+ normalizeSecondaryEmails(["[email protected]", " [email protected] "]),
+ ).toEqual(["[email protected]"]);
+ });
+
+ it("drops empty entries and non-string values", () => {
+ expect(
+ normalizeSecondaryEmails(["[email protected]", "", " ", 42, null]),
+ ).toEqual(["[email protected]"]);
+ });
+
+ it("preserves the order of the remaining addresses", () => {
+ expect(
+ normalizeSecondaryEmails(["[email protected]", "[email protected]", "[email protected]"]),
+ });
+});
diff --git a/supabase/functions/users/normalizeSecondaryEmails.ts b/supabase/functions/users/normalizeSecondaryEmails.ts
new file mode 100644
index 00000000..7b7360ae
--- /dev/null
+++ b/supabase/functions/users/normalizeSecondaryEmails.ts
@@ -0,0 +1,15 @@
+export const normalizeSecondaryEmails = (
+ secondaryEmails: unknown,
+): string[] => {
+ if (!Array.isArray(secondaryEmails)) {
+ return [];
+ }
+ return [
+ ...new Set(
+ secondaryEmails
+ .filter((email): email is string => typeof email === "string")
+ .map((email) => email.trim().toLowerCase())
+ .filter(Boolean),
+ ),
+ ];
+};
diff --git a/supabase/migrations/20260811131131_sales_secondary_emails.sql b/supabase/migrations/20260811131131_sales_secondary_emails.sql
new file mode 100644
index 00000000..2d2a69f6
--- /dev/null
+++ b/supabase/migrations/20260811131131_sales_secondary_emails.sql
@@ -0,0 +1 @@
+alter table "public"."sales" add column "secondary_emails" jsonb not null default '[]'::jsonb;
diff --git a/supabase/schemas/01_tables.sql b/supabase/schemas/01_tables.sql
index 7e3d8752..d6cc5f80 100644
--- a/supabase/schemas/01_tables.sql
+++ b/supabase/schemas/01_tables.sql
@@ -97,7 +97,8 @@ create table public.sales (
administrator boolean not null,
user_id uuid not null,
avatar jsonb,
- disabled boolean not null default false
+ disabled boolean not null default false,
+ secondary_emails jsonb not null default '[]'::jsonb
);
create unique index uq__sales__user_id on public.sales using btree (user_id);