import { Injectable } from '@angular/core'; import { AbstractControl, FormArray, ValidationErrors, ValidatorFn } from '@angular/forms'; import { StatusService } from '@core/services/status.service'; import { TimeZoneService } from '@core/services/time-zone.service'; import { LocationState } from '@core/states/location.state'; import { AutomationAPI } from '@core/typings/api/automation.typing'; import { Automation } from '@core/typings/ui/automation.typing'; import { ReferenceFieldsUI } from '@core/typings/ui/reference-fields.typing'; import { ClientSettingsService } from '@features/client-settings/client-settings.service'; import { FormDefinitionComponent } from '@features/configure-forms/form.typing'; import { CustomDataTablesService } from '@features/custom-data-tables/custom-data-table.service'; import { EmployeeSSOFieldsService } from '@features/employee-sso-fields/employee-sso-fields.service'; import { ComponentHelperService } from '@features/formio/services/component-helper/component-helper.service'; import { ReferenceFieldsService } from '@features/reference-fields/services/reference-fields.service'; import { UserService } from '@features/users/user.service'; import { ArrayHelpersService, SimpleStringMap, TypeaheadSelectOption } from '@yourcause/common'; import { I18nService } from '@yourcause/common/i18n'; import moment from 'moment'; @Injectable({ providedIn: 'root' }) export class RuleAutomationService { private formRuleObjectMap: SimpleStringMap = {}; constructor ( private i18n: I18nService, private statusService: StatusService, private referenceFieldService: ReferenceFieldsService, private arrayHelper: ArrayHelpersService, private customDataTablesService: CustomDataTablesService, private userService: UserService, private componentHelper: ComponentHelperService, private locationState: LocationState, private employeeSSOFieldsService: EmployeeSSOFieldsService, private clientSettingsService: ClientSettingsService, private timezoneService: TimeZoneService ) { } /** * * @returns the Selected options */ getSelectedOptions () { return [{ label: this.i18n.translate( 'GLOBAL:lblIsSelected', {}, 'Is selected' ), value: true }, { label: this.i18n.translate( 'GLOBAL:lblIsNotSelected', {}, 'Is not selected' ), value: false }]; } /** * * @returns the file upload options */ getFileUploadOptions () { return [{ label: this.i18n.translate( 'GLOBAL:lblIsUploaded', {}, 'Is uploaded' ), value: true }, { label: this.i18n.translate( 'GLOBAL:lblIsNotUploaded', {}, 'Is not uploaded' ), value: false }]; } /** * * @returns the Comparison negate options */ getComparisonNegateOptions () { return [{ label: this.i18n.translate('GLOBAL:lblIs', {}, 'is'), value: false }, { label: this.i18n.translate('GLOBAL:lblIsNot', {}, 'is not'), value: true }]; } /** * * @returns the Majority options */ getMajorityOptions () { return [{ label: this.i18n.translate('common:lblAllCap', {}, 'All'), value: Automation.MajorityOptions.All }, { label: this.i18n.translate('GLOBAL:lblMajority', {}, 'Majority'), value: Automation.MajorityOptions.Majority }, { label: this.i18n.translate('GLOBAL:lblOne', {}, 'One'), value: Automation.MajorityOptions.One }]; } /** * * @returns the Date options */ getDateOptions () { return [{ label: this.i18n.translate('common:textIsBetween', {}, 'Is between'), value: Automation.CriteriaComparisonTypes.Default }, { label: this.i18n.translate('common:textToday', {}, 'Today'), value: Automation.CriteriaComparisonTypes.Today }, { label: this.i18n.translate('common:textYesterday', {}, 'Yesterday'), value: Automation.CriteriaComparisonTypes.Yesterday }, { label: this.i18n.translate('common:textTomorrow', {}, 'Tomorrow'), value: Automation.CriteriaComparisonTypes.Tomorrow }, { label: this.i18n.translate('common:textLastWeek', {}, 'Last week'), value: Automation.CriteriaComparisonTypes.LastWeek }, { label: this.i18n.translate('common:textThisWeek', {}, 'This week'), value: Automation.CriteriaComparisonTypes.ThisWeek }, { label: this.i18n.translate('common:textLastMonth', {}, 'Last month'), value: Automation.CriteriaComparisonTypes.LastMonth }, { label: this.i18n.translate('common:textThisMonth', {}, 'This month'), value: Automation.CriteriaComparisonTypes.ThisMonth }, { label: this.i18n.translate('common:textLastYear', {}, 'Last year'), value: Automation.CriteriaComparisonTypes.LastYear }, { label: this.i18n.translate('common:textThisYear', {}, 'This year'), value: Automation.CriteriaComparisonTypes.ThisYear }, { label: this.i18n.translate('common:textLast365Days', {}, 'Last 365 days'), value: Automation.CriteriaComparisonTypes.Last365Days }]; } /** * * @returns the Number is options */ getNumberIsOptions () { return [{ label: this.i18n.translate('GLOBAL:lblEqualsLowercase', {}, 'equals'), value: false }]; } /** * * @param isPostApplicationCreate: is this after the app is created? * @param isRouting: is this for routing? * @returns the Application Object for Automation */ getApplicationObject ( isPostApplicationCreate: boolean, isRouting = false ): Automation.ObjectConfig { return { label: this.i18n.translate('common:lblApplication'), key: 'Application', columns: this.arrayHelper.sort([{ label: this.i18n.translate( 'GLOBAL:lblCashAmountRequested', {}, 'Cash amount requested' ), key: 'AmountRequested', removeObjectName: true, comparison: Automation.Comparisons.NumberRange }, !isRouting ? { label: this.i18n.translate( 'GLOBAL:lblInKindAmountRequested', {}, 'In-kind amount requested' ), key: 'InKindAmountRequested', removeObjectName: true, comparison: Automation.Comparisons.NumberRange } : undefined, !isRouting ? { label: this.i18n.translate( 'GLOBAL:lblTotalAmountRequested', {}, 'Total amount requested' ), key: 'TotalAmountRequested', removeObjectName: true, comparison: Automation.Comparisons.NumberRange } : undefined, isPostApplicationCreate ? { label: this.i18n.translate( 'GLOBAL:textRecommendedFundingAmount', {}, 'Recommended funding amount' ), key: 'RecommendedFundingAmount', removeObjectName: true, comparison: Automation.Comparisons.NumberRange } : undefined, isPostApplicationCreate ? { label: this.i18n.translate( 'common:hdrStatus', {}, 'Status' ), key: 'ApplicationStatus', removeObjectName: true, comparison: Automation.Comparisons.SelectIs, options: this.statusService.get('appStatusOptions') } : undefined].filter((item) => !!item) as any, 'label') }; } /** * * @returns the Applicant Object for automation */ getApplicantObject (): Automation.ObjectConfig { return { label: this.i18n.translate( 'common:lblApplicant' ), key: 'ApplicantInfo', columns: this.arrayHelper.sort([{ label: this.i18n.translate( 'GLOBAL:CITY' ), key: 'City', comparison: Automation.Comparisons.TextIs }, { label: this.i18n.translate( 'GLOBAL:lblState' ), key: 'State', comparison: Automation.Comparisons.TextIs }, { label: this.i18n.translate( 'GLOBAL:COUNTRY' ), key: 'Country', comparison: Automation.Comparisons.SelectIs, options: this.locationState.countries.map((country) => { return { label: country.name, value: country.code }; }) }, { label: this.i18n.translate( 'GLOBAL:lblPostalCode' ), key: 'PostalCode', comparison: Automation.Comparisons.TextIs }], 'label') }; } /** * * @returns the Budget Object for automation */ getBudgetObject (): Automation.ObjectConfig { return { label: this.i18n.translate( 'common:lblBudget' ), key: 'Budget', columns: this.arrayHelper.sort([{ label: this.i18n.translate( 'GLOBAL:textTotalRemaining', {}, 'Total remaining' ), key: 'TotalRemaining', comparison: Automation.Comparisons.NumberRange }], 'label') }; } /** * * @returns the Organization Object for automation */ getOrganizationObject (): Automation.ObjectConfig { return { label: this.i18n.translate( 'common:lblOrganization' ), key: 'OrganizationInfo', columns: this.arrayHelper.sort([{ label: this.i18n.translate( 'GLOBAL:CITY' ), key: 'City', comparison: Automation.Comparisons.TextIs }, { label: this.i18n.translate( 'GLOBAL:lblState' ), key: 'State', comparison: Automation.Comparisons.TextIs }, { label: this.i18n.translate( 'GLOBAL:COUNTRY' ), key: 'Country', comparison: Automation.Comparisons.SelectIs, options: this.locationState.countries.map((country) => { return { label: country.name, value: country.code }; }) }, { label: this.i18n.translate( 'GLOBAL:lblPostalCode' ), key: 'PostalCode', comparison: Automation.Comparisons.TextIs }, { label: this.i18n.translate( 'nonprofit:textTotalAwardedYearToDate', {}, 'Total Awarded - year to date' ), key: 'aggregatedTotalAwardedAmount', comparison: Automation.Comparisons.NumberRange }, { label: this.i18n.translate( 'nonprofit:textTotalRequestedYearToDate', {}, 'Total Requested - year to date' ), key: 'aggregateTotalRequestedAmount', comparison: Automation.Comparisons.NumberRange }, { label: this.i18n.translate( 'nonprofit:textTotalRequestedPerProgramForInProgressYTD', {}, 'Total Requested per program for In Progress - Year to date' ), key: 'aggregateTotalRequestedAmountInProgress', comparison: Automation.Comparisons.NumberRange }, { label: this.i18n.translate( 'nonprofit:textTotalRequestedPerProgramForAwaitingReviewYTD', {}, 'Total Requested per program for Awaiting Review - Year to date' ), key: 'aggregateTotalRequestedAmountAwaitingReview', comparison: Automation.Comparisons.NumberRange }, { label: this.i18n.translate( 'nonprofit:textTotalRequestedPerProgramForApprovedYTD', {}, 'Total Requested per program for Approved - Year to date' ), key: 'aggregateTotalRequestedAmountApproved', comparison: Automation.Comparisons.NumberRange }, { label: this.i18n.translate( 'nonprofit:textTotalRequestedPerProgramForHoldYTD', {}, 'Total Requested per program for Hold - Year to date' ), key: 'aggregateTotalRequestedAmountHold', comparison: Automation.Comparisons.NumberRange }, { label: this.i18n.translate( 'nonprofit:textTotalRequestedPerProgramForCancelledYTD', {}, 'Total Requested per program for Cancelled - Year to date' ), key: 'aggregateTotalRequestedAmountCancelled', comparison: Automation.Comparisons.NumberRange }, { label: this.i18n.translate( 'nonprofit:textTotalRequestedPerProgramForDeclinedYTD', {}, 'Total Requested per program for Declined - Year to date' ), key: 'aggregateTotalRequestedAmountDeclined', comparison: Automation.Comparisons.NumberRange }, { label: this.i18n.translate( 'nonprofit:textTotalRequestedPerProgramForArchivedYTD', {}, 'Total Requested per program for Archived - Year to date' ), key: 'aggregateTotalRequestedAmountIsArchived', comparison: Automation.Comparisons.NumberRange }, { label: this.i18n.translate( 'nonprofit:textTotalRequestedPerProgramForDraftYTD', {}, 'Total Requested per program for Draft - Year to date' ), key: 'aggregateTotalRequestedAmountIsDraft', comparison: Automation.Comparisons.NumberRange }, { label: this.i18n.translate( 'nonprofit:textTotalAwardedPerProgramForApprovedYTD', {}, 'Total Awarded per program for Approved - Year to date' ), key: 'aggregatedTotalAwardedAmountApproved', comparison: Automation.Comparisons.NumberRange }], 'label') }; } /** * * @returns the Employee SSO Object for automation */ getEmployeeSsoObject (): Automation.ObjectConfig { if (this.clientSettingsService.clientSettings.hasSSO) { this.employeeSSOFieldsService.setEmployeeColumnsForAutomation(); return { label: this.i18n.translate( 'GLOBAL:lblEmployee' ), key: 'EmployeeApplicantInfo', columns: this.arrayHelper.sort(this.employeeSSOFieldsService.get( 'employeeColumnsForAutomation' ), 'label') }; } return null; } /** * * @returns the Aggregate Object for automation */ getAggregateObject (): Automation.ObjectConfig { const aggregateFields = this.referenceFieldService.getAllAggregateFields(); if (aggregateFields.length > 0) { return { label: this.i18n.translate( 'GLOBAL:textAggregate', {}, 'Aggregate' ), key: 'referenceFields', columns: this.arrayHelper.sort(aggregateFields.map((field) => { return { label: field.name, key: field.key, comparison: Automation.Comparisons.NumberRange }; }), 'label') }; } return null; } /** * * @returns the Award Object for automation */ getAwardObject (): Automation.ObjectConfig { return { label: this.i18n.translate('common:lblAward'), key: 'Award', columns: this.arrayHelper.sort([{ label: this.i18n.translate( 'GLOBAL:lblTotalAwardAmount', {}, 'Total award amount' ), key: 'TotalAwardAmount', comparison: Automation.Comparisons.NumberRange }, { label: this.i18n.translate( 'GLOBAL:lblLastAwardDate', {}, 'Last award date' ), key: 'LastAwardDateModel', comparison: Automation.Comparisons.DateRange }], 'label') }; } /** * * @returns the Decision Object for automation */ getDecisionObject (): Automation.ObjectConfig { return { label: this.i18n.translate( 'GLOBAL:lblDecision' ), key: 'Decisions', columns: this.arrayHelper.sort([{ label: this.i18n.translate( 'GLOBAL:lblApprovalRatio', {}, 'Approval ratio' ), key: 'DecisionsYesRatio', comparison: Automation.Comparisons.Majority }, { label: this.i18n.translate( 'GLOBAL:lblDeclinationRatio', {}, 'Declination ratio' ), key: 'DecisionsNoRatio', comparison: Automation.Comparisons.Majority }, { label: this.i18n.translate( 'GLOBAL:lblApprovalCount', {}, 'Approval count' ), key: 'DecisionsYesCount', comparison: Automation.Comparisons.NumberIs }, { label: this.i18n.translate( 'GLOBAL:lblDeclinationCount', {}, 'Declination count' ), key: 'DecisionsNoCount', comparison: Automation.Comparisons.NumberIs }], 'label') }; } /** * * @returns the Payment Object for automation */ getPaymentObject (): Automation.ObjectConfig { return { label: this.i18n.translate('common:lblPayment'), key: 'Payment', columns: this.arrayHelper.sort([{ label: this.i18n.translate( 'GLOBAL:lblHasPayment', {}, 'Has payment' ), key: 'HasPayment', comparison: Automation.Comparisons.IsSelected, options: [{ label: this.i18n.translate( 'common:textIsTrue', {}, 'Is true' ), value: true }, { label: this.i18n.translate( 'common:textIsFalse', {}, 'Is false' ), value: false }] }, { label: this.i18n.translate( 'GLOBAL:lblDisbursedPaymentRatio', {}, 'Disbursed payment ratio' ), key: 'DisbursedPaymentRatio', comparison: Automation.Comparisons.Majority }, { label: this.i18n.translate( 'GLOBAL:lblPaymentAmountEqualsAwardAmount', {}, 'Payment amount equals award amount' ), key: 'PaymentAmountMatchesAwardAmount', comparison: Automation.Comparisons.IsSelected, options: [{ label: this.i18n.translate( 'common:textIsTrue', {}, 'Is true' ), value: true }, { label: this.i18n.translate( 'common:textIsFalse', {}, 'Is false' ), value: false }] }], 'label') }; } async formToRuleObject ( form: Automation.FormForRuleObject ): Promise { if (this.formRuleObjectMap[form.id]) { return this.formRuleObjectMap[form.id]; } const comps: FormDefinitionComponent[] = []; form.formDefinition.forEach((tab) => { this.componentHelper.eachComponent(tab.components, (comp) => { if (this.componentHelper.isReferenceFieldComp(comp.type)) { const refFieldOriginalKey = this.componentHelper.getRefFieldKeyFromCompType( comp.type ); const refField = this.referenceFieldService.getReferenceFieldByKey( refFieldOriginalKey ); if ( (!refField.supportsMultiple || refField.type === ReferenceFieldsUI.ReferenceFieldTypes.SelectBoxes) && !refField.isTableField && refField.type !== ReferenceFieldsUI.ReferenceFieldTypes.Table && refField.isSingleResponse ) { comps.push(comp); } } }); }); const columns: Automation.ObjectColumnConfig[] = []; const refFields = comps.filter((comp) => { return this.componentHelper.isReferenceFieldComp(comp.type); }).map((comp) => { const refFieldKey = comp.type.split('-')[1]; return this.referenceFieldService.getReferenceFieldByKey(refFieldKey); }); const guids = refFields.map((field) => { return field.customDataTableGuid; }).filter((guid) => !!guid); await this.customDataTablesService.getAllCdtOptionsPerForm( guids, true, this.userService.getCurrentUserCulture(), [form.id] ); comps.forEach((comp) => { if (this.componentHelper.isReferenceFieldComp(comp.type)) { const newColumn = this.referenceFieldService.formRefFieldToAutomationType( comp ); columns.push( newColumn ); } }); return this.formRuleObjectMap[form.id] = { label: form.name, key: 'referenceFields', columns: this.arrayHelper.sort(columns, 'label') }; } clearFormRuleObjectMap () { this.formRuleObjectMap = {}; } getAdaptedRulesForAPI (rules: Automation.CriteriaFormState[]) { return rules.reduce((acc, rule) => { return [ ...acc, ...this.mapCriteriaToAPIRule(rule, false) ]; }, [] as AutomationAPI.SaveAutomationRuleSetExpressionModel[]); } mapCriteriaToAPIRule ( formState: Automation.CriteriaFormState, applyFilters = true ): AutomationAPI.SaveAutomationRuleSetExpressionModel[] { const models = this.getMappedCriteriaToAPIRule(formState); if (applyFilters) { return models.filter(model => !model.isRemoved || model.automationRuleSetExpressionId); } return models; } getMappedCriteriaToAPIRule ( formState: Automation.CriteriaFormState ): AutomationAPI.SaveAutomationRuleSetExpressionModel[] { const baseValue = formState.values.find(value => !value.isRemoved) || formState.values[0]; const negated = baseValue?.comparisonNegated; const isRemoved = baseValue?.isRemoved; if (formState.column) { const key = (formState.column.removeObjectName ? '' : formState.object?.key + '.') + formState.column.key; const referenceFieldId = this.referenceFieldService.referenceFieldMap[ formState.column.key ]?.referenceFieldId ?? null; switch (formState.column.comparison) { case Automation.Comparisons.DateRange: if (baseValue.comparisonType !== Automation.CriteriaComparisonTypes.Default) { // typed as any below because typescript doesn't know the values are the same (ensured by if check above) const baseComparisonType: AutomationAPI.AutomationRuleComparisonTypes = baseValue.comparisonType as any; return [{ automationRuleSetExpressionId: baseValue.valueId, isRemoved, columnName: key, comparisonType: baseComparisonType, comparisonValue: '', referenceFieldId }, // if we switched from between to something else, remove the between rules ...(baseValue.greaterThanId ? [{ automationRuleSetExpressionId: baseValue.greaterThanId, isRemoved: true, columnName: key, comparisonType: baseComparisonType, comparisonValue: '', referenceFieldId }] : []), ...(baseValue.lessThanId ? [{ automationRuleSetExpressionId: baseValue.lessThanId, isRemoved: true, columnName: key, comparisonType: baseComparisonType, comparisonValue: '', referenceFieldId }] : [])]; } // fall through to number range since logic is the same // eslint-disable-next-line no-fallthrough case Automation.Comparisons.NumberRange: const isDate = formState.column.comparison === Automation.Comparisons.DateRange; return formState.values .reduce((acc, value) => { const { comparisonGreaterThan, comparisonLessThan } = value; return [ ...acc, // if we switched from a non-between comparison type, remove the old rule ...(value.valueId ? [{ automationRuleSetExpressionId: value.valueId, isRemoved: true, columnName: key, comparisonType: value.comparisonType, comparisonValue: '', referenceFieldId }] : []), comparisonGreaterThan || (comparisonGreaterThan === 0) ? { automationRuleSetExpressionId: value.greaterThanId, isRemoved: value.isRemoved, columnName: key, comparisonType: AutomationAPI.AutomationRuleComparisonTypes.GreaterThanOrEquals, comparisonValue: isDate ? moment(value.comparisonGreaterThan).utc().startOf('day') : '' + value.comparisonGreaterThan, referenceFieldId } : null, comparisonLessThan || comparisonLessThan === 0 ? { automationRuleSetExpressionId: value.lessThanId, isRemoved: value.isRemoved, columnName: key, comparisonType: AutomationAPI.AutomationRuleComparisonTypes.LessThanOrEquals, comparisonValue: isDate ? moment(value.comparisonLessThan).utc().endOf('day') : '' + value.comparisonLessThan, referenceFieldId } : null ].filter(val => val !== null); }, []); case Automation.Comparisons.SelectIs: case Automation.Comparisons.TextIs: case Automation.Comparisons.NumberIs: return formState.values.map(val => ({ automationRuleSetExpressionId: val.valueId, isRemoved: val.isRemoved, columnName: key, comparisonType: negated ? AutomationAPI.AutomationRuleComparisonTypes.NotEquals : AutomationAPI.AutomationRuleComparisonTypes.Equals, comparisonValue: '' + val.comparisonValue, referenceFieldId })); case Automation.Comparisons.IsUploaded: return [{ automationRuleSetExpressionId: baseValue.valueId, isRemoved, columnName: key, comparisonType: baseValue.comparisonValue ? AutomationAPI.AutomationRuleComparisonTypes.HasAValue : AutomationAPI.AutomationRuleComparisonTypes.DoesNotHaveAValue, comparisonValue: '' + baseValue.comparisonValue, referenceFieldId }]; case Automation.Comparisons.IsSelected: return [{ automationRuleSetExpressionId: baseValue.valueId, isRemoved, columnName: key, comparisonType: AutomationAPI.AutomationRuleComparisonTypes.Equals, comparisonValue: '' + baseValue.comparisonValue, referenceFieldId }]; case Automation.Comparisons.Majority: const comparisonValue = '' + (+baseValue.comparisonValue === Automation.MajorityOptions.All ? 1 : +baseValue.comparisonValue === Automation.MajorityOptions.Majority ? .5 : 0); const comparisonType = +baseValue.comparisonValue === Automation.MajorityOptions.All ? AutomationAPI.AutomationRuleComparisonTypes.Equals : AutomationAPI.AutomationRuleComparisonTypes.GreaterThan; return [{ automationRuleSetExpressionId: baseValue.valueId, isRemoved, columnName: key, comparisonType, comparisonValue, referenceFieldId }]; } } return [{ isRemoved: true, automationRuleSetExpressionId: baseValue?.valueId || baseValue?.greaterThanId || baseValue?.lessThanId, columnName: null, comparisonType: null, comparisonValue: null, referenceFieldId: null }]; } ruleArrayValidator () { return (control: AbstractControl) => { const formArray = control as FormArray; if (formArray.length === 0) { return {}; } for (let index = 0; index < formArray.length; index++) { const element = formArray.at(index); if (!element.value.isRemoved) { return null; } } return {}; }; } ruleValueArrayValidator (): ValidatorFn { return (control: AbstractControl) => { const formArray = control as FormArray; if (!formArray.parent) { return null; } const column = (formArray.parent.value).column; if (!column) { return null; } const baseFormGroup = formArray.at(0); if (!baseFormGroup) { return null; } for (let index = 0; index < formArray.length; index++) { const formGroup = formArray.at(index); const value: Automation.CriteriaValueFormState = formGroup.value; if (value.isRemoved) { continue; } switch (column.comparison) { case Automation.Comparisons.DateRange: // only add validator if default comparisonType if (value.comparisonType && value.comparisonType !== Automation.CriteriaComparisonTypes.Default) { break; } else if (!value.comparisonType) { baseFormGroup.setErrors({ comparisonType: { required: true } }); } // eslint-disable-next-line no-fallthrough case Automation.Comparisons.NumberRange: if (value.comparisonGreaterThan === null && value.comparisonLessThan === null) { baseFormGroup.setErrors({ comparisonLessThan: { required: true }, comparisonGreaterThan: { required: true } }); } else { baseFormGroup.setErrors(null); } break; default: if ( !value.comparisonValue && value.comparisonValue !== false ) { formGroup.setErrors({ comparisonValue: { required: true } }); } else { formGroup.setErrors(null); } } } return null as ValidationErrors; }; } /** * * @param column: the column of the rule * @returns the column comparison options */ getColumnComparisonOptions (column: Automation.ObjectColumnConfig) { return 'options' in column ? column.options : this.getSelectedOptions(); } /** * Gets the sentence connector when creating a rule summary * * @param rule: the rule to evaluate * @returns the sentence connector for summary */ getSentenceConnector (rule: Automation.CriteriaFormState) { let options: TypeaheadSelectOption[] = []; let findLabelFromOptions = false; let fallbackConnecterWord = ''; const nonRemovedRules = rule.values.filter((val) => !val.isRemoved); const firstValue = nonRemovedRules[0]; switch (rule.column.comparison) { case Automation.Comparisons.DateRange: const comparisonType = firstValue.comparisonType; const isBetween = comparisonType === Automation.CriteriaComparisonTypes.Default; if (!isBetween) { fallbackConnecterWord = this.i18n.translate('GLOBAL:lblIs', {}, 'is'); } break; case Automation.Comparisons.NumberIs: options = this.getNumberIsOptions(); findLabelFromOptions = true; break; case Automation.Comparisons.Majority: fallbackConnecterWord = this.i18n.translate('GLOBAL:lblIs', {}, 'is'); break; case Automation.Comparisons.SelectIs: case Automation.Comparisons.TextIs: options = this.getComparisonNegateOptions(); findLabelFromOptions = true; break; } if (findLabelFromOptions) { const found = options.find((opt) => { return opt.value === firstValue.comparisonNegated; }); return found?.label?.toLowerCase() || ''; } else { return fallbackConnecterWord?.toLowerCase() || ''; } } /** * Gets the value connector when creating a rule summary * * @param rule: the rule to evaluate * @returns the value connector for the summary */ getValueConnector (rule: Automation.CriteriaFormState) { const filteredValues = rule.values.filter((val) => !val.isRemoved); return filteredValues.reduce((acc, value) => { let options: TypeaheadSelectOption[] = []; let attr: 'comparisonType'|'comparisonValue'; let label = ''; switch (rule.column.comparison) { case Automation.Comparisons.DateRange: const comparisonType = value.comparisonType; const isBetween = comparisonType === Automation.CriteriaComparisonTypes.Default; if (isBetween) { let date1 = null; let date2 = null; if (value.comparisonGreaterThan) { date1 = (value.comparisonGreaterThan as moment.Moment).format('ll'); } if (value.comparisonLessThan) { date2 = (value.comparisonLessThan as moment.Moment).format('ll'); } if (date1 && date2) { label = this.i18n.translate( 'common:textIsBetweenDynamic', { number1: date1, number2: date2 }, 'is between __number1__ and __number2__' ); } else if (date1) { label = this.i18n.translate( 'common:textIsAfterDate', { date: date1 }, 'is after __date__' ); } else if (date2) { label = this.i18n.translate( 'common:textIsBeforeDate', { date: date2 }, 'is before __date__' ); } } else { options = this.getDateOptions(); attr = 'comparisonType'; } break; case Automation.Comparisons.IsSelected: options = this.getSelectedOptions(); attr = 'comparisonValue'; break; case Automation.Comparisons.IsUploaded: options = this.getFileUploadOptions(); attr = 'comparisonValue'; break; case Automation.Comparisons.Majority: options = this.getMajorityOptions(); attr = 'comparisonValue'; break; case Automation.Comparisons.SelectIs: options = this.getColumnComparisonOptions(rule.column); attr = 'comparisonValue'; break; case Automation.Comparisons.NumberRange: const num1 = value.comparisonGreaterThan; const num2 = value.comparisonLessThan; const has1 = !!num1 || num1 === 0; const has2 = !!num2 || num2 === 0; if (has1 && has2) { label = this.i18n.translate( 'common:textIsBetweenDynamic', { number1: num1, number2: num2 }, 'is between __number1__ and __number2__' ); } else if (has1) { label = this.i18n.translate( 'common:textIsGreaterThanNumber', { number: num1 }, 'is greater than __number__' ); } else if (has2) { label = this.i18n.translate( 'common:textIsLessThanNumber', { number: num2 }, 'is less than __number__' ); } break; case Automation.Comparisons.TextIs: label = value.comparisonValue as string; break; case Automation.Comparisons.NumberIs: label = value.comparisonValue as string; break; } if (attr) { label = this.getLabelFromOptionsAndAttr(options, value, attr); } if (acc && label) { const negated = filteredValues[0].comparisonNegated; const hasMany = rule.column.comparison === Automation.Comparisons.TextIs || rule.column.comparison === Automation.Comparisons.SelectIs; const negatedConnector = hasMany ? ` ${this.i18n.translate( negated ? 'GLOBAL:lblAND' : 'GLOBAL:lblOR', {}, negated ? 'AND' : 'OR' ).toLowerCase()}` : ','; return `${acc}${negatedConnector} ${label}`; } else if (acc) { return acc; } else { return label; } }, ''); } /** * Get the Label by passing in the options and attr to use * * @param options: typeahead select options * @param value: the value * @param attr: the attribute to check for the value * @returns the label */ getLabelFromOptionsAndAttr ( options: TypeaheadSelectOption[], value: Automation.CriteriaValueFormState, attr: keyof Automation.CriteriaValueFormState ) { return options.find((opt) => { return opt.value === value[attr]; })?.label ?? ''; } /** * Create a rule sentence based on a rule * * @param rule: the rule to evaluate * @returns a sentence summary of the rule */ createRuleSentence ( rule: Automation.CriteriaFormState ) { const column = rule.column; let sentence = column.label; if (column) { const sentenceConnector = this.getSentenceConnector(rule); if (sentenceConnector) { sentence = `${sentence} ${sentenceConnector}`; } const valueConnector = this.getValueConnector(rule); if (valueConnector) { sentence = `${sentence} ${valueConnector}`; } } return sentence; } mapAPIRulesToView ( apiRules: AutomationAPI.AutomationRuleSetExpressionBaseModel[], objects: Automation.ObjectConfig[] ): Automation.DisplayRule[] { const uiRules = this.mapAPIRulesToCriteria(apiRules, objects); const errorRule = uiRules.find(rule => !!rule.err); if (errorRule) { throw errorRule.err; } const rules = uiRules.map((uiRule) => { const column = uiRule.column; return { column: column.label, value: uiRule.values.map(value => { switch (column.comparison) { case Automation.Comparisons.TextIs: case Automation.Comparisons.SelectIs: case Automation.Comparisons.NumberIs: if (column.key === 'ApplicationStatus') { return this.statusService.applicationStatusMap[ value.comparisonValue as any ].translated; } if ('options' in uiRule.column) { const foundOption = uiRule.column.options.find(option => option.value === value.comparisonValue); if (foundOption) { return foundOption.label; } } return value.comparisonValue; case Automation.Comparisons.DateRange: if (value.comparisonType !== Automation.CriteriaComparisonTypes.Default) { let display: string; switch (value.comparisonType) { case Automation.CriteriaComparisonTypes.Today: display = this.i18n.translate('common:textToday', {}, 'Today'); break; case Automation.CriteriaComparisonTypes.Yesterday: display = this.i18n.translate('common:textYesterday', {}, 'Yesterday'); break; case Automation.CriteriaComparisonTypes.Tomorrow: display = this.i18n.translate('common:textTomorrow', {}, 'Tomorrow'); break; case Automation.CriteriaComparisonTypes.LastWeek: display = this.i18n.translate('common:textLastWeek', {}, 'Last week'); break; case Automation.CriteriaComparisonTypes.ThisWeek: display = this.i18n.translate('common:textThisWeek', {}, 'This week'); break; case Automation.CriteriaComparisonTypes.LastMonth: display = this.i18n.translate('common:textLastMonth', {}, 'Last month'); break; case Automation.CriteriaComparisonTypes.ThisMonth: display = this.i18n.translate('common:textThisMonth', {}, 'This month'); break; case Automation.CriteriaComparisonTypes.LastYear: display = this.i18n.translate('common:textLastYear', {}, 'Last year'); break; case Automation.CriteriaComparisonTypes.ThisYear: display = this.i18n.translate('common:textThisYear', {}, 'This year'); break; case Automation.CriteriaComparisonTypes.Last365Days: display = this.i18n.translate('common:textLast365Days', {}, 'Last 365 days'); break; } return display; } return `${moment( value.comparisonGreaterThan ).format('ll')} - ${moment( value.comparisonLessThan ).format('ll')}`; case Automation.Comparisons.NumberRange: return (`${value.comparisonGreaterThan || '0.00'} - ${value.comparisonLessThan || '999,999,999.99'}`); case Automation.Comparisons.IsUploaded: return !value.comparisonValue ? this.i18n.translate('GLOBAL:lblIsNotUploaded', {}, 'Is not uploaded') : this.i18n.translate('GLOBAL:lblIsUploaded', {}, 'Is uploaded'); case Automation.Comparisons.IsSelected: return !value.comparisonValue ? this.i18n.translate('GLOBAL:lblIsNotSelected', {}, 'Is not selected') : this.i18n.translate('GLOBAL:lblIsSelected', {}, 'Is selected'); case Automation.Comparisons.Majority: return value.comparisonValue === Automation.MajorityOptions.All ? this.i18n.translate('GLOBAL:lblAll') : value.comparisonValue === Automation.MajorityOptions.Majority ? this.i18n.translate('GLOBAL:lblMajority') : this.i18n.translate('GLOBAL:lblOne'); } }).join(', ') }; }); return rules; } mapAPIRulesToCriteria ( rules: AutomationAPI.AutomationRuleSetExpressionBaseModel[], objects: Automation.ObjectConfig[] ): Automation.CriteriaFormState[] { const groupedRules = rules.reduce((acc, rule) => { return { ...acc, [rule.columnName]: [ ...(acc[rule.columnName] || []), rule ] }; }, {} as SimpleStringMap); let err: Error; return Object.keys(groupedRules).map((columnName) => { const rulesForColumn = groupedRules[columnName]; let [objectKey, columnKey] = columnName.split('.'); if (!columnKey) { objects.some((obj) => { return obj.columns.some(searchColumn => { if (searchColumn.removeObjectName && searchColumn.key === objectKey) { objectKey = obj.key; columnKey = searchColumn.key; return true; } return false; }); }, null); } const object = objects.find((obj) => { return obj.key === objectKey && obj.columns.some((col) => col.key === columnKey); }); const column: Automation.ObjectColumnConfig = object ? object.columns.find(({ key }) => key === columnKey) : null; const comparison = column ? column.comparison : this.apiComparisonToUIComparison(rulesForColumn[0].comparisonType); let values: Automation.CriteriaValueFormState[]; switch (comparison) { case Automation.Comparisons.DateRange: // if relativeDateRule, we need to handle case here, otherwise it goes into number range logic const relativeDateRule = rulesForColumn.find(rule => [ AutomationAPI.AutomationRuleComparisonTypes.Last365Days, AutomationAPI.AutomationRuleComparisonTypes.LastMonth, AutomationAPI.AutomationRuleComparisonTypes.LastWeek, AutomationAPI.AutomationRuleComparisonTypes.LastYear, AutomationAPI.AutomationRuleComparisonTypes.ThisMonth, AutomationAPI.AutomationRuleComparisonTypes.ThisWeek, AutomationAPI.AutomationRuleComparisonTypes.ThisYear, AutomationAPI.AutomationRuleComparisonTypes.Today, AutomationAPI.AutomationRuleComparisonTypes.Tomorrow, AutomationAPI.AutomationRuleComparisonTypes.Yesterday ].includes(rule.comparisonType)); if (relativeDateRule) { // this is any because Typescript is comparing the values and is unaware that the values overlap since we are insuring this above const baseComparisonType: Automation.CriteriaComparisonTypes = relativeDateRule.comparisonType as any; values = [{ comparisonType: baseComparisonType, comparisonGreaterThan: null, comparisonLessThan: null, comparisonValue: '', isRemoved: false, comparisonNegated: null, greaterThanId: null, lessThanId: null, valueId: rulesForColumn[0].automationRuleSetExpressionId }]; break; } // eslint-disable-next-line no-fallthrough case Automation.Comparisons.NumberRange: const isDate = comparison === Automation.Comparisons.DateRange; const comparisonGreaterThanRule = rulesForColumn.find(rule => [ AutomationAPI.AutomationRuleComparisonTypes.GreaterThan, AutomationAPI.AutomationRuleComparisonTypes.GreaterThanOrEquals ].includes(rule.comparisonType)); const comparisonLessThanRule = rulesForColumn.find(rule => [ AutomationAPI.AutomationRuleComparisonTypes.LessThan, AutomationAPI.AutomationRuleComparisonTypes.LessThanOrEquals ].includes(rule.comparisonType)); let greaterThanVal = comparisonGreaterThanRule?.comparisonValue; let lessThanVal = comparisonLessThanRule?.comparisonValue; if (isDate) { greaterThanVal = greaterThanVal ? this.timezoneService.returnMidnightUTCDateShort(greaterThanVal) : greaterThanVal; lessThanVal = lessThanVal ? this.timezoneService.returnMidnightUTCDateShort(lessThanVal) : lessThanVal; } values = [{ comparisonGreaterThan: greaterThanVal ? (isDate ? moment(greaterThanVal) : +greaterThanVal) : null, comparisonLessThan: lessThanVal ? (isDate ? moment(lessThanVal) : +lessThanVal) : null, comparisonType: Automation.CriteriaComparisonTypes.Default, comparisonValue: null, comparisonNegated: null, isRemoved: false, greaterThanId: comparisonGreaterThanRule ? comparisonGreaterThanRule.automationRuleSetExpressionId : null, lessThanId: comparisonLessThanRule ? comparisonLessThanRule.automationRuleSetExpressionId : null, valueId: null }]; break; case Automation.Comparisons.Majority: const apiValue = +rulesForColumn[0].comparisonValue; const comparisonValue: any = apiValue === 1 ? Automation.MajorityOptions.All : apiValue === 0 ? Automation.MajorityOptions.One : Automation.MajorityOptions.Majority; values = [{ comparisonType: Automation.CriteriaComparisonTypes.Default, comparisonGreaterThan: null, comparisonLessThan: null, comparisonValue, isRemoved: false, comparisonNegated: null, greaterThanId: null, lessThanId: null, valueId: rulesForColumn[0].automationRuleSetExpressionId }]; break; case null: values = rulesForColumn.map(rule => { const subFormState: Automation.CriteriaValueFormState = { comparisonValue: rule.comparisonValue, comparisonType: Automation.CriteriaComparisonTypes.Default, comparisonGreaterThan: null, comparisonLessThan: null, comparisonNegated: rulesForColumn[0].comparisonType === AutomationAPI.AutomationRuleComparisonTypes.NotEquals, isRemoved: !object || !column, greaterThanId: null, lessThanId: null, valueId: rule.automationRuleSetExpressionId }; return subFormState; }); break; default: values = rulesForColumn.map((rule) => { let value = rule.comparisonValue; if ( (comparison === Automation.Comparisons.IsSelected) || (comparison === Automation.Comparisons.IsUploaded) ) { try { value = JSON.parse(rule.comparisonValue); } catch (e) { err = e as typeof err; value = null; } } if (column && 'options' in column) { const foundOption = (column as Automation.ObjectColumnSelectType) .options.find(option => { // eslint-disable-next-line eqeqeq return option.value == value; }); if (!foundOption) { err = new Error('missing select option'); value = null; } else { value = foundOption.value; } } const subFormState: Automation.CriteriaValueFormState = { comparisonValue: value, comparisonType: Automation.CriteriaComparisonTypes.Default, comparisonGreaterThan: null, comparisonLessThan: null, comparisonNegated: rulesForColumn[0].comparisonType === AutomationAPI.AutomationRuleComparisonTypes.NotEquals, isRemoved: !object || !column, greaterThanId: null, lessThanId: null, valueId: rule.automationRuleSetExpressionId }; return subFormState; }); } const hasNotDeletedVal = values.some((val) => { return !val.isRemoved; }); if (!hasNotDeletedVal) { values.push({ comparisonType: Automation.CriteriaComparisonTypes.Default, comparisonValue: null, comparisonGreaterThan: null, comparisonLessThan: null, comparisonNegated: false, isRemoved: false, greaterThanId: null, lessThanId: null, valueId: null }); } return { column, object, values, isRemoved: false, err }; }); } apiComparisonToUIComparison (comparison: AutomationAPI.AutomationRuleComparisonTypes) { switch (comparison) { case AutomationAPI.AutomationRuleComparisonTypes.DoesNotHaveAValue: case AutomationAPI.AutomationRuleComparisonTypes.HasAValue: return Automation.Comparisons.IsUploaded; case AutomationAPI.AutomationRuleComparisonTypes.GreaterThanOrEquals: case AutomationAPI.AutomationRuleComparisonTypes.LessThanOrEquals: case AutomationAPI.AutomationRuleComparisonTypes.GreaterThan: case AutomationAPI.AutomationRuleComparisonTypes.LessThan: return Automation.Comparisons.NumberRange; case AutomationAPI.AutomationRuleComparisonTypes.Equals: case AutomationAPI.AutomationRuleComparisonTypes.NotEquals: return Automation.Comparisons.TextIs; case AutomationAPI.AutomationRuleComparisonTypes.Last365Days: case AutomationAPI.AutomationRuleComparisonTypes.LastYear: case AutomationAPI.AutomationRuleComparisonTypes.LastWeek: case AutomationAPI.AutomationRuleComparisonTypes.LastMonth: case AutomationAPI.AutomationRuleComparisonTypes.LastYear: case AutomationAPI.AutomationRuleComparisonTypes.ThisMonth: case AutomationAPI.AutomationRuleComparisonTypes.ThisWeek: case AutomationAPI.AutomationRuleComparisonTypes.ThisYear: case AutomationAPI.AutomationRuleComparisonTypes.Today: case AutomationAPI.AutomationRuleComparisonTypes.Tomorrow: case AutomationAPI.AutomationRuleComparisonTypes.Yesterday: return Automation.Comparisons.DateRange; } } }