Project

General

Profile

1
/**
2
 * Created by stefania on 7/13/17.
3
 */
4
import { Component, ViewChild, OnInit, ElementRef } from '@angular/core';
5
import { ActivatedRoute, Router } from '@angular/router';
6
import { HelpContentService } from '../../services/help-content.service';
7
import { FormGroup } from '@angular/forms';
8
import { CommunityFormComponent } from './community-form.component';
9
import { CheckPortal, Portal } from '../../domain/portal';
10
import { EnvProperties } from '../../openaireLibrary/utils/properties/env-properties';
11

    
12
import {Session} from '../../openaireLibrary/login/utils/helper.class';
13
import {LoginErrorCodes} from '../../openaireLibrary/login/utils/guardHelper.class';
14
import {HelperFunctions} from "../../openaireLibrary/utils/HelperFunctions.class";
15
import {Title} from '@angular/platform-browser';
16

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

    
22
export class CommunitiesComponent implements OnInit {
23

    
24
    // @ViewChild(ModalFormComponent)
25
    // @ViewChild('saveModal')
26
    // public modal:ModalFormComponent;
27
    //
28
    // @ViewChild('updateModal')
29
    // public updateModal:ModalFormComponent;
30

    
31
    // @ViewChild('deleteConfirmationModal')
32
    // public deleteConfirmationModal : DeleteConfirmationDialogComponent;
33
    @ViewChild('AlertModalSaveCommunity') alertModalSaveCommunity;
34
    @ViewChild('AlertModalUpdateCommunity') alertModalUpdateCommunity;
35
    @ViewChild('AlertModalDeleteCommunities') alertModalDeleteCommunities;
36
    private selectedCommunities: string[] = [];
37

    
38
    @ViewChild(CommunityFormComponent)
39
    public formComponent: CommunityFormComponent;
40

    
41
    public checkboxes: CheckPortal[] = [];
42

    
43
    public communities: Portal[] = [];
44

    
45
    // public errorMessage: string;
46

    
47
    public formGroup: FormGroup;
48

    
49
    private searchText: RegExp = new RegExp('');
50
    public  keyword = '';
51

    
52
    public properties: EnvProperties = null;
53

    
54
    public showLoading = true;
55
    public errorMessage = '';
56
    public updateErrorMessage = '';
57
    public modalErrorMessage = '';
58

    
59
    ngOnInit() {
60
        this.formGroup = this.formComponent.form;
61

    
62
        this.route.data
63
          .subscribe((data: { envSpecific: EnvProperties }) => {
64
            HelperFunctions.scroll();
65
            this.title.setTitle('Administration Dashboard | Communities');
66
            this.properties = data.envSpecific;
67
             this.getCommunities();
68
          });
69
    }
70

    
71
    constructor(private element: ElementRef, private route: ActivatedRoute,
72
                private title: Title,
73
                private _router: Router, private _helpContentService: HelpContentService) {}
74

    
75

    
76
    getCommunities() {
77
      if (!Session.isLoggedIn()) {
78
        this._router.navigate(['/user-info'], {
79
            queryParams: { 'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl':  this._router.url} });
80
      } else {
81
        this.showLoading = true;
82
        this.updateErrorMessage = '';
83
        this.errorMessage = '';
84

    
85

    
86
        this._helpContentService.getCommunitiesFull( this.properties.adminToolsAPIURL).subscribe(
87
            communities => {
88
                this.communities = communities;
89
                communities.forEach(_ => {
90
                  this.checkboxes.push(<CheckPortal>{community : _, checked : false});
91
                });
92
                this.showLoading = false;
93
        },
94
        error => this.handleError('System error retrieving communities', error));
95
      }
96
    }
97

    
98
    // public showModal():void {
99
    //     this.modal.showModal();
100
    // }
101

    
102
    public toggleCheckBoxes(event) {
103
        this.checkboxes.forEach(_ => _.checked = event.target.checked);
104
    }
105

    
106
    public applyCheck(flag: boolean) {
107
        this.checkboxes.forEach(_ => _.checked = flag);
108
    }
109

    
110
    public getSelectedCommunities(): string[] {
111
        return this.checkboxes.filter(community => community.checked === true).
112
        map(checkedCommunity => checkedCommunity.community).map(res => res._id);
113
    }
114

    
115
    private deleteCommunitiesFromArray(ids: string[]): void {
116
        for (let id of ids) {
117
            let i = this.checkboxes.findIndex(_ => _.community._id === id);
118
            this.checkboxes.splice(i, 1);
119
        }
120
    }
121

    
122
    public confirmDeleteCommunity(id: string) {
123
        // this.deleteConfirmationModal.ids = [id];
124
        // this.deleteConfirmationModal.showModal();
125
        this.selectedCommunities = [id];
126
        this.confirmModalOpen();
127
    }
128

    
129
    public confirmDeleteSelectedCommunities() {
130
        // this.deleteConfirmationModal.ids = this.getSelectedCommunities();
131
        // this.deleteConfirmationModal.showModal();
132
        this.selectedCommunities = this.getSelectedCommunities();
133
        this.confirmModalOpen();
134
    }
135

    
136
    private confirmModalOpen() {
137
      if (!Session.isLoggedIn()) {
138
        this._router.navigate(['/user-info'], {
139
            queryParams: { 'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl':  this._router.url} });
140
      } else {
141
        this.alertModalDeleteCommunities.cancelButton = true;
142
        this.alertModalDeleteCommunities.okButton = true;
143
        this.alertModalDeleteCommunities.alertTitle = 'Delete Confirmation';
144
        this.alertModalDeleteCommunities.message = 'Are you sure you want to delete the selected community(-ies)?';
145
        this.alertModalDeleteCommunities.okButtonText = 'Yes';
146
        this.alertModalDeleteCommunities.open();
147
      }
148
    }
149

    
150
    public confirmedDeleteCommunities(data: any) {
151
      if (!Session.isLoggedIn()) {
152
        this._router.navigate(['/user-info'], {
153
            queryParams: { 'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl':  this._router.url} });
154
      } else {
155
        this.showLoading = true;
156
        this.updateErrorMessage = '';
157

    
158
        this._helpContentService.deleteCommunities(this.selectedCommunities, this.properties.adminToolsAPIURL).
159
        subscribe(
160
            _ => {
161
              this.deleteCommunitiesFromArray(this.selectedCommunities);
162
              this.showLoading = false;
163
            },
164
            error => this.handleUpdateError('System error deleting the selected communities', error)
165
        );
166
      }
167
    }
168

    
169
    public editCommunity(i: number) {
170
        const community: Portal = this.checkboxes[i].community;
171
        this.formGroup.patchValue(community);
172
        this.formGroup.controls['type'].disable();
173
        // this.updateModal.showModal();
174
        this.modalErrorMessage = '';
175
        this.communitiesModalOpen(this.alertModalUpdateCommunity, 'Update', 'Update Community');
176
    }
177

    
178
    public newCommunity() {
179
      this.formGroup.controls['type'].enable();
180
      this.formComponent.reset();
181
      this.modalErrorMessage = '';
182
      this.communitiesModalOpen(this.alertModalSaveCommunity, 'Save', 'Add a new Community');
183
    }
184

    
185
    private communitiesModalOpen(modal: any, title: string, yesBtn: string) {
186
      if (!Session.isLoggedIn()) {
187
        this._router.navigate(['/user-info'], {
188
            queryParams: { 'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl':  this._router.url} });
189
      } else {
190
        modal.cancelButton = true;
191
        modal.okButton = true;
192
        modal.alertTitle = title;
193
        modal.okButtonText = yesBtn;
194
        modal.open();
195
      }
196
    }
197

    
198
    public communitySaveConfirmed(data: any) {
199
      if (!Session.isLoggedIn()) {
200
        this._router.navigate(['/user-info'], {
201
            queryParams: { 'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl':  this._router.url} });
202
      } else {
203
        if (!this.formGroup.valid) {
204
          this.communitiesModalOpen(this.alertModalSaveCommunity, 'Save', 'Add a new Community');
205
          this.modalErrorMessage = 'Please fill in all required fields marked with *';
206
        } else {
207
          this.modalErrorMessage = '';
208
          this._helpContentService.saveCommunity(<Portal> this.formGroup.value,
209
              this.properties.adminToolsAPIURL).subscribe(
210
              community => {
211
                this.communitySavedSuccessfully(community);
212
              },
213
              error => this.handleUpdateError('System error creating community', error)
214
          );
215
        }
216
      }
217
    }
218

    
219
    public communityUpdateConfirmed(data: any) {
220
      if (!Session.isLoggedIn()) {
221
        this._router.navigate(['/user-info'], {
222
            queryParams: { 'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl':  this._router.url} });
223
      } else {
224
        if (!this.formGroup.valid) {
225
          this.communitiesModalOpen(this.alertModalUpdateCommunity, 'Update', 'Update Community');
226
          this.modalErrorMessage = 'Please fill in all required fields marked with *';
227
        } else {
228
          this.formGroup.controls['type'].enable();
229
          this._helpContentService.updateCommunity(<Portal> this.formGroup.value,
230
              this.properties.adminToolsAPIURL).subscribe(
231
              community => {
232
                this.communityUpdatedSuccessfully(community);
233
              },
234
              error => this.handleUpdateError('System error updating community', error)
235
          );
236
        }
237
      }
238
    }
239

    
240
    public communitySavedSuccessfully(community: Portal) {
241
        this.checkboxes.push(<CheckPortal>{community : community, checked : false});
242
        this.applyCheck(false);
243
    }
244

    
245
    public communityUpdatedSuccessfully(community: Portal) {
246
        this.checkboxes.find(checkItem => checkItem.community._id === community._id).community = community;
247
        this.applyCheck(false);
248
    }
249

    
250
    public filterBySearch(text: string) {
251
        this.searchText = new RegExp(text, 'i');
252
        this.applyFilter();
253
    }
254

    
255
    public applyFilter() {
256
        this.checkboxes = [];
257
        this.communities.filter(item => this.filterCommunities(item)).forEach(
258
            _ => this.checkboxes.push(<CheckPortal>{community: _, checked: false})
259
        );
260
    }
261

    
262
    public filterCommunities(community: Portal): boolean {
263
        const textFlag = this.searchText.toString() === '' || (community.name || community.type).match(this.searchText) != null;
264
        return textFlag;
265
    }
266

    
267
    handleUpdateError(message: string, error) {
268
        if (error == null) {
269
            this.formComponent.reset();
270
        } else {
271
          this.updateErrorMessage = message;
272
          console.log('Server responded: ' + error);
273
        }
274

    
275
        this.showLoading = false;
276
    }
277

    
278
    handleError(message: string, error) {
279
        this.errorMessage = message;
280
        console.log('Server responded: ' + error);
281

    
282
        this.showLoading = false;
283
    }
284
}
(3-3/6)