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 {FormArray, FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
5
import {CheckPage, Page} from '../../utils/entities/adminTool/page';
6
import {Portal} from '../../utils/entities/adminTool/portal';
7
import {CheckEntity, Entity} from '../../utils/entities/adminTool/entity';
8
import {EnvProperties} from '../../utils/properties/env-properties';
9
import {Session} from '../../login/utils/helper.class';
10
import {LoginErrorCodes} from '../../login/utils/guardHelper.class';
11
import {HelperFunctions} from '../../utils/HelperFunctions.class';
12
import {UserManagementService} from '../../services/user-management.service';
13
import {Observable, Subscriber} from "rxjs";
14
import {map, startWith} from "rxjs/operators";
15
import {MatAutocompleteSelectedEvent} from "@angular/material";
16
import {PortalUtils} from "../portal/portalHelper";
17
import {properties} from "../../../../environments/environment";
18
import {ConnectHelper} from "../../connect/connectHelper";
19
import {Option} from "../../sharedComponents/input/input.component";
20
import {AlertModal} from "../../utils/modal/alert";
21

    
22
@Component({
23
  selector: 'pages',
24
  templateUrl: './pages.component.html',
25
})
26

    
27
export class PagesComponent implements OnInit {
28
  
29
  @ViewChild('editModal') editModal: AlertModal;
30
  @ViewChild('deleteModal') deleteModal: AlertModal;
31
  private selectedPages: string[] = [];
32
  
33
  public checkboxes: CheckPage[] = [];
34
  
35
  public pages: Page[] = [];
36
  public pageWithDivIds: string[] = [];
37
  
38
  //public errorMessage: string;
39
  
40
  public pageForm: FormGroup;
41
  
42
  private searchText: RegExp = new RegExp('');
43
  public keyword: string = '';
44
  
45
  public portal: string;
46
  
47
  public pagesType: string;
48
  public properties: EnvProperties = properties;
49
  
50
  public showLoading: boolean = true;
51
  public errorMessage: string = '';
52
  public updateErrorMessage: string = '';
53
  public modalErrorMessage: string = '';
54
  public isPortalAdministrator = null;
55
  public filterForm: FormGroup;
56
  public typeOptions = [{label: 'Search', value: 'search'}, {
57
    label: 'Share',
58
    value: 'share'
59
  }, {label: 'Landing', value: 'landing'}, {label: 'HTML', value: 'html'}, {
60
    label: 'Link',
61
    value: 'link'
62
  }, {label: 'Other', value: 'other'}];
63
  public entitiesCtrl: FormArray;
64
  @ViewChild('PageInput') pageInput: ElementRef<HTMLInputElement>;
65
  allEntities: Option[] = [];
66
  private subscriptions: any[] = [];
67
  public portalUtils: PortalUtils = new PortalUtils();
68
  private index: number;
69
  
70
  constructor(private element: ElementRef, private route: ActivatedRoute,
71
              private _router: Router, private _helpContentService: HelpContentService,
72
              private userManagementService: UserManagementService, private _fb: FormBuilder) {
73
  }
74
  
75
  ngOnInit() {
76
    this.filterForm = this._fb.group({
77
      keyword: [''],
78
      type: ['all', Validators.required]
79
    });
80
    this.subscriptions.push(this.filterForm.get('keyword').valueChanges.subscribe(value => {
81
      this.searchText = new RegExp(value, 'i');
82
      this.applyFilters();
83
    }));
84
    this.subscriptions.push(this.filterForm.get('type').valueChanges.subscribe(value => {
85
      this.applyFilters();
86
    }));
87
    this.subscriptions.push(this.route.queryParams.subscribe(params => {
88
      this.pagesType = '';
89
      if (params['type']) {
90
        // this.pagesType = params['type'];
91
        this.filterForm.get('type').setValue(params['type']);
92
      }
93
      this.portal = (this.route.snapshot.data.portal) ? this.route.snapshot.data.portal : this.route.snapshot.params[this.route.snapshot.data.param];
94
      if (this.portal === 'connect' || this.portal === 'explore') {
95
        ConnectHelper.setPortalTypeFromPid(this.portal);
96
      }
97
      this.keyword = '';
98
      this.subscriptions.push(this.userManagementService.getUserInfo().subscribe(user => {
99
        this.applyPortalFilter(this.portal);
100
        this.isPortalAdministrator = Session.isPortalAdministrator(user) && !this.portal;
101
      }));
102
    }));
103
    
104
    this.subscriptions.push(this._helpContentService.getEntities(this.properties.adminToolsAPIURL).subscribe(
105
      entities => {
106
        this.allEntities = [];
107
        entities.forEach(entity => {
108
         this.allEntities.push({
109
           label: entity.name,
110
           value: entity
111
         });
112
        });
113
        this.showLoading = false;
114
      },
115
      error => this.handleError('System error retrieving pages', error)));
116
    
117
    
118
  }
119
  
120
  ngOnDestroy(): void {
121
    this.subscriptions.forEach(value => {
122
      if (value instanceof Subscriber) {
123
        value.unsubscribe();
124
      } else if (value instanceof Function) {
125
        value();
126
      }
127
    });
128
  }
129
  
130
  getPages(portal: string) {
131
    if (!Session.isLoggedIn()) {
132
      this._router.navigate(['/user-info'], {
133
        queryParams: {
134
          'errorCode': LoginErrorCodes.NOT_VALID,
135
          'redirectUrl': this._router.url
136
        }
137
      });
138
    } else {
139
      this.showLoading = true;
140
      this.updateErrorMessage = '';
141
      this.errorMessage = '';
142
      
143
      this.pageWithDivIds = [];
144
      
145
      let parameters = '';
146
      if (this.pagesType) {
147
        parameters = '?page_type=' + this.pagesType;
148
      }
149
      if (portal) {
150
        this.subscriptions.push(this._helpContentService.getCommunityPagesByType(portal, parameters, this.properties.adminToolsAPIURL).subscribe(
151
          pages => {
152
            this.pagesReturned(pages);
153
            //if(!this.pagesType || this.pagesType == "link") {
154
            this.getPagesWithDivIds(portal);
155
            //} else {
156
            //this.showLoading = false;
157
            //}
158
          },
159
          error => this.handleError('System error retrieving pages', error)
160
        ));
161
      } else {
162
        this.subscriptions.push(this._helpContentService.getAllPagesFull(this.properties.adminToolsAPIURL).subscribe(
163
          pages => {
164
            this.pagesReturned(pages);
165
            this.showLoading = false;
166
          },
167
          error => this.handleError('System error retrieving pages', error)
168
        ));
169
      }
170
    }
171
  }
172
  
173
  getPagesWithDivIds(portal: string) {
174
    if (!Session.isLoggedIn()) {
175
      this._router.navigate(['/user-info'], {
176
        queryParams: {
177
          'errorCode': LoginErrorCodes.NOT_VALID,
178
          'redirectUrl': this._router.url
179
        }
180
      });
181
    } else {
182
      this.subscriptions.push(this._helpContentService.getPageIdsFromDivIds(portal, this.properties.adminToolsAPIURL).subscribe(
183
        pages => {
184
          this.pageWithDivIds = pages;
185
          this.showLoading = false;
186
        },
187
        error => this.handleError('System error retrieving information about pages\' classes', error)));
188
    }
189
  }
190
  
191
  pagesReturned(pages: Page[]) {
192
    this.pages = pages;
193
    this.checkboxes = [];
194
    
195
    if (pages) {
196
      pages.forEach(_ => {
197
        this.checkboxes.push(<CheckPage>{page: _, checked: false});
198
      });
199
    }
200
  }
201
  
202
  /*
203
      getPortals() {
204
          this._helpContentService.getCommunities(this.properties.adminToolsAPIURL).subscribe(
205
              communities => {
206
                  this.communities = communities;
207
                  this.portal = this.communities[0].pid;
208
                  this.getPages(this.portal);
209
                  this.getPagesWithDivIds(this.portal);
210
          },
211
          error => this.handleError('System error retrieving communities', error));
212
      }
213
  */
214
  
215
  public toggleCheckBoxes(event) {
216
    this.checkboxes.forEach(_ => _.checked = event.target.checked);
217
  }
218
  
219
  public applyCheck(flag: boolean) {
220
    this.checkboxes.forEach(_ => _.checked = flag);
221
  }
222
  
223
  public getSelectedPages(): string[] {
224
    return this.checkboxes.filter(page => page.checked == true).map(checkedPage => checkedPage.page).map(res => res._id);
225
  }
226
  
227
  private deletePagesFromArray(ids: string[]): void {
228
    for (let id of ids) {
229
      let i = this.pages.findIndex(_ => _._id == id);
230
      this.pages.splice(i, 1);
231
    }
232
    this.applyFilters();
233
  }
234
  
235
  public confirmDeletePage(id: string) {
236
    //this.deleteConfirmationModal.ids = [id];
237
    //this.deleteConfirmationModal.showModal();
238
    this.selectedPages = [id];
239
    this.confirmModalOpen();
240
  }
241
  
242
  public confirmDeleteSelectedPages() {
243
    //this.deleteConfirmationModal.ids = this.getSelectedPages();
244
    //this.deleteConfirmationModal.showModal();
245
    this.selectedPages = this.getSelectedPages();
246
    this.confirmModalOpen();
247
  }
248
  
249
  private confirmModalOpen() {
250
    if (!Session.isLoggedIn()) {
251
      this._router.navigate(['/user-info'], {
252
        queryParams: {
253
          'errorCode': LoginErrorCodes.NOT_VALID,
254
          'redirectUrl': this._router.url
255
        }
256
      });
257
    } else {
258
      this.deleteModal.cancelButton = true;
259
      this.deleteModal.okButton = true;
260
      this.deleteModal.alertTitle = 'Delete Confirmation';
261
      this.deleteModal.message = 'Are you sure you want to delete the selected page(s)?';
262
      this.deleteModal.okButtonText = 'Yes';
263
      this.deleteModal.open();
264
    }
265
  }
266
  
267
  public confirmedDeletePages(data: any) {
268
    if (!Session.isLoggedIn()) {
269
      this._router.navigate(['/user-info'], {
270
        queryParams: {
271
          'errorCode': LoginErrorCodes.NOT_VALID,
272
          'redirectUrl': this._router.url
273
        }
274
      });
275
    } else {
276
      this.showLoading = true;
277
      this.updateErrorMessage = '';
278
      
279
      this.subscriptions.push(this._helpContentService.deletePages(this.selectedPages, this.properties.adminToolsAPIURL).subscribe(
280
        _ => {
281
          this.deletePagesFromArray(this.selectedPages);
282
          this.showLoading = false;
283
        },
284
        error => this.handleUpdateError('System error deleting the selected pages', error)
285
      ));
286
    }
287
  }
288
  
289
  public editPage(i: number) {
290
    this.entitiesCtrl = this._fb.array([]);
291
    let page: Page = this.checkboxes[i].page;
292
    this.index = this.pages.findIndex(value => value._id === page._id);
293
    this.pageForm = this._fb.group({
294
      _id: this._fb.control(page._id),
295
      route: this._fb.control(page.route, Validators.required),
296
      name: this._fb.control(page.name, Validators.required),
297
      isEnabled: this._fb.control(page.isEnabled),
298
      portalType: this._fb.control(page.portalType, Validators.required),
299
      top: this._fb.control(page.top),
300
      bottom: this._fb.control(page.bottom),
301
      left: this._fb.control(page.left),
302
      right: this._fb.control(page.right),
303
      type: this._fb.control(page.type, Validators.required),
304
      entities: this.entitiesCtrl
305
    });
306
    this.pageForm.get('portalType').disable();
307
    for (let i = 0; i < page.entities.length; i++) {
308
      this.entitiesCtrl.push(this._fb.control(page.entities[i]));
309
    }
310
    this.modalErrorMessage = '';
311
    this.pagesModalOpen('Edit Page', 'Save changes');
312
  }
313
  
314
  public newPage() {
315
    if(this.pageForm) {
316
      this.pageForm.get('portalType').enable();
317
    }
318
    this.entitiesCtrl = this._fb.array([]);
319
    this.pageForm = this._fb.group({
320
      _id: this._fb.control(null),
321
      route: this._fb.control('', Validators.required),
322
      name: this._fb.control('', Validators.required),
323
      isEnabled: this._fb.control(true),
324
      portalType: this._fb.control('', Validators.required),
325
      top: this._fb.control(true),
326
      bottom: this._fb.control(true),
327
      left: this._fb.control(true),
328
      right: this._fb.control(true),
329
      type: this._fb.control(this.typeOptions[0].value, Validators.required),
330
      entities: this.entitiesCtrl,
331
    });
332
    this.modalErrorMessage = '';
333
    this.pagesModalOpen('Create Page', 'Create');
334
  }
335
  
336
  private pagesModalOpen(title: string, yesBtn: string) {
337
    if (!Session.isLoggedIn()) {
338
      this._router.navigate(['/user-info'], {
339
        queryParams: {
340
          'errorCode': LoginErrorCodes.NOT_VALID,
341
          'redirectUrl': this._router.url
342
        }
343
      });
344
    } else {
345
      this.editModal.cancelButton = true;
346
      this.editModal.okButton = true;
347
      this.editModal.okButtonLeft = false;
348
      this.editModal.alertTitle = title;
349
      this.editModal.okButtonText = yesBtn;
350
      this.editModal.open();
351
    }
352
  }
353
  
354
  public pageSaveConfirmed(data: any) {
355
    if (!Session.isLoggedIn()) {
356
      this._router.navigate(['/user-info'], {
357
        queryParams: {
358
          'errorCode': LoginErrorCodes.NOT_VALID,
359
          'redirectUrl': this._router.url
360
        }
361
      });
362
    } else {
363
      if (!this.pageForm.value._id) {
364
        this.modalErrorMessage = '';
365
        this.subscriptions.push(this._helpContentService.savePage(<Page>this.pageForm.value, this.properties.adminToolsAPIURL).subscribe(
366
          page => {
367
            this.pageSavedSuccessfully(page, true);
368
          },
369
          error => this.handleUpdateError('System error creating page', error)
370
        ));
371
      } else {
372
        this.pageForm.get('portalType').enable();
373
        this.subscriptions.push(this._helpContentService.updatePage(<Page>this.pageForm.value, this.properties.adminToolsAPIURL).subscribe(
374
          page => {
375
            this.pageSavedSuccessfully(page, false);
376
          },
377
          error => this.handleUpdateError('System error updating page', error)
378
        ));
379
      }
380
      
381
    }
382
  }
383
  
384
  public pageSavedSuccessfully(page: Page, isNew: boolean) {
385
    if (isNew) {
386
      this.pages.push(page);
387
    } else {
388
      this.pages[this.index] = page;
389
    }
390
    this.applyFilters();
391
    this.applyCheck(false);
392
  }
393
  
394
  public applyFilters() {
395
    this.checkboxes = [];
396
    this.pages.filter(item => this.filterByType(item)).forEach(
397
      _ => this.checkboxes.push(<CheckPage>{page: _, checked: false})
398
    );
399
    this.checkboxes = this.checkboxes.filter(item => this.filterPages(item.page));
400
  }
401
  
402
  public filterByType(page: Page): boolean {
403
    let type = this.filterForm.get("type").value;
404
    return type == "all" || (type == page.type);
405
  }
406
  
407
  public filterPages(page: Page): boolean {
408
    let textFlag = this.searchText.toString() == '' || (page.route + ' ' + page.name + ' ' + page.portalType).match(this.searchText) != null;
409
    return textFlag;
410
  }
411
  
412
  handleError(message: string, error) {
413
    // if(error == null) {
414
    //     this.formComponent.reset();
415
    // } else {
416
    this.errorMessage = message;// + ' (Server responded: ' + error + ')';
417
    console.log('Server responded: ' + error);
418
    //}
419
    
420
    this.showLoading = false;
421
  }
422
  
423
  handleUpdateError(message: string, error) {
424
    if (error == null) {
425
      // this.formComponent.reset();
426
      this.pageForm = this._fb.group({
427
        route: this._fb.control('', Validators.required),
428
        name: this._fb.control('', Validators.required),
429
        isEnabled: this._fb.control(true),
430
        portalType: this._fb.control('', Validators.required),
431
        top: this._fb.control(true),
432
        bottom: this._fb.control(true),
433
        left: this._fb.control(true),
434
        right: this._fb.control(true),
435
        type: this._fb.control(this.typeOptions[0].value, Validators.required),
436
        entities: this.entitiesCtrl,
437
        _id: this._fb.control(''),
438
      });
439
    } else {
440
      this.updateErrorMessage = message;// + ' (Server responded: ' + error + ')';
441
      console.log('Server responded: ' + error);
442
    }
443
    
444
    this.showLoading = false;
445
  }
446
  
447
  // public filterByPortal(event: any) {
448
  //     this.portal = event.target.value;
449
  //     this.applyPortalFilter(this.portal);
450
  // }
451
  
452
  public applyPortalFilter(portal: string) {
453
    this.getPages(portal);
454
  }
455
  
456
  public togglePages(status: boolean, ids: string[]) {
457
    if (!Session.isLoggedIn()) {
458
      this._router.navigate(['/user-info'], {
459
        queryParams: {
460
          'errorCode': LoginErrorCodes.NOT_VALID,
461
          'redirectUrl': this._router.url
462
        }
463
      });
464
    } else {
465
      this.updateErrorMessage = '';
466
      
467
      this.subscriptions.push(this._helpContentService.togglePages(this.portal, ids, status, this.properties.adminToolsAPIURL).subscribe(
468
        () => {
469
          for (let id of ids) {
470
            let i = this.checkboxes.findIndex(_ => _.page._id == id);
471
            this.checkboxes[i].page.isEnabled = status;
472
          }
473
          this.applyCheck(false);
474
        },
475
        error => this.handleUpdateError('System error changing the status of the selected page(s)', error)
476
      ));
477
    }
478
  }
479
  
480
  public capitalizeFirstLetter(str: string) {
481
    return str.charAt(0).toUpperCase() + str.slice(1);
482
  }
483
}
(3-3/4)