Project

General

Profile

1
import {Component, ViewChild, OnInit, ElementRef} from '@angular/core';
2
import {ActivatedRoute, Router} from '@angular/router';
3
import {HelpContentService} from '../../services/help-content.service';
4
import {FormBuilder, FormControl, 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 {HelperFunctions} from "../../utils/HelperFunctions.class";
11
import {UserManagementService} from '../../services/user-management.service';
12
import {Subscriber} from "rxjs";
13
import {properties} from "../../../../environments/environment";
14

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

    
20
export class EntitiesComponent implements OnInit {
21

    
22
  @ViewChild('AlertModalSaveEntity') alertModalSaveEntity;
23
  @ViewChild('AlertModalDeleteEntities') alertModalDeleteEntities;
24
  private selectedEntities: string[] = [];
25

    
26
  public checkboxes: CheckEntity[] = [];
27

    
28
  public entities: Entity[] = [];
29

    
30
  public myForm: FormGroup;
31

    
32
  private searchText: RegExp = new RegExp('');
33
  public keyword = '';
34

    
35
  public communities: Portal[] = [];
36
  public selectedCommunityPid: string;
37

    
38
  @ViewChild('AlertModalRelatedPages') alertModalRelatedPages;
39

    
40
  public toggleIds: string[];
41
  public toggleStatus: boolean;
42
  public properties: EnvProperties = null;
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

    
52
  constructor(private element: ElementRef, private route: ActivatedRoute,
53
              private _router: Router,
54
              private _helpContentService: HelpContentService,
55
              private userManagementService: UserManagementService, private _fb: FormBuilder) {
56
  }
57

    
58
  ngOnInit() {
59
    this.filterForm = this._fb.group({
60
      keyword: [''],
61
      status: ['all', Validators.required]});
62

    
63
    this.myForm = this._fb.group({
64
      pid: ['', Validators.required],
65
      name: ['', Validators.required],
66
      isEnabled: '',
67
      _id: ''
68
    });
69
    this.subscriptions.push(this.filterForm.get('keyword').valueChanges.subscribe(value => {
70
      this.filterBySearch(value);
71
    }));
72
    this.subscriptions.push(this.filterForm.get('status').valueChanges.subscribe(value => {
73
      this.applyStatusFilter();
74
    }));
75

    
76
      this.properties = properties;
77
      this.subscriptions.push(this.route.queryParams.subscribe(params => {
78
        HelperFunctions.scroll();
79
        this.userManagementService.getUserInfo().subscribe(user => {
80
          this.selectedCommunityPid = params['communityId'];
81
          this.applyCommunityFilter(this.selectedCommunityPid);
82
          this.isPortalAdministrator = Session.isPortalAdministrator(user) && !this.selectedCommunityPid;
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
  getEntities(community_pid: string) {
98
    if (!Session.isLoggedIn()) {
99
      this._router.navigate(['/user-info'],
100
        {queryParams: {'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl': this._router.url}});
101
    } else {
102
      this.showLoading = true;
103
      this.updateErrorMessage = '';
104
      this.errorMessage = '';
105
      if (community_pid) {
106
        this._helpContentService.getCommunityEntities(community_pid, this.properties.adminToolsAPIURL).subscribe(
107
          entities => {
108
            this.entities = entities;
109
            this.checkboxes = [];
110

    
111
            let self = this;
112
            entities.forEach(_ => {
113
              self.checkboxes.push(<CheckEntity>{entity: _, checked: false});
114
            });
115

    
116
            this.showLoading = false;
117
          },
118
          error => this.handleError('System error retrieving entities', error));
119
      } else {
120
        this._helpContentService.getEntities(this.properties.adminToolsAPIURL).subscribe(
121
          entities => {
122
            this.entities = entities;
123
            this.checkboxes = [];
124

    
125
            let self = this;
126
            entities.forEach(_ => {
127
              self.checkboxes.push(<CheckEntity>{entity: _, checked: false});
128
            });
129
            this.showLoading = false;
130
          },
131
          error => this.handleError('System error retrieving entities', error));
132
      }
133
    }
134
  }
135

    
136
  public toggleCheckBoxes(event) {
137
    this.checkboxes.forEach(_ => _.checked = event.target.checked);
138
  }
139

    
140
  public applyCheck(flag: boolean) {
141
    this.checkboxes.forEach(_ => _.checked = flag);
142
  }
143

    
144
  public getSelectedEntities(): string[] {
145
    return this.checkboxes.filter(entity => entity.checked === true).map(checkedEntity => checkedEntity.entity).map(res => res._id);
146
  }
147

    
148
  private deleteEntitiesFromArray(ids: string[]): void {
149
    for (let id of ids) {
150
      const i = this.checkboxes.findIndex(_ => _.entity._id === id);
151
      this.checkboxes.splice(i, 1);
152
    }
153
  }
154

    
155
  public confirmDeleteEntity(id: string) {
156
    // this.deleteConfirmationModal.ids = [id];
157
    // this.deleteConfirmationModal.showModal();
158
    this.selectedEntities = [id];
159
    this.confirmDeleteEntitiesModalOpen();
160
  }
161

    
162
  public confirmDeleteSelectedEntities() {
163
    // this.deleteConfirmationModal.ids = this.getSelectedEntities();
164
    // this.deleteConfirmationModal.showModal();
165
    this.selectedEntities = this.getSelectedEntities();
166
    this.confirmDeleteEntitiesModalOpen();
167
  }
168

    
169
  private confirmDeleteEntitiesModalOpen() {
170
    if (!Session.isLoggedIn()) {
171
      this._router.navigate(['/user-info'],
172
        {queryParams: {'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl': this._router.url}});
173
    } else {
174
      this.alertModalDeleteEntities.cancelButton = true;
175
      this.alertModalDeleteEntities.okButton = true;
176
      this.alertModalDeleteEntities.alertTitle = 'Delete Confirmation';
177
      this.alertModalDeleteEntities.message = 'Are you sure you want to delete the selected entity(-ies)?';
178
      this.alertModalDeleteEntities.okButtonText = 'Yes';
179
      this.alertModalDeleteEntities.open();
180
    }
181
  }
182

    
183
  public confirmedDeleteEntities(data: any) {
184
    if (!Session.isLoggedIn()) {
185
      this._router.navigate(['/user-info'],
186
        {queryParams: {'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl': this._router.url}});
187
    } else {
188
      this.showLoading = true;
189
      this.updateErrorMessage = '';
190

    
191
      this._helpContentService.deleteEntities(this.selectedEntities, this.properties.adminToolsAPIURL).subscribe(
192
        _ => {
193
          this.deleteEntitiesFromArray(this.selectedEntities);
194
          this.showLoading = false;
195
        },
196
        error => this.handleUpdateError('System error deleting the selected entities', error)
197
      );
198
    }
199
  }
200

    
201
  public editEntity(i: number) {
202
    const entity: Entity = this.checkboxes[i].entity;
203
    this.myForm = this._fb.group({
204
      name: [entity.name, Validators.required],
205
      _id: entity._id,
206
      pid: [entity.pid, Validators.required],
207
    });
208
    this.modalErrorMessage = '';
209
    this.entitiesModalOpen(this.alertModalSaveEntity, '', 'Save Changes');
210
  }
211

    
212
  public newEntity() {
213
    this.myForm = this._fb.group({
214
      pid: ['', Validators.required],
215
      name: ['', Validators.required],
216
      isEnabled: '',
217
      _id: ''
218
    });
219
    this.modalErrorMessage = '';
220
    this.entitiesModalOpen(this.alertModalSaveEntity, '', 'Save');
221
  }
222

    
223
  private entitiesModalOpen(modal: any, title: string, yesBtn: string) {
224
    if (!Session.isLoggedIn()) {
225
      this._router.navigate(['/user-info'],
226
        {queryParams: {'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl': this._router.url}});
227
    } else {
228
      modal.cancelButton = true;
229
      modal.okButton = true;
230
      modal.alertTitle = title;
231
      modal.okButtonText = yesBtn;
232
      modal.open();
233
    }
234
  }
235

    
236
  public entitySaveConfirmed(data: any) {
237
    if (!Session.isLoggedIn()) {
238
      this._router.navigate(['/user-info'],
239
        {queryParams: {'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl': this._router.url}});
240
    } else {
241
      this.modalErrorMessage = '';
242
      if (this.myForm.getRawValue()['_id'].length > 0) {
243
        this._helpContentService.updateEntity(
244
          <Entity>this.myForm.value, this.properties.adminToolsAPIURL).subscribe(
245
          entity => {
246
            this.entityUpdatedSuccessfully(entity);
247
          },
248
          error => this.handleUpdateError('System error updating entity', error)
249
        );
250
      } else {
251
        this._helpContentService.saveEntity(<Entity>this.myForm.value, this.properties.adminToolsAPIURL).subscribe(
252
          entity => {
253
            this.entitySavedSuccessfully(entity);
254
          },
255
          error => this.handleUpdateError('System error creating entity', error)
256
        );
257
      }
258
    }
259
  }
260

    
261

    
262
  public entitySavedSuccessfully(entity: Entity) {
263
    this.checkboxes.push(<CheckEntity>{entity: entity, checked: false});
264
    this.applyCheck(false);
265
  }
266

    
267
  public entityUpdatedSuccessfully(entity: Entity) {
268
    this.checkboxes.find(checkItem => checkItem.entity._id === entity._id).entity = entity;
269
    this.applyCheck(false);
270
  }
271

    
272
  public filterBySearch(text: string) {
273
    this.searchText = new RegExp(text, 'i');
274
    this.applyFilter();
275
  }
276

    
277
  public applyFilter() {
278
    this.checkboxes = [];
279
    this.entities.filter(item => this.filterEntities(item)).forEach(
280
      _ => this.checkboxes.push(<CheckEntity>{entity: _, checked: false})
281
    );
282
  }
283

    
284
  public filterEntities(entity: Entity): boolean {
285
    const textFlag = this.searchText.toString() === '' || (entity.name).match(this.searchText) != null;
286
    return textFlag;
287
  }
288

    
289
  public applyStatusFilter() {
290
    this.checkboxes = [];
291
    this.entities.filter(item => this.filterEntitiesByStatus(item)).forEach(
292
      _ => this.checkboxes.push(<CheckEntity>{entity: _, checked: false})
293
    );
294
  }
295

    
296
  public filterEntitiesByStatus(entity: Entity): boolean {
297
    let status = this.filterForm.get("status").value;
298
    return  status == "all" || (status == "disabled" && !entity.isEnabled) || (status == "enabled" && entity.isEnabled);
299
  }
300

    
301
  handleError(message: string, error) {
302
    this.errorMessage = message;
303
    console.log('Server responded: ' + error);
304

    
305
    this.showLoading = false;
306
  }
307

    
308
  handleUpdateError(message: string, error) {
309
    if (error == null) {
310
      this.myForm = this._fb.group({
311
        pid: ['', Validators.required],
312
        name: ['', Validators.required],
313
        isEnabled: '',
314
        _id: ''
315
      });
316
    } else {
317
      this.updateErrorMessage = message;
318
      console.log('Server responded: ' + error);
319
    }
320

    
321
    this.showLoading = false;
322
  }
323

    
324
  public applyCommunityFilter(community_pid: string) {
325
    this.getEntities(community_pid);
326
  }
327

    
328
  public toggleEntities(status: boolean, ids: string[]) {
329
    // this.okModal.showModal();
330
    this.toggleIds = ids;
331
    this.toggleStatus = status;
332
    this.confirmRelatedPagesModalOpen();
333
  }
334

    
335
  private confirmRelatedPagesModalOpen() {
336
    if (!Session.isLoggedIn()) {
337
      this._router.navigate(['/user-info'],
338
        {queryParams: {'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl': this._router.url}});
339
    } else {
340
      this.alertModalRelatedPages.cancelButton = true;
341
      this.alertModalRelatedPages.okButton = true;
342
      this.alertModalRelatedPages.alertTitle = 'Warning';
343
      this.alertModalRelatedPages.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?";
344
      this.alertModalRelatedPages.okButtonText = 'Yes';
345
      this.alertModalRelatedPages.open();
346
    }
347
  }
348

    
349
  public continueToggling(event: any) {
350
    if (!Session.isLoggedIn()) {
351
      this._router.navigate(['/user-info'],
352
        {queryParams: {'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl': this._router.url}});
353
    } else {
354
      this.updateErrorMessage = '';
355
      this._helpContentService.toggleEntities(
356
        this.selectedCommunityPid, this.toggleIds, this.toggleStatus, this.properties.adminToolsAPIURL).subscribe(
357
        () => {
358
          for (let id of this.toggleIds) {
359
            const i = this.checkboxes.findIndex(_ => _.entity._id === id);
360
            this.checkboxes[i].entity.isEnabled = this.toggleStatus;
361
          }
362
          this.applyCheck(false);
363
        },
364
        error => this.handleUpdateError('System error changing the status of the selected entity(-ies)', error)
365
      );
366
    }
367
  }
368
}
(3-3/4)