Skip to content

Commit

Permalink
feat: modified group call to attach user and add tags to company
Browse files Browse the repository at this point in the history
  • Loading branch information
manish339k committed Jun 10, 2024
1 parent 1bd9372 commit 55ba5fa
Show file tree
Hide file tree
Showing 7 changed files with 418 additions and 24 deletions.
4 changes: 2 additions & 2 deletions src/cdk/v2/destinations/intercom/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const BASE_AU_ENDPOINT = 'https://api.au.intercom.io';

const SEARCH_CONTACT_ENDPOINT = 'contacts/search';
const CREATE_OR_UPDATE_COMPANY_ENDPOINT = 'companies';
const TAGS = 'tags';
const TAGS_ENDPOINT = 'tags';

const ReservedAttributes = {
v1UserAttributes: [
Expand Down Expand Up @@ -79,5 +79,5 @@ module.exports = {
SEARCH_CONTACT_ENDPOINT,
ReservedCompanyProperties,
CREATE_OR_UPDATE_COMPANY_ENDPOINT,
TAGS,
TAGS_ENDPOINT,
};
25 changes: 23 additions & 2 deletions src/cdk/v2/destinations/intercom/procWorkflow.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ bindings:
- name: addExternalIdToTraits
path: ../../../../v0/util
- path: ../../bindings/jsontemplate
- name: HTTP_STATUS_CODES
path: ../../../../v0/util/constant

steps:
- name: checkIfProcessed
Expand Down Expand Up @@ -178,18 +180,21 @@ steps:
const contactId = $.outputs.searchContact;
const companyId = await $.createOrUpdateCompany($.context.payload, .destination);
$.assert(companyId, "Unable to create or update company");
await $.addOrUpdateTagToCompany(.message, .destination, companyId);
$.context.payload = {
id: companyId,
};
$.context.endpoint = $.getBaseEndpoint(.destination) + "/" + "contacts" + "/" + contactId + "/" + "companies";
const payload = $.context.payload;
const endpoint = $.context.endpoint;
await $.attachContactToCompany(payload, endpoint, .destination);
await $.addOrUpdateTagsToCompany(.message, .destination, companyId);
else:
name: whenSearchContactNotFound
template: |
const companyId = await $.createOrUpdateCompany($.context.payload, .destination);
$.assert(companyId, "Unable to create or update company");
await $.addOrUpdateTagToCompany(.message, .destination, companyId);
$.context.endpoint = $.getBaseEndpoint(.destination) + "/" + "companies";
await $.addOrUpdateTagsToCompany(.message, .destination, companyId);
- name: prepareFinalPayload
template: |
$.context.requestMethod = 'POST';
Expand All @@ -212,9 +217,25 @@ steps:
response.method = "POST";
response.userId = .message.anonymousId;
$.context.response.push(response);
payload = response.body.JSON;
const companyId = await $.createOrUpdateCompany(payload, .destination);
$.assert(companyId, "Unable to create or update company");
const attachUserAndCompanyResponse = $.attachUserAndCompany(.message, .destination.Config);
attachUserAndCompanyResponse ? attachUserAndCompanyResponse.userId = .message.anonymousId;
attachUserAndCompanyResponse ? $.context.response.push(attachUserAndCompanyResponse);
payload = attachUserAndCompanyResponse.body.JSON;
let endpoint = attachUserAndCompanyResponse.endpoint;
attachUserAndCompanyResponse ? await $.attachContactToCompany(payload, endpoint, .destination);
await $.addOrUpdateTagsToCompany(.message, .destination, companyId);
- name: statusCode
condition: $.outputs.messageType === {{$.EventType.GROUP}}
template: |
$.HTTP_STATUS_CODES.SUPPRESS_EVENTS
else:
name: successStatusCode
template: |
$.HTTP_STATUS_CODES.OK
- name: buildResponseForProcessTransformation
description: Build response for multiple transformed event
Expand Down
2 changes: 1 addition & 1 deletion src/cdk/v2/destinations/intercom/rtWorkflow.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ steps:
"batched": false,
"destination": ^[idx].destination,
"metadata": ^[idx].metadata[],
"statusCode": 200
"statusCode": .outputs.statusCode
})[]
- name: failedEvents
template: |
Expand Down
68 changes: 60 additions & 8 deletions src/cdk/v2/destinations/intercom/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ const {
SEARCH_CONTACT_ENDPOINT,
ReservedCompanyProperties,
CREATE_OR_UPDATE_COMPANY_ENDPOINT,
TAGS,
TAGS_ENDPOINT,
} = require('./config');

