aboutsummaryrefslogtreecommitdiffstats
path: root/catalog-ui/src/app/ng2/pages/type-workspace/type-workspace.component.ts
blob: 11a11747ffcf09663e8b290750b78f4417c1ef11 (plain)
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
/*
 * -
 *  ============LICENSE_START=======================================================
 *  Copyright (C) 2022 Nordix Foundation.
 *  ================================================================================
 *  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.
 *
 *  SPDX-License-Identifier: Apache-2.0
 *  ============LICENSE_END=========================================================
 */

import {Component, Inject, Injector, OnInit} from '@angular/core';
import {SdcMenuToken, IAppMenu} from "../../config/sdc-menu.config";
import {MenuItem, MenuItemGroup} from "../../../utils/menu-handler";
import {CacheService} from "../../services/cache.service";
import {DataTypeModel} from "../../../models/data-types";
import {DataTypeService} from "../../services/data-type.service";
import {IWorkspaceViewModelScope} from "../../../view-models/workspace/workspace-view-model";
import {TranslateService} from "../../shared/translator/translate.service";
import {HttpErrorResponse} from "@angular/common/http";
import {ServerErrorResponse} from "../../../models/server-error-response";
import {Observable} from "rxjs/Observable";
import {SdcUiCommon, SdcUiComponents, SdcUiServices} from "onap-ui-angular/dist";

@Component({
  selector: 'app-type-workspace',
  templateUrl: './type-workspace.component.html',
  styleUrls: ['./type-workspace.component.less']
})
export class TypeWorkspaceComponent implements OnInit {

  private typeMenuItemGroup: MenuItemGroup;
  isLoading: boolean;
  disabled: boolean;
  isViewOnly: boolean = true;
  sdcVersion: string;
  breadcrumbsModel: Array<MenuItemGroup> = [];
  dataType: DataTypeModel = new DataTypeModel();
  importedDataType: DataTypeModel = new DataTypeModel();
  currentMenu: MenuItem;

  constructor(@Inject('$scope') private $scope: IWorkspaceViewModelScope,
              private dataTypeService: DataTypeService, private cacheService: CacheService,
              @Inject('Notification') private Notification: any,
              private translateService: TranslateService,
              @Inject('$state') private $state: ng.ui.IStateService,
              @Inject('$stateParams') private stateParams,
              private injector: Injector,
              private modalServiceSdcUI: SdcUiServices.ModalService,
              @Inject(SdcMenuToken) public sdcMenu: IAppMenu) { }

  ngOnInit(): void {
    this.sdcVersion = this.cacheService.get('version');
    this.typeMenuItemGroup = this.createTypeBreadcrumb();

    this.loadDataType();
  }

  private loadDataType(): void {
    if (this.stateParams.id && this.stateParams.id != "import") {
      this.dataTypeService.findById(this.stateParams.id).subscribe(dataType => {
        this.dataType = dataType;
        this.updateTypeBreadcrumb();
      }, error => {
        console.debug('Could not find data type %s', this.stateParams.id, error);
        this.goToBreadcrumbHome();
      });
        this.isViewOnly = true;
    } else {

      this.isViewOnly = false;
      this.dataType = new DataTypeModel();
    }
  }

  onImportedType(dataType) {
    this.typeMenuItemGroup.updateSelectedMenuItemText(`Data Type: ${dataType.name}`);
  }

  private createImportType() {
      if (this.$scope.dataType.derivedFromName != undefined && this.$scope.dataType.model != undefined) {
          this.dataTypeService.createImportedType(this.$scope.dataType.model.name, this.$scope.importFile)
              .subscribe(response => {
              this.importedDataType = new DataTypeModel(response);
              this.Notification.success({
                  message: this.$scope.dataType.name + ' ' + this.translateService.translate('IMPORT_DATA_TYPE_SUCCESS_MESSAGE_TEXT'),
                  title: this.translateService.translate('IMPORT_DATA_TYPE_TITLE_TEXT')
              });
              this.$state.go(this.$state.current.name, {importedFile: null, id: this.$scope.dataType.uniqueId, isViewOnly: true}, {reload: true});
          }, error => {//because overriding http interceptor
                  if (error instanceof HttpErrorResponse) {
                      const errorResponse: ServerErrorResponse = new ServerErrorResponse(error);
                      const modalService = this.injector.get(SdcUiServices.ModalService);
                      const errorDetails = {
                          'Error Code': errorResponse.status != 409 ? errorResponse.messageId : "Data Type already exists",
                          'Status Code': errorResponse.status
                      };
                      modalService.openErrorDetailModal('Error', errorResponse.status != 409 ? errorResponse.message : "Data Type already exists", 'error-modal', errorDetails);
                      return Observable.throwError(error);
                  }
              });
      }
      else {
          this.Notification.error({
              message: this.$scope.dataType.name + ' ' + "Derived from is invalid in file",
              title: this.translateService.translate('IMPORT_DATA_TYPE_TITLE_TEXT')
          });
      }
  }

