All files / src/services mapping-expression.service.ts

71.86% Statements 120/167
52.12% Branches 86/165
78.57% Functions 11/14
70.63% Lines 113/160

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438                              7x             7x   7x   7x 7x   7x   7x 7x           7x         7x 8x 4x       4x       7x 2x     7x 5x                             5x 5x                           5x   1x     5x   5x 3x 3x 3x                         3x       2x 2x 2x       7x   1x                                 7x               1x   1x     1x 1x   1x 1x 1x 1x         1x   1x 1x         1x                               7x         2x 2x     2x 2x 6x 6x 6x 6x 6x 6x   12x 10x   10x   10x         4x                 4x 2x       2x 2x 2x 2x 2x 2x     4x 4x 4x 4x 4x   10x                   2x                     7x 110x     110x     110x 87x           87x       23x 23x                         7x 1x 1x 1x       1x 1x         1x           1x 1x 1x                               1x 1x 1x     7x 2x 2x                                     7x                                   7x                                                                       7x 1x     1x 1x       2x 2x       2x   2x 1x     1x   7x  
/*
    Copyright (C) 2017 Red Hat, Inc.
 
    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at
 
            http://www.apache.org/licenses/LICENSE-2.0
 
    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/
import {
  ErrorInfo,
  ErrorLevel,
  ErrorScope,
  ErrorType,
} from '../models/error.model';
import { MappedField, MappingModel } from '../models/mapping.model';
import { TransitionMode, TransitionModel } from '../models/transition.model';
 
import { CommonUtil } from '../utils/common-util';
import { ConfigModel } from '../models/config.model';
import { ExpressionModel } from '../models/expression.model';
import { Field } from '../models/field.model';
import { FieldActionArgumentValue } from '../models/field-action.model';
import { FieldType } from '../contracts/common';
import { IExpressionNode } from '../contracts/expression';
import { MappingUtil } from '../utils/mapping-util';
import { Multiplicity } from '../contracts/field-action';
import { Subscription } from 'rxjs';
 
/**
 * Manages conditional mapping expression.
 */
export class MappingExpressionService {
  cfg!: ConfigModel;
 
  private mappingUpdatedSubscription?: Subscription;
 
  willClearOutSourceFieldsOnTogglingExpression() {
    if (this.cfg.mappings?.activeMapping?.transition.enableExpression) {
      return (
        this.cfg.mappings.activeMapping.getFirstCollectionField(true) != null
      );
    } else {
      return false;
    }
  }
 
  isExpressionEnabledForActiveMapping(): boolean {
    return !!this.cfg.mappings?.activeMapping?.transition?.enableExpression;
  }
 
  toggleExpressionMode() {
    Iif (
      !this.cfg.mappings ||
      !this.cfg.mappings.activeMapping ||
      !this.cfg.mappings.activeMapping.transition
    ) {
      this.cfg.errorService.addError(
        new ErrorInfo({
          message: 'Please select a mapping first.',
          level: ErrorLevel.INFO,
          scope: ErrorScope.MAPPING,
          type: ErrorType.USER,
        })
      );
      return;
    }
    const activeMapping = this.cfg.mappings.activeMapping;
    Iif (activeMapping.transition.mode === TransitionMode.ONE_TO_MANY) {
      this.cfg.errorService.addError(
        new ErrorInfo({
          message: `Cannot establish a conditional mapping expression when multiple target fields are selected.
        Please select only one target field and try again.`,
          level: ErrorLevel.WARN,
          scope: ErrorScope.MAPPING,
          type: ErrorType.USER,
          mapping: activeMapping,
        })
      );
      return;
    }
 
    if (this.willClearOutSourceFieldsOnTogglingExpression()) {
      // Clear out source fields, if the mapping contains a source collection
      activeMapping.sourceFields.splice(0, activeMapping.sourceFields.length);
    }
 
    activeMapping.transition.enableExpression =
      !activeMapping.transition.enableExpression;
    if (activeMapping.transition.enableExpression) {
      activeMapping.transition.mode = TransitionMode.EXPRESSION;
      activeMapping.transition.transitionFieldAction = null;
      this.mappingUpdatedSubscription =
        this.cfg.mappingService.mappingUpdated$.subscribe(() => {
          if (
            !this.cfg ||
            !this.cfg.mappings ||
            !this.cfg.mappings.activeMapping
          ) {
            return;
          }
          if (this.cfg.mappings.activeMapping.isFullyMapped()) {
            this.updateExpression(this.cfg.mappings.activeMapping);
          }
        });
      Iif (activeMapping.transition.expression) {
        this.cfg.mappings.activeMapping.transition.expression.expressionUpdatedSource.next();
      }
    } else {
      this.mappingUpdatedSubscription?.unsubscribe();
      activeMapping.transition.mode = TransitionMode.ONE_TO_ONE;
      this.cfg.mappingService.updateActiveMappingTransition();
    }
  }
 
