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 {CheckDivId, DivId} from "../../utils/entities/adminTool/divId";
6
import {Page} from "../../utils/entities/adminTool/page";
7
import {EnvProperties} from '../../utils/properties/env-properties';
8

    
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 {Observable, Subscriber} from "rxjs";
13
import {map, startWith} from "rxjs/operators";
14
import {MatAutocompleteSelectedEvent, MatChipInputEvent} from "@angular/material";
15
import {properties} from "../../../../environments/environment";
16
import {PortalUtils} from "../portal/portalHelper";
17
import {CheckPortal, Portal} from "../../utils/entities/adminTool/portal";
18

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

    
24
export class DivIdsComponent implements OnInit {
25
  @ViewChild('AlertModalSaveDivId') alertModalSaveDivId;
26
  @ViewChild('AlertModalDeleteDivIds') alertModalDeleteDivIds;
27
  private selectedDivIds: string[] = [];
28
  public checkboxes: CheckDivId[] = [];
29
  public divIds: DivId[] = [];
30

    
31
  public myForm: FormGroup;
32
  public pageSearchCtrl: FormControl;
33
  public pagesCtrl: FormArray;
34

    
35
  private searchText: RegExp = new RegExp('');
36
  public keyword: string = "";
37

    
38
  public properties: EnvProperties = null;
39
  public formPages: Page[] = [];
40

    
41
  public showLoading: boolean = true;
42
  public errorMessage: string = '';
43
  public updateErrorMessage: string = '';
44
  public modalErrorMessage: string = '';
45
  public filterForm: FormGroup;
46
  private subscriptions: any[] = [];
47
  public allPages: Page[] = [];
48
  filteredPages: Observable<Page[]>;
49
  @ViewChild('PageInput') pageInput: ElementRef<HTMLInputElement>;
50
  selectedPages: Page[] = [];
51
  selectedCommunityPid = null;
52
  public portalUtils:PortalUtils = new PortalUtils();
53
  ngOnInit() {
54
    this.filterForm =  this._fb.group({
55
      keyword: [''],
56
      type: ['all', Validators.required]});
57
    this.subscriptions.push(this.filterForm.get('keyword').valueChanges.subscribe(value => {
58
      this.filterBySearch(value);
59
    }));
60
    this.subscriptions.push(this.filterForm.get('type').valueChanges.subscribe(value => {
61
      this.applyTypeFilter();
62
    }));
63
    this.pageSearchCtrl = this._fb.control('');
64
    this.pagesCtrl = this._fb.array([]);
65
    this.myForm = this._fb.group({
66
      _id: '',
67
      name: ['', Validators.required],
68
      pages: this.pagesCtrl,
69
      portalType: ['', Validators.required]
70
    });
71
    this.properties = properties;
72
    this.getDivIds();
73
    this.subscriptions.push(this.route.queryParams.subscribe(params => {
74
      HelperFunctions.scroll();
75
      this.selectedCommunityPid = params['communityId'];
76
      this.getPages();
77
    }));
78

    
79
  }
80

    
81
  constructor(private element: ElementRef, private route: ActivatedRoute, private _router: Router, private _helpContentService: HelpContentService, private _fb: FormBuilder) {
82
  }
83

    
84
  ngOnDestroy(): void {
85
    this.subscriptions.forEach(value => {
86
      if (value instanceof Subscriber) {
87
        value.unsubscribe();
88
      } else if (value instanceof Function) {
89
        value();
90
      }
91
    });
92
  }
93

    
94
  getDivIds() {
95
    if (!Session.isLoggedIn()) {
96
      this._router.navigate(['/user-info'], {
97
        queryParams: {
98
          "errorCode": LoginErrorCodes.NOT_VALID,
99
          "redirectUrl": this._router.url
100
        }
101
      });
102
    } else {
103
      this.showLoading = true;
104
      this.updateErrorMessage = "";
105
      this.errorMessage = "";
106

    
107
      this.subscriptions.push(this._helpContentService.getAllDivIdsFull( this.properties.adminToolsAPIURL).subscribe(
108
        divIds => {
109
          this.divIds = divIds;
110
          this.checkboxes = [];
111

    
112
          let self = this;
113
          divIds.forEach(_ => {
114
            self.checkboxes.push(<CheckDivId>{divId: _, checked: false});
115
          });
116

    
117
          this.showLoading = false;
118
        },
119
        error => this.handleError('System error retrieving classes', error)));
120
    }
121
  }
122

    
123
  // public showModal():void {
124
  //     this.modal.showModal();
125
  // }
126

    
127
  public toggleCheckBoxes(event) {
128
    this.checkboxes.forEach(_ => _.checked = event.target.checked);
129
  }
130

    
131
  public applyCheck(flag: boolean) {
132
    this.checkboxes.forEach(_ => _.checked = flag);
133
  }
134

    
135
  public getSelectedDivIds(): string[] {
136
    return this.checkboxes.filter(divId => divId.checked == true).map(checkedDivId => checkedDivId.divId).map(res => res._id);
137
  }
138

    
139
  private deleteDivIdsFromArray(ids: string[]): void {
140
    for (let id of ids) {
141
      let i = this.checkboxes.findIndex(_ => _.divId._id == id);
142
      this.checkboxes.splice(i, 1);
143
    }
144
  }
145

    
146
  public confirmDeleteDivId(id: string) {
147
    this.selectedDivIds = [id];
148
    this.confirmModalOpen();
149
  }
150

    
151
  public confirmDeleteSelectedDivIds() {
152
    this.selectedDivIds = this.getSelectedDivIds();
153
    this.confirmModalOpen();
154
  }
155

    
156
  private confirmModalOpen() {
157
    if (!Session.isLoggedIn()) {
158
      this._router.navigate(['/user-info'], {
159
        queryParams: {
160
          "errorCode": LoginErrorCodes.NOT_VALID,
161
          "redirectUrl": this._router.url
162
        }
163
      });
164
    } else {
165
      this.alertModalDeleteDivIds.cancelButton = true;
166
      this.alertModalDeleteDivIds.okButton = true;
167
      this.alertModalDeleteDivIds.alertTitle = "Delete Confirmation";
168
      this.alertModalDeleteDivIds.message = "Are you sure you want to delete the selected class(es)?";
169
      this.alertModalDeleteDivIds.okButtonText = "Yes";
170
      this.alertModalDeleteDivIds.open();
171
    }
172
  }
173

    
174
  public confirmedDeleteDivIds(data: any) {
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.showLoading = true;
184
      this.updateErrorMessage = "";
185
      this.subscriptions.push(this._helpContentService.deleteDivIds(this.selectedDivIds, this.properties.adminToolsAPIURL).subscribe(
186
        _ => {
187
          this.deleteDivIdsFromArray(this.selectedDivIds);
188
          this.showLoading = false;
189
        },
190
        error => this.handleUpdateError('System error deleting the selected classes', error)
191
      ));
192
    }
193
  }