  private deleteDataType() {
      const modalTitle: string = this.translateService.translate('DELETE_DATA_TYPE_TITLE_CONFIRMATION_TEXT');
      const modalMessage: string = this.translateService.translate('DELETE_DATA_TYPE_MESSAGE_CONFIRMATION_TEXT');;
      const modalButton = {
          testId: 'ok-button',
          text: this.sdcMenu.alertMessages.okButton,
          type: SdcUiCommon.ButtonType.warning,
          callback: this.handleDeleteDataType(),
          closeModal: true
      } as SdcUiComponents.ModalButtonComponent;
      this.modalServiceSdcUI.openWarningModal(modalTitle, modalMessage, 'alert-modal', [modalButton]);
  }

  private handleDeleteDataType():Function {
    return () => {
      this.isLoading = true;
      this.dataTypeService.deleteDataType(this.dataType.uniqueId).subscribe(()=> {
        this.Notification.success({
            message: this.dataType.model + ' ' + this.dataType.name + ' ' + this.translateService.translate('DELETE_SUCCESS_MESSAGE_TEXT'),
            title: this.translateService.translate("DELETE_SUCCESS_MESSAGE_TITLE")
        });
        if (this.$state.params.previousState) {
            switch (this.$state.params.previousState) {
                case 'catalog':
                case 'dashboard':
                    this.$state.go(this.$state.params.previousState);
                    break;
                default:
                    this.$state.go('dashboard');
                    break;
            }
        }
    }, (error) => {
        this.isLoading = false;
        this.Notification.error({
            message: this.dataType.model + ' ' + this.dataType.name + ' ' + this.translateService.translate('DELETE_FAILURE_MESSAGE_TEXT'),
            title: this.translateService.translate('DELETE_FAILURE_MESSAGE_TITLE')
        });
        if (error instanceof HttpErrorResponse) {
            const errorResponse: ServerErrorResponse = new ServerErrorResponse(error);
            const modalService = this.injector.get(SdcUiServices.ModalService);
            const errorDetails = {
                'Error Code': errorResponse.messageId,
                'Status Code': errorResponse.status
            };
            modalService.openErrorDetailModal('Error', errorResponse.message, 'error-modal', errorDetails);
        }
    });
    }
  }

  private updateTypeBreadcrumb(): void {
    this.typeMenuItemGroup.updateSelectedMenuItemText(`Data Type: ${this.dataType.name}`);
  }

  private createTypeBreadcrumb(): MenuItemGroup {
    const menuItem = new MenuItem(`Data Type: ${this.dataType ? this.dataType.name : ''}`, undefined, undefined, undefined, [], [], false);
    return new MenuItemGroup(0, [menuItem]);
  }

  goToBreadcrumbHome(): void {
    const homeMenuItemGroup: MenuItemGroup = this.breadcrumbsModel[0];
    this.$state.go(homeMenuItemGroup.menuItems[homeMenuItemGroup.selectedIndex].state);
  }

  onMenuUpdate(menuItemGroup: MenuItemGroup): void {
    this.breadcrumbsModel.push(...[this.typeMenuItemGroup, menuItemGroup]);
    if (!this.isViewOnly) {
        this.$scope.leftBarTabs.menuItems.forEach((item: MenuItem) => {
            item.isDisabled = ('general' !== item.state);
            item.disabledCategory = ('general' !== item.state);
        });
    }
  }

  onMenuClick(menuItem: MenuItem): void {
    this.currentMenu = menuItem;
  }
}