n8n/packages/editor-ui/src/modules/userHelpers.ts
Iván Ovejero 1db4fa2bf8
feat(Code Node): create Code node (#3965)
* Introduce node deprecation (#3930)

 Introduce node deprecation

* 🚧 Scaffold out Code node

* 👕 Fix lint

* 📘 Create types file

* 🚚 Rename theme

* 🔥 Remove unneeded prop

*  Override keybindings

*  Expand lintings

*  Create editor content getter

* 🚚 Ensure all helpers use `$`

*  Add autocompletion

*  Filter out welcome note node

*  Convey error line number

*  Highlight error line

*  Restore logging from node

*  More autocompletions

*  Streamline completions

* ✏️ Update placeholders

*  Update linter to new methods

* 🔥 Remove `$nodeItem` completions

*  Re-update placeholders

* 🎨 Fix formatting

* 📦 Update `package-lock.json`

*  Refresh with multi-line empty string

*  Account for syntax errors

* 🔥 Remove unneeded variant

*  Minor improvements

*  Add more autocompletions

* 🚚 Rename extension

* 🔥 Remove outdated comments

* 🚚 Rename field

*  More autocompletions

*  Fix up error display when empty text

* 🔥 Remove logging

*  More error validation

* 🐛 Fix `pairedItem` to `pairedItem()`

*  Add item to validation info

* 📦 Update `package-lock.json`

*  Leftover fixes

*  Set `insertNewlineAndIndent`

* 📦 Update `package-lock.json`

* 📦 Re-update `package-lock.json`

* 👕 Add lint exception

* 📘 Add type to mixin type

* Clean up comment

*  Refactor completion per new requirements

*  Adjust placeholders

*  Add `json` autocompletions for `$input`

* 🎨 Set border

*  Restore local completion source

*  Implement autocompletion for imports

*  Add `.*` to follow user typing on autocompletion

* 📘 Fix typings in autocompletions

* 👕 Add linting for use of `item()`

* 📦 Update `package-lock.json`

* 🐛 Fix for `$items(nodeName)[0]`

*  Filter down built-in modules list

*  Refactor error handling

*  Linter and validation improvements

*  Apply review feedback

* ♻️ More general refactorings

*  Add dot notation utility

* Customize input handler

*  Support `.json.` completions

*  Adjust placeholder

*  Sort imports

* 🔥 Remove blank rows addition

*  Add more error validation

* 📦 Update `package-lock.json`

*  Make date logging consistent

* 🔧 Adjust linting highlight range

*  Add line numbers to each item mode errors

*  Allow for links in error descriptions

*  More input validation

*  Expand linting to loops

*  Deprecate Function and Function Item nodes

* 🐛 Fix placeholder syntax

* 📘 Narrow down type

* 🚚 Rename using kebab-case

* 🔥 Remove `mapGetters`

* ✏️ Fix casing

*  Adjust import for type

* ✏️ Fix quotes

* 🐛 Fix `activeNode` reference

*  Use constant

* 🔥 Remove logging

* ✏️ Fix typo

*  Add missing `notice`

* ✏️ Add tags

* ✏️ Fix alias

* ✏️ Update copy

* 🔥 Remove wrong linting

* ✏️ Update copy

*  Add validation for `null`

*  Add validation for non-object and non-array

*  Add validation for non-array with json

* ✏️ Intentionally use wrong spelling

*  More validation

* ✏️ More copy updates

* ✏️ Placeholder updates

*  Restore spelling

*  Fix var name

* ✏️ More copy updates

*  Add luxon autocompletions

*  Make scrollable

*  Fix comma from merge conflict resolution

* 📦 Update `package-lock.json`

* 👕 Fix lint detail

* 🎨 Set font family

*  Bring in expressions fix

* ♻️ Address feedback

*  Exclude codemirror packages from render chunks

* 🐛 Fix placeholder not showing on first load

* feat(editor-ui): Replace `lezer` with `esprima` in client linter (#4192)

* 🔥 Remove addition from misresolved conflict

*  Replace `lezer` with `esprima` in client linter

*  Add missing key

* 📦 Update `package-lock.json`

*  Match dependencies

* 📦 Update `package-lock.json`

* 📦 Re-update `package-lock.json`

*  Match whitespace

* 🐛 Fix selection

*  Expand validation

* 🔥 Remove validation

* ✏️ Update copy

* 🚚 Move to constants

*  More `null` validation

*  Support `all()` with index to access item

*  Gloss over n8n syntax error

* 🎨 Re-style diagnostic button

* 🔥 Remove `item` as `itemAlias`

*  Add linting for `item.json` in single item mode

*  Refactor to add label info descriptions

*  More autocompletions

* 👕 Fix lint

*  Simplify typings

* feat(nodes-base): Multiline autocompletion for `code-node-editor` (#4220)

*  Simplify typings

*  Consolidate helpers in utils

*  Multiline autocompletion for standalone vars

* 🔥 Remove unneeded mixins

* ✏️ Update copy

* ✏️ Prep TODOs

*  Multiline completion for `$input.method` + `$input.item`

* 🔥 Remove unused method

* 🔥 Remove another unused method

* 🚚 Move luxon strings to helpers

*  Multiline autocompletion for methods output

*  Refactor to use optional chaining

* 👕 Fix lint

* ✏️ Update TODOs

*  Multiline autocompletion for `json` fields

* 📘 Add typings

*  De-duplicate callback to forEach

* 🐛 Fix autocompletions not working with leading whitespace

* 🌐 Apply i18n

* 👕 Fix lint

* :constructor: Second-period var usage completions

* 👕 Fix lint

* 👕 Add exception

*  Add completion telemetry

* 📘 Add typing

*  Major refactoring to organize

* 🐛 Fix multiline `.all()[index]`

* 🐛 Do not autoclose square brackets prior to `.json`

* 🐛 Fix accessor for multiline `jsonField` completions

*  Add completions for half-assignments

* 🐛 Fix `jsonField` completions for `x.json`

* ✏️ Improve comments

* 🐛 Fix `.json[field]` for multiline matches

*  Cleanup

* 📦 Update `package-lock.json`

* 👕 Fix lint

* 🐛 Rely on original value for custom matcher

*  Create `customMatcherJsonFieldCompletions` to simplify setup

* 🐛 Include selector in `customMatcherJsonField` completions

* ✏️ Make naming consistent

* ✏️ Add docline

*  Finish self-review cleanup

* 🔥 Remove outdated comment

* 📌 Pin luxon to major-minor

* ✏️ Fix typo

* 📦 Update `package-lock.json`

* 📦 Update `package-lock.json`

* 📦 Re-update `package-lock.json`

*  Add `luxon` for Gmail node

* 📦 Update `package-lock.json`

*  Replace Function with Code in suggested nodes

* 🐛 Fix `$prevNode` completions

* ✏️ Update `$execution.mode` copy

*  Separate luxon getters from methods

*  Adjusting linter to tolerate `.binary`

*  Adjust top-level item keys check

*  Anticipate user expecting `item` to pre-exist

*  Add linting for legacy item access

*  Add hint for attempted `items` access

*  Add keybinding for toggling comments

* ✏️ Update copy of `all`, `first`, `last` and `itemMatching`

* 🐛 Make `input.all()` etc act on copies

* 📦 Update `package-lock.json`

* 🐛 Fix guard in `$input.last()`

* ♻️ Address Jan's feedback

* ⬆️ Upgrade `eslint-plugin-n8n-nodes-base`

* 📦 Update `package-lock.json`

* 🔥 Remove unneeded exceptions

*  Restore placeholder logic

*  Add placeholders to client

*  Account for shadow item

* ✏️ More completion info labels

* 👕 Fix lint

* ✏️ Update copy

* ✏️ Update copy

* ✏️ More copy updates

* 📦 Update `package-lock.json`

*  Add more validation

*  Add placheolder on first load

* Replace `Cmd` with `Mod`

* 📦 Update `package-lock.json`
2022-10-13 14:28:02 +02:00

330 lines
11 KiB
TypeScript

import { CALENDLY_TRIGGER_NODE_TYPE, CLEARBIT_NODE_TYPE, COMPANY_SIZE_1000_OR_MORE, COMPANY_SIZE_500_999, CRON_NODE_TYPE, ELASTIC_SECURITY_NODE_TYPE, EMAIL_SEND_NODE_TYPE, EXECUTE_COMMAND_NODE_TYPE, FINANCE_WORK_AREA, GITHUB_TRIGGER_NODE_TYPE, HTTP_REQUEST_NODE_TYPE, IF_NODE_TYPE, ITEM_LISTS_NODE_TYPE, IT_ENGINEERING_WORK_AREA, JIRA_TRIGGER_NODE_TYPE, MICROSOFT_EXCEL_NODE_TYPE, MICROSOFT_TEAMS_NODE_TYPE, PAGERDUTY_NODE_TYPE, PRODUCT_WORK_AREA, QUICKBOOKS_NODE_TYPE, SALESFORCE_NODE_TYPE, SALES_BUSINESSDEV_WORK_AREA, SECURITY_WORK_AREA, SEGMENT_NODE_TYPE, SET_NODE_TYPE, SLACK_NODE_TYPE, SPREADSHEET_FILE_NODE_TYPE, SWITCH_NODE_TYPE, WEBHOOK_NODE_TYPE, XERO_NODE_TYPE, COMPANY_SIZE_KEY, WORK_AREA_KEY, CODING_SKILL_KEY, COMPANY_TYPE_KEY, ECOMMERCE_COMPANY_TYPE, MSP_COMPANY_TYPE, PERSONAL_COMPANY_TYPE, AUTOMATION_GOAL_KEY, OTHER_AUTOMATION_GOAL, NOT_SURE_YET_GOAL, CUSTOMER_INTEGRATIONS_GOAL, CUSTOMER_SUPPORT_GOAL, FINANCE_ACCOUNTING_GOAL, ZENDESK_TRIGGER_NODE_TYPE, WOOCOMMERCE_TRIGGER_NODE_TYPE, SALES_MARKETING_GOAL, HUBSPOT_TRIGGER_NODE_TYPE, HR_GOAL, WORKABLE_TRIGGER_NODE_TYPE, OPERATIONS_GOAL, PRODUCT_GOAL, NOTION_TRIGGER_NODE_TYPE, SECURITY_GOAL, THE_HIVE_TRIGGER_NODE_TYPE, ZENDESK_NODE_TYPE, SERVICENOW_NODE_TYPE, JIRA_NODE_TYPE, BAMBOO_HR_NODE_TYPE, GOOGLE_SHEETS_NODE_TYPE, CODE_NODE_TYPE } from '@/constants';
import { IPermissions, IPersonalizationSurveyAnswersV1, IPersonalizationSurveyAnswersV2, IPersonalizationSurveyAnswersV3, IPersonalizationSurveyVersions, IUser } from '@/Interface';
import { ILogInStatus, IRole, IUserPermissions } from "@/Interface";
function isPersonalizationV2OrV3(data: IPersonalizationSurveyVersions): data is IPersonalizationSurveyAnswersV2 | IPersonalizationSurveyAnswersV3 {
return "version" in data;
}
export const ROLE: {Owner: IRole, Member: IRole, Default: IRole} = {
Owner: 'owner',
Member: 'member',
Default: 'default', // default user with no email when setting up instance
};
export const LOGIN_STATUS: {LoggedIn: ILogInStatus, LoggedOut: ILogInStatus} = {
LoggedIn: 'LoggedIn', // Can be owner or member or default user
LoggedOut: 'LoggedOut', // Can only be logged out if UM has been setup
};
export const PERMISSIONS: IUserPermissions = {
TAGS: {
CAN_DELETE_TAGS: {
allow: {
role: [ROLE.Owner, ROLE.Default],
},
},
},
PRIMARY_MENU: {
CAN_ACCESS_USER_INFO: {
allow: {
loginStatus: [LOGIN_STATUS.LoggedIn],
},
deny: {
role: [ROLE.Default],
},
},
},
USER_SETTINGS: {
VIEW_UM_SETUP_WARNING: {
allow: {
role: [ROLE.Default],
},
},
},
};
/**
* To be authorized, user must pass all deny rules and pass any of the allow rules.
*
*/
export const isAuthorized = (permissions: IPermissions, currentUser: IUser | null): boolean => {
const loginStatus = currentUser ? LOGIN_STATUS.LoggedIn : LOGIN_STATUS.LoggedOut;
// big AND block
// if any of these are false, block user
if (permissions.deny) {
if (permissions.deny.shouldDeny && permissions.deny.shouldDeny()) {
return false;
}
if (permissions.deny.loginStatus && permissions.deny.loginStatus.includes(loginStatus)) {
return false;
}
if (currentUser && currentUser.globalRole) {
const role = currentUser.isDefaultUser ? ROLE.Default : currentUser.globalRole.name;
if (permissions.deny.role && permissions.deny.role.includes(role)) {
return false;
}
}
else if (permissions.deny.role) {
return false;
}
}
// big OR block
// if any of these are true, allow user
if (permissions.allow) {
if (permissions.allow.shouldAllow && permissions.allow.shouldAllow()) {
return true;
}
if (permissions.allow.loginStatus && permissions.allow.loginStatus.includes(loginStatus)) {
return true;
}
if (currentUser && currentUser.globalRole) {
const role = currentUser.isDefaultUser ? ROLE.Default : currentUser.globalRole.name;
if (permissions.allow.role && permissions.allow.role.includes(role)) {
return true;
}
}
}
return false;
};
export function getPersonalizedNodeTypes(answers: IPersonalizationSurveyAnswersV1 | IPersonalizationSurveyAnswersV2 | IPersonalizationSurveyAnswersV3 | null): string[] {
if (!answers) {
return [];
}
if (isPersonalizationV2OrV3(answers)) {
return getPersonalizationV2(answers);
}
return getPersonalizationV1(answers);
}
export function getAccountAge(currentUser: IUser): number {
if(currentUser.createdAt) {
const accountCreatedAt = new Date(currentUser.createdAt);
const today = new Date();
return Math.ceil((today.getTime() - accountCreatedAt.getTime()) / (1000* 3600 * 24));
}
return -1;
}
function getPersonalizationV2(answers: IPersonalizationSurveyAnswersV2 | IPersonalizationSurveyAnswersV3) {
let nodeTypes: string[] = [];
const {version, ...data} = answers;
if (Object.keys(data).length === 0) {
return [];
}
const companySize = answers[COMPANY_SIZE_KEY];
const companyType = answers[COMPANY_TYPE_KEY];
const automationGoal = answers[AUTOMATION_GOAL_KEY];
let codingSkill = null;
if (CODING_SKILL_KEY in answers && answers[CODING_SKILL_KEY]) {
codingSkill = parseInt(answers[CODING_SKILL_KEY] as string, 10);
codingSkill = isNaN(codingSkill)? 0 : codingSkill;
}
// slot 1 trigger
if (companyType === ECOMMERCE_COMPANY_TYPE) {
nodeTypes = nodeTypes.concat(WOOCOMMERCE_TRIGGER_NODE_TYPE);
} else if (companyType === MSP_COMPANY_TYPE) {
nodeTypes = nodeTypes.concat(JIRA_TRIGGER_NODE_TYPE);
} else if((companyType === PERSONAL_COMPANY_TYPE || automationGoal === OTHER_AUTOMATION_GOAL || automationGoal === NOT_SURE_YET_GOAL) && codingSkill !== null && codingSkill >= 4) {
nodeTypes = nodeTypes.concat(WEBHOOK_NODE_TYPE);
} else if((companyType === PERSONAL_COMPANY_TYPE || automationGoal === OTHER_AUTOMATION_GOAL || automationGoal === NOT_SURE_YET_GOAL) && codingSkill !== null && codingSkill < 3) {
nodeTypes = nodeTypes.concat(CRON_NODE_TYPE);
} else if (automationGoal === CUSTOMER_INTEGRATIONS_GOAL) {
nodeTypes = nodeTypes.concat(WEBHOOK_NODE_TYPE);
} else if (automationGoal === CUSTOMER_SUPPORT_GOAL || automationGoal === FINANCE_ACCOUNTING_GOAL) {
nodeTypes = nodeTypes.concat(ZENDESK_TRIGGER_NODE_TYPE);
} else if (automationGoal === SALES_MARKETING_GOAL) {
nodeTypes = nodeTypes.concat(HUBSPOT_TRIGGER_NODE_TYPE);
} else if (automationGoal === HR_GOAL) {
nodeTypes = nodeTypes.concat(WORKABLE_TRIGGER_NODE_TYPE);
} else if (automationGoal === OPERATIONS_GOAL) {
nodeTypes = nodeTypes.concat(CRON_NODE_TYPE);
} else if (automationGoal === PRODUCT_GOAL) {
nodeTypes = nodeTypes.concat(NOTION_TRIGGER_NODE_TYPE);
} else if (automationGoal === SECURITY_GOAL) {
nodeTypes = nodeTypes.concat(THE_HIVE_TRIGGER_NODE_TYPE);
} else {
nodeTypes = nodeTypes.concat(WEBHOOK_NODE_TYPE);
}
// slot 2 data transformation
if (codingSkill !== null && codingSkill >= 4) {
nodeTypes = nodeTypes.concat(CODE_NODE_TYPE);
} else {
nodeTypes = nodeTypes.concat(ITEM_LISTS_NODE_TYPE);
}
// slot 3 logic node
if (codingSkill !== null && codingSkill < 3) {
nodeTypes = nodeTypes.concat(IF_NODE_TYPE);
}
else {
nodeTypes = nodeTypes.concat(SWITCH_NODE_TYPE);
}
// slot 4 use case #1
if (companySize === COMPANY_SIZE_500_999 || companySize === COMPANY_SIZE_1000_OR_MORE) {
switch (automationGoal) {
case CUSTOMER_INTEGRATIONS_GOAL:
nodeTypes = nodeTypes.concat(HTTP_REQUEST_NODE_TYPE);
break;
case CUSTOMER_SUPPORT_GOAL:
nodeTypes = nodeTypes.concat(ZENDESK_NODE_TYPE);
break;
case SALES_MARKETING_GOAL:
nodeTypes = nodeTypes.concat(SALESFORCE_NODE_TYPE);
break;
case HR_GOAL:
nodeTypes = nodeTypes.concat(SERVICENOW_NODE_TYPE);
break;
case PRODUCT_GOAL:
nodeTypes = nodeTypes.concat(JIRA_NODE_TYPE);
break;
case FINANCE_ACCOUNTING_GOAL:
nodeTypes = nodeTypes.concat(SPREADSHEET_FILE_NODE_TYPE);
break;
case SECURITY_GOAL:
nodeTypes = nodeTypes.concat(ELASTIC_SECURITY_NODE_TYPE);
break;
default:
nodeTypes = nodeTypes.concat(SLACK_NODE_TYPE);
}
} else {
switch (automationGoal) {
case CUSTOMER_INTEGRATIONS_GOAL:
nodeTypes = nodeTypes.concat(HTTP_REQUEST_NODE_TYPE);
break;
case CUSTOMER_SUPPORT_GOAL:
nodeTypes = nodeTypes.concat(ZENDESK_NODE_TYPE);
break;
case FINANCE_ACCOUNTING_GOAL:
nodeTypes = nodeTypes.concat(QUICKBOOKS_NODE_TYPE);
break;
case HR_GOAL:
nodeTypes = nodeTypes.concat(BAMBOO_HR_NODE_TYPE);
break;
case PRODUCT_GOAL:
nodeTypes = nodeTypes.concat(JIRA_NODE_TYPE);
break;
case SALES_MARKETING_GOAL:
nodeTypes = nodeTypes.concat(GOOGLE_SHEETS_NODE_TYPE);
break;
case SECURITY_GOAL:
nodeTypes = nodeTypes.concat(ELASTIC_SECURITY_NODE_TYPE);
break;
default:
nodeTypes = nodeTypes.concat(SLACK_NODE_TYPE);
}
}
// slot 4
nodeTypes = nodeTypes.concat(SET_NODE_TYPE);
return nodeTypes;
}
function getPersonalizationV1(answers: IPersonalizationSurveyAnswersV1) {
const companySize = answers[COMPANY_SIZE_KEY];
const workArea = answers[WORK_AREA_KEY];
function isWorkAreaAnswer(name: string) {
if (Array.isArray(workArea)) {
return workArea.includes(name);
} else {
return workArea === name;
}
}
const workAreaIsEmpty = !workArea|| workArea.length === 0;
if (companySize === null && workAreaIsEmpty && answers[CODING_SKILL_KEY] === null) {
return [];
}
let codingSkill = null;
if (answers[CODING_SKILL_KEY]) {
codingSkill = parseInt(answers[CODING_SKILL_KEY] as string, 10);
codingSkill = isNaN(codingSkill)? 0 : codingSkill;
}
let nodeTypes = [] as string[];
if (isWorkAreaAnswer(IT_ENGINEERING_WORK_AREA)) {
nodeTypes = nodeTypes.concat(WEBHOOK_NODE_TYPE);
}
else {
nodeTypes = nodeTypes.concat(CRON_NODE_TYPE);
}
if (codingSkill !== null && codingSkill >= 4) {
nodeTypes = nodeTypes.concat(CODE_NODE_TYPE);
}
else {
nodeTypes = nodeTypes.concat(ITEM_LISTS_NODE_TYPE);
}
if (codingSkill !== null && codingSkill < 3) {
nodeTypes = nodeTypes.concat(IF_NODE_TYPE);
}
else {
nodeTypes = nodeTypes.concat(SWITCH_NODE_TYPE);
}
if (companySize === COMPANY_SIZE_500_999 || companySize === COMPANY_SIZE_1000_OR_MORE) {
if (isWorkAreaAnswer(SALES_BUSINESSDEV_WORK_AREA)) {
nodeTypes = nodeTypes.concat(SALESFORCE_NODE_TYPE);
}
else if (isWorkAreaAnswer(SECURITY_WORK_AREA)) {
nodeTypes = nodeTypes.concat([ELASTIC_SECURITY_NODE_TYPE, HTTP_REQUEST_NODE_TYPE]);
}
else if (isWorkAreaAnswer(PRODUCT_WORK_AREA)) {
nodeTypes = nodeTypes.concat([JIRA_TRIGGER_NODE_TYPE, SEGMENT_NODE_TYPE]);
}
else if (isWorkAreaAnswer(IT_ENGINEERING_WORK_AREA)) {
nodeTypes = nodeTypes.concat([GITHUB_TRIGGER_NODE_TYPE, HTTP_REQUEST_NODE_TYPE]);
}
else {
nodeTypes = nodeTypes.concat([MICROSOFT_EXCEL_NODE_TYPE, MICROSOFT_TEAMS_NODE_TYPE]);
}
}
else {
if (isWorkAreaAnswer(SALES_BUSINESSDEV_WORK_AREA)) {
nodeTypes = nodeTypes.concat(CLEARBIT_NODE_TYPE);
}
else if (isWorkAreaAnswer(SECURITY_WORK_AREA)) {
nodeTypes = nodeTypes.concat([PAGERDUTY_NODE_TYPE, HTTP_REQUEST_NODE_TYPE]);
}
else if (isWorkAreaAnswer(PRODUCT_WORK_AREA)) {
nodeTypes = nodeTypes.concat([JIRA_TRIGGER_NODE_TYPE, CALENDLY_TRIGGER_NODE_TYPE]);
}
else if (isWorkAreaAnswer(IT_ENGINEERING_WORK_AREA)) {
nodeTypes = nodeTypes.concat([EXECUTE_COMMAND_NODE_TYPE, HTTP_REQUEST_NODE_TYPE]);
}
else if (isWorkAreaAnswer(FINANCE_WORK_AREA)) {
nodeTypes = nodeTypes.concat([XERO_NODE_TYPE, QUICKBOOKS_NODE_TYPE, SPREADSHEET_FILE_NODE_TYPE]);
}
else {
nodeTypes = nodeTypes.concat([EMAIL_SEND_NODE_TYPE, SLACK_NODE_TYPE]);
}
}
nodeTypes = nodeTypes.concat(SET_NODE_TYPE);
return nodeTypes;
}