Project

General

Profile

1
import { Component, ViewChild, OnInit, ViewEncapsulation, Input, Output, EventEmitter } from '@angular/core';
2
import { ActivatedRoute, Router } from "@angular/router";
3
import { Subject } from 'rxjs/Subject';
4
import { DataTableDirective } from 'angular-datatables';
5

    
6
import {ErrorCodes} from '../../../openaireLibrary/utils/properties/errorCodes';
7
import {SearchUtilsClass } from '../../../openaireLibrary/searchPages/searchUtils/searchUtils.class';
8
import {EnvProperties} from '../../../openaireLibrary/utils/properties/env-properties';
9
import {ManageCommunityProjectsService} from '../../../services/manageProjects.service';
10
import {SearchCommunityProjectsService} from '../../../openaireLibrary/connect/projects/searchProjects.service';
11
import {RouterHelper} from '../../../openaireLibrary/utils/routerHelper.class';
12
import {DOI, StringUtils} from '../../../openaireLibrary/utils/string-utils.class';
13

    
14
import {Session} from '../../../openaireLibrary/login/utils/helper.class';
15
import {LoginErrorCodes} from '../../../openaireLibrary/login/utils/guardHelper.class';
16

    
17
@Component({
18
    selector: 'remove-projects',
19
    templateUrl: './remove-projects.component.html',
20
    styles: [`
21
      #dpTable_info, #dpTable_paginate,  #dpTable_length,  #dpTable_filter{
22
        display: none;
23
      }
24

    
25
      `],
26
    encapsulation: ViewEncapsulation.None // this used in order styles to work
27
})
28

    
29
export class RemoveProjectsComponent implements OnInit {
30
  public routerHelper:RouterHelper = new RouterHelper();
31

    
32
  private community: string = '';
33
  private communityUrl = "https://beta.explore.openaire.eu";
34

    
35
  private errorCodes: ErrorCodes;
36

    
37
  @Output() communityProjectsChanged  = new EventEmitter();
38
  public communityProjects = [];
39
  public communitySearchUtils:SearchUtilsClass = new SearchUtilsClass();
40

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

    
44
  public disableForms: boolean = false;
45

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

    
51
  public rowsOnPage:number  = 10;
52

    
53
  public queryParameters: string = "";
54

    
55
  public query = '';
56
  public selectedProjects=[] ;
57
  public elementRef;
58

    
59
  public funders:Set<string>;
60
  public selectedFunder:string ="";
61
  //@Output() projectSelected = new EventEmitter();
62
  //@Input() public properties:EnvProperties;
63

    
64
  public projects:string[];
65
  private triggered: boolean = false;
66

    
67
  private selectedCommunityProject: any;
68

    
69
  @ViewChild('AlertModalDeleteCommunity') alertModalDeleteCommunity;
70

    
71
  ngOnInit() {
72
    this.route.data.subscribe((data: { envSpecific: EnvProperties }) => {
73
        this.properties = data.envSpecific;
74
      });
75

    
76
    this.route.queryParams.subscribe(params => {
77
      if(params['communityId']) {
78
        this.community = params['communityId'];
79
        this.communityUrl = "https://beta."+this.community+".openaire.eu";
80

    
81
        this._getCommunityProjects();
82
        //this.getFunders();
83
        //this._getOpenaireProjects("", 1, 10);
84
      }
85
    });
86

    
87
    this.dtOptions = {
88
      // "paging": true,
89
      // "searching": true,
90
      // "lengthChange": false,
91
      "pageLength": this.rowsOnPage,
92
      "language": {
93
          "search": "",
94
          "searchPlaceholder": "Search projects..."
95
        }
96
    };
97

    
98
    this.communitySearchUtils.keyword = "";
99
  }
100

    
101
  constructor(private route: ActivatedRoute, private _router: Router, private _manageCommunityProjectsService: ManageCommunityProjectsService, private _searchCommunityProjectsService: SearchCommunityProjectsService) {
102
    this.errorCodes = new ErrorCodes();
103
    this.communitySearchUtils.status = this.errorCodes.LOADING;
104
  }
105

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

    
117
    $.fn['dataTable'].ext.search.pop();
118
  }
119

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

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

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

    
133
       if (this.filterData(data, this.communitySearchUtils.keyword, this.selectedFunder)) {
134
         return true;
135
       }
136
       return false;
137
     });
138

    
139
     console.info("ngAfterViewInit");
140
  }
141

    
142
  filterData(row: any, query: string, selectedFunder: string) {
143
    let returnValue: boolean = false;
144

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

    
154
      if(!returnValue) {
155
        return false;
156
      }
157
    }
158

    
159
    if(selectedFunder){
160
      return this.filterQuery(row[2], selectedFunder);
161
    }
162

    
163
    return true;
164
  }
165

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

    
174

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

    
188
  public inCommunity(result: any): any {
189
    let found = false;
190
    for(let project of this.communityProjects) {
191
      if(project.opeaireId == result.id) {
192
        return true;
193
      } else if(result['title'].name.search("("+project.grantId+")") != -1 && result.funderShortname == project.funder) {
194
        return true;
195
      }
196
    }
197
    return found;
198

    
199
  }
200

    
201
  goTo(page:number = 1){
202
      this.communitySearchUtils.page=page;
203

    
204
      var table = $('#dpTable').DataTable();
205
      table.page( page - 1  ).draw( false );
206

    
207
      var info = table.page.info();
208
      console.info("records: "+info.recordsDisplay);
209
      this.communitySearchUtils.totalResults = info.recordsDisplay;
210
  }
