Code development platform for open source projects from the European Union institutions

Skip to content
Snippets Groups Projects
service-group-details-dialog.component.ts 10.3 KiB
Newer Older
import {ChangeDetectorRef, Component, Inject, OnInit, ViewChild} from '@angular/core';
import {MAT_DIALOG_DATA, MatDialog, MatDialogRef} from '@angular/material';
Joze RIHTARSIC's avatar
Joze RIHTARSIC committed
import {Observable} from "rxjs/internal/Observable";
import {HttpClient} from "@angular/common/http";
import {SmpConstants} from "../../smp.constants";
import {AlertService} from "../../alert/alert.service";
import {AbstractControl, FormBuilder, FormControl, FormGroup, Validators} from "@angular/forms";
import {SearchTableEntityStatus} from "../../common/search-table/search-table-entity-status.model";
import {ServiceGroupEditRo} from "../service-group-edit-ro.model";
import {GlobalLookups} from "../../common/global-lookups";
import {ServiceGroupExtensionWizardDialogComponent} from "../service-group-extension-wizard-dialog/service-group-extension-wizard-dialog.component";
import {ServiceGroupExtensionRo} from "./service-extension-edit-ro.model";
import {DomainRo} from "../../domain/domain-ro.model";
import {ServiceGroupDomainEditRo} from "../service-group-domain-edit-ro.model";
import {ConfirmationDialogComponent} from "../../common/confirmation-dialog/confirmation-dialog.component";

