Project

General

Profile

1
import {Component, ViewChild, OnInit, ElementRef} from '@angular/core';
2
import {Router, ActivatedRoute} from "@angular/router";
3
import {FormBuilder, FormControl, FormGroup} from "@angular/forms";
4
import {HelpContentService} from "../../services/help-content.service";
5
import {
6
  DivHelpContent,
7
  CheckDivHelpContent,
8
  DivHelpContentFilterOptions
9
} from "../../utils/entities/adminTool/div-help-content";
10
import {Page} from "../../utils/entities/adminTool/page";
11
import {Community} from "../../utils/entities/adminTool/community";
12
import {DivId} from "../../utils/entities/adminTool/divId";
13
import {EnvProperties} from '../../utils/properties/env-properties';
14

    
15
import {Session} from '../../login/utils/helper.class';
16
import {LoginErrorCodes} from '../../login/utils/guardHelper.class';
17
import {HelperFunctions} from "../../utils/HelperFunctions.class";
18
import {Subscriber} from "rxjs";
19

    
20
@Component({
21
  selector: 'div-help-contents',
22
  templateUrl: './div-help-contents.component.html',
23
})
24

    
25
export class DivHelpContentsComponent implements OnInit {
26
  // @ViewChild('deleteConfirmationModal')
27
  // public deleteConfirmationModal : DeleteConfirmationDialogComponent;
28
  @ViewChild('AlertModalDeleteDivHelpContents') alertModalDeleteDivHelpContents;
29
  private selectedDivContents: string[] = [];
30

    
31
  public checkboxes: CheckDivHelpContent[] = [];
32

    
33
  public divHelpContents: DivHelpContent[] = [];
34

    
35
  //public errorMessage: string;
36

    
37
  public formGroup: FormGroup;
38

    
39
  public pages: Page[];
40

    
41
  public checkboxAll: boolean = false;
42

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

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

    
48
  public communities: Community[] = [];
49

    
50
  public selectedCommunityPid: string;
51

    
52
  public selectedPageId: string;
53

    
54
  public community: Community;
55

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

    
59
  public showLoading: boolean = true;
60
  public errorMessage: string = '';
61
  public updateErrorMessage: string = '';
62
  public filterForm: FormControl;
63
  public selectForm: FormControl;
64
  public selectOptions = [];
65
  private subscriptions: any[] = [];
66

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

    
77
    this.route.data
78
      .subscribe((data: { envSpecific: EnvProperties }) => {
79
        this.properties = data.envSpecific;
80

    
81
        this.route.queryParams.subscribe(params => {
82
          HelperFunctions.scroll();
83

    
84
          this.selectedCommunityPid = params['communityId'];
85
          this.selectedPageId = params['pageId'];
86

    
87
          if (this.selectedCommunityPid && this.selectedPageId) {
88
            this.getPage(this.selectedPageId);
89
          } else if (this.selectedCommunityPid) {
90
            this.selectedPageId = "";
91
            this.getPages(this.selectedCommunityPid);
92
          }
93
        });
94
      });
95
  }
96

    
97
  constructor(private element: ElementRef, private route: ActivatedRoute, private _helpService: HelpContentService, private router: Router, private _fb: FormBuilder) {
98
  }
99

    
100
  ngOnDestroy(): void {
101
    this.subscriptions.forEach(value => {
102
      if (value instanceof Subscriber) {
103
        value.unsubscribe();
104
      } else if (value instanceof Function) {
105
        value();
106
      }
107
    });
108
  }
109

    
110
  getPage(pageId: string) {
111
    if (!Session.isLoggedIn()) {
112
      this.router.navigate(['/user-info'], {
113
        queryParams: {
114
          "errorCode": LoginErrorCodes.NOT_VALID,
115
          "redirectUrl": this.router.url
116
        }
117
      });
118
    } else {
119
      this.showLoading = true;
120
      this.updateErrorMessage = "";
121
      this.errorMessage = "";
122

    
123
      this._helpService.getPage(pageId, this.properties.adminToolsAPIURL).subscribe(
124
        page => {
125
          if ((this.selectedCommunityPid == 'openaire' && !page.openaire)
126
            || (this.selectedCommunityPid == 'connect' && !page.connect)
127
            || (this.selectedCommunityPid != 'openaire' && this.selectedCommunityPid != 'connect' && !page.communities)) {
128
            this.router.navigate(['/classContents'], {queryParams: {"communityId": this.selectedCommunityPid}});
129
          } else {
130
            this.page = page;
131
            this.getDivHelpContents(this.selectedCommunityPid);
132
          }
133
        },
134
        error => this.handleError('System error retrieving page', error));
135
    }
136
  }
