A full-featured CRM built with React, shadcn/ui, and Supabase.
Resolve the sender's sale once, before writing anything
Jerome425e1b46a1e5
diff --git a/src/components/atomic-crm/settings/ProfilePage.tsx b/src/components/atomic-crm/settings/ProfilePage.tsxindex d30c3c05..246374cb 100644--- a/src/components/atomic-crm/settings/ProfilePage.tsx+++ b/src/components/atomic-crm/settings/ProfilePage.tsx@@ -72,6 +72,8 @@ export const ProfilePage = () => {});},onError: (error) => {+ refetchIdentity();+ refetchUser();const { message, args } = getSalesErrorNotification(error);notify(message, {type: "error",diff --git a/src/components/atomic-crm/settings/SettingsPageMobile.tsx b/src/components/atomic-crm/settings/SettingsPageMobile.tsxindex e453227d..c5eb8c99 100644--- a/src/components/atomic-crm/settings/SettingsPageMobile.tsx+++ b/src/components/atomic-crm/settings/SettingsPageMobile.tsx@@ -162,7 +162,6 @@ const ProfileSection = () => {"getOne",{ id: String(identity.id), meta: undefined },];- const previousData = queryClient.getQueryData(queryKey);queryClient.setQueryData(queryKey, (old: any) =>old ? { ...old, [field]: value } : old,);@@ -178,7 +177,8 @@ const ProfileSection = () => {messageArgs: { _: "Your profile has been updated" },});} catch (error) {- queryClient.setQueryData(queryKey, previousData);+ refetchIdentity();+ refetchUser();const { message, args } = getSalesErrorNotification(error);notify(message, {type: "error",diff --git a/supabase/functions/postmark/addNoteToContact.test.ts b/supabase/functions/postmark/addNoteToContact.test.tsindex a269d84e..65048378 100644--- a/supabase/functions/postmark/addNoteToContact.test.ts+++ b/supabase/functions/postmark/addNoteToContact.test.ts@@ -528,7 +528,9 @@ describe("addNoteToContact", () => {});describe("addNoteToContact", () => {+ const sales = { id: 1 };const baseParams = {+ sales,salesEmail: "[email protected]",email: "[email protected]",domain: "acme.com",@@ -540,8 +542,15 @@ describe("addNoteToContact", () => {website: "https://acme.com",};+ const contactFound = (contact: unknown) => ({+ select: () => ({+ contains: () => ({+ maybeSingle: () => Promise.resolve({ data: contact, error: null }),+ }),+ }),+ });+it("creates a note and returns undefined on success", async () => {- const salesRecord = { id: 1, email: "[email protected]" };const existingContact = {id: 10,first_name: "Alice",@@ -549,32 +558,11 @@ describe("addNoteToContact", () => {};mockFrom+ .mockReturnValueOnce(contactFound(existingContact)).mockReturnValueOnce({- // 1st call: fetch sales → found- select: () => ({- eq: () => ({- neq: () => ({- maybeSingle: () =>- Promise.resolve({ data: salesRecord, error: null }),- }),- }),- }),- })- .mockReturnValueOnce({- // 2nd call: fetch contact → found- select: () => ({- contains: () => ({- maybeSingle: () =>- Promise.resolve({ data: existingContact, error: null }),- }),- }),- })- .mockReturnValueOnce({- // 3rd call: insert note into contact_notes → successinsert: () => Promise.resolve({ error: null }),}).mockReturnValueOnce({- // 4th call: update contacts.last_seenupdate: () => ({eq: () => Promise.resolve({ error: null }),}),@@ -583,47 +571,18 @@ describe("addNoteToContact", () => {const result = await addNoteToContact(baseParams);expect(result).toBeUndefined();- expect(mockFrom).toHaveBeenCalledTimes(4);- expect(mockFrom).toHaveBeenNthCalledWith(3, "contact_notes");- expect(mockFrom).toHaveBeenNthCalledWith(4, "contacts");+ expect(mockFrom).toHaveBeenCalledTimes(3);+ expect(mockFrom).toHaveBeenNthCalledWith(2, "contact_notes");+ expect(mockFrom).toHaveBeenNthCalledWith(3, "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",- };+ it("files the note under the sale it was given, without looking one up", async () => {const insertNote = vi.fn().mockResolvedValue({ error: null });mockFrom- .mockReturnValueOnce(primaryLookupMiss)- .mockReturnValueOnce({- // 2nd call: fetch sales by secondary emails → found- select: () => ({- contains: () => secondaryLookupResult([salesRecord]),- }),- })+ .mockReturnValueOnce(contactFound({ id: 10 }))+ .mockReturnValueOnce({ insert: insertNote }).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_seenupdate: () => ({eq: () => Promise.resolve({ error: null }),}),@@ -631,46 +590,20 @@ describe("addNoteToContact", () => {const result = await addNoteToContact({...baseParams,- salesEmail: "[email protected]",+ sales: { id: 7 },});expect(result).toBeUndefined();expect(insertNote).toHaveBeenCalledWith(expect.objectContaining({ sales_id: 7, contact_id: 10 }),);+ expect(mockFrom).not.toHaveBeenCalledWith("sales");});it("returns 500 when inserting the note into contact_notes fails", async () => {- const salesRecord = { id: 1, email: "[email protected]" };- const existingContact = {- id: 10,- first_name: "Alice",- last_name: "Smith",- };-mockFrom+ .mockReturnValueOnce(contactFound({ id: 10 })).mockReturnValueOnce({- // 1st call: fetch sales → found- select: () => ({- eq: () => ({- neq: () => ({- maybeSingle: () =>- Promise.resolve({ data: salesRecord, error: null }),- }),- }),- }),- })- .mockReturnValueOnce({- // 2nd call: fetch contact → found- select: () => ({- contains: () => ({- maybeSingle: () =>- Promise.resolve({ data: existingContact, error: null }),- }),- }),- })- .mockReturnValueOnce({- // 3rd call: insert note into contact_notes → failsinsert: () =>Promise.resolve({ error: { message: "Insert failed" } }),});@@ -682,36 +615,22 @@ describe("addNoteToContact", () => {expect(await response!.text()).toBe("Could not add note to contact [email protected], sales [email protected]",);- expect(mockFrom).toHaveBeenCalledTimes(3);+ expect(mockFrom).toHaveBeenCalledTimes(2);});it("returns 500 when getOrCreateContactFromEmailInfo throws", async () => {- const salesRecord = { id: 1, email: "[email protected]" };const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {});- mockFrom- .mockReturnValueOnce({- // 1st call: fetch sales → found- select: () => ({- eq: () => ({- neq: () => ({- maybeSingle: () =>- Promise.resolve({ data: salesRecord, error: null }),- }),- }),- }),- })- .mockReturnValueOnce({- // 2nd call: fetch contact → DB error, causes getOrCreateContactFromEmailInfo to throw- select: () => ({- contains: () => ({- maybeSingle: () =>- Promise.resolve({ data: null, error: { message: "DB error" } }),- }),+ mockFrom.mockReturnValueOnce({+ select: () => ({+ contains: () => ({+ maybeSingle: () =>+ Promise.resolve({ data: null, error: { message: "DB error" } }),}),- });+ }),+ });const response = await addNoteToContact(baseParams);diff --git a/supabase/functions/postmark/addNoteToContact.ts b/supabase/functions/postmark/addNoteToContact.tsindex f0c1441c..380e5663 100644--- a/supabase/functions/postmark/addNoteToContact.ts+++ b/supabase/functions/postmark/addNoteToContact.ts@@ -151,6 +151,7 @@ export const findActiveSaleByEmail = async (salesEmail: string) => {};export const addNoteToContact = async ({+ sales,salesEmail,email,domain,@@ -161,6 +162,7 @@ export const addNoteToContact = async ({companyName,website,}: {+ sales: { id: number };salesEmail: string;email: string;domain: string;@@ -171,24 +173,6 @@ export const addNoteToContact = async ({companyName: string;website: string;}) => {- const { data: sales, error: fetchSalesError } =- await findActiveSaleByEmail(salesEmail);-- if (fetchSalesError) {- return new Response(- `Could not fetch sales from database, email: ${salesEmail}`,- { status: 500 },- );- }- if (!sales) {- // Return a 403 to let Postmark know that it's no use to retry this request- // https://postmarkapp.com/developer/webhooks/inbound-webhook#errors-and-retries- return new Response(- `Unable to find (active) sales in database, email: ${salesEmail}`,- { status: 403 },- );- }-const { contact, error } = await getOrCreateContactFromEmailInfo({email,firstName,diff --git a/supabase/functions/postmark/index.ts b/supabase/functions/postmark/index.tsindex 77925c51..3b39457e 100644--- a/supabase/functions/postmark/index.ts+++ b/supabase/functions/postmark/index.ts@@ -4,7 +4,7 @@// Setup type definitions for built-in Supabase Runtime APIsimport "jsr:@supabase/functions-js/edge-runtime.d.ts";-import { addNoteToContact } from "./addNoteToContact.ts";+import { addNoteToContact, findActiveSaleByEmail } from "./addNoteToContact.ts";import {getForwardedMailContent,stripSubjectForwardingPrefix,@@ -112,8 +112,30 @@ Deno.serve(async (req) => {const contacts = extractMailContactData(ToFull);+ const { data: sales, error: fetchSalesError } =+ await findActiveSaleByEmail(salesEmail);++ if (fetchSalesError) {+ console.error("Could not fetch the sender's sale:", fetchSalesError);+ return new Response(+ `Could not fetch sales from database, email: ${salesEmail}`,+ { status: 500 },+ );+ }++ if (!sales) {+ // Return a 403 to let Postmark know that it's no use to retry this request+ // https://postmarkapp.com/developer/webhooks/inbound-webhook#errors-and-retries+ return new Response(+ `Unable to find (active) sales in database, email: ${salesEmail}`,+ { status: 403 },+ );+ }+const attachments = await extractAndUploadAttachments(Attachments);+ const failedContacts: string[] = [];+for (const {firstName,lastName,@@ -131,6 +153,7 @@ Deno.serve(async (req) => {}const errorResponse = await addNoteToContact({+ sales,salesEmail,email,domain,@@ -143,10 +166,22 @@ Deno.serve(async (req) => {});if (errorResponse) {- return errorResponse;+ console.error(+ `Could not add the note for ${email}: ${await errorResponse.text()}`,+ );+ failedContacts.push(email);}}+ if (failedContacts.length) {+ // Return a 403 to let Postmark know that it's no use to retry this request:+ // the notes already written are not idempotent, a redelivery would duplicate them+ return new Response(+ `Could not add the note for: ${failedContacts.join(", ")}`,+ { status: 403 },+ );+ }+return new Response("OK");});