Project

General

Profile

1 61381 k.triantaf
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 {Option} from '../../sharedComponents/input/input.component';
15
import {AlertModal} from '../../utils/modal/alert';
16
import {SearchInputComponent} from '../../sharedComponents/search-input/search-input.component';
17
import {Title} from '@angular/platform-browser';
18
import {StringUtils} from '../../utils/string-utils.class';
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
  pageHelpContentsCount = {};
67
  pageClassContentsCount = {};
68
69
  constructor(private element: ElementRef, private route: ActivatedRoute,
70
              private title: Title,
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.route.snapshot.data.portal) {
95
        this.title.setTitle(StringUtils.capitalize(this.portal) + ' | Pages');
96
      } else if (this.route.snapshot.params[this.route.snapshot.data.param]) {
97
        this.title.setTitle(this.portal.toUpperCase() + ' | Pages');
98
      } else {
99
        this.title.setTitle('Administrator Dashboard | Pages');
100
      }
101
      this.keyword = '';
102
      this.subscriptions.push(this.userManagementService.getUserInfo().subscribe(user => {
103
        this.applyPortalFilter(this.portal);
104
        this.isPortalAdministrator = Session.isPortalAdministrator(user) && !this.portal;
105
      }));
106
    }));
107
    this.subscriptions.push(this._helpContentService.getEntities(this.properties.adminToolsAPIURL).subscribe(
108
      entities => {
109
        this.allEntities = [];
110
        entities.forEach(entity => {
111
          this.allEntities.push({
112
            label: entity.name,
113
            value: entity
114
          });
115
        });
116
      },
117
      error => this.handleError('System error retrieving pages', error)));
118
    if (this.portal) {
119
      this.getPageHelpContentsCounts(this.portal);
120
    }
121
122
  }
123
124
  ngOnDestroy(): void {
125
    this.subscriptions.forEach(value => {
126
      if (value instanceof Subscriber) {
127
        value.unsubscribe();
128
      } else if (value instanceof Function) {
129
        value();
130
      }
131
    });
132
  }
133
134
  getPages(portal: string) {
135
    this.showLoading = true;
136
    this.pageWithDivIds = [];
137
    let parameters = '';
138
    if (this.pagesType) {
139
      parameters = '?page_type=' + this.pagesType;
140
    }
141
    if (portal) {
142
      this.subscriptions.push(this._helpContentService.getCommunityPagesByType(portal, parameters, this.properties.adminToolsAPIURL).subscribe(
143
        pages => {
144
          this.pagesReturned(pages);
145
          //if(!this.pagesType || this.pagesType == "link") {
146
          this.getPagesWithDivIds(portal);
147
          //} else {
148
          //this.showLoading = false;
149
          //}
150
        },
151
        error => this.handleError('System error retrieving pages', error)
152
      ));
153
    } else {
154
      this.subscriptions.push(this._helpContentService.getAllPagesFull(this.properties.adminToolsAPIURL).subscribe(
155
        pages => {
156
          this.pagesReturned(pages);
157
          this.showLoading = false;
158
        },
159
        error => this.handleError('System error retrieving pages', error)
160
      ));
161
    }
162
  }
163
164
  getPagesWithDivIds(portal: string) {
165
    this.subscriptions.push(this._helpContentService.getPageIdsFromDivIds(portal, this.properties.adminToolsAPIURL).subscribe(
166
      pages => {
167
        this.pageWithDivIds = pages;
168
        this.showLoading = false;
169
      },
170
      error => this.handleError('System error retrieving information about pages\' classes', error)));
171
  }
172
173
  pagesReturned(pages: Page[]) {
174
    this.pages = pages;
175
    this.checkboxes = [];
176
177
    if (pages) {
178
      pages.forEach(_ => {
179
        this.checkboxes.push(<CheckPage>{page: _, checked: false});
180
      });
181
    }
182
  }
183
184
  public toggleCheckBoxes(event) {
185
    this.checkboxes.forEach(_ => _.checked = event.target.checked);
186
  }
187
188
  public applyCheck(flag: boolean) {
189
    this.checkboxes.forEach(_ => _.checked = flag);
190
  }
191
192
  public getSelectedPages(): string[] {
193
    return this.checkboxes.filter(page => page.checked == true).map(checkedPage => checkedPage.page).map(res => res._id);
194
  }
195
196
  private deletePagesFromArray(ids: string[]): void {
197
    for (let id of ids) {
198
      let i = this.pages.findIndex(_ => _._id == id);
199
      this.pages.splice(i, 1);
200
    }
201
    this.applyFilters();
202
  }
203
204
  public confirmDeletePage(id: string) {
205
    this.selectedPages = [id];
206
    this.confirmModalOpen();
207
  }
