EspoCRM – Open Source CRM Application
PHP calendarcontactscrmcrm-platformcrm-systemcustomer-portalcustomer-supportcustomizabledocumentsemail-marketingkanbanleadsopen-sourcephpplatformsales-automationsingle-page-applicationsupport
TS migration
Yuriiac76cd4fc676
diff --git a/client/src/views/fields/email.js b/client/src/views/fields/email.tssimilarity index 62%rename from client/src/views/fields/email.jsrename to client/src/views/fields/email.tsindex 6b9d855ac6..f03640c29f 100644--- a/client/src/views/fields/email.js+++ b/client/src/views/fields/email.ts@@ -26,280 +26,76 @@* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.************************************************************************/-/** @module views/fields/email */-import VarcharFieldView from 'views/fields/varchar';import MailtoHelper from 'helpers/misc/mailto';import Autocomplete from 'ui/autocomplete';+import {BaseOptions, BaseParams, BaseViewSchema, FieldValidator} from 'views/fields/base';+import Ui from 'ui';+import Ajax from 'ajax';/**- * @extends VarcharFieldView<module:views/fields/email~params>+ * Parameters.*/-class EmailFieldView extends VarcharFieldView {-- /**- * @typedef {Object} module:views/fields/email~options- * @property {- * module:views/fields/email~params &- * module:views/fields/base~params &- * Record- * } [params] Parameters.- */-+export interface EmailParams extends BaseParams {/**- * @typedef {Object} module:views/fields/email~params- * @property {boolean} [required] Required.- * @property {boolean} [onlyPrimary] Only primary.+ * Required.*/-- /**- * @param {- * module:views/fields/email~options &- * module:views/fields/base~options- * } options Options.- */- constructor(options) {- super(options);- }-- type = 'email'-- editTemplate = 'fields/email/edit'- detailTemplate = 'fields/email/detail'- listTemplate = 'fields/email/list'-+ required?: boolean;/**- * @inheritDoc- * @type {Array<(function (): boolean)|string>}+ * Only primary email address.*/- validations = ['required', 'emailData']-- events = {- /** @this EmailFieldView */- 'click [data-action="mailTo"]': function (e) {- this.mailTo($(e.currentTarget).data('email-address'));- },- /** @this EmailFieldView */- 'click [data-action="switchEmailProperty"]': function (e) {- const $target = $(e.currentTarget);- const $block = $(e.currentTarget).closest('div.email-address-block');- const property = $target.data('property-type');- const $input = $block.find('input.email-address');-- if (property === 'primary') {- if (!$target.hasClass('active')) {- if ($input.val() !== '') {- this.$el.find('button.email-property[data-property-type="primary"]')- .removeClass('active').children().addClass('text-muted');-- $target.addClass('active').children().removeClass('text-muted');- }- }-- this.trigger('change');-- return;- }-- let active = false;-- if ($target.hasClass('active')) {- $target.removeClass('active').children().addClass('text-muted');- } else {- $target.addClass('active').children().removeClass('text-muted');-- active = true;- }-- if (property === 'optOut') {- active ?- $input.addClass('text-strikethrough') :- $input.removeClass('text-strikethrough');- }-- if (property === 'invalid') {- active ?- $input.addClass('text-danger') :- $input.removeClass('text-danger');- }-- this.trigger('change');- },- /** @this EmailFieldView */- 'click [data-action="removeEmailAddress"]': function (e) {- const $block = $(e.currentTarget).closest('div.email-address-block');-- this.removeEmailAddress($block);-- const $last = this.$el.find('.email-address').last();-- if ($last.length) {- // noinspection JSUnresolvedReference- $last[0].focus({preventScroll: true});- }- },- /** @this EmailFieldView */- 'change input.email-address': function (e) {- const $input = $(e.currentTarget);- const $block = $input.closest('div.email-address-block');-- if (this._itemJustRemoved) {- return;- }-- if ($input.val() === '' && $block.length) {- this.removeEmailAddress($block);- }- else {- this.trigger('change');- }-- this.trigger('change');-- this.manageAddButton();- },- /** @this EmailFieldView */- 'keypress input.email-address': function () {- this.manageAddButton();- },- /** @this EmailFieldView */- 'paste input.email-address': function () {- setTimeout(() => this.manageAddButton(), 10);- },- /** @this EmailFieldView */- 'click [data-action="addEmailAddress"]': function () {- this.addEmailAddress();- },- /** @this EmailFieldView */- 'keydown input.email-address': function (e) {- const key = Espo.Utils.getKeyFromKeyEvent(e);-- const $target = $(e.currentTarget);-- if (key === 'Enter') {- if (!this.$el.find('[data-action="addEmailAddress"]').hasClass('disabled')) {- this.addEmailAddress();-- e.stopPropagation();- }-- return;- }-- if (key === 'Backspace' && $target.val() === '') {- const $block = $target.closest('div.email-address-block');-- this._itemJustRemoved = true;- setTimeout(() => this._itemJustRemoved = false, 100);-- e.stopPropagation();-- this.removeEmailAddress($block);-- setTimeout(() => this.focusOnLast(true), 50);- }- },- }-- // noinspection JSUnusedGlobalSymbols- validateEmailData() {- const data = this.model.get(this.dataFieldName);-- if (!data || !data.length) {- return;- }-- const addressList = [];-- const regExp = new RegExp(- /^[-!#$%&'*+/=?^_`{|}~A-Za-z0-9]+(?:\.[-!#$%&'*+/=?^_`{|}~A-Za-z0-9]+)*/.source +- /@([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?\.)+[A-Za-z0-9][A-Za-z0-9-]*[A-Za-z0-9]/.source- );-- let notValid = false;-- data.forEach((row, i) => {- const address = row.emailAddress || '';- const addressLowerCase = String(address).toLowerCase();-- if (!regExp.test(addressLowerCase) && address.indexOf(this.erasedPlaceholder) !== 0) {- const msg = this.translate('fieldShouldBeEmail', 'messages')- .replace('{field}', this.getLabelText());-- this.reRender();+ onlyPrimary?: boolean;+}- this.showValidationMessage(msg, 'div.email-address-block:nth-child(' + (i + 1)- .toString() + ') input');+/**+ * Options.+ */+export interface EmailOptions extends BaseOptions {}- notValid = true;+class EmailFieldView<+ S extends BaseViewSchema = BaseViewSchema,+ O extends EmailOptions = EmailOptions,+ P extends EmailParams = EmailParams,+> extends VarcharFieldView<S, O, P> {- return;- }+ readonly type: string = 'email'- if (addressList.includes(addressLowerCase)) {- const msg = this.translate('fieldValueDuplicate', 'messages')- .replace('{field}', this.getLabelText());+ protected editTemplate = 'fields/email/edit'+ protected detailTemplate = 'fields/email/detail'+ protected listTemplate = 'fields/email/list'- this.showValidationMessage(msg, 'div.email-address-block:nth-child(' + (i + 1)- .toString() + ') input');+ protected validations: (FieldValidator | string)[] = [+ 'required',+ 'emailData',+ ]- notValid = true;+ private dataFieldName: string;- return;- }+ private maxCount: number | null = null;- addressList.push(addressLowerCase);- });+ private isOptedOutFieldName: string;- if (notValid) {- return true;- }- }+ private emailAddressOptedOutByDefault: boolean;- validateRequired() {- if (this.isRequired()) {- if (!this.model.get(this.name)) {- const msg = this.translate('fieldIsRequired', 'messages')- .replace('{field}', this.getLabelText());+ private isInvalidFieldName: string;- this.showValidationMessage(msg, 'div.email-address-block:nth-child(1) input');+ private erasedPlaceholder: string;- return true;- }- }- }+ private itemMaxLength: number;- validateMaxCount() {- /** @type {number|null} */- const maxCount = this.maxCount;+ private autocompleteMaxCount: number;- if (!maxCount) {- return false;- }+ private _itemJustRemoved: boolean;- const items = this.model.attributes[this.dataFieldName] || [];-- if (items.length <= maxCount) {- return false;- }-- const msg = this.translate('fieldExceedsMaxCount', 'messages')- .replace('{maxCount}', maxCount.toString());-- this.showValidationMessage(msg, 'div.email-address-block:last-child input');-- return true;- }-- data() {- let emailAddressData;+ protected data(): Record<string, any> {+ let emailAddressData: Record<string, any>[];if (this.mode === this.MODE_EDIT) {emailAddressData = Espo.Utils.clone(this.model.get(this.dataFieldName));if (this.model.isNew() || !this.model.get(this.name)) {if (!emailAddressData || !emailAddressData.length) {- let optOut;+ let optOut: boolean;if (this.model.isNew()) {optOut = this.emailAddressOptedOutByDefault && this.model.entityType !== 'User';@@ -342,7 +138,7 @@ class EmailFieldView extends VarcharFieldView {const data = {...super.data(),emailAddressData: emailAddressData,- };+ } as Record<string, any>;if (this.isReadMode()) {data.isOptedOut = this.model.get(this.isOptedOutFieldName);@@ -361,15 +157,72 @@ class EmailFieldView extends VarcharFieldView {return data;}- getAutocompleteMaxCount() {+ private getAutocompleteMaxCount(): number {if (this.autocompleteMaxCount) {return this.autocompleteMaxCount;}- return this.getConfig().get('recordsPerPage');+ return this.getConfig().get('recordsPerPage') as number;}- focusOnLast(cursorAtEnd) {+ // noinspection JSUnusedGlobalSymbols+ protected validateEmailData(): boolean {+ const data = this.model.get(this.dataFieldName) as Record<string, unknown>[] | undefined;++ if (!data || !data.length) {+ return false;+ }++ const addressList: string[] = [];++ const regExp = new RegExp(+ /^[-!#$%&'*+/=?^_`{|}~A-Za-z0-9]+(?:\.[-!#$%&'*+/=?^_`{|}~A-Za-z0-9]+)*/.source ++ /@([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?\.)+[A-Za-z0-9][A-Za-z0-9-]*[A-Za-z0-9]/.source+ );++ let notValid = false;++ data.forEach((row, i) => {+ const address = (row.emailAddress || '') as string;+ const addressLowerCase = String(address).toLowerCase();++ if (!regExp.test(addressLowerCase) && address.indexOf(this.erasedPlaceholder) !== 0) {+ const msg = this.translate('fieldShouldBeEmail', 'messages')+ .replace('{field}', this.getLabelText());++ this.reRender();++ this.showValidationMessage(msg, 'div.email-address-block:nth-child(' + (i + 1)+ .toString() + ') input');++ notValid = true;++ return false;+ }++ if (addressList.includes(addressLowerCase)) {+ const msg = this.translate('fieldValueDuplicate', 'messages')+ .replace('{field}', this.getLabelText());++ this.showValidationMessage(msg, 'div.email-address-block:nth-child(' + (i + 1)+ .toString() + ') input');++ notValid = true;++ return false;+ }++ addressList.push(addressLowerCase);+ });++ if (notValid) {+ return true;+ }++ return false;+ }++ private focusOnLast(cursorAtEnd?: boolean) {const $item = this.$el.find('input.form-control').last();$item.focus();@@ -380,7 +233,7 @@ class EmailFieldView extends VarcharFieldView {}}- removeEmailAddress($block) {+ private removeEmailAddress($block: any) {if ($block.parent().children().length === 1) {$block.find('input.email-address').val('');} else {@@ -390,7 +243,7 @@ class EmailFieldView extends VarcharFieldView {this.trigger('change');}- addEmailAddress() {+ private addEmailAddress() {const data = Espo.Utils.cloneDeep(this.fetchEmailAddressData());const o = {@@ -409,7 +262,7 @@ class EmailFieldView extends VarcharFieldView {.then(() => this.focusOnLast());}- removeEmailAddressBlock($block) {+ private removeEmailAddressBlock($block: any) {let changePrimary = false;if ($block.find('button[data-property-type="primary"]').hasClass('active')) {@@ -427,14 +280,39 @@ class EmailFieldView extends VarcharFieldView {this.manageAddButton();}- afterRender() {+ protected setup() {+ this.addActionHandler('mailTo', (_e, target) => this.mailTo(target.dataset.emailAddress as string));+ this.addActionHandler('switchEmailProperty', (_e, target) => this.switchEmailProperty(target));+ this.addActionHandler('removeEmailAddress', (_e, target) => this.removeEmailAddressHandler(target));+ this.addHandler('change', 'input.email-address', (_e, target) => this.inputChangeHandler(target));+ this.addHandler('keypress', 'input.email-address', () => this.manageAddButton());+ this.addHandler('paste', 'input.email-address', () => setTimeout(() => this.manageAddButton(), 10));+ this.addActionHandler('addEmailAddress', () => this.addEmailAddress());+ this.addHandler('keydown', 'input.email-address', (e, target) => this.inputKeydownHandler(e, target));++ this.dataFieldName = `${this.name}Data`;+ this.isOptedOutFieldName = `${this.name}IsOptedOut`;+ this.isInvalidFieldName = `${this.name}IsInvalid`;++ this.erasedPlaceholder = 'ERASED:';++ this.emailAddressOptedOutByDefault = this.getConfig().get('emailAddressIsOptedOutByDefault');+ this.maxCount = this.getConfig().get('emailAddressMaxCount');++ this.itemMaxLength = this.getMetadata()+ .get(['entityDefs', 'EmailAddress', 'fields', 'name', 'maxLength']) || 255;++ this.validations.push(() => this.validateMaxCount());+ }++ protected afterRender() {super.afterRender();this.manageButtonsVisibility();this.manageAddButton();if (this.mode === this.MODE_SEARCH) {- const autocomplete = new Autocomplete(this.$element.get(0), {+ const autocomplete = new Autocomplete(this.$element?.get(0) as HTMLInputElement, {name: this.name,autoSelectFirst: true,triggerSelectOnValidInput: true,@@ -442,34 +320,32 @@ class EmailFieldView extends VarcharFieldView {minChars: 1,forceHide: true,handleFocusMode: 1,- onSelect: item => {- this.$element.val(item.emailAddress);+ onSelect: (item: any) => {+ this.$element?.val(item.emailAddress);},- formatResult: item => {+ formatResult: (item: any) => {return this.getHelper().escapeString(item.name) + ' <' +this.getHelper().escapeString(item.id) + '>';},- lookupFunction: query => {- return Espo.Ajax- .getRequest('EmailAddress/search', {- q: query,- maxSize: this.getAutocompleteMaxCount(),- entityType: this.entityType,- })- .then(/** Record[] */response => {- return response.map(item => {- return {- id: item.emailAddress,- name: item.entityName,- emailAddress: item.emailAddress,- entityId: item.entityId,- entityName: item.entityName,- entityType: item.entityType,- data: item.emailAddress,- value: item.emailAddress,- };- });- });+ lookupFunction: async (query: string) => {+ const response: any[] = await Ajax.getRequest('EmailAddress/search', {+ q: query,+ maxSize: this.getAutocompleteMaxCount(),+ entityType: this.entityType,+ });++ return response.map(item => {+ return {+ id: item.emailAddress,+ name: item.entityName,+ emailAddress: item.emailAddress,+ entityId: item.entityId,+ entityName: item.entityName,+ entityType: item.entityType,+ data: item.emailAddress,+ value: item.emailAddress,+ };+ });},});@@ -477,13 +353,49 @@ class EmailFieldView extends VarcharFieldView {}}- manageAddButton() {+ validateRequired(): boolean {+ if (this.isRequired()) {+ if (!this.model.get(this.name)) {+ const msg = this.translate('fieldIsRequired', 'messages')+ .replace('{field}', this.getLabelText());++ this.showValidationMessage(msg, 'div.email-address-block:nth-child(1) input');++ return true;+ }+ }++ return false;+ }++ protected validateMaxCount(): boolean {+ const maxCount = this.maxCount;++ if (!maxCount) {+ return false;+ }++ const items = this.model.attributes[this.dataFieldName] || [];++ if (items.length <= maxCount) {+ return false;+ }++ const msg = this.translate('fieldExceedsMaxCount', 'messages')+ .replace('{maxCount}', maxCount.toString());++ this.showValidationMessage(msg, 'div.email-address-block:last-child input');++ return true;+ }++ private manageAddButton() {const $input = this.$el.find('input.email-address');let c = 0;- $input.each((i, /** HTMLInputElement */input) => {+ $input.each((_i: number, input: HTMLInputElement) => {if (input.value !== '') {- c++;+ c ++;}});@@ -500,7 +412,7 @@ class EmailFieldView extends VarcharFieldView {.attr('disabled', 'disabled');}- manageButtonsVisibility() {+ private manageButtonsVisibility() {const $primary = this.$el.find('button[data-property-type="primary"]');const $remove = this.$el.find('button[data-action="removeEmailAddress"]');@@ -513,11 +425,11 @@ class EmailFieldView extends VarcharFieldView {}}- mailTo(emailAddress) {+ private mailTo(emailAddress: string) {const attributes = {status: 'Draft',- to: emailAddress- };+ to: emailAddress,+ } as Record<string, any>;const scope = this.model.entityType;@@ -546,20 +458,16 @@ class EmailFieldView extends VarcharFieldView {break;}- if (- this.model.collection &&- ('parentModel' in this.model.collection) &&- this.model.collection.parentModel- ) {- if (this.checkParentTypeAvailability(this.model.collection.parentModel.entityType)) {- attributes.parentType = this.model.collection.parentModel.entityType;- attributes.parentId = this.model.collection.parentModel.id;- attributes.parentName = this.model.collection.parentModel.get('name');- }+ const parentModel = this.model.collection?.parentModel;++ if (parentModel?.entityType && this.checkParentTypeAvailability(parentModel.entityType)) {+ attributes.parentType = parentModel.entityType;+ attributes.parentId = parentModel.id;+ attributes.parentName = parentModel.get('name');}if (!attributes.parentId) {- if (this.checkParentTypeAvailability(this.model.entityType)) {+ if (this.model.entityType && this.checkParentTypeAvailability(this.model.entityType)) {attributes.parentType = this.model.entityType;attributes.parentId = this.model.id;attributes.parentName = this.model.get('name');@@ -572,8 +480,7 @@ class EmailFieldView extends VarcharFieldView {}}-- if (['Contact', 'Lead', 'Account'].includes(this.model.entityType)) {+ if (this.model.entityType && ['Contact', 'Lead', 'Account'].includes(this.model.entityType)) {attributes.nameHash = {};attributes.nameHash[emailAddress] = this.model.get('name');}@@ -586,38 +493,132 @@ class EmailFieldView extends VarcharFieldView {return;}- const viewName = this.getMetadata()- .get('clientDefs.' + this.scope + '.modalViews.compose') || 'views/modals/compose-email';+ const viewName = 'views/modals/compose-email';- Espo.Ui.notifyWait();+ Ui.notifyWait();this.createView('quickCreate', viewName, {attributes: attributes,- }, view => {+ }).then(view => {view.render();- view.notify(false);++ Ui.notify();});}- checkParentTypeAvailability(parentType) {- return ~(this.getMetadata()- .get(['entityDefs', 'Email', 'fields', 'parent', 'entityList']) || []).indexOf(parentType);+ private checkParentTypeAvailability(parentType: string): boolean {+ const entityTypeList = (this.getMetadata()+ .get(['entityDefs', 'Email', 'fields', 'parent', 'entityList']) ?? []) as string[];++ return entityTypeList.includes(parentType);}- setup() {- this.dataFieldName = this.name + 'Data';- this.isOptedOutFieldName = this.name + 'IsOptedOut';- this.isInvalidFieldName = this.name + 'IsInvalid';+ private inputKeydownHandler(e: Event, target: HTMLElement) {+ const key = Espo.Utils.getKeyFromKeyEvent(e as KeyboardEvent);- this.erasedPlaceholder = 'ERASED:';+ const $target = $(target);- this.emailAddressOptedOutByDefault = this.getConfig().get('emailAddressIsOptedOutByDefault');- this.maxCount = this.getConfig().get('emailAddressMaxCount');+ if (key === 'Enter') {+ if (!this.$el.find('[data-action="addEmailAddress"]').hasClass('disabled')) {+ this.addEmailAddress();- this.itemMaxLength = this.getMetadata()- .get(['entityDefs', 'EmailAddress', 'fields', 'name', 'maxLength']) || 255;+ e.stopPropagation();+ }- this.validations.push(() => this.validateMaxCount());+ return;+ }++ if (key === 'Backspace' && $target.val() === '') {+ const $block = $target.closest('div.email-address-block');++ this._itemJustRemoved = true;+ setTimeout(() => this._itemJustRemoved = false, 100);++ e.stopPropagation();++ this.removeEmailAddress($block);++ setTimeout(() => this.focusOnLast(true), 50);+ }+ }++ private inputChangeHandler(target: HTMLElement) {+ const input = target as HTMLInputElement;++ const $block = $(target).closest('div.email-address-block');++ if (this._itemJustRemoved) {+ return;+ }++ if (input.value === '' && $block.length) {+ this.removeEmailAddress($block);+ } else {+ this.trigger('change');+ }++ this.trigger('change');++ this.manageAddButton();+ }++ private removeEmailAddressHandler(target: HTMLElement) {+ const $block = $(target).closest('div.email-address-block');++ this.removeEmailAddress($block);++ const $last = this.$el.find('.email-address').last();++ if ($last.length) {+ // noinspection JSUnresolvedReference+ $last[0].focus({preventScroll: true});+ }+ }++ private switchEmailProperty(target: HTMLElement) {+ const $target = $(target);+ const $block = $(target).closest('div.email-address-block');+ const property = $target.data('property-type');+ const $input = $block.find('input.email-address');++ if (property === 'primary') {+ if (!$target.hasClass('active')) {+ if ($input.val() !== '') {+ this.$el.find('button.email-property[data-property-type="primary"]')+ .removeClass('active').children().addClass('text-muted');++ $target.addClass('active').children().removeClass('text-muted');+ }+ }++ this.trigger('change');++ return;+ }++ let active = false;++ if ($target.hasClass('active')) {+ $target.removeClass('active').children().addClass('text-muted');+ } else {+ $target.addClass('active').children().removeClass('text-muted');++ active = true;+ }++ if (property === 'optOut') {+ active ?+ $input.addClass('text-strikethrough') :+ $input.removeClass('text-strikethrough');+ }++ if (property === 'invalid') {+ active ?+ $input.addClass('text-danger') :+ $input.removeClass('text-danger');+ }++ this.trigger('change');}/**@@ -629,17 +630,23 @@ class EmailFieldView extends VarcharFieldView {* lower: string,* }[]}*/- fetchEmailAddressData() {- const data = [];+ private fetchEmailAddressData(): {+ emailAddress: string;+ primary: boolean;+ optOut: boolean;+ invalid: boolean;+ lower: string;+ }[] {+ const data: any[] = [];const $list = this.$el.find('div.email-address-block');if ($list.length) {- $list.each((i, d) => {- const row = {};- const $d = $(d);+ $list.each((_i: number, itemElement: HTMLElement) => {+ const row = {} as any;+ const $d = $(itemElement);- row.emailAddress = $d.find('input.email-address').val().trim();+ row.emailAddress = ($d.find('input.email-address').val() as string).trim();if (row.emailAddress === '') {return;@@ -657,9 +664,8 @@ class EmailFieldView extends VarcharFieldView {return data;}-- fetch() {- const data = {};+ fetch(): Record<string, unknown> {+ const data = {} as any;const addressData = this.fetchEmailAddressData();@@ -721,7 +727,7 @@ class EmailFieldView extends VarcharFieldView {return data;}- fetchSearch() {+ fetchSearch(): Record<string, unknown> | null {const type = this.fetchSearchType();if (['isEmpty', 'isNotEmpty'].includes(type)) {diff --git a/client/src/views/fields/varchar.ts b/client/src/views/fields/varchar.tsindex 48ee78fd80..35a0f2a902 100644--- a/client/src/views/fields/varchar.ts+++ b/client/src/views/fields/varchar.ts@@ -392,7 +392,7 @@ class VarcharFieldView<return data;}- fetchSearch() {+ fetchSearch(): Record<string, unknown> | null {const type = this.fetchSearchType() || 'startsWith';if (['isEmpty', 'isNotEmpty'].includes(type)) {@@ -415,6 +415,7 @@ class VarcharFieldView<},};}+const value = [{type: 'isNotNull',