137

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

    
151
      this._helpService.getCommunityPagesWithDivId(community_pid, this.properties.adminToolsAPIURL).subscribe(
152
        //this._helpService.getPagesWithDivIds(community_pid, this.properties.adminToolsAPIURL).subscribe(
153
        pages => {
154
          this.pages = pages;
155
          this.getDivHelpContents(this.selectedCommunityPid);
156
          this.selectOptions = [{label:'All pages', value: ''}];
157
          for (let page of this.pages) {
158
            this.selectOptions.push({label:page.name, value: page._id})
159
          }
160
        },
161
        error => this.handleError('System error retrieving pages', error));
162
    }
163
  }
164

    
165
  public countDivHelpContents() {
166
    this.counter = {all: 0, active: 0, inactive: 0};
167
    let filter = Object.assign({}, this.filters);
168
    filter.active = null;
169
    this.divHelpContents.forEach(_ => {
170
      if (this.filterDivHelpContent(_, filter)) {
171
        if (_.isActive == true) this.counter.active++;
172
        else this.counter.inactive++
173
      }
174
    });
175
    this.counter.all = this.counter.active + this.counter.inactive;
176
  }
177

    
178
  getDivHelpContents(community_pid: string) {
179
    if (!Session.isLoggedIn()) {
180
      this.router.navigate(['/user-info'], {
181
        queryParams: {
182
          "errorCode": LoginErrorCodes.NOT_VALID,
183
          "redirectUrl": this.router.url
184
        }
185
      });
186
    } else {
187
      this._helpService.getCommunityDivHelpContents(community_pid, this.properties.adminToolsAPIURL).subscribe(
188
        divHelpContents => {
189
          this.divHelpContents = divHelpContents as Array<DivHelpContent>;
190
          this.counter.all = this.divHelpContents.length;
191
          this.checkboxes = [];
192

    
193
          for (let i = this.divHelpContents.length - 1; i >= 0; i -= 1) {
194
            //for (let i = 0; i < this.divHelpContents.length; i++) {
195
            let divId: DivId = this.divHelpContents[i].divId as DivId;
196
            let pages: Page[] = divId.pages as Page[];
197
            const pageIds = pages.map(x => x._id);
198

    
199
            if (!this.selectedPageId || pageIds.includes(this.selectedPageId)) {
200
              this.cutContent(this.divHelpContents[i]);
201
              this.checkboxes.unshift(<CheckDivHelpContent>{divHelpContent: this.divHelpContents[i], checked: false});
202
            } else {
203
              this.divHelpContents.splice(i, 1);
204
            }
205
          }
206

    
207
          this.countDivHelpContents();
208

    
209
          this.showLoading = false;
210
        },
211
        error => this.handleError('System error retrieving page contents', error));
212
    }
213
  }
214

    
215
  public toggleCheckBoxes(event) {
216
    this.checkboxes.forEach(_ => _.checked = event.target.checked);
217
    this.checkboxAll = event.target.checked;
218
  }
219

    
220
  public applyCheck(flag: boolean) {
221
    this.checkboxes.forEach(_ => _.checked = flag);
222
    this.checkboxAll = false;
223
  }
224

    
225
  public getSelectedDivHelpContents(): string[] {
226
    return this.checkboxes.filter(divHelpContent => divHelpContent.checked == true)
227
      .map(checkedDivHelpContent => checkedDivHelpContent.divHelpContent).map(res => res._id);
228
  }
229

    
230
  public confirmDeleteDivHelpContent(id: string) {
231
    //this.deleteConfirmationModal.ids = [id];
232
    //this.deleteConfirmationModal.showModal();
233
    this.selectedDivContents = [id];
234
    this.confirmModalOpen();
235
  }
