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, FormGroup, Validators} from '@angular/forms';
5
import {CheckPage, Page} from '../../utils/entities/adminTool/page';
6
import {Entity} from '../../utils/entities/adminTool/entity';
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 {PortalUtils} from "../portal/portalHelper";
13
import {properties} from "../../../../environments/environment";
14
import {ConnectHelper} from "../../connect/connectHelper";
15
import {Option} from "../../sharedComponents/input/input.component";
16
import {AlertModal} from "../../utils/modal/alert";
17
import {SearchInputComponent} from "../../sharedComponents/search-input/search-input.component";
18
import {CheckPageHelpContent, PageHelpContent} from '../../utils/entities/adminTool/page-help-content';
19

    
20
declare var UIkit;
21

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