From 654a8650071ab9375d013418aa432133485a44c4 Mon Sep 17 00:00:00 2001 From: Joe Au-Yeung <65426560+joeauyeung@users.noreply.github.com> Date: Fri, 3 Oct 2025 14:53:00 -0400 Subject: [PATCH] refactor: Salesforce `getContacts` (#24235) * lint fixes * Create getContactOrLeadFromEmail method * Use getContactOrLeadFromEmail in getContacts * Move normal getContact query * fix: correct return type in getContactOrLeadFromEmail and add search mock - Fix getContactOrLeadFromEmail to return single ContactRecord instead of array - Add conn.search() implementation to salesforceMock for integration tests - Ensure id field is always string with proper fallbacks for AccountId and Id - Fix Owner.Email to use undefined instead of null in mock Co-Authored-By: joe@cal.com * test: add comprehensive tests for getContactOrLeadFromEmail method - Add 6 new unit tests covering all key scenarios - Test contact lookup, lead fallback, and preference logic - Test both roundRobinSkipFallbackToLeadOwner and createEventOnLeadCheckForContact code paths - Add search mock support to mockConnection in beforeEach - All 34 tests passing, type-check clean Co-Authored-By: joe@cal.com * Implement change to error from #24090 * Address feedback * Type fix * test: update SOQL query expectations to include Account.OwnerId Co-Authored-By: joe@cal.com --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- .../salesforce/lib/CrmService.test.ts | 231 +++++++++++++++++- .../app-store/salesforce/lib/CrmService.ts | 189 ++++++++------ .../lib/__tests__/salesforceMock.ts | 27 ++ 3 files changed, 368 insertions(+), 79 deletions(-) diff --git a/packages/app-store/salesforce/lib/CrmService.test.ts b/packages/app-store/salesforce/lib/CrmService.test.ts index 3c499c793c..3d3d9f807c 100644 --- a/packages/app-store/salesforce/lib/CrmService.test.ts +++ b/packages/app-store/salesforce/lib/CrmService.test.ts @@ -57,7 +57,7 @@ const leadQueryResponse = { ], }; -const ownerQueryResponse = { +const _ownerQueryResponse = { records: [ { Id: "owner001", @@ -88,7 +88,11 @@ vi.mock("./graphql/SalesforceGraphQLClient", () => ({ describe("SalesforceCRMService", () => { let service: SalesforceCRMService; - let mockConnection: { query: any; sobject: any }; + let mockConnection: { + query: ReturnType; + sobject: ReturnType; + search: ReturnType; + }; setupAndTeardown(); @@ -96,6 +100,7 @@ describe("SalesforceCRMService", () => { mockConnection = { query: vi.fn(), sobject: vi.fn(), + search: vi.fn(), }; const mockCredential: CredentialPayload = { @@ -334,7 +339,7 @@ describe("SalesforceCRMService", () => { expect(querySpy).toHaveBeenNthCalledWith( 1, - "SELECT Id, Email, OwnerId, AccountId, Account.Owner.Email, Account.Website FROM Contact WHERE Email = 'test@example.com' AND AccountId != null" + "SELECT Id, Email, OwnerId, AccountId, Account.OwnerId, Account.Owner.Email, Account.Website FROM Contact WHERE Email = 'test@example.com' AND AccountId != null" ); }); }); @@ -424,7 +429,7 @@ describe("SalesforceCRMService", () => { expect(querySpy).toHaveBeenNthCalledWith( 1, - "SELECT Id, Email, OwnerId, AccountId, Account.Owner.Email, Account.Website FROM Contact WHERE Email = 'test@example.com' AND AccountId != null" + "SELECT Id, Email, OwnerId, AccountId, Account.OwnerId, Account.Owner.Email, Account.Website FROM Contact WHERE Email = 'test@example.com' AND AccountId != null" ); }); }); @@ -522,6 +527,224 @@ describe("SalesforceCRMService", () => { }); }); + describe("getContactOrLeadFromEmail via getContacts", () => { + describe("with roundRobinSkipFallbackToLeadOwner enabled", () => { + it("should return contact when contact is found", async () => { + mockAppOptions({ + createEventOn: SalesforceRecordEnum.CONTACT, + roundRobinSkipCheckRecordOn: SalesforceRecordEnum.CONTACT, + roundRobinSkipFallbackToLeadOwner: true, + }); + + const searchSpy = vi.spyOn(mockConnection, "search"); + searchSpy.mockResolvedValueOnce({ + searchRecords: [ + { + Id: "contact001", + Email: "test@example.com", + OwnerId: "owner001", + attributes: { type: "Contact" }, + Owner: { Email: "owner@example.com" }, + }, + ], + }); + + const result = await service.getContacts({ + emails: "test@example.com", + forRoundRobinSkip: true, + }); + + expect(result).toEqual([ + { + id: "contact001", + email: "test@example.com", + ownerId: "owner001", + ownerEmail: "owner@example.com", + recordType: "Contact", + }, + ]); + + expect(searchSpy).toHaveBeenCalledWith( + "FIND {test@example.com} IN EMAIL FIELDS RETURNING Lead(Id, Email, OwnerId, Owner.Email), Contact(Id, Email, OwnerId, Owner.Email)" + ); + }); + + it("should return lead when no contact exists but lead is found", async () => { + mockAppOptions({ + createEventOn: SalesforceRecordEnum.CONTACT, + roundRobinSkipCheckRecordOn: SalesforceRecordEnum.CONTACT, + roundRobinSkipFallbackToLeadOwner: true, + }); + + const searchSpy = vi.spyOn(mockConnection, "search"); + searchSpy.mockResolvedValueOnce({ + searchRecords: [ + { + Id: "lead001", + Email: "test@example.com", + OwnerId: "owner001", + attributes: { type: "Lead" }, + Owner: { Email: "owner@example.com" }, + }, + ], + }); + + const result = await service.getContacts({ + emails: "test@example.com", + forRoundRobinSkip: true, + }); + + expect(result).toEqual([ + { + id: "lead001", + email: "test@example.com", + ownerId: "owner001", + ownerEmail: "owner@example.com", + recordType: "Lead", + }, + ]); + + expect(searchSpy).toHaveBeenCalled(); + }); + + it("should prefer contact over lead when both exist", async () => { + mockAppOptions({ + createEventOn: SalesforceRecordEnum.CONTACT, + roundRobinSkipCheckRecordOn: SalesforceRecordEnum.CONTACT, + roundRobinSkipFallbackToLeadOwner: true, + }); + + const searchSpy = vi.spyOn(mockConnection, "search"); + searchSpy.mockResolvedValueOnce({ + searchRecords: [ + { + Id: "lead001", + Email: "test@example.com", + OwnerId: "owner002", + attributes: { type: "Lead" }, + Owner: { Email: "lead-owner@example.com" }, + }, + { + Id: "contact001", + Email: "test@example.com", + OwnerId: "owner001", + attributes: { type: "Contact" }, + Owner: { Email: "contact-owner@example.com" }, + }, + ], + }); + + const result = await service.getContacts({ + emails: "test@example.com", + forRoundRobinSkip: true, + }); + + expect(result).toEqual([ + { + id: "contact001", + email: "test@example.com", + ownerId: "owner001", + ownerEmail: "contact-owner@example.com", + recordType: "Contact", + }, + ]); + + expect(searchSpy).toHaveBeenCalled(); + }); + + it("should return empty array when no records found", async () => { + mockAppOptions({ + createEventOn: SalesforceRecordEnum.CONTACT, + roundRobinSkipCheckRecordOn: SalesforceRecordEnum.CONTACT, + roundRobinSkipFallbackToLeadOwner: true, + }); + + const searchSpy = vi.spyOn(mockConnection, "search"); + searchSpy.mockResolvedValueOnce({ + searchRecords: [], + }); + + const result = await service.getContacts({ + emails: "test@example.com", + forRoundRobinSkip: true, + }); + + expect(result).toEqual([]); + expect(searchSpy).toHaveBeenCalled(); + }); + }); + + describe("with createEventOnLeadCheckForContact enabled", () => { + it("should find and return contact when it exists", async () => { + mockAppOptions({ + createEventOn: SalesforceRecordEnum.LEAD, + createEventOnLeadCheckForContact: true, + }); + + const searchSpy = vi.spyOn(mockConnection, "search"); + searchSpy.mockResolvedValueOnce({ + searchRecords: [ + { + Id: "contact001", + Email: "test@example.com", + OwnerId: "owner001", + attributes: { type: "Contact" }, + Owner: { Email: "owner@example.com" }, + }, + ], + }); + + const result = await service.getContacts({ + emails: "test@example.com", + }); + + expect(result).toEqual([ + { + id: "contact001", + email: "test@example.com", + recordType: "Contact", + }, + ]); + + expect(searchSpy).toHaveBeenCalled(); + }); + + it("should fallback to lead when contact not found", async () => { + mockAppOptions({ + createEventOn: SalesforceRecordEnum.LEAD, + createEventOnLeadCheckForContact: true, + }); + + const searchSpy = vi.spyOn(mockConnection, "search"); + searchSpy.mockResolvedValueOnce({ + searchRecords: [ + { + Id: "lead001", + Email: "test@example.com", + OwnerId: "owner001", + attributes: { type: "Lead" }, + Owner: { Email: "owner@example.com" }, + }, + ], + }); + + const result = await service.getContacts({ + emails: "test@example.com", + }); + + expect(result).toEqual([ + { + id: "lead001", + email: "test@example.com", + recordType: "Lead", + }, + ]); + + expect(searchSpy).toHaveBeenCalled(); + }); + }); + }); + describe("createContacts", () => { describe("createEventOn lead", () => { describe("createNewContactUnderAccount enabled", () => { diff --git a/packages/app-store/salesforce/lib/CrmService.ts b/packages/app-store/salesforce/lib/CrmService.ts index 1c95bcc916..ce241bed40 100644 --- a/packages/app-store/salesforce/lib/CrmService.ts +++ b/packages/app-store/salesforce/lib/CrmService.ts @@ -45,15 +45,6 @@ type ExtendedTokenResponse = TokenResponse & { instance_url: string; }; -type ContactSearchResult = { - attributes: { - type: string; - url: string; - }; - Id: string; - Email: string; -}; - const sfApiErrors = { INVALID_EVENTWHOIDS: "INVALID_FIELD: No such column 'EventWhoIds' on sobject of type Event", }; @@ -62,7 +53,31 @@ type ContactRecord = { Id?: string; Email?: string; OwnerId?: string; - [key: string]: any; + AccountId?: string; + attributes?: { + type?: string; + }; + Account?: { + Owner?: { + Email?: string; + }; + Website?: string; + }; + Owner?: { + Email?: string; + Name?: string; + }; +}; + +type SalesforceDuplicateError = { + name?: string; + duplicateResult?: { + matchResults?: Array<{ + matchRecords?: Array<{ + record: { Id: string }; + }>; + }>; + }; }; type Attendee = { email: string; name: string }; @@ -442,23 +457,6 @@ export default class SalesforceCRMService implements CRM { } } - // Handle Account record type - if (recordToSearch === SalesforceRecordEnum.ACCOUNT) { - // For an account let's assume that the first email is the one we should be querying against - const attendeeEmail = emailArray[0]; - log.info("[recordToSearch=ACCOUNT] Searching contact for email", safeStringify({ attendeeEmail })); - soql = `SELECT Id, Email, OwnerId, AccountId, Account.Owner.Email, Account.Website FROM ${SalesforceRecordEnum.CONTACT} WHERE Email = '${attendeeEmail}' AND AccountId != null`; - } else { - // Handle Contact/Lead record types - soql = `SELECT Id, Email, OwnerId, Owner.Email FROM ${recordToSearch} WHERE Email IN ('${emailArray.join( - "','" - )}')`; - } - - const results = await conn.query(soql); - - log.info("Query results", safeStringify({ recordCount: results.records?.length })); - let records: ContactRecord[] = []; // This combination is for searching for ownership via contacts @@ -467,27 +465,9 @@ export default class SalesforceCRMService implements CRM { appOptions?.roundRobinSkipFallbackToLeadOwner && forRoundRobinSkip ) { - const searchResult = await conn.search( - `FIND {${emailArray[0]}} IN EMAIL FIELDS RETURNING Lead(Id, Email, OwnerId, Owner.Email), Contact(Id, Email, OwnerId, Owner.Email)` - ); - - if (searchResult.searchRecords.length > 0) { - // See if a contact was found first - const contactQuery = searchResult.searchRecords.filter( - (record) => record.attributes?.type === SalesforceRecordEnum.CONTACT - ); - - if (contactQuery.length > 0) { - records = contactQuery as ContactRecord[]; - } else { - // If not fallback to lead - const leadQuery = searchResult.searchRecords.filter( - (record) => record.attributes?.type === SalesforceRecordEnum.LEAD - ); - if (leadQuery.length > 0) { - records = leadQuery as ContactRecord[]; - } - } + const record = await this.getContactOrLeadFromEmail({ email: emailArray[0], conn }); + if (record) { + records.push(record); } } @@ -497,32 +477,42 @@ export default class SalesforceCRMService implements CRM { appOptions.createEventOnLeadCheckForContact && !forRoundRobinSkip ) { - // Get any matching contacts - const contactSearch = await conn.query( - `SELECT Id, Email, OwnerId, Owner.Email FROM ${ - SalesforceRecordEnum.CONTACT - } WHERE Email IN ('${emailArray.join("','")}')` - ); - - if (contactSearch?.records?.length > 0) { - records = contactSearch.records as ContactRecord[]; - this.setFallbackToContact(true); - log.info( - "Found matching contacts, falling back to contact", - safeStringify({ - contactCount: records.length, - }) - ); + const record = await this.getContactOrLeadFromEmail({ + email: emailArray[0], + setFallbackToContact: true, + conn, + }); + if (record) { + records.push(record); } } - if (!records.length && results?.records?.length) { - records = results.records as ContactRecord[]; - } + if (records.length === 0) { + // Handle Account record type + if (recordToSearch === SalesforceRecordEnum.ACCOUNT) { + // For an account let's assume that the first email is the one we should be querying against + const attendeeEmail = emailArray[0]; + log.info("[recordToSearch=ACCOUNT] Searching contact for email", safeStringify({ attendeeEmail })); + soql = `SELECT Id, Email, OwnerId, AccountId, Account.OwnerId, Account.Owner.Email, Account.Website FROM ${SalesforceRecordEnum.CONTACT} WHERE Email = '${attendeeEmail}' AND AccountId != null`; + } else { + // Handle Contact/Lead record types + soql = `SELECT Id, Email, OwnerId, Owner.Email FROM ${recordToSearch} WHERE Email IN ('${emailArray.join( + "','" + )}')`; + } - if (!records.length) { - log.info("No records found"); - return []; + const results = await conn.query(soql); + + log.info("Query results", safeStringify({ recordCount: results.records?.length })); + + if (results.records.length === 0) { + log.info("No records found"); + return []; + } + + if (!records.length && results?.records?.length) { + records = results.records as ContactRecord[]; + } } const includeOwnerData = @@ -539,7 +529,7 @@ export default class SalesforceCRMService implements CRM { : record?.Owner?.Email; return { - id: includeAccountRecordType ? record?.AccountId : record?.Id || "", + id: includeAccountRecordType ? record?.AccountId || "" : record?.Id || "", email: record?.Email || "", recordType: includeAccountRecordType ? SalesforceRecordEnum.ACCOUNT : record?.attributes?.type, ...(includeOwnerData && { @@ -554,6 +544,44 @@ export default class SalesforceCRMService implements CRM { } } + private async getContactOrLeadFromEmail({ + email, + setFallbackToContact = false, + conn, + }: { + email: string; + setFallbackToContact?: boolean; + conn: Connection; + }) { + const searchResult = await conn.search( + `FIND {${email}} IN EMAIL FIELDS RETURNING Lead(Id, Email, OwnerId, Owner.Email), Contact(Id, Email, OwnerId, Owner.Email)` + ); + + if (searchResult.searchRecords.length === 0) { + return null; + } + + // See if a contact was found first + const contactQuery = searchResult.searchRecords.filter( + (record) => record.attributes?.type === SalesforceRecordEnum.CONTACT + ); + + if (contactQuery.length > 0) { + this.setFallbackToContact(setFallbackToContact); + return contactQuery[0] as ContactRecord; + } else { + // If not fallback to lead + const leadQuery = searchResult.searchRecords.filter( + (record) => record.attributes?.type === SalesforceRecordEnum.LEAD + ); + if (leadQuery.length > 0) { + return leadQuery[0] as ContactRecord; + } + } + + return null; + } + async createContacts( contactsToCreate: Attendee[], organizerEmail?: string, @@ -674,9 +702,10 @@ export default class SalesforceCRMService implements CRM { if (result.success) { createdContacts.push({ id: result.id, email: attendee.email }); } - } catch (error: any) { - if (error.name === "DUPLICATES_DETECTED") { - const existingId = this.getExistingIdFromDuplicateError(error); + } catch (error: unknown) { + if (error instanceof Error && error.name === "DUPLICATES_DETECTED") { + // we know it's a DuplicateError now (DUPLICATES_DETECTED) + const existingId = this.getExistingIdFromDuplicateError(error as SalesforceDuplicateError); if (existingId) { log.info("Using existing record:", existingId); createdContacts.push({ id: existingId, email: attendee.email }); @@ -770,7 +799,7 @@ export default class SalesforceCRMService implements CRM { } } - private getExistingIdFromDuplicateError(error: any): string | null { + private getExistingIdFromDuplicateError(error: SalesforceDuplicateError): string | null { if (error.duplicateResult && error.duplicateResult.matchResults) { for (const matchResult of error.duplicateResult.matchResults) { if (matchResult.matchRecords && matchResult.matchRecords.length > 0) { @@ -1059,15 +1088,19 @@ export default class SalesforceCRMService implements CRM { recordId, }: { existingFields: Field[]; + // eslint-disable-next-line @typescript-eslint/no-explicit-any personRecord: Record; + // eslint-disable-next-line @typescript-eslint/no-explicit-any fieldsToWriteTo: Record; startTime?: string; bookingUid?: string | null; organizerEmail?: string; calEventResponses?: CalEventResponses | null; recordId: string; + // eslint-disable-next-line @typescript-eslint/no-explicit-any }): Promise> { const log = logger.getSubLogger({ prefix: [`[buildRecordUpdatePayload] ${recordId}`] }); + // eslint-disable-next-line @typescript-eslint/no-explicit-any const writeOnRecordBody: Record = {}; let fieldTypeHandled = false; @@ -1192,6 +1225,8 @@ export default class SalesforceCRMService implements CRM { : []; const confirmedCustomFieldInputs: { + // This is unique to each instance so we don't know the type + // eslint-disable-next-line @typescript-eslint/no-explicit-any [key: string]: any; } = {}; @@ -1439,6 +1474,7 @@ export default class SalesforceCRMService implements CRM { contactId: string, existingFields: Field[], personRecordType: SalesforceRecordEnum + // eslint-disable-next-line @typescript-eslint/no-explicit-any ): Promise | null> { const conn = await this.conn; const existingFieldNames = existingFields.map((field) => field.name); @@ -1452,6 +1488,7 @@ export default class SalesforceCRMService implements CRM { return null; } + // eslint-disable-next-line @typescript-eslint/no-explicit-any return query.records[0] as Record; } @@ -1512,6 +1549,8 @@ export default class SalesforceCRMService implements CRM { const accountQuery = (await conn.query( `SELECT ${lookupField.name} FROM ${SalesforceRecordEnum.ACCOUNT} WHERE Id = '${accountId}'` )) as { + // We do not know what fields are included in the account since it's unqiue to each instance + // eslint-disable-next-line @typescript-eslint/no-explicit-any records: { [key: string]: any }; }; diff --git a/packages/app-store/salesforce/lib/__tests__/salesforceMock.ts b/packages/app-store/salesforce/lib/__tests__/salesforceMock.ts index 766c861b02..a75548554b 100644 --- a/packages/app-store/salesforce/lib/__tests__/salesforceMock.ts +++ b/packages/app-store/salesforce/lib/__tests__/salesforceMock.ts @@ -269,6 +269,32 @@ export const createSalesforceMock = () => { // @ts-ignore const mockConnection = { query: vi.fn().mockImplementation(handleQuery), + search: vi.fn().mockImplementation((searchQuery: string) => { + const emailMatch = searchQuery.match(/FIND \{([^}]+)\}/i); + if (!emailMatch) return { searchRecords: [] }; + + const email = emailMatch[1]; + const searchRecords = []; + + const matchingContacts = records.contacts.filter((c) => c.Email === email); + searchRecords.push(...matchingContacts); + + const matchingLeads = records.leads.filter((l) => l.Email === email); + searchRecords.push(...matchingLeads); + + if (searchQuery.includes("Owner.Email")) { + searchRecords.forEach((record) => { + if (record.OwnerId) { + const owner = records.users.find((u) => u.Id === record.OwnerId); + record.Owner = { + Email: owner ? owner.Email : undefined, + }; + } + }); + } + + return { searchRecords }; + }), sobject: vi.fn().mockReturnValue({ create: vi.fn().mockImplementation(async (data) => { // eslint-disable-next-line @typescript-eslint/ban-ts-comment @@ -362,6 +388,7 @@ export const createSalesforceMock = () => { records.users = []; records.events = []; mockConnection.query.mockClear(); + mockConnection.search.mockClear(); mockConnection.sobject.mockClear(); mockConnection.describe.mockClear(); },