: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 close crm destination template (#69271)
Meikel Ratz48998a7a5d50
diff --git a/nodejs/src/cdp/templates/_destinations/close/close.template.test.ts b/nodejs/src/cdp/templates/_destinations/close/close.template.test.tsnew file mode 100644index 000000000000..326244fa2a7f--- /dev/null+++ b/nodejs/src/cdp/templates/_destinations/close/close.template.test.ts@@ -0,0 +1,242 @@+import { parseJSON } from '~/common/utils/json-parse'++import { TemplateTester } from '../../test/test-helpers'+import { template } from './close.template'++const SEARCH_URL = 'https://api.close.com/api/v1/data/search/'+const LEAD_URL = 'https://api.close.com/api/v1/lead/'++const EXPECTED_HEADERS = {+ 'Content-Type': 'application/json',+ Accept: 'application/json',+ Authorization: `Basic ${Buffer.from('API_KEY:').toString('base64')}`,+}++const EXPECTED_SEARCH_BODY = {+ query: {+ type: 'and',+ queries: [+ { type: 'object_type', object_type: 'contact' },+ {+ type: 'has_related',+ this_object_type: 'contact',+ related_object_type: 'contact_email',+ related_query: {+ type: 'field_condition',+ field: { type: 'regular_field', object_type: 'contact_email', field_name: 'email' },+ condition: { type: 'text', mode: 'phrase', value: '[email protected]' },+ },+ },+ ],+ },+ _fields: { contact: ['id', 'lead_id'] },+ _limit: 1,+}++describe('close template', () => {+ const tester = new TemplateTester(template)++ beforeEach(async () => {+ await tester.beforeEach()+ })++ const defaultInputs = {+ apiKey: 'API_KEY',+ email: '[email protected]',+ leadName: 'PostHog',+ firstName: 'Max',+ lastName: 'AI',+ properties: {+ title: 'Hedgehog in Residence',+ },+ leadProperties: {},+ }++ const parseBody = (invocation: any): Record<string, any> => {+ return parseJSON(invocation.queueParameters.body)+ }++ it('creates a lead when no contact matches', async () => {+ const searchRequest = await tester.invoke(+ { ...defaultInputs, leadProperties: { url: 'https://posthog.com' } },+ {}+ )++ expect(searchRequest.error).toBeUndefined()+ expect(searchRequest.finished).toBe(false)+ const searchParams = searchRequest.invocation.queueParameters as any+ expect(searchParams.url).toBe(SEARCH_URL)+ expect(searchParams.method).toBe('POST')+ expect(searchParams.headers).toEqual(EXPECTED_HEADERS)+ expect(parseBody(searchRequest.invocation)).toEqual(EXPECTED_SEARCH_BODY)++ const createRequest = await tester.invokeFetchResponse(searchRequest.invocation, {+ status: 200,+ body: { data: [], cursor: null },+ })++ expect(createRequest.finished).toBe(false)+ const createParams = createRequest.invocation.queueParameters as any+ expect(createParams.url).toBe(LEAD_URL)+ expect(createParams.method).toBe('POST')+ expect(createParams.headers).toEqual(EXPECTED_HEADERS)+ expect(parseBody(createRequest.invocation)).toEqual({+ name: 'PostHog',+ contacts: [+ {+ emails: [{ email: '[email protected]', type: 'office' }],+ name: 'Max AI',+ title: 'Hedgehog in Residence',+ },+ ],+ url: 'https://posthog.com',+ })++ const done = await tester.invokeFetchResponse(createRequest.invocation, {+ status: 200,+ body: { id: 'lead_123' },+ })+ expect(done.error).toBeUndefined()+ expect(done.finished).toBe(true)+ })++ it('updates the matched contact without touching its emails', async () => {+ const searchRequest = await tester.invoke(defaultInputs, {+ person: { properties: { $geoip_country_name: 'United States', plan: 'pay-as-you-go' } },+ })++ const updateRequest = await tester.invokeFetchResponse(searchRequest.invocation, {+ status: 200,+ body: { data: [{ __object_type: 'contact', id: 'cont_123', lead_id: 'lead_456' }] },+ })++ expect(updateRequest.finished).toBe(false)+ const updateParams = updateRequest.invocation.queueParameters as any+ expect(updateParams.url).toBe('https://api.close.com/api/v1/contact/cont_123/')+ expect(updateParams.method).toBe('PUT')+ expect(updateParams.headers).toEqual(EXPECTED_HEADERS)+ // only the explicitly mapped fields, and no "emails" key - a PUT would+ // replace the contact's existing emails+ expect(parseBody(updateRequest.invocation)).toEqual({+ name: 'Max AI',+ title: 'Hedgehog in Residence',+ })++ const done = await tester.invokeFetchResponse(updateRequest.invocation, {+ status: 200,+ body: { id: 'cont_123' },+ })+ expect(done.error).toBeUndefined()+ expect(done.finished).toBe(true)+ })++ it('omits name when both firstName and lastName are empty', async () => {+ const searchRequest = await tester.invoke({ ...defaultInputs, firstName: '', lastName: '' }, {})++ const createRequest = await tester.invokeFetchResponse(searchRequest.invocation, {+ status: 200,+ body: { data: [] },+ })++ expect(parseBody(createRequest.invocation)).toEqual({+ name: 'PostHog',+ contacts: [+ {+ emails: [{ email: '[email protected]', type: 'office' }],+ title: 'Hedgehog in Residence',+ },+ ],+ })+ })++ it('skips the PUT when a contact matches but there is nothing to update', async () => {+ const searchRequest = await tester.invoke({ ...defaultInputs, firstName: '', lastName: '', properties: {} }, {})++ const response = await tester.invokeFetchResponse(searchRequest.invocation, {+ status: 200,+ body: { data: [{ __object_type: 'contact', id: 'cont_123', lead_id: 'lead_456' }] },+ })++ expect(response.error).toBeUndefined()+ expect(response.finished).toBe(true)+ expect(response.invocation.queueParameters).toBeFalsy()+ expect(response.logs.some((log) => log.message.includes('No contact fields to update. Skipping...'))).toBe(true)+ })++ it('JSON-stringifies object-valued property mappings', async () => {+ const searchRequest = await tester.invoke(+ {+ ...defaultInputs,+ properties: {+ title: 'Hedgehog in Residence',+ 'custom.cf_addresses': [{ city: 'Berlin' }, { city: 'London' }],+ },+ },+ {}+ )++ const createRequest = await tester.invokeFetchResponse(searchRequest.invocation, {+ status: 200,+ body: { data: [] },+ })++ const body = parseBody(createRequest.invocation)+ expect(body.contacts[0]['custom.cf_addresses']).toBe('[{"city":"Berlin"},{"city":"London"}]')+ expect(body.contacts[0].title).toBe('Hedgehog in Residence')+ })++ it('skips when email is empty', async () => {+ const response = await tester.invoke({ ...defaultInputs, email: '' }, {})++ expect(response.error).toBeUndefined()+ expect(response.finished).toBe(true)+ expect(response.invocation.queueParameters).toBeFalsy()+ expect(response.logs.some((log) => log.message.includes('No email set. Skipping...'))).toBe(true)+ })++ it('throws when the search request fails', async () => {+ const searchRequest = await tester.invoke(defaultInputs, {})++ const errorResponse = await tester.invokeFetchResponse(searchRequest.invocation, {+ status: 400,+ body: { error: 'error' },+ })++ expect(errorResponse.finished).toBe(true)+ expect(errorResponse.error).toMatch('Error from api.close.com (status 400)')+ })++ it('throws when the lead create request fails', async () => {+ const searchRequest = await tester.invoke(defaultInputs, {})++ const createRequest = await tester.invokeFetchResponse(searchRequest.invocation, {+ status: 200,+ body: { data: [] },+ })++ const errorResponse = await tester.invokeFetchResponse(createRequest.invocation, {+ status: 400,+ body: { error: 'error' },+ })++ expect(errorResponse.finished).toBe(true)+ expect(errorResponse.error).toMatch('Error from api.close.com (status 400)')+ })++ it('throws when the contact update request fails', async () => {+ const searchRequest = await tester.invoke(defaultInputs, {})++ const updateRequest = await tester.invokeFetchResponse(searchRequest.invocation, {+ status: 200,+ body: { data: [{ __object_type: 'contact', id: 'cont_123', lead_id: 'lead_456' }] },+ })++ const errorResponse = await tester.invokeFetchResponse(updateRequest.invocation, {+ status: 400,+ body: { error: 'error' },+ })++ expect(errorResponse.finished).toBe(true)+ expect(errorResponse.error).toMatch('Error from api.close.com (status 400)')+ })+})diff --git a/nodejs/src/cdp/templates/_destinations/close/close.template.ts b/nodejs/src/cdp/templates/_destinations/close/close.template.tsnew file mode 100644index 000000000000..f4a890c56137--- /dev/null+++ b/nodejs/src/cdp/templates/_destinations/close/close.template.ts@@ -0,0 +1,192 @@+import { HogFunctionTemplate } from '~/cdp/types'++export const template: HogFunctionTemplate = {+ status: 'alpha',+ free: false,+ type: 'destination',+ id: 'template-close',+ name: 'Close',+ description:+ 'Sync PostHog persons to Close as contacts. Creates a new lead when no contact with the same email exists yet.',+ icon_url: '/static/services/close.png',+ category: ['CRM', 'Customer Success'],+ code_language: 'hog',+ code: `+if (empty(inputs.email)) {+ print('No email set. Skipping...')+ return+}++let headers := {+ 'Content-Type': 'application/json',+ 'Accept': 'application/json',+ 'Authorization': f'Basic {base64Encode(f'{inputs.apiKey}:')}',+}++let searchRes := fetch('https://api.close.com/api/v1/data/search/', {+ 'method': 'POST',+ 'headers': headers,+ 'body': {+ 'query': {+ 'type': 'and',+ 'queries': [+ {'type': 'object_type', 'object_type': 'contact'},+ {+ 'type': 'has_related',+ 'this_object_type': 'contact',+ 'related_object_type': 'contact_email',+ 'related_query': {+ 'type': 'field_condition',+ 'field': {'type': 'regular_field', 'object_type': 'contact_email', 'field_name': 'email'},+ 'condition': {'type': 'text', 'mode': 'phrase', 'value': inputs.email}+ }+ }+ ]+ },+ '_fields': {'contact': ['id', 'lead_id']},+ '_limit': 1+ }+})++if (searchRes.status >= 400) {+ throw Error(f'Error from api.close.com (status {searchRes.status}): {searchRes.body}')+}++let contactAttributes := {}++for (let key, value in inputs.properties) {+ if (not empty(value)) {+ if (typeof(value) in ('object', 'array', 'tuple')) {+ contactAttributes[key] := jsonStringify(value)+ } else {+ contactAttributes[key] := value+ }+ }+}++let fullName := trim(f'{inputs.firstName} {inputs.lastName}')+if (not empty(fullName)) {+ contactAttributes.name := fullName+}++let res++if (not empty(searchRes.body.data)) {+ if (empty(contactAttributes)) {+ print('No contact fields to update. Skipping...')+ return+ }+ // Never send emails on update - PUT replaces the contact's whole emails array+ res := fetch(f'https://api.close.com/api/v1/contact/{searchRes.body.data.1.id}/', {+ 'method': 'PUT',+ 'headers': headers,+ 'body': contactAttributes+ })+} else {+ let contact := {+ 'emails': [{'email': inputs.email, 'type': 'office'}]+ }+ for (let key, value in contactAttributes) {+ contact[key] := value+ }+ let lead := {+ 'name': inputs.leadName,+ 'contacts': [contact]+ }+ for (let key, value in inputs.leadProperties) {+ if (not empty(value)) {+ lead[key] := value+ }+ }+ res := fetch('https://api.close.com/api/v1/lead/', {+ 'method': 'POST',+ 'headers': headers,+ 'body': lead+ })+}++if (res.status >= 400) {+ throw Error(f'Error from api.close.com (status {res.status}): {res.body}')+}+`,+ inputs_schema: [+ {+ key: 'apiKey',+ type: 'string',+ label: 'Close API key',+ description:+ 'You can create an API key in Settings > Developer > API keys: https://app.close.com/settings/developer/api-keys/',+ secret: true,+ required: true,+ },+ {+ key: 'email',+ type: 'string',+ label: 'Email of the user',+ description:+ 'Where to find the email of the contact. You can use the filters section to filter out unwanted emails or internal users.',+ default: '{person.properties.email}',+ secret: false,+ required: true,+ },+ {+ key: 'leadName',+ type: 'string',+ label: 'Lead name',+ description: 'Name of the lead (company) to create if no contact with this email exists yet.',+ default: '{person.properties.company ?? person.properties.email}',+ secret: false,+ required: true,+ },+ {+ key: 'firstName',+ type: 'string',+ label: 'First name',+ description:+ "First name of the contact. Combined with the last name and sent as Close's single `name` field; if both are empty the name is omitted.",+ default: '{person.properties.first_name}',+ secret: false,+ required: false,+ },+ {+ key: 'lastName',+ type: 'string',+ label: 'Last name',+ description:+ "Last name of the contact. Combined with the first name and sent as Close's single `name` field; if both are empty the name is omitted.",+ default: '{person.properties.last_name}',+ secret: false,+ required: false,+ },+ {+ key: 'properties',+ type: 'dictionary',+ label: 'Contact field mapping',+ description:+ 'Map of Close contact fields and their values. Note that Close only accepts valid contact fields (e.g. title, or custom.cf_FIELD_ID keys) - unknown fields may be rejected. Custom fields use the custom.cf_FIELD_ID format: https://developer.close.com/resources/custom-fields/',+ default: {+ title: '{person.properties.job_title}',+ },+ secret: false,+ required: false,+ },+ {+ key: 'leadProperties',+ type: 'dictionary',+ label: 'Lead field mapping',+ description:+ 'Map of Close lead fields and their values, only applied when a new lead is created (e.g. url or custom.cf_FIELD_ID keys).',+ default: {},+ secret: false,+ required: false,+ },+ ],+ filters: {+ events: [+ { id: '$identify', name: '$identify', type: 'events', order: 0 },+ { id: '$set', name: '$set', type: 'events', order: 1 },+ ],+ actions: [],+ filter_test_accounts: true,+ },+}diff --git a/nodejs/src/cdp/templates/index.ts b/nodejs/src/cdp/templates/index.tsindex a8e9c85e0d07..88cc6a1106d5 100644--- a/nodejs/src/cdp/templates/index.ts+++ b/nodejs/src/cdp/templates/index.ts@@ -4,6 +4,7 @@ import { HogFunctionTemplate, NativeTemplate } from '../types'import { template as accoilTemplate } from './_destinations/accoil/accoil.template'import { template as appcuesTemplate } from './_destinations/appcues/appcues.template'import { template as clickupTemplate } from './_destinations/clickup/clickup.template'+import { template as closeTemplate } from './_destinations/close/close.template'import { allComingSoonTemplates } from './_destinations/coming-soon/coming-soon-destinations.template'import { template as emailTemplate } from './_destinations/email/email.template'import { template as firebasePushTemplate } from './_destinations/firebase_push/firebase_push.template'@@ -84,6 +85,7 @@ export const HOG_FUNCTION_TEMPLATES_DESTINATIONS: HogFunctionTemplate[] = [appcuesTemplate,klimeTemplate,unifyTemplate,+ closeTemplate,]export const HOG_FUNCTION_TEMPLATES_TRANSFORMATIONS: HogFunctionTemplate[] = [