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: [email protected] <[email protected]>

* 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: [email protected] <[email protected]>

* Implement change to error from #24090

* Address feedback

* Type fix

* test: update SOQL query expectations to include Account.OwnerId

Co-Authored-By: [email protected] <[email protected]>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2025-10-03 14:53:00 -04:00
1 parent 409a0277fb
commit 654a865007
3 files changed
+368 -79

No files matched your search

@@ -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<typeof vi.fn>;
sobject: ReturnType<typeof vi.fn>;
search: ReturnType<typeof vi.fn>;
};
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 = '[email protected]' AND AccountId != null"
"SELECT Id, Email, OwnerId, AccountId, Account.OwnerId, Account.Owner.Email, Account.Website FROM Contact WHERE Email = '[email protected]' 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 = '[email protected]' AND AccountId != null"
"SELECT Id, Email, OwnerId, AccountId, Account.OwnerId, Account.Owner.Email, Account.Website FROM Contact WHERE Email = '[email protected]' 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: "[email protected]",
OwnerId: "owner001",
attributes: { type: "Contact" },
Owner: { Email: "[email protected]" },
},
],
});
const result = await service.getContacts({
emails: "[email protected]",
forRoundRobinSkip: true,
});
expect(result).toEqual([
{
id: "contact001",
email: "[email protected]",
ownerId: "owner001",
ownerEmail: "[email protected]",
recordType: "Contact",
},
]);
expect(searchSpy).toHaveBeenCalledWith(
"FIND {[email protected]} 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: "[email protected]",
OwnerId: "owner001",
attributes: { type: "Lead" },
Owner: { Email: "[email protected]" },
},
],
});
const result = await service.getContacts({
emails: "[email protected]",
forRoundRobinSkip: true,
});
expect(result).toEqual([
{
id: "lead001",
email: "[email protected]",
ownerId: "owner001",
ownerEmail: "[email protected]",
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: "[email protected]",
OwnerId: "owner002",
attributes: { type: "Lead" },
Owner: { Email: "[email protected]" },
},
{
Id: "contact001",
Email: "[email protected]",
OwnerId: "owner001",
attributes: { type: "Contact" },
Owner: { Email: "[email protected]" },
},
],
});
const result = await service.getContacts({
emails: "[email protected]",
forRoundRobinSkip: true,
});
expect(result).toEqual([
{
id: "contact001",
email: "[email protected]",
ownerId: "owner001",
ownerEmail: "[email protected]",
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: "[email protected]",
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: "[email protected]",
OwnerId: "owner001",
attributes: { type: "Contact" },
Owner: { Email: "[email protected]" },
},
],
});
const result = await service.getContacts({
emails: "[email protected]",
});
expect(result).toEqual([
{
id: "contact001",
email: "[email protected]",
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: "[email protected]",
OwnerId: "owner001",
attributes: { type: "Lead" },
Owner: { Email: "[email protected]" },
},
],
});
const result = await service.getContacts({
emails: "[email protected]",
});
expect(result).toEqual([
{
id: "lead001",
email: "[email protected]",
recordType: "Lead",
},
]);
expect(searchSpy).toHaveBeenCalled();
});
});
});
describe("createContacts", () => {
describe("createEventOn lead", () => {
describe("createNewContactUnderAccount enabled", () => {
+114 -75
View File
@@ -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<string, any>;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
fieldsToWriteTo: Record<string, any>;
startTime?: string;
bookingUid?: string | null;
organizerEmail?: string;
calEventResponses?: CalEventResponses | null;
recordId: string;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
}): Promise<Record<string, any>> {
const log = logger.getSubLogger({ prefix: [`[buildRecordUpdatePayload] ${recordId}`] });
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const writeOnRecordBody: Record<string, any> = {};
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<Record<string, any> | 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<string, any>;
}
@@ -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 };
};
@@ -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();
},