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 {UserManagementService} from '../../services/user-management.service';
10
import {Subscriber} from "rxjs";
11
import {properties} from "../../../../environments/environment";
12
import {AlertModal} from "../../utils/modal/alert";
13
import {SearchInputComponent} from "../../sharedComponents/search-input/search-input.component";
14
import {StringUtils} from "../../utils/string-utils.class";
15
import {Title} from "@angular/platform-browser";
16

    
17
declare var UIkit;
18

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