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

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

    
19
export class EntitiesComponent implements OnInit {
20

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

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

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

    
29
  public myForm: FormGroup;
30

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

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

    
37
  @ViewChild('AlertModalRelatedPages') alertModalRelatedPages;
38

    
39
  public toggleIds: string[];
40
  public toggleStatus: boolean;
41
  public properties: EnvProperties = null;
42

    
43
  public showLoading = true;
44
  public errorMessage = '';
45
  public updateErrorMessage = '';
46
  public modalErrorMessage = '';
47
  public isPortalAdministrator = null;
48
  public filterForm: FormControl;
49
  private subscriptions: any[] = [];
50

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

    
57
  ngOnInit() {
58
    this.filterForm = this._fb.control('');
59
    this.myForm = this._fb.group({
60
      pid: ['', Validators.required],
61
      name: ['', Validators.required],
62
      isEnabled: '',
63
      _id: ''
64
    });
65
    this.subscriptions.push(this.filterForm.valueChanges.subscribe(value => {
66
      this.filterBySearch(value);
67
    }));
68
    this.route.data
69
      .subscribe((data: { envSpecific: EnvProperties }) => {
70
        this.properties = data.envSpecific;
71

    
72
        this.route.queryParams.subscribe(params => {
73
          HelperFunctions.scroll();
74
          this.userManagementService.getUserInfo().subscribe(user => {
75
            this.selectedCommunityPid = params['communityId'];
76
            this.applyCommunityFilter(this.selectedCommunityPid);
77
            this.isPortalAdministrator = Session.isPortalAdministrator(user) && !this.selectedCommunityPid;
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
  getEntities(community_pid: 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 (community_pid) {
101
        this._helpContentService.getCommunityEntities(community_pid, 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 community 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
      const i = this.checkboxes.findIndex(_ => _.entity._id === id);
146
      this.checkboxes.splice(i, 1);
147
    }
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
    if (!Session.isLoggedIn()) {
166
      this._router.navigate(['/user-info'],
167
        {queryParams: {'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl': this._router.url}});
168
    } else {
169
      this.alertModalDeleteEntities.cancelButton = true;
170
      this.alertModalDeleteEntities.okButton = true;
171
      this.alertModalDeleteEntities.alertTitle = 'Delete Confirmation';
172
      this.alertModalDeleteEntities.message = 'Are you sure you want to delete the selected entity(-ies)?';
173
      this.alertModalDeleteEntities.okButtonText = 'Yes';
174
      this.alertModalDeleteEntities.open();
175
    }
176
  }
177

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

    
186
      this._helpContentService.deleteEntities(this.selectedEntities, this.properties.adminToolsAPIURL).subscribe(
187
        _ => {
188
          this.deleteEntitiesFromArray(this.selectedEntities);
189
          this.showLoading = false;
190
        },
191
        error => this.handleUpdateError('System error deleting the selected entities', error)
192
      );
193
    }
194
  }
195

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

    
207
  public newEntity() {
208
    this.myForm = this._fb.group({
209
      pid: ['', Validators.required],
210
      name: ['', Validators.required],
211
      isEnabled: '',
212
      _id: ''
213
    });
214
    this.modalErrorMessage = '';
215
    this.entitiesModalOpen(this.alertModalSaveEntity, '', 'Save');
216
  }
217

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

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

    
256

    
257
  public entitySavedSuccessfully(entity: Entity) {
258
    this.checkboxes.push(<CheckEntity>{entity: entity, checked: false});
259
    this.applyCheck(false);
260
  }
261

    
262
  public entityUpdatedSuccessfully(entity: Entity) {
263
    this.checkboxes.find(checkItem => checkItem.entity._id === entity._id).entity = entity;
264
    this.applyCheck(false);
265
  }
266

    
267
  public filterBySearch(text: string) {
268
    this.searchText = new RegExp(text, 'i');
269
    this.applyFilter();
270
  }
271

    
272
  public applyFilter() {
273
    this.checkboxes = [];
274
    this.entities.filter(item => this.filterEntities(item)).forEach(
275
      _ => this.checkboxes.push(<CheckEntity>{entity: _, checked: false})
276
    );
277
  }
278

    
279
  public filterEntities(entity: Entity): boolean {
280
    const textFlag = this.searchText.toString() === '' || (entity.name).match(this.searchText) != null;
281
    return textFlag;
282
  }
283

    
284
  handleError(message: string, error) {
285
    this.errorMessage = message;
286
    console.log('Server responded: ' + error);
287

    
288
    this.showLoading = false;
289
  }
290

    
291
  handleUpdateError(message: string, error) {
292
    if (error == null) {
293
      this.myForm = this._fb.group({
294
        pid: ['', Validators.required],
295
        name: ['', Validators.required],
296
        isEnabled: '',
297
        _id: ''
298
      });
299
    } else {
300
      this.updateErrorMessage = message;
301
      console.log('Server responded: ' + error);
302
    }
303

    
304
    this.showLoading = false;
305
  }
306

    
307
  public applyCommunityFilter(community_pid: string) {
308
    this.getEntities(community_pid);
309
  }
310

    
311
  public toggleEntities(status: boolean, ids: string[]) {
312
    // this.okModal.showModal();
313
    this.toggleIds = ids;
314
    this.toggleStatus = status;
315
    this.confirmRelatedPagesModalOpen();
316
  }
317

    
318
  private confirmRelatedPagesModalOpen() {
319
    if (!Session.isLoggedIn()) {
320
      this._router.navigate(['/user-info'],
321
        {queryParams: {'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl': this._router.url}});
322
    } else {
323
      this.alertModalRelatedPages.cancelButton = true;
324
      this.alertModalRelatedPages.okButton = true;
325
      this.alertModalRelatedPages.alertTitle = 'Warning';
326
      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?";
327
      this.alertModalRelatedPages.okButtonText = 'Yes';
328
      this.alertModalRelatedPages.open();
329
    }
330
  }
331

    
332
  public continueToggling(event: any) {
333
    if (!Session.isLoggedIn()) {
334
      this._router.navigate(['/user-info'],
335
        {queryParams: {'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl': this._router.url}});
336
    } else {
337
      this.updateErrorMessage = '';
338
      this._helpContentService.toggleEntities(
339
        this.selectedCommunityPid, this.toggleIds, this.toggleStatus, this.properties.adminToolsAPIURL).subscribe(
340
        () => {
341
          for (let id of this.toggleIds) {
342
            const i = this.checkboxes.findIndex(_ => _.entity._id === id);
343
            this.checkboxes[i].entity.isEnabled = this.toggleStatus;
344
          }
345
          this.applyCheck(false);
346
        },
347
        error => this.handleUpdateError('System error changing the status of the selected entity(-ies)', error)
348
      );
349
    }
350
  }
351
}
(2-2/3)