Project

General

Profile

1
import {Component, EventEmitter, Input, OnInit, Output, ViewChild} from '@angular/core';
2
import {ActivatedRoute, Router} from "@angular/router";
3
import {Subscriber} from 'rxjs';
4

    
5
import {ErrorCodes} from '../../openaireLibrary/utils/properties/errorCodes';
6
import {SearchUtilsClass} from '../../openaireLibrary/searchPages/searchUtils/searchUtils.class';
7
import {EnvProperties} from '../../openaireLibrary/utils/properties/env-properties';
8
import {ManageCommunityContentProvidersService} from '../../services/manageContentProviders.service';
9
import {SearchCommunityDataprovidersService} from '../../openaireLibrary/connect/contentProviders/searchDataproviders.service';
10
import {RouterHelper} from '../../openaireLibrary/utils/routerHelper.class';
11

    
12
import {Session} from '../../openaireLibrary/login/utils/helper.class';
13
import {LoginErrorCodes} from '../../openaireLibrary/login/utils/guardHelper.class';
14
import {Criteria, SelectionCriteria} from '../../openaireLibrary/utils/entities/contentProvider';
15
import {properties} from "../../../environments/environment";
16
import {SearchInputComponent} from "../../openaireLibrary/sharedComponents/search-input/search-input.component";
17
import {FormBuilder, FormGroup} from "@angular/forms";
18
import {Option} from "../../openaireLibrary/sharedComponents/input/input.component";
19
import {CommunityService} from "../../openaireLibrary/connect/community/community.service";
20
import {CriteriaUtils} from "./criteria-utils";
21

    
22
declare var UIkit;
23

    
24
@Component({
25
  selector: 'remove-content-providers',
26
  templateUrl: './remove-content-providers.component.html'
27
})
28
export class RemoveContentProvidersComponent implements OnInit {
29
  public portal: string;
30
  public name: string;
31
  public routerHelper: RouterHelper = new RouterHelper();
32
  public contentProviderUrl = "https://" + ((properties.environment == "beta" || properties.environment == "development") ? "beta." : "") + "explore.openaire.eu" + properties.searchLinkToDataProvider;
33
  public previewCommunityContentProviders = [];
34
  public communitySearchUtils: SearchUtilsClass = new SearchUtilsClass();
35
  public errorCodes: ErrorCodes;
36
  @Input() public showLoading: boolean = true;
37
  @Input() public communityContentProviders = [];
38
  @Output() communityContentProvidersChanged = new EventEmitter();
39
  private properties: EnvProperties = properties;
40
  private subscriptions: any[] = [];
41
  private selectedCommunityContentProvider: any;
42
  @ViewChild('AlertModalDeleteCommunity') alertModalDeleteCommunity;
43
  /** Criteria */
44
  private fields = CriteriaUtils.fields;
45
  private verbs = CriteriaUtils.verbs;
46
  /** Paging */
47
  page: number = 1;
48
  resultsPerPage: number = properties.resultsPerPage;
49
  /** Search */
50
  @ViewChild('searchInputComponent') searchInputComponent: SearchInputComponent;
51
  filterForm: FormGroup;
52
  private searchText: RegExp = new RegExp('');
53
  public keyword: string = '';
54
  sortOptions: Option[] = [
55
    {label: "Name ", value: {sort: "name", descending: false}},
56
    {label: "Official Name ", value: {sort: "officialname", descending: false}}
57
  ];
58

    
59
  @Output() toggleView: EventEmitter<any> = new EventEmitter();
60
  @Input() public toggle: boolean = true;
61

    
62
  constructor(private route: ActivatedRoute, private _router: Router,
63
              private _fb: FormBuilder, private communityService: CommunityService,
64
              private _manageCommunityContentProvidersService: ManageCommunityContentProvidersService,
65
              private _searchCommunityContentProvidersService: SearchCommunityDataprovidersService) {
66
    this.errorCodes = new ErrorCodes();
67
    this.communitySearchUtils.status = this.errorCodes.LOADING;
68
  }
69

    
70
  ngOnInit() {
71
    this.communitySearchUtils.keyword = "";
72

    
73
    this.filterForm = this._fb.group({
74
      keyword: [''],
75
      // sort: this._fb.control(this.sortOptions[0].value)
76
    });
77

    
78
    this.subscriptions.push(this.filterForm.get('keyword').valueChanges.subscribe(value => {
79
      this.searchText = new RegExp(value, 'i');
80
      this.page = 1;
81
      this.applyFilters();
82
    }));
83

    
84
    // this.subscriptions.push(this.filterForm.get('sort').valueChanges.subscribe(value => {
85
    //   this.page = 1;
86
    //   this.sort();
87
    // }));
88

    
89
    this.subscriptions.push(this.communityService.getCommunityAsObservable().subscribe(community => {
90
      if (community) {
91
        this.portal = community.communityId;
92
        this.name = community.shortTitle;
93
        this.contentProviderUrl = "https://"
94
          + ((this.properties.environment == "beta" || this.properties.environment == "development") ? "beta." : "")
95
          + this.portal + ".openaire.eu" + this.properties.searchLinkToDataProvider;
96

    
97
        this.keyword = '';
98
        this._getCommunityContentProviders();
99
      }
100
    }));
101
  }
102

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

    
111
  public getCriteriaLabel(selectionCriteria: SelectionCriteria): string {
112
    if (selectionCriteria && selectionCriteria.criteria.length > 0) {
113
      return (selectionCriteria.criteria.length === 1) ? '1 criterion' : (selectionCriteria.criteria.length + ' criteria')
114
    } else {
115
      return 'no criteria';
116
    }
117
  }
118

    
119
  // filterData(row: any, query: string) {
120
  //   let returnValue: boolean = false;
121
  //
122
  //   if(query) {
123
  //     for(var i=0; i <2; i++){
124
  //       var r= this.filterQuery(row[i], query);
125
  //       if(r) {
126
  //         returnValue = true;
127
  //         break;
128
  //       }
129
  //     }
130
  //
131
  //     if(!returnValue) {
132
  //       return false;
133
  //     }
134
  //   }
135
  //
136
  //   return true;
137
  // }
138
  //
139
  // filterQuery(data, query){
140
  //   if(data.toLowerCase().indexOf(query.toLowerCase()) > -1){
141
  //     return true;
142
  //   }else{
143
  //     return false;
144
  //   }
145
  // }
146

    
147
  public inCommunity(result: any): any {
148
    let found = false;
149
    for (let contentProvider of this.communityContentProviders) {
150
      if (contentProvider.opeaireId == result.id) {
151
        return true;
152
      }
153
    }
154
    return found;
155

    
156
  }
157

    
158
  totalPages(): number {
159
    let totalPages: any = this.communitySearchUtils.totalResults / (this.resultsPerPage);
160
    if (!(Number.isInteger(totalPages))) {
161
      totalPages = (parseInt(totalPages, 10) + 1);
162
    }
163
    return totalPages;
164
  }
165
  
166
  getFiltersAsText(criteria: Criteria[]): string {
167
    let text = criteria.slice(0,3).map((criterion, index) => (index + 1) + ". " + criterion.constraint.map(constraint => {
168
      let field = this.fields.find(field => field.value === constraint.field).label;
169
      let matchCase = false;
170
      if(!constraint.verb.includes('_caseinsensitive')) {
171
        matchCase = true;
172
      }
173
      let verb = this.verbs.find(verb => verb.value === constraint.verb.replace("_caseinsensitive", "")).label;
174
      let value = '"' + constraint.value + '"' + (matchCase?" (Match case)":"");
175
      return field + " " + verb + " " + value;
176
    }).join(" <b>and</b> "));
177
    return text.join("<br>");
178
  }
179

    
180
  // goTo(page:number = 1){
181
  //     this.communitySearchUtils.page=page;
182
  //
183
  //     var table = $('#dpTable').DataTable();
184
  //     table.page( page - 1  ).draw( false );
185
  //
186
  //     var info = table.page.info();
187
  //     this.communitySearchUtils.totalResults = info.recordsDisplay;
188
  // }
189

    
190
  public confirmedDeleteContentProvider(data: any) {
191
    if (!Session.isLoggedIn()) {
192
      this._router.navigate(['/user-info'], {
193
        queryParams: {
194
          "errorCode": LoginErrorCodes.NOT_VALID,
195
          "redirectUrl": this._router.url
196
        }
197
      });
198
    } else {
199
      this.subscriptions.push(this._manageCommunityContentProvidersService.removeContentProvider(this.properties, this.portal, this.selectedCommunityContentProvider.id).subscribe(
200
        data => {
201
          let index = this.communityContentProviders.indexOf(this.selectedCommunityContentProvider);
202
          this.communityContentProviders.splice(index, 1);
203

    
204
          this.applyFilters();
205

    
206
          UIkit.notification('Content Provider successfully removed!', {
207
            status: 'success',
208
            timeout: 6000,
209
            pos: 'bottom-right'
210
          });
211

    
212
          this.communityContentProvidersChanged.emit({
213
            value: this.communityContentProviders,
214
          });
215

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

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

    
263
  public _getCommunityContentProviders() {
264
    if (!Session.isLoggedIn()) {
265
      this._router.navigate(['/user-info'], {
266
        queryParams: {
267
          "errorCode": LoginErrorCodes.NOT_VALID,
268
          "redirectUrl": this._router.url
269
        }
270
      });
271
    } else {
272
      this.communitySearchUtils.status = this.errorCodes.LOADING;
273
      this.communityContentProviders = [];
274
      this.communitySearchUtils.totalResults = 0;
275
      this.communitySearchUtils.page = 1;
276
      this.communitySearchUtils.keyword = "";
277

    
278
      this.subscriptions.push(this._searchCommunityContentProvidersService.searchDataproviders(this.properties, this.portal).subscribe(
279
        data => {
280
          this.communityContentProviders = data;
281
          this.previewCommunityContentProviders = this.communityContentProviders;
282
          // this.sort();
283

    
284
          this.communitySearchUtils.totalResults = data.length;
285
          this.communitySearchUtils.status = this.errorCodes.DONE;
286

    
287
          this.communityContentProvidersChanged.emit({
288
            value: this.communityContentProviders,
289
          });
290

    
291
          this.showLoading = false;
292
        },
293
        err => {
294
          console.error(err);
295
          //TODO check erros (service not available, bad request)
296

    
297
          if (err.status == '404') {
298
            this.communitySearchUtils.status = this.errorCodes.NOT_FOUND;
299
          } else if (err.status == '500') {
300
            this.communitySearchUtils.status = this.errorCodes.ERROR;
301
          } else {
302
            this.communitySearchUtils.status = this.errorCodes.NOT_AVAILABLE;
303
          }
304

    
305
          this.showLoading = false;
306
        }
307
      ));
308
    }
309
  }
310

    
311
  public updatePage($event) {
312
    this.page = $event.value;
313
  }
314

    
315
  addNew() {
316
    this.toggleView.emit(null);
317
  }
318

    
319
  public applyFilters() {
320
    this.previewCommunityContentProviders = this.communityContentProviders.filter(contentProvider => {
321
      return this.filterCommunityContentProviderByKeyword(contentProvider);
322
    });
323

    
324
    // check paging here!!!
325
    if (this.previewCommunityContentProviders.slice((this.page - 1) * this.resultsPerPage, this.page * this.resultsPerPage).length == 0) {
326
      this.page = 1;
327
    }
328

    
329
    // this.sort();
330
  }
331

    
332
  public filterCommunityContentProviderByKeyword(contentProvider): boolean {
333
    const textFlag = this.searchText.toString() === ''
334
      || (contentProvider.name + " " + contentProvider.officialname).match(this.searchText) != null;
335
    return textFlag;
336
  }
337

    
338
  private sort() {
339
    let sortOption: { sort: string, descending: boolean } = this.filterForm.get('sort').value;
340

    
341
    this.previewCommunityContentProviders.sort((left, right): number => {
342
      if (sortOption.sort == "name") {
343
        if (left.name > right.name) {
344
          return sortOption.descending ? -1 : 1;
345
        } else if (left.name < right.name) {
346
          return sortOption.descending ? 1 : -1;
347
        }
348
      } else if (sortOption.sort == "officialname") {
349
        if (left.officialname > right.officialname) {
350
          return sortOption.descending ? -1 : 1;
351
        } else if (left.officialname < right.officialname) {
352
          return sortOption.descending ? 1 : -1;
353
        }
354
      }
355

    
356
      return 0;
357
    });
358
  }
359

    
360
  public onSearchClose() {
361
    this.communitySearchUtils.keyword = this.filterForm.get('keyword').value;
362
  }
363

    
364
  public resetInput() {
365
    this.communitySearchUtils.keyword = null;
366
    this.searchInputComponent.reset()
367
  }
368

    
369
  handleError(message: string) {
370
    UIkit.notification(message, {
371
      status: 'danger',
372
      timeout: 6000,
373
      pos: 'bottom-right'
374
    });
375
  }
376

    
377
  goToCriteria(openaireId: string) {
378
    this._router.navigate([openaireId], {
379
      queryParams: {
380
        // community: this.portal,
381
        // provider: openaireId
382
      },
383
      relativeTo: this.route
384
    })
385
  }
386
}
(7-7/7)