🔀 Merge branch 'feature/hubspotCRM-node' of https://github.com/RicardoE105/n8n into RicardoE105-feature/hubspotCRM-node

This commit is contained in:
Jan Oberhauser 2019-12-07 10:28:28 +01:00
commit 975856a772
7 changed files with 966 additions and 0 deletions

View file

@ -0,0 +1,17 @@
import {
ICredentialType,
NodePropertyTypes,
} from 'n8n-workflow';
export class HubspotApi implements ICredentialType {
name = 'hubspotApi';
displayName = 'Hubspot API';
properties = [
{
displayName: 'API Key',
name: 'apiKey',
type: 'string' as NodePropertyTypes,
default: '',
},
];
}

View file

@ -0,0 +1,489 @@
import { INodeProperties } from "n8n-workflow";
export const dealOperations = [
{
displayName: 'Operation',
name: 'operation',
type: 'options',
displayOptions: {
show: {
resource: [
'deal',
],
},
},
options: [
{
name: 'Create',
value: 'create',
description: 'Create a deal',
},
{
name: 'Update',
value: 'update',
description: 'Update a deal',
},
{
name: 'Get',
value: 'get',
description: 'Get a deal',
},
{
name: 'Get All',
value: 'getAll',
description: 'Get all deals',
},
{
name: 'Delete',
value: 'delete',
description: 'Delete a deals',
},
{
name: 'Recents Created',
value: 'getRecentsCreated',
description: 'Get recently created deals',
},
{
name: 'Recents Modified',
value: 'getRecentsModified',
description: 'Get recently modified deals',
},
],
default: 'create',
description: 'The operation to perform.',
},
] as INodeProperties[];
export const dealFields = [
/* -------------------------------------------------------------------------- */
/* deal:create */
/* -------------------------------------------------------------------------- */
{
displayName: 'Deal Stage',
name: 'stage',
type: 'options',
required: true,
typeOptions: {
loadOptionsMethod: 'getDealStages'
},
displayOptions: {
show: {
resource: [
'deal',
],
operation: [
'create',
],
},
},
default: '',
options: [],
description: 'The dealstage is required when creating a deal. See the CRM Pipelines API for details on managing pipelines and stages.',
},
{
displayName: 'Additional Fields',
name: 'additionalFields',
type: 'collection',
placeholder: 'Add Field',
default: {},
displayOptions: {
show: {
resource: [
'deal',
],
operation: [
'create',
],
},
},
options: [
{
displayName: 'Deal Name',
name: 'dealName',
type: 'string',
default: '',
},
{
displayName: 'Deal Stage',
name: 'dealStage',
type: 'string',
default: '',
},
{
displayName: 'Pipeline',
name: 'pipeline',
type: 'string',
default: '',
},
{
displayName: 'Close Date',
name: 'closeDate',
type: 'dateTime',
default: '',
},
{
displayName: 'Amount',
name: 'amount',
type: 'string',
default: '',
},
{
displayName: 'Deal Type',
name: 'dealType',
type: 'options',
typeOptions: {
loadOptionsMethod: 'getDealTypes',
},
default: [],
},
{
displayName: 'Associated Company',
name: 'associatedCompany',
type: 'multiOptions',
typeOptions: {
loadOptionsMethod:'getCompanies' ,
},
default: [],
},
{
displayName: 'Associated Vids',
name: 'associatedVids',
type: 'multiOptions',
typeOptions: {
loadOptionsMethod:'getContacts' ,
},
default: [],
},
]
},
/* -------------------------------------------------------------------------- */
/* deal:update */
/* -------------------------------------------------------------------------- */
{
displayName: 'Deal ID',
name: 'dealId',
type: 'string',
required: true,
displayOptions: {
show: {
resource: [
'deal',
],
operation: [
'update',
],
},
},
default: '',
description: 'Unique identifier for a particular deal',
},
{
displayName: 'Update Fields',
name: 'updateFields',
type: 'collection',
placeholder: 'Add Update Field',
default: {},
displayOptions: {
show: {
resource: [
'deal',
],
operation: [
'update',
],
},
},
options: [
{
displayName: 'Deal Name',
name: 'dealName',
type: 'string',
default: '',
},
{
displayName: 'Deal Stage',
name: 'stage',
type: 'options',
required: true,
typeOptions: {
loadOptionsMethod: 'getDealStages'
},
default: [],
description: 'The dealstage is required when creating a deal. See the CRM Pipelines API for details on managing pipelines and stages.',
},
{
displayName: 'Deal Stage',
name: 'dealStage',
type: 'string',
default: '',
},
{
displayName: 'Pipeline',
name: 'pipeline',
type: 'string',
default: '',
},
{
displayName: 'Close Date',
name: 'closeDate',
type: 'dateTime',
default: '',
},
{
displayName: 'Amount',
name: 'amount',
type: 'string',
default: '',
},
{
displayName: 'Deal Type',
name: 'dealType',
type: 'options',
typeOptions: {
loadOptionsMethod: 'getDealTypes',
},
default: [],
},
]
},
/* -------------------------------------------------------------------------- */
/* deal:get */
/* -------------------------------------------------------------------------- */
{
displayName: 'Deal ID',
name: 'dealId',
type: 'string',
required: true,
displayOptions: {
show: {
resource: [
'deal',
],
operation: [
'get',
],
},
},
default: '',
description: 'Unique identifier for a particular deal',
},
{
displayName: 'Additional Fields',
name: 'additionalFields',
type: 'collection',
placeholder: 'Add Field',
default: {},
displayOptions: {
show: {
resource: [
'deal',
],
operation: [
'get',
],
},
},
options: [
{
displayName: 'Include Property Versions ',
name: 'includePropertyVersions',
type: 'boolean',
default: false,
description: `By default, you will only get data for the most recent version of a property in the "versions" data.<br/>
If you include this parameter, you will get data for all previous versions.`,
},
]
},
/* -------------------------------------------------------------------------- */
/* deal:getAll */
/* -------------------------------------------------------------------------- */
{
displayName: 'Return All',
name: 'returnAll',
type: 'boolean',
displayOptions: {
show: {
resource: [
'deal',
],
operation: [
'getAll',
],
},
},
default: false,
description: 'If all results should be returned or only up to a given limit.',
},
{
displayName: 'Limit',
name: 'limit',
type: 'number',
displayOptions: {
show: {
resource: [
'deal',
],
operation: [
'getAll',
],
returnAll: [
false,
],
},
},
typeOptions: {
minValue: 1,
maxValue: 250,
},
default: 100,
description: 'How many results to return.',
},
{
displayName: 'Filters',
name: 'filters',
type: 'collection',
placeholder: 'Add Filter',
default: {},
displayOptions: {
show: {
resource: [
'deal',
],
operation: [
'getAll',
],
},
},
options: [
{
displayName: 'Include Associations',
name: 'includeAssociations',
type: 'boolean',
default: false,
description: `Include the IDs of the associated contacts and companies in the results<br/>.
This will also automatically include the num_associated_contacts property.`,
},
{
displayName: 'Properties',
name: 'properties',
type: 'string',
default: '',
description: `Used to include specific deal properties in the results.<br/>
By default, the results will only include Deal ID and will not include the values for any properties for your Deals.<br/>
Including this parameter will include the data for the specified property in the results.<br/>
You can include this parameter multiple times to request multiple properties separed by ,.`,
},
{
displayName: 'Properties With History',
name: 'propertiesWithHistory',
type: 'string',
default: '',
description: `Works similarly to properties=, but this parameter will include the history for the specified property,<br/>
instead of just including the current value. Use this parameter when you need the full history of changes to a property's value.`,
},
]
},
/* -------------------------------------------------------------------------- */
/* deal:delete */
/* -------------------------------------------------------------------------- */
{
displayName: 'Deal ID',
name: 'dealId',
type: 'string',
required: true,
displayOptions: {
show: {
resource: [
'deal',
],
operation: [
'delete',
],
},
},
default: '',
description: 'Unique identifier for a particular deal',
},
/* -------------------------------------------------------------------------- */
/* deal:getRecentsCreated deal:getRecentsModified */
/* -------------------------------------------------------------------------- */
{
displayName: 'Return All',
name: 'returnAll',
type: 'boolean',
displayOptions: {
show: {
resource: [
'deal',
],
operation: [
'getRecentsCreated',
'getRecentsModified',
],
},
},
default: false,
description: 'If all results should be returned or only up to a given limit.',
},
{
displayName: 'Limit',
name: 'limit',
type: 'number',
displayOptions: {
show: {
resource: [
'deal',
],
operation: [
'getRecentsCreated',
'getRecentsModified',
],
returnAll: [
false,
],
},
},
typeOptions: {
minValue: 1,
maxValue: 250,
},
default: 100,
description: 'How many results to return.',
},
{
displayName: 'Filters',
name: 'filters',
type: 'collection',
placeholder: 'Add Filter',
default: {},
displayOptions: {
show: {
resource: [
'deal',
],
operation: [
'getRecentsCreated',
'getRecentsModified',
],
},
},
options: [
{
displayName: 'Since',
name: 'since',
type: 'dateTime',
default: '',
description: `Only return deals created after timestamp x`,
},
{
displayName: 'Include Property Versions',
name: 'includePropertyVersions',
type: 'boolean',
default: false,
description: `By default, you will only get data for the most recent version of a property in the "versions" data.<br/>
If you include this parameter, you will get data for all previous versions.`,
},
]
},
] as INodeProperties[];

