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 { CheckCommunity, Community } from '../../domain/community';
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: CheckCommunity[] = [];
42

    
43
    public communities: Community[] = [];
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(<CheckCommunity>{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: Community = this.checkboxes[i].community;
171
        this.formGroup.patchValue(community);
172
        // this.updateModal.showModal();
173
        this.modalErrorMessage = '';
174
        this.communitiesModalOpen(this.alertModalUpdateCommunity, 'Update', 'Update Community');
175
    }
176

    
177
    public newCommunity() {
178
        this.formComponent.reset();
179
        this.modalErrorMessage = '';
180
        this.communitiesModalOpen(this.alertModalSaveCommunity, 'Save', 'Add a new Community');
181
    }
182

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

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

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

    
237
    public communitySavedSuccessfully(community: Community) {
238
        this.checkboxes.push(<CheckCommunity>{community : community, checked : false});
239
        this.applyCheck(false);
240
    }
241

    
242
    public communityUpdatedSuccessfully(community: Community) {
243
        this.checkboxes.find(checkItem => checkItem.community._id === community._id).community = community;
244
        this.applyCheck(false);
245
    }
246

    
247
    public filterBySearch(text: string) {
248
        this.searchText = new RegExp(text, 'i');
249
        this.applyFilter();
250
    }
251

    
252
    public applyFilter() {
253
        this.checkboxes = [];
254
        this.communities.filter(item => this.filterCommunities(item)).forEach(
255
            _ => this.checkboxes.push(<CheckCommunity>{community: _, checked: false})
256
        );
257
    }
258

    
259
    public filterCommunities(community: Community): boolean {
260
        const textFlag = this.searchText.toString() === '' || (community.name).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
          this.updateErrorMessage = message;
269
          console.log('Server responded: ' + error);
270
        }
271

    
272
        this.showLoading = false;
273
    }
274

    
275
    handleError(message: string, error) {
276
        this.errorMessage = message;
277
        console.log('Server responded: ' + error);
278

    
279
        this.showLoading = false;
280
    }
281
}
(3-3/6)