Project

General

Profile

1
import {Component, ViewChild, OnInit, ElementRef} from '@angular/core';
2
import {FormBuilder, FormControl, FormGroup} from "@angular/forms";
3
import {ActivatedRoute, Router} from "@angular/router";
4
import {HelpContentService} from "../../services/help-content.service";
5
import {
6
  PageHelpContent,
7
  CheckPageHelpContent,
8
  PageHelpContentFilterOptions
9
} from "../../utils/entities/adminTool/page-help-content";
10
import {Page} from "../../utils/entities/adminTool/page";
11
import {Portal} from "../../utils/entities/adminTool/portal";
12
import {EnvProperties} from '../../utils/properties/env-properties';
13
import {Session} from '../../login/utils/helper.class';
14
import {LoginErrorCodes} from '../../login/utils/guardHelper.class';
15
import {HelperFunctions} from "../../utils/HelperFunctions.class";
16
import {Subscriber} from "rxjs";
17
import {properties} from "../../../../environments/environment";
18
import {DomSanitizer} from '@angular/platform-browser';
19
import {SearchInputComponent} from '../../sharedComponents/search-input/search-input.component';
20
import {ConnectHelper} from '../../connect/connectHelper';
21

    
22

    
23
@Component({
24
  selector: 'page-help-contents',
25
  templateUrl: './page-help-contents.component.html',
26
})
27
export class PageHelpContentsComponent implements OnInit {
28

    
29
  @ViewChild('AlertModalDeletePageHelpContents') alertModalDeletePageHelpContents;
30
  private selectedPageContents: string[] = [];
31

    
32
  public checkboxes: CheckPageHelpContent[] = [];
33

    
34
  public pageHelpContents: PageHelpContent[] = [];
35

    
36
  public formGroup: FormGroup;
37

    
38
  public pages: Page[];
39

    
40
  public checkboxAll: boolean = false;
41

    
42
  public filters: PageHelpContentFilterOptions = {id: '', active: null, text: new RegExp('')};
43
  public keyword: string = "";
44

    
45
  public counter = {all: 0, active: 0, inactive: 0};
46

    
47
  public communities: Portal[] = [];
48

    
49
  public portal: string;
50

    
51
  public selectedPageId: string;
52

    
53
  public community: Portal;
54

    
55
  public page: Page;
56
  public properties: EnvProperties = null;
57

    
58
  public showLoading: boolean = true;
59
  public errorMessage: string = '';
60
  public updateErrorMessage: string = '';
61
  public filterForm: FormControl;
62
  public selectForm: FormControl;
63
  public selectOptions = [];
64
  private subscriptions: any[] = [];
65
  public selectedKeyword: string;
66
  @ViewChild('searchInputComponent') searchInputComponent: SearchInputComponent;
67

    
68
  ngOnInit() {
69
    this.filterForm = this._fb.control('');
70
    this.selectForm = this._fb.control('');
71
    this.subscriptions.push(this.filterForm.valueChanges.subscribe(value => {
72
      this.filterBySearch(value);
73
    }));
74
    this.subscriptions.push(this.selectForm.valueChanges.subscribe(value => {
75
      this.filterByPage(value);
76
    }));
77

    
78
    this.properties = properties;
79
    this.subscriptions.push(this.route.params.subscribe(params => {
80
      this.portal = (this.route.snapshot.data.portal) ? this.route.snapshot.data.portal : this.route.snapshot.params[this.route.snapshot.data.param];
81
      ConnectHelper.setPortalTypeFromPid(this.portal);
82
      this.subscriptions.push(this.route.queryParams.subscribe(params => {
83
        HelperFunctions.scroll();
84
        this.selectedPageId = params['pageId'];
85
        if (this.portal && this.selectedPageId) {
86
          this.getPage(this.selectedPageId);
87
        }
88
        if(!this.selectedPageId) {
89
          this.router.navigate(['../pages'], {relativeTo: this.route });
90
        }
91
      }));
92
    }));
93
  }
94

    
95
  constructor(private element: ElementRef, private route: ActivatedRoute, private router: Router, private _helpService: HelpContentService, private _fb: FormBuilder, private sanitizer: DomSanitizer) {
96
  }
97
  ngOnDestroy(): void {
98
    this.subscriptions.forEach(value => {
99
      if (value instanceof Subscriber) {
100
        value.unsubscribe();
101
      } else if (value instanceof Function) {
102
        value();
103
      }
104
    });
105
  }
106
  init(){
107

    
108
  }
109
  getPage(pageId: string) {
110
    if (!Session.isLoggedIn()) {
111
      this.router.navigate(['/user-info'], {
112
        queryParams: {
113
          "errorCode": LoginErrorCodes.NOT_VALID,
114
          "redirectUrl": this.router.url
115
        }
116
      });
117
    } else {
118
      this.showLoading = true;
119
      this.updateErrorMessage = "";
120
      this.errorMessage = "";
121
      this.subscriptions.push(this._helpService.getPageByPortal(pageId, this.properties.adminToolsAPIURL, this.portal).subscribe(
122
        page => {
123
          if (this.properties.adminToolsPortalType != page.portalType) {
124
            this.router.navigate(['./pageContents'], {queryParams: {"communityId": this.portal}});
125
          } else {
126
            this.page = page;
127
            this.getPageHelpContents(this.portal);
128
          }
129
        },
130
        error => this.handleError('System error retrieving page', error)));
131
    }
132
  }
133

    
134
  getPages(community_pid: string) {
135
    if (!Session.isLoggedIn()) {
136
      this.router.navigate(['/user-info'], {
137
        queryParams: {
138
          "errorCode": LoginErrorCodes.NOT_VALID,
139
          "redirectUrl": this.router.url
140
        }
141
      });
142
    } else {
143
      this.showLoading = true;
144
      this.updateErrorMessage = "";
145
      this.errorMessage = "";
146

    
147
      //this._helpService.getCommunityPages(community_pid, "", this.properties.adminToolsAPIURL).subscribe(
148
      this.subscriptions.push(this._helpService.getCommunityPagesWithPositions(community_pid,this.properties.adminToolsAPIURL).subscribe(
149
        pages => {
150
          this.pages = pages;
151
          this.getPageHelpContents(this.portal);
152
          this.selectOptions = [{label:'All pages', value: ''}];
153
          for (let page of this.pages) {
154
            this.selectOptions.push({label:page.name, value: page._id})
155
          }
156
        },
157
        error => this.handleError('System error retrieving pages', error)));
158
    }
159
  }
160

    
161
  public countPageHelpContents() {
162
    this.counter = {all: 0, active: 0, inactive: 0};
163
    let filter = Object.assign({}, this.filters);
164
    filter.active = null;
165
    this.pageHelpContents.forEach(_ => {
166
      if (this.filterPageHelpContent(_, filter)) {
167
        if (_.isActive == true) this.counter.active++;
168
        else this.counter.inactive++
169
      }
170
    });
171
    this.counter.all = this.counter.active + this.counter.inactive;
172
  }
173

    
174
  getPageHelpContents(community_pid: string) {
175
    if (!Session.isLoggedIn()) {
176
      this.router.navigate(['/user-info'], {
177
        queryParams: {
178
          "errorCode": LoginErrorCodes.NOT_VALID,
179
          "redirectUrl": this.router.url
180
        }
181
      });
182
    } else {
183
      this.subscriptions.push(this._helpService.getCommunityPageHelpContents(community_pid, this.properties.adminToolsAPIURL, this.selectedPageId).subscribe(
184
        pageHelpContents => {
185
          this.pageHelpContents = pageHelpContents as Array<PageHelpContent>;
186
          this.counter.all = this.pageHelpContents.length;
187
          this.checkboxes = [];
188

    
189
          for (let i = this.pageHelpContents.length - 1; i >= 0; i -= 1) {
190
              this.cutContent(this.pageHelpContents[i]);
191
              this.checkboxes.unshift(<CheckPageHelpContent>{
192
                pageHelpContent: this.pageHelpContents[i],
193
                checked: false
194
              });
195
          }
196

    
197
          this.countPageHelpContents();
198

    
199
          this.showLoading = false;
200
        },
201
        error => this.handleError('System error retrieving page contents', error)));
202
    }
203
  }
204

    
205
  // public showModal():void {
206
  //     this.modal.showModal();
207
  // }
208

    
209
  public toggleCheckBoxes(event) {
210
    this.checkboxes.forEach(_ => _.checked = event.target.checked);
211
    this.checkboxAll = event.target.checked;
212
  }
213

    
214
  public applyCheck(flag: boolean) {
215
    this.checkboxes.forEach(_ => _.checked = flag);
216
    this.checkboxAll = false;
217
  }
218

    
219
  public getSelectedPageHelpContents(): string[] {
220
    return this.checkboxes.filter(pageHelpContent => pageHelpContent.checked == true)
221
      .map(checkedPageHelpContent => checkedPageHelpContent.pageHelpContent).map(res => res._id);
222
  }
223

    
224
  public confirmDeletePageHelpContent(id: string) {
225
    //this.deleteConfirmationModal.ids = [id];
226
    //this.deleteConfirmationModal.showModal();
227
    this.selectedPageContents = [id];
228
    this.confirmModalOpen();
229
  }
230

    
231
  public confirmDeleteSelectedPageHelpContents() {
232
    //this.deleteConfirmationModal.ids = this.getSelectedPageHelpContents();
233
    //this.deleteConfirmationModal.showModal();
234
    this.selectedPageContents = this.getSelectedPageHelpContents();
235
    this.confirmModalOpen();
236
  }
237

    
238
  private confirmModalOpen() {
239
    if (!Session.isLoggedIn()) {
240
      this.router.navigate(['/user-info'], {
241
        queryParams: {
242
          "errorCode": LoginErrorCodes.NOT_VALID,
243
          "redirectUrl": this.router.url
244
        }
245
      });
246
    } else {
247
      this.alertModalDeletePageHelpContents.cancelButton = true;
248
      this.alertModalDeletePageHelpContents.okButton = true;
249
      this.alertModalDeletePageHelpContents.alertTitle = "Delete Confirmation";
250
      this.alertModalDeletePageHelpContents.message = "Are you sure you want to delete the selected page content(s)?";
251
      this.alertModalDeletePageHelpContents.okButtonText = "Yes";
252
      this.alertModalDeletePageHelpContents.open();
253
    }
254
  }
255

    
256
  public confirmedDeletePageHelpContents(data: any) {
257
    if (!Session.isLoggedIn()) {
258
      this.router.navigate(['/user-info'], {
259
        queryParams: {
260
          "errorCode": LoginErrorCodes.NOT_VALID,
261
          "redirectUrl": this.router.url
262
        }
263
      });
264
    } else {
265
      this.showLoading = true;
266
      this.updateErrorMessage = "";
267

    
268
      this.subscriptions.push(this._helpService.deletePageHelpContents(this.selectedPageContents, this.properties.adminToolsAPIURL, this.portal).subscribe(
269
        _ => {
270
          this.deletePageHelpContentsFromArray(this.selectedPageContents);
271
          this.showLoading = false;
272
        },
273
        error => this.handleUpdateError('System error deleting the selected page content(s)', error)
274
      ));
275
    }
276
  }
277

    
278
  private deletePageHelpContentsFromArray(ids: string[]): void {
279
    for (let id of ids) {
280
      let iqc = this.checkboxes.findIndex(_ => _.pageHelpContent._id == id);
281
      let iq = this.pageHelpContents.findIndex(_ => _._id == id);
282
      this.checkboxes.splice(iqc, 1);
283
      this.pageHelpContents.splice(iqc, 1);
284
    }
285
    this.countPageHelpContents();
286
  }
287

    
288
  public editPageHelpContent(id: string) {
289
    //this.router.navigate(['/pageContents/edit/', _id]);
290
    if (this.selectedPageId) {
291
      this.router.navigate(['edit/'], {
292
        queryParams: {
293
          "pageContentId": id,
294
          "communityId": this.portal,
295
          "pageId": this.selectedPageId
296
        }, relativeTo: this.route
297
      });
298
    } else {
299
      this.router.navigate(['edit/'], {
300
        queryParams: {
301
          "pageContentId": id,
302
          "communityId": this.portal
303
        }, relativeTo: this.route
304
      });
305
    }
306
  }
307

    
308
  public togglePageHelpContents(status: boolean, ids: string[]) {
309
    if (!Session.isLoggedIn()) {
310
      this.router.navigate(['/user-info'], {
311
        queryParams: {
312
          "errorCode": LoginErrorCodes.NOT_VALID,
313
          "redirectUrl": this.router.url
314
        }
315
      });
316
    } else {
317
      this.updateErrorMessage = "";
318

    
319
      this.subscriptions.push(this._helpService.togglePageHelpContents(ids, status, this.properties.adminToolsAPIURL, this.portal).subscribe(
320
        () => {
321
          for (let id of ids) {
322
            let i = this.checkboxes.findIndex(_ => _.pageHelpContent._id == id);
323
            this.checkboxes[i].pageHelpContent.isActive = status;
324
          }
325
          this.countPageHelpContents();
326
          this.applyCheck(false);
327
        },
328
        error => this.handleUpdateError('System error changing the status of the selected page content(s)', error)
329
      ));
330
    }
331
  }
332

    
333
  public pageHelpContentSavedSuccessfully(pageHelpContent: PageHelpContent) {
334
    this.cutContent(pageHelpContent);
335
    this.checkboxes.push(<CheckPageHelpContent>{pageHelpContent: pageHelpContent, checked: false});
336
    this.pageHelpContents.push(pageHelpContent);
337
    this.applyCheck(false);
338
    this.countPageHelpContents();
339
  }
340

    
341
  public pageHelpContentUpdatedSuccessfully(pageHelpContent: PageHelpContent) {
342
    this.checkboxes.find(checkItem => checkItem.pageHelpContent._id == pageHelpContent._id).pageHelpContent = pageHelpContent;
343
    let index = this.pageHelpContents.findIndex(checkItem => checkItem._id == pageHelpContent._id);
344
    this.pageHelpContents[index] = pageHelpContent;
345
    this.applyCheck(false);
346
    this.countPageHelpContents();
347
  }
348

    
349

    
350
  public filterPageHelpContent(pageHelpContent: PageHelpContent, filters: PageHelpContentFilterOptions): boolean {
351
    let idFlag = filters.id == '' || (<Page>pageHelpContent.page)._id == filters.id;
352
    let activeFlag = filters.active == null || pageHelpContent.isActive == filters.active;
353
    let textFlag = filters.text.toString() == '' || (pageHelpContent.content).match(filters.text) != null
354
      || ((<Page>pageHelpContent.page).name).match(filters.text) != null;
355
    return idFlag && activeFlag && textFlag;
356
  }
357

    
358
  public cutContent(pageHelpContent: PageHelpContent) {
359
    pageHelpContent.content = pageHelpContent.content.replace(/<[^>]*>/g, '');
360
    pageHelpContent.content = pageHelpContent.content.replace(/(\r\n|\n|\r| +(?= ))|\s\s+/gm, " ");
361

    
362
    if (pageHelpContent.content.length > 200) {
363
      pageHelpContent.content = pageHelpContent.content.substr(0, 200) + "...";
364
    }
365
  }
366

    
367
  public applyFilter() {
368
    this.checkboxes = [];
369
    this.pageHelpContents.filter(item => this.filterPageHelpContent(item, this.filters)).forEach(
370
      _ => {
371
        this.cutContent(_);
372
        this.checkboxes.push(<CheckPageHelpContent>{pageHelpContent: _, checked: false})
373
      }
374
    );
375
    // this.countPageHelpContents();
376
  }
377

    
378
  public filterByPage(event: any) {
379
    if(event.target && event.target.value) {
380
      this.filters.id = event.target.value;
381
      this.applyFilter();
382
    }
383
  }
384

    
385
  public displayAllPageHelpContents() {
386
    this.filters.active = null;
387
    this.applyFilter();
388
  }
389

    
390
  public displayActivePageHelpContents() {
391
    this.filters.active = true;
392
    this.applyFilter();
393
  }
394

    
395
  public filterBySearch(text: string) {
396
    this.filters.text = new RegExp(text, "i");
397
    this.applyFilter();
398
  }
399

    
400
  public displayInactivePageHelpContents() {
401
    this.filters.active = false;
402
    this.applyFilter();
403
  }
404

    
405
  handleError(message: string, error) {
406
    this.errorMessage = message;
407
    console.log('Server responded: ' + error);
408

    
409
    this.showLoading = false;
410
  }
411

    
412
  handleUpdateError(message: string, error) {
413
    this.updateErrorMessage = message;
414
    console.log('Server responded: ' + error);
415

    
416
    this.showLoading = false;
417
  }
418

    
419
  public newPageContent() {
420
      this.router.navigate(['edit'], {
421
        queryParams: {
422
          pageId: this.selectedPageId
423
        }, relativeTo: this.route
424
      });
425
  }
426

    
427
  public onSearchClose() {
428
    this.selectedKeyword = this.filterForm.value;
429
  }
430

    
431
  public reset() {
432
    this.selectedKeyword = null;
433
    this.searchInputComponent.reset()
434
  }
435
  selectAll(){
436
    let checked = !!(this.getSelectedPageHelpContents().length != this.checkboxes.length);
437
      for (let check of this.checkboxes) {
438
        check.checked = checked;
439
      }
440
  }
441
}
(7-7/8)