  updateExpression(mapping: MappingModel, position?: string, offset?: number) {
    // Update conditional expression field references.
    mapping.transition.expression?.updateFieldReference(
      mapping,
      position,
      offset
    );
  }
 
  /**
   * Add the specified document ID/field path to the specified mapping/ expression.
   *
   * @param mapping
   * @param docId
   * @param fieldPath
   * @param newTextNode
   * @param atIndex
   * @param isTrailer
   */
  addFieldToExpression(
    mapping: MappingModel,
    docId: string,
    fieldPath: string,
    newTextNode: IExpressionNode,
    atIndex: number,
    isTrailer: boolean
  ) {
    let mappedField = mapping.getMappedFieldByPath(fieldPath, true, docId);
 
    Eif (!mappedField) {
      // If the selected field was not part of the original mapping
      // and is complex then add it as a reference node.
      mappedField = mapping.getReferenceField(docId, fieldPath);
      Eif (!mappedField) {
        // Try adding the selected field to the active mapping.
        const docDef = this.cfg.getDocForIdentifier(docId, true);
        const field = Field.getField(fieldPath, docDef?.getAllFields()!);
        Eif (field) {
          this.updateExpression(
            mapping,
            newTextNode.getUuid(),
            isTrailer ? newTextNode.toText().length : atIndex
          );
          this.cfg.mappingService.addFieldToActiveMapping(field);
        }
        mappedField = mapping.getMappedFieldByPath(fieldPath, true, docId);
        Iif (!mappedField) {
          return;
        }
      }
    }
    mapping.transition!.expression?.addConditionalExpressionNode(
      mappedField,
      newTextNode.getUuid(),
      isTrailer ? newTextNode.str.length : atIndex
    );
  }
 
  /**
   * Return an array of strings representing display names of mapping fields based on the
   * specified filter.
   * @todo ATM this is specialized for listing up candidate fields for adding into expression.
   * We will need to consolidate with field filter on the Document tree when we implement server
   * side field search - https://github.com/atlasmap/atlasmap/issues/603
   *
   * @param filter
   */
  executeFieldSearch(
    configModel: ConfigModel,
    filter: string,
    isSource: boolean
  ): string[][] {
    const activeMapping = configModel.mappings!.activeMapping;
    Iif (!activeMapping) {
      return [];
    }
    const formattedFields: string[][] = [];
    let fields: Field[] = [];
    for (const docDef of configModel.getDocs(isSource)) {
      fields = docDef.getTerminalFields();
      fields = fields.concat(docDef.getComplexFields());
      Field.alphabetizeFields(fields);
      let documentName = '';
      let fieldCount = -1;
 
      for (const field of fields) {
        const formattedField: string[] = [''];
        let displayName =
          field == null ? '' : field.getFieldLabel(configModel.showTypes, true);
 
        if (
          filter == null ||
          filter === '' ||
          displayName.toLowerCase().indexOf(filter.toLowerCase()) !== -1
        ) {
          Iif (
            !configModel.mappingService.isFieldSelectable(
              activeMapping,
              field
            ) &&
            field.type !== FieldType.COMPLEX
          ) {
            continue;
          }
          if (documentName !== field.docDef.name) {
            Iif (fieldCount === 0) {
              formattedFields.pop();
              continue;
            } else {
              const documentField = [''];
              documentName = field.docDef.name;
              documentField[0] = documentName;
              documentField[1] = field.docDef.id;
              fieldCount = 0;
              formattedFields.push(documentField);
            }
          }
          displayName = CommonUtil.extractDisplayPath(field.path, 100);
          formattedField[0] = field.docDef.id;
          formattedField[1] = field.path;
          fieldCount++;
          formattedFields.push(formattedField);
        }
        Iif (formattedFields.length > 500) {
          const endField: string[] = [''];
          endField[0] = '** Displayable field limit reached **';
          endField[1] = '';
          fieldCount++;
          formattedFields.push(endField);
          break;
        }
      }
    }
    return formattedFields;
  }
 
  /**
   * Return a string, in either text or HTML form, representing the
   * expression mapping of either the optionally specified mapping or
   * the active mapping if it exists, empty string otherwise.
   * @todo avoid any, use typed mapping object - https://github.com/atlasmap/atlasmap/issues/2975
   * @param asHTML
   * @param mapping
   */
  getMappingExpressionStr(asHTML: boolean, mapping?: any): string {
    Iif (!mapping && !MappingUtil.activeMapping(this.cfg)) {
      return '';
    }
    Iif (!mapping) {
      mapping = this.cfg.mappings?.activeMapping;
    }
    if (!mapping.transition.expression) {
      Iif (
        mapping.transition.enableExpression &&
        MappingUtil.hasFieldAction(mapping.sourceFields)
      ) {
        this.createMappingExpression(mapping);
      } else {
        return '';
      }
    }
 
    Eif (mapping.transition.expression && mapping.transition.enableExpression) {
      return asHTML
        ? mapping.transition.expression.expressionHTML
        : mapping.transition.expression.toText(true);
    }
    return '';
  }
 
