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

67.86% Statements 76/112
40.48% Branches 34/84
85.71% Functions 12/14
71.11% Lines 64/90

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                              7x           7x         7x     7x           7x     92x 92x 92x 92x 92x 92x         92x         7x 1x       1x 1x   1x     7x 1x 1x     1x 1x 1x 1x 1x     1x               1x     1x 1x       1x 1x       1x     1x     1x         1x                   1x             7x     1x                         7x       1x                                                                     7x 1x 1x     1x 1x                 7x 1x 1x     1x 2x 5x 5x 2x 2x         1x 1x   1x 1x 1x   1x 1x 1x               7x               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 {
  IProcessMappingRequestContainer,
  IProcessMappingResponseContainer,
  PROCESS_MAPPING_REQUEST_JSON_TYPE,
} from '../contracts/mapping-preview';
import { Subject, Subscription } from 'rxjs';
import { ConfigModel } from '../models/config.model';
import { MappingModel } from '../models/mapping.model';
import { MappingSerializer } from '../utils/mapping-serializer';
import ky from 'ky';
 
/**
 * Manages Mapping Preview.
 */
export class MappingPreviewService {
  cfg!: ConfigModel;
 
  mappingPreviewInputSource = new Subject<MappingModel>();
  mappingPreviewInput$ = this.mappingPreviewInputSource.asObservable();
  mappingPreviewOutputSource = new Subject<MappingModel>();
  mappingPreviewOutput$ = this.mappingPreviewOutputSource.asObservable();
  mappingPreviewErrorSource = new Subject<ErrorInfo[]>();
  mappingPreviewError$ = this.mappingPreviewErrorSource.asObservable();
 
  private mappingPreviewInputSubscription?: Subscription;
  private mappingUpdatedSubscription?: Subscription;
 
  constructor(private api: typeof ky) {}
 
  /**
   * Enable Mapping Preview.
   */
  enableMappingPreview(): void {
    Iif (this.cfg.initCfg.baseMappingServiceUrl == null) {
      // process mapping service not configured.
      return;
    }
    this.cfg.showMappingPreview = true;
    this.mappingPreviewInputSubscription =
      this.createMappingPreviewSubscription();
    this.mappingUpdatedSubscription = this.createMappingUpdatedSubscription();
  }
 
  private createMappingPreviewSubscription(): Subscription {
    return this.mappingPreviewInput$.subscribe((inputFieldMapping) => {
      Iif (!inputFieldMapping || !inputFieldMapping.isFullyMapped()) {
        return;
      }
      let hasValue = false;
      for (const sourceField of inputFieldMapping.getFields(true)) {
        Eif (sourceField.value) {
          hasValue = true;
          break;
        }
      }
      Iif (!hasValue) {
        for (const targetField of inputFieldMapping.getFields(false)) {
          if (targetField.value) {
            hasValue = true;
            break;
          }
        }
      }
      Iif (!hasValue) {
        return;
      }
      const payload = this.createPreviewRequestBody(inputFieldMapping);
      this.cfg.logger!.debug(
        `Process Mapping Preview Request: ${JSON.stringify(payload)}`
      );
      const url: string =
        this.cfg.initCfg.baseMappingServiceUrl + 'mapping/process';
      this.api
        .put(url, { json: payload })
        .json<IProcessMappingResponseContainer>()
        .then((body) => {
          this.cfg.logger!.debug(
            `Process Mapping Preview Response: ${JSON.stringify(body)}`
          );
          this.processPreviewResponse(inputFieldMapping, body);
        })
        .catch((error: any) => {
          Eif (
            this.cfg.mappings &&
            this.cfg.mappings.activeMapping &&
            this.cfg.mappings.activeMapping === inputFieldMapping
          ) {
            this.cfg.errorService.addError(
              new ErrorInfo({
                message: error,
                level: ErrorLevel.ERROR,
                mapping: inputFieldMapping,
                scope: ErrorScope.MAPPING,
                type: ErrorType.PREVIEW,
              })
            );
          }
          this.mappingPreviewErrorSource.next([
            new ErrorInfo({ message: error, level: ErrorLevel.ERROR }),
          ]);
        });
    });
  }
 