194

    
195
  public editDivId(i: number) {
196
    let divId: DivId = this.checkboxes[i].divId;
197
    this.formPages = <Page[]>divId.pages;
198
    this.pagesCtrl = this._fb.array([]);
199
    this.myForm = this._fb.group({
200
      _id: divId._id,
201
      name: [divId.name,Validators.required],
202
      pages: this.pagesCtrl,
203
      portalType: [divId.portalType, Validators.required]
204
    });
205
    this.myForm.controls['portalType'].disable();
206

    
207
    for(let i = 0; i < divId.pages.length; i++) {
208
      this.pagesCtrl.push(this._fb.control(divId.pages[i]));
209
    }
210
    this.filteredPages = this.pageSearchCtrl.valueChanges.pipe(startWith(''),
211
      map(page => this._filter(page)));
212
    this.selectedPages = JSON.parse(JSON.stringify(divId.pages));
213
    this.divIdsModalOpen(this.alertModalSaveDivId, "", "Save Changes");
214
  }
215

    
216
  public newDivId() {
217
    this.myForm.controls['portalType'].enable();
218

    
219
    this.pagesCtrl = this._fb.array([]);
220
    this.myForm = this._fb.group({
221
      _id: '',
222
      name: ['', Validators.required],
223
      pages: this.pagesCtrl,
224
      //openaire: this._fb.control(true),
225
      portalType: ['', Validators.required]
226
    });
227
    this.filteredPages = this.pageSearchCtrl.valueChanges.pipe(startWith(''),
228
      map(page => this._filter(page)));
229
    this.modalErrorMessage = "";
230
    this.selectedPages = [];
231
    this.divIdsModalOpen(this.alertModalSaveDivId, "", "Save");
232
  }
233

    
234
  private divIdsModalOpen(modal: any, title: string, yesBtn: string) {
235
    if (!Session.isLoggedIn()) {
236
      this._router.navigate(['/user-info'], {
237
        queryParams: {
238
          "errorCode": LoginErrorCodes.NOT_VALID,
239
          "redirectUrl": this._router.url
240
        }
241
      });
242
    } else {
243
      modal.cancelButton = true;
244
      modal.okButton = true;
245
      modal.alertTitle = title;
246
      modal.okButtonText = yesBtn;
247
      modal.open();
248
    }
249
  }