@Component({
  selector: 'service-group-details',
Joze RIHTARSIC's avatar
Joze RIHTARSIC committed
  templateUrl: './service-group-details-dialog.component.html',
  styleUrls: ['./service-group-details-dialog.component.css']
export class ServiceGroupDetailsDialogComponent implements OnInit {
Joze RIHTARSIC's avatar
Joze RIHTARSIC committed
  static readonly NEW_MODE = 'New ServiceGroup';
  static readonly EDIT_MODE = 'ServiceGroup Edit';

  @ViewChild('domainSelector') domainSelector: any;
Joze RIHTARSIC's avatar
Joze RIHTARSIC committed

  editMode: boolean;
  formTitle: string;
  current: ServiceGroupEditRo & { confirmation?: string };

  dialogForm: FormGroup;
  extensionObserver: Observable<ServiceGroupExtensionRo>;

  extensionValidationMessage: String = null;
  isExtensionValid: boolean = true;

  serviceGroupDomain: ServiceGroupDomainEditRo[];

  minSelectedListCount(min: number) {
    return (c: AbstractControl): { [key: string]: any } => {
      if (c.value && c.value.length >= min)
Joze RIHTARSIC's avatar
Joze RIHTARSIC committed
        return null;

      return {'minSelectedListCount': {valid: false}};
  constructor(public dialog: MatDialog,
              protected http: HttpClient,
              public dialogRef: MatDialogRef<ServiceGroupDetailsDialogComponent>,
              private alertService: AlertService,
              public lookups: GlobalLookups,
Joze RIHTARSIC's avatar
Joze RIHTARSIC committed
              @Inject(MAT_DIALOG_DATA) public data: any,
              private dialogFormBuilder: FormBuilder,
              private changeDetector: ChangeDetectorRef) {
    this.editMode = this.data.edit;
    this.formTitle = this.editMode ? ServiceGroupDetailsDialogComponent.EDIT_MODE : ServiceGroupDetailsDialogComponent.NEW_MODE;
Joze RIHTARSIC's avatar
Joze RIHTARSIC committed
    this.current = this.editMode
      ? {
Joze RIHTARSIC's avatar
Joze RIHTARSIC committed
      }
      : {
        id: null,
        participantIdentifier: '',
        participantScheme: '',
        serviceMetadata: [],
        users: [],
        serviceGroupDomains: [],
        extension: '',
Joze RIHTARSIC's avatar
Joze RIHTARSIC committed
        status: SearchTableEntityStatus.NEW,
      };
    // user is new when reopening the new item in edit mode!
    // allow to change data but warn on error!
Joze RIHTARSIC's avatar
Joze RIHTARSIC committed

    this.dialogForm = this.dialogFormBuilder.group({
      'participantIdentifier': new FormControl({
          value: '',
          disabled: this.current.status !== SearchTableEntityStatus.NEW
        },
        this.current.status !== SearchTableEntityStatus.NEW ? Validators.required : null),
      'participantScheme': new FormControl({value: '', disabled: this.current.status !== SearchTableEntityStatus.NEW},
        this.current.status !== SearchTableEntityStatus.NEW ? Validators.required : null),
      'serviceGroupDomains': new FormControl({value: []}, [this.minSelectedListCount(1)]),
      'users': new FormControl({value: []}, [this.minSelectedListCount(1)]),
      'extension': new FormControl({value: []}, []),
    });
    // update values
    this.dialogForm.controls['participantIdentifier'].setValue(this.current.participantIdentifier);
    this.dialogForm.controls['participantScheme'].setValue(this.current.participantScheme);
    this.dialogForm.controls['serviceGroupDomains'].setValue(this.current.serviceGroupDomains);
    this.dialogForm.controls['users'].setValue(this.current.users)
    this.dialogForm.controls['extension'].setValue(this.current.extension)
  ngOnInit() {
    // retrieve xml extension for this service group
    if (this.current.status !== SearchTableEntityStatus.NEW && !this.current.extension) {
      // init domains
      this.extensionObserver = this.http.get<ServiceGroupExtensionRo>(SmpConstants.REST_SERVICE_GROUP_EXTENSION+'/' + this.current.id);
      this.extensionObserver.subscribe((res: ServiceGroupExtensionRo) => {
        this.dialogForm.get('extension').setValue(res.extension);
      });
    }
    // detect changes for updated values in mat-selection-list (check change detection operations)
    // else the following error is thrown :xpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value:
    // 'aria-selected: false'. Current value: 'aria-selected: true'
    //
    this.changeDetector.detectChanges()
Joze RIHTARSIC's avatar
Joze RIHTARSIC committed

  submitForm() {
    this.checkValidity(this.dialogForm)
    this.dialogRef.close(true);
  }

  checkValidity(g: FormGroup) {
    Object.keys(g.controls).forEach(key => {
      g.get(key).markAsDirty();
    });
    Object.keys(g.controls).forEach(key => {
      g.get(key).markAsTouched();
    });
    //!!! updateValueAndValidity - else some filed did no update current / on blur never happened
    Object.keys(g.controls).forEach(key => {
      g.get(key).updateValueAndValidity();
    });
  }


  compareTableItemById(item1, item2): boolean {
    return item1.id === item2.id;

  compareDomain(domain: DomainRo, serviceGroupDomain: ServiceGroupDomainEditRo): boolean {
    return domain.id === serviceGroupDomain.domainId;

  public getCurrent(): ServiceGroupEditRo {
    // change this two properties only on new
    if (this.current.status === SearchTableEntityStatus.NEW) {
      this.current.participantIdentifier = this.dialogForm.value['participantIdentifier'];
      this.current.participantScheme = this.dialogForm.value['participantScheme'];
    } else {
      this.current.extensionStatus = SearchTableEntityStatus.UPDATED;
    this.current.users = this.dialogForm.value['users'];
    this.current.extension = this.dialogForm.value['extension'];


    let domainOptions = this.domainSelector.options._results;
    domainOptions.forEach(opt => {
      let domValue = opt.value;
      let sgd = this.getServiceGroupDomain(domValue.domainCode);
      // if contains and deselected  - delete
      if (sgd && !opt.selected) {
        this.current.serviceMetadata.forEach(metadata=>{
          if (metadata.domainCode === sgd.domainCode) {
            metadata.status = SearchTableEntityStatus.REMOVED;
            metadata.deleted = true;
          }
        });

        var index = this.current.serviceGroupDomains.indexOf(sgd);
        if (index !== -1) this.current.serviceGroupDomains.splice(index, 1);

        // delete service group
      } else if (!sgd && opt.selected) {
        let newDomain: ServiceGroupDomainEditRo = {
          id: null,
          domainId: domValue.id,
          domainCode: domValue.domainCode,
          smlSubdomain: domValue.domainCode,
          smlRegistered: false,
          serviceMetadataCount: 0,
          status: SearchTableEntityStatus.NEW,
        };
        this.current.serviceGroupDomains.push(newDomain);
      }
    });
    return this.current;

  onExtensionDelete() {
    this.dialogForm.controls['extension'].setValue("");
  }

  onStartWizardDialog() {

    const formRef: MatDialogRef<any> = this.dialog.open(ServiceGroupExtensionWizardDialogComponent);
    formRef.afterClosed().subscribe(result => {
      if (result) {
        let existingXML = this.dialogForm.controls['extension'].value;
        let val = (existingXML ? existingXML + '\n' : '') + formRef.componentInstance.getExtensionXML();
        this.dialogForm.controls['extension'].setValue(val);
      }
    });
  }

  onExtensionValidate() {
    let existingXML = this.dialogForm.controls['extension'].value;
    let request: ServiceGroupExtensionRo = {
      serviceGroupId: this.current.id,
      extension: existingXML,
    }
    //
    let validationObservable = this.http.post<ServiceGroupExtensionRo>(SmpConstants.REST_SERVICE_GROUP_EXTENSION_VALIDATE, request);
    validationObservable.subscribe((res: ServiceGroupExtensionRo) => {
      if (res.errorMessage) {
        this.extensionValidationMessage = res.errorMessage;
        this.isExtensionValid = false;
      } else {
        this.extensionValidationMessage = "Extension is valid!";
        this.isExtensionValid = true;
      }

    });
  }

  onPrettyPrintExtension() {
    let existingXML = this.dialogForm.controls['extension'].value;
    let request: ServiceGroupExtensionRo = {
      serviceGroupId: this.current.id,
      extension: existingXML,
    }
    let validationObservable = this.http.post<ServiceGroupExtensionRo>(SmpConstants.REST_SERVICE_GROUP_EXTENSION_FORMAT, request);
    validationObservable.subscribe((res: ServiceGroupExtensionRo) => {
      if (res.errorMessage) {
        this.extensionValidationMessage = res.errorMessage;
        this.isExtensionValid = false;
      } else {
        this.dialogForm.get('extension').setValue(res.extension);
        this.isExtensionValid = true;
      }

    });
  onDomainSelectionChanged(event) {
    // if deselected warn  serviceMetadata will be deleted
    let domainCode = event.option.value.domainCode;
    if (!event.option.selected) {
      this.dialog.open(ConfirmationDialogComponent, {
        data: {
          title: "Registred serviceMetadata on domain!",
          description: "Unregistration of domain will also delete it's serviceMetadata. Do you want to continue?"
        }
      }).afterClosed().subscribe(result => {
        if (!result) {
          event.option.selected = true;
        }
      })


    }
  }

  public getServiceMetadataCountOnDomain(domainCode: String) {
    return this.current.serviceMetadata.filter(smd => {
      return smd.domainCode === domainCode
    }).length;

  public getServiceGroupDomain(domainCode: String) {
    return this.current.serviceGroupDomains?
    this.current.serviceGroupDomains.find(smd => {
      return smd.domainCode === domainCode
    }):null;
  }