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, Subscriber} from 'rxjs';
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
import {FormArray, FormBuilder, FormGroup, Validators} from "@angular/forms";
17
import {ConnectHelper} from "../../openaireLibrary/connect/connectHelper";
18
import {properties} from "../../../environments/environment";
19
import {CommunityService} from "../../openaireLibrary/connect/community/community.service";
20
import {Option} from "../../openaireLibrary/sharedComponents/input/input.component";
21
import {CheckPortal, Portal} from "../../openaireLibrary/utils/entities/adminTool/portal";
22
import {SearchInputComponent} from "../../openaireLibrary/sharedComponents/search-input/search-input.component";
23

    
24
declare var UIkit;
25

    
26
@Component({
27
    selector: 'remove-projects',
28
    templateUrl: './remove-projects.component.html',
29
    // styles: [`
30
    //   #dpTable_info, #dpTable_paginate,  #dpTable_length,  #dpTable_filter{
31
    //     display: none;
32
    //   }
33
    // `],
34
    // encapsulation: ViewEncapsulation.None // this used in order styles to work
35
})
36

    
37
export class RemoveProjectsComponent implements OnInit {
38
  public routerHelper:RouterHelper = new RouterHelper();
39

    
40
  private community: string = '';
41
  private communityUrl = "https://beta.explore.openaire.eu";
42

    
43
  public errorCodes: ErrorCodes;
44

    
45
  @Output() communityProjectsChanged  = new EventEmitter();
46
  @Input() public communityProjects = [];
47
  public previewCommunityProjects = [];
48
  public communitySearchUtils:SearchUtilsClass = new SearchUtilsClass();
49

    
50
  public sub: any; public subResults: any; subRemove: any;
51
  properties:EnvProperties = properties;
52

    
53
  public disableForms: boolean = false;
54

    
55
  dtOptions: DataTables.Settings = {};
56
  showTable = false; filteringAdded = false;
57
  @ViewChild(DataTableDirective) datatableElement: DataTableDirective;
58
  dtTrigger: Subject<any> = new Subject(); //necessary
59

    
60
  public rowsOnPage:number  = 10;
61

    
62
  public queryParameters: string = "";
63

    
64
  public query = '';
65
  public selectedProjects=[] ;
66
  public elementRef;
67

    
68
  public funders:Set<string>;
69
  public selectedFunder:string ="";
70
  //@Output() projectSelected = new EventEmitter();
71
  //@Input() public properties:EnvProperties;
72

    
73
  public projects:string[];
74
  private triggered: boolean = false;
75

    
76
  private selectedCommunityProject: any;
77

    
78
  @ViewChild('AlertModalDeleteCommunity') alertModalDeleteCommunity;
79
  @ViewChild('searchInputComponent') searchInputComponent: SearchInputComponent;
80

    
81

    
82
  @Input() public showLoading: boolean = true;
83
  private subscriptions: any[] = [];
84
  /* Paging */
85
  page: number = 1;
86
  pageSize: number = 10;
87
  public portal: string;
88
  public name: string;
89
  public isPortalAdministrator = null;
90
  /* Search */
91
  filterForm: FormGroup;
92
  public fundersCtrl: FormArray;
93
  private searchText: RegExp = new RegExp('');
94
  public keyword: string = '';
95
  allOptions: Option[] = [];
96
  sortOptions: Option[] = [
97
    //{label:"Title (desc) ", value:{ sort: "title",descending: true }},
98
    {label:"Title ", value: { sort: "title",descending:false }},
99
    //{label:"Grant ID (desc) ", value:{ sort: "grant",descending: true }},
100
    {label:"Grant ID ", value: { sort: "grant",descending:false }},
101
    //{label:"Funder (desc) ", value:{ sort: "funder",descending: true }},
102
    {label:"Funder ", value: { sort: "funder",descending:false }}
103
  ];
104

    
105
  @Output() toggleView: EventEmitter<any> = new EventEmitter();
106
  @Input() public toggle: boolean = true;
107

    
108
  ngOnInit() {
109
    this.communitySearchUtils.keyword = "";
110

    
111
    this.fundersCtrl = this._fb.array([]);
112
    this.filterForm = this._fb.group({
113
      keyword: [''],
114
      funder: this.fundersCtrl,
115
      sort: this._fb.control(this.sortOptions[0].value)
116
    });
117

    
118
    this.subscriptions.push(this.filterForm.get('keyword').valueChanges.subscribe(value => {
119
      this.searchText = new RegExp(value, 'i');
120
      this.page = 1;
121
      this.applyFilters();
122
    }));
123

    
124
    this.subscriptions.push(this.filterForm.get('funder').valueChanges.subscribe(value => {
125
      console.log("funder changed: ",value);
126
      this.page = 1;
127
      this.applyFilters();
128
    }));
129

    
130
    this.subscriptions.push(this.filterForm.get('sort').valueChanges.subscribe(value => {
131
      this.page = 1;
132
      this.sort();
133
    }));
134

    
135
    this.subscriptions.push(this.communityService.getCommunityAsObservable().subscribe(community => {
136
      if(community) {
137
        this.portal = community.communityId;
138
        this.name = community.shortTitle;
139
        this.communityUrl = "https://beta."+this.portal+".openaire.eu";
140

    
141
        this.keyword = '';
142
        this._getCommunityProjects();
143
        // this.initPreviewCommunityProjects();
144
      }
145
    }));
146
  }
147

    
148
  constructor(private route: ActivatedRoute, private _router: Router,
149
              private _fb: FormBuilder,
150
              private communityService: CommunityService,
151
              private _manageCommunityProjectsService: ManageCommunityProjectsService,
152
              private _searchCommunityProjectsService: SearchCommunityProjectsService) {
153
    this.errorCodes = new ErrorCodes();
154
    this.communitySearchUtils.status = this.errorCodes.LOADING;
155
  }
156

    
157
  public ngOnDestroy() {
158
    this.subscriptions.forEach(sub => {
159
      if (sub instanceof Subscriber) {
160
        sub.unsubscribe();
161
      }
162
    });
163
  }
164

    
165
  // changekeyword() {
166
  //   if (this.filterForm.get("keyword").value.length >= 3 || this.filterForm.get("keyword").value.length == 0) {
167
  //     this.searchTermStream.next(this.filterForm.get("keyword").value);
168
  //   }
169
  // }
170

    
171
  public inCommunity(result: any): any {
172
    let found = false;
173
    for(let project of this.communityProjects) {
174
      if(project.opeaireId == result.id) {
175
        return true;
176
      } else if(result['title'].name.search("("+project.grantId+")") != -1 && result.funderShortname == project.funder) {
177
        return true;
178
      }
179
    }
180
    return found;
181

    
182
  }
183

    
184
  totalPages(): number {
185
      let totalPages:any = this.communitySearchUtils.totalResults/(this.rowsOnPage);
186
      if(!(Number.isInteger(totalPages))) {
187
          totalPages = (parseInt(totalPages, 10) + 1);
188
      }
189
      return totalPages;
190
  }
191

    
192
  public confirmedDeleteProject(data : any) {
193
    if(!Session.isLoggedIn()){
194
      this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
195
    } else {
196
      this.subscriptions.push(this._manageCommunityProjectsService.removeProject(this.properties, this.portal, this.selectedCommunityProject.id).subscribe(
197
        data => {
198
          let index = this.communityProjects.indexOf(this.selectedCommunityProject);
199
          this.communityProjects.splice(index, 1);
200

    
201
          this.applyFilters();
202

    
203
          // index = this.previewCommunityProjects.indexOf(this.selectedCommunityProject);
204
          // this.previewCommunityProjects.splice(index, 1);
205
          //
206
          // console.log("after previewCommunityProjects: ",this.previewCommunityProjects);
207

    
208
          UIkit.notification('Project successfully removed!', {
209
            status: 'success',
210
            timeout: 6000,
211
            pos: 'bottom-right'
212
          });
213

    
214
          this.communityProjectsChanged.emit({
215
            value: this.communityProjects,
216
          });
217

    
218
          this.communitySearchUtils.totalResults--;
219
          this.communitySearchUtils.page=1;
220
          // this.createFunderFilter();
221
        },
222
        err => {
223
          this.handleError('An error has been occurred. Try again later!');
224
          console.error(err);
225
        },
226
        () => {
227

    
228
        }
229
      ));
230
    }
231
  }
232

    
233
  public removeProject(communityProject: any) {
234
    if(!Session.isLoggedIn()){
235
      this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
236
    } else {
237
      this.selectedCommunityProject = communityProject;
238
      this.alertModalDeleteCommunity.cancelButton = true;
239
      this.alertModalDeleteCommunity.okButton = true;
240
      this.alertModalDeleteCommunity.alertTitle = "Remove project?";
241
      let title = "";
242
      if(communityProject.name) {
243
        title = communityProject.name;
244
      }
245
      if(communityProject.name && communityProject.acronym) {
246
        title += " (";
247
      }
248
      if(communityProject.acronym) {
249
        title += communityProject.acronym;
250
      }
251
      if(communityProject.name && communityProject.acronym) {
252
        title += ")";
253
      }
254
      this.alertModalDeleteCommunity.message = "Project";
255
      if(title) {
256
        this.alertModalDeleteCommunity.message += " '"+title+"' ";
257
      }
258
      this.alertModalDeleteCommunity.message += "will be removed from your community. Are you sure?";
259
      this.alertModalDeleteCommunity.okButtonText = "Yes";
260
      this.alertModalDeleteCommunity.open();
261
    }
262
  }
263

    
264
  public initPreviewCommunityProjects() {
265
    this.previewCommunityProjects = this.communityProjects;
266
    this.sort();
267

    
268
    this.communitySearchUtils.totalResults = this.communityProjects.length;
269
    this.communitySearchUtils.status = this.errorCodes.DONE;
270

    
271
    this.disableForms = false;
272
    this.createFunderFilter();
273
  }
274

    
275
  public _getCommunityProjects(){
276
    if(!Session.isLoggedIn()){
277
      this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
278
    } else {
279
      this.communitySearchUtils.status = this.errorCodes.LOADING;
280
      this.disableForms = true;
281
      this.communityProjects = [];
282
      this.communitySearchUtils.totalResults = 0;
283
      this.communitySearchUtils.page=1;
284
      this.communitySearchUtils.keyword = "";
285
      this.selectedFunder = "";
286

    
287
      this.subscriptions.push(this._searchCommunityProjectsService.searchProjects(this.properties, this.portal).subscribe(
288
          data => {
289
            this.communityProjects = data;
290
            this.previewCommunityProjects = this.communityProjects;
291
            this.sort();
292

    
293
            this.communitySearchUtils.totalResults = data.length;
294
            this.communitySearchUtils.status = this.errorCodes.DONE;
295
            // if(this.communitySearchUtils.totalResults == 0 ){
296
            //   this.communitySearchUtils.status = this.errorCodes.NONE;
297
            // }
298
            this.disableForms = false;
299

    
300
            this.communityProjectsChanged.emit({
301
                value: this.communityProjects,
302
            });
303

    
304
            this.createFunderFilter();
305

    
306
            this.showLoading = false;
307
          },
308
          err => {
309
            console.error(err);
310
             //TODO check erros (service not available, bad request)
311

    
312
            if(err.status == '404') {
313
              this.communitySearchUtils.status = this.errorCodes.NOT_FOUND;
314
            } else if(err.status == '500') {
315
              this.communitySearchUtils.status = this.errorCodes.ERROR;
316
            } else {
317
              this.communitySearchUtils.status = this.errorCodes.NOT_AVAILABLE;
318
            }
319

    
320
            this.disableForms = false;
321
            this.showLoading = false;
322
          }
323
      ));
324
    }
325
  }
326

    
327
  public createFunderFilter(): Set<String> {
328
    this.funders = new Set<string>();
329
    this.allOptions = [];
330
    let i;
331
    for(i=0; i<this.communityProjects.length; i++) {
332
      let funder = this.communityProjects[i].funder;
333
      if(funder && !this.funders.has(funder)) {
334
        this.funders.add(funder);
335
        this.allOptions.push({label: funder, value: {id:funder, label: funder}});
336
      }
337
    }
338
    return this.funders;
339
  }
340

    
341
  public updatePage($event) {
342
    this.page = $event.value;
343
  }
344

    
345
  addNew() {
346
    this.toggleView.emit(null);
347
  }
348

    
349
  public applyFilters() {
350
    // this.page = 1;
351

    
352
    this.previewCommunityProjects = this.communityProjects.filter(project => {
353
      let return_value: boolean = (this.filterCommunityProjectByKeyword(project) && this.filterCommunityProjectByFunder(project));
354
      return return_value;
355
    });
356

    
357
    // check paging here!!!
358
    if(this.previewCommunityProjects.slice((this.page - 1)*this.pageSize, this.page*this.pageSize).length == 0) {
359
      this.page = 1;
360
    }
361

    
362
    this.sort();
363
  }
364

    
365
  public filterCommunityProjectByKeyword(project): boolean {
366
    const textFlag = this.searchText.toString().toLowerCase() === ''
367
            || (project.name.toLowerCase() || project.acronym || project.grantId || project.funder).match(this.searchText) != null;
368
    return textFlag;
369
  }
370

    
371
  public filterCommunityProjectByFunder(project): boolean {
372
    if(this.fundersCtrl.getRawValue().length == 0) {
373
      return true;
374
    }
375
    for (let funder of this.fundersCtrl.getRawValue()) {
376
      if (project.funder.toLowerCase().indexOf(funder.label.toLowerCase()) != -1) {
377
        return true;
378
      }
379
    }
380
    return false;
381
  }
382

    
383
  private sort() {
384
    // this.page = 1;
385
    let sortOption: { sort: string, descending: boolean } = this.filterForm.get('sort').value;
386

    
387
    this.previewCommunityProjects.sort((left, right): number => {
388
      if (sortOption.sort == "title") {
389
        if((left.name+left.acronym) > (right.name+right.acronym)) {
390
          return sortOption.descending ? -1 : 1;
391
        } else if((left.name+left.acronym) < (right.name+right.acronym)) {
392
          return sortOption.descending ? 1 : -1;
393
        }
394
      } else if (sortOption.sort == "grant") {
395
        if(left.grantId > right.grantId) {
396
          return sortOption.descending ? -1 : 1;
397
        } else if(left.grantId < right.grantId) {
398
          return sortOption.descending ? 1 : -1;
399
        }
400
      } else if (sortOption.sort == "funder") {
401
        if(left.funder > right.funder) {
402
          return sortOption.descending ? -1 : 1;
403
        } else if(left.funder < right.funder) {
404
          return sortOption.descending ? 1 : -1;
405
        }
406
      }
407

    
408
      return 0;
409
    });
410
  }
411

    
412
  public onSearchClose() {
413
    this.communitySearchUtils.keyword = this.filterForm.get('keyword').value;
414
  }
415

    
416
  public resetInput() {
417
    this.communitySearchUtils.keyword = null;
418
    this.searchInputComponent.reset()
419
  }
420

    
421
  handleError(message: string) {
422
    UIkit.notification(message, {
423
      status: 'danger',
424
      timeout: 6000,
425
      pos: 'bottom-right'
426
    });
427
  }
428
}
(6-6/6)