236

    
237
  public confirmDeleteSelectedDivHelpContents() {
238
    //this.deleteConfirmationModal.ids = this.getSelectedDivHelpContents();
239
    //this.deleteConfirmationModal.showModal();
240
    this.selectedDivContents = this.getSelectedDivHelpContents();
241
    this.confirmModalOpen();
242
  }
243

    
244
  private confirmModalOpen() {
245
    if (!Session.isLoggedIn()) {
246
      this.router.navigate(['/user-info'], {
247
        queryParams: {
248
          "errorCode": LoginErrorCodes.NOT_VALID,
249
          "redirectUrl": this.router.url
250
        }
251
      });
252
    } else {
253
      this.alertModalDeleteDivHelpContents.cancelButton = true;
254
      this.alertModalDeleteDivHelpContents.okButton = true;
255
      this.alertModalDeleteDivHelpContents.alertTitle = "Delete Confirmation";
256
      this.alertModalDeleteDivHelpContents.message = "Are you sure you want to delete the help text(s)?";
257
      this.alertModalDeleteDivHelpContents.okButtonText = "Yes";
258
      this.alertModalDeleteDivHelpContents.open();
259
    }
260
  }
261

    
262
  public confirmedDeleteDivHelpContents(data: any) {
263
    if (!Session.isLoggedIn()) {
264
      this.router.navigate(['/user-info'], {
265
        queryParams: {
266
          "errorCode": LoginErrorCodes.NOT_VALID,
267
          "redirectUrl": this.router.url
268
        }
269
      });
270
    } else {
271
      this.showLoading = true;
272
      this.updateErrorMessage = "";
273

    
274
      this._helpService.deleteDivHelpContents(this.selectedDivContents, this.properties.adminToolsAPIURL).subscribe(
275
        _ => {
276
          this.deleteDivHelpContentsFromArray(this.selectedDivContents);
277
          this.showLoading = false;
278
        },
279
        error => this.handleUpdateError('System error deleting the selected class content(s)', error)
280
      );
281
    }
282
  }
283

    
284
  private deleteDivHelpContentsFromArray(ids: string[]): void {
285
    for (let id of ids) {
286
      let iqc = this.checkboxes.findIndex(_ => _.divHelpContent._id == id);
287
      let iq = this.divHelpContents.findIndex(_ => _._id == id);
288
      this.checkboxes.splice(iqc, 1);
289
      this.divHelpContents.splice(iqc, 1);
290
    }
291
    this.countDivHelpContents();
292
  }
293

    
294
  public editDivHelpContent(id: string) {
295
    //this.router.navigate(['/pageContents/edit/', _id]);
296
    if (this.selectedPageId) {
297
      this.router.navigate(['/classContents/edit/'], {
298
        queryParams: {
299
          "classContentId": id,
300
          "communityId": this.selectedCommunityPid,
301
          "pageId": this.selectedPageId
302
        }
303
      });
304
    } else {
305
      this.router.navigate(['/classContents/edit/'], {
306
        queryParams: {
307
          "classContentId": id,
308
          "communityId": this.selectedCommunityPid
309
        }
310
      });
311
    }
312
  }
313

    
314
  public toggleDivHelpContents(status: boolean, ids: string[]) {
315
    if (!Session.isLoggedIn()) {
316
      this.router.navigate(['/user-info'], {
317
        queryParams: {
318
          "errorCode": LoginErrorCodes.NOT_VALID,
319
          "redirectUrl": this.router.url
320
        }
321
      });
322
    } else {
323
      this.updateErrorMessage = "";
324

    
325
      this._helpService.toggleDivHelpContents(ids, status, this.properties.adminToolsAPIURL).subscribe(
326
        () => {
327
          for (let id of ids) {
328
            let i = this.checkboxes.findIndex(_ => _.divHelpContent._id == id);
329
            this.checkboxes[i].divHelpContent.isActive = status;
330
          }
331
          this.countDivHelpContents();
332
          this.applyCheck(false);
333
        },
334
        error => this.handleUpdateError('System error changing the status of the selected page content(s)', error)
335
      );
336
    }
337
  }