/**
Expand Down Expand Up @@ -286,7 +286,8 @@ const searchContact = async (message, destination) => {
* @returns
*/
const createOrUpdateCompany = async (payload, destination) => {
const headers = getHeaders(destination);
const { apiVersion } = destination.Config;
const headers = getHeaders(destination, apiVersion);
const finalPayload = JSON.stringify(removeUndefinedAndNullValues(payload));
const baseEndPoint = getBaseEndpoint(destination);
const endpoint = `${baseEndPoint}/${CREATE_OR_UPDATE_COMPANY_ENDPOINT}`;
Expand Down Expand Up @@ -371,18 +372,68 @@ const addMetadataToPayload = (payload) => {
};

/**
* Add or Update tags to a company
* Api call to attach user to the company
* Ref doc v1: https://developers.intercom.com/docs/references/1.4/rest-api/users/companies-and-users/
* Ref doc v2: https://developers.intercom.com/docs/references/2.10/rest-api/api.intercom.io/Contacts/attachContactToACompany/
* @param {*} payload
* @param {*} endpoint
* @param {*} destination
*/
const attachContactToCompany = async (payload, endpoint, destination) => {
let { apiVersion } = destination.Config;
apiVersion = isDefinedAndNotNull(apiVersion) ? apiVersion : 'v2';
let endpointPath = '/contact/{id}/companies';
if (apiVersion === 'v1') {
endpointPath = '/users';
}
const headers = getHeaders(destination, apiVersion);
const finalPayload = JSON.stringify(removeUndefinedAndNullValues(payload));
const response = await httpPOST(
endpoint,
finalPayload,
{
headers,
},
{
destType: 'intercom',
feature: 'transformation',
endpointPath,
requestMethod: 'POST',
module: 'router',
},
);

const processedResponse = processAxiosResponse(response);
if (!isHttpStatusSuccess(processedResponse.status)) {
throw new NetworkError(

Check warning on line 408 in src/cdk/v2/destinations/intercom/utils.js

View check run for this annotation

Codecov / codecov/patch

src/cdk/v2/destinations/intercom/utils.js#L408

Added line #L408 was not covered by tests
`Unable to attach Contact to Company due to : ${JSON.stringify(
processedResponse?.response?.errors,
)}`,
processedResponse?.status,
{
[tags]: getDynamicErrorType(processedResponse?.status),
},
processedResponse,
);
}
};

/**
* Api calls to add or update tags to the company
* Ref doc v1: https://developers.intercom.com/docs/references/1.4/rest-api/tags/tag-or-untag-users-companies-leads-contacts/
* Ref doc v2: https://developers.intercom.com/docs/references/2.10/rest-api/api.intercom.io/Tags/createTag/
* @param message
* @param destination
* @param id
* @returns
*/
const addOrUpdateTagToCompany = async (message, destination, id) => {
const companyTags = message?.traits?.tags || message?.context?.traits?.tags;
const addOrUpdateTagsToCompany = async (message, destination, id) => {
const companyTags = message?.context?.traits?.tags;
if (!companyTags) return;
const headers = getHeaders(destination);
const { apiVersion } = destination.Config;
const headers = getHeaders(destination, apiVersion);
const baseEndPoint = getBaseEndpoint(destination);
const endpoint = `${baseEndPoint}/${TAGS}`;
const endpoint = `${baseEndPoint}/${TAGS_ENDPOINT}`;
const statTags = {
destType: 'intercom',
feature: 'transformation',
Expand Down Expand Up @@ -438,5 +489,6 @@ module.exports = {
filterCustomAttributes,
checkIfEmailOrUserIdPresent,
separateReservedAndRestMetadata,
addOrUpdateTagToCompany,
attachContactToCompany,
addOrUpdateTagsToCompany,
};
23 changes: 14 additions & 9 deletions src/cdk/v2/destinations/intercom/utils.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ const {
filterCustomAttributes,
checkIfEmailOrUserIdPresent,
separateReservedAndRestMetadata,
addOrUpdateTagToCompany,
attachContactToCompany,
addOrUpdateTagsToCompany,
} = require('./utils');
const { BASE_ENDPOINT, BASE_EU_ENDPOINT, BASE_AU_ENDPOINT } = require('./config');

Expand Down Expand Up @@ -765,11 +766,13 @@ describe('attachUserAndCompany utility test', () => {
});
});

describe('addOrUpdateTagToCompany utility test', () => {
describe('addOrUpdateTagsToCompany utility test', () => {
it('Should successfully add tags to company', async () => {
const message = {
traits: {
tags: ['tag1', 'tag2'],
context: {
traits: {
tags: ['tag1', 'tag2'],
},
},
};
const destination = { Config: { apiKey: 'testApiKey', apiServer: 'us' } };
Expand All @@ -786,7 +789,7 @@ describe('addOrUpdateTagToCompany utility test', () => {
});

axios.post.mockClear();
await addOrUpdateTagToCompany(message, destination, id);
await addOrUpdateTagsToCompany(message, destination, id);

expect(axios.post).toHaveBeenCalledTimes(2);

Expand All @@ -809,8 +812,10 @@ describe('addOrUpdateTagToCompany utility test', () => {

it('Should throw an error in case if axios calls returns an error', async () => {
const message = {
traits: {
tags: ['tag1'],
context: {
traits: {
tags: ['tag1'],
},
},
};
const destination = { Config: { apiKey: 'testApiKey', apiServer: 'us' } };
Expand All @@ -832,7 +837,7 @@ describe('addOrUpdateTagToCompany utility test', () => {

try {
axios.post.mockClear();
await addOrUpdateTagToCompany(message, destination, id);
await addOrUpdateTagsToCompany(message, destination, id);
} catch (error) {
expect(error.message).toEqual(
`Unable to Add or Update the Tag to Company due to : [{"code":"unauthorized","message":"Access Token Invalid"}]`,
Expand All @@ -846,7 +851,7 @@ describe('addOrUpdateTagToCompany utility test', () => {
const id = 'companyId';

axios.post.mockClear();
await addOrUpdateTagToCompany(message, destination, id);
await addOrUpdateTagsToCompany(message, destination, id);

expect(axios.post).not.toHaveBeenCalled();
});
Expand Down
Loading

0 comments on commit 55ba5fa

Please sign in to comment.