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

    
16
@Component({
17
  selector: 'divIds',
18
  templateUrl: './divIds.component.html',
19
})
20

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

    
28
  public myForm: FormGroup;
29
  public pageSearchCtrl: FormControl;
30
  public pagesCtrl: FormArray;
31

    
32
  private searchText: RegExp = new RegExp('');
33
  public keyword: string = "";
34

    
35
  public properties: EnvProperties = null;
36
  public formPages: Page[] = [];
37

    
38
  public showLoading: boolean = true;
39
  public errorMessage: string = '';
40
  public updateErrorMessage: string = '';
41
  public modalErrorMessage: string = '';
42
  public filterForm: FormControl;
43
  private subscriptions: any[] = [];
44
  public allPages: Page[] = [];
45
  filteredPages: Observable<Page[]>;
46
  @ViewChild('PageInput') pageInput: ElementRef<HTMLInputElement>;
47
  selectedPages: Page[] = [];
48
  selectedCommunityPid = null;
49

    
50
  ngOnInit() {
51
    this.filterForm = this._fb.control('');
52
    this.pageSearchCtrl = this._fb.control('');
53
    this.subscriptions.push(this.filterForm.valueChanges.subscribe(value => {
54
      this.filterBySearch(value);
55
    }));
56
    this.pagesCtrl = this._fb.array([]);
57
    this.myForm = this._fb.group({
58
      _id: '',
59
      name: ['', Validators.required],
60
      pages: this.pagesCtrl,
61
      portalType: ['', Validators.required]
62
    });
63

    
64
    this.route.data
65
      .subscribe((data: { envSpecific: EnvProperties }) => {
66
        HelperFunctions.scroll();
67

    
68
        this.properties = data.envSpecific;
69

    
70
        this.getDivIds();
71
        this.route.queryParams.subscribe(params => {
72
          this.selectedCommunityPid = params['communityId'];
73
          this.getPages();
74
        });
75
      });
76
  }
77

    
78
  constructor(private element: ElementRef, private route: ActivatedRoute, private _router: Router, private _helpContentService: HelpContentService, private _fb: FormBuilder) {
79
  }
80

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

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

    
104
      this._helpContentService.getDivIdsFull(null, this.properties.adminToolsAPIURL).subscribe(
105
        divIds => {
106
          this.divIds = divIds;
107
          this.checkboxes = [];
108

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

    
114
          this.showLoading = false;
115
        },
116
        error => this.handleError('System error retrieving classes', error));
117
    }
118
  }
119

    
120
  // public showModal():void {
121
  //     this.modal.showModal();
122
  // }
123

    
124
  public toggleCheckBoxes(event) {
125
    this.checkboxes.forEach(_ => _.checked = event.target.checked);
126
  }
127

    
128
  public applyCheck(flag: boolean) {
129
    this.checkboxes.forEach(_ => _.checked = flag);
130
  }
131

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

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

    
143
  public confirmDeleteDivId(id: string) {
144
    this.selectedDivIds = [id];
145
    this.confirmModalOpen();
146
  }
147

    
148
  public confirmDeleteSelectedDivIds() {
149
    this.selectedDivIds = this.getSelectedDivIds();
150
    this.confirmModalOpen();
151
  }
152

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

    
171
  public confirmedDeleteDivIds(data: any) {
172
    if (!Session.isLoggedIn()) {
173
      this._router.navigate(['/user-info'], {
174
        queryParams: {
175
          "errorCode": LoginErrorCodes.NOT_VALID,
176
          "redirectUrl": this._router.url
177
        }
178
      });
179
    } else {
180
      this.showLoading = true;
181
      this.updateErrorMessage = "";
182
      this._helpContentService.deleteDivIds(this.selectedDivIds, this.properties.adminToolsAPIURL).subscribe(
183
        _ => {
184
          this.deleteDivIdsFromArray(this.selectedDivIds);
185
          this.showLoading = false;
186
        },
187
        error => this.handleUpdateError('System error deleting the selected classes', error)
188
      );
189
    }
190
  }
191

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

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

    
213
  public newDivId() {
214
    this.myForm.controls['portalType'].enable();
215

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

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

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

    
261
        this.modalErrorMessage = "";
262

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

    
277
      }
278
    }
279
  }
280

    
281
  public divIdSavedSuccessfully(divId: DivId) {
282
    this.checkboxes.push(<CheckDivId>{divId: divId, checked: false});
283
    this.applyCheck(false);
284
  }
285

    
286
  public divIdUpdatedSuccessfully(divId: DivId) {
287
    this.checkboxes.find(checkItem => checkItem.divId._id == divId._id).divId = divId;
288
    this.applyCheck(false);
289
  }
290

    
291
  public filterBySearch(text: string) {
292
    this.searchText = new RegExp(text, 'i');
293
    this.applyFilter();
294
  }
295

    
296
  public applyFilter() {
297
    this.checkboxes = [];
298
    this.divIds.filter(item => this.filterDivIds(item)).forEach(
299
      _ => this.checkboxes.push(<CheckDivId>{divId: _, checked: false})
300
    );
301
  }
302

    
303
  public filterDivIds(divId: DivId): boolean {
304
    let textFlag = this.searchText.toString() == '' || (divId.name + ' ' + divId.portalType).match(this.searchText) != null;
305
    return textFlag;
306
  }
307

    
308
  handleUpdateError(message: string, error) {
309
    if (error == null) {
310
      // this.formComponent.reset();
311
    } else {
312
      this.updateErrorMessage = message;
313
      console.log('Server responded: ' + error);
314
    }
315

    
316
    this.showLoading = false;
317
  }
318

    
319
  handleError(message: string, error) {
320
    this.errorMessage = message;
321
    console.log('Server responded: ' + error);
322

    
323
    this.showLoading = false;
324
  }
325

    
326
  getPages() {
327
    this.showLoading = true;
328
    this.errorMessage = "";
329
    this._helpContentService.getPages(this.properties.adminToolsAPIURL, this.selectedCommunityPid).subscribe(
330
      pages => {
331
        this.allPages = pages;
332
        this.showLoading = false;
333
      },
334
      error => this.handleError('System error retrieving pages', error)
335
    );
336

    
337
  }
338

    
339
  remove(page): void {
340
    let index = this.selectedPages.indexOf(page);
341
    if (index >= 0) {
342
      this.selectedPages.splice(index, 1);
343
      this.pagesCtrl.value.splice(index, 1);
344
      this.pagesCtrl.markAsDirty();
345
    }
346
  }
347

    
348
  selected(event: MatAutocompleteSelectedEvent): void {
349
    let newPage = event.option.value;
350
    if (this.selectedPages.indexOf(newPage) == -1) {
351
      this.selectedPages.push(event.option.value);
352
      this.pagesCtrl.push(this._fb.control(newPage));
353
      this.pagesCtrl.markAsDirty();
354
    }
355
    this.pageInput.nativeElement.value = '';
356
    this.pageSearchCtrl.setValue('');
357
  }
358

    
359
  private _filter(value: string): Page[] {
360
    if (!value || value.length == 0) {
361
      return this.allPages.slice();
362
    }
363
    const filterValue = value.toString().toLowerCase();
364
    return this.allPages.filter(page => page.name.toLowerCase().indexOf(filterValue) != -1);
365
  }
366
}
(2-2/3)