338

    
339
  public divHelpContentSavedSuccessfully(divHelpContent: DivHelpContent) {
340
    this.cutContent(divHelpContent);
341
    this.checkboxes.push(<CheckDivHelpContent>{divHelpContent: divHelpContent, checked: false});
342
    this.divHelpContents.push(divHelpContent);
343
    this.applyCheck(false);
344
    this.countDivHelpContents();
345
  }
346

    
347
  public divHelpContentUpdatedSuccessfully(divHelpContent: DivHelpContent) {
348
    this.checkboxes.find(checkItem => checkItem.divHelpContent._id == divHelpContent._id).divHelpContent = divHelpContent;
349
    let index = this.divHelpContents.findIndex(checkItem => checkItem._id == divHelpContent._id);
350
    this.divHelpContents[index] = divHelpContent;
351
    this.applyCheck(false);
352
    this.countDivHelpContents();
353
  }
354

    
355

    
356
  public filterDivHelpContent(divHelpContent: DivHelpContent, filters: DivHelpContentFilterOptions): boolean {
357
    let divId: DivId = divHelpContent.divId as DivId;
358
    let pages: Page[] = <Page[]>divId.pages;
359
    let pageIds: string[] = pages.map(x => x._id);
360

    
361
    let idFlag = filters.id == '' || /*(<Page[]>divId.pages)._id == filters.id*/ pageIds.includes(filters.id);
362
    let activeFlag = filters.active == null || divHelpContent.isActive == filters.active;
363
    let textFlag = filters.text.toString() == '' || (divHelpContent.content).match(filters.text) != null
364
      || ((<DivId>divHelpContent.divId).name).match(filters.text) != null;
365
    return idFlag && activeFlag && textFlag;
366
  }
367

    
368
  public cutContent(divHelpContent: DivHelpContent) {
369
    divHelpContent.content = divHelpContent.content.replace(/<[^>]*>/g, '');
370
    divHelpContent.content = divHelpContent.content.replace(/(\r\n|\n|\r| +(?= ))|\s\s+/gm, " ");
371
    if (divHelpContent.content.length > 200) {
372
      divHelpContent.content = divHelpContent.content.substr(0, 200) + "...";
373
    }
374
  }
375

    
376
  public applyFilter() {
377
    this.checkboxes = [];
378
    this.divHelpContents.filter(item => this.filterDivHelpContent(item, this.filters)).forEach(
379
      _ => {
380
        this.cutContent(_);
381
        this.checkboxes.push(<CheckDivHelpContent>{divHelpContent: _, checked: false})
382
      }
383
    );
384
    this.countDivHelpContents();
385
  }
386

    
387
  public filterByPage(value: any) {
388
    this.filters.id = value;
389
    this.applyFilter();
390
  }
391

    
392
  public displayAllDivHelpContents() {
393
    this.filters.active = null;
394
    this.applyFilter();
395
  }
396

    
397
  public displayActiveDivHelpContents() {
398
    this.filters.active = true;
399
    this.applyFilter();
400
  }
401

    
402
  public filterBySearch(text: string) {
403
    this.filters.text = new RegExp(text, "i");
404
    this.applyFilter();
405
  }
406

    
407
  public displayInactiveDivHelpContents() {
408
    this.filters.active = false;
409
    this.applyFilter();
410
  }
411

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

    
416
    this.showLoading = false;
417
  }
418

    
419
  handleUpdateError(message: string, error) {
420
    this.updateErrorMessage = message;
421
    console.log('Server responded: ' + error);
422

    
423
    this.showLoading = false;
424
  }
425

    
426
  public newClassContent() {
427
    if (this.selectedPageId) {
428
      this.router.navigate(['/classContents/new'], {
429
        queryParams: {
430
          communityId: this.selectedCommunityPid,
431
          pageId: this.selectedPageId
432
        }
433
      });
434
    } else {
435
      this.router.navigate(['/classContents/new'], {queryParams: {communityId: this.selectedCommunityPid}});
436
    }
437
  }
438
}
(5-5/12)