Project

General

Profile

1
import {Component, ViewChild, OnInit, Input, Output, ElementRef}     from '@angular/core';
2
import {ViewEncapsulation, EventEmitter}                 from '@angular/core';
3
import {SimpleChanges, OnChanges}                        from '@angular/core';
4
import {FormGroup, FormArray, FormBuilder, Validators}   from '@angular/forms';
5
import {ActivatedRoute, Router}                          from '@angular/router';
6
import {Subject}                                         from 'rxjs';
7
import {DataTableDirective}                              from 'angular-datatables';
8

    
9
import {EnvProperties}                                   from '../../openaireLibrary/utils/properties/env-properties';
10
import {SubscribeService}                                from '../../openaireLibrary/utils/subscribe/subscribe.service';
11
import {RouterHelper}                                    from '../../openaireLibrary/utils/routerHelper.class';
12

    
13
import {ErrorCodes}                                      from '../../openaireLibrary/utils/properties/errorCodes';
14
import {SearchUtilsClass}                                from '../../openaireLibrary/searchPages/searchUtils/searchUtils.class';
15

    
16
import {Session} from '../../openaireLibrary/login/utils/helper.class';
17
import {LoginErrorCodes} from '../../openaireLibrary/login/utils/guardHelper.class';
18
import {HelperFunctions} from "../../openaireLibrary/utils/HelperFunctions.class";
19

    
20
@Component({
21
    selector: 'manage-subscribers',
22
    templateUrl: './manage-subscribers.component.html',
23
    styles: [`
24
      #dpTable_info, #dpTable_paginate,  #dpTable_length,  #dpTable_filter{
25
        display: none;
26
      }
27
    `],
28
    encapsulation: ViewEncapsulation.None // this used in order styles to work
29
})
30

    
31
export class ManageSubscribersComponent implements OnInit {
32
    public routerHelper:RouterHelper = new RouterHelper();
33

    
34
    private errorCodes: ErrorCodes;
35

    
36
    @Output() commmunitySubscribersChanged = new EventEmitter();
37
    public communitySubscribers = [];
38
    public subscribersSearchUtils: SearchUtilsClass = new SearchUtilsClass();
39

    
40
    public sub: any; public subResults: any; subRemove: any;
41
    public properties: EnvProperties;
42

    
43
    public disableForms: boolean = false;
44

    
45
    dtOptions: DataTables.Settings = {};
46
    showTable = false; filteringAdded = false;
47
    @ViewChild(DataTableDirective) datatableElement: DataTableDirective;
48
    dtTrigger: Subject<any> = new Subject(); //necessary
49

    
50
    public rowsOnPage:number = 10;
51

    
52
    public queryParameters: string = "";
53

    
54
    public query = '';
55
    public selectedSubscribersEmail=[];
56
    public elementRef;
57

    
58
    public subscribers:string[];
59
    private triggered: boolean = false;
60

    
61
    private selectedSubscriberEmail: any;
62

    
63
    public communityId = null;
64

    
65
    @ViewChild('AlertModalDeleteSubscriber') alertModalDeleteSubscriber;
66

    
67
    constructor (private element: ElementRef,
68
                 private route: ActivatedRoute,
69
                 private _router: Router,
70
                 public _fb: FormBuilder,
71
                 private _subscribeService: SubscribeService) {
72

    
73
        this.errorCodes = new ErrorCodes();
74
        this.subscribersSearchUtils.status = this.errorCodes.LOADING;
75
    }
76

    
77
    ngOnInit() {
78
        this.route.data.subscribe((data: { envSpecific: EnvProperties }) => {
79
        this.properties = data.envSpecific;
80
        this.route.queryParams.subscribe(
81

    
82
            communityId => {
83
                HelperFunctions.scroll();
84

    
85
                this.communityId = communityId['communityId'];
86

    
87
                if (this.communityId != null && this.communityId != '') {
88
                    this._getCommunitySubscribers();
89
                }
90
            });
91
    });
92

    
93
        this.dtOptions = {
94
            "pageLength": this.rowsOnPage,
95
            "language": {
96
                "search": "",
97
                "searchPlaceholder": "Search subscribers..."
98
            }
99
        };
100

    
101
        this.subscribersSearchUtils.keyword = "";
102
    }
103

    
104
    public ngOnDestroy() {
105
        if(this.sub){
106
          this.sub.unsubscribe();
107
        }
108
        if(this.subResults) {
109
          this.subResults.unsubscribe();
110
        }
111
        if(this.subRemove) {
112
          this.subRemove.unsubscribe();
113
        }
114

    
115
        $.fn['dataTable'].ext.search.pop();
116
    }
117

    
118
    rerender(): void {
119
        this.datatableElement.dtInstance.then((dtInstance: DataTables.Api) => {
120
            // Destroy the table first
121
            dtInstance.destroy();
122

    
123
            // Call the dtTrigger to rerender again
124
            this.dtTrigger.next();
125
        });
126
    }
127

    
128
    ngAfterViewInit(): void {
129
        $.fn['dataTable'].ext.search.push((settings, data, dataIndex) => {
130

    
131
            if (this.filterData(data, this.subscribersSearchUtils.keyword)) {
132
                return true;
133
            }
134
                return false;
135
        });
136

    
137
        //console.info("ngAfterViewInit");
138
    }
139

    
140
    filterData(row: any, query: string) {
141
      if(!Session.isLoggedIn()){
142
        this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
143
      } else {
144
        let returnValue: boolean = false;
145

    
146
        if(query) {
147
            for(var i = 0; i < 2; i++) {
148
                var r= this.filterQuery(row[i], query);
149
                if(r) {
150
                    returnValue = true;
151
                    break;
152
                }
153
            }
154

    
155
            if(!returnValue) {
156
                return false;
157
            }
158
        }
159
        return true;
160
      }
161
    }
162

    
163
    filterQuery(data, query){
164
        if(data.toLowerCase().indexOf(query.toLowerCase()) > -1) {
165
            return true;
166
        } else {
167
            return false;
168
        }
169
    }
170

    
171
    /*
172
    Trigger a table draw in order to get the initial filtering
173
    */
174
    triggerInitialLoad(){
175
        this.triggered = true;
176
        //console.info("triggerInitialLoad");
177
        setTimeout(function() {
178
            var table = (<any>$('#dpTable')).DataTable();
179
            table.page( 0  ).draw( false );
180
        }, 500);
181
        this.dtTrigger.next();
182
    }
183

    
184
    public goTo(page:number = 1) {
185
      if(!Session.isLoggedIn()){
186
        this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
187
      } else {
188
        this.subscribersSearchUtils.page=page;
189

    
190
        var table = $('#dpTable').DataTable();
191
        table.page( page - 1  ).draw( false );
192

    
193
        var info = table.page.info();
194
        this.subscribersSearchUtils.totalResults = info.recordsDisplay;
195
      }
196
    }
197

    
198
    totalPages(): number {
199
        let totalPages:any = this.subscribersSearchUtils.totalResults/(this.rowsOnPage);
200
        if(!(Number.isInteger(totalPages))) {
201
            totalPages = (parseInt(totalPages, 10) + 1);
202
        }
203
        return totalPages;
204
    }
205

    
206
    public removeSubscriber(email:string) {
207
      if(!Session.isLoggedIn()){
208
        this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
209
      } else {
210
        this.selectedSubscriberEmail = email;
211
        this.alertModalDeleteSubscriber.cancelButton = true;
212
        this.alertModalDeleteSubscriber.okButton = true;
213
        this.alertModalDeleteSubscriber.alertTitle = "Remove subscriber?";
214

    
215
        this.alertModalDeleteSubscriber.message = "Subscriber with email ";
216
            if (email) {
217
                this.alertModalDeleteSubscriber.message += " '"+email+"' ";
218
            }
219

    
220
        this.alertModalDeleteSubscriber.message += "will be removed from your community. Are you sure?";
221
        this.alertModalDeleteSubscriber.okButtonText = "Yes";
222
        this.alertModalDeleteSubscriber.open();
223
      }
224
    }
225

    
226
    public confirmedDeleteSubscriber() {
227
      if(!Session.isLoggedIn()){
228
        this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
229
      } else {
230
        this.subRemove = this._subscribeService.unSubscribeToCommunity(this.communityId, this.selectedSubscriberEmail, this.properties.adminToolsAPIURL).subscribe(
231
            result => {
232
                this.communitySubscribers = result;
233
            },
234
            err => {
235
                console.log(err);
236
            },
237
            () => {
238
                this.subscribersSearchUtils.totalResults--;
239
                this.subscribersSearchUtils.page=1;
240

    
241
                this.rerender();
242
            }
243
        )
244
      }
245
    }
246

    
247
    public _getCommunitySubscribers(){
248
      if(!Session.isLoggedIn()){
249
        this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
250
      } else {
251
        this.subscribersSearchUtils.status = this.errorCodes.LOADING;
252
        this.disableForms = true;
253
        this.communitySubscribers = [];
254
        this.subscribersSearchUtils.totalResults = 0;
255
        this.subscribersSearchUtils.page=1;
256
        this.subscribersSearchUtils.keyword = "";
257

    
258
        this.subResults = this._subscribeService.getCommunitySubscribers(this.properties, this.communityId).subscribe(
259

    
260
            res => {
261
                //console.info("search Subscribers [total communitySubscribers:"+res.subscribers.length+"]");
262
                this.communitySubscribers = res;
263

    
264
                this.subscribersSearchUtils.totalResults = res.subscribers.length;
265
                this.subscribersSearchUtils.status = this.errorCodes.DONE;
266

    
267
                this.disableForms = false;
268
                if(!this.triggered) {
269
                    this.triggerInitialLoad();
270
                } else {
271
                    var table = $('#dpTable').DataTable();
272
                    table.clear();
273

    
274
                this.rerender();
275
                }
276

    
277
                this.commmunitySubscribersChanged.emit({
278
                    value: this.communitySubscribers,
279
                });
280
            },
281
            err => {
282
                console.log(err);
283
                //TODO check erros (service not available, bad request)
284

    
285
                if(err.status == '404') {
286
                    this.subscribersSearchUtils.status = this.errorCodes.NOT_FOUND;
287
                } else if(err.status == '500') {
288
                    this.subscribersSearchUtils.status = this.errorCodes.ERROR;
289
                } else {
290
                    this.subscribersSearchUtils.status = this.errorCodes.NOT_AVAILABLE;
291
                }
292

    
293
                this.disableForms = false;
294
                if(!this.triggered) {
295
                    this.triggerInitialLoad();
296
                } else {
297
                    var table = $('#dpTable').DataTable();
298
                    table.clear();
299

    
300
                    this.rerender();
301
                }
302
            }
303
        );
304
      }
305
    }
306
}
(3-3/6)