View file

@ -0,0 +1,12 @@
import { IDataObject } from "n8n-workflow";
export interface IAssociation {
associatedCompanyIds?: number[];
associatedVids?: number[];
}
export interface IDeal {
associations?: IAssociation;
properties?: IDataObject[];
}

View file

@ -0,0 +1,78 @@
import { OptionsWithUri } from 'request';
import {
IExecuteFunctions,
IHookFunctions,
ILoadOptionsFunctions,
IExecuteSingleFunctions
} from 'n8n-core';
import {
IDataObject,
} from 'n8n-workflow';
export async function hubspotApiRequest(this: IHookFunctions | IExecuteFunctions | IExecuteSingleFunctions | ILoadOptionsFunctions, method: string, endpoint: string, body: any = {}, query: IDataObject = {}, uri?: string): Promise<any> { // tslint:disable-line:no-any
const credentials = this.getCredentials('hubspotApi');
if (credentials === undefined) {
throw new Error('No credentials got returned!');
}
query!.hapikey = credentials.apiKey as string;
const options: OptionsWithUri = {
method,
qs: query,
uri: uri || `https://api.hubapi.com${endpoint}`,
body,
json: true,
useQuerystring: true,
};
try {
return await this.helpers.request!(options);
} catch (error) {
const errorMessage = error.response.body.message || error.response.body.Message;
if (errorMessage !== undefined) {
throw errorMessage;
}
throw error.response.body;
}
}
/**
* Make an API request to paginated hubspot endpoint
* and return all results
*/
export async function hubspotApiRequestAllItems(this: IHookFunctions | IExecuteFunctions | ILoadOptionsFunctions, propertyName: string, method: string, endpoint: string, body: any = {}, query: IDataObject = {}): Promise<any> { // tslint:disable-line:no-any
const returnData: IDataObject[] = [];
let responseData;
query.limit = 250;
query.count = 100;
do {
responseData = await hubspotApiRequest.call(this, method, endpoint, body, query);
query.offset = responseData.offset;
query['vid-offset'] = responseData['vid-offset'];
returnData.push.apply(returnData, responseData[propertyName]);
} while (
responseData['has-more'] !== undefined &&
responseData['has-more'] !== null &&
responseData['has-more'] !== false
);
return returnData;
}
export function validateJSON(json: string | undefined): any { // tslint:disable-line:no-any
let result;
try {
result = JSON.parse(json!);
} catch (exception) {
result = '';
}
return result;
}