208
209
  public confirmDeleteSelectedPages() {
210
    this.selectedPages = this.getSelectedPages();
211
    this.confirmModalOpen();
212
  }
213
214
  private confirmModalOpen() {
215
    this.deleteModal.cancelButton = true;
216
    this.deleteModal.okButton = true;
217
    this.deleteModal.alertTitle = 'Delete Confirmation';
218
    this.deleteModal.message = 'Are you sure you want to delete the selected page(s)?';
219
    this.deleteModal.okButtonText = 'Yes';
220
    this.deleteModal.open();
221
  }
222
223
  public confirmedDeletePages(data: any) {
224
    this.showLoading = true;
225
    this.subscriptions.push(this._helpContentService.deletePages(this.selectedPages, this.properties.adminToolsAPIURL).subscribe(
226
      _ => {
227
        this.deletePagesFromArray(this.selectedPages);
228
        UIkit.notification('Pages have been <b>successfully deleted</b>', {
229
          status: 'success',
230
          timeout: 6000,
231
          pos: 'bottom-right'
232
        });
233
        this.showLoading = false;
234
      },
235
      error => this.handleUpdateError('System error deleting the selected pages', error)
236
    ));
237
  }
238
239
  public editPage(i: number) {
240
    this.entitiesCtrl = this._fb.array([]);
241
    let page: Page = this.checkboxes[i].page;
242
    this.index = this.pages.findIndex(value => value._id === page._id);
243
    this.pageForm = this._fb.group({
244
      _id: this._fb.control(page._id),
245
      route: this._fb.control(page.route, Validators.required),
246
      name: this._fb.control(page.name, Validators.required),
247
      isEnabled: this._fb.control(page.isEnabled),
248
      portalType: this._fb.control(page.portalType, Validators.required),
249
      top: this._fb.control(page.top),
250
      bottom: this._fb.control(page.bottom),
251
      left: this._fb.control(page.left),
252
      right: this._fb.control(page.right),
253
      type: this._fb.control(page.type, Validators.required),
254
      entities: this.entitiesCtrl
255
    });
256
    this.pageForm.get('portalType').disable();
257
    for (let i = 0; i < page.entities.length; i++) {
258
      this.entitiesCtrl.push(this._fb.control(page.entities[i]));
259
    }
260
    this.pagesModalOpen('Edit Page', 'Save changes');
261
  }
262
263
  public newPage() {
264
    if (this.pageForm) {
265
      this.pageForm.get('portalType').enable();
266
    }
267
    this.entitiesCtrl = this._fb.array([]);
268
    this.pageForm = this._fb.group({
269
      _id: this._fb.control(null),
270
      route: this._fb.control('', Validators.required),
271
      name: this._fb.control('', Validators.required),
272
      isEnabled: this._fb.control(true),
273
      portalType: this._fb.control('', Validators.required),
274
      top: this._fb.control(true),
275
      bottom: this._fb.control(true),
276
      left: this._fb.control(true),
277
      right: this._fb.control(true),
278
      type: this._fb.control(this.typeOptions[0].value, Validators.required),
279
      entities: this.entitiesCtrl,
280
    });
281
    this.pagesModalOpen('Create Page', 'Create');
282
  }
283
284
  private pagesModalOpen(title: string, yesBtn: string) {
285
    this.editModal.cancelButton = true;
286
    this.editModal.okButton = true;
287
    this.editModal.okButtonLeft = false;
288
    this.editModal.alertTitle = title;
289
    this.editModal.okButtonText = yesBtn;
290
    this.editModal.open();
291
  }
292
293
  public pageSaveConfirmed(data: any) {
294
    this.showLoading = true;
295
    if (!this.pageForm.value._id) {
296
      this.subscriptions.push(this._helpContentService.savePage(<Page>this.pageForm.value, this.properties.adminToolsAPIURL).subscribe(
297
        page => {
298
          this.pageSavedSuccessfully(page, true);
299
          UIkit.notification('Page <b>' + page.name + '</b> has been <b>successfully created</b>', {
300
            status: 'success',
301
            timeout: 6000,
302
            pos: 'bottom-right'
303
          });
304
        },
305
        error => this.handleUpdateError('System error creating page', error)
306
      ));
307
    } else {
308
      this.pageForm.get('portalType').enable();
309
      this.subscriptions.push(this._helpContentService.updatePage(<Page>this.pageForm.value, this.properties.adminToolsAPIURL).subscribe(
310
        page => {
311
          this.pageSavedSuccessfully(page, false);
312
          UIkit.notification('Page <b>' + page.name + '</b> has been <b>successfully updated</b>', {
313
            status: 'success',
314
            timeout: 6000,
315
            pos: 'bottom-right'
316
          });
317
        },
318
        error => this.handleUpdateError('System error updating page', error)
319
      ));
320
    }
321
  }
