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 {FormBuilder, FormGroup, Validators} from '@angular/forms';
5
import {EnvProperties} from '../../utils/properties/env-properties';
6

    
7
import {Session} from '../../login/utils/helper.class';
8
import {LoginErrorCodes} from '../../login/utils/guardHelper.class';
9
import {HelperFunctions} from "../../utils/HelperFunctions.class";
10
import {Subscriber} from "rxjs";
11
import {CheckPortal, Portal} from "../../utils/entities/adminTool/portal";
12
import {PortalUtils} from "./portalHelper";
13
import {properties} from "../../../../environments/environment";
14
import {AlertModal} from "../../utils/modal/alert";
15
import {SearchInputComponent} from "../../sharedComponents/search-input/search-input.component";
16
import {Title} from "@angular/platform-browser";
17

    
18
declare var UIkit;
19

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

    
25
export class PortalsComponent implements OnInit {
26
  
27
  @ViewChild('editModal') editModal: AlertModal;
28
  @ViewChild('deleteModal') deleteModal: AlertModal;
29
  private selectedPortals: string[] = [];
30
  
31
  public checkboxes: CheckPortal[] = [];
32
  public portals: Portal[] = [];
33
  
34
  public portalForm: FormGroup;
35
  public filterForm: FormGroup;
36
  private subscriptions: any[] = [];
37
  
38
  private searchText: RegExp = new RegExp('');
39
  public keyword = '';
40
  
41
  public properties: EnvProperties = null;
42
  
43
  public showLoading = true;
44
  public portalUtils: PortalUtils = new PortalUtils();
45
  private index: number;
46
  public selectedKeyword: string;
47
  @ViewChild('searchInputComponent') searchInputComponent: SearchInputComponent;
48
  
49
  constructor(private element: ElementRef, private route: ActivatedRoute,
50
              private title: Title,
51
              private _router: Router, private _helpContentService: HelpContentService, private _fb: FormBuilder) {
52
  }
53
  
54
  ngOnInit() {
55
    this.title.setTitle('Administrator Dashboard | Portals');
56
    this.filterForm = this._fb.group({
57
      keyword: [''],
58
      type: ['all', Validators.required]
59
    });
60
    this.subscriptions.push(this.filterForm.get('keyword').valueChanges.subscribe(value => {
61
      this.searchText = new RegExp(value, 'i');
62
      this.applyFilters();
63
    }));
64
    this.subscriptions.push(this.filterForm.get('type').valueChanges.subscribe(value => {
65
      this.applyFilters();
66
    }));
67
    
68
    HelperFunctions.scroll();
69
    this.properties = properties;
70
    this.getPortals();
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
  getPortals() {
85
    if (!Session.isLoggedIn()) {
86
      this._router.navigate(['/user-info'], {
87
        queryParams: {'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl': this._router.url}
88
      });
89
    } else {
90
      this.showLoading = true;
91
      this.subscriptions.push(this._helpContentService.getPortalsFull(this.properties.adminToolsAPIURL).subscribe(
92
        portals => {
93
          this.portals = portals;
94
          if (portals) {
95
            portals.forEach(_ => {
96
              this.checkboxes.push(<CheckPortal>{portal: _, checked: false});
97
            });
98
          }
99
          this.showLoading = false;
100
        },
101
        error => this.handleError('System error retrieving portals', error)));
102
    }
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 getSelectedPortals(): string[] {
114
    return this.checkboxes.filter(portal => portal.checked === true).map(checkedPortal => checkedPortal.portal).map(res => res._id);
115
  }
116
  
117
  private deletePortalsFromArray(ids: string[]): void {
118
    for (let id of ids) {
119
      let i = this.portals.findIndex(_ => _._id == id);
120
      this.portals.splice(i, 1);
121
    }
122
    this.applyFilters();
123
  }
124
  
125
  public confirmDeletePortal(id: string) {
126
    // this.deleteConfirmationModal.ids = [id];
127
    // this.deleteConfirmationModal.showModal();
128
    this.selectedPortals = [id];
129
    this.confirmModalOpen();
130
  }
131
  
132
  public confirmDeleteSelectedPortals() {
133
    this.selectedPortals = this.getSelectedPortals();
134
    this.confirmModalOpen();
135
  }
136
  
137
  private confirmModalOpen() {
138
      this.deleteModal.cancelButton = true;
139
      this.deleteModal.okButton = true;
140
      this.deleteModal.alertTitle = 'Delete Confirmation';
141
      this.deleteModal.message = 'Are you sure you want to delete the selected portal(-ies)?';
142
      this.deleteModal.okButtonText = 'Yes';
143
      this.deleteModal.open();
144
  }
145
  
146
  public confirmedDeletePortals(data: any) {
147
      this.showLoading = true;
148
      this.subscriptions.push(this._helpContentService.deleteCommunities(this.selectedPortals, this.properties.adminToolsAPIURL).subscribe(
149
        _ => {
150
          this.deletePortalsFromArray(this.selectedPortals);
151
          UIkit.notification('Portals have been <b>successfully deleted</b>', {
152
            status: 'success',
153
            timeout: 6000,
154
            pos: 'bottom-right'
155
          });
156
          this.showLoading = false;
157
        },
158
        error => this.handleUpdateError('System error deleting the selected communities', error)
159
      ));
160
  }
161
  
162
  public editPortal(i: number) {
163
    const portal: Portal = this.checkboxes[i].portal;
164
    this.index = this.portals.findIndex(value => value._id === portal._id);
165
    this.portalForm = this._fb.group({
166
      _id: this._fb.control(portal._id),
167
      name: this._fb.control(portal.name, Validators.required),
168
      pid: this._fb.control(portal.pid, Validators.required),
169
      piwik: this._fb.control(portal.piwik),
170
      type: this._fb.control(portal.type, Validators.required),
171
    });
172
    this.portalForm.get('type').disable();
173
    this.portalModalOpen('Edit Portal', 'Save');
174
  }
175
  
176
  public newPortal() {
177
    if(this.portalForm) {
178
      this.portalForm.get('type').enable();
179
    }
180
    this.portalForm = this._fb.group({
181
      _id: this._fb.control(''),
182
      name: this._fb.control('', Validators.required),
183
      pid: this._fb.control('', Validators.required),
184
      piwik: this._fb.control(''),
185
      type: this._fb.control('', Validators.required),
186
    });
187
    this.portalModalOpen('Create Portal', 'Create');
188
  }
189
  
190
  private portalModalOpen(title: string, yesBtn: string) {
191
    if (!Session.isLoggedIn()) {
192
      this._router.navigate(['/user-info'], {
193
        queryParams: {
194
          "errorCode": LoginErrorCodes.NOT_VALID,
195
          "redirectUrl": this._router.url
196
        }
197
      });
198
    } else {
199
      this.editModal.okButtonLeft = false;
200
      this.editModal.cancelButton = true;
201
      this.editModal.okButton = true;
202
      this.editModal.alertTitle = title;
203
      this.editModal.okButtonText = yesBtn;
204
      this.editModal.open();
205
    }
206
  }
207
  
208
  public portalSaveConfirmed(data: any) {
209
    this.showLoading = true;
210
    if (!Session.isLoggedIn()) {
211
      this._router.navigate(['/user-info'], {
212
        queryParams: {
213
          "errorCode": LoginErrorCodes.NOT_VALID,
214
          "redirectUrl": this._router.url
215
        }
216
      });
217
    } else {
218
      if (this.portalForm.value._id) {
219
        this.portalForm.get('type').enable();
220
        this.subscriptions.push(this._helpContentService.updateCommunity(<Portal>this.portalForm.value,
221
          this.properties.adminToolsAPIURL).subscribe(
222
          portal => {
223
            this.portalUpdatedSuccessfully(portal);
224
            UIkit.notification('Portal <b>' + portal.name + '</b> has been <b>successfully updated</b>', {
225
              status: 'success',
226
              timeout: 6000,
227
              pos: 'bottom-right'
228
            });
229
          },
230
          error => this.handleUpdateError('System error updating portal', error)
231
        ));
232
      } else {
233
        this.subscriptions.push(this._helpContentService.saveCommunity(<Portal>this.portalForm.value,
234
          this.properties.adminToolsAPIURL).subscribe(
235
          portal => {
236
            this.portalSavedSuccessfully(portal);
237
            UIkit.notification('Portal <b>' + portal.name + '</b> has been <b>successfully created</b>', {
238
              status: 'success',
239
              timeout: 6000,
240
              pos: 'bottom-right'
241
            });
242
          },
243
          error => this.handleUpdateError('System error creating portal', error)
244
        ));
245
      }
246
    }
247
  }
248
  
249
  public portalSavedSuccessfully(portal: Portal) {
250
    this.portals.push(portal);
251
    this.applyFilters();
252
    this.applyCheck(false);
253
    this.showLoading = false;
254
  }
255
  
256
  public portalUpdatedSuccessfully(portal: Portal) {
257
    this.portals[this.index] = portal;
258
    this.applyFilters();
259
    this.applyCheck(false);
260
    this.showLoading = false;
261
  }
262
  
263
  public applyFilters() {
264
    this.checkboxes = [];
265
    this.portals.filter(item => this.filterByType(item)).forEach(
266
      _ => this.checkboxes.push(<CheckPortal>{portal: _, checked: false})
267
    );
268
    this.checkboxes = this.checkboxes.filter(item => this.filterPortals(item.portal));
269
  }
270
  
271
  public filterByType(portal: Portal): boolean {
272
    let type = this.filterForm.get("type").value;
273
    return type == "all" || (type == portal.type);
274
  }
275
  
276
  public filterPortals(portal: Portal): boolean {
277
    const textFlag = this.searchText.toString() === '' || (portal.name || portal.type).match(this.searchText) != null;
278
    return textFlag;
279
  }
280
  
281
  handleUpdateError(message: string, error) {
282
    if (error == null) {
283
      this.portalForm = this._fb.group({
284
        name: '',
285
        _id: '',
286
        pid: '',
287
        piwik: '',
288
        type: ''
289
      });
290
    } else {
291
      UIkit.notification(message, {
292
        status: 'danger',
293
        timeout: 6000,
294
        pos: 'bottom-right'
295
      });
296
      console.log('Server responded: ' + error);
297
    }
298
    this.showLoading = false;
299
  }
300
  
301
  handleError(message: string, error) {
302
    UIkit.notification(message, {
303
      status: 'danger',
304
      timeout: 6000,
305
      pos: 'bottom-right'
306
    });
307
    console.log('Server responded: ' + error);
308
    this.showLoading = false;
309
  }
310
  
311
  public onSearchClose() {
312
    this.selectedKeyword = this.filterForm.get('keyword').value;
313
  }
314
  
315
  public reset() {
316
    this.selectedKeyword = null;
317
    this.searchInputComponent.reset()
318
  }
319
}
(4-4/5)