feat(salesforce): add field rules for round robin routing (#27402)

* feat(salesforce): add field rules for round robin skip

- Add rrSkipFieldRules schema to appDataSchema in zod.ts
- Implement applyFieldRules method in CrmService.ts for post-query filtering
- Integrate field rules into getContacts method when forRoundRobinSkip=true
- Add UI component for configuring field rules in EventTypeAppCardInterface
- Add translations for new UI strings
- Add comprehensive tests for field rules functionality

Field rules allow users to specify conditions based on Salesforce record fields
with 'ignore' or 'must_include' actions. Rules are evaluated with AND logic
and gracefully handle missing fields by skipping those rules.

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

* fix: add children prop to Section.SubSectionHeader for field rules

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

* feat(salesforce): add edit button for field rules

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

* feat(salesforce): apply field rules to GraphQL results

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

* feat(salesforce): add Redis caching for field validation

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

* fix(salesforce): remove Redis caching to fix ERR_INVALID_THIS error

- Removed Redis caching for field validation that was causing ERR_INVALID_THIS errors
- Simplified field rules filtering to try query directly and skip filtering if it fails
- Restored ensureFieldsExistOnObject method for other uses (write to record)
- Field rules now gracefully handle invalid fields by skipping filtering

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

* chore: reformat getAttributes.ts

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* feat(salesforce): dynamically build GraphQL query for field rules with multi-edge iteration

- Add buildDynamicAccountQuery to inject field rule fields into GraphQL query
- Add passesFieldRules to evaluate ignore/must_include rules against UIAPI nodes
- Validate field rules via getObjectFieldNames (in-memory + Redis cache) before branching
- Remove applyFieldRulesToGraphQLRecords (used jsforce conn in GraphQL path)
- Iterate all edges in Tiers 1 and 2 instead of only the first result
- Rank Tier 3 accounts by contact count and fallback to next on field rule failure

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* feat(salesforce): add field rule routing trace steps

Add trace calls alongside field rule info logs for routing visibility:
- fieldRulesValidated: records validation result in CrmService
- fieldRuleFilteredRecord: records when account is filtered at each tier
- fieldRuleEvaluated: records individual rule evaluation details
- allRecordsFilteredByFieldRules: records when SOQL records are all filtered

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* fix(salesforce): remove duplicate field validation and fix disabled Select options

applyFieldRules now receives pre-validated rules from the early
validation block instead of re-validating internally. Also adds
the missing options prop to the disabled Select in the field rules UI.

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* feat(salesforce): include failed rule details in field rule trace steps

Rename passesFieldRules to getFailingFieldRule so the caller receives
the specific rule that caused filtering. The fieldRuleFilteredRecord
trace step now includes failedRule with field, value, and action.

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* test(salesforce): add GraphQL path tests for field rules

Cover field rule filtering across all three GraphQL resolution tiers
(contact, account, related contacts) with ignore and must_include
actions, multi-edge fallback, case-insensitivity, and dynamic query
selection.

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* Abstract new field rules settings

* Reduce extra SOQL call

* fix(salesforce): fix type errors in CrmService and GraphQL client

- Add missing import for getRedisService from @calcom/features/di/containers/Redis
- Fix ensureFieldsExistOnObject to properly return Field[] instead of incomplete function
- Use Array.from() instead of spread operator for Set and Map iterators to fix downlevelIteration errors

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

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 4.5 <[email protected]>
This commit is contained in:
authored and GitHub committed 2026-02-01 23:03:19 -05:00
1 parent 3f053b4e22
commit f91511b927
11 files changed
+1680 -151

No files matched your search

@@ -3734,6 +3734,11 @@
"completed_onboarding": "Completed onboarding",
"salesforce_on_cancel_write_to_event": "On cancelled booking, write to event record instead of deleting event",
"salesforce_on_every_cancellation": "On every cancellation",
"salesforce_rr_skip_field_rules": "Field rules for round robin skip",
"salesforce_rr_skip_field_rule_ignore": "Ignore",
"salesforce_rr_skip_field_rule_must_include": "Must include",
"salesforce_field_name_placeholder": "Field name (e.g., Industry)",
"add_new_rule": "Add new rule",
"report_issue": "Report issue",
"report_issue_description": "You can submit a ticket on GitHub or upgrade your plan to receive real-time support with developer conferences",
"open_issue": "Open Issue",
@@ -17,7 +17,8 @@ import { Section } from "@calcom/ui/components/section";
import { showToast } from "@calcom/ui/components/toast";
import { SalesforceRecordEnum } from "../lib/enums";
import type { appDataSchema } from "../zod";
import type { appDataSchema, RRSkipFieldRule } from "../zod";
import FieldRulesSettings from "./components/FieldRulesSettings";
import WriteToObjectSettings, { BookingActionEnum } from "./components/WriteToObjectSettings";
const EventTypeAppCard: EventTypeAppCardComponent = function EventTypeAppCard({ app, eventType, onAppInstallSuccess }) {
@@ -46,6 +47,7 @@ const EventTypeAppCard: EventTypeAppCardComponent = function EventTypeAppCard({
const roundRobinSkipFallbackToLeadOwner = getAppData("roundRobinSkipFallbackToLeadOwner") ?? false;
const onCancelWriteToEventRecord = getAppData("onCancelWriteToEventRecord") ?? false;
const onCancelWriteToEventRecordFields = getAppData("onCancelWriteToEventRecordFields") ?? {};
const rrSkipFieldRules = (getAppData("rrSkipFieldRules") ?? []) as RRSkipFieldRule[];
const { t } = useLocale();
@@ -435,6 +437,10 @@ const EventTypeAppCard: EventTypeAppCardComponent = function EventTypeAppCard({
</Section.SubSectionHeader>
<Alert severity="info" title={t("skip_rr_description")} />
</Section.SubSection>
<FieldRulesSettings
fieldRules={rrSkipFieldRules}
updateFieldRules={(rules) => setAppData("rrSkipFieldRules", rules)}
/>
</>
) : null}
</>
@@ -0,0 +1,238 @@
import { useState } from "react";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Button } from "@calcom/ui/components/button";
import { InputField } from "@calcom/ui/components/form";
import { Select } from "@calcom/ui/components/form";
import { Section } from "@calcom/ui/components/section";
import type { RRSkipFieldRule } from "../../zod";
import { RRSkipFieldRuleActionEnum } from "../../zod";
type FieldRuleAction = (typeof RRSkipFieldRuleActionEnum)[keyof typeof RRSkipFieldRuleActionEnum];
const FieldRulesSettings = ({
fieldRules,
updateFieldRules,
}: {
fieldRules: RRSkipFieldRule[];
updateFieldRules: (rules: RRSkipFieldRule[]) => void;
}) => {
const { t } = useLocale();
const actionOptions = [
{ label: t("salesforce_rr_skip_field_rule_ignore"), value: RRSkipFieldRuleActionEnum.IGNORE },
{ label: t("salesforce_rr_skip_field_rule_must_include"), value: RRSkipFieldRuleActionEnum.MUST_INCLUDE },
];
const [newRule, setNewRule] = useState<{ field: string; value: string; action: FieldRuleAction }>({
field: "",
value: "",
action: RRSkipFieldRuleActionEnum.IGNORE,
});
const [editingIndex, setEditingIndex] = useState<number | null>(null);
const [editingRule, setEditingRule] = useState<{
field: string;
value: string;
action: FieldRuleAction;
} | null>(null);
const startEditing = (index: number) => {
const rule = fieldRules[index];
setEditingIndex(index);
setEditingRule({ field: rule.field, value: rule.value, action: rule.action });
};
const cancelEditing = () => {
setEditingIndex(null);
setEditingRule(null);
};
const saveEditing = () => {
if (editingIndex === null || !editingRule) return;
if (!editingRule.field.trim() || !editingRule.value.trim()) return;
const newRules = [...fieldRules];
newRules[editingIndex] = {
field: editingRule.field.trim(),
value: editingRule.value.trim(),
action: editingRule.action,
};
updateFieldRules(newRules);
cancelEditing();
};
return (
<Section.SubSection>
<Section.SubSectionHeader
icon="filter"
title={t("salesforce_rr_skip_field_rules")}
labelFor="rr-skip-field-rules">
<></>
</Section.SubSectionHeader>
<Section.SubSectionContent>
<div className="text-subtle flex gap-3 px-3 py-[6px] text-sm font-medium">
<div className="flex-1">{t("field_name")}</div>
<div className="flex-1">{t("value")}</div>
<div className="w-32">{t("action")}</div>
<div className="w-20" />
</div>
<Section.SubSectionNested>
{fieldRules.map((rule, index) => {
const isEditing = editingIndex === index;
return (
<div className="flex items-center gap-2" key={`${rule.field}-${index}`}>
<div className="flex-1">
{isEditing ? (
<InputField
value={editingRule?.field || ""}
onChange={(e) =>
setEditingRule((prev) => (prev ? { ...prev, field: e.target.value } : null))
}
size="sm"
className="w-full"
/>
) : (
<InputField value={rule.field} readOnly size="sm" className="w-full" />
)}
</div>
<div className="flex-1">
{isEditing ? (
<InputField
value={editingRule?.value || ""}
onChange={(e) =>
setEditingRule((prev) => (prev ? { ...prev, value: e.target.value } : null))
}
size="sm"
className="w-full"
/>
) : (
<InputField value={rule.value} readOnly size="sm" className="w-full" />
)}
</div>
<div className="w-32">
{isEditing ? (
<Select
size="sm"
className="w-full"
options={actionOptions}
value={actionOptions.find((opt) => opt.value === editingRule?.action)}
onChange={(e) => {
if (e) {
setEditingRule((prev) => (prev ? { ...prev, action: e.value } : null));
}
}}
/>
) : (
<Select
size="sm"
className="w-full"
options={actionOptions}
value={actionOptions.find((opt) => opt.value === rule.action)}
isDisabled={true}
/>
)}
</div>
<div className="flex w-20 justify-center gap-1">
{isEditing ? (
<>
<Button
size="sm"
StartIcon="check"
variant="icon"
color="primary"
onClick={() => saveEditing()}
/>
<Button
size="sm"
StartIcon="x"
variant="icon"
color="secondary"
onClick={() => cancelEditing()}
/>
</>
) : (
<>
<Button
size="sm"
StartIcon="pencil"
variant="icon"
color="minimal"
onClick={() => startEditing(index)}
/>
<Button
StartIcon="x"
variant="icon"
size="sm"
color="minimal"
onClick={() => {
updateFieldRules(fieldRules.filter((_, i) => i !== index));
}}
/>
</>
)}
</div>
</div>
);
})}
<div className="mt-2 flex gap-2">
<div className="flex-1">
<InputField
size="sm"
className="w-full"
placeholder={t("salesforce_field_name_placeholder")}
value={newRule.field}
onChange={(e) => setNewRule({ ...newRule, field: e.target.value })}
/>
</div>
<div className="flex-1">
<InputField
size="sm"
className="w-full"
placeholder={t("value")}
value={newRule.value}
onChange={(e) => setNewRule({ ...newRule, value: e.target.value })}
/>
</div>
<div className="w-32">
<Select
size="sm"
className="w-full"
options={actionOptions}
value={actionOptions.find((opt) => opt.value === newRule.action)}
onChange={(e) => {
if (e) {
setNewRule({ ...newRule, action: e.value });
}
}}
/>
</div>
<div className="w-20" />
</div>
</Section.SubSectionNested>
<Button
className="text-subtle mt-2 w-fit"
StartIcon="plus"
color="minimal"
size="sm"
disabled={!(newRule.field && newRule.value)}
onClick={() => {
updateFieldRules([
...fieldRules,
{
field: newRule.field.trim(),
value: newRule.value.trim(),
action: newRule.action,
},
]);
setNewRule({ field: "", value: "", action: RRSkipFieldRuleActionEnum.IGNORE });
}}>
{t("add_new_rule")}
</Button>
</Section.SubSectionContent>
</Section.SubSection>
);
};
export default FieldRulesSettings;
@@ -806,4 +806,297 @@ describe("SalesforceCRMService", () => {
);
});
});
describe("getContacts with rrSkipFieldRules", () => {
const mockDescribeResponse = {
fields: [
{ name: "Industry", type: "string" },
{ name: "Type", type: "string" },
{ name: "Status", type: "string" },
],
};
it("should filter out records matching ignore rule", async () => {
mockAppOptions({
roundRobinSkipCheckRecordOn: SalesforceRecordEnum.CONTACT,
createEventOn: SalesforceRecordEnum.CONTACT,
rrSkipFieldRules: [{ field: "Industry", value: "Technology", action: "ignore" }],
});
const querySpy = vi.spyOn(mockConnection, "query");
// Field rule fields are now included in the main SOQL query
querySpy.mockResolvedValueOnce({
records: [
{
Id: "001",
Email: "[email protected]",
OwnerId: "owner001",
attributes: { type: "Contact" },
Owner: { Email: "[email protected]" },
Industry: "Technology",
},
],
});
// Mock describe for field validation
mockConnection.describe = vi.fn().mockResolvedValue(mockDescribeResponse);
const result = await service.getContacts({
emails: "[email protected]",
forRoundRobinSkip: true,
});
expect(result).toEqual([]);
expect(querySpy).toHaveBeenCalledTimes(1);
});
it("should keep records not matching ignore rule", async () => {
mockAppOptions({
roundRobinSkipCheckRecordOn: SalesforceRecordEnum.CONTACT,
createEventOn: SalesforceRecordEnum.CONTACT,
rrSkipFieldRules: [{ field: "Industry", value: "Technology", action: "ignore" }],
});
const querySpy = vi.spyOn(mockConnection, "query");
querySpy.mockResolvedValueOnce({
records: [
{
Id: "001",
Email: "[email protected]",
OwnerId: "owner001",
attributes: { type: "Contact" },
Owner: { Email: "[email protected]" },
Industry: "Healthcare",
},
],
});
mockConnection.describe = vi.fn().mockResolvedValue(mockDescribeResponse);
const result = await service.getContacts({
emails: "[email protected]",
forRoundRobinSkip: true,
});
expect(result).toEqual([
{
id: "001",
email: "[email protected]",
ownerId: "owner001",
ownerEmail: "[email protected]",
recordType: "Contact",
},
]);
expect(querySpy).toHaveBeenCalledTimes(1);
});
it("should filter out records not matching must_include rule", async () => {
mockAppOptions({
roundRobinSkipCheckRecordOn: SalesforceRecordEnum.CONTACT,
createEventOn: SalesforceRecordEnum.CONTACT,
rrSkipFieldRules: [{ field: "Industry", value: "Technology", action: "must_include" }],
});
const querySpy = vi.spyOn(mockConnection, "query");
querySpy.mockResolvedValueOnce({
records: [
{
Id: "001",
Email: "[email protected]",
OwnerId: "owner001",
attributes: { type: "Contact" },
Owner: { Email: "[email protected]" },
Industry: "Healthcare",
},
],
});
mockConnection.describe = vi.fn().mockResolvedValue(mockDescribeResponse);
const result = await service.getContacts({
emails: "[email protected]",
forRoundRobinSkip: true,
});
expect(result).toEqual([]);
expect(querySpy).toHaveBeenCalledTimes(1);
});
it("should keep records matching must_include rule", async () => {
mockAppOptions({
roundRobinSkipCheckRecordOn: SalesforceRecordEnum.CONTACT,
createEventOn: SalesforceRecordEnum.CONTACT,
rrSkipFieldRules: [{ field: "Industry", value: "Technology", action: "must_include" }],
});
const querySpy = vi.spyOn(mockConnection, "query");
querySpy.mockResolvedValueOnce({
records: [
{
Id: "001",
Email: "[email protected]",
OwnerId: "owner001",
attributes: { type: "Contact" },
Owner: { Email: "[email protected]" },
Industry: "Technology",
},
],
});
mockConnection.describe = vi.fn().mockResolvedValue(mockDescribeResponse);
const result = await service.getContacts({
emails: "[email protected]",
forRoundRobinSkip: true,
});
expect(result).toEqual([
{
id: "001",
email: "[email protected]",
ownerId: "owner001",
ownerEmail: "[email protected]",
recordType: "Contact",
},
]);
expect(querySpy).toHaveBeenCalledTimes(1);
});
it("should handle multiple rules with AND logic", async () => {
mockAppOptions({
roundRobinSkipCheckRecordOn: SalesforceRecordEnum.CONTACT,
createEventOn: SalesforceRecordEnum.CONTACT,
rrSkipFieldRules: [
{ field: "Industry", value: "Technology", action: "must_include" },
{ field: "Type", value: "Inactive", action: "ignore" },
],
});
const querySpy = vi.spyOn(mockConnection, "query");
querySpy.mockResolvedValueOnce({
records: [
{
Id: "001",
Email: "[email protected]",
OwnerId: "owner001",
attributes: { type: "Contact" },
Owner: { Email: "[email protected]" },
Industry: "Technology",
Type: "Active",
},
],
});
mockConnection.describe = vi.fn().mockResolvedValue(mockDescribeResponse);
const result = await service.getContacts({
emails: "[email protected]",
forRoundRobinSkip: true,
});
expect(result).toEqual([
{
id: "001",
email: "[email protected]",
ownerId: "owner001",
ownerEmail: "[email protected]",
recordType: "Contact",
},
]);
expect(querySpy).toHaveBeenCalledTimes(1);
});
it("should skip rules for fields that do not exist on the record type", async () => {
mockAppOptions({
roundRobinSkipCheckRecordOn: SalesforceRecordEnum.CONTACT,
createEventOn: SalesforceRecordEnum.CONTACT,
rrSkipFieldRules: [{ field: "NonExistentField", value: "SomeValue", action: "must_include" }],
});
const querySpy = vi.spyOn(mockConnection, "query");
querySpy.mockResolvedValueOnce(contactQueryResponse);
mockConnection.describe = vi.fn().mockResolvedValue(mockDescribeResponse);
const result = await service.getContacts({
emails: "[email protected]",
forRoundRobinSkip: true,
});
expect(result).toEqual([
{
id: "001",
email: "[email protected]",
ownerId: "owner001",
ownerEmail: "[email protected]",
recordType: "Contact",
},
]);
});
it("should be case-insensitive when matching field values", async () => {
mockAppOptions({
roundRobinSkipCheckRecordOn: SalesforceRecordEnum.CONTACT,
createEventOn: SalesforceRecordEnum.CONTACT,
rrSkipFieldRules: [{ field: "Industry", value: "TECHNOLOGY", action: "must_include" }],
});
const querySpy = vi.spyOn(mockConnection, "query");
querySpy.mockResolvedValueOnce({
records: [
{
Id: "001",
Email: "[email protected]",
OwnerId: "owner001",
attributes: { type: "Contact" },
Owner: { Email: "[email protected]" },
Industry: "technology",
},
],
});
mockConnection.describe = vi.fn().mockResolvedValue(mockDescribeResponse);
const result = await service.getContacts({
emails: "[email protected]",
forRoundRobinSkip: true,
});
expect(result).toEqual([
{
id: "001",
email: "[email protected]",
ownerId: "owner001",
ownerEmail: "[email protected]",
recordType: "Contact",
},
]);
expect(querySpy).toHaveBeenCalledTimes(1);
});
it("should not apply field rules when forRoundRobinSkip is false", async () => {
mockAppOptions({
createEventOn: SalesforceRecordEnum.CONTACT,
rrSkipFieldRules: [{ field: "Industry", value: "Technology", action: "ignore" }],
});
const querySpy = vi.spyOn(mockConnection, "query");
querySpy.mockResolvedValueOnce(contactQueryResponse);
const result = await service.getContacts({
emails: "[email protected]",
forRoundRobinSkip: false,
});
expect(result).toEqual([
{
id: "001",
email: "[email protected]",
recordType: "Contact",
},
]);
expect(querySpy).toHaveBeenCalledTimes(1);
});
});
});
+177 -5
View File
@@ -18,13 +18,15 @@ import type { CredentialPayload } from "@calcom/types/Credential";
import type { CRM, Contact, CrmEvent } from "@calcom/types/CrmService";
import { CredentialRepository } from "@calcom/features/credentials/repositories/CredentialRepository";
import { getRedisService } from "@calcom/features/di/containers/Redis";
import type { ParseRefreshTokenResponse } from "../../_utils/oauth/parseRefreshTokenResponse";
import { SalesforceRoutingTraceService } from "./tracing";
import parseRefreshTokenResponse from "../../_utils/oauth/parseRefreshTokenResponse";
import { findFieldValueByIdentifier } from "../../routing-forms/lib/findFieldValueByIdentifier";
import { default as appMeta } from "../config.json";
import type { writeToRecordDataSchema, appDataSchema, writeToBookingEntry } from "../zod";
import type { writeToRecordDataSchema, appDataSchema, writeToBookingEntry, RRSkipFieldRule } from "../zod";
import { RRSkipFieldRuleActionEnum } from "../zod";
import {
SalesforceRecordEnum,
SalesforceFieldType,
@@ -129,6 +131,7 @@ class SalesforceCRMService implements CRM {
private instanceUrl: string;
private hasAttemptedRefresh = false;
private credentialId: number;
private describeCache = new Map<string, Set<string>>();
constructor(credential: CredentialPayload, appOptions: z.infer<typeof appDataSchema>, testMode = false) {
this.integrationName = "salesforce_other_calendar";
@@ -566,13 +569,52 @@ class SalesforceCRMService implements CRM {
})
);
// Validate field rules early, before branching to GraphQL or SOQL paths
let validatedFieldRules: RRSkipFieldRule[] | undefined;
if (forRoundRobinSkip && appOptions?.rrSkipFieldRules?.length) {
log.info(
"Validating field rules",
safeStringify({
rules: appOptions.rrSkipFieldRules,
recordToSearch,
})
);
const existingFieldNames = await this.getObjectFieldNames(recordToSearch);
log.info(`Found ${existingFieldNames.size} fields on ${recordToSearch}`);
if (existingFieldNames.size > 0) {
const filtered = appOptions.rrSkipFieldRules.filter((r) => existingFieldNames.has(r.field));
if (filtered.length > 0) {
validatedFieldRules = filtered;
log.info("Validated field rules", safeStringify({ validatedFieldRules }));
SalesforceRoutingTraceService.fieldRulesValidated({
recordType: recordToSearch,
configuredCount: appOptions.rrSkipFieldRules.length,
validCount: filtered.length,
validFields: filtered.map((r) => r.field),
});
} else {
log.warn(
"No field rules matched existing fields",
safeStringify({
configuredFields: appOptions.rrSkipFieldRules.map((r) => r.field),
})
);
SalesforceRoutingTraceService.fieldRulesValidated({
recordType: recordToSearch,
configuredCount: appOptions.rrSkipFieldRules.length,
validCount: 0,
});
}
}
}
if (recordToSearch === SalesforceRecordEnum.ACCOUNT && forRoundRobinSkip) {
try {
const client = new SalesforceGraphQLClient({
accessToken: this.accessToken,
instanceUrl: this.instanceUrl,
});
return await client.GetAccountRecordsForRRSkip(emailArray[0]);
return await client.GetAccountRecordsForRRSkip(emailArray[0], validatedFieldRules);
} catch (error) {
log.error("Error getting account records for round robin skip", safeStringify({ error }));
return [];
@@ -610,15 +652,19 @@ class SalesforceCRMService implements CRM {
}
if (records.length === 0) {
// Build extra SELECT fields from validated field rules so we don't need a second query
const extraFields =
validatedFieldRules?.length ? ", " + validatedFieldRules.map((r) => r.field).join(", ") : "";
// 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`;
soql = `SELECT Id, Email, OwnerId, AccountId, Account.OwnerId, Account.Owner.Email, Account.Website${extraFields} 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(
soql = `SELECT Id, Email, OwnerId, Owner.Email${extraFields} FROM ${recordToSearch} WHERE Email IN ('${emailArray.join(
"','"
)}')`;
}
@@ -637,6 +683,18 @@ class SalesforceCRMService implements CRM {
}
}
// Apply field rules if configured and this is for round robin skip
if (forRoundRobinSkip && validatedFieldRules?.length && records.length > 0) {
records = this.applyFieldRules(records, validatedFieldRules);
if (records.length === 0) {
log.info("All records filtered out by field rules");
SalesforceRoutingTraceService.allRecordsFilteredByFieldRules({
recordType: recordToSearch,
});
return [];
}
}
const isFreeEmailDomain = await this.shouldSkipAttendeeIfFreeEmailDomain(emailArray[0]);
const includeOwnerData = (includeOwner || forRoundRobinSkip) && !isFreeEmailDomain;
@@ -1051,7 +1109,62 @@ class SalesforceCRMService implements CRM {
};
}
private async ensureFieldsExistOnObject(fieldsToTest: string[], sobject: string) {
/**
* Gets all field names for a Salesforce object.
* Uses a two-level cache: in-memory (per request) and Redis (cross-request, 1hr TTL).
*/
private async getObjectFieldNames(sobject: string): Promise<Set<string>> {
const log = logger.getSubLogger({ prefix: [`[getObjectFieldNames]`] });
// Level 1: in-memory cache (same request)
const memoryCached = this.describeCache.get(sobject);
if (memoryCached) {
return memoryCached;
}
// Level 2: Redis cache (cross-request)
const cacheKey = `salesforce:describe:${this.instanceUrl}:${sobject}`;
const CACHE_TTL_MS = 60 * 60 * 1000; // 1 hour
try {
const redis = getRedisService();
const redisCached = await redis.get<string[]>(cacheKey);
if (redisCached) {
log.info(`Redis cache hit for ${sobject} field names`);
const fieldNames = new Set(redisCached);
this.describeCache.set(sobject, fieldNames);
return fieldNames;
}
} catch (cacheError) {
log.warn(`Redis cache unavailable, falling back to API`, safeStringify({ error: cacheError }));
}
// Level 3: Salesforce API
const conn = await this.conn;
try {
const salesforceEntity = await conn.describe(sobject);
const fieldNamesList = salesforceEntity.fields.map((f) => f.name);
const fieldNames = new Set(fieldNamesList);
this.describeCache.set(sobject, fieldNames);
// Persist to Redis for other requests
try {
const redis = getRedisService();
await redis.set(cacheKey, fieldNamesList, { ttl: CACHE_TTL_MS });
log.info(`Cached ${sobject} field names in Redis (${fieldNamesList.length} fields)`);
} catch (cacheError) {
log.warn(`Failed to cache field names in Redis`, safeStringify({ error: cacheError }));
}
return fieldNames;
} catch (e) {
log.error(`Error fetching field names for ${sobject}`, safeStringify({ error: e }));
return new Set();
}
}
private async ensureFieldsExistOnObject(fieldsToTest: string[], sobject: string): Promise<Field[]> {
const log = logger.getSubLogger({ prefix: [`[ensureFieldsExistOnObject]`] });
const conn = await this.conn;
@@ -1077,6 +1190,65 @@ class SalesforceCRMService implements CRM {
}
}
/**
* Filters records in-memory based on pre-validated field rules.
* Field rule values are expected to already be present on the records
* (included in the original SOQL SELECT).
* Records without the field value (e.g. from SOSL path) are kept.
*
* @param records - The records to filter (must already contain field rule field values)
* @param validRules - Array of pre-validated rules (fields already confirmed to exist on the object)
* @returns Filtered records that pass all rules (AND logic)
*/
private applyFieldRules(records: ContactRecord[], validRules: RRSkipFieldRule[]): ContactRecord[] {
const log = logger.getSubLogger({ prefix: [`[applyFieldRules]`] });
if (!validRules.length || !records.length) {
return records;
}
log.info("Applying field rules", {
ruleCount: validRules.length,
recordCount: records.length,
});
return records.filter((record) => {
for (const rule of validRules) {
// Access dynamic field via bracket notation — value is on the record from SOQL
const rawRecord = record as unknown as Record<string, unknown>;
const actualValue = String(rawRecord[rule.field] ?? "").toLowerCase();
const ruleValue = rule.value.toLowerCase();
const matches = actualValue === ruleValue;
// If field value is missing (empty string from nullish coalescing), skip the rule.
// This handles records from SOSL path that don't have field rule fields.
if (rawRecord[rule.field] === undefined || rawRecord[rule.field] === null) {
log.info(`Record ${record.Id} missing field "${rule.field}", skipping rule`);
continue;
}
if (rule.action === RRSkipFieldRuleActionEnum.IGNORE && matches) {
log.info(`Record ${record.Id} filtered out by ignore rule`, {
field: rule.field,
value: rule.value,
});
return false;
}
if (rule.action === RRSkipFieldRuleActionEnum.MUST_INCLUDE && !matches) {
log.info(`Record ${record.Id} filtered out by must_include rule`, {
field: rule.field,
expectedValue: rule.value,
actualValue,
});
return false;
}
}
return true;
});
}
private async checkRecordOwnerNameFromRecordId(id: string, newOwnerId: string) {
const conn = await this.conn;
const appOptions = this.getAppOptions();
@@ -10,6 +10,8 @@ import { SalesforceRoutingTraceService } from "../tracing";
import getAllPossibleWebsiteValuesFromEmailDomain from "../utils/getAllPossibleWebsiteValuesFromEmailDomain";
import getDominantAccountId from "../utils/getDominantAccountId";
import { GetAccountRecordsForRRSkip } from "./documents/queries";
import type { RRSkipFieldRule } from "../../zod";
import { RRSkipFieldRuleActionEnum } from "../../zod";
export class SalesforceGraphQLClient {
private log: typeof logger;
@@ -17,7 +19,13 @@ export class SalesforceGraphQLClient {
private accessToken: string;
private client: Client;
constructor({ accessToken, instanceUrl }: { accessToken: string; instanceUrl: string }) {
constructor({
accessToken,
instanceUrl,
}: {
accessToken: string;
instanceUrl: string;
}) {
this.accessToken = accessToken;
const exchanges = [cacheExchange, fetchExchange];
@@ -56,10 +64,16 @@ export class SalesforceGraphQLClient {
* 2. If no contact is found, then find an account that is an exact match of the email domain
* 3. If no account is found, then find contacts that match the email domain and find the account that the majority of contacts are connect to
*/
async GetAccountRecordsForRRSkip(email: string): Promise<Contact[]> {
const log = logger.getSubLogger({ prefix: [`[getAccountRecordsForRRSkip]:${email}`] });
async GetAccountRecordsForRRSkip(
email: string,
fieldRules?: RRSkipFieldRule[]
): Promise<Contact[]> {
const log = logger.getSubLogger({
prefix: [`[getAccountRecordsForRRSkip]:${email}`],
});
const emailDomain = email.split("@")[1];
const websites = this.getAllPossibleAccountWebsiteFromEmailDomain(emailDomain);
const websites =
this.getAllPossibleAccountWebsiteFromEmailDomain(emailDomain);
// Trace query initiation
SalesforceRoutingTraceService.graphqlQueryInitiated({
@@ -69,7 +83,25 @@ export class SalesforceGraphQLClient {
log.info(`Query against email and email domain of ${emailDomain}`);
const query = await this.client.query(GetAccountRecordsForRRSkip, {
const hasFieldRules = fieldRules && fieldRules.length > 0;
const fieldRuleFields = hasFieldRules
? Array.from(new Set(fieldRules.map((r) => r.field)))
: [];
log.info(`fieldRuleFields`, fieldRuleFields);
if (hasFieldRules) {
log.info(
"Using dynamic query with field rule fields",
safeStringify({ fieldRuleFields, fieldRules })
);
}
// Use dynamic query if field rules require extra fields, otherwise use static typed query
const queryDoc = hasFieldRules
? this.buildDynamicAccountQuery(fieldRuleFields)
: GetAccountRecordsForRRSkip;
const query = await this.client.query(queryDoc, {
email,
websites,
emailDomain: `%@${emailDomain}`,
@@ -94,9 +126,31 @@ export class SalesforceGraphQLClient {
// If there is an existing contact, return the owner of the account
if (queryData.uiapi.query.Contact) {
const contact = queryData.uiapi.query.Contact?.edges?.[0]?.node;
const contactEdges = queryData.uiapi.query.Contact?.edges ?? [];
for (const edge of contactEdges) {
const contact = edge?.node;
if (!contact) continue;
const accountNode = contact.Account;
// Check field rules against the contact's account
if (hasFieldRules && accountNode) {
const failedRule = this.getFailingFieldRule(accountNode, fieldRules);
if (failedRule) {
log.info(
`Contact ${contact.Id}'s account filtered out by field rules, checking next contact`
);
SalesforceRoutingTraceService.fieldRuleFilteredRecord({
tier: "contact",
recordId: contact.Id,
reason: "Contact's account filtered out by field rules",
failedRule: { field: failedRule.field, value: failedRule.value, action: failedRule.action },
});
continue;
}
}
if (contact) {
log.info(`Existing contact found with id ${contact.Id}`);
SalesforceRoutingTraceService.graphqlExistingContactFound({
contactId: contact.Id,
@@ -117,8 +171,29 @@ export class SalesforceGraphQLClient {
// If no contact is found, query for accounts based on website field
if (queryData.uiapi.query.Account) {
const account = queryData.uiapi.query.Account?.edges?.[0]?.node;
if (account) {
const accountEdges = queryData.uiapi.query.Account?.edges ?? [];
for (const edge of accountEdges) {
const account = edge?.node;
if (!account) continue;
// Check field rules against the account
if (hasFieldRules) {
const failedRule = this.getFailingFieldRule(account, fieldRules);
if (failedRule) {
log.info(
`Account ${account.Id} filtered out by field rules, checking next account`
);
SalesforceRoutingTraceService.fieldRuleFilteredRecord({
tier: "account",
recordId: account.Id,
reason: "Account filtered out by field rules",
failedRule: { field: failedRule.field, value: failedRule.value, action: failedRule.action },
});
continue;
}
}
log.info(
`Existing account with website that matches email domain of ${emailDomain} found with id ${account.Id}`
);
@@ -140,39 +215,63 @@ export class SalesforceGraphQLClient {
// If no account is found, find an account based on existing contacts
if (queryData.uiapi.query.relatedContacts) {
const relatedContactsResults = queryData.uiapi.query.relatedContacts?.edges;
const relatedContactsResults =
queryData.uiapi.query.relatedContacts?.edges;
if (!relatedContactsResults) return [];
// Collect all valid related contacts and store their Account nodes for field rule checks
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const accountNodesByAccountId = new Map<string, Record<string, any>>();
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore - in CD/CI pipeline this will have any type
const relatedContacts = relatedContactsResults.reduce((contacts, edge) => {
const node = edge?.node;
if (!node) {
log.error("A related contact query didn't include a node");
return contacts;
}
if (!node.AccountId?.value) {
log.error(`A related contact with id ${node.Id} didn't have an account id`);
return contacts;
}
if (!node.Account?.Owner?.Id) {
log.error(`A related contact with id ${node.Id} didn't have an account owner id`);
return contacts;
}
if (!node.Account?.Owner?.Email?.value) {
log.error(`A related contact with id ${node.Id} didn't have an account owner email`);
return contacts;
}
const relatedContacts = relatedContactsResults.reduce(
(contacts, edge) => {
const node = edge?.node;
if (!node) {
log.error("A related contact query didn't include a node");
return contacts;
}
if (!node.AccountId?.value) {
log.error(
`A related contact with id ${node.Id} didn't have an account id`
);
return contacts;
}
if (!node.Account?.Owner?.Id) {
log.error(
`A related contact with id ${node.Id} didn't have an account owner id`
);
return contacts;
}
if (!node.Account?.Owner?.Email?.value) {
log.error(
`A related contact with id ${node.Id} didn't have an account owner email`
);
return contacts;
}
contacts.push({
id: node.Id,
AccountId: node.AccountId.value,
ownerId: node.Account.Owner.Id,
ownerEmail: node.Account.Owner.Email.value,
});
// Store the Account node for field rule evaluation later
if (!accountNodesByAccountId.has(node.AccountId.value)) {
accountNodesByAccountId.set(node.AccountId.value, node.Account);
}
return contacts;
}, [] as { id: string; AccountId: string; ownerId: string; ownerEmail: string }[]);
contacts.push({
id: node.Id,
AccountId: node.AccountId.value,
ownerId: node.Account.Owner.Id,
ownerEmail: node.Account.Owner.Email.value,
});
return contacts;
},
[] as {
id: string;
AccountId: string;
ownerId: string;
ownerEmail: string;
}[]
);
// Trace searching by contact domain
SalesforceRoutingTraceService.graphqlSearchingByContactDomain({
@@ -180,54 +279,90 @@ export class SalesforceGraphQLClient {
contactCount: relatedContacts.length,
});
const dominantAccountId = getDominantAccountId(relatedContacts);
if (!dominantAccountId) {
log.error(
"Could not find dominant account id with the following contacts",
safeStringify({ relatedContacts })
);
if (relatedContacts.length === 0) {
SalesforceRoutingTraceService.graphqlNoAccountFound({
email,
reason: "Could not find dominant account from related contacts",
reason: "No valid related contacts found",
});
return [];
}
// Get a contact from the dominant account
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore - in CD/CI pipeline this will have any type
const contactUnderAccount = relatedContacts.find((contact) => contact.AccountId === dominantAccountId);
if (!contactUnderAccount) {
log.error(
`Could not find a contact under the dominant account id ${dominantAccountId}`,
safeStringify({ relatedContacts })
// Rank accounts by contact count (most contacts first)
const accountCounts = new Map<string, number>();
for (const contact of relatedContacts) {
accountCounts.set(contact.AccountId, (accountCounts.get(contact.AccountId) || 0) + 1);
}
const rankedAccountIds = Array.from(accountCounts.entries())
.sort((a, b) => b[1] - a[1])
.map(([accountId]) => accountId);
// Try each account in order of dominance, applying field rules
for (const accountId of rankedAccountIds) {
// Check field rules against the account node
if (hasFieldRules) {
const accountNode = accountNodesByAccountId.get(accountId);
if (accountNode) {
const failedRule = this.getFailingFieldRule(accountNode, fieldRules);
if (failedRule) {
log.info(
`Dominant account ${accountId} filtered out by field rules, trying next account`
);
SalesforceRoutingTraceService.fieldRuleFilteredRecord({
tier: "related_contacts",
recordId: accountId,
reason: "Dominant account filtered out by field rules",
failedRule: { field: failedRule.field, value: failedRule.value, action: failedRule.action },
});
continue;
}
}
}
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore - in CD/CI pipeline this will have any type
const contactUnderAccount = relatedContacts.find(
(contact) => contact.AccountId === accountId
);
return [];
if (!contactUnderAccount) {
log.error(
`Could not find a contact under account id ${accountId}`,
safeStringify({ relatedContacts })
);
continue;
}
// Trace account selection
const contactsUnderAccount = relatedContacts.filter(
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
(contact) => contact.AccountId === accountId
);
SalesforceRoutingTraceService.graphqlDominantAccountSelected({
accountId,
contactCount: contactsUnderAccount.length,
ownerEmail: contactUnderAccount.ownerEmail,
});
log.info(
`Account found via related contacts with account id ${accountId}`
);
return [
{
id: accountId,
email: "",
ownerId: contactUnderAccount.ownerId,
ownerEmail: contactUnderAccount.ownerEmail,
recordType: SalesforceRecordEnum.ACCOUNT,
},
];
}
// Trace dominant account selection
const contactsUnderDominantAccount = relatedContacts.filter(
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
(contact) => contact.AccountId === dominantAccountId
);
SalesforceRoutingTraceService.graphqlDominantAccountSelected({
accountId: dominantAccountId,
contactCount: contactsUnderDominantAccount.length,
ownerEmail: contactUnderAccount.ownerEmail,
log.info("All related contact accounts filtered out by field rules");
SalesforceRoutingTraceService.graphqlNoAccountFound({
email,
reason: "All accounts filtered out by field rules",
});
log.info(`Account found via related contacts with account id ${dominantAccountId}`);
return [
{
id: dominantAccountId,
email: "",
ownerId: contactUnderAccount.ownerId,
ownerEmail: contactUnderAccount.ownerEmail,
recordType: SalesforceRecordEnum.ACCOUNT,
},
];
return [];
}
log.info("No account found for attendee");
@@ -238,6 +373,143 @@ export class SalesforceGraphQLClient {
return [];
}
/**
* Checks whether an Account node passes all configured field rules.
* Account nodes use the UIAPI pattern where field values are wrapped in { value }.
*
* @returns `null` if all rules pass, or the first failing rule if filtered.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private getFailingFieldRule(
accountNode: Record<string, any>,
fieldRules: RRSkipFieldRule[]
): RRSkipFieldRule | null {
const log = logger.getSubLogger({ prefix: [`[getFailingFieldRule]`] });
for (const rule of fieldRules) {
const fieldData = accountNode[rule.field];
const actualValue = String(fieldData?.value ?? "").toLowerCase();
const ruleValue = rule.value.toLowerCase();
const matches = actualValue === ruleValue;
log.info(
`Evaluating rule: field="${rule.field}" action="${
rule.action
}" ruleValue="${ruleValue}" actualValue="${actualValue}" rawFieldData=${safeStringify(
fieldData
)} matches=${matches}`
);
if (rule.action === RRSkipFieldRuleActionEnum.IGNORE && matches) {
log.info(
`FILTERED: ignore rule matched — field "${rule.field}" equals "${ruleValue}"`
);
SalesforceRoutingTraceService.fieldRuleEvaluated({
field: rule.field,
action: rule.action,
ruleValue,
actualValue,
matches,
result: "filtered",
});
return rule;
}
if (rule.action === RRSkipFieldRuleActionEnum.MUST_INCLUDE && !matches) {
log.info(
`FILTERED: must_include rule failed — field "${rule.field}" is "${actualValue}", expected "${ruleValue}"`
);
SalesforceRoutingTraceService.fieldRuleEvaluated({
field: rule.field,
action: rule.action,
ruleValue,
actualValue,
matches,
result: "filtered",
});
return rule;
}
}
log.info("All field rules passed");
return null;
}
/**
* Builds a GraphQL query string that includes additional Account fields
* for field rule evaluation. Mirrors the static GetAccountRecordsForRRSkip query
* but injects extra fields into all Account selections.
*/
private buildDynamicAccountQuery(fieldRuleFields: string[]): string {
const extraFields = fieldRuleFields
.map((field) => `${field} { value }`)
.join("\n ");
return `
query GetAccountRecordsForRRSkipWithFields($email: Email!, $websites: [Url!]!, $emailDomain: Email!) {
uiapi {
query {
Contact(where: { Email: { eq: $email } }) {
edges {
node {
Id
Email { value }
OwnerId { value }
AccountId { value }
Account {
Website { value }
Owner {
Id
Email { value }
}
${extraFields}
}
}
}
}
Account(where: { Website: { in: $websites } }) {
edges {
node {
Id
Website { value }
Owner {
Id
Email { value }
}
${extraFields}
}
}
}
relatedContacts: Contact(
where: {
and: [
{ Email: { like: $emailDomain } }
{ Email: { ne: $email } }
{ AccountId: { ne: null } }
]
}
) {
edges {
node {
Id
Email { value }
AccountId { value }
Account {
Id
Owner {
Id
Email { value }
}
${extraFields}
}
}
}
}
}
}
}
`;
}
private getAllPossibleAccountWebsiteFromEmailDomain(emailDomain: string) {
return getAllPossibleWebsiteValuesFromEmailDomain(emailDomain);
}
@@ -1,11 +1,18 @@
import { describe, it, vi, expect, beforeEach } from "vitest";
import { RRSkipFieldRuleActionEnum } from "../../../zod";
import type { RRSkipFieldRule } from "../../../zod";
import { SalesforceRecordEnum } from "../../enums";
import { SalesforceGraphQLClient } from "../SalesforceGraphQLClient";
import {
mockValueOfAccountOwnershipQueryMatchingContact,
mockValueOfAccountOwnershipQueryMatchingAccountWebsite,
mockValueOfAccountOwnershipQueryMatchingRelatedContacts,
mockValueOfContactWithFieldRuleFields,
mockValueOfMultipleContactsWithFieldRuleFields,
mockValueOfAccountWithFieldRuleFields,
mockValueOfMultipleAccountsWithFieldRuleFields,
mockValueOfRelatedContactsWithFieldRuleFields,
} from "./urqlMock";
const mockUrqlQuery = vi.fn();
@@ -76,4 +83,213 @@ describe("SalesforceGraphQLClient", () => {
},
]);
});
describe("with field rules", () => {
const ignoreFinanceRule: RRSkipFieldRule[] = [
{ field: "Industry", value: "Finance", action: RRSkipFieldRuleActionEnum.IGNORE },
];
const mustIncludeTechRule: RRSkipFieldRule[] = [
{ field: "Industry", value: "Technology", action: RRSkipFieldRuleActionEnum.MUST_INCLUDE },
];
describe("contact tier", () => {
it("should return contact when account passes ignore rule", async () => {
mockUrqlQuery.mockResolvedValue(mockValueOfContactWithFieldRuleFields("Technology"));
const client = new SalesforceGraphQLClient({ accessToken: "", instanceUrl: "" });
const result = await client.GetAccountRecordsForRRSkip("[email protected]", ignoreFinanceRule);
expect(result).toEqual([
{
id: "accountId",
email: "[email protected]",
ownerId: "ownerId",
ownerEmail: "[email protected]",
recordType: SalesforceRecordEnum.ACCOUNT,
},
]);
});
it("should filter out contact when account matches ignore rule", async () => {
mockUrqlQuery.mockResolvedValue(mockValueOfContactWithFieldRuleFields("Finance"));
const client = new SalesforceGraphQLClient({ accessToken: "", instanceUrl: "" });
const result = await client.GetAccountRecordsForRRSkip("[email protected]", ignoreFinanceRule);
expect(result).toEqual([]);
});
it("should return contact when account matches must_include rule", async () => {
mockUrqlQuery.mockResolvedValue(mockValueOfContactWithFieldRuleFields("Technology"));
const client = new SalesforceGraphQLClient({ accessToken: "", instanceUrl: "" });
const result = await client.GetAccountRecordsForRRSkip("[email protected]", mustIncludeTechRule);
expect(result).toEqual([
{
id: "accountId",
email: "[email protected]",
ownerId: "ownerId",
ownerEmail: "[email protected]",
recordType: SalesforceRecordEnum.ACCOUNT,
},
]);
});
it("should filter out contact when account fails must_include rule", async () => {
mockUrqlQuery.mockResolvedValue(mockValueOfContactWithFieldRuleFields("Healthcare"));
const client = new SalesforceGraphQLClient({ accessToken: "", instanceUrl: "" });
const result = await client.GetAccountRecordsForRRSkip("[email protected]", mustIncludeTechRule);
expect(result).toEqual([]);
});
it("should skip to next contact when first contact's account is filtered", async () => {
mockUrqlQuery.mockResolvedValue(mockValueOfMultipleContactsWithFieldRuleFields());
const client = new SalesforceGraphQLClient({ accessToken: "", instanceUrl: "" });
const result = await client.GetAccountRecordsForRRSkip("[email protected]", ignoreFinanceRule);
expect(result).toEqual([
{
id: "accountId2",
email: "[email protected]",
ownerId: "ownerId2",
ownerEmail: "[email protected]",
recordType: SalesforceRecordEnum.ACCOUNT,
},
]);
});
});
describe("account tier", () => {
it("should return account when it passes ignore rule", async () => {
mockUrqlQuery.mockResolvedValue(mockValueOfAccountWithFieldRuleFields("Technology"));
const client = new SalesforceGraphQLClient({ accessToken: "", instanceUrl: "" });
const result = await client.GetAccountRecordsForRRSkip("[email protected]", ignoreFinanceRule);
expect(result).toEqual([
{
id: "accountId",
email: "",
ownerId: "ownerId",
ownerEmail: "[email protected]",
recordType: SalesforceRecordEnum.ACCOUNT,
},
]);
});
it("should filter out account matching ignore rule and fall through to next", async () => {
mockUrqlQuery.mockResolvedValue(mockValueOfMultipleAccountsWithFieldRuleFields());
const client = new SalesforceGraphQLClient({ accessToken: "", instanceUrl: "" });
const result = await client.GetAccountRecordsForRRSkip("[email protected]", ignoreFinanceRule);
expect(result).toEqual([
{
id: "accountId2",
email: "",
ownerId: "ownerId2",
ownerEmail: "[email protected]",
recordType: SalesforceRecordEnum.ACCOUNT,
},
]);
});
it("should return empty when all accounts fail must_include rule", async () => {
mockUrqlQuery.mockResolvedValue(mockValueOfAccountWithFieldRuleFields("Healthcare"));
const client = new SalesforceGraphQLClient({ accessToken: "", instanceUrl: "" });
const result = await client.GetAccountRecordsForRRSkip("[email protected]", mustIncludeTechRule);
expect(result).toEqual([]);
});
});
describe("related contacts tier", () => {
it("should skip dominant account when it fails field rules and use next account", async () => {
// accountId1 is dominant (3 contacts) but has Industry=Finance
// accountId2 (2 contacts) has Industry=Technology
mockUrqlQuery.mockResolvedValue(mockValueOfRelatedContactsWithFieldRuleFields());
const client = new SalesforceGraphQLClient({ accessToken: "", instanceUrl: "" });
const result = await client.GetAccountRecordsForRRSkip("[email protected]", ignoreFinanceRule);
expect(result).toEqual([
{
id: "accountId2",
email: "",
ownerId: "owner2",
ownerEmail: "[email protected]",
recordType: SalesforceRecordEnum.ACCOUNT,
},
]);
});
it("should return dominant account when it passes must_include rule", async () => {
mockUrqlQuery.mockResolvedValue(mockValueOfRelatedContactsWithFieldRuleFields());
const client = new SalesforceGraphQLClient({ accessToken: "", instanceUrl: "" });
const result = await client.GetAccountRecordsForRRSkip("[email protected]", [
{ field: "Industry", value: "Finance", action: RRSkipFieldRuleActionEnum.MUST_INCLUDE },
]);
expect(result).toEqual([
{
id: "accountId1",
email: "",
ownerId: "owner1",
ownerEmail: "[email protected]",
recordType: SalesforceRecordEnum.ACCOUNT,
},
]);
});
it("should return empty when all accounts fail field rules", async () => {
mockUrqlQuery.mockResolvedValue(mockValueOfRelatedContactsWithFieldRuleFields());
const client = new SalesforceGraphQLClient({ accessToken: "", instanceUrl: "" });
const result = await client.GetAccountRecordsForRRSkip("[email protected]", [
{ field: "Industry", value: "Healthcare", action: RRSkipFieldRuleActionEnum.MUST_INCLUDE },
]);
expect(result).toEqual([]);
});
});
it("should be case-insensitive when evaluating field rules", async () => {
mockUrqlQuery.mockResolvedValue(mockValueOfContactWithFieldRuleFields("TECHNOLOGY"));
const client = new SalesforceGraphQLClient({ accessToken: "", instanceUrl: "" });
const result = await client.GetAccountRecordsForRRSkip("[email protected]", [
{ field: "Industry", value: "technology", action: RRSkipFieldRuleActionEnum.MUST_INCLUDE },
]);
expect(result).toEqual([
{
id: "accountId",
email: "[email protected]",
ownerId: "ownerId",
ownerEmail: "[email protected]",
recordType: SalesforceRecordEnum.ACCOUNT,
},
]);
});
it("should use dynamic query when field rules are provided", async () => {
mockUrqlQuery.mockResolvedValue(mockValueOfContactWithFieldRuleFields("Technology"));
const client = new SalesforceGraphQLClient({ accessToken: "", instanceUrl: "" });
await client.GetAccountRecordsForRRSkip("[email protected]", mustIncludeTechRule);
// When field rules are present, the query document should be a string (dynamic query)
// rather than the static typed document
const queryArg = mockUrqlQuery.mock.calls[0][0];
expect(typeof queryArg).toBe("string");
expect(queryArg).toContain("Industry { value }");
});
});
});
@@ -171,3 +171,179 @@ export const mockValueOfAccountOwnershipQueryMatchingRelatedContacts = () => {
},
});
};
/**
* Contact tier: contact's account has a field rule field (Industry).
*/
export const mockValueOfContactWithFieldRuleFields = (industry: string) => {
return generateMockResponse({
Contact: {
edges: [
{
node: {
Id: "contactId",
Email: { value: "[email protected]" },
AccountId: { value: "accountId" },
Account: {
Owner: { Id: "ownerId", Email: { value: "[email protected]" } },
Industry: { value: industry },
},
},
},
],
},
Account: { edges: [] },
});
};
/**
* Contact tier: two contacts, first account fails field rules, second passes.
*/
export const mockValueOfMultipleContactsWithFieldRuleFields = () => {
return generateMockResponse({
Contact: {
edges: [
{
node: {
Id: "contactId1",
Email: { value: "[email protected]" },
AccountId: { value: "accountId1" },
Account: {
Owner: { Id: "ownerId1", Email: { value: "[email protected]" } },
Industry: { value: "Finance" },
},
},
},
{
node: {
Id: "contactId2",
Email: { value: "[email protected]" },
AccountId: { value: "accountId2" },
Account: {
Owner: { Id: "ownerId2", Email: { value: "[email protected]" } },
Industry: { value: "Technology" },
},
},
},
],
},
Account: { edges: [] },
});
};
/**
* Account tier: account with a field rule field (Industry).
*/
export const mockValueOfAccountWithFieldRuleFields = (industry: string) => {
return generateMockResponse({
Contact: { edges: [] },
Account: {
edges: [
{
node: {
Id: "accountId",
Owner: { Id: "ownerId", Email: { value: "[email protected]" } },
Industry: { value: industry },
},
},
],
},
});
};
/**
* Account tier: two accounts, first fails field rules, second passes.
*/
export const mockValueOfMultipleAccountsWithFieldRuleFields = () => {
return generateMockResponse({
Contact: { edges: [] },
Account: {
edges: [
{
node: {
Id: "accountId1",
Owner: { Id: "ownerId1", Email: { value: "[email protected]" } },
Industry: { value: "Finance" },
},
},
{
node: {
Id: "accountId2",
Owner: { Id: "ownerId2", Email: { value: "[email protected]" } },
Industry: { value: "Technology" },
},
},
],
},
});
};
/**
* Related contacts tier: contacts across two accounts with field rule fields.
* accountId1 has 3 contacts (dominant), accountId2 has 2 contacts.
*/
export const mockValueOfRelatedContactsWithFieldRuleFields = () => {
return generateMockResponse({
Contact: { edges: [] },
Account: { edges: [] },
relatedContacts: {
edges: [
{
node: {
Id: "contact1",
AccountId: { value: "accountId1" },
Account: {
Id: "accountId1",
Owner: { Id: "owner1", Email: { value: "[email protected]" } },
Industry: { value: "Finance" },
},
},
},
{
node: {
Id: "contact2",
AccountId: { value: "accountId1" },
Account: {
Id: "accountId1",
Owner: { Id: "owner1", Email: { value: "[email protected]" } },
Industry: { value: "Finance" },
},
},
},
{
node: {
Id: "contact3",
AccountId: { value: "accountId1" },
Account: {
Id: "accountId1",
Owner: { Id: "owner1", Email: { value: "[email protected]" } },
Industry: { value: "Finance" },
},
},
},
{
node: {
Id: "contact4",
AccountId: { value: "accountId2" },
Account: {
Id: "accountId2",
Owner: { Id: "owner2", Email: { value: "[email protected]" } },
Industry: { value: "Technology" },
},
},
},
{
node: {
Id: "contact5",
AccountId: { value: "accountId2" },
Account: {
Id: "accountId2",
Owner: { Id: "owner2", Email: { value: "[email protected]" } },
Industry: { value: "Technology" },
},
},
},
],
},
});
};
@@ -176,4 +176,51 @@ export class SalesforceRoutingTraceService {
static graphqlNoAccountFound(data: { email: string; reason: string }): void {
SalesforceRoutingTraceService.addStep("graphql_no_account_found", data);
}
// ===== Field Rules =====
/**
* Record field rules validation result.
*/
static fieldRulesValidated(data: {
recordType: string;
configuredCount: number;
validCount: number;
validFields?: string[];
}): void {
SalesforceRoutingTraceService.addStep("field_rules_validated", data);
}
/**
* Record when a record is filtered out by field rules.
*/
static fieldRuleFilteredRecord(data: {
tier: string;
recordId: string;
reason: string;
failedRule?: { field: string; value: string; action: string };
}): void {
SalesforceRoutingTraceService.addStep("field_rule_filtered_record", data);
}
/**
* Record field rule evaluation detail.
*/
static fieldRuleEvaluated(data: {
field: string;
action: string;
ruleValue: string;
actualValue: string;
matches: boolean;
result: "passed" | "filtered";
}): void {
SalesforceRoutingTraceService.addStep("field_rule_evaluated", data);
}
/**
* Record when all records are filtered out by field rules in the SOQL path.
*/
static allRecordsFilteredByFieldRules(data: { recordType: string }): void {
SalesforceRoutingTraceService.addStep("all_records_filtered_by_field_rules", data);
}
}
+14
View File
@@ -18,6 +18,19 @@ export const writeToRecordEntrySchema = z.object({
export const writeToRecordDataSchema = z.record(z.string(), writeToBookingEntry);
export const RRSkipFieldRuleActionEnum = {
IGNORE: "ignore",
MUST_INCLUDE: "must_include",
} as const;
export const rrSkipFieldRuleSchema = z.object({
field: z.string(),
value: z.string(),
action: z.enum([RRSkipFieldRuleActionEnum.IGNORE, RRSkipFieldRuleActionEnum.MUST_INCLUDE]),
});
export type RRSkipFieldRule = z.infer<typeof rrSkipFieldRuleSchema>;
export const routingFormOptions = z
.object({
rrSkipToAccountLookupField: z.boolean().optional(),
@@ -40,6 +53,7 @@ export const appDataSchema = eventTypeAppCardZod.extend({
.nativeEnum(SalesforceRecordEnum)
.default(SalesforceRecordEnum.CONTACT)
.optional(),
rrSkipFieldRules: z.array(rrSkipFieldRuleSchema).optional(),
ifFreeEmailDomainSkipOwnerCheck: z.boolean().optional(),
roundRobinSkipFallbackToLeadOwner: z.boolean().optional(),
skipContactCreation: z.boolean().optional(),
+161 -71
View File
@@ -1,6 +1,9 @@
// TODO: Queries in this file are not optimized. Need to optimize them.
import type { Attribute } from "@calcom/app-store/routing-forms/types/types";
import type { AttributeId, AttributeOptionValueWithType } from "@calcom/app-store/routing-forms/types/types";
import type {
AttributeId,
AttributeOptionValueWithType,
} from "@calcom/app-store/routing-forms/types/types";
import { PrismaAttributeRepository } from "@calcom/features/attributes/repositories/PrismaAttributeRepository";
import { PrismaAttributeToUserRepository } from "@calcom/features/attributes/repositories/PrismaAttributeToUserRepository";
import logger from "@calcom/lib/logger";
@@ -42,7 +45,13 @@ type FullAttribute = {
}[];
};
async function _findMembershipsForBothOrgAndTeam({ orgId, teamId }: { orgId: number; teamId: number }) {
async function _findMembershipsForBothOrgAndTeam({
orgId,
teamId,
}: {
orgId: number;
teamId: number;
}) {
const memberships = await prisma.membership.findMany({
where: {
teamId: {
@@ -81,43 +90,62 @@ function _prepareAssignmentData({
assignmentsForTheTeam: AssignmentForTheTeam[];
attributesOfTheOrg: Attribute[];
}) {
const teamMembersThatHaveOptionAssigned = assignmentsForTheTeam.reduce((acc, attributeToUser) => {
const userId = attributeToUser.userId;
const attributeOption = attributeToUser.attributeOption;
const attribute = attributeToUser.attribute;
const teamMembersThatHaveOptionAssigned = assignmentsForTheTeam.reduce(
(acc, attributeToUser) => {
const userId = attributeToUser.userId;
const attributeOption = attributeToUser.attributeOption;
const attribute = attributeToUser.attribute;
if (!acc[userId]) {
acc[userId] = { userId, attributes: {} };
}
if (!acc[userId]) {
acc[userId] = { userId, attributes: {} };
}
const attributes = acc[userId].attributes;
const currentAttributeOptionValue = attributes[attribute.id]?.attributeOption;
const newAttributeOptionValue = {
isGroup: attributeOption.isGroup,
value: attributeOption.value,
contains: tranformContains({ contains: attributeOption.contains, attribute }),
};
if (currentAttributeOptionValue instanceof Array) {
attributes[attribute.id].attributeOption = [...currentAttributeOptionValue, newAttributeOptionValue];
} else if (currentAttributeOptionValue) {
attributes[attribute.id].attributeOption = [
currentAttributeOptionValue,
{
isGroup: attributeOption.isGroup,
value: attributeOption.value,
contains: tranformContains({ contains: attributeOption.contains, attribute }),
},
];
} else {
// Set the first value
attributes[attribute.id] = {
type: attribute.type,
attributeOption: newAttributeOptionValue,
const attributes = acc[userId].attributes;
const currentAttributeOptionValue =
attributes[attribute.id]?.attributeOption;
const newAttributeOptionValue = {
isGroup: attributeOption.isGroup,
value: attributeOption.value,
contains: tranformContains({
contains: attributeOption.contains,
attribute,
}),
};
}
return acc;
}, {} as Record<UserId, { userId: UserId; attributes: Record<AttributeId, AttributeOptionValueWithType> }>);
if (currentAttributeOptionValue instanceof Array) {
attributes[attribute.id].attributeOption = [
...currentAttributeOptionValue,
newAttributeOptionValue,
];
} else if (currentAttributeOptionValue) {
attributes[attribute.id].attributeOption = [
currentAttributeOptionValue,
{
isGroup: attributeOption.isGroup,
value: attributeOption.value,
contains: tranformContains({
contains: attributeOption.contains,
attribute,
}),
},
];
} else {
// Set the first value
attributes[attribute.id] = {
type: attribute.type,
attributeOption: newAttributeOptionValue,
};
}
return acc;
},
{} as Record<
UserId,
{
userId: UserId;
attributes: Record<AttributeId, AttributeOptionValueWithType>;
}
>
);
return Object.values(teamMembersThatHaveOptionAssigned);
@@ -141,13 +169,17 @@ function _prepareAssignmentData({
}) {
return contains
.map((optionId) => {
const allOptions = attributesOfTheOrg.find((_attribute) => _attribute.id === attribute.id)?.options;
const allOptions = attributesOfTheOrg.find(
(_attribute) => _attribute.id === attribute.id
)?.options;
const option = allOptions?.find((option) => option.id === optionId);
if (!option) {
console.error(
`Enriching "contains" for attribute ${
attribute.name
}: Option with id ${optionId} not found. Looked up in ${JSON.stringify(allOptions)}`
}: Option with id ${optionId} not found. Looked up in ${JSON.stringify(
allOptions
)}`
);
return null;
}
@@ -157,7 +189,9 @@ function _prepareAssignmentData({
slug: option.slug,
};
})
.filter((option): option is NonNullable<typeof option> => option !== null);
.filter(
(option): option is NonNullable<typeof option> => option !== null
);
}
}
@@ -182,24 +216,39 @@ function _getAttributeOptionFromAttributeOption({
}) {
const matchingOption = allAttributesOfTheOrg.reduce((found, attribute) => {
if (found) return found;
return attribute.options.find((option) => option.id === attributeOptionId) || null;
return (
attribute.options.find((option) => option.id === attributeOptionId) ||
null
);
}, null as null | (typeof allAttributesOfTheOrg)[number]["options"][number]);
return matchingOption;
}
async function _getOrgMembershipToUserIdForTeam({ orgId, teamId }: { orgId: number; teamId: number }) {
const { orgMemberships, teamMemberships } = await _findMembershipsForBothOrgAndTeam({
orgId,
teamId,
});
async function _getOrgMembershipToUserIdForTeam({
orgId,
teamId,
}: {
orgId: number;
teamId: number;
}) {
const { orgMemberships, teamMemberships } =
await _findMembershipsForBothOrgAndTeam({
orgId,
teamId,
});
// Using map for performance lookup as it matters in the below loop working with 1000s of records
const orgMembershipsByUserId = new Map(orgMemberships.map((m) => [m.userId, m]));
const orgMembershipsByUserId = new Map(
orgMemberships.map((m) => [m.userId, m])
);
/**
* Holds the records of orgMembershipId to userId for the sub-team's members only.
*/
const orgMembershipToUserIdForTeamMembers = new Map<OrgMembershipId, UserId>();
const orgMembershipToUserIdForTeamMembers = new Map<
OrgMembershipId,
UserId
>();
/**
* For an organization with 3000 users and 10 teams, with every team having around 300 members, the total memberships we get for a team are 3000+300 = 3300
@@ -208,32 +257,45 @@ async function _getOrgMembershipToUserIdForTeam({ orgId, teamId }: { orgId: numb
teamMemberships.forEach((teamMembership) => {
const orgMembership = orgMembershipsByUserId.get(teamMembership.userId);
if (!orgMembership) {
console.error(
`Org membership not found for userId ${teamMembership.userId} in the organization's memberships`
);
// console.error(
// `Org membership not found for userId ${teamMembership.userId} in the organization's memberships`
// );
return;
}
orgMembershipToUserIdForTeamMembers.set(orgMembership.id, orgMembership.userId);
orgMembershipToUserIdForTeamMembers.set(
orgMembership.id,
orgMembership.userId
);
});
return orgMembershipToUserIdForTeamMembers;
}
async function _queryAllData({ orgId, teamId }: { orgId: number; teamId: number }) {
async function _queryAllData({
orgId,
teamId,
}: {
orgId: number;
teamId: number;
}) {
const attributeRepo = new PrismaAttributeRepository(prisma);
const attributeToUserRepo = new PrismaAttributeToUserRepository(prisma);
const [orgMembershipToUserIdForTeamMembers, attributesOfTheOrg] = await Promise.all([
_getOrgMembershipToUserIdForTeam({ orgId, teamId }),
attributeRepo.findManyByOrgId({ orgId }),
]);
const [orgMembershipToUserIdForTeamMembers, attributesOfTheOrg] =
await Promise.all([
_getOrgMembershipToUserIdForTeam({ orgId, teamId }),
attributeRepo.findManyByOrgId({ orgId }),
]);
const orgMembershipIds = Array.from(orgMembershipToUserIdForTeamMembers.keys());
const orgMembershipIds = Array.from(
orgMembershipToUserIdForTeamMembers.keys()
);
// Get all the attributes assigned to the members of the team
const attributesToUsersForTeam = await attributeToUserRepo.findManyByOrgMembershipIds({
orgMembershipIds,
});
const attributesToUsersForTeam =
await attributeToUserRepo.findManyByOrgMembershipIds({
orgMembershipIds,
});
return {
attributesOfTheOrg,
@@ -242,8 +304,16 @@ async function _queryAllData({ orgId, teamId }: { orgId: number; teamId: number
};
}
async function getAttributesAssignedToMembersOfTeam({ teamId, userId }: { teamId: number; userId?: number }) {
const log = logger.getSubLogger({ prefix: ["getAttributeToUserWithMembershipAndAttributes"] });
async function getAttributesAssignedToMembersOfTeam({
teamId,
userId,
}: {
teamId: number;
userId?: number;
}) {
const log = logger.getSubLogger({
prefix: ["getAttributeToUserWithMembershipAndAttributes"],
});
const whereClauseForAttributesAssignedToMembersOfTeam = {
options: {
@@ -310,7 +380,9 @@ function _buildAssignmentsForTeam({
const orgMembershipId = attributeToUser.memberId;
const userId = orgMembershipToUserIdForTeamMembers.get(orgMembershipId);
if (!userId) {
console.error(`No org membership found for membership id ${orgMembershipId}`);
console.error(
`No org membership found for membership id ${orgMembershipId}`
);
return null;
}
const attribute = _getAttributeFromAttributeOption({
@@ -337,15 +409,27 @@ function _buildAssignmentsForTeam({
attributeOption,
};
})
.filter((assignment): assignment is NonNullable<typeof assignment> => assignment !== null);
.filter(
(assignment): assignment is NonNullable<typeof assignment> =>
assignment !== null
);
}
export async function getAttributesAssignmentData({ orgId, teamId }: { orgId: number; teamId: number }) {
const { attributesOfTheOrg, attributesToUsersForTeam, orgMembershipToUserIdForTeamMembers } =
await _queryAllData({
orgId,
teamId,
});
export async function getAttributesAssignmentData({
orgId,
teamId,
}: {
orgId: number;
teamId: number;
}) {
const {
attributesOfTheOrg,
attributesToUsersForTeam,
orgMembershipToUserIdForTeamMembers,
} = await _queryAllData({
orgId,
teamId,
});
const assignmentsForTheTeam = _buildAssignmentsForTeam({
attributesToUsersForTeam,
@@ -369,6 +453,12 @@ export async function getAttributesForTeam({ teamId }: { teamId: number }) {
return attributes satisfies Attribute[];
}
export async function getUsersAttributes({ userId, teamId }: { userId: number; teamId: number }) {
export async function getUsersAttributes({
userId,
teamId,
}: {
userId: number;
teamId: number;
}) {
return await getAttributesAssignedToMembersOfTeam({ teamId, userId });
}