Project

General

Profile

1
import {Component, EventEmitter, Input, OnInit, Output, ViewChild} from '@angular/core';
2
import {ActivatedRoute, Router} from "@angular/router";
3
import {SearchResult} from '../../openaireLibrary/utils/entities/searchResult';
4
import {ErrorCodes} from '../../openaireLibrary/utils/properties/errorCodes';
5
import {SearchUtilsClass} from '../../openaireLibrary/searchPages/searchUtils/searchUtils.class';
6
import {EnvProperties} from '../../openaireLibrary/utils/properties/env-properties';
7
import {SearchProjectsService} from '../../openaireLibrary/services/searchProjects.service';
8
import {RouterHelper} from '../../openaireLibrary/utils/routerHelper.class';
9
import {StringUtils} from '../../openaireLibrary/utils/string-utils.class';
10
import {ManageCommunityProjectsService} from '../../services/manageProjects.service';
11

    
12
import {Session} from '../../openaireLibrary/login/utils/helper.class';
13
import {LoginErrorCodes} from '../../openaireLibrary/login/utils/guardHelper.class';
14
import {properties} from "../../../environments/environment";
15
import {Subscriber} from "rxjs";
16
import {FormBuilder, FormGroup} from "@angular/forms";
17
import {Option} from "../../openaireLibrary/sharedComponents/input/input.component";
18
import {debounceTime, distinctUntilChanged} from "rxjs/operators";
19
import {ResultPreview} from "../../openaireLibrary/utils/result-preview/result-preview";
20
import {SearchInputComponent} from "../../openaireLibrary/sharedComponents/search-input/search-input.component";
21

    
22
declare var UIkit;
23

    
24
@Component({
25
  selector: 'add-projects',
26
  templateUrl: './add-projects.component.html',
27
})
28

    
29
export class AddProjectsComponent implements OnInit {
30
  private subscriptions: any[] = [];
31
  public subResults: any;
32

    
33
  private community: string = '';
34

    
35
  public routerHelper: RouterHelper = new RouterHelper();
36
  public properties: EnvProperties = properties;
37
  public errorCodes: ErrorCodes;
38
  public openaireSearchUtils: SearchUtilsClass = new SearchUtilsClass();
39
  @Output() communityProjectsChanged = new EventEmitter();
40
  @Input() communityProjects = [];
41
  public openaireProjects = [];
42
  public queryParameters: string = "";
43

    
44
  // public pagingLimit: number = properties.pagingLimit;
45
  public resultsPerPage: number = properties.resultsPerPage;
46
  public selectedFunderId: string = "";
47

    
48
  filterForm: FormGroup;
49
  allOptions: Option[] = [];
50
  @ViewChild('searchInputComponent') searchInputComponent: SearchInputComponent;
51

    
52
  private projectUrl: string = "https://" + ((properties.environment == "beta" || properties.environment == "development") ? "beta." : "") + "explore.openaire.eu" + properties.searchLinkToProject;
53
  public body: string = "Send from page";
54

    
55
  @Output() toggleView: EventEmitter<any> = new EventEmitter();
56

    
57
  constructor(private route: ActivatedRoute, private _router: Router, private _searchProjectsService: SearchProjectsService,
58
              private _manageCommunityProjectsService: ManageCommunityProjectsService,
59
              private _fb: FormBuilder) {
60
    this.errorCodes = new ErrorCodes();
61
    this.openaireSearchUtils.status = this.errorCodes.LOADING;
62
  }
63

    
64
  ngOnInit() {
65
    this.subscriptions.push(this.route.params.subscribe(params => {
66
      this.openaireSearchUtils.status = this.errorCodes.LOADING;
67

    
68
      this.community = params['community'];
69
      // this.projectUrl = "https://" + ((this.properties.environment == "beta" || this.properties.environment == "development") ? "beta." : "")
70
      //   + this.community + ".openaire.eu" + this.properties.searchLinkToProject;
71

    
72
      this.getFunders();
73
      this._getOpenaireProjects("", 1, this.resultsPerPage);
74

    
75
      this.body = "[Please write your message here]";
76
      this.body = StringUtils.URIEncode(this.body);
77
    }));
78

    
79
    this.openaireSearchUtils.keyword = "";
80

    
81
    this.filterForm = this._fb.group({
82
      keyword: [''],
83
      funder: []
84
    });
85

    
86
    this.subscriptions.push(this.filterForm.get('keyword').valueChanges
87
      .pipe(debounceTime(1000), distinctUntilChanged())
88
      .subscribe(value => {
89
        this.keywordChanged(value);
90
      }));
91

    
92
    this.subscriptions.push(this.filterForm.get('funder').valueChanges
93
      .pipe(debounceTime(1000), distinctUntilChanged())
94
      .subscribe(value => {
95
        // console.log("value: ",value);
96
        if (value == null) {
97
          // console.log("will be called funder changed: null");
98
          this.funderChanged("", "");
99
        } else if (value && value.id != undefined && value.id != this.selectedFunderId) {
100
          // console.log("will be called funder changed: name="+value.label+", id="+value.id);
101
          this.funderChanged(value.id, value.label);
102
        }
103
      }));
104
  }
105

    
106
  public ngOnDestroy() {
107
    this.subscriptions.forEach(sub => {
108
      if (sub instanceof Subscriber) {
109
        sub.unsubscribe();
110
      }
111
    });
112

    
113
    if (this.subResults) {
114
      this.subResults.unsubscribe();
115
    }
116
  }
117

    
118
  public addProject(project: SearchResult) {
119
    if (!Session.isLoggedIn()) {
120
      this._router.navigate(['/user-info'], {
121
        queryParams: {
122
          "errorCode": LoginErrorCodes.NOT_VALID,
123
          "redirectUrl": this._router.url
124
        }
125
      });
126
    } else {
127
      this.subscriptions.push(this._manageCommunityProjectsService.addProject(this.properties, this.community, project).subscribe(
128
        data => {
129
          this.communityProjects.push(data);
130
          UIkit.notification('Project successfully added!', {
131
            status: 'success',
132
            timeout: 6000,
133
            pos: 'bottom-right'
134
          });
135
          this.communityProjectsChanged.emit({
136
            value: this.communityProjects,
137
          });
138
        },
139
        err => {
140
          this.handleError('An error has been occurred. Try again later!');
141
          console.error(err.status);
142
        }
143
      ));
144
    }
145
  }
146

    
147
  public removeProject(project: any) {
148
    if (!Session.isLoggedIn()) {
149
      this._router.navigate(['/user-info'], {
150
        queryParams: {
151
          "errorCode": LoginErrorCodes.NOT_VALID,
152
          "redirectUrl": this._router.url
153
        }
154
      });
155
    } else {
156
      let communityProject = this.getCommunityProject(project);
157
      let projectId: string = communityProject['id'];
158
      this.subscriptions.push(this._manageCommunityProjectsService.removeProject(this.properties, this.community, projectId).subscribe(
159
        data => {
160
          let index = this.communityProjects.indexOf(communityProject);
161
          this.communityProjects.splice(index, 1);
162
          UIkit.notification('Project successfully removed!', {
163
            status: 'success',
164
            timeout: 6000,
165
            pos: 'bottom-right'
166
          });
167
          this.communityProjectsChanged.emit({
168
            value: this.communityProjects,
169
          });
170
        },
171
        err => {
172
          this.handleError('An error has been occurred. Try again later!');
173
          console.error(err);
174
        }
175
      ));
176
    }
177
  }
178

    
179
  public getCommunityProject(project: any): string {
180
    let index: number = 0;
181
    for (let communityProject of this.communityProjects) {
182
      if (communityProject.openaireId == project.id ||
183
        (project.code == communityProject.grantId && project.funderShortname == communityProject.funder)) {
184
        return communityProject;
185
      }
186
      index++;
187
    }
188
    return "";
189
  }
190

    
191
  getFunders() {
192
    if (!Session.isLoggedIn()) {
193
      this._router.navigate(['/user-info'], {
194
        queryParams: {
195
          "errorCode": LoginErrorCodes.NOT_VALID,
196
          "redirectUrl": this._router.url
197
        }
198
      });
199
    } else {
200
      this.subscriptions.push(this._searchProjectsService.getFunders(this.properties).subscribe(
201
        data => {
202
          let funders = data[1];
203
          this.allOptions = [];
204
          let i;
205
          for (i = 0; i < funders.length; i++) {
206
            let funder = funders[i];
207
            if (funder && funder['id']) {
208
              this.allOptions.push({label: funder['name'], value: {id: funder['id'], label: funder['name']}});
209
            }
210
          }
211
        },
212
        err => console.error("Server error fetching funders: ", err)
213
      ));
214
    }
215
  }
216

    
217
  public getResultPreview(result: SearchResult): ResultPreview {
218
    return ResultPreview.searchResultConvert(result, "project");
219
  }
220

    
221
  private _getOpenaireProjects(parameters: string, page: number, size: number) {
222
    if (!Session.isLoggedIn()) {
223
      this._router.navigate(['/user-info'], {
224
        queryParams: {
225
          "errorCode": LoginErrorCodes.NOT_VALID,
226
          "redirectUrl": this._router.url
227
        }
228
      });
229
    } else {
230
      // if (page > this.pagingLimit) {
231
      //   size = 0;
232
      // }
233

    
234
      if (this.openaireSearchUtils.status == this.errorCodes.LOADING) {
235
        this.openaireSearchUtils.status = this.errorCodes.LOADING;
236

    
237
        this.openaireProjects = [];
238
        this.openaireSearchUtils.totalResults = 0;
239

    
240
        if (this.subResults) {
241
          this.subResults.unsubscribe();
242
        }
243
        this.subResults = this._searchProjectsService.searchProjects(parameters, null, page, size, [], this.properties).subscribe(
244
          data => {
245
            this.openaireSearchUtils.totalResults = data[0];
246
            this.openaireProjects = data[1];
247

    
248
            //this.searchPage.checkSelectedFilters(this.filters);
249
            this.openaireSearchUtils.status = this.errorCodes.DONE;
250
            if (this.openaireSearchUtils.totalResults == 0) {
251
              this.openaireSearchUtils.status = this.errorCodes.NONE;
252
            }
253

    
254
            // if (this.openaireSearchUtils.status == this.errorCodes.DONE) {
255
            //   // Page out of limit!!!
256
            //   let totalPages: any = this.openaireSearchUtils.totalResults / (this.openaireSearchUtils.size);
257
            //   if (!(Number.isInteger(totalPages))) {
258
            //     totalPages = (parseInt(totalPages, 10) + 1);
259
            //   }
260
            //   if (totalPages < page) {
261
            //     this.openaireSearchUtils.totalResults = 0;
262
            //     this.openaireSearchUtils.status = this.errorCodes.OUT_OF_BOUND;
263
            //   }
264
            // }
265
          },
266
          err => {
267
            console.error(err);
268
            //TODO check erros (service not available, bad request)
269
            if (err.status == '404') {
270
              this.openaireSearchUtils.status = this.errorCodes.NOT_FOUND;
271
            } else if (err.status == '500') {
272
              this.openaireSearchUtils.status = this.errorCodes.ERROR;
273
            } else {
274
              this.openaireSearchUtils.status = this.errorCodes.NOT_AVAILABLE;
275
            }
276
          }
277
        );
278
      }
279
    }
280
  }
281

    
282
  totalPages(): number {
283
    let totalPages: any = this.openaireSearchUtils.totalResults / (this.resultsPerPage);
284
    if (!(Number.isInteger(totalPages))) {
285
      totalPages = (parseInt(totalPages, 10) + 1);
286
    }
287
    return totalPages;
288
  }
289

    
290
  keywordChanged(keyword) {
291
    this.openaireSearchUtils.keyword = keyword;
292
    this.buildQueryParameters();
293
    this.goTo(1);
294
  }
295

    
296
  funderChanged(funderId: string, funderName: string) {
297
    this.selectedFunderId = funderId;
298

    
299
    this.buildQueryParameters();
300
    this.goTo(1);
301
  }
302

    
303
  buildQueryParameters() {
304
    this.queryParameters = "";
305

    
306
    if (this.openaireSearchUtils.keyword) {
307
      this.queryParameters = "q=" + StringUtils.URIEncode(this.openaireSearchUtils.keyword);
308
    }
309

    
310
    if (this.selectedFunderId) {
311
      this.queryParameters += this.queryParameters ? "&" : "";
312
      this.queryParameters += "fq=funder exact " + '"' + StringUtils.URIEncode(this.selectedFunderId) + '"';
313
    }
314
  }
315

    
316
  goTo(page: number = 1) {
317
    this.openaireSearchUtils.page = page;
318
    this.openaireSearchUtils.status = this.errorCodes.LOADING;
319
    this._getOpenaireProjects(this.queryParameters, page, this.resultsPerPage);
320
  }
321

    
322
  back() {
323
    this.toggleView.emit(null);
324
  }
325

    
326
  public onSearchClose() {
327
    this.openaireSearchUtils.keyword = this.filterForm.get('keyword').value;
328
  }
329

    
330
  public resetInput() {
331
    this.openaireSearchUtils.keyword = null;
332
    this.searchInputComponent.reset()
333
  }
334

    
335
  handleError(message: string) {
336
    UIkit.notification(message, {
337
      status: 'danger',
338
      timeout: 6000,
339
      pos: 'bottom-right'
340
    });
341
  }
342
}
(2-2/6)