  /**
   * Create a conditional mapping expression from the specified mapping model.  Start
   * with a multiplicity action if applicable, then any field-specific field actions.
   *
   * @param mapping
   */
  createMappingExpression(mapping: MappingModel): string {
    let expr = '';
    const sourceMappedFields = mapping.getMappedFields(true);
    const sourceMappedCollection = MappingUtil.hasMappedCollection(
      mapping,
      true
    );
    const targetMappedFields = mapping.getMappedFields(false);
    const targetMappedCollection = MappingUtil.hasMappedCollection(
      mapping,
      false
    );
 
    Eif (
      sourceMappedFields.length > 1 ||
      (sourceMappedCollection &&
        mapping.transition.transitionFieldAction?.definition?.multiplicity ===
          Multiplicity.MANY_TO_ONE)
    ) {
      expr = 'Concatenate (';
      expr += this.fieldActionsToExpression(mapping);
      expr +=
        ", '" +
        TransitionModel.delimiterModels[mapping.transition.delimiter]
          .actualDelimiter +
        "')";
    } else if (
      (targetMappedFields.length > 1 || targetMappedCollection) &&
      mapping.transition.transitionFieldAction?.definition?.multiplicity ===
        Multiplicity.ONE_TO_MANY
    ) {
      expr = 'Split (';
      expr += this.fieldActionsToExpression(mapping);
      expr += ')';
    } else {
      expr += this.fieldActionsToExpression(mapping);
    }
    mapping.transition.expression = new ExpressionModel(mapping, this.cfg);
    mapping.transition.expression.insertText(expr);
    return expr;
  }
 
  private qualifiedExpressionRef(mappedField: MappedField): string {
    Eif (mappedField.field?.path !== null) {
      return (
        '${' +
        mappedField.field?.docDef?.id +
        ':' +
        mappedField.field?.path +
        '}'
      );
    } else {
      return 'null';
    }
  }
 
  /**
   * Create a conditional expression fragment based on the specified field action
   * argument and type.
   *
   * @param actionArgument
   * @param actionArgType
   */
  private fieldActionArgumentToExpression(
    actionArgument: FieldActionArgumentValue,
    actionArgType: string
  ): string {
    if (actionArgType === 'string') {
      return "'" + actionArgument.value + "'";
    } else {
      return actionArgument.value;
    }
  }
 
  /**
   * Create a conditional expression fragment based on a single field action
   * and its arguments if any.
   *
   * @param mappedField
   * @param mfActionIndex
   */
  private fieldActionToExpression(
    mappedField: MappedField,
    mfActionIndex: number
  ): string {
    let action = mappedField.actions[mfActionIndex];
    let expression = action.name + ' (';
    if (mfActionIndex < mappedField.actions.length - 1) {
      mfActionIndex++;
      expression += this.fieldActionToExpression(mappedField, mfActionIndex);
    } else {
      expression += this.qualifiedExpressionRef(mappedField);
    }
    if (action.argumentValues.length > 0) {
      for (
        let actionArgIndex = 0;
        actionArgIndex < action.argumentValues.length;
        actionArgIndex++
      ) {
        expression +=
          ', ' +
          this.fieldActionArgumentToExpression(
            action.argumentValues[actionArgIndex],
            action.definition!.arguments[actionArgIndex].type
          );
      }
    }
    expression += ')';
    return expression;
  }
 
  /**
   * Create a conditional expression fragment based on the field actions of the specified
   * mapping model and the root field reference.
   *
   * @param mapping
   */
  private fieldActionsToExpression(mapping: MappingModel): string {
    let expression = '';
    let mappedField: MappedField;
 
    for (
      let mappedFieldIndex = 0;
      mappedFieldIndex < mapping.sourceFields.length;
      mappedFieldIndex++
    ) {
      mappedField = mapping.sourceFields[mappedFieldIndex];
      Iif (mappedField.actions.length > 0) {
        let mfActionIndex = 0;
        expression += this.fieldActionToExpression(mappedField, mfActionIndex);
      } else {
        expression += this.qualifiedExpressionRef(mappedField);
      }
      if (mappedFieldIndex !== mapping.sourceFields.length - 1) {
        expression += ', ';
      }
    }
    return expression;
  }
}