View file

@ -0,0 +1,368 @@
import {
IExecuteFunctions,
} from 'n8n-core';
import {
IDataObject,
INodeTypeDescription,
INodeExecutionData,
INodeType,
ILoadOptionsFunctions,
INodePropertyOptions,
} from 'n8n-workflow';
import {
hubspotApiRequest,
hubspotApiRequestAllItems,
} from './GenericFunctions';
import {
dealOperations,
dealFields,
} from '../Hubspot/DealDescription';
import { IDeal, IAssociation } from './DealInterface';
export class Hubspot implements INodeType {
description: INodeTypeDescription = {
displayName: 'Hubspot',
name: 'hubspot',
icon: 'file:hubspot.png',
group: ['output'],
version: 1,
subtitle: '={{$parameter["operation"] + ": " + $parameter["resource"]}}',
description: 'Consume Hubspot API',
defaults: {
name: 'Hubspot',
color: '#356ae6',
},
inputs: ['main'],
outputs: ['main'],
credentials: [
{
name: 'hubspotApi',
required: true,
}
],
properties: [
{
displayName: 'Resource',
name: 'resource',
type: 'options',
options: [
{
name: 'Deal',
value: 'deal',
},
],
default: 'deal',
description: 'Resource to consume.',
},
// Deal
...dealOperations,
...dealFields,
],
};
methods = {
loadOptions: {
// Get all the groups to display them to user so that he can
// select them easily
async getDealStages(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
const returnData: INodePropertyOptions[] = [];
let stages;
try {
const endpoint = '/crm-pipelines/v1/pipelines/deals';
stages = await hubspotApiRequest.call(this, 'GET', endpoint, {});
stages = stages.results[0].stages;
} catch (err) {
throw new Error(`Hubspot Error: ${err}`);
}
for (const stage of stages) {
const stageName = stage.label;
const stageId = stage.stageId;
returnData.push({
name: stageName,
value: stageId,
});
}
return returnData;
},
// Get all the companies to display them to user so that he can
// select them easily
async getCompanies(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
const returnData: INodePropertyOptions[] = [];
let companies;
try {
const endpoint = '/companies/v2/companies/paged';
companies = await hubspotApiRequestAllItems.call(this, 'results', 'GET', endpoint);
} catch (err) {
throw new Error(`Hubspot Error: ${err}`);
}
for (const company of companies) {
const companyName = company.properties.name.value;
const companyId = company.companyId;
returnData.push({
name: companyName,
value: companyId,
});
}
return returnData;
},
// Get all the companies to display them to user so that he can
// select them easily
async getContacts(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
const returnData: INodePropertyOptions[] = [];
let contacts;
try {
const endpoint = '/contacts/v1/lists/all/contacts/all';
contacts = await hubspotApiRequestAllItems.call(this, 'contacts', 'GET', endpoint);
} catch (err) {
throw new Error(`Hubspot Error: ${err}`);
}
for (const contact of contacts) {
const contactName = `${contact.properties.firstname.value} ${contact.properties.lastname.value}` ;
const contactId = contact.vid;
returnData.push({
name: contactName,
value: contactId,
});
}
return returnData;
},
// Get all the deal types to display them to user so that he can
// select them easily
async getDealTypes(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
const returnData: INodePropertyOptions[] = [];
let dealTypes;
try {
const endpoint = '/properties/v1/deals/properties/named/dealtype';
dealTypes = await hubspotApiRequest.call(this, 'GET', endpoint);
} catch (err) {
throw new Error(`Hubspot Error: ${err}`);
}
for (const dealType of dealTypes.options) {
const dealTypeName = dealType.label ;
const dealTypeId = dealType.value;
returnData.push({
name: dealTypeName,
value: dealTypeId,
});
}
return returnData;
},
}
};
async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
const items = this.getInputData();
const returnData: IDataObject[] = [];
const length = items.length as unknown as number;
let responseData;
const qs: IDataObject = {};
const resource = this.getNodeParameter('resource', 0) as string;
const operation = this.getNodeParameter('operation', 0) as string;
for (let i = 0; i < length; i++) {
//https://developers.hubspot.com/docs/methods/deals/deals_overview
if (resource === 'deal') {
if (operation === 'create') {
const body: IDeal = {};
body.properties = [];
const association: IAssociation = {};
const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject;
const stage = this.getNodeParameter('stage', i) as string;
if (stage) {
// @ts-ignore
body.properties.push({
name: 'dealstage',
value: stage
});
}
if (additionalFields.associatedCompany) {
association.associatedCompanyIds = additionalFields.associatedCompany as number[];
}
if (additionalFields.associatedVids) {
association.associatedVids = additionalFields.associatedVids as number[];
}
if (additionalFields.dealName) {
// @ts-ignore
body.properties.push({
name: 'dealname',
value: additionalFields.dealName as string
});
}
if (additionalFields.closeDate) {
// @ts-ignore
body.properties.push({
name: 'closedate',
value: new Date(additionalFields.closeDate as string).getTime()
});
}
if (additionalFields.amount) {
// @ts-ignore
body.properties.push({
name: 'amount',
value: additionalFields.amount as string
});
}
if (additionalFields.dealType) {
// @ts-ignore
body.properties.push({
name: 'dealtype',
value: additionalFields.dealType as string
});
}
if (additionalFields.pipeline) {
// @ts-ignore
body.properties.push({
name: 'pipeline',
value: additionalFields.pipeline as string
});
}
body.associations = association;
try {
const endpoint = '/deals/v1/deal';
responseData = await hubspotApiRequest.call(this, 'POST', endpoint, body);
} catch (err) {
throw new Error(`Hubspot Error: ${JSON.stringify(err)}`);
}
}
if (operation === 'update') {
const body: IDeal = {};
body.properties = [];
const updateFields = this.getNodeParameter('updateFields', i) as IDataObject;
const dealId = this.getNodeParameter('dealId', i) as string;
if (updateFields.stage) {
body.properties.push({
name: 'dealstage',
value: updateFields.stage as string,
});
}
if (updateFields.dealName) {
// @ts-ignore
body.properties.push({
name: 'dealname',
value: updateFields.dealName as string
});
}
if (updateFields.closeDate) {
// @ts-ignore
body.properties.push({
name: 'closedate',
value: new Date(updateFields.closeDate as string).getTime()
});
}
if (updateFields.amount) {
// @ts-ignore
body.properties.push({
name: 'amount',
value: updateFields.amount as string
});
}
if (updateFields.dealType) {
// @ts-ignore
body.properties.push({
name: 'dealtype',
value: updateFields.dealType as string
});
}
if (updateFields.pipeline) {
// @ts-ignore
body.properties.push({
name: 'pipeline',
value: updateFields.pipeline as string
});
}
try {
const endpoint = `/deals/v1/deal/${dealId}`;
responseData = await hubspotApiRequest.call(this, 'PUT', endpoint, body);
} catch (err) {
throw new Error(`Hubspot Error: ${JSON.stringify(err)}`);
}
}
if (operation === 'get') {
const dealId = this.getNodeParameter('dealId', i) as string;
const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject;
if (additionalFields.includePropertyVersions) {
qs.includePropertyVersions = additionalFields.includePropertyVersions as boolean;
}
try {
const endpoint = `/deals/v1/deal/${dealId}`;
responseData = await hubspotApiRequest.call(this, 'GET', endpoint);
} catch (err) {
throw new Error(`Hubspot Error: ${JSON.stringify(err)}`);
}
}
if (operation === 'getAll') {
const filters = this.getNodeParameter('filters', i) as IDataObject;
const returnAll = this.getNodeParameter('returnAll', 0) as boolean;
if (filters.includeAssociations) {
qs.includeAssociations = filters.includeAssociations as boolean;
}
if (filters.properties) {
// @ts-ignore
qs.properties = filters.properties.split(',');
}
if (filters.propertiesWithHistory) {
// @ts-ignore
qs.propertiesWithHistory = filters.propertiesWithHistory.split(',');
}
try {
const endpoint = `/deals/v1/deal/paged`;
if (returnAll) {
responseData = await hubspotApiRequestAllItems.call(this, 'deals', 'GET', endpoint, {}, qs);
} else {
qs.limit = this.getNodeParameter('limit', 0) as number;
responseData = await hubspotApiRequest.call(this, 'GET', endpoint, {}, qs);
responseData = responseData.deals;
}
} catch (err) {
throw new Error(`Hubspot Error: ${JSON.stringify(err)}`);
}
}
if (operation === 'getRecentsCreated' || operation === 'getRecentsModified') {
let endpoint;
const filters = this.getNodeParameter('filters', i) as IDataObject;
const returnAll = this.getNodeParameter('returnAll', 0) as boolean;
if (filters.since) {
qs.since = new Date(filters.since as string).getTime();
}
if (filters.includePropertyVersions) {
qs.includePropertyVersions = filters.includePropertyVersions as boolean;
}
try {
if (operation === 'getRecentsCreated') {
endpoint = `/deals/v1/deal/recent/created`;
} else {
endpoint = `/deals/v1/deal/recent/modified`;
}
if (returnAll) {
responseData = await hubspotApiRequestAllItems.call(this, 'results', 'GET', endpoint, {}, qs);
} else {
qs.count = this.getNodeParameter('limit', 0) as number;
responseData = await hubspotApiRequest.call(this, 'GET', endpoint, {}, qs);
responseData = responseData.results;
}
} catch (err) {
throw new Error(`Hubspot Error: ${JSON.stringify(err)}`);
}
}
if (operation === 'delete') {
const dealId = this.getNodeParameter('dealId', i) as string;
try {
const endpoint = `/deals/v1/deal/${dealId}`;
responseData = await hubspotApiRequest.call(this, 'DELETE', endpoint);
} catch (err) {
throw new Error(`Hubspot Error: ${JSON.stringify(err)}`);
}
}
}
if (Array.isArray(responseData)) {
returnData.push.apply(returnData, responseData as IDataObject[]);
} else {
returnData.push(responseData as IDataObject);
}
}
return [this.helpers.returnJsonArray(returnData)];
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

View file

@ -41,6 +41,7 @@
"dist/credentials/HttpBasicAuth.credentials.js",
"dist/credentials/HttpDigestAuth.credentials.js",
"dist/credentials/HttpHeaderAuth.credentials.js",
"dist/credentials/HubspotApi.credentials.js",
"dist/credentials/Imap.credentials.js",
"dist/credentials/IntercomApi.credentials.js",
"dist/credentials/JiraSoftwareCloudApi.credentials.js",
@ -101,6 +102,7 @@
"dist/nodes/Google/GoogleSheets.node.js",
"dist/nodes/GraphQL/GraphQL.node.js",
"dist/nodes/HttpRequest.node.js",
"dist/nodes/Hubspot/Hubspot.node.js",
"dist/nodes/If.node.js",
"dist/nodes/Interval.node.js",
"dist/nodes/Intercom/Intercom.node.js",