Project

General

Profile

1
import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';
2
import {ActivatedRoute, Router} from '@angular/router';
3
import {HelpContentService} from '../../services/help-content.service';
4
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
5
import {CheckEntity, Entity} from '../../utils/entities/adminTool/entity';
6
import {Portal} from '../../utils/entities/adminTool/portal';
7
import {EnvProperties} from '../../utils/properties/env-properties';
8
import {Session} from '../../login/utils/helper.class';
9
import {LoginErrorCodes} from '../../login/utils/guardHelper.class';
10
import {UserManagementService} from '../../services/user-management.service';
11
import {Subscriber} from "rxjs";
12
import {properties} from "../../../../environments/environment";
13
import {ConnectHelper} from "../../connect/connectHelper";
14
import {AlertModal} from "../../utils/modal/alert";
15

    
16
@Component({
17
  selector: 'entities',
18
  templateUrl: './entities.component.html',
19
})
20

    
21
export class EntitiesComponent implements OnInit {
22
  
23
  @ViewChild('editModal') editModal: AlertModal;
24
  @ViewChild('deleteModal') deleteModal: AlertModal;
25
  @ViewChild('relatedPages') relatedPages: AlertModal;
26
  private selectedEntities: string[] = [];
27
  
28
  public checkboxes: CheckEntity[] = [];
29
  
30
  public entities: Entity[] = [];
31
  
32
  public entityForm: FormGroup;
33
  
34
  private searchText: RegExp = new RegExp('');
35
  public keyword = '';
36
  
37
  public communities: Portal[] = [];
38
  public portal: string;
39
  
40
  public toggleIds: string[];
41
  public toggleStatus: boolean;
42
  public properties: EnvProperties = properties;
43
  
44
  public showLoading = true;
45
  public errorMessage = '';
46
  public updateErrorMessage = '';
47
  public modalErrorMessage = '';
48
  public isPortalAdministrator = null;
49
  public filterForm: FormGroup;
50
  private subscriptions: any[] = [];
51
  private index: number;
52
  
53
  constructor(private element: ElementRef, private route: ActivatedRoute,
54
              private _router: Router,
55
              private _helpContentService: HelpContentService,
56
              private userManagementService: UserManagementService, private _fb: FormBuilder) {
57
  }
58
  
59
  ngOnInit() {
60
    this.filterForm = this._fb.group({
61
      keyword: [''],
62
      status: ['all', Validators.required]
63
    });
64
    this.subscriptions.push(this.filterForm.get('keyword').valueChanges.subscribe(value => {
65
      this.searchText = new RegExp(value, 'i');
66
      this.applyFilters();
67
    }));
68
    this.subscriptions.push(this.filterForm.get('status').valueChanges.subscribe(value => {
69
      this.applyFilters();
70
    }));
71
    this.userManagementService.getUserInfo().subscribe(user => {
72
      this.portal = (this.route.snapshot.data.portal) ? this.route.snapshot.data.portal : this.route.snapshot.params[this.route.snapshot.data.param];
73
      if(this.portal === 'connect' || this.portal === 'explore') {
74
        ConnectHelper.setPortalTypeFromPid(this.portal);
75
      }
76
      this.applyPortalFilter(this.portal);
77
      this.isPortalAdministrator = Session.isPortalAdministrator(user) && !this.portal;
78
    });
79
    
80
    
81
  }
82
  
83
  ngOnDestroy(): void {
84
    this.subscriptions.forEach(value => {
85
      if (value instanceof Subscriber) {
86
        value.unsubscribe();
87
      } else if (value instanceof Function) {
88
        value();
89
      }
90
    });
91
  }
92
  
93
  getEntities(portal: string) {
94
    if (!Session.isLoggedIn()) {
95
      this._router.navigate(['/user-info'],
96
        {queryParams: {'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl': this._router.url}});
97
    } else {
98
      this.showLoading = true;
99
      this.updateErrorMessage = '';
100
      this.errorMessage = '';
101
      if (portal) {
102
        this._helpContentService.getCommunityEntities(portal, this.properties.adminToolsAPIURL).subscribe(
103
          entities => {
104
            this.entities = entities;
105
            this.checkboxes = [];
106
            
107
            let self = this;
108
            entities.forEach(_ => {
109
              self.checkboxes.push(<CheckEntity>{entity: _, checked: false});
110
            });
111
            
112
            this.showLoading = false;
113
          },
114
          error => this.handleError('System error retrieving entities', error));
115
      } else {
116
        this._helpContentService.getEntities(this.properties.adminToolsAPIURL).subscribe(
117
          entities => {
118
            this.entities = entities;
119
            this.checkboxes = [];
120
            
121
            let self = this;
122
            entities.forEach(_ => {
123
              self.checkboxes.push(<CheckEntity>{entity: _, checked: false});
124
            });
125
            this.showLoading = false;
126
          },
127
          error => this.handleError('System error retrieving entities', error));
128
      }
129
    }
130
  }
131
  
132
  public toggleCheckBoxes(event) {
133
    this.checkboxes.forEach(_ => _.checked = event.target.checked);
134
  }
135
  
136
  public applyCheck(flag: boolean) {
137
    this.checkboxes.forEach(_ => _.checked = flag);
138
  }
139
  
140
  public getSelectedEntities(): string[] {
141
    return this.checkboxes.filter(entity => entity.checked === true).map(checkedEntity => checkedEntity.entity).map(res => res._id);
142
  }
143
  
144
  private deleteEntitiesFromArray(ids: string[]): void {
145
    for (let id of ids) {
146
      let i = this.entities.findIndex(_ => _._id == id);
147
      this.entities.splice(i, 1);
148
    }
149
    this.applyFilters();
150
  }
151
  
152
  public confirmDeleteEntity(id: string) {
153
    // this.deleteConfirmationModal.ids = [id];
154
    // this.deleteConfirmationModal.showModal();
155
    this.selectedEntities = [id];
156
    this.confirmDeleteEntitiesModalOpen();
157
  }
158
  
159
  public confirmDeleteSelectedEntities() {
160
    // this.deleteConfirmationModal.ids = this.getSelectedEntities();
161
    // this.deleteConfirmationModal.showModal();
162
    this.selectedEntities = this.getSelectedEntities();
163
    this.confirmDeleteEntitiesModalOpen();
164
  }
165
  
166
  private confirmDeleteEntitiesModalOpen() {
167
    if (!Session.isLoggedIn()) {
168
      this._router.navigate(['/user-info'],
169
        {queryParams: {'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl': this._router.url}});
170
    } else {
171
      this.deleteModal.cancelButton = true;
172
      this.deleteModal.okButton = true;
173
      this.deleteModal.alertTitle = 'Delete Confirmation';
174
      this.deleteModal.message = 'Are you sure you want to delete the selected entity(-ies)?';
175
      this.deleteModal.okButtonText = 'Yes';
176
      this.deleteModal.open();
177
    }
178
  }
179
  
180
  public confirmedDeleteEntities(data: any) {
181
    if (!Session.isLoggedIn()) {
182
      this._router.navigate(['/user-info'],
183
        {queryParams: {'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl': this._router.url}});
184
    } else {
185
      this.showLoading = true;
186
      this.updateErrorMessage = '';
187
      
188
      this._helpContentService.deleteEntities(this.selectedEntities, this.properties.adminToolsAPIURL).subscribe(
189
        _ => {
190
          this.deleteEntitiesFromArray(this.selectedEntities);
191
          this.showLoading = false;
192
        },
193
        error => this.handleUpdateError('System error deleting the selected entities', error)
194
      );
195
    }
196
  }
197
  
198
  public editEntity(i: number) {
199
    const entity: Entity = this.checkboxes[i].entity;
200
    this.index = this.entities.findIndex(value => value._id === entity._id);
201
    this.entityForm = this._fb.group({
202
      name: this._fb.control(entity.name, Validators.required),
203
      _id: this._fb.control(entity._id),
204
      pid: this._fb.control(entity.pid, Validators.required)
205
    });
206
    this.modalErrorMessage = '';
207
    this.entitiesModalOpen('Edit Entity', 'Save Changes');
208
  }
209
  
210
  public newEntity() {
211
    this.entityForm = this._fb.group({
212
      _id: this._fb.control(null),
213
      name: this._fb.control('', Validators.required),
214
      pid: this._fb.control('', Validators.required)
215
    });
216
    this.modalErrorMessage = '';
217
    this.entitiesModalOpen('Create Entity', 'Create');
218
  }
219
  
220
  private entitiesModalOpen(title: string, yesBtn: string) {
221
    if (!Session.isLoggedIn()) {
222
      this._router.navigate(['/user-info'],
223
        {queryParams: {'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl': this._router.url}});
224
    } else {
225
      this.editModal.cancelButton = true;
226
      this.editModal.okButton = true;
227
      this.editModal.okButtonLeft = false;
228
      this.editModal.alertTitle = title;
229
      this.editModal.okButtonText = yesBtn;
230
      this.editModal.open();
231
    }
232
  }
233
  
234
  public entitySaveConfirmed(data: any) {
235
    if (!Session.isLoggedIn()) {
236
      this._router.navigate(['/user-info'],
237
        {queryParams: {'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl': this._router.url}});
238
    } else {
239
      this.modalErrorMessage = '';
240
      if (this.entityForm.value._id) {
241
        this._helpContentService.updateEntity(
242
          <Entity>this.entityForm.value, this.properties.adminToolsAPIURL).subscribe(
243
          entity => {
244
            this.entityUpdatedSuccessfully(entity);
245
          },
246
          error => this.handleUpdateError('System error updating entity', error)
247
        );
248
      } else {
249
        this._helpContentService.saveEntity(<Entity>this.entityForm.value, this.properties.adminToolsAPIURL).subscribe(
250
          entity => {
251
            this.entitySavedSuccessfully(entity);
252
          },
253
          error => this.handleUpdateError('System error creating entity', error)
254
        );
255
      }
256
    }
257
  }
258
  
259
  
260
  public entitySavedSuccessfully(entity: Entity) {
261
    this.entities.push(entity);
262
    this.applyFilters();
263
    this.applyCheck(false);
264
  }
265
  
266
  public entityUpdatedSuccessfully(entity: Entity) {
267
    this.entities[this.index] = entity;
268
    this.applyFilters();
269
    this.applyCheck(false);
270
  }
271
  
272
  public applyFilters() {
273
    this.checkboxes = [];
274
    this.entities.filter(item => this.filterEntitiesByStatus(item)).forEach(
275
      _ => this.checkboxes.push(<CheckEntity>{entity: _, checked: false})
276
    );
277
    this.checkboxes = this.checkboxes.filter(item => this.filterEntities(item.entity));
278
  }
279
  
280
  public filterEntities(entity: Entity): boolean {
281
    const textFlag = this.searchText.toString() === '' || (entity.name).match(this.searchText) != null;
282
    return textFlag;
283
  }
284
  
285
  public filterEntitiesByStatus(entity: Entity): boolean {
286
    let status = this.filterForm.get("status").value;
287
    return status == "all" || (status == "disabled" && !entity.isEnabled) || (status == "enabled" && entity.isEnabled);
288
  }
289
  
290
  handleError(message: string, error) {
291
    this.errorMessage = message;
292
    console.log('Server responded: ' + error);
293
    
294
    this.showLoading = false;
295
  }
296
  
297
  handleUpdateError(message: string, error) {
298
    if (error == null) {
299
      this.entityForm = this._fb.group({
300
        pid: ['', Validators.required],
301
        name: ['', Validators.required],
302
        isEnabled: '',
303
        _id: ''
304
      });
305
    } else {
306
      this.updateErrorMessage = message;
307
      console.log('Server responded: ' + error);
308
    }
309
    
310
    this.showLoading = false;
311
  }
312
  
313
  public applyPortalFilter(portal: string) {
314
    this.getEntities(portal);
315
  }
316
  
317
  public toggleEntities(status: boolean, ids: string[]) {
318
    // this.okModal.showModal();
319
    this.toggleIds = ids;
320
    this.toggleStatus = status;
321
    this.confirmRelatedPagesModalOpen();
322
  }
323
  
324
  private confirmRelatedPagesModalOpen() {
325
    if (!Session.isLoggedIn()) {
326
      this._router.navigate(['/user-info'],
327
        {queryParams: {'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl': this._router.url}});
328
    } else {
329
      this.relatedPages.cancelButton = true;
330
      this.relatedPages.okButton = true;
331
      this.relatedPages.alertTitle = 'Warning';
332
      this.relatedPages.message = "This action will affect all search pages related to this entity! Pages' status will change to entity's status! Do you want to continue?";
333
      this.relatedPages.okButtonText = 'Yes';
334
      this.relatedPages.open();
335
    }
336
  }
337
  
338
  public continueToggling(event: any) {
339
    if (!Session.isLoggedIn()) {
340
      this._router.navigate(['/user-info'],
341
        {queryParams: {'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl': this._router.url}});
342
    } else {
343
      this.updateErrorMessage = '';
344
      this._helpContentService.toggleEntities(
345
        this.portal, this.toggleIds, this.toggleStatus, this.properties.adminToolsAPIURL).subscribe(
346
        () => {
347
          for (let id of this.toggleIds) {
348
            const i = this.checkboxes.findIndex(_ => _.entity._id === id);
349
            this.checkboxes[i].entity.isEnabled = this.toggleStatus;
350
          }
351
          this.applyCheck(false);
352
        },
353
        error => this.handleUpdateError('System error changing the status of the selected entity(-ies)', error)
354
      );
355
    }
356
  }
357
}
(3-3/4)