211

    
212
  totalPages(): number {
213
      let totalPages:any = this.communitySearchUtils.totalResults/(this.rowsOnPage);
214
      if(!(Number.isInteger(totalPages))) {
215
          totalPages = (parseInt(totalPages, 10) + 1);
216
      }
217
      return totalPages;
218
  }
219

    
220
  public confirmedDeleteProject(data : any) {
221
    if(!Session.isLoggedIn()){
222
      console.info(this._router.url);
223
      this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
224
    } else {
225
      console.info("REMOVE: "+ this.selectedCommunityProject.id);
226
      this.subRemove = this._manageCommunityProjectsService.removeProject(this.properties, this.community, this.selectedCommunityProject.id).subscribe(
227
        data => {
228
          console.info("data REMOVE");
229
          console.info(data);
230
        },
231
        err => {
232
          console.info("error REMOVE");
233
          console.log(err);
234
        },
235
        () => {
236
          console.info("completed REMOVE");
237
          let index = this.communityProjects.indexOf(this.selectedCommunityProject);
238
          this.communityProjects.splice(index, 1);
239

    
240
          this.communitySearchUtils.totalResults--;
241
          this.communitySearchUtils.page=1;
242

    
243
          this.rerender();
244
        }
245
      )
246
    }
247
  }
248

    
249
  public removeProject(communityProject: any) {
250
    if(!Session.isLoggedIn()){
251
      console.info(this._router.url);
252
      this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
253
    } else {
254
      this.selectedCommunityProject = communityProject;
255
      this.alertModalDeleteCommunity.cancelButton = true;
256
      this.alertModalDeleteCommunity.okButton = true;
257
      this.alertModalDeleteCommunity.alertTitle = "Remove project?";
258
      let title = "";
259
      if(communityProject.name) {
260
        title = communityProject.name;
261
      }
262
      if(communityProject.name && communityProject.acronym) {
263
        title += " (";
264
      }
265
      if(communityProject.acronym) {
266
        title += communityProject.acronym;
267
      }
268
      if(communityProject.name && communityProject.acronym) {
269
        title += ")";
270
      }
271
      this.alertModalDeleteCommunity.message = "Project";
272
      if(title) {
273
        this.alertModalDeleteCommunity.message += " '"+title+"' ";
274
      }
275
      this.alertModalDeleteCommunity.message += "will be removed from your community. Are you sure?";
276
      this.alertModalDeleteCommunity.okButtonText = "Yes";
277
      this.alertModalDeleteCommunity.open();
278
    }
279
  }
280

    
281
  public _getCommunityProjects(){
282
    if(!Session.isLoggedIn()){
283
      console.info(this._router.url);
284
      this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
285
    } else {
286
      this.communitySearchUtils.status = this.errorCodes.LOADING;
287
      this.disableForms = true;
288
      this.communityProjects = [];
289
      this.communitySearchUtils.totalResults = 0;
290
      this.communitySearchUtils.page=1;
291
      this.communitySearchUtils.keyword = "";
292
      this.selectedFunder = "";
293

    
294
      this.subResults = this._searchCommunityProjectsService.searchProjects(this.properties, this.community).subscribe(
295
          data => {
296
            console.info(data);
297
            console.info("search Projects [total communityProjects:"+data.length+"]");
298
            this.communityProjects = data;
299

    
300
            this.communitySearchUtils.totalResults = data.length;
301
            this.communitySearchUtils.status = this.errorCodes.DONE;
302
            // if(this.communitySearchUtils.totalResults == 0 ){
303
            //   this.communitySearchUtils.status = this.errorCodes.NONE;
304
            // }
305
            this.disableForms = false;
306
            if(!this.triggered) {
307
              this.triggerInitialLoad();
308
            } else {
309
              var table = $('#dpTable').DataTable();
310
              table.clear();
311

    
312
              this.rerender();
313
            }
314

    
315
            this.communityProjectsChanged.emit({
316
                value: this.communityProjects,
317
            });
318

    
319
            this.createFunderFilter();
320
          },
321
          err => {
322
            console.log(err);
323
             //TODO check erros (service not available, bad request)
324

    
325
            if(err.status == '404') {
326
              this.communitySearchUtils.status = this.errorCodes.NOT_FOUND;
327
            } else if(err.status == '500') {
328
              this.communitySearchUtils.status = this.errorCodes.ERROR;
329
            } else {
330
              this.communitySearchUtils.status = this.errorCodes.NOT_AVAILABLE;
331
            }
332

    
333
            this.disableForms = false;
334
            if(!this.triggered) {
335
              this.triggerInitialLoad();
336
            } else {
337
              var table = $('#dpTable').DataTable();
338
              table.clear();
339

    
340
              this.rerender();
341
            }
342
          }
343
      );
344
    }
345
  }
346

    
347
  private createFunderFilter(): Set<String> {
348
    this.funders = new Set<string>();
349
    let i;
350
    for(i=0; i<this.communityProjects.length; i++) {
351
      let funder = this.communityProjects[i].funder;
352
      if(funder && !this.funders.has(funder)) {
353
        this.funders.add(funder);
354
      }
355
    }
356
    console.info(this.funders);
357
    return this.funders;
358
  }
359
}
(6-6/6)