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