:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(cdp): add a Salesforce lookup step (#81732)
Harley Alexander6e5038079f05
diff --git a/posthog/cdp/templates/__init__.py b/posthog/cdp/templates/__init__.pyindex b88918776f45..c6c2c857ca77 100644--- a/posthog/cdp/templates/__init__.py+++ b/posthog/cdp/templates/__init__.py@@ -74,6 +74,7 @@ from .rudderstack.template_rudderstack import ()from .salesforce.template_salesforce import (template_create as salesforce_create,+ template_lookup as salesforce_lookup,template_update as salesforce_update,)from .sendgrid.template_sendgrid import (@@ -127,6 +128,7 @@ HOG_FUNCTION_TEMPLATES = [reddit_pixel,rudderstack,salesforce_create,+ salesforce_lookup,salesforce_update,sendgrid,snapchat_pixel,diff --git a/posthog/cdp/templates/salesforce/template_salesforce.py b/posthog/cdp/templates/salesforce/template_salesforce.pyindex 00f962f2a93b..1a5737030a10 100644--- a/posthog/cdp/templates/salesforce/template_salesforce.py+++ b/posthog/cdp/templates/salesforce/template_salesforce.py@@ -233,6 +233,152 @@ return empty(res.body) ? {'success': true} : res.body)+template_lookup: HogFunctionTemplateDC = HogFunctionTemplateDC(+ status="beta",+ free=False,+ type="destination",+ id="template-salesforce-lookup",+ name="Salesforce",+ description="Look up an object in Salesforce",+ icon_url="/static/services/salesforce.png",+ category=["CRM", "Customer Success"],+ code_language="hog",+ code=r"""+let assertApiName := (value, label, pattern) -> {+ if (not match(value, pattern)) {+ throw Error(f'{label} \'{value}\' is not a valid Salesforce API name. Use letters, numbers, and underscores.')+ }+}++// Backslash goes first, otherwise the sequences introduced below get escaped a second time.+let escapeSoql := (value) -> {+ let escaped := replaceAll(value, '\\', '\\\\')+ escaped := replaceAll(escaped, '\'', '\\\'')+ escaped := replaceAll(escaped, '\n', '\\n')+ escaped := replaceAll(escaped, '\r', '\\r')+ escaped := replaceAll(escaped, '\t', '\\t')+ escaped := replaceAll(escaped, '\b', '\\b')+ escaped := replaceAll(escaped, '\f', '\\f')+ return escaped+}++// The query travels in the URL, so percent-encode anything that would end the query+// string or change its meaning. Percent signs go first, otherwise the replacements+// below get encoded a second time.+let encodeForUrl := (value) -> {+ let encoded := replaceAll(value, '%', '%25')+ encoded := replaceAll(encoded, ' ', '%20')+ encoded := replaceAll(encoded, '"', '%22')+ encoded := replaceAll(encoded, '#', '%23')+ encoded := replaceAll(encoded, '&', '%26')+ encoded := replaceAll(encoded, '\'', '%27')+ encoded := replaceAll(encoded, '+', '%2B')+ encoded := replaceAll(encoded, ',', '%2C')+ encoded := replaceAll(encoded, '/', '%2F')+ encoded := replaceAll(encoded, '<', '%3C')+ encoded := replaceAll(encoded, '=', '%3D')+ encoded := replaceAll(encoded, '>', '%3E')+ encoded := replaceAll(encoded, '?', '%3F')+ encoded := replaceAll(encoded, '\\', '%5C')+ return encoded+}++let object := trim(inputs.object)+let matchField := trim(inputs.match_field)+let matchValue := trim(inputs.match_value)++if (empty(matchValue)) {+ throw Error('Salesforce lookup has no value to match on. The property mapped to the match value was empty when this ran. Check that it is set before this step.')+}++assertApiName(object, 'Object', '^[A-Za-z0-9_]+$')+assertApiName(matchField, 'Match field', '^[A-Za-z0-9_]+$')++let selected := ['Id']+for (let rawField in splitByString(',', inputs.fields ?? '')) {+ let field := trim(rawField)+ if (notEmpty(field) and not has(selected, field)) {+ assertApiName(field, 'Field', '^[A-Za-z0-9_.]+$')+ selected := arrayPushBack(selected, field)+ }+}++let selectList := arrayStringConcat(selected, ', ')+let escapedValue := escapeSoql(matchValue)++// Two rows are enough to tell a unique match from an ambiguous one. This bounds the+// row count only. One long field still exceeds the workflow variable limit, which is+// why the returned fields are listed explicitly rather than selected wholesale.+let soql := f'SELECT {selectList} FROM {object} WHERE {matchField} = \'{escapedValue}\' LIMIT 2'+let queryString := encodeForUrl(soql)++let res := fetch(f'{inputs.oauth.instance_url}/services/data/v61.0/query/?q={queryString}', {+ 'method': 'GET',+ 'headers': {+ 'Authorization': f'Bearer {inputs.oauth.access_token}',+ 'Content-Type': 'application/json'+ }+});++if (res.status >= 400) {+ throw Error(f'Salesforce lookup on {object} failed with status {res.status}: {res.body}');+}++let records := res.body?.records ?? []+let found := length(records) > 0++print(f'Salesforce lookup on {object} matched {length(records)} record(s)')++return {+ 'found': found,+ 'multiple': length(records) > 1,+ 'id': found ? records[1].Id : null,+ 'record': found ? records[1] : null+}+""".strip(),+ inputs_schema=[+ common_inputs["oauth"],+ {+ "key": "object",+ "type": "string",+ "label": "Object",+ "description": "The Salesforce object to search, such as `Lead` or `Contact`.",+ "default": "Lead",+ "secret": False,+ "required": True,+ },+ {+ "key": "match_field",+ "type": "string",+ "label": "Match field",+ "description": "The field to match on, such as `Email`. Unlike the update step, this does not have to be an External ID field.",+ "default": "Email",+ "secret": False,+ "required": True,+ },+ {+ "key": "match_value",+ "type": "string",+ "label": "Match value",+ "description": "The value to match. The step fails if this is empty, so map it to a property that is set by the time the step runs.",+ "default": "{person.properties.email}",+ "secret": False,+ "required": True,+ },+ {+ "key": "fields",+ "type": "string",+ "label": "Fields to return",+ "description": "Comma separated fields to return on the matched record. `Id` is always included. Workflow variables share a 5 KB limit, so avoid long text fields here, or set a result path on the output variable to store only what you need.",+ "default": "Id",+ "secret": False,+ "required": False,+ },+ ],+ filters=common_filters,+)++class TemplatSalesforceMigrator(HogFunctionTemplateMigrator):plugin_url = "https://github.com/PostHog/posthog-plugin-replicator"diff --git a/posthog/cdp/templates/salesforce/test_template_salesforce.py b/posthog/cdp/templates/salesforce/test_template_salesforce.pyindex 1189a85a7b92..851729cdef0b 100644--- a/posthog/cdp/templates/salesforce/test_template_salesforce.py+++ b/posthog/cdp/templates/salesforce/test_template_salesforce.py@@ -7,6 +7,7 @@ from posthog.cdp.templates.helpers import BaseHogFunctionTemplateTestfrom posthog.cdp.templates.salesforce.template_salesforce import (TemplatSalesforceMigrator,template_create as template_salesforce_create,+ template_lookup as template_salesforce_lookup,template_update as template_salesforce_update,)@@ -161,6 +162,93 @@ class TestTemplateSalesforceUpdate(BaseHogFunctionTemplateTest):assert self.run_function(self._inputs(path="Lead/00Q1")).result == {"success": True}+class TestTemplateSalesforceLookup(BaseHogFunctionTemplateTest):+ template = template_salesforce_lookup++ def _inputs(self, **kwargs):+ inputs = {+ "oauth": {+ "instance_url": "https://example.my.salesforce.com",+ "access_token": "oauth-1234",+ },+ "object": "Lead",+ "match_field": "Email",+ "match_value": "[email protected]",+ "fields": "Id",+ }+ inputs.update(kwargs)+ return inputs++ def _respond(self, records):+ self.mock_fetch_response = lambda *args: {"status": 200, "body": {"records": records}} # type: ignore++ def _query(self):+ return self.get_mock_fetch_calls()[0][0].split("?q=")[1]++ def test_queries_salesforce_and_returns_the_match(self):+ self._respond([{"Id": "00Q1", "Status": "Open"}])+ result = self.run_function(self._inputs(fields="Id, Status")).result+ url, options = self.get_mock_fetch_calls()[0]+ assert url == (+ "https://example.my.salesforce.com/services/data/v61.0/query/"+ "?q=SELECT%20Id%2C%20Status%20FROM%20Lead%20WHERE%20Email%20%3D%20%[email protected]%27%20LIMIT%202"+ )+ assert options["method"] == "GET"+ assert result == {+ "found": True,+ "multiple": False,+ "id": "00Q1",+ "record": {"Id": "00Q1", "Status": "Open"},+ }++ @parameterized.expand(+ [+ ("single quote", "x' OR Name != '", "%27x%5C%27%20OR%20Name%20!%3D%20%5C%27%27"),+ ("plus addressing", "[email protected]", "%27a%[email protected]%27"),+ ("backslash", "a\\[email protected]", "%27a%5C%[email protected]%27"),+ ("embedded newline", "a@\nb.com", "%27a@%5Cnb.com%27"),+ ]+ )+ def test_escapes_the_match_value(self, _name: str, match_value: str, expected: str):+ self._respond([])+ self.run_function(self._inputs(match_value=match_value))+ assert expected in self._query()++ def test_returns_not_found_instead_of_failing(self):+ self._respond([])+ assert self.run_function(self._inputs()).result == {+ "found": False,+ "multiple": False,+ "id": None,+ "record": None,+ }++ def test_flags_more_than_one_match(self):+ self._respond([{"Id": "00Q1"}, {"Id": "00Q2"}])+ result = self.run_function(self._inputs()).result+ assert result["multiple"] is True+ assert result["id"] == "00Q1"++ def test_rejects_empty_match_value(self):+ with pytest.raises(UncaughtHogVMException) as e:+ self.run_function(self._inputs(match_value=""))+ assert "no value to match on" in str(e.value)+ assert self.get_mock_fetch_calls() == []++ @parameterized.expand(+ [+ ("object", {"object": "Lead WHERE Id != null"}),+ ("match field", {"match_field": "Email'"}),+ ("returned field", {"fields": "Id, Name FROM User"}),+ ]+ )+ def test_rejects_invalid_api_names(self, _name: str, override: dict):+ with pytest.raises(UncaughtHogVMException) as e:+ self.run_function(self._inputs(**override))+ assert "is not a valid Salesforce API name" in str(e.value)+ assert self.get_mock_fetch_calls() == []++class TestTemplateMigration(BaseTest):def get_plugin_config(self, config: dict):_config = {