250

    
251
  public divIdSaveConfirmed(data: any) {
252
    if (!Session.isLoggedIn()) {
253
      this._router.navigate(['/user-info'], {
254
        queryParams: {
255
          "errorCode": LoginErrorCodes.NOT_VALID,
256
          "redirectUrl": this._router.url
257
        }
258
      });
259
    } else {
260
      console.log(this.myForm.value)
261
      if (this.myForm.value['_id'].length == 0) {
262
        this.myForm.controls['portalType'].enable();
263

    
264
        this.modalErrorMessage = "";
265

    
266
        this.subscriptions.push(this._helpContentService.saveDivId(<DivId>this.myForm.value, this.properties.adminToolsAPIURL).subscribe(
267
          divId => {
268
            this.divIdSavedSuccessfully(divId);
269
          },
270
          error => this.handleUpdateError("System error creating class", error)
271
        ));
272
      } else {
273
        this.subscriptions.push(this._helpContentService.updateDivId(<DivId>this.myForm.value, this.properties.adminToolsAPIURL).subscribe(
274
          divId => {
275
            this.divIdUpdatedSuccessfully(divId);
276
          },
277
          error => this.handleUpdateError("System error updating class", error)
278
        ));
279

    
280
      }
281
    }
282
  }
283

    
284
  public divIdSavedSuccessfully(divId: DivId) {
285
    this.checkboxes.push(<CheckDivId>{divId: divId, checked: false});
286
    this.applyCheck(false);
287
  }
288

    
289
  public divIdUpdatedSuccessfully(divId: DivId) {
290
    this.checkboxes.find(checkItem => checkItem.divId._id == divId._id).divId = divId;
291
    this.applyCheck(false);
292
  }
293

    
294
  public filterBySearch(text: string) {
295
    this.searchText = new RegExp(text, 'i');
296
    this.applyFilter();
297
  }
298

    
299
  public applyFilter() {
300
    this.checkboxes = [];
301
    this.divIds.filter(item => this.filterDivIds(item)).forEach(
302
      _ => this.checkboxes.push(<CheckDivId>{divId: _, checked: false})
303
    );
304
  }
305
  public applyTypeFilter() {
306
    this.checkboxes = [];
307
    this.divIds.filter(item => this.filterByType(item)).forEach(
308
      _ => this.checkboxes.push(<CheckDivId>{divId: _, checked: false})
309
    );
310
  }
311

    
312
  public filterByType(divId: DivId): boolean {
313
    let type = this.filterForm.get("type").value;
314
    return  type == "all" || (type  == divId.portalType);
315
  }
316
  public filterDivIds(divId: DivId): boolean {
317
    let textFlag = this.searchText.toString() == '' || (divId.name + ' ' + divId.portalType).match(this.searchText) != null;
318
    return textFlag;
319
  }
320

    
321
  handleUpdateError(message: string, error) {
322
    if (error == null) {
323
      // this.formComponent.reset();
324
    } else {
325
      this.updateErrorMessage = message;
326
      console.log('Server responded: ' + error);
327
    }
328

    
329
    this.showLoading = false;
330
  }
331

    
332
  handleError(message: string, error) {
333
    this.errorMessage = message;
334
    console.log('Server responded: ' + error);
335

    
336
    this.showLoading = false;
337
  }
338

    
339
  getPages() {
340
    this.showLoading = true;
341
    this.errorMessage = "";
342
    this.subscriptions.push(this._helpContentService.getAllPages(this.properties.adminToolsAPIURL).subscribe(
343
      pages => {
344
        this.allPages = pages;
345
        this.showLoading = false;
346
      },
347
      error => this.handleError('System error retrieving pages', error)
348
    ));
349

    
350
  }
351

    
352
  remove(page): void {
353
    let index = this.selectedPages.indexOf(page);
354
    if (index >= 0) {
355
      this.selectedPages.splice(index, 1);
356
      this.pagesCtrl.value.splice(index, 1);
357
      this.pagesCtrl.markAsDirty();
358
    }
359
  }
360

    
361
  selected(event: MatAutocompleteSelectedEvent): void {
362
    let newPage = event.option.value;
363
    if (this.selectedPages.indexOf(newPage) == -1) {
364
      this.selectedPages.push(event.option.value);
365
      this.pagesCtrl.push(this._fb.control(newPage));
366
      this.pagesCtrl.markAsDirty();
367
    }
368
    this.pageInput.nativeElement.value = '';
369
    this.pageSearchCtrl.setValue('');
370
  }
371

    
372
  private _filter(value: string): Page[] {
373
    if (!value || value.length == 0) {
374
      return this.allPages.slice();
375
    }
376
    const filterValue = value.toString().toLowerCase();
377
    return this.allPages.filter(page => page.name.toLowerCase().indexOf(filterValue) != -1);
378
  }
379
}
(3-3/4)