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
import {ClearCacheService} from "../../openaireLibrary/services/clear-cache.service";
17

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

    
23
export class CommunitiesComponent implements OnInit {
24

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

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

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

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

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

    
46
    // public errorMessage: string;
47

    
48
    public formGroup: FormGroup;
49

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

    
53
    public properties: EnvProperties = null;
54

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

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

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

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

    
77

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

    
87

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

    
100
    // public showModal():void {
101
    //     this.modal.showModal();
102
    // }
103

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
245
    public communitySavedSuccessfully(community: Portal) {
246
        this.checkboxes.push(<CheckPortal>{community : community, checked : false});
247
        this.applyCheck(false);
248
    }
249

    
250
    public communityUpdatedSuccessfully(community: Portal) {
251
        this.checkboxes.find(checkItem => checkItem.community._id === community._id).community = community;
252
        this.applyCheck(false);
253
    }
254

    
255
    public filterBySearch(text: string) {
256
        this.searchText = new RegExp(text, 'i');
257
        this.applyFilter();
258
    }
259

    
260
    public applyFilter() {
261
        this.checkboxes = [];
262
        this.communities.filter(item => this.filterCommunities(item)).forEach(
263
            _ => this.checkboxes.push(<CheckPortal>{community: _, checked: false})
264
        );
265
    }
266

    
267
    public filterCommunities(community: Portal): boolean {
268
        const textFlag = this.searchText.toString() === '' || (community.name || community.type).match(this.searchText) != null;
269
        return textFlag;
270
    }
271

    
272
    handleUpdateError(message: string, error) {
273
        if (error == null) {
274
            this.formComponent.reset();
275
        } else {
276
          this.updateErrorMessage = message;
277
          console.log('Server responded: ' + error);
278
        }
279

    
280
        this.showLoading = false;
281
    }
282

    
283
    handleError(message: string, error) {
284
        this.errorMessage = message;
285
        console.log('Server responded: ' + error);
286

    
287
        this.showLoading = false;
288
    }
289
}
(3-3/6)