322
323
  public pageSavedSuccessfully(page: Page, isNew: boolean) {
324
    if (isNew) {
325
      this.pages.push(page);
326
    } else {
327
      this.pages[this.index] = page;
328
    }
329
    this.applyFilters();
330
    this.applyCheck(false);
331
    this.showLoading = false;
332
  }
333
334
  public applyFilters() {
335
    this.checkboxes = [];
336
    this.pages.filter(item => this.filterByType(item)).forEach(
337
      _ => this.checkboxes.push(<CheckPage>{page: _, checked: false})
338
    );
339
    this.checkboxes = this.checkboxes.filter(item => this.filterPages(item.page));
340
  }
341
342
  public filterByType(page: Page): boolean {
343
    let type = this.filterForm.get("type").value;
344
    return type == "all" || (type == page.type);
345
  }
346
347
  public filterPages(page: Page): boolean {
348
    return this.searchText.toString() == '' || (page.route + ' ' + page.name + ' ' + page.portalType).match(this.searchText) != null;
349
  }
350
351
  handleError(message: string, error) {
352
    UIkit.notification(message, {
353
      status: 'danger',
354
      timeout: 6000,
355
      pos: 'bottom-right'
356
    });
357
    console.log('Server responded: ' + error);
358
    this.showLoading = false;
359
  }
360
361
  handleUpdateError(message: string, error) {
362
    if (error == null) {
363
      // this.formComponent.reset();
364
      this.pageForm = this._fb.group({
365
        route: this._fb.control('', Validators.required),
366
        name: this._fb.control('', Validators.required),
367
        isEnabled: this._fb.control(true),
368
        portalType: this._fb.control('', Validators.required),
369
        top: this._fb.control(true),
370
        bottom: this._fb.control(true),
371
        left: this._fb.control(true),
372
        right: this._fb.control(true),
373
        type: this._fb.control(this.typeOptions[0].value, Validators.required),
374
        entities: this.entitiesCtrl,
375
        _id: this._fb.control(''),
376
      });
377
    } else {
378
      UIkit.notification(message, {
379
        status: 'danger',
380
        timeout: 6000,
381
        pos: 'bottom-right'
382
      });
383
    }
384
    this.showLoading = false;
385
  }
386
387
  public getEntitiesAsString(page: Page): string {
388
    if (page.entities) {
389
      return (<any[]>page.entities).map((page: Entity) => page.name).join(',');
390
    }
391
    return '';
392
  }
393
394
  public applyPortalFilter(portal: string) {
395
    this.getPages(portal);
396
  }
397
398
  public togglePages(status: boolean, ids: string[]) {
399
    if (!Session.isLoggedIn()) {
400
      this._router.navigate(['/user-info'], {
401
        queryParams: {
402
          'errorCode': LoginErrorCodes.NOT_VALID,
403
          'redirectUrl': this._router.url
404
        }
405
      });
406
    } else {
407
      this.subscriptions.push(this._helpContentService.togglePages(this.portal, ids, status, this.properties.adminToolsAPIURL).subscribe(
408
        () => {
409
          for (let id of ids) {
410
            let i = this.checkboxes.findIndex(_ => _.page._id == id);
411
            this.checkboxes[i].page.isEnabled = status;
412
          }
413
          this.applyCheck(false);
414
        },
415
        error => this.handleUpdateError('System error changing the status of the selected page(s)', error)
416
      ));
417
    }
418
  }
419
420
  public onSearchClose() {
421
    this.selectedKeyword = this.filterForm.get('keyword').value;
422
  }
423
424
  public reset() {
425
    this.selectedKeyword = null;
426
    this.searchInputComponent.reset()
427
  }
428
429
  selectAll() {
430
    let checked = this.getSelectedPages().length != this.checkboxes.length;
431
    for (let check of this.checkboxes) {
432
      check.checked = checked;
433
    }
434
  }
435
436
  getPageHelpContentsCounts(community_pid: string) {
437
    this.subscriptions.push(this._helpContentService.countCommunityPageHelpContents(community_pid, this.properties.adminToolsAPIURL, false).subscribe(
438
      pageHelpContentsCount => {
439
        this.pageHelpContentsCount = pageHelpContentsCount;
440
      },
441
      error => this.handleError('System error retrieving page contents', error)));
442
    this.subscriptions.push(this._helpContentService.countCommunityPageHelpContents(community_pid, this.properties.adminToolsAPIURL, true).subscribe(
443
      pageClassContentsCount => {
444
        this.pageClassContentsCount = pageClassContentsCount;
445
      },
446
      error => this.handleError('System error retrieving page contents', error)));
447
  }
448
}