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 {CheckDivId, DivId} from "../../utils/entities/adminTool/divId";
6
import {Page} from "../../utils/entities/adminTool/page";
7
import {EnvProperties} from '../../utils/properties/env-properties';
8
import {HelperFunctions} from "../../utils/HelperFunctions.class";
9
import {Subscriber} from "rxjs";
10
import {properties} from "../../../../environments/environment";
11
import {PortalUtils} from "../portal/portalHelper";
12
import {AlertModal} from "../../utils/modal/alert";
13
import {Option} from "../../sharedComponents/input/input.component";
14
import {SearchInputComponent} from "../../sharedComponents/search-input/search-input.component";
15
import {Title} from "@angular/platform-browser";
16
17
declare var UIkit;
18
19
@Component({
20
  selector: 'divIds',
21
  templateUrl: './divIds.component.html',
22
})
23
24
export class DivIdsComponent implements OnInit {
25
  @ViewChild('editModal') editModal: AlertModal;
26
  @ViewChild('deleteModal') deleteModal: AlertModal;
27
  private selectedDivIds: string[] = [];
28
  public checkboxes: CheckDivId[] = [];
29
  public divIds: DivId[] = [];
30
  public classForm: FormGroup;
31
  public pagesCtrl: FormArray;
32
33
  private searchText: RegExp = new RegExp('');
34
  public keyword: string = "";
35
  public properties: EnvProperties = properties;
36
  public formPages: Page[] = [];
37
  public showLoading: boolean = true;
38
  public filterForm: FormGroup;
39
  private subscriptions: any[] = [];
40
  public allPages: Option[] = [];
41
  selectedCommunityPid = null;
42
  public portalUtils: PortalUtils = new PortalUtils();
43
  private index: number;
44
  public selectedKeyword: string;
45
  @ViewChild('searchInputComponent') searchInputComponent: SearchInputComponent;
46
47
  constructor(private element: ElementRef, private route: ActivatedRoute, private _router: Router,
48
              private title: Title,
49
              private _helpContentService: HelpContentService, private _fb: FormBuilder) {
50
  }
51
52
  ngOnInit() {
53
    this.title.setTitle('Administrator Dashboard | Classes');
54
    this.filterForm = this._fb.group({
55
      keyword: [''],
56
      type: ['all', Validators.required]
57
    });
58
    this.subscriptions.push(this.filterForm.get('keyword').valueChanges.subscribe(value => {
59
      this.searchText = new RegExp(value, 'i');
60
      this.applyFilters();
61
    }));
62
    this.subscriptions.push(this.filterForm.get('type').valueChanges.subscribe(value => {
63
      this.applyFilters();
64
    }));
65
    this.getDivIds();
66
    this.subscriptions.push(this.route.queryParams.subscribe(params => {
67
      HelperFunctions.scroll();
68
      this.selectedCommunityPid = params['communityId'];
69
      this.getPages();
70
    }));
71
72
  }
73
74
  ngOnDestroy(): void {
75
    this.subscriptions.forEach(value => {
76
      if (value instanceof Subscriber) {
77
        value.unsubscribe();
78
      } else if (value instanceof Function) {
79
        value();
80
      }
81
    });
82
  }
83
84
  getDivIds() {
85
    this.showLoading = true;
86
    this.subscriptions.push(this._helpContentService.getAllDivIdsFull(this.properties.adminToolsAPIURL).subscribe(
87
      divIds => {
88
        this.divIds = divIds;
89
        this.checkboxes = [];
90
91
        let self = this;
92
        divIds.forEach(_ => {
93
          self.checkboxes.push(<CheckDivId>{divId: _, checked: false});
94
        });
95
96
        this.showLoading = false;
97
      },
98
      error => this.handleError('System error retrieving classes', error)));
99
  }
100
101
  // public showModal():void {
102
  //     this.modal.showModal();
103
  // }
104
105
  public toggleCheckBoxes(event) {
106
    this.checkboxes.forEach(_ => _.checked = event.target.checked);
107
  }
108
109
  public applyCheck(flag: boolean) {
110
    this.checkboxes.forEach(_ => _.checked = flag);
111
  }
112
113
  public getSelectedDivIds(): string[] {
114
    return this.checkboxes.filter(divId => divId.checked == true).map(checkedDivId => checkedDivId.divId).map(res => res._id);
115
  }
116
117
  private deleteDivIdsFromArray(ids: string[]): void {
118
    for (let id of ids) {
119
      let i = this.divIds.findIndex(_ => _._id == id);
120
      this.divIds.splice(i, 1);
121
    }
122
    this.applyFilters();
123
  }
124
125
  public confirmDeleteDivId(id: string) {
126
    this.selectedDivIds = [id];
127
    this.confirmModalOpen();
128
  }
129
130
  public confirmDeleteSelectedDivIds() {
131
    this.selectedDivIds = this.getSelectedDivIds();
132
    this.confirmModalOpen();
133
  }
134
135
  private confirmModalOpen() {
136
    this.deleteModal.cancelButton = true;
137
    this.deleteModal.okButton = true;
138
    this.deleteModal.alertTitle = "Delete Confirmation";
139
    this.deleteModal.message = "Are you sure you want to delete the selected class(es)?";
140
    this.deleteModal.okButtonText = "Yes";
141
    this.deleteModal.open();
142
  }
143
144
  public confirmedDeleteDivIds(data: any) {
145
    this.showLoading = true;
146
    this.subscriptions.push(this._helpContentService.deleteDivIds(this.selectedDivIds, this.properties.adminToolsAPIURL).subscribe(
147
      _ => {
148
        this.deleteDivIdsFromArray(this.selectedDivIds);
149
        UIkit.notification('Classes have been <b>successfully deleted</b>', {
150
          status: 'success',
151
          timeout: 6000,
152
          pos: 'bottom-right'
153
        });
154
        this.showLoading = false;
155
      },
156
      error => this.handleUpdateError('System error deleting the selected classes', error)
157
    ));
158
  }
159
160
  public editDivId(i: number) {
161
    let divId: DivId = this.checkboxes[i].divId;
162
    this.index = this.divIds.findIndex(value => value._id === divId._id);
163
    this.formPages = <Page[]>divId.pages;
164
    this.pagesCtrl = this._fb.array([], Validators.required);
165
    this.classForm = this._fb.group({
166
      _id: this._fb.control(divId._id),
167
      name: this._fb.control(divId.name, Validators.required),
168
      pages: this.pagesCtrl,
169
      portalType: this._fb.control(divId.portalType, Validators.required)
170
    });
171
    this.classForm.get('portalType').disable();
172
    for (let i = 0; i < divId.pages.length; i++) {
173
      this.pagesCtrl.push(this._fb.control(divId.pages[i]));
174
    }
175
    this.divIdsModalOpen("Edit class", "Save Changes");
176
  }
177
178
  public newDivId() {
179
    this.pagesCtrl = this._fb.array([], Validators.required);
180
    if (this.classForm) {
181
      this.classForm.get('portalType').enable();
182
    }
183
    this.classForm = this._fb.group({
184
      _id: this._fb.control(null),
185
      name: this._fb.control('', Validators.required),
186
      pages: this.pagesCtrl,
187
      portalType: this._fb.control('', Validators.required)
188
    });
189
    this.divIdsModalOpen("Create class", "Create");
190
  }
191
192
  private divIdsModalOpen(title: string, yesBtn: string) {
193
    this.editModal.cancelButton = true;
194
    this.editModal.okButton = true;
195
    this.editModal.okButtonLeft = false;
196
    this.editModal.alertTitle = title;
197
    this.editModal.okButtonText = yesBtn;
198
    this.editModal.open();
199
  }
200
201
  public divIdSaveConfirmed(data: any) {
202
    this.showLoading = true;
203
    if (!this.classForm.value._id) {
204
      this.subscriptions.push(this._helpContentService.saveDivId(<DivId>this.classForm.value, this.properties.adminToolsAPIURL).subscribe(
205
        divId => {
206
          this.divIdSavedSuccessfully(divId);
207
          UIkit.notification('Class <b>' + divId.name + '</b> has been <b>successfully created</b>', {
208
            status: 'success',
209
            timeout: 6000,
210
            pos: 'bottom-right'
211
          });
212
        },
213
        error => this.handleUpdateError("System error creating class", error)
214
      ));
215
    } else {
216
      this.classForm.get('portalType').enable();
217
      this.subscriptions.push(this._helpContentService.updateDivId(<DivId>this.classForm.value, this.properties.adminToolsAPIURL).subscribe(
218
        divId => {
219
          this.divIdUpdatedSuccessfully(divId);
220
          UIkit.notification('Class <b>' + divId.name + '</b> has been <b>successfully updated</b>', {
221
            status: 'success',
222
            timeout: 6000,
223
            pos: 'bottom-right'
224
          });
225
        },
226
        error => this.handleUpdateError("System error updating class", error)
227
      ));
228
229
    }
230
  }
231
232
  public divIdSavedSuccessfully(divId: DivId) {
233
    this.divIds.push(divId);
234
    this.applyFilters();
235
    this.applyCheck(false);
236
    this.showLoading = false;
237
  }
238
239
  public divIdUpdatedSuccessfully(divId: DivId) {
240
    this.divIds[this.index] = divId;
241
    this.applyFilters();
242
    this.applyCheck(false);
243
    this.showLoading = false;
244
  }
245
246
  public applyFilters() {
247
    this.checkboxes = [];
248
    this.divIds.filter(item => this.filterByType(item)).forEach(
249
      item => this.checkboxes.push(<CheckDivId>{divId: item, checked: false})
250
    );
251
    this.checkboxes = this.checkboxes.filter(item => this.filterDivIds(item.divId));
252
  }
253
254
  public filterByType(divId: DivId): boolean {
255
    let type = this.filterForm.get("type").value;
256
    return type == "all" || (type == divId.portalType);
257
  }
258
259
  public filterDivIds(divId: DivId): boolean {
260
    let textFlag = this.searchText.toString() == '' || (divId.name + ' ' + divId.portalType).match(this.searchText) != null;
261
    return textFlag;
262
  }
263
264
  handleUpdateError(message: string, error) {
265
    if (error == null) {
266
      // this.formComponent.reset();
267
    } else {
268
      UIkit.notification(message, {
269
        status: 'danger',
270
        timeout: 6000,
271
        pos: 'bottom-right'
272
      });
273
      console.log('Server responded: ' + error);
274
    }
275
    this.showLoading = false;
276
  }
277
278
  handleError(message: string, error) {
279
    UIkit.notification(message, {
280
      status: 'danger',
281
      timeout: 6000,
282
      pos: 'bottom-right'
283
    });
284
    console.log('Server responded: ' + error);
285
    this.showLoading = false;
286
  }
287
288
  getPages() {
289
    this.showLoading = true;
290
    this.subscriptions.push(this._helpContentService.getAllPages(this.properties.adminToolsAPIURL).subscribe(
291
      pages => {
292
        this.allPages = [];
293
        pages.forEach(page => {
294
          this.allPages.push({
295
            label: page.name + " [" + page.portalType + "]",
296
            value: page
297
          });
298
        });
299
        this.showLoading = false;
300
      },
301
      error => this.handleError('System error retrieving pages', error)
302
    ));
303
  }
304
305
  public onSearchClose() {
306
    this.selectedKeyword = this.filterForm.get('keyword').value;
307
  }
308
309
  public reset() {
310
    this.selectedKeyword = null;
311
    this.searchInputComponent.reset()
312
  }
313
}