  private createPreviewRequestBody(
    inputFieldMapping: MappingModel
  ): IProcessMappingRequestContainer {
    return {
      ProcessMappingRequest: {
        jsonType: PROCESS_MAPPING_REQUEST_JSON_TYPE,
        mapping: MappingSerializer.serializeFieldMapping(
          this.cfg,
          inputFieldMapping,
          'preview',
          false
        ),
      },
    };
  }
 
  private processPreviewResponse(
    inputFieldMapping: MappingModel,
    body: IProcessMappingResponseContainer
  ) {
    const answer = MappingSerializer.deserializeFieldMapping(
      body.ProcessMappingResponse.mapping,
      this.cfg
    );
    for (const toWrite of inputFieldMapping.targetFields) {
      for (const toRead of answer.targetFields) {
        // TODO: check these non null operator
        if (
          toWrite.field?.docDef?.id === toRead.field?.docDef.id &&
          toWrite.field?.path === toRead.field?.path
        ) {
          // TODO let field component subscribe mappingPreviewOutputSource instead of doing this
          // TODO: check this non null operator
          toWrite.field!.value = toRead.mappingField?.value!;
          const index = answer.targetFields.indexOf(toRead);
          if (index !== -1) {
            answer.targetFields.splice(index, 1);
            break;
          }
        }
      }
    }
    this.mappingPreviewOutputSource.next(answer);
    const audits = MappingSerializer.deserializeAudits(
      body.ProcessMappingResponse.audits,
      ErrorType.PREVIEW
    );
    // TODO: check this non null operator
    if (this.cfg.mappings!.activeMapping === inputFieldMapping) {
      audits.forEach((a) => (a.mapping = inputFieldMapping));
      this.cfg.errorService.addError(...audits);
    }
    this.mappingPreviewErrorSource.next(audits);
  }
 
  private createMappingUpdatedSubscription(): Subscription {
    return this.cfg.mappingService.mappingUpdated$.subscribe(() => {
      Iif (!this.cfg || !this.cfg.mappings || !this.cfg.mappings.activeMapping) {
        return;
      }
      Eif (this.cfg.mappings.activeMapping.isFullyMapped()) {
        this.mappingPreviewInputSource.next(this.cfg.mappings.activeMapping);
      }
    });
  }
 
  /**
   * On mapping preview disable, clear any preview values and unsubscribe from
   * both the mapping-updated and mapping-preview subscriptions.
   */
  disableMappingPreview(): void {
    let mappedValueCleared = false;
    this.cfg.showMappingPreview = false;
 
    // Clear any preview values on mapping preview disable.
    Eif (this.cfg.mappings?.activeMapping?.isFullyMapped()) {
      for (const mapping of this.cfg.mappings.getAllMappings(true)) {
        for (const mappedField of mapping.getAllFields()) {
          if (mappedField.value?.length > 0 && !mappedField.isConstant()) {
            mappedField.value = '';
            mappedValueCleared = true;
          }
        }
      }
    }
    Eif (mappedValueCleared) {
      this.cfg.mappingService.notifyMappingUpdated();
    }
    Eif (this.mappingUpdatedSubscription) {
      this.mappingUpdatedSubscription.unsubscribe();
      this.mappingUpdatedSubscription = undefined;
    }
    Eif (this.mappingPreviewInputSubscription) {
      this.mappingPreviewInputSubscription.unsubscribe();
      this.mappingPreviewInputSubscription = undefined;
    }
  }
 
  /**
   * Toggle Mapping Preview.
   * @param enabled
   */
  toggleMappingPreview(enabled: boolean) {
    if (enabled) {
      this.enableMappingPreview();
    } else {
      this.disableMappingPreview();
    }
    return enabled;
  }
}