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

    
19
@Component({
20
  selector: 'pages',
21
  templateUrl: './pages.component.html',
22
})
23

    
24
export class PagesComponent implements OnInit {
25

    
26
  @ViewChild('AlertModalSavePage') alertModalSavePage;
27
  @ViewChild('AlertModalDeletePages') alertModalDeletePages;
28
  private selectedPages: string[] = [];
29

    
30
  public checkboxes: CheckPage[] = [];
31

    
32
  public pages: Page[] = [];
33
  public pageWithDivIds: string[] = [];
34

    
35
  //public errorMessage: string;
36

    
37
  public myForm: FormGroup;
38

    
39
  private searchText: RegExp = new RegExp('');
40
  public keyword: string = '';
41

    
42
  public communities: Portal[] = [];
43

    
44
  public selectedCommunityPid: string;
45

    
46
  public pagesType: string;
47
  public properties: EnvProperties = null;
48

    
49
  public showLoading: boolean = true;
50
  public errorMessage: string = '';
51
  public updateErrorMessage: string = '';
52
  public modalErrorMessage: string = '';
53
  public isPortalAdministrator = null;
54
  public filterForm: FormGroup;
55
  public typeOptions = [{label: 'Search', value: 'search'},   {
56
    label: 'Share',
57
    value: 'share'
58
  }, {label: 'Landing', value: 'landing'}, {label: 'HTML', value: 'html'}, {
59
    label: 'Link',
60
    value: 'link'
61
  }, {label: 'Other', value: 'other'}];
62
  public entitiesCtrl: FormArray;
63
  @ViewChild('PageInput') pageInput: ElementRef<HTMLInputElement>;
64
  public entitiesSearchCtrl: FormControl;
65
  filteredEntities: Observable<Entity[]>;
66
  selectedEntities: Entity[] = [];
67
  allEntities: Entity[] = [];
68

    
69
  private subscriptions: any[] = [];
70
  public portalUtils:PortalUtils = new PortalUtils();
71
  constructor(private element: ElementRef, private route: ActivatedRoute,
72
              private _router: Router, private _helpContentService: HelpContentService,
73
              private userManagementService: UserManagementService, private _fb: FormBuilder) {
74
  }
75

    
76
  ngOnInit() {
77
    this.filterForm =  this._fb.group({
78
      keyword: [''],
79
      type: ['all', Validators.required]});
80
    this.subscriptions.push(this.filterForm.get('keyword').valueChanges.subscribe(value => {
81
      this.filterBySearch(value);
82
    }));
83
    this.subscriptions.push(this.filterForm.get('type').valueChanges.subscribe(value => {
84
      this.applyTypeFilter();
85
    }));
86
    this.entitiesSearchCtrl = this._fb.control('');
87
    this.myForm = this._fb.group({
88
      route: ['', Validators.required],
89
      name: ['', Validators.required],
90
      isEnabled: true,
91
      portalType: ['', Validators.required],
92
      top: true,
93
      bottom: true,
94
      left: true,
95
      right: true,
96
      type: ['', Validators.required],
97
      entities: this.entitiesCtrl,
98
      _id: '',
99
    });
100

    
101
    this.properties = properties;
102
    this.subscriptions.push(this.route.queryParams.subscribe(params => {
103
      HelperFunctions.scroll();
104

    
105
      this.pagesType = '';
106
      if (params['type']) {
107
        // this.pagesType = params['type'];
108
        this.filterForm.get('type').setValue(params['type']);
109
      }
110
      this.selectedCommunityPid = params['communityId'];
111
      this.keyword = '';
112
      this.subscriptions.push(this.userManagementService.getUserInfo().subscribe(user => {
113
        this.applyCommunityFilter(this.selectedCommunityPid);
114
        this.isPortalAdministrator = Session.isPortalAdministrator(user) && !this.selectedCommunityPid;
115
      }));
116
      //this.getCommunities();
117
    }));
118

    
119
    this.subscriptions.push(this._helpContentService.getEntities(this.properties.adminToolsAPIURL).subscribe(
120
      entities => {
121
        this.allEntities = entities;
122
        this.showLoading = false;
123
      },
124
      error => this.handleError('System error retrieving pages', error)));
125

    
126

    
127
  }
128

    
129
  ngOnDestroy(): void {
130
    this.subscriptions.forEach(value => {
131
      if (value instanceof Subscriber) {
132
        value.unsubscribe();
133
      } else if (value instanceof Function) {
134
        value();
135
      }
136
    });
137
  }
138

    
139
  getPages(community_pid: string) {
140
    if (!Session.isLoggedIn()) {
141
      this._router.navigate(['/user-info'], {
142
        queryParams: {
143
          'errorCode': LoginErrorCodes.NOT_VALID,
144
          'redirectUrl': this._router.url
145
        }
146
      });
147
    } else {
148
      this.showLoading = true;
149
      this.updateErrorMessage = '';
150
      this.errorMessage = '';
151

    
152
      this.pageWithDivIds = [];
153

    
154
      let parameters = '';
155
      if (this.pagesType) {
156
        parameters = '?page_type=' + this.pagesType;
157
      }
158
      if (community_pid) {
159
        this.subscriptions.push(this._helpContentService.getCommunityPagesByType(community_pid, parameters, this.properties.adminToolsAPIURL).subscribe(
160
          pages => {
161
            this.pagesReturned(pages);
162
            //if(!this.pagesType || this.pagesType == "link") {
163
            this.getPagesWithDivIds(community_pid);
164
            //} else {
165
            //this.showLoading = false;
166
            //}
167
          },
168
          error => this.handleError('System error retrieving pages', error)
169
        ));
170
      } else {
171
        this.subscriptions.push(this._helpContentService.getAllPagesFull(this.properties.adminToolsAPIURL).subscribe(
172
          pages => {
173
            this.pagesReturned(pages);
174
            this.showLoading = false;
175
          },
176
          error => this.handleError('System error retrieving pages', error)
177
        ));
178
      }
179
    }
180
  }
181

    
182
  getPagesWithDivIds(community_pid: string) {
183
    if (!Session.isLoggedIn()) {
184
      this._router.navigate(['/user-info'], {
185
        queryParams: {
186
          'errorCode': LoginErrorCodes.NOT_VALID,
187
          'redirectUrl': this._router.url
188
        }
189
      });
190
    } else {
191
      this.subscriptions.push(this._helpContentService.getPageIdsFromDivIds(community_pid, this.properties.adminToolsAPIURL).subscribe(
192
        pages => {
193
          this.pageWithDivIds = pages;
194
          this.showLoading = false;
195
        },
196
        error => this.handleError('System error retrieving information about pages\' classes', error)));
197
    }
198
  }
199

    
200
  pagesReturned(pages: Page[]) {
201
    this.pages = pages;
202
    this.checkboxes = [];
203

    
204
    if (pages) {
205
      pages.forEach(_ => {
206
        this.checkboxes.push(<CheckPage>{page: _, checked: false});
207
      });
208
    }
209
  }
210

    
211
  /*
212
      getCommunities() {
213
          this._helpContentService.getCommunities(this.properties.adminToolsAPIURL).subscribe(
214
              communities => {
215
                  this.communities = communities;
216
                  this.selectedCommunityPid = this.communities[0].pid;
217
                  this.getPages(this.selectedCommunityPid);
218
                  this.getPagesWithDivIds(this.selectedCommunityPid);
219
          },
220
          error => this.handleError('System error retrieving communities', error));
221
      }
222
  */
223

    
224
  public toggleCheckBoxes(event) {
225
    this.checkboxes.forEach(_ => _.checked = event.target.checked);
226
  }
227

    
228
  public applyCheck(flag: boolean) {
229
    this.checkboxes.forEach(_ => _.checked = flag);
230
  }
231

    
232
  public getSelectedPages(): string[] {
233
    return this.checkboxes.filter(page => page.checked == true).map(checkedPage => checkedPage.page).map(res => res._id);
234
  }
235

    
236
  private deletePagesFromArray(ids: string[]): void {
237
    for (let id of ids) {
238
      let i = this.checkboxes.findIndex(_ => _.page._id == id);
239
      this.checkboxes.splice(i, 1);
240
    }
241
  }
242

    
243
  public confirmDeletePage(id: string) {
244
    //this.deleteConfirmationModal.ids = [id];
245
    //this.deleteConfirmationModal.showModal();
246
    this.selectedPages = [id];
247
    this.confirmModalOpen();
248
  }
249

    
250
  public confirmDeleteSelectedPages() {
251
    //this.deleteConfirmationModal.ids = this.getSelectedPages();
252
    //this.deleteConfirmationModal.showModal();
253
    this.selectedPages = this.getSelectedPages();
254
    this.confirmModalOpen();
255
  }
256

    
257
  private confirmModalOpen() {
258
    if (!Session.isLoggedIn()) {
259
      this._router.navigate(['/user-info'], {
260
        queryParams: {
261
          'errorCode': LoginErrorCodes.NOT_VALID,
262
          'redirectUrl': this._router.url
263
        }
264
      });
265
    } else {
266
      this.alertModalDeletePages.cancelButton = true;
267
      this.alertModalDeletePages.okButton = true;
268
      this.alertModalDeletePages.alertTitle = 'Delete Confirmation';
269
      this.alertModalDeletePages.message = 'Are you sure you want to delete the selected page(s)?';
270
      this.alertModalDeletePages.okButtonText = 'Yes';
271
      this.alertModalDeletePages.open();
272
    }
273
  }
274

    
275
  public confirmedDeletePages(data: any) {
276
    if (!Session.isLoggedIn()) {
277
      this._router.navigate(['/user-info'], {
278
        queryParams: {
279
          'errorCode': LoginErrorCodes.NOT_VALID,
280
          'redirectUrl': this._router.url
281
        }
282
      });
283
    } else {
284
      this.showLoading = true;
285
      this.updateErrorMessage = '';
286

    
287
      this.subscriptions.push(this._helpContentService.deletePages(this.selectedPages, this.properties.adminToolsAPIURL).subscribe(
288
        _ => {
289
          this.deletePagesFromArray(this.selectedPages);
290
          this.showLoading = false;
291
        },
292
        error => this.handleUpdateError('System error deleting the selected pages', error)
293
      ));
294
    }
295
  }
296

    
297
  public editPage(i: number) {
298
    this.entitiesCtrl = this._fb.array([]);
299
    let page: Page = this.checkboxes[i].page;
300
    this.myForm = this._fb.group({
301
      route: [page.route, Validators.required],
302
      name: [page.name, Validators.required],
303
      isEnabled: page.isEnabled,
304
      portalType: ['', Validators.required],
305
      top: page.top,
306
      bottom: page.bottom,
307
      left: page.left,
308
      right: page.right,
309
      type: [page.type, Validators.required],
310
      entities: this.entitiesCtrl,
311
      _id: page._id,
312
    });
313
    this.myForm.controls['portalType'].disable();
314

    
315
    for (let i = 0; i < page.entities.length; i++) {
316
      this.entitiesCtrl.push(this._fb.control(page.entities[i]));
317
    }
318
    this.filteredEntities = this.entitiesSearchCtrl.valueChanges.pipe(startWith(''),
319
      map(page => this._filter(page)));
320
    this.selectedEntities = JSON.parse(JSON.stringify(page.entities));
321
    this.modalErrorMessage = '';
322
    this.pagesModalOpen(this.alertModalSavePage, '', 'Save changes');
323
  }
324

    
325
  private _filter(value: string): Entity[] {
326
    if (!value || value.length == 0) {
327
      return this.allEntities.slice();
328
    }
329
    const filterValue = value.toString().toLowerCase();
330
    return this.allEntities.filter(page => page.name.toLowerCase().indexOf(filterValue) != -1);
331
  }
332

    
333
  public newPage() {
334
    this.myForm.controls['portalType'].enable();
335

    
336
    this.entitiesCtrl = this._fb.array([]);
337
    this.myForm = this._fb.group({
338
      route: ['', Validators.required],
339
      name: ['', Validators.required],
340
      isEnabled: true,
341
      portalType: ['', Validators.required],
342
      top: true,
343
      bottom: true,
344
      left: true,
345
      right: true,
346
      type: [this.typeOptions[0].value, Validators.required],
347
      entities: this._fb.array([]),
348
      _id: '',
349
    });
350
    this.selectedEntities = [];
351
    this.modalErrorMessage = '';
352
    this.filteredEntities = this.entitiesSearchCtrl.valueChanges.pipe(startWith(''),
353
      map(page => this._filter(page)));
354
    this.pagesModalOpen(this.alertModalSavePage, '', 'Save');
355
  }
356

    
357
  private pagesModalOpen(modal: any, title: string, yesBtn: string) {
358
    if (!Session.isLoggedIn()) {
359
      this._router.navigate(['/user-info'], {
360
        queryParams: {
361
          'errorCode': LoginErrorCodes.NOT_VALID,
362
          'redirectUrl': this._router.url
363
        }
364
      });
365
    } else {
366
      modal.cancelButton = true;
367
      modal.okButton = true;
368
      modal.alertTitle = title;
369
      modal.okButtonText = yesBtn;
370
      modal.open();
371
    }
372
  }
373

    
374
  public pageSaveConfirmed(data: any) {
375
    if (!Session.isLoggedIn()) {
376
      this._router.navigate(['/user-info'], {
377
        queryParams: {
378
          'errorCode': LoginErrorCodes.NOT_VALID,
379
          'redirectUrl': this._router.url
380
        }
381
      });
382
    } else {
383
      console.log(this.myForm.value)
384
      if (this.myForm.value['_id'].length == 0) {
385
        this.myForm.controls['portalType'].enable();
386

    
387
        this.modalErrorMessage = '';
388
        this.subscriptions.push(this._helpContentService.savePage(<Page>this.myForm.value, this.properties.adminToolsAPIURL).subscribe(
389
          page => {
390
            this.pageSavedSuccessfully(page, true);
391
          },
392
          error => this.handleUpdateError('System error creating page', error)
393
        ));
394
      } else {
395
        this.subscriptions.push(this._helpContentService.updatePage(<Page>this.myForm.value, this.properties.adminToolsAPIURL).subscribe(
396
          page => {
397
            this.pageSavedSuccessfully(page, false);
398
          },
399
          error => this.handleUpdateError('System error updating page', error)
400
        ));
401
      }
402

    
403
    }
404
  }
405

    
406
  /* public pageUpdateConfirmed(data: any) {
407
     if (!Session.isLoggedIn()) {
408
       this._router.navigate(['/user-info'], {queryParams: {'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl': this._router.url}});
409
     } else {
410
       if (!this.myForm.valid) {
411
         this.pagesModalOpen(this.alertModalSavePage, 'Update', 'Update Page');
412
         this.modalErrorMessage = 'Please fill in all required fields marked with *';
413
       } else {
414
         this._helpContentService.updatePage(<Page>this.myForm.value, this.properties.adminToolsAPIURL).subscribe(
415
           page => {
416
             this.pageUpdatedSuccessfully(page);
417
           },
418
           error => this.handleUpdateError('System error updating page', error)
419
         );
420
       }
421
     }
422
   }*/
423

    
424
  public pageSavedSuccessfully(page: Page, isNew: boolean) {
425
    if (isNew) {
426
      this.checkboxes.push(<CheckPage>{page: page, checked: false});
427
    } else {
428
      this.checkboxes.find(checkItem => checkItem.page._id == page._id).page = page;
429
    }
430
    this.applyCheck(false);
431
  }
432

    
433

    
434
  public filterBySearch(text: string) {
435
    this.searchText = new RegExp(text, 'i');
436
    this.applyFilter();
437
  }
438

    
439
  public applyFilter() {
440
    this.checkboxes = [];
441
    this.pages.filter(item => this.filterPages(item)).forEach(
442
      _ => this.checkboxes.push(<CheckPage>{page: _, checked: false})
443
    );
444
  }
445
  public applyTypeFilter() {
446
    this.checkboxes = [];
447
    this.pages.filter(item => this.filterByType(item)).forEach(
448
      _ => this.checkboxes.push(<CheckPage>{page: _, checked: false})
449
    );
450
  }
451

    
452
  public filterByType(page: Page): boolean {
453
    let type = this.filterForm.get("type").value;
454
    return  type == "all" || (type  == page.type);
455
  }
456
  public filterPages(page: Page): boolean {
457
    let textFlag = this.searchText.toString() == '' || (page.route + ' ' + page.name + ' ' + page.portalType).match(this.searchText) != null;
458
    return textFlag;
459
  }
460

    
461
  handleError(message: string, error) {
462
    // if(error == null) {
463
    //     this.formComponent.reset();
464
    // } else {
465
    this.errorMessage = message;// + ' (Server responded: ' + error + ')';
466
    console.log('Server responded: ' + error);
467
    //}
468

    
469
    this.showLoading = false;
470
  }
471

    
472
  handleUpdateError(message: string, error) {
473
    if (error == null) {
474
      // this.formComponent.reset();
475
      this.myForm = this._fb.group({
476
        route: ['', Validators.required],
477
        name: ['', Validators.required],
478
        isEnabled: true,
479
        portalType: ['', Validators.required],
480
        top: true,
481
        bottom: true,
482
        left: true,
483
        right: true,
484
        type: ['', Validators.required],
485
        entities: this._fb.array([]),
486
        _id: '',
487
      });
488
    } else {
489
      this.updateErrorMessage = message;// + ' (Server responded: ' + error + ')';
490
      console.log('Server responded: ' + error);
491
    }
492

    
493
    this.showLoading = false;
494
  }
495

    
496
  // public filterByCommunity(event: any) {
497
  //     this.selectedCommunityPid = event.target.value;
498
  //     this.applyCommunityFilter(this.selectedCommunityPid);
499
  // }
500

    
501
  public applyCommunityFilter(community_pid: string) {
502
    this.getPages(community_pid);
503
  }
504

    
505
  public togglePages(status: boolean, ids: string[]) {
506
    if (!Session.isLoggedIn()) {
507
      this._router.navigate(['/user-info'], {
508
        queryParams: {
509
          'errorCode': LoginErrorCodes.NOT_VALID,
510
          'redirectUrl': this._router.url
511
        }
512
      });
513
    } else {
514
      this.updateErrorMessage = '';
515

    
516
      this.subscriptions.push(this._helpContentService.togglePages(this.selectedCommunityPid, ids, status, this.properties.adminToolsAPIURL).subscribe(
517
        () => {
518
          for (let id of ids) {
519
            let i = this.checkboxes.findIndex(_ => _.page._id == id);
520
            this.checkboxes[i].page.isEnabled = status;
521
          }
522
          this.applyCheck(false);
523
        },
524
        error => this.handleUpdateError('System error changing the status of the selected page(s)', error)
525
      ));
526
    }
527
  }
528

    
529
  public capitalizeFirstLetter(str: string) {
530
    return str.charAt(0).toUpperCase() + str.slice(1);
531
  }
532

    
533
  remove(entity): void {
534
    let index = this.selectedEntities.indexOf(entity);
535
    console.log(entity);
536
    console.log(this.selectedEntities);
537
    console.log(index)
538
    if (index >= 0) {
539
      this.selectedEntities.splice(index, 1);
540
      this.entitiesCtrl.value.splice(index, 1);
541
      this.entitiesCtrl.markAsDirty();
542
    }
543
  }
544

    
545
  selected(event: MatAutocompleteSelectedEvent): void {
546

    
547
    let newEntity = event.option.value;
548

    
549
    if (this.selectedEntities.indexOf(newEntity) == -1) {
550
      this.selectedEntities.push(event.option.value);
551
      this.entitiesCtrl.push(this._fb.control(newEntity));
552
      this.entitiesCtrl.markAsDirty();
553
    }
554
    this.pageInput.nativeElement.value = '';
555
    this.entitiesSearchCtrl.setValue('');
556
  }
557
}
(3-3/4)