n8n/packages/nodes-base/nodes/Keap/Keap.node.ts

870 lines
30 KiB
TypeScript
Raw Normal View History

import { IExecuteFunctions } from 'n8n-core';
2020-04-01 15:10:41 -07:00
import {
IBinaryKeyData,
2020-04-01 15:10:41 -07:00
IDataObject,
ILoadOptionsFunctions,
INodeExecutionData,
2020-04-01 15:10:41 -07:00
INodePropertyOptions,
INodeType,
INodeTypeDescription,
:sparkles: Improve node error handling (#1309) * Add path mapping and response error interfaces * Add error handling and throwing functionality * Refactor error handling into a single function * Re-implement error handling in Hacker News node * Fix linting details * Re-implement error handling in Spotify node * Re-implement error handling in G Suite Admin node * :construction: create basic setup NodeError * :construction: add httpCodes * :construction: add path priolist * :construction: handle statusCode in error, adjust interfaces * :construction: fixing type issues w/Ivan * :construction: add error exploration * 👔 fix linter issues * :wrench: improve object check * :construction: remove path passing from NodeApiError * :construction: add multi error + refactor findProperty method * 👔 allow any * :wrench: handle multi error message callback * :zap: change return type of callback * :zap: add customCallback to MultiError * :construction: refactor to use INode * :hammer: handle arrays, continue search after first null property found * 🚫 refactor method access * :construction: setup NodeErrorView * :zap: change timestamp to Date.now * :books: Add documentation for methods and constants * :construction: change message setting * 🚚 move NodeErrors to workflow * :sparkles: add new ErrorView for Nodes * :art: improve error notification * :art: refactor interfaces * :zap: add WorkflowOperationError, refactor error throwing * 👕 fix linter issues * :art: rename param * :bug: fix handling normal errors * :zap: add usage of NodeApiError * :art: fix throw new error instead of constructor * :art: remove unnecessary code/comments * :art: adjusted spacing + updated status messages * :art: fix tab indentation * ✨ Replace current errors with custom errors (#1576) * :zap: Introduce NodeApiError in catch blocks * :zap: Introduce NodeOperationError in nodes * :zap: Add missing errors and remove incompatible * :zap: Fix NodeOperationError in incompatible nodes * :wrench: Adjust error handling in missed nodes PayPal, FileMaker, Reddit, Taiga and Facebook Graph API nodes * :hammer: Adjust Strava Trigger node error handling * :hammer: Adjust AWS nodes error handling * :hammer: Remove duplicate instantiation of NodeApiError * :bug: fix strava trigger node error handling * Add XML parsing to NodeApiError constructor (#1633) * :bug: Remove type annotation from catch variable * :sparkles: Add XML parsing to NodeApiError * :zap: Simplify error handling in Rekognition node * :zap: Pass in XML flag in generic functions * :fire: Remove try/catch wrappers at call sites * :hammer: Refactor setting description from XML * :hammer: Refactor let to const in resource loaders * :zap: Find property in parsed XML * :zap: Change let to const * :fire: Remove unneeded try/catch block * :shirt: Fix linting issues * :bug: Fix errors from merge conflict resolution * :zap: Add custom errors to latest contributions * :shirt: Fix linting issues * :zap: Refactor MongoDB helpers for custom errors * :bug: Correct custom error type * :zap: Apply feedback to A nodes * :zap: Apply feedback to missed A node * :zap: Apply feedback to B-D nodes * :zap: Apply feedback to E-F nodes * :zap: Apply feedback to G nodes * :zap: Apply feedback to H-L nodes * :zap: Apply feedback to M nodes * :zap: Apply feedback to P nodes * :zap: Apply feedback to R nodes * :zap: Apply feedback to S nodes * :zap: Apply feedback to T nodes * :zap: Apply feedback to V-Z nodes * :zap: Add HTTP code to iterable node error * :hammer: Standardize e as error * :hammer: Standardize err as error * :zap: Fix error handling for non-standard nodes Co-authored-by: Ben Hesseldieck <b.hesseldieck@gmail.com> Co-authored-by: Ben Hesseldieck <b.hesseldieck@gmail.com> Co-authored-by: Ben Hesseldieck <1849459+BHesseldieck@users.noreply.github.com>
2021-04-16 09:33:36 -07:00
NodeOperationError,
2020-04-01 15:10:41 -07:00
} from 'n8n-workflow';
import { keapApiRequest, keapApiRequestAllItems, keysToSnakeCase } from './GenericFunctions';
2020-04-01 15:10:41 -07:00
import { contactFields, contactOperations } from './ContactDescription';
2020-04-01 15:10:41 -07:00
import { contactNoteFields, contactNoteOperations } from './ContactNoteDescription';
2020-04-01 15:10:41 -07:00
import { contactTagFields, contactTagOperations } from './ContactTagDescription';
2020-04-01 15:10:41 -07:00
import { ecommerceOrderFields, ecommerceOrderOperations } from './EcommerceOrderDescripion';
2020-04-01 15:10:41 -07:00
import { ecommerceProductFields, ecommerceProductOperations } from './EcommerceProductDescription';
2020-04-01 15:10:41 -07:00
import { emailFields, emailOperations } from './EmailDescription';
2020-04-01 15:10:41 -07:00
import { fileFields, fileOperations } from './FileDescription';
2020-04-01 15:10:41 -07:00
import { companyFields, companyOperations } from './CompanyDescription';
2020-04-01 15:10:41 -07:00
import {
IAddress,
IContact,
2020-04-01 15:10:41 -07:00
IEmailContact,
IFax,
2020-04-01 15:10:41 -07:00
IPhone,
ISocialAccount,
2020-04-01 15:10:41 -07:00
} from './ConctactInterface';
import { IAttachment, IEmail } from './EmaiIInterface';
2020-04-01 15:10:41 -07:00
import { INote } from './ContactNoteInterface';
2020-04-01 15:10:41 -07:00
import { IEcommerceOrder, IItem, IShippingAddress } from './EcommerceOrderInterface';
2020-04-01 15:10:41 -07:00
import { IEcommerceProduct } from './EcommerceProductInterface';
2020-04-01 15:10:41 -07:00
import { IFile } from './FileInterface';
2020-04-01 15:10:41 -07:00
import { ICompany } from './CompanyInterface';
2020-04-01 15:10:41 -07:00
import { capitalCase, pascalCase } from 'change-case';
2020-04-01 15:10:41 -07:00
import moment from 'moment-timezone';
2020-04-01 15:10:41 -07:00
2020-04-02 16:37:40 -07:00
export class Keap implements INodeType {
2020-04-01 15:10:41 -07:00
description: INodeTypeDescription = {
2020-04-02 16:37:40 -07:00
displayName: 'Keap',
2020-06-04 08:46:43 -07:00
name: 'keap',
refactor: Apply more `eslint-plugin-n8n-nodes-base` rules (#3534) * :zap: Update `lintfix` script * :zap: Run baseline `lintfix` * :fire: Remove unneeded exceptions (#3538) * :fire: Remove exceptions for `node-param-default-wrong-for-simplify` * :fire: Remove exceptions for `node-param-placeholder-miscased-id` * :zap: Update version * :shirt: Apply `node-param-placeholder-missing` (#3542) * :shirt: Apply `filesystem-wrong-cred-filename` (#3543) * :shirt: Apply `node-param-description-missing-from-dynamic-options` (#3545) Co-authored-by: Iván Ovejero <ivov.src@gmail.com> * :shirt: Apply `node-class-description-empty-string` (#3546) * :shirt: Apply `node-class-description-icon-not-svg` (#3548) * :shirt: Apply `filesystem-wrong-node-filename` (#3549) Co-authored-by: Iván Ovejero <ivov.src@gmail.com> * :shirt: Expand lintings to credentials (#3550) * :shirt: Apply `node-param-multi-options-type-unsorted-items` (#3552) * :zap: fix * :zap: Minor fixes Co-authored-by: Michael Kret <michael.k@radency.com> * :shirt: Apply `node-param-description-wrong-for-dynamic-multi-options` (#3541) * :zap: Add new lint rule, node-param-description-wrong-for-dynamic-multi-options * :zap: Fix with updated linting rules * :zap: Minor fixes Co-authored-by: Iván Ovejero <ivov.src@gmail.com> * :shirt: Apply `node-param-description-boolean-without-whether` (#3553) * :zap: fix * Update packages/nodes-base/nodes/Clockify/ProjectDescription.ts Co-authored-by: Iván Ovejero <ivov.src@gmail.com> * :shirt: Apply node-param-display-name-wrong-for-dynamic-multi-options (#3537) * :shirt: Add exceptions * :shirt: Add exception * :pencil2: Alphabetize rules * :zap: Restore `lintfix` command Co-authored-by: agobrech <45268029+agobrech@users.noreply.github.com> Co-authored-by: Omar Ajoue <krynble@gmail.com> Co-authored-by: Michael Kret <michael.k@radency.com> Co-authored-by: brianinoa <54530642+brianinoa@users.noreply.github.com> Co-authored-by: Michael Kret <88898367+michael-radency@users.noreply.github.com>
2022-06-20 07:54:01 -07:00
// eslint-disable-next-line n8n-nodes-base/node-class-description-icon-not-svg
2020-04-02 16:37:40 -07:00
icon: 'file:keap.png',
2020-04-01 15:10:41 -07:00
group: ['input'],
version: 1,
subtitle: '={{$parameter["operation"] + ": " + $parameter["resource"]}}',
description: 'Consume Keap API',
2020-04-01 15:10:41 -07:00
defaults: {
2020-04-02 16:37:40 -07:00
name: 'Keap',
2020-04-01 15:10:41 -07:00
},
inputs: ['main'],
outputs: ['main'],
credentials: [
{
2020-04-02 16:37:40 -07:00
name: 'keapOAuth2Api',
2020-04-01 15:10:41 -07:00
required: true,
},
],
properties: [
{
displayName: 'Resource',
name: 'resource',
type: 'options',
refactor: Apply more nodelinting rules (#3324) * :pencil2: Alphabetize lint rules * :fire: Remove duplicates * :zap: Update `lintfix` script * :shirt: Apply `node-param-operation-without-no-data-expression` (#3329) * :shirt: Apply `node-param-operation-without-no-data-expression` * :shirt: Add exceptions * :shirt: Apply `node-param-description-weak` (#3328) Co-authored-by: Iván Ovejero <ivov.src@gmail.com> * :shirt: Apply `node-param-option-value-duplicate` (#3331) * :shirt: Apply `node-param-description-miscased-json` (#3337) * :shirt: Apply `node-param-display-name-excess-inner-whitespace` (#3335) Co-authored-by: Iván Ovejero <ivov.src@gmail.com> * :shirt: Apply `node-param-type-options-missing-from-limit` (#3336) * Rule workig as intended * :pencil2: Uncomment rules Co-authored-by: Iván Ovejero <ivov.src@gmail.com> * :shirt: Apply `node-param-option-name-duplicate` (#3338) Co-authored-by: Iván Ovejero <ivov.src@gmail.com> * :shirt: Apply `node-param-description-wrong-for-simplify` (#3334) * :zap: fix * :zap: exceptions * :zap: changed rule ignoring from file to line * :shirt: Apply `node-param-resource-without-no-data-expression` (#3339) * :shirt: Apply `node-param-display-name-untrimmed` (#3341) * :shirt: Apply `node-param-display-name-miscased-id` (#3340) Co-authored-by: Iván Ovejero <ivov.src@gmail.com> * :shirt: Apply `node-param-resource-with-plural-option` (#3342) * :shirt: Apply `node-param-description-wrong-for-upsert` (#3333) * :zap: fix * :zap: replaced record with contact in description * :zap: fix Co-authored-by: Iván Ovejero <ivov.src@gmail.com> * :shirt: Apply `node-param-option-description-identical-to-name` (#3343) * :shirt: Apply `node-param-option-name-containing-star` (#3347) * :shirt: Apply `node-param-display-name-wrong-for-update-fields` (#3348) * :shirt: Apply `node-param-option-name-wrong-for-get-all` (#3345) * :zap: fix * :zap: exceptions * :shirt: Apply node-param-display-name-wrong-for-simplify (#3344) * Rule working as intended * Uncomented other rules * :shirt: Undo and add exceptions Co-authored-by: Iván Ovejero <ivov.src@gmail.com> * :zap: Alphabetize lint rules * :zap: Restore `lintfix` script Co-authored-by: Michael Kret <88898367+michael-radency@users.noreply.github.com> Co-authored-by: agobrech <45268029+agobrech@users.noreply.github.com>
2022-05-20 14:47:24 -07:00
noDataExpression: true,
2020-04-01 15:10:41 -07:00
options: [
{
name: 'Company',
value: 'company',
},
{
name: 'Contact',
value: 'contact',
},
{
name: 'Contact Note',
value: 'contactNote',
},
{
name: 'Contact Tag',
value: 'contactTag',
},
{
name: 'Ecommerce Order',
value: 'ecommerceOrder',
},
{
name: 'Ecommerce Product',
value: 'ecommerceProduct',
},
{
name: 'Email',
value: 'email',
},
{
name: 'File',
value: 'file',
},
],
default: 'company',
},
// COMPANY
...companyOperations,
...companyFields,
// CONTACT
...contactOperations,
...contactFields,
// CONTACT NOTE
...contactNoteOperations,
...contactNoteFields,
// CONTACT TAG
...contactTagOperations,
...contactTagFields,
// ECOMMERCE ORDER
...ecommerceOrderOperations,
...ecommerceOrderFields,
// ECOMMERCE PRODUCT
...ecommerceProductOperations,
...ecommerceProductFields,
// EMAIL
...emailOperations,
...emailFields,
// FILE
...fileOperations,
...fileFields,
],
};
methods = {
loadOptions: {
// Get all the tags to display them to user so that he can
// select them easily
async getTags(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
const returnData: INodePropertyOptions[] = [];
2020-04-02 16:37:40 -07:00
const tags = await keapApiRequestAllItems.call(this, 'tags', 'GET', '/tags');
2020-04-01 15:10:41 -07:00
for (const tag of tags) {
const tagName = tag.name;
const tagId = tag.id;
returnData.push({
name: tagName as string,
value: tagId as string,
});
}
return returnData;
},
// Get all the users to display them to user so that he can
// select them easily
async getUsers(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
const returnData: INodePropertyOptions[] = [];
2020-04-02 16:37:40 -07:00
const users = await keapApiRequestAllItems.call(this, 'users', 'GET', '/users');
2020-04-01 15:10:41 -07:00
for (const user of users) {
const userName = user.given_name;
const userId = user.id;
returnData.push({
name: userName as string,
value: userId as string,
});
}
return returnData;
},
// Get all the countries to display them to user so that he can
// select them easily
async getCountries(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
const returnData: INodePropertyOptions[] = [];
2020-04-02 16:37:40 -07:00
const { countries } = await keapApiRequest.call(this, 'GET', '/locales/countries');
2020-04-01 15:10:41 -07:00
for (const key of Object.keys(countries)) {
const countryName = countries[key];
const countryId = key;
returnData.push({
name: countryName as string,
value: countryId as string,
});
}
return returnData;
},
// Get all the provinces to display them to user so that he can
// select them easily
async getProvinces(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
const countryCode = this.getCurrentNodeParameter('countryCode') as string;
const returnData: INodePropertyOptions[] = [];
const { provinces } = await keapApiRequest.call(
this,
'GET',
`/locales/countries/${countryCode}/provinces`,
);
2020-04-01 15:10:41 -07:00
for (const key of Object.keys(provinces)) {
const provinceName = provinces[key];
const provinceId = key;
returnData.push({
name: provinceName as string,
value: provinceId as string,
});
}
return returnData;
},
// Get all the contact types to display them to user so that he can
// select them easily
async getContactTypes(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
const returnData: INodePropertyOptions[] = [];
2020-04-02 16:37:40 -07:00
const types = await keapApiRequest.call(this, 'GET', '/setting/contact/optionTypes');
2020-04-01 15:10:41 -07:00
for (const type of types.value.split(',')) {
const typeName = type;
const typeId = type;
returnData.push({
name: typeName,
value: typeId,
});
}
return returnData;
},
// Get all the timezones to display them to user so that he can
// select them easily
async getTimezones(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
const returnData: INodePropertyOptions[] = [];
for (const timezone of moment.tz.names()) {
const timezoneName = timezone;
const timezoneId = timezone;
returnData.push({
name: timezoneName,
value: timezoneId,
});
}
return returnData;
},
},
};
async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
const items = this.getInputData();
const returnData: IDataObject[] = [];
refactor: Apply `eslint-plugin-n8n-nodes-base` autofixable rules (#3174) * :zap: Initial setup * :shirt: Update `.eslintignore` * :shirt: Autofix node-param-default-missing (#3173) * :fire: Remove duplicate key * :shirt: Add exceptions * :package: Update package-lock.json * :shirt: Apply `node-class-description-inputs-wrong-trigger-node` (#3176) * :shirt: Apply `node-class-description-inputs-wrong-regular-node` (#3177) * :shirt: Apply `node-class-description-outputs-wrong` (#3178) * :shirt: Apply `node-execute-block-double-assertion-for-items` (#3179) * :shirt: Apply `node-param-default-wrong-for-collection` (#3180) * :shirt: Apply node-param-default-wrong-for-boolean (#3181) * Autofixed default missing * Autofixed booleans, worked well * :zap: Fix params * :rewind: Undo exempted autofixes * :package: Update package-lock.json * :shirt: Apply node-class-description-missing-subtitle (#3182) * :zap: Fix missing comma * :shirt: Apply `node-param-default-wrong-for-fixed-collection` (#3184) * :shirt: Add exception for `node-class-description-missing-subtitle` * :shirt: Apply `node-param-default-wrong-for-multi-options` (#3185) * :shirt: Apply `node-param-collection-type-unsorted-items` (#3186) * Missing coma * :shirt: Apply `node-param-default-wrong-for-simplify` (#3187) * :shirt: Apply `node-param-description-comma-separated-hyphen` (#3190) * :shirt: Apply `node-param-description-empty-string` (#3189) * :shirt: Apply `node-param-description-excess-inner-whitespace` (#3191) * Rule looks good * Add whitespace rule in eslint config * :zao: fix * :shirt: Apply `node-param-description-identical-to-display-name` (#3193) * :shirt: Apply `node-param-description-missing-for-ignore-ssl-issues` (#3195) * :rewind: Revert ":zao: fix" This reverts commit ef8a76f3dfedffd1bdccf3178af8a8d90cf5a55c. * :shirt: Apply `node-param-description-missing-for-simplify` (#3196) * :shirt: Apply `node-param-description-missing-final-period` (#3194) * Rule working as intended * Add rule to eslint * :shirt: Apply node-param-description-missing-for-return-all (#3197) * :zap: Restore `lintfix` command Co-authored-by: agobrech <45268029+agobrech@users.noreply.github.com> Co-authored-by: Omar Ajoue <krynble@gmail.com> Co-authored-by: agobrech <ael.gobrecht@gmail.com> Co-authored-by: Michael Kret <michael.k@radency.com>
2022-04-22 09:29:51 -07:00
const length = items.length;
2020-04-01 15:10:41 -07:00
const qs: IDataObject = {};
let responseData;
const resource = this.getNodeParameter('resource', 0) as string;
const operation = this.getNodeParameter('operation', 0) as string;
for (let i = 0; i < length; i++) {
if (resource === 'company') {
2020-04-02 16:37:40 -07:00
//https://developer.keap.com/docs/rest/#!/Company/createCompanyUsingPOST
2020-04-01 15:10:41 -07:00
if (operation === 'create') {
const addresses = (this.getNodeParameter('addressesUi', i) as IDataObject)
.addressesValues as IDataObject[];
const faxes = (this.getNodeParameter('faxesUi', i) as IDataObject)
.faxesValues as IDataObject[];
const phones = (this.getNodeParameter('phonesUi', i) as IDataObject)
.phonesValues as IDataObject[];
2020-04-01 15:10:41 -07:00
const companyName = this.getNodeParameter('companyName', i) as string;
const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject;
const body: ICompany = {
company_name: companyName,
};
keysToSnakeCase(additionalFields);
Object.assign(body, additionalFields);
if (addresses) {
body.address = keysToSnakeCase(addresses)[0];
}
if (faxes) {
2020-04-01 15:10:41 -07:00
body.fax_number = faxes[0];
}
if (phones) {
body.phone_number = phones[0];
}
2020-04-02 16:37:40 -07:00
responseData = await keapApiRequest.call(this, 'POST', '/companies', body);
2020-04-01 15:10:41 -07:00
}
//https://developer.infusionsoft.com/docs/rest/#!/Company/listCompaniesUsingGET
if (operation === 'getAll') {
const returnAll = this.getNodeParameter('returnAll', i) as boolean;
const options = this.getNodeParameter('options', i) as IDataObject;
keysToSnakeCase(options);
Object.assign(qs, options);
if (qs.fields) {
qs.optional_properties = qs.fields;
delete qs.fields;
}
if (returnAll) {
responseData = await keapApiRequestAllItems.call(
this,
'companies',
'GET',
'/companies',
{},
qs,
);
2020-04-01 15:10:41 -07:00
} else {
qs.limit = this.getNodeParameter('limit', i) as number;
2020-04-02 16:37:40 -07:00
responseData = await keapApiRequest.call(this, 'GET', '/companies', {}, qs);
2020-04-01 15:10:41 -07:00
responseData = responseData.companies;
}
}
}
if (resource === 'contact') {
//https://developer.infusionsoft.com/docs/rest/#!/Contact/createOrUpdateContactUsingPUT
2020-04-02 16:37:40 -07:00
if (operation === 'upsert') {
2020-04-01 15:10:41 -07:00
const duplicateOption = this.getNodeParameter('duplicateOption', i) as string;
const addresses = (this.getNodeParameter('addressesUi', i) as IDataObject)
.addressesValues as IDataObject[];
const emails = (this.getNodeParameter('emailsUi', i) as IDataObject)
.emailsValues as IDataObject[];
const faxes = (this.getNodeParameter('faxesUi', i) as IDataObject)
.faxesValues as IDataObject[];
const socialAccounts = (this.getNodeParameter('socialAccountsUi', i) as IDataObject)
.socialAccountsValues as IDataObject[];
const phones = (this.getNodeParameter('phonesUi', i) as IDataObject)
.phonesValues as IDataObject[];
2020-04-01 15:10:41 -07:00
const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject;
const body: IContact = {
duplicate_option: pascalCase(duplicateOption),
};
if (additionalFields.anniversary) {
body.anniversary = additionalFields.anniversary as string;
}
if (additionalFields.contactType) {
body.contact_type = additionalFields.contactType as string;
}
if (additionalFields.familyName) {
body.family_name = additionalFields.familyName as string;
}
if (additionalFields.givenName) {
body.given_name = additionalFields.givenName as string;
}
if (additionalFields.jobTitle) {
body.job_title = additionalFields.jobTitle as string;
}
if (additionalFields.leadSourceId) {
body.lead_source_id = additionalFields.leadSourceId as number;
}
if (additionalFields.middleName) {
body.middle_name = additionalFields.middleName as string;
}
if (additionalFields.middleName) {
body.middle_name = additionalFields.middleName as string;
}
if (additionalFields.OptInReason) {
body.opt_in_reason = additionalFields.OptInReason as string;
}
if (additionalFields.ownerId) {
body.owner_id = additionalFields.ownerId as number;
}
if (additionalFields.preferredLocale) {
body.preferred_locale = additionalFields.preferredLocale as string;
}
if (additionalFields.preferredName) {
body.preferred_name = additionalFields.preferredName as string;
}
if (additionalFields.sourceType) {
body.source_type = additionalFields.sourceType as string;
}
if (additionalFields.spouseName) {
body.spouse_name = additionalFields.spouseName as string;
}
if (additionalFields.timezone) {
body.time_zone = additionalFields.timezone as string;
}
if (additionalFields.website) {
body.website = additionalFields.website as string;
}
if (additionalFields.ipAddress) {
body.origin = { ip_address: additionalFields.ipAddress as string };
}
if (additionalFields.companyId) {
body.company = { id: additionalFields.companyId as number };
}
if (additionalFields.optInReason) {
body.opt_in_reason = additionalFields.optInReason as string;
}
2020-04-01 15:10:41 -07:00
if (addresses) {
body.addresses = keysToSnakeCase(addresses) as IAddress[];
}
if (emails) {
body.email_addresses = emails as IEmailContact[];
}
if (faxes) {
2020-04-01 15:10:41 -07:00
body.fax_numbers = faxes as IFax[];
}
if (socialAccounts) {
body.social_accounts = socialAccounts as ISocialAccount[];
}
if (phones) {
body.phone_numbers = phones as IPhone[];
}
2020-04-02 16:37:40 -07:00
responseData = await keapApiRequest.call(this, 'PUT', '/contacts', body);
2020-04-01 15:10:41 -07:00
}
//https://developer.infusionsoft.com/docs/rest/#!/Contact/deleteContactUsingDELETE
if (operation === 'delete') {
const contactId = parseInt(this.getNodeParameter('contactId', i) as string, 10);
2020-04-02 16:37:40 -07:00
responseData = await keapApiRequest.call(this, 'DELETE', `/contacts/${contactId}`);
2020-04-01 15:10:41 -07:00
responseData = { success: true };
}
//https://developer.infusionsoft.com/docs/rest/#!/Contact/getContactUsingGET
if (operation === 'get') {
const contactId = parseInt(this.getNodeParameter('contactId', i) as string, 10);
const options = this.getNodeParameter('options', i) as IDataObject;
if (options.fields) {
qs.optional_properties = options.fields as string;
}
2020-04-02 16:37:40 -07:00
responseData = await keapApiRequest.call(this, 'GET', `/contacts/${contactId}`, {}, qs);
2020-04-01 15:10:41 -07:00
}
//https://developer.infusionsoft.com/docs/rest/#!/Contact/listContactsUsingGET
if (operation === 'getAll') {
const returnAll = this.getNodeParameter('returnAll', i) as boolean;
const options = this.getNodeParameter('options', i) as IDataObject;
if (options.email) {
qs.email = options.email as boolean;
}
if (options.givenName) {
qs.given_name = options.givenName as string;
}
if (options.familyName) {
qs.family_name = options.familyName as boolean;
}
if (options.order) {
qs.order = options.order as string;
}
if (options.orderDirection) {
qs.order_direction = options.orderDirection as string;
}
if (options.since) {
qs.since = options.since as string;
}
if (options.until) {
qs.until = options.until as string;
}
if (returnAll) {
responseData = await keapApiRequestAllItems.call(
this,
'contacts',
'GET',
'/contacts',
{},
qs,
);
2020-04-01 15:10:41 -07:00
} else {
qs.limit = this.getNodeParameter('limit', i) as number;
2020-04-02 16:37:40 -07:00
responseData = await keapApiRequest.call(this, 'GET', '/contacts', {}, qs);
2020-04-01 15:10:41 -07:00
responseData = responseData.contacts;
}
}
}
if (resource === 'contactNote') {
//https://developer.infusionsoft.com/docs/rest/#!/Note/createNoteUsingPOST
if (operation === 'create') {
const userId = this.getNodeParameter('userId', i) as number;
const contactId = parseInt(this.getNodeParameter('contactId', i) as string, 10);
const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject;
const body: INote = {
user_id: userId,
contact_id: contactId,
};
keysToSnakeCase(additionalFields);
if (additionalFields.type) {
additionalFields.type = pascalCase(additionalFields.type as string);
}
Object.assign(body, additionalFields);
2020-04-02 16:37:40 -07:00
responseData = await keapApiRequest.call(this, 'POST', '/notes', body);
2020-04-01 15:10:41 -07:00
}
//https://developer.infusionsoft.com/docs/rest/#!/Note/deleteNoteUsingDELETE
if (operation === 'delete') {
const noteId = this.getNodeParameter('noteId', i) as string;
2020-04-02 16:37:40 -07:00
responseData = await keapApiRequest.call(this, 'DELETE', `/notes/${noteId}`);
2020-04-01 15:10:41 -07:00
responseData = { success: true };
}
//https://developer.infusionsoft.com/docs/rest/#!/Note/getNoteUsingGET
if (operation === 'get') {
const noteId = this.getNodeParameter('noteId', i) as string;
2020-04-02 16:37:40 -07:00
responseData = await keapApiRequest.call(this, 'GET', `/notes/${noteId}`);
2020-04-01 15:10:41 -07:00
}
//https://developer.infusionsoft.com/docs/rest/#!/Note/listNotesUsingGET
if (operation === 'getAll') {
const returnAll = this.getNodeParameter('returnAll', i) as boolean;
const filters = this.getNodeParameter('filters', i) as IDataObject;
keysToSnakeCase(filters);
Object.assign(qs, filters);
if (returnAll) {
responseData = await keapApiRequestAllItems.call(
this,
'notes',
'GET',
'/notes',
{},
qs,
);
2020-04-01 15:10:41 -07:00
} else {
qs.limit = this.getNodeParameter('limit', i) as number;
2020-04-02 16:37:40 -07:00
responseData = await keapApiRequest.call(this, 'GET', '/notes', {}, qs);
2020-04-01 15:10:41 -07:00
responseData = responseData.notes;
}
}
//https://developer.infusionsoft.com/docs/rest/#!/Note/updatePropertiesOnNoteUsingPATCH
if (operation === 'update') {
const noteId = this.getNodeParameter('noteId', i) as string;
const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject;
const body: INote = {};
keysToSnakeCase(additionalFields);
if (additionalFields.type) {
additionalFields.type = pascalCase(additionalFields.type as string);
}
Object.assign(body, additionalFields);
2020-04-02 16:37:40 -07:00
responseData = await keapApiRequest.call(this, 'PATCH', `/notes/${noteId}`, body);
2020-04-01 15:10:41 -07:00
}
}
if (resource === 'contactTag') {
//https://developer.infusionsoft.com/docs/rest/#!/Contact/applyTagsToContactIdUsingPOST
if (operation === 'create') {
const contactId = parseInt(this.getNodeParameter('contactId', i) as string, 10);
const tagIds = this.getNodeParameter('tagIds', i) as number[];
const body: IDataObject = {
tagIds,
};
responseData = await keapApiRequest.call(
this,
'POST',
`/contacts/${contactId}/tags`,
body,
);
2020-04-01 15:10:41 -07:00
}
//https://developer.infusionsoft.com/docs/rest/#!/Contact/removeTagsFromContactUsingDELETE_1
if (operation === 'delete') {
const contactId = parseInt(this.getNodeParameter('contactId', i) as string, 10);
const tagIds = this.getNodeParameter('tagIds', i) as string;
qs.ids = tagIds;
responseData = await keapApiRequest.call(
this,
'DELETE',
`/contacts/${contactId}/tags`,
{},
qs,
);
2020-04-01 15:10:41 -07:00
responseData = { success: true };
}
//https://developer.infusionsoft.com/docs/rest/#!/Contact/listAppliedTagsUsingGET
if (operation === 'getAll') {
const returnAll = this.getNodeParameter('returnAll', i) as boolean;
const contactId = parseInt(this.getNodeParameter('contactId', i) as string, 10);
if (returnAll) {
responseData = await keapApiRequestAllItems.call(
this,
'tags',
'GET',
`/contacts/${contactId}/tags`,
{},
qs,
);
2020-04-01 15:10:41 -07:00
} else {
qs.limit = this.getNodeParameter('limit', i) as number;
responseData = await keapApiRequest.call(
this,
'GET',
`/contacts/${contactId}/tags`,
{},
qs,
);
2020-04-01 15:10:41 -07:00
responseData = responseData.tags;
}
}
}
if (resource === 'ecommerceOrder') {
//https://developer.infusionsoft.com/docs/rest/#!/E-Commerce/createOrderUsingPOST
if (operation === 'create') {
const contactId = parseInt(this.getNodeParameter('contactId', i) as string, 10);
const orderDate = this.getNodeParameter('orderDate', i) as string;
const orderTitle = this.getNodeParameter('orderTitle', i) as string;
const orderType = this.getNodeParameter('orderType', i) as string;
const orderItems = (this.getNodeParameter('orderItemsUi', i) as IDataObject)
.orderItemsValues as IDataObject[];
const shippingAddress = (this.getNodeParameter('addressUi', i) as IDataObject)
.addressValues as IDataObject;
2020-04-01 15:10:41 -07:00
const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject;
const body: IEcommerceOrder = {
contact_id: contactId,
order_date: orderDate,
order_title: orderTitle,
order_type: pascalCase(orderType),
};
if (additionalFields.promoCodes) {
additionalFields.promoCodes = (additionalFields.promoCodes as string).split(
',',
) as string[];
2020-04-01 15:10:41 -07:00
}
keysToSnakeCase(additionalFields);
Object.assign(body, additionalFields);
body.order_items = keysToSnakeCase(orderItems) as IItem[];
if (shippingAddress) {
body.shipping_address = keysToSnakeCase(shippingAddress)[0] as IShippingAddress;
}
2020-04-02 16:37:40 -07:00
responseData = await keapApiRequest.call(this, 'POST', '/orders', body);
2020-04-01 15:10:41 -07:00
}
//https://developer.infusionsoft.com/docs/rest/#!/E-Commerce/deleteOrderUsingDELETE
if (operation === 'delete') {
const orderId = parseInt(this.getNodeParameter('orderId', i) as string, 10);
2020-04-02 16:37:40 -07:00
responseData = await keapApiRequest.call(this, 'DELETE', `/orders/${orderId}`);
2020-04-01 15:10:41 -07:00
responseData = { success: true };
}
//https://developer.infusionsoft.com/docs/rest/#!/E-Commerce/getOrderUsingGET
if (operation === 'get') {
const orderId = parseInt(this.getNodeParameter('orderId', i) as string, 10);
2020-04-02 16:37:40 -07:00
responseData = await keapApiRequest.call(this, 'get', `/orders/${orderId}`);
2020-04-01 15:10:41 -07:00
}
//https://developer.infusionsoft.com/docs/rest/#!/E-Commerce/listOrdersUsingGET
if (operation === 'getAll') {
const returnAll = this.getNodeParameter('returnAll', i) as boolean;
const options = this.getNodeParameter('options', i) as IDataObject;
keysToSnakeCase(options);
Object.assign(qs, options);
if (returnAll) {
responseData = await keapApiRequestAllItems.call(
this,
'orders',
'GET',
'/orders',
{},
qs,
);
2020-04-01 15:10:41 -07:00
} else {
qs.limit = this.getNodeParameter('limit', i) as number;
2020-04-02 16:37:40 -07:00
responseData = await keapApiRequest.call(this, 'GET', '/orders', {}, qs);
2020-04-01 15:10:41 -07:00
responseData = responseData.orders;
}
}
}
if (resource === 'ecommerceProduct') {
//https://developer.infusionsoft.com/docs/rest/#!/Product/createProductUsingPOST
if (operation === 'create') {
const productName = this.getNodeParameter('productName', i) as string;
const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject;
const body: IEcommerceProduct = {
product_name: productName,
};
keysToSnakeCase(additionalFields);
Object.assign(body, additionalFields);
2020-04-02 16:37:40 -07:00
responseData = await keapApiRequest.call(this, 'POST', '/products', body);
2020-04-01 15:10:41 -07:00
}
//https://developer.infusionsoft.com/docs/rest/#!/Product/deleteProductUsingDELETE
if (operation === 'delete') {
const productId = this.getNodeParameter('productId', i) as string;
2020-04-02 16:37:40 -07:00
responseData = await keapApiRequest.call(this, 'DELETE', `/products/${productId}`);
2020-04-01 15:10:41 -07:00
responseData = { success: true };
}
//https://developer.infusionsoft.com/docs/rest/#!/Product/retrieveProductUsingGET
if (operation === 'get') {
const productId = this.getNodeParameter('productId', i) as string;
2020-04-02 16:37:40 -07:00
responseData = await keapApiRequest.call(this, 'get', `/products/${productId}`);
2020-04-01 15:10:41 -07:00
}
//https://developer.infusionsoft.com/docs/rest/#!/Product/listProductsUsingGET
if (operation === 'getAll') {
const returnAll = this.getNodeParameter('returnAll', i) as boolean;
const filters = this.getNodeParameter('filters', i) as IDataObject;
keysToSnakeCase(filters);
Object.assign(qs, filters);
if (returnAll) {
responseData = await keapApiRequestAllItems.call(
this,
'products',
'GET',
'/products',
{},
qs,
);
2020-04-01 15:10:41 -07:00
} else {
qs.limit = this.getNodeParameter('limit', i) as number;
2020-04-02 16:37:40 -07:00
responseData = await keapApiRequest.call(this, 'GET', '/products', {}, qs);
2020-04-01 15:10:41 -07:00
responseData = responseData.products;
}
}
}
if (resource === 'email') {
//https://developer.infusionsoft.com/docs/rest/#!/Email/createEmailUsingPOST
if (operation === 'createRecord') {
const sentFromAddress = this.getNodeParameter('sentFromAddress', i) as string;
const sendToAddress = this.getNodeParameter('sentToAddress', i) as string;
const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject;
const body: IDataObject = {
sent_to_address: sendToAddress,
sent_from_address: sentFromAddress,
};
Object.assign(body, additionalFields);
keysToSnakeCase(body as IDataObject);
2020-04-02 16:37:40 -07:00
responseData = await keapApiRequest.call(this, 'POST', '/emails', body);
2020-04-01 15:10:41 -07:00
}
//https://developer.infusionsoft.com/docs/rest/#!/Email/deleteEmailUsingDELETE
if (operation === 'deleteRecord') {
const emailRecordId = parseInt(this.getNodeParameter('emailRecordId', i) as string, 10);
2020-04-02 16:37:40 -07:00
responseData = await keapApiRequest.call(this, 'DELETE', `/emails/${emailRecordId}`);
2020-04-01 15:10:41 -07:00
responseData = { success: true };
}
//https://developer.infusionsoft.com/docs/rest/#!/Email/listEmailsUsingGET
if (operation === 'getAll') {
const returnAll = this.getNodeParameter('returnAll', i) as boolean;
const filters = this.getNodeParameter('filters', i) as IDataObject;
keysToSnakeCase(filters);
Object.assign(qs, filters);
if (returnAll) {
responseData = await keapApiRequestAllItems.call(
this,
'emails',
'GET',
'/emails',
{},
qs,
);
2020-04-01 15:10:41 -07:00
} else {
qs.limit = this.getNodeParameter('limit', i) as number;
2020-04-02 16:37:40 -07:00
responseData = await keapApiRequest.call(this, 'GET', '/emails', {}, qs);
2020-04-01 15:10:41 -07:00
responseData = responseData.emails;
}
}
//https://developer.infusionsoft.com/docs/rest/#!/Email/deleteEmailUsingDELETE
if (operation === 'send') {
const userId = this.getNodeParameter('userId', i) as number;
const contactIds = (
(this.getNodeParameter('contactIds', i) as string).split(',') as string[]
).map((e) => parseInt(e, 10));
2020-04-01 15:10:41 -07:00
const subject = this.getNodeParameter('subject', i) as string;
const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject;
const body: IEmail = {
user_id: userId,
contacts: contactIds,
subject,
};
keysToSnakeCase(additionalFields);
Object.assign(body, additionalFields);
const attachmentsUi = this.getNodeParameter('attachmentsUi', i) as IDataObject;
let attachments: IAttachment[] = [];
if (attachmentsUi) {
if (attachmentsUi.attachmentsValues) {
keysToSnakeCase(attachmentsUi.attachmentsValues as IDataObject);
attachments = attachmentsUi.attachmentsValues as IAttachment[];
}
if (
attachmentsUi.attachmentsBinary &&
(attachmentsUi.attachmentsBinary as IDataObject).length
) {
2020-04-01 15:10:41 -07:00
if (items[i].binary === undefined) {
throw new NodeOperationError(this.getNode(), 'No binary data exists on item!', {
itemIndex: i,
});
2020-04-01 15:10:41 -07:00
}
for (const { property } of attachmentsUi.attachmentsBinary as IDataObject[]) {
const item = items[i].binary as IBinaryKeyData;
if (item[property as string] === undefined) {
throw new NodeOperationError(
this.getNode(),
`Binary data property "${property}" does not exists on item!`,
{ itemIndex: i },
);
2020-04-01 15:10:41 -07:00
}
attachments.push({
file_data: item[property as string].data,
file_name: item[property as string].fileName,
});
}
}
body.attachments = attachments;
}
2020-04-02 16:37:40 -07:00
responseData = await keapApiRequest.call(this, 'POST', '/emails/queue', body);
2020-04-01 15:10:41 -07:00
responseData = { success: true };
}
}
if (resource === 'file') {
//https://developer.infusionsoft.com/docs/rest/#!/File/deleteFileUsingDELETE
if (operation === 'delete') {
const fileId = parseInt(this.getNodeParameter('fileId', i) as string, 10);
2020-04-02 16:37:40 -07:00
responseData = await keapApiRequest.call(this, 'DELETE', `/files/${fileId}`);
2020-04-01 15:10:41 -07:00
responseData = { success: true };
}
//https://developer.infusionsoft.com/docs/rest/#!/File/listFilesUsingGET
if (operation === 'getAll') {
const returnAll = this.getNodeParameter('returnAll', i) as boolean;
const filters = this.getNodeParameter('filters', i) as IDataObject;
keysToSnakeCase(filters);
Object.assign(qs, filters);
if (qs.permission) {
qs.permission = (qs.permission as string).toUpperCase();
}
if (qs.type) {
2020-04-14 12:07:53 -07:00
qs.type = capitalCase(qs.type as string);
2020-04-01 15:10:41 -07:00
}
if (qs.viewable) {
qs.viewable = (qs.viewable as string).toUpperCase();
}
if (returnAll) {
responseData = await keapApiRequestAllItems.call(
this,
'files',
'GET',
'/files',
{},
qs,
);
2020-04-01 15:10:41 -07:00
} else {
qs.limit = this.getNodeParameter('limit', i) as number;
2020-04-02 16:37:40 -07:00
responseData = await keapApiRequest.call(this, 'GET', '/files', {}, qs);
2020-04-01 15:10:41 -07:00
responseData = responseData.files;
}
}
//https://developer.infusionsoft.com/docs/rest/#!/File/createFileUsingPOST
if (operation === 'upload') {
const binaryData = this.getNodeParameter('binaryData', i) as boolean;
const fileAssociation = this.getNodeParameter('fileAssociation', i) as string;
const isPublic = this.getNodeParameter('isPublic', i) as boolean;
const body: IFile = {
is_public: isPublic,
file_association: fileAssociation.toUpperCase(),
};
if (fileAssociation === 'contact') {
const contactId = parseInt(this.getNodeParameter('contactId', i) as string, 10);
body.contact_id = contactId;
}
if (binaryData) {
const binaryPropertyName = this.getNodeParameter('binaryPropertyName', i) as string;
if (items[i].binary === undefined) {
throw new NodeOperationError(this.getNode(), 'No binary data exists on item!', {
itemIndex: i,
});
2020-04-01 15:10:41 -07:00
}
const item = items[i].binary as IBinaryKeyData;
if (item[binaryPropertyName as string] === undefined) {
throw new NodeOperationError(
this.getNode(),
`No binary data property "${binaryPropertyName}" does not exists on item!`,
{ itemIndex: i },
);
2020-04-01 15:10:41 -07:00
}
body.file_data = item[binaryPropertyName as string].data;
body.file_name = item[binaryPropertyName as string].fileName;
} else {
const fileName = this.getNodeParameter('fileName', i) as string;
const fileData = this.getNodeParameter('fileData', i) as string;
body.file_name = fileName;
body.file_data = fileData;
}
2020-04-02 16:37:40 -07:00
responseData = await keapApiRequest.call(this, 'POST', '/files', body);
2020-04-01 15:10:41 -07:00
}
}
if (Array.isArray(responseData)) {
returnData.push.apply(returnData, responseData as IDataObject[]);
} else if (responseData !== undefined) {
returnData.push(responseData as IDataObject);
}
}
return [this.helpers.returnJsonArray(returnData)];
}
}