Project

General

Profile

1 61381 k.triantaf
import {ChangeDetectorRef, Component, ElementRef, Input, Output, ViewChild} from '@angular/core';
2
import {Location} from '@angular/common';
3
import {ActivatedRoute, Router} from '@angular/router';
4
import {Meta, Title} from '@angular/platform-browser';
5
6
import {AdvancedField, Filter, Value} from './searchHelperClasses.class';
7
import {SearchCustomFilter, SearchUtilsClass} from './searchUtils.class';
8
import {ModalLoading} from '../../utils/modal/loading.component';
9
import {Dates, Identifier, StringUtils} from '../../utils/string-utils.class';
10
import {ErrorCodes} from '../../utils/properties/errorCodes';
11
import {RouterHelper} from '../../utils/routerHelper.class';
12
13
import {PiwikService} from '../../utils/piwik/piwik.service';
14
import {EnvProperties} from '../../utils/properties/env-properties';
15
import {SEOService} from '../../sharedComponents/SEO/SEO.service';
16
import {HelperService} from "../../utils/helper/helper.service";
17
import {SearchFields} from "../../utils/properties/searchFields";
18
import {RefineResultsUtils} from "../../services/servicesUtils/refineResults.class";
19
import {RangeFilter} from "../../utils/rangeFilter/rangeFilterHelperClasses.class";
20
import {ZenodoInformationClass} from "../../deposit/utils/zenodoInformation.class";
21
import {Breadcrumb} from "../../utils/breadcrumbs/breadcrumbs.component";
22
import {HelperFunctions} from "../../utils/HelperFunctions.class";
23
import {properties} from "../../../../environments/environment";
24
import {AlertModal} from "../../utils/modal/alert";
25
import {Subscriber} from "rxjs";
26
import {IndexInfoService} from "../../utils/indexInfo.service";
27
28
declare var UIkit: any;
29
30
@Component({
31
  selector: 'new-search-page',
32
  templateUrl: 'newSearchPage.component.html'
33
})
34
export class NewSearchPageComponent {
35
  @ViewChild('offcanvas_element') offcanvasElement: ElementRef;
36
  @Input() piwikSiteId = null;
37
  @Input() hasPrefix: boolean = true;
38
  @Input() prefix: string = "OpenAIRE | ";
39
  @Input() pageTitle = "";
40
  pageTitleWithFilters = "";
41
  @Input() results = [];
42
  @Input() type;
43
  @Input() entityType;
44
  @Input() searchUtils: SearchUtilsClass = new SearchUtilsClass();
45
  @Input() fieldIds: string[];
46
  @Input() fieldIdsMap;//:{ [key:string]:{ name:string, operator:string, type:string, indexField:string, equalityOperator:string  }} ;
47
  @Input() selectedFields: AdvancedField[];
48
  @ViewChild(ModalLoading) loading: ModalLoading;
49
  @Input() csvParams: string;
50
  @Input() csvPath: string;
51
  @Input() simpleSearchLink: string = "";
52
  @Input() advancedSearchLink: string = "";
53
  @Input() disableForms: boolean = false;
54
  @Input() disableRefineForms: boolean = false;
55
  @Input() loadPaging: boolean = true;
56
  @Input() oldTotalResults: number = 0;
57
  @Input() openaireLink: string;
58
  @Input() customFilter: SearchCustomFilter;
59
  @Input() sort: boolean = true;
60
  @Input() sortedByChanged: string = "";
61
  @Input() resultsPerPageChanged: number;
62
  @Input() searchFormClass: string = "searchForm";
63
  //From simple:
64
  @Input() rangeFilters: RangeFilter[] = [];
65
  @Input() rangeFields: string[][] = [];
66
  @Input() refineFields = [];
67
  @Input() filters:Filter[] = [];
68
  selectedFilters: number = 0;
69
  selectedRangeFilters: number = 0;
70
  private searchFieldsHelper: SearchFields = new SearchFields();
71
  @Input() newQueryButton: boolean = true;
72
  public showUnknownFilters: boolean = false; // when a filter exists in query but has no results, so no filters returned from the query
73
  URLCreatedFilters: Filter[] = [];
74
  URLCreatedRangeFilters: RangeFilter[] = [];
75
  @Input() showRefine: boolean = true;
76
  @Input() tableViewLink: string;
77
  @Input() usedBy: string = "search";
78
  @Input() public zenodoInformation: ZenodoInformationClass = new ZenodoInformationClass();
79
  @Input() showIndexInfo: boolean = true;
80
  @Input() showResultCount: boolean = true;
81
  @Input() showMoreFilterValuesInline: boolean = true;
82
  @Input() filterValuesNum: number = 6;
83
  @Input() keywordFields = [];
84
  @Input() simpleView: boolean = true;
85
  @Input() formPlaceholderText = "Type Keywords...";
86
  @Input() resultTypes:Filter = null;
87
  resultTypeOptions = {"publications":{"id":"publication", "name":"Publications"},"datasets":{"id":"dataset", "name":"Research data"},
88
    "software":{"id":"software", "name":"Software"},"other":{"id":"other", "name":" Other research products"}};
89
  selectedTypesNum = 0;
90
  @Input() quickFilter: { filter: Filter, selected: boolean, filterId: string, value: string };
91
  @Input() includeOnlyResultsAndFilter:boolean = false;
92
  @Input() showBreadcrumb:boolean = false;
93
  @Input() showDownload: boolean = true;
94
  public dashboard: boolean = properties.isDashboard;
95
96
  subscriptions = [];
97
  public parameterNames: string[] = [];
98
  public parameterValues: string[] = [];
99
100
  public csvLimit: number = 0;
101
  public pagingLimit: number = 0;
102
  public resultsPerPage: number = 0;
103
  isPiwikEnabled = false;
104
  properties: EnvProperties = properties;
105
  public pageContents = null;
106
  public divContents = null;
107
  public routerHelper: RouterHelper = new RouterHelper();
108
  public errorCodes: ErrorCodes = new ErrorCodes();
109
  breadcrumbs:Breadcrumb[] = [];
110
  url = null;
111
  metaDescription = "";
112
  @Input() basicMetaDescription = [];
113
114
  @Input() entitiesSelection:boolean = true;
115
  @Input() showSwitchSearchLink:boolean = true;
116
117
  // on 1st load, do not show filters until results query returns.
118
  public hideFilters: boolean = true;
119
120
  //Dashboard
121
  filterToggle = false;
122
  customFilterEnabled:boolean =  false;
123
  //stickyform
124
  @Input() stickyForm:boolean = false;
125
126
  @ViewChild('removeCustomFilter') removeCustomFilter: AlertModal;
127
  currentValueToRemove;
128
  currentFilterToRemove;
129
  public indexUpdateDate: Date;
130
  constructor(private route: ActivatedRoute,
131
              private location: Location,
132
              private _meta: Meta,
133
              private _title: Title,
134
              private _piwikService: PiwikService,
135
              private router: Router,
136
              private seoService: SEOService,
137
              private helper: HelperService,
138
              private cdr:ChangeDetectorRef, private indexInfoService: IndexInfoService) {
139
  }
140
141
  ngOnInit() {
142
      //this.getDivContents();
143
      this.getPageContents();
144
      this.pagingLimit = this.properties.pagingLimit;
145
      this.resultsPerPage = this.properties.resultsPerPage;
146
      this.csvLimit = this.properties.csvLimit;
147
      this.isPiwikEnabled = this.properties.enablePiwikTrack;
148
      this.updateUrl(this.properties.domain + this.properties.baseLink + this.router.url);
149
      this.url = this.properties.domain + this.properties.baseLink + this.router.url;
150
      if (typeof document !== 'undefined' && this.isPiwikEnabled && !this.includeOnlyResultsAndFilter && this.piwikSiteId) {
151
        this.subscriptions.push(this._piwikService.trackView(this.properties, this.pageTitle, this.piwikSiteId).subscribe());
152
      }
153
    this.route.queryParams.subscribe(params => {
154
      if (params['page'] && params['page'] != 1) {
155
        HelperFunctions.scrollToId("searchForm");
156
      }
157
      this.customFilterEnabled = params['cf'] && params['cf'] == "true";
158
      if(this.basicMetaDescription.length == 0 ){
159
        if (this.entityType == "result") {
160
          this.basicMetaDescription =  ["Research outcomes","Discover" + (this.properties.adminToolsCommunity == 'openaire'?" over 100 million of":"")+" research outcomes ", "categorized by research type, year range, funder, languages, community and content providers."];
161
        } else if (this.entityType == "project") {
162
          this.basicMetaDescription =  ["Research projects", "Discover research projects and correlated research categorized by Funder and active year. ", "Statistics data about produced research outcomes per year available."];
163
        } else if (this.entityType == "organization") {
164
          this.basicMetaDescription =  ["Research organization","Discover worldwide research organizations from over 100 countries and correlated research. ", "Funding, content providers, research pubblications and research data available."];
165
        }else{
166
          this.basicMetaDescription.push(this.pageTitle)
167
        }
168
      }
169
      // console.log("title " + this.pageTitle, this.basicMetaDescription)
170
      this.updateMeta(this.pageTitle);
171
    });
172
    this.searchUtils.baseUrl = "/" + this.searchUtils.baseUrl;
173
    this.breadcrumbs.push({name: 'home', route: '/'});
174
    if(this.simpleView) {
175
      this.breadcrumbs.push( {name: "Search", route: null});
176
    }else if(!this.simpleView && this.advancedSearchLink) {
177
      this.breadcrumbs.push({name: "Advanced Search", route: null});
178
    }
179
    //console.log(this.filters)
180
    if (typeof document !== 'undefined') {
181
      this.subscriptions.push(this.indexInfoService.getLastIndexDate(this.properties).subscribe(lastIndexUpdate => {
182
        if (lastIndexUpdate) {
183
          this.indexUpdateDate = new Date(lastIndexUpdate);
184
        }
185
      }));
186
    }
187
  }
188
189
  private getPageContents() {
190
    this.subscriptions.push(this.helper.getPageHelpContents(this.properties, (this.customFilter && this.customFilter.queryFieldName == "communityId") ? this.customFilter.valueId : this.properties.adminToolsCommunity, this.router.url).subscribe(contents => {
191
      this.pageContents = contents;
192
    }));
193
194
  }
195
196
  private getDivContents() {
197
      this.subscriptions.push(this.helper.getDivHelpContents(this.properties, (this.customFilter && this.customFilter.queryFieldName == "communityId") ? this.customFilter.valueId : this.properties.adminToolsCommunity, this.router.url).subscribe(contents => {
198
        this.divContents = contents;
199
      }));
200
  }
201
202
  ngOnDestroy() {
203
    this.subscriptions.forEach(subscription => {
204
      if (subscription instanceof Subscriber) {
205
        subscription.unsubscribe();
206
      }
207
    });
208
  }
209
210
  updateMeta(title:string) {
211
    let filterArray = [];
212
    let filtervalues = [];
213
    let filterURL = "";
214
    if(this.resultTypes && this.resultTypes.countSelectedValues> 0){
215
      filterURL += ((filterURL.length == 0) ? '?' : '&') + this.resultTypes.filterId + "=";
216
      let filterName = this.resultTypes.title+" ";
217
      for(let value of this.resultTypes.values){
218
        if(value.selected) {
219
          filterArray.push(filterName + '"' + value.name + '"');
220
          filtervalues.push(value.name);
221
          filterURL += ((filterName.length == 0) ? ',' : '') + StringUtils.URIEncode('"' + value.id+ '"' );
222
          filterName = "";
223
        }
224
      }
225
    }
226
    for(let filter of this.filters){
227
      if(filter.countSelectedValues> 0){
228
        filterURL += ((filterURL.length == 0) ? '?' : '&') + filter.filterId + "=";
229
        let filterName = filter.title+" ";
230
       for(let value of filter.values){
231
         if(value.selected) {
232
           filterArray.push(filterName + '"' + value.name + '"');
233
           filtervalues.push(value.name);
234
           filterURL += ((filterName.length == 0) ? ',' : '') + StringUtils.URIEncode( '"' + StringUtils.URIEncode( value.id ) + '"');
235
           filterName = "";
236
237
         }
238
        }
239
      }
240
    }
241
    let nonCanonicalizedPage = filterArray.length > 0;
242
      this.metaDescription= (nonCanonicalizedPage?( (this.basicMetaDescription[0] + " filtered by: " + filterArray.join(" and ") + ". ") + (this.basicMetaDescription.length > 1 ?this.basicMetaDescription[1]:""))
243
      :((this.basicMetaDescription.length > 2 ?this.basicMetaDescription[1] + this.basicMetaDescription[2]:this.basicMetaDescription[0])));
244
    this._meta.updateTag({content: this.metaDescription}, "name='description'");
245
    this._meta.updateTag({content: this.metaDescription}, "property='og:description'");
246
    this.updateTitle(title, (nonCanonicalizedPage ? filtervalues.join(" | ") + " | ": ""));
247
    filterURL =  (nonCanonicalizedPage ?  filterURL : "");
248
    this.url = this.properties.domain + this.properties.baseLink + this.router.url.split('?')[0] +  filterURL;
249
    this.seoService.createLinkForCanonicalURL(this.url + (this.searchUtils.page !=1?(filterURL.length > 0?'&':'?')+'page='+this.searchUtils.page:''), true);
250
    this.seoService.createLinkForNextURL(this.url +   (filterURL.length > 0 ? '&' : '?') + 'page=' + (this.searchUtils.page + 1), true);
251
    if(this.searchUtils.page != 1) {
252
      this.seoService.createLinkForPrevURL(this.url + (this.searchUtils.page !=2?(filterURL.length > 0?'&':'?')+'page='+(this.searchUtils.page - 1):'') , true);
253
    }else{
254
      this.seoService.removeLinkForPrevURL();
255
    }
256
  }
257
258
  updateTitle(title: string, filters:string) {
259
    let _title = (this.hasPrefix?this.prefix:"") + filters + title;
260
    // _title = ((_title.length > 50) ? _title.substring(0, 50) : _title);
261
    this.pageTitleWithFilters = _title;
262
    this._title.setTitle(_title);
263
    this._meta.updateTag({content: _title}, "property='og:title'");
264
  }
265
266
  updateUrl(url: string) {
267
    this._meta.updateTag({content: url}, "property='og:url'");
268
  }
269
270
271
  clearFilters() {
272
    for (var i = 0; i < this.filters.length; i++) {
273
      for (var j = 0; j < this.filters[i].countSelectedValues; j++) {
274
        if (this.filters[i].values[j].selected) {
275
          this.filters[i].values[j].selected = false;
276
        }
277
        this.filters[i].countSelectedValues = 0;
278
        this.filters[i].radioValue = "";
279
      }
280
    }
281
    this.selectedFilters = 0;
282
    for(let i = 0; i < this.rangeFilters.length; i++) {
283
      this.rangeFilters[i].selectedFromValue = null;
284
      this.rangeFilters[i].selectedToValue = null;
285
    }
286
    this.selectedRangeFilters = 0;
287
    // if (this.quickFilter) {
288
    //   this.removeValueFromQuickFilter();
289
    // }
290
    if(this.resultTypes) {
291
      this.resultTypes.values = [];
292
    }
293
    this.goTo(1);
294
    // this.clearKeywords();
295
  }
296
297
  goTo(page: number = 1, scroll:boolean = true) {
298
    if(this.offcanvasElement && (typeof document !== 'undefined')) {
299
      UIkit.offcanvas(this.offcanvasElement.nativeElement).hide();
300
    }
301
302
    this.searchUtils.page = page;
303
    this.buildPageURLParameters(this.filters, this.rangeFilters, true);
304
    this.router.navigate([this.searchUtils.baseUrl], {queryParams: this.routerHelper.createQueryParams(this.parameterNames, this.parameterValues)});
305
    if(scroll) {
306
      HelperFunctions.scrollToId("searchForm");
307
    }
308
    /* Code For Piwik*/
309
    if (typeof localStorage !== 'undefined') {
310
      //console.log("In PreviousRouteRecorder : "+this.router.url );
311
      localStorage.setItem('previousRoute', this.router.url);
312
    }
313
    if (this.isPiwikEnabled && (typeof document !== 'undefined') && this.piwikSiteId) {
314
      this.subscriptions.push(this._piwikService.trackView(this.properties, this.pageTitle, this.piwikSiteId).subscribe());
315
    }
316
    /* End Piwik Code */
317
  }
318
319
  queryChanged($event) {
320
    if($event == "filters_update"){
321
      this.cdr.detectChanges();
322
      return;
323
    }
324
    this.goTo(1, false);
325
  }
326
327
328
  sizeChanged($event) {
329
    //this.searchUtils.size = $event.value;
330
    this.resultsPerPageChanged = $event;
331
332
    this.goTo(1);
333
  }
334
335
  sortByChanged($event) {
336
    //this.searchUtils.sortBy = $event.value;
337
    this.sortedByChanged = $event;
338
    this.goTo(1);
339
  }
340
341
342
  getOperatorParameter(parameter: string): string {
343
    for (let id of this.fieldIds) {
344
      if (this.fieldIdsMap[id]["param"] == parameter) {
345
        return this.fieldIdsMap[id]["operator"];
346
      }
347
    }
348
  }
349
350
  /*
351
* Get A sub-array of this.refineFields array, which contains the ids of the selected filters
352
*/
353
  public getSelectedFilters(): string[] {
354
    var selected: string[] = [];
355
    var filters= this.URLCreatedFilters;
356
    for (var i = 0; i < filters.length; i++) {
357
      var filter: Filter = filters[i];
358
      if (filter.countSelectedValues > 0) {
359
        selected.push(filter.filterId);
360
      }
361
    }
362
    return selected;
363
  }
364
365
  /*
366
    * Get A sub-array of this.refineFields array, which contains the ids of the selected parameters
367
    */
368
  private getSelectedParameters(): string[] {
369
    var selected: string[] = [];
370
    for (var i = 0; i < this.refineFields.length; i++) {
371
      if (this.parameterNames.indexOf(this.refineFields[i]) != -1) {
372
        selected.push(this.refineFields[i]);
373
      }
374
    }
375
    return selected;
376
  }
377
378
  /*
379
  * Get A sub-array of this.refineFields array, which hides hidden fields (e.g Funding level 0,1,2,..), and contains those that depend on another fields (e.g  Funding level 0 if Funder is selected )
380
  */
381
  public getFields(): string[] {
382
    var selected_filters: string[] = this.getSelectedFilters();
383
    if (selected_filters.length == 0) {
384
      selected_filters = this.getSelectedParameters();
385
    }
386
    var fields: string[] = [];
387
    for (var i = 0; i < this.refineFields.length; i++) {
388
      var dependentTo = this.searchFieldsHelper.DEPENDENT_FIELDS[this.refineFields[i]];
389
390
      //if filter is not marked as hidden OR it is hidden but it is dependent to a field that it IS selected
391
      if (this.searchFieldsHelper.HIDDEN_FIELDS.indexOf(this.refineFields[i]) == -1 || (selected_filters.indexOf(dependentTo) != -1) || (selected_filters.indexOf(this.refineFields[i]) != -1)) {
392
        fields.push(this.refineFields[i]);
393
      }
394
    }
395
    return fields;
396
  }
397
398
  /*
399
  * Get a query  string of all fields, that want to get from search (e.g. &fields=funderid&fields=projectstartyear&...))
400
  */
401
  public getRefineFieldsQuery(): string {
402
403
    var fields: string[] = this.getFields();
404
    var fieldsStr = ""
405
    for (var i = 0; i < fields.length; i++) {
406
      fieldsStr += "&fields=" + fields[i];
407
    }
408
    return "&refine=true" + fieldsStr;
409
  }
410
411
412
  /*
413
  * Mark as check the new filters that are selected, when you get them from search
414
  */
415
  public checkSelectedFilters(filters: Filter[]) {
416
    this.filters = filters;
417
    if(this.customFilter && !this.customFilter.isHiddenFilter) {
418
      this.customFilter.selected = null;
419
    }
420
    for (var i = 0; i < filters.length; i++) {
421
      var filter: Filter = filters[i];
422
      filter.countSelectedValues = 0;
423
      if (this.parameterNames.indexOf(filter.filterId) != -1) {
424
        let values = (decodeURIComponent(this.parameterValues[this.parameterNames.indexOf(filter.filterId)])).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
425
        for (let filterValue of filter.values) {
426
          if (values.indexOf(StringUtils.quote(filterValue.id)) > -1) {
427
            filterValue.selected = true;
428
            filter.countSelectedValues++;
429
          } else {
430
            filterValue.selected = false;
431
432
          }
433
        }
434
        if(this.customFilter){
435
          this.customFilter.selected = this.customFilter.queryFieldName == filter.filterId && values.indexOf(StringUtils.quote(this.customFilter.valueId)) != -1;
436
        }
437
      // } else if (this.quickFilter && this.quickFilter.filterId == filter.filterId && this.quickFilter.selected) {
438
      //   for (let filterValue of filter.values) {
439
      //     if (filterValue.id == this.quickFilter.value) {
440
      //       filterValue.selected = true;
441
      //       filter.countSelectedValues++;
442
      //     } else {
443
      //       filterValue.selected = false;
444
      //     }
445
      //   }
446
      } else {
447
        for (let filterValue of filter.values) {
448
          filterValue.selected = false;
449
        }
450
      }
451
      // if (this.quickFilter && filter.filterId == this.quickFilter.filterId) {
452
      //   this.quickFilter.filter = filter;
453
      // }
454
    }
455
    if (this.parameterNames.indexOf("cf") != -1 && this.parameterValues[this.parameterNames.indexOf("cf")] == "true") {
456
      this.customFilter.selected = true;
457
    }else if(this.customFilter && this.customFilter.selected == null){
458
      this.customFilter.selected = false;
459
    }
460
    this.filterFilterValues(this.filters);
461
    if(!this.includeOnlyResultsAndFilter) {
462
      this.updateMeta(this.pageTitle);
463
    }
464
    return filters;
465
  }
466
467
  /*
468
* Mark as check the new range filters that are selected
469
*/
470
  public checkSelectedRangeFilters(filters: RangeFilter[]) {
471
    //console.log("checkSelectedRangeFilters: parameterNames.length: "+this.parameterNames.length);
472
473
    this.rangeFilters = filters;
474
    for (let i = 0; i < filters.length; i++) {
475
      let filter: RangeFilter = filters[i];
476
477
      if (this.parameterNames.indexOf(filter.filterId) != -1) {
478
        //console.log(filter.filterId + " "+this.parameterNames.indexOf(filter.filterId) );
479
        let values = (decodeURIComponent(this.parameterValues[this.parameterNames.indexOf(filter.filterId)])).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
480
        let operators: string [] = (StringUtils.URIDecode(this.parameterValues[this.parameterNames.indexOf(filter.filterId)])).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
481
        if (values.length == operators.length) {
482
          for (let j = 0; j < values.length; j++) {
483
            if (this.fieldIdsMap[filter.originalFilterIdFrom+"-range-"+filter.originalFilterIdTo].filterType == "range") {
484
              let value: string = StringUtils.unquote(values[j]);
485
              let validDates: boolean = true;
486
487
              let years: string[] = (value.substring(5)).split(":");
488
              let yearFrom: string = (Dates.isValidYear(years[0]) ? years[0] : null);
489
              let yearTo: string = (Dates.isValidYear(years[1]) ? years[1] : null);
490
              //console.log("checkSelectedRangeFilters: yearFrom: " + yearFrom + " - yearTo: "+yearTo);
491
              if(yearFrom) {
492
                filter.selectedFromValue = yearFrom;
493
              }
494
              if(yearTo) {
495
                filter.selectedToValue = yearTo;
496
              }
497
              if(yearFrom && yearTo) {
498
                filter.selectedFromAndToValues = yearFrom + "-" + yearTo;
499
              } else if(yearFrom) {
500
                filter.selectedFromAndToValues = "From " + yearFrom;
501
              } else if(yearTo) {
502
                filter.selectedFromAndToValues = "Until " + yearTo;
503
              }
504
505
              if(!yearFrom && !yearTo) {
506
                validDates = false;
507
              }
508
509
              // if (value.length < 14) {
510
              //   validDates = false;
511
              //   console.log("not valid (length<14)");
512
              // } else {
513
              //   if (!Dates.isValidYear(value.substring(5, 9)) || !Dates.isValidYear(value.substring(10, 14))) {
514
              //     validDates = false;
515
              //     console.log("not valid years");
516
              //   } else {
517
              //     filter.selectedFromValue = value.substring(5, 9);
518
              //     filter.selectedToValue = value.substring(10, 14);
519
              //     console.log(filter);
520
              //   }
521
              // }
522
            }
523
          }
524
        }
525
      } else {
526
        filter.selectedFromValue = null;
527
        filter.selectedToValue = null;
528
      }
529
    }
530
    return this.rangeFilters;
531
  }
532
533
  get existingFiltersWithValues() {
534
    if(this.filters.length == 0) {
535
      return 0;
536
    }
537
    return this.filters.some(filter => (filter.values && filter.values.length > 0));
538
  }
539
540
  /*
541
  * For Funder filters - if funder selected
542
  */
543
  public filterFilterValues(filters: Filter[]) {
544
    var funders = [];
545
    var funder_prefix = [];
546
    for (var i = 0; i < filters.length; i++) {
547
548
      var filter: Filter = filters[i];
549
      //  console.log(filter.filterId);
550
      if (filter.filterId.indexOf("funder") != -1 && this.parameterNames.indexOf(filter.filterId) != -1) {
551
        let funders = (decodeURIComponent(this.parameterValues[this.parameterNames.indexOf(filter.filterId)])).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
552
        for (let funder of funders) {
553
          funder_prefix.push(StringUtils.unquote(funder).split("____")[0]);
554
        }
555
        //  console.log(funder_prefix );
556
      } else if (filter.filterId.indexOf("funding") != -1) {
557
        //  console.log(" funding: "+filter.filterId );
558
        var filteredValues = []
559
        for (let filterValue of filter.values) {
560
          var value_prefix = filterValue.id.split("____")[0];
561
          //  console.log("Value prefix: "+value_prefix );
562
          if (funder_prefix.indexOf(value_prefix) != -1) {
563
            //  console.log("here" + value_prefix);
564
            filteredValues.push(filterValue);
565
          }
566
567
        }
568
        if (filteredValues.length > 0) {
569
          filter.values = filteredValues;
570
        }
571
      }
572
573
    }
574
575
    return filters;
576
  }
577
578
  public countSelectedFilters(filters: Filter[]): number {
579
    this.selectedFilters = 0;
580
    for (let filter of filters) {
581
      if (filter.countSelectedValues > 0) {
582
        this.selectedFilters += filter.countSelectedValues;
583
      }
584
    }
585
    return this.selectedFilters;
586
  }
587
588
  public countSelectedRangeFilters(rangeFilters: RangeFilter[]) : number {
589
    this.selectedRangeFilters = 0;
590
    for(let filter of rangeFilters) {
591
      if(filter.selectedFromValue || filter.selectedToValue) {
592
        this.selectedRangeFilters++;
593
      }
594
    }
595
    return this.selectedRangeFilters;
596
  }
597
598
  private clearKeywords() {
599
    if (this.searchUtils.keyword.length > 0) {
600
      this.searchUtils.keyword = '';
601
    }
602
    this.goTo(1);
603
  }
604
605
  public removeFilter(value: Value, filter: Filter, forceRemove:boolean = false) {
606
    this.currentValueToRemove = value;
607
    this.currentFilterToRemove = filter;
608
    if(!forceRemove && this.customFilter && this.customFilter.queryFieldName ==filter.filterId && this.customFilter.valueId == value.id && this.customFilter.promptToAddFilter ){
609
      this.openRemoveCustomFilterModal();
610
      return;
611
    }
612
    filter.countSelectedValues--;
613
    this.selectedFilters--;
614
    if (value.selected == true) {
615
      value.selected = false;
616
    }
617
    if(filter.filterType == "radio"){
618
      filter.radioValue = "";
619
    }
620
    // if (this.quickFilter && this.quickFilter.filterId == filter.filterId) {
621
    //   this.removeValueFromQuickFilter();
622
    // }
623
    this.goTo(1);
624
  }
625
  public openRemoveCustomFilterModal() {
626
    this.removeCustomFilter.alertTitle = 'Remove filter';
627
    this.removeCustomFilter.message = 'You are about to see results that are not related to '+ this.customFilter.valueName + '. Do you want to proceed?';
628
    this.removeCustomFilter.okButtonText = 'Yes';
629
    this.removeCustomFilter.cancelButtonText = 'No';
630
    this.removeCustomFilter.open();
631
  }
632
633
  closeCustomFilterModal() {
634
    this.customFilterEnabled = false;
635
    this.removeFilter(this.currentValueToRemove, this.currentFilterToRemove, true);
636
  }
637
638
  public removeRangeFilter(filter: RangeFilter) {
639
    filter.selectedFromValue = null;
640
    filter.selectedToValue = null;
641
    this.goTo(1);
642
  }
643
644
  getSelectedValues(filter): any {
645
    var selected = [];
646
    if (filter.countSelectedValues > 0) {
647
      for (var i = 0; i < filter.values.length; i++) {
648
        if (filter.values[i].selected) {
649
          selected.push(filter.values[i]);
650
        }
651
      }
652
    }
653
    return selected;
654
655
  }
656
657
  filterChanged($event) {
658
/*    if (this.quickFilter && this.quickFilter.filter) {
659
      this.removeValueFromQuickFilter();
660
    }*/
661
    this.goTo(1);
662
663
  }
664
665
  /**
666
   * if there is a change in the values of the quick filter, this function has to be run, to also update the quickFilter
667
   */
668
/*  removeValueFromQuickFilter() {
669
    if (this.quickFilter.filter.countSelectedValues == 0) {
670
      this.quickFilter.selected = false;
671
    } else {
672
      let isQuickEnabled = false;
673
      for (let filterValue of this.quickFilter.filter.values) {
674
        isQuickEnabled = (filterValue.name == this.quickFilter.value)
675
      }
676
      this.quickFilter.selected = (isQuickEnabled && this.quickFilter.filter.countSelectedValues == 1);
677
    }
678
  }*/
679
680
  /**
681
   * Set selected the value of the custom filter.
682
   */
683
  addCustomFilter() {
684
    this.customFilter.selected = true;
685
    this.customFilterEnabled = true;
686
    if(this.refineFields.indexOf(this.customFilter.queryFieldName) != -1  ){
687
      let found = false;
688
      for (let filter of this.filters) {
689
        if (this.customFilter.queryFieldName == filter.filterId) {
690
          for (let value of filter.values) {
691
            if (value.id == this.customFilter.valueId) {
692
              value.selected = true;
693
              filter.countSelectedValues++;
694
              found = true;
695
              break;
696
            }
697
          }
698
          //add filter when field exist in refine but not in the refine values
699
          if(!found){
700
            filter.countSelectedValues ++ ;
701
            filter.values.push({selected : true, name: this.customFilter.valueName, id: this.customFilter.valueId, number:0});
702
          }
703
          break;
704
        }
705
      }
706
    }
707
    this.filterChanged(null);
708
709
  }
710
  // for loading
711
  public openLoading() {
712
    this.loading.open();
713
  }
714
715
  public closeLoading() {
716
    this.loading.close();
717
  }
718
719
  /**
720
   * Build advanced search Filters based on the URL parameters
721
   * @param params
722
   */
723
  createAdvancedSearchSelectedFiltersFromNewURLParameters(params) {
724
    for (let i = 0; i < Object.keys(params).length; i++) {
725
      if(params["f"+i] && params["fv"+i]   ) {
726
        let fieldId = params["f" + i].split(",")[0];
727
        let operator = (params["f" + i].split(",").length  >1 )?params["f" + i].split(",")[1]:"and";
728
        let fieldparam = (this.fieldIdsMap[fieldId]) ? this.fieldIdsMap[fieldId].param : "";
729
730
        if (!this.fieldIdsMap[fieldId]) {
731
          console.error("Field: " + fieldId + " not found in fieldIds map");
732
          continue;
733
        }
734
        let value: string = StringUtils.URIDecode(params["fv"+i]);
735
        if (this.fieldIdsMap[fieldId].type == "date") {
736
            let validDates: boolean = true;
737
            let dateField: AdvancedField = new AdvancedField(fieldId, fieldparam, this.fieldIdsMap[fieldId].name, this.fieldIdsMap[fieldId].type, value, operator);
738
            if (value.indexOf("range") != -1) {
739
              dateField.dateValue.type = "range";
740
              if (value.length < 26) {
741
                validDates = false;
742
              } else {
743
                if (!Dates.isValidDate(value.substring(5, 15)) || !Dates.isValidDate(value.substring(16, 26))) {
744
                  validDates = false;
745
                } else {
746
                  dateField.dateValue.from = Dates.getDateFromString(value.substring(5, 15));
747
                  dateField.dateValue.to = Dates.getDateFromString(value.substring(16, 26));
748
                }
749
              }
750
              //  "rangeYYYY-MM-DD:YYYY-MM-DD"
751
            } else {
752
              dateField.dateValue.setDatesByType(value);
753
            }
754
            if (validDates) {
755
              this.selectedFields.push(dateField);
756
            }
757
758
          } else {
759
            this.selectedFields.push(new AdvancedField(fieldId, fieldparam, this.fieldIdsMap[fieldId].name, this.fieldIdsMap[fieldId].type,value, operator));
760
          }
761
762
        }
763
      }
764
  }
765
  /**
766
   * Build advanced search Filters based on the URL parameters
767
   * @param params
768
   */
769
  createAdvancedSearchSelectedFiltersFromURLParameters(params) {
770
    this.createAdvancedSearchSelectedFiltersFromNewURLParameters(params);
771
    for (var i = 0; i < this.fieldIds.length; i++) {
772
      var fieldId = this.fieldIds[i];
773
      var fieldparam = (this.fieldIdsMap[fieldId]) ? this.fieldIdsMap[fieldId].param : "";
774
      if (!this.fieldIdsMap[fieldId]) {
775
        console.error("Field: " + fieldId + " not found in fieldIds map");
776
        continue;
777
      }
778
779
      var operatorId = this.getOperatorParameter(fieldparam);
780
      if (params[fieldparam] != undefined && params[operatorId] != undefined) {
781
        var values: string [] = StringUtils.URIDecode(params[fieldparam]).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
782
        var operators: string [] = (StringUtils.URIDecode(params[operatorId])).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
783
        if (values.length == operators.length) {
784
          for (var j = 0; j < values.length; j++) {
785
            if (this.fieldIdsMap[fieldId].type == "date") {
786
              var value: string = StringUtils.unquote(values[j]);
787
              var validDates: boolean = true;
788
              var dateField: AdvancedField = new AdvancedField(fieldId, fieldparam, this.fieldIdsMap[fieldId].name, this.fieldIdsMap[fieldId].type, value, operators[j]);
789
              if (value.indexOf("range") != -1) {
790
                dateField.dateValue.type = "range";
791
                if (value.length < 26) {
792
                  validDates = false;
793
                } else {
794
                  if (!Dates.isValidDate(value.substring(5, 15)) || !Dates.isValidDate(value.substring(16, 26))) {
795
                    validDates = false;
796
                  } else {
797
                    dateField.dateValue.from = Dates.getDateFromString(value.substring(5, 15));
798
                    dateField.dateValue.to = Dates.getDateFromString(value.substring(16, 26));
799
                  }
800
                }
801
                //  "rangeYYYY-MM-DD:YYYY-MM-DD"
802
              } else {
803
                dateField.dateValue.setDatesByType(value);
804
              }
805
              if (validDates) {
806
                this.selectedFields.push(dateField);
807
              }
808
809
            } else {
810
              this.selectedFields.push(new AdvancedField(fieldId, fieldparam, this.fieldIdsMap[fieldId].name, this.fieldIdsMap[fieldId].type, values[j], operators[j]));
811
            }
812
          }
813
        }
814
      }
815
    }
816
    if (params['keyword'] && params['keyword'].length > 0) {
817
      this.selectedFields.push(new AdvancedField(this.fieldIds[0], this.fieldIdsMap[this.fieldIds[0]].param, this.fieldIdsMap[this.fieldIds[0]].name, this.fieldIdsMap[this.fieldIds[0]].type, params['keyword'], "and"));
818
    }
819
    if (this.selectedFields.length == 0) {
820
      this.selectedFields.push(new AdvancedField(this.fieldIds[0], this.fieldIdsMap[this.fieldIds[0]].param, this.fieldIdsMap[this.fieldIds[0]].name, this.fieldIdsMap[this.fieldIds[0]].type, "", "and"));
821
    }
822
  }
823
824
  /**
825
   * Create Search API query based on the selected fields of the advanced form
826
   */
827
  getSearchAPIQueryForAdvancedSearhFields() {
828
829
    var params = "";
830
    var countParams = 0;
831
    for (var i = 0; i < this.selectedFields.length; i++) {
832
      if (this.fieldIdsMap[this.selectedFields[i].id] != undefined && (this.selectedFields[i].value != "" || this.selectedFields[i].type == "date")) {
833
        //console.log("createQueryParameters::"+this.selectedFields[i].type);
834
        if (this.selectedFields[i].type == "date") {
835
          if (this.selectedFields[i].dateValue.type != "any") {
836
            params += (countParams == 0 ? "" : this.selectedFields[i].operatorId) + " " + this.selectedFields[i].id + this.fieldIdsMap[this.selectedFields[i].id].equalityOperator + '"' + StringUtils.URIEncode(Dates.getDateToString(this.selectedFields[i].dateValue.from)) + " "
837
              + StringUtils.URIEncode(Dates.getDateToString(this.selectedFields[i].dateValue.to)) + '"' + " ";
838
          }
839
        } else {
840
          if (this.selectedFields[i].id == "q") {
841
            // console.log(this.selectedFields[i].value)
842
/*            var op = "";
843
            var doisParams = "";
844
            if ((this.entityType == 'publication' || this.entityType == 'dataset' || this.entityType == 'software' || this.entityType == 'other' || this.entityType == "result")) {
845
              var DOIs: Identifier[] = Identifier.getIdentifiersFromString(this.selectedFields[i].value);
846
              for (let identifier of DOIs) {
847
                // console.log(identifier)
848
                // pidclassid exact \"doi\" and pid exact \"10.1016/j.nima.2015.11.134\"
849
                //and (authorid exact \"0000-0001-7291-3210 \" )"
850
                if(identifier.class == "ORCID"){
851
                  doisParams += (doisParams.length > 0 ? " or " : "") +'(authorid="' + identifier.id + '")';
852
                }else{
853
                  doisParams += (doisParams.length > 0 ? " or " : "") +'(pidclassid exact "' + identifier.class + '" and pid="' +  identifier.id + '")';
854
                }
855
              }
856
            }
857
            if (doisParams.length > 0) {
858
              params += this.createQuotedKeywordQuery(this.selectedFields[i].value, this.selectedFields[i].id, this.selectedFields[i].operatorId ,countParams,true, true) + " or " + doisParams;
859
            } else {
860
              params += this.createQuotedKeywordQuery(this.selectedFields[i].value, this.selectedFields[i].id, this.selectedFields[i].operatorId,countParams,true);
861
            }*/
862
            params += NewSearchPageComponent.createKeywordQuery(this.entityType,this.selectedFields[i].value, this.selectedFields[i].id, this.selectedFields[i].operatorId, countParams);
863
            //TODO deposit case
864
            // console.log(this.usedBy)
865
            // console.log(this.keywordFields)
866
867
            if(this.usedBy == "deposit") {
868
869
              if(this.keywordFields.length > 0) {
870
                params += " or ("
871
              }
872
              for(let j=0; j< this.keywordFields.length ; j++) {
873
                if(j > 0) {
874
                  params += " or "
875
                }
876
                params += NewSearchPageComponent.createQuotedKeywordQuery(this.selectedFields[i].value, this.keywordFields[j].name, " or ", countParams,false);
877
                // let field = this.keywordFields[i];
878
                //keywordQuery += field.name+field.equalityOperator+StringUtils.URIEncode(keyword);
879
                // params += field.name+field.equalityOperator+StringUtils.quote(StringUtils.URIEncode(keyword));
880
              }
881
              if(this.keywordFields.length > 0) {
882
                params += " ) "
883
              }
884
            }
885
886
          } else if(this.selectedFields[i].type == "identifier") {
887
            params += NewSearchPageComponent.createKeywordQuery(this.entityType,this.selectedFields[i].value, this.selectedFields[i].id, this.selectedFields[i].operatorId, countParams);
888
          } else if (countParams == 0 && this.selectedFields[i].operatorId == "not" && this.fieldIdsMap[this.selectedFields[i].id].equalityOperator != "=") {
889
            params += " " + this.selectedFields[i].id + " <> " + '"' + StringUtils.URIEncode(this.selectedFields[i].value) + '"' + " ";
890
          } else if(this.fieldIdsMap[this.selectedFields[i].id].equalityOperator == "=") {
891
            params+=NewSearchPageComponent.createQuotedKeywordQuery(this.selectedFields[i].value, this.selectedFields[i].id, this.selectedFields[i].operatorId, countParams, false);
892
          }else{
893
              params += (countParams == 0 ? "" : " " + this.selectedFields[i].operatorId + " ") + this.selectedFields[i].id + this.fieldIdsMap[this.selectedFields[i].id].equalityOperator + '"' + encodeURIComponent(this.selectedFields[i].value) + '"' + " ";
894
895
          }
896
        }
897
        countParams++;
898
      }
899
    }
900
901
    // console.log("ParameterS:")
902
    // console.log(params)
903
    return params;
904
  }
905
  public static createKeywordQuery(entityType:string, value:string, id, operatorId, countParams=0){
906
    let params = "";
907
    let doisParams = "";
908
    var DOIs: Identifier[] = Identifier.getIdentifiersFromString(value);
909
    if ((entityType == 'publication' || entityType == 'dataset' || entityType == 'software' || entityType == 'other' || entityType == "result")) {
910
      for (let identifier of DOIs) {
911
        // console.log(identifier)
912
        // pidclassid exact \"doi\" and pid exact \"10.1016/j.nima.2015.11.134\"
913
        //and (authorid exact \"0000-0001-7291-3210 \" )"
914
        if(identifier.class == "ORCID"){
915
          doisParams += (doisParams.length > 0 ? " or " : "") +'(authorid="' + StringUtils.URIEncode(identifier.id) + '")';
916
          // doisParams += (doisParams.length > 0 ? " or " : "") +'(authorid="' + StringUtils.URIEncode(identifier.id) + '" and (authoridtype exact "orcid"))';
917
        }else{
918
          doisParams += (doisParams.length > 0 ? " or " : "") +'(pidclassid exact "' + identifier.class + '" and pid="' +  StringUtils.URIEncode(identifier.id) + '")';
919
          // doisParams += (doisParams.length > 0 ? " or " : "") +'(pidclassid exact "' + identifier.class + '" and pid="' +  identifier.id + '")';
920
        }
921
      }
922
    }
923
    if (doisParams.length > 0) {
924
      params += "(" + this.createQuotedKeywordQuery(value, id, operatorId ,countParams,true, true) + " or " + doisParams+")";
925
    } else {
926
      //if it is PIDs but no doisquery produced, forced to use quotes as the query will fail due to special characters
927
      params += this.createQuotedKeywordQuery(value, id, operatorId,countParams,true,
928
        (DOIs.length > 0 && doisParams.length == 0) );
929
    }
930
    return params;
931
932
  }
933
  private static createQuotedKeywordQuery(fieldValue, fieldId, fieldOperator, countParams:number, isSearchAll:boolean, forceQuotted:boolean=false){
934
    let params = "";
935
    let countQuote = (fieldValue.match(/'/g) || []).length;
936
    let countDoubleQuote = (fieldValue.match(/"/g) || []).length;
937
    let quotedParts = [];
938
    if(countQuote % 2 == 0 && countDoubleQuote % 2 ==0){
939
      quotedParts = (fieldValue)?fieldValue.match(/(["'])(.*?)*?\1/g):[];
940
    }
941
    params+= (countParams == 0 ? "" : fieldOperator);
942
    params+=   " (";
943
    if(forceQuotted){
944
      return (countParams == 0 ? "" : " "+fieldOperator+" ") + this.getQuotedQueryPart(fieldId, '"'+ fieldValue+'"',isSearchAll);
945
    }
946
    if(quotedParts && quotedParts.length == 1 && quotedParts[0] == fieldValue ){
947
      params+=this.getQuotedQueryPart(fieldId, fieldValue,isSearchAll);
948
    }else if( quotedParts && quotedParts.length > 0){
949
      for(let i=0; i< quotedParts.length; i++){
950
        params+=(i>0)?" and ":"";
951
        params+=this.getQuotedQueryPart(fieldId, quotedParts[i],isSearchAll);
952
      }
953
      let startPoint = 0;
954
      let endPoint = 0;
955
      for(let i=0; i< quotedParts.length; i++){
956
        let index = fieldValue.indexOf(quotedParts[i]);
957
        endPoint = (i+1<quotedParts.length)? fieldValue.indexOf(quotedParts[i+1]):fieldValue.length;
958
        // console.log(fieldValue.indexOf(quotedParts[i+1]) +" - "+fieldValue.length);
959
        // console.log(" SP "+ startPoint+" EP: "+endPoint);
960
        if(index==startPoint){
961
          startPoint +=quotedParts[i].length;
962
        }else if(startPoint < index){
963
          endPoint = index;
964
        }
965
        // console.log(" SP "+ startPoint+" EP: "+endPoint);
966
        if(decodeURIComponent(fieldValue.substring(startPoint,endPoint)).split(" ").join("").length > 0) {
967
          params += " and " + this.getNoQuotedQueryPart(fieldId, fieldValue.substring(startPoint, endPoint), isSearchAll);
968
        }
969
        // console.log("For "+i+"  " +params+" SP "+ startPoint+" EP: "+endPoint);
970
        // startPoint = (i+1<quotedParts.length)? fieldValue.indexOf(quotedParts[i+i]):fieldValue.length;//(startPoint<index  )?(index + quotedParts[i].length):fieldValue.length;
971
        startPoint = ((i+1<quotedParts.length)?(fieldValue.indexOf(quotedParts[i+1])+quotedParts[i+1].length):(endPoint== index?(index+quotedParts[i].length):endPoint));
972
      }
973
      if(startPoint !=fieldValue.length && decodeURIComponent(fieldValue.substring(startPoint,fieldValue.length)).split(" ").join("").length > 0){
974
        params+=" and " + this.getNoQuotedQueryPart(fieldId, fieldValue.substring(startPoint,fieldValue.length),isSearchAll);
975
      }
976
    }else{
977
      params+=this.getNoQuotedQueryPart(fieldId, fieldValue,isSearchAll);
978
    }
979
    params += ")";
980
    return params;
981
  }
982
983
  private static getQuotedQueryPart(fieldId:string, value:string,  isSearchAll:boolean){
984
      return (isSearchAll?"__all":fieldId)+" exact "+StringUtils.URIEncode(value);
985
  }
986
  private static getNoQuotedQueryPart(fieldId:string, value:string,  isSearchAll:boolean){
987
    //split the keywords of the vlaue and query seperately for each keyword using quotes to allow characters like .@
988
    let valueKeywords= value.split(" ");
989
    let query = "";
990
    let i=0;
991
    for(let keyword of valueKeywords ){
992
      if(keyword.length > 0){
993
        query+= (i!=0?" and ":"")+(isSearchAll?"(":fieldId+"=")+"\""+StringUtils.URIEncode(this.checkForReservedWords(keyword)) +"\""+ (isSearchAll?")":"");
994
        i++;
995
      }
996
    }
997
    return query
998
  }
999
  private static checkForReservedWords(keyword:string){
1000
    let reservedWords = ["AND", "OR", "NOT"];
1001
    if(reservedWords.indexOf(keyword)!=-1){
1002
      return keyword.toLowerCase();
1003
    }
1004
    return keyword;
1005
  }
1006
  /**
1007
   * Create Search API query based on the filters of refine fields
1008
   * @param URLparams
1009
   * @param firstLoad
1010
   */
1011
  getSearchAPIQueryForRefineFields(URLparams, firstLoad: boolean) {
1012
1013
    var allFqs = "";
1014
    // console.log(this.refineFields)
1015
    for (var i = 0; i < this.refineFields.length; i++) {
1016
      var filterId = this.refineFields[i];
1017
1018
      if (URLparams[filterId] != undefined) {
1019
        let values = (StringUtils.URIDecode(StringUtils.URIDecode(URLparams[filterId]))).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
1020
        var countvalues = 0;
1021
        var fq = "";
1022
        let filterOp: string = this.searchFieldsHelper.getFieldOperator(filterId);
1023
        // console.info(filterId, filterOp);
1024
        for (let value of values) {
1025
          countvalues++;
1026
          var paramId = this.fieldIdsMap[filterId].param;
1027
          // parameters+='&' + paramId+ '='+ value;//+"&" + this.fieldIdsMap[paramId].operator + "="+((countvalues == 1)?"and":"or");
1028
          fq += (fq.length > 0 ? " " + filterOp + " " : "") + filterId + " exact " + (value);
1029
        }
1030
        if (countvalues > 0) {
1031
          fq = "&fq=" + StringUtils.URIEncode(fq);
1032
        }
1033
        allFqs += fq;
1034
      }
1035
    }
1036
    this.customFilterEnabled = URLparams["cf"] == "true";
1037
    if(this.customFilter && (this.customFilter.isHiddenFilter || this.customFilterEnabled)){
1038
      allFqs += "&fq=" + StringUtils.URIEncode(this.customFilter.queryFieldName + " exact " + StringUtils.quote((this.customFilter.valueId)));
1039
    }
1040
1041
/*    if (this.quickFilter && this.entityType == "result") {
1042
      if((URLparams[this.quickFilter.filterId] == undefined && URLparams["qf"] == undefined)   || URLparams["qf"] == "true"
1043
        || ((URLparams[this.quickFilter.filterId] != undefined && StringUtils.URIDecode(URLparams[this.quickFilter.filterId]).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1).indexOf(StringUtils.quote(this.quickFilter.value)) != -1))) {
1044
        this.quickFilter.selected = true;
1045
      } else {
1046
        this.quickFilter.selected = false;
1047
      }
1048
      if( this.quickFilter.selected && URLparams[this.quickFilter.filterId] == undefined){
1049
      // if ((firstLoad && URLparams[this.quickFilter.filterId] == undefined && URLparams["qf"] == undefined)
1050
      // ||( URLparams[this.quickFilter.filterId] == undefined && URLparams["qf"] == "true")) {
1051
        allFqs += "&fq=resultbestaccessright exact " + StringUtils.quote(this.quickFilter.value);
1052
      }
1053
    }*/
1054
1055
    if (this.entityType == "result") {
1056
      if (URLparams["type"]) {
1057
        let types = URLparams["type"];
1058
        types = Array.isArray(types) ? types.join(',').split(","):types.split(",");
1059
        types.map( function (t) {
1060
          return StringUtils.unquote(StringUtils.URIDecode(t));
1061
        } );
1062
1063
        if(types.indexOf("publications")!=-1 && types.indexOf("datasets")!=-1 && types.indexOf("software")!=-1 && types.indexOf("other")!=-1 ){
1064
          allFqs += "&type=results";
1065
        }else{
1066
          for (let type of types) {
1067
            allFqs += "&type=" + StringUtils.unquote(StringUtils.URIDecode(type));
1068
          }
1069
        }
1070
      }else{
1071
        allFqs += "&type=results";
1072
      }
1073
    } else if (this.entityType == "publication") {
1074
      allFqs += "&type=publications";
1075
    } else if (this.entityType == "dataset") {
1076
      allFqs += "&type=datasets";
1077
    } else if (this.entityType == "software") {
1078
      allFqs += "&type=software";
1079
    } else if (this.entityType == "other") {
1080
      allFqs += "&type=other";
1081
    } else if(this.entityType == "project") {
1082
      allFqs += "&type=projects";
1083
    } else if(this.entityType == "organization") {
1084
      allFqs += "&type=organizations";
1085
    } else if(this.entityType == "dataprovider") {
1086
      allFqs += "&type=datasources";
1087
    }
1088
    // console.log("AllFqs (check type): "+allFqs);
1089
    // console.log("type: "+this.entityType);
1090
    // var keyword = URLparams['keyword'];
1091
    // var doiQuery = "";
1092
    // var keywordQuery = "";
1093
    // if((keyword && keyword.length > 0)){
1094
    //   if((this.type == 'publications' ||this.type == 'research data' || this.type == 'software' || this.type == 'other research products')){
1095
    //     var DOIs:string[] = DOI.getDOIsFromString(keyword);
1096
    //     var doisParams = "";
1097
    //
1098
    //     for(var i =0 ;i < DOIs.length; i++){
1099
    //       doisParams+=(doisParams.length > 0?"&":"")+'doi="'+ DOIs[i]+'"';
1100
    //     }
1101
    //     if(doisParams.length > 0){
1102
    //       doiQuery += "&"+doisParams;
1103
    //     }else {
1104
    //       keywordQuery += "&q="+StringUtils.URIEncode(keyword);
1105
    //     }
1106
    //   }else{
1107
    //     if(this.usedBy == "deposit") {
1108
    //       if(this.keywordFields.length > 0) {
1109
    //         keywordQuery = "&fq=";
1110
    //       }
1111
    //
1112
    //       for(let i=0; i< this.keywordFields.length ; i++) {
1113
    //         if(i > 0) {
1114
    //           keywordQuery += " or ";
1115
    //         }
1116
    //         let field = this.keywordFields[i];
1117
    //         //keywordQuery += field.name+field.equalityOperator+StringUtils.URIEncode(keyword);
1118
    //         keywordQuery += field.name+field.equalityOperator+StringUtils.quote(StringUtils.URIEncode(keyword));
1119
    //       }
1120
    //     } else {
1121
    //       keywordQuery += "&q=" + StringUtils.URIEncode(keyword);
1122
    //     }
1123
    //
1124
    //   }
1125
    // }
1126
    //TODO add DOI?
1127
     return allFqs;
1128
1129
  }
1130
1131
  /**
1132
   * Create Search API query based on the filters of refine fields
1133
   * @param URLparams
1134
   */
1135
  getSearchAPIQueryForRangeFields(URLparams) {
1136
    let allFqs = "";
1137
    for (let i = 0; i < this.rangeFields.length; i++) {
1138
      let filterId = this.rangeFields[i][0]+"-range-"+this.rangeFields[i][1];
1139
      let filterParam = this.searchFieldsHelper.getFieldParam(filterId, this.entityType);
1140
1141
      if (URLparams[filterParam] != undefined) {
1142
        let values = (StringUtils.URIDecode(StringUtils.URIDecode(URLparams[filterParam]))).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
1143
        var countvalues = 0;
1144
        var fq = "";
1145
        var fqFrom = "";
1146
        var fqTo = "";
1147
        let filterOp: string = this.searchFieldsHelper.getFieldOperator(filterId);
1148
1149
        for (let value of values) {
1150
          if (this.fieldIdsMap[filterId].filterType == "range") {
1151
1152
            let selectedFromValue;
1153
            let selectedToValue;
1154
1155
            let years: string[] = (value.substring(5)).split(":");
1156
            let yearFrom: string = (Dates.isValidYear(years[0]) ? years[0] : null);
1157
            //(Number.isInteger(parseInt(years[0], 10)) ? years[0] : null);
1158
            let yearTo: string = (Dates.isValidYear(years[1]) ? years[1] : null);
1159
            //console.log("getSearchAPIQueryForRangeFields: yearFrom: " + yearFrom + " - yearTo: "+yearTo);
1160
            if(yearFrom) {
1161
              selectedFromValue = yearFrom;
1162
            }
1163
            if(yearTo) {
1164
              selectedToValue = yearTo;
1165
            }
1166
            if(yearFrom || yearTo) {
1167
1168
            // if (value.length <= 14) {
1169
            //   if(Dates.isValidYear(value.substring(5, 9))) {
1170
            //     selectedFromValue = value.substring(5, 9);
1171
            //   }
1172
            //   if(Dates.isValidYear(value.substring(10, 14))) {
1173
            //     selectedToValue = value.substring(10, 14);
1174
            //   }
1175
1176
              /*if(this.rangeFields[i][0] == this.rangeFields[i][1]) {
1177
                //console.log(selectedFromValue + " - "+selectedToValue);
1178
                if (selectedFromValue && selectedToValue) {
1179
                  let equalityOp = this.fieldIdsMap[filterId].equalityOperator;
1180
                  fq += (fq.length > 0 ? " " + filterOp + " " : "") + this.rangeFields[i][0] + equalityOp + "\"" + selectedFromValue + " " + selectedToValue + "\"";
1181
                  fq = "&fq=" + StringUtils.URIEncode(fq);
1182
                } else if (selectedFromValue) {
1183
                  let equalityOp = this.fieldIdsMap[this.rangeFields[i][0]].equalityOperator;
1184
                  if(equalityOp == " = ") {
1185
                    equalityOp = " >= ";
1186
                  }
1187
                  fq += (fq.length > 0 ? " " + filterOp + " " : "") + this.rangeFields[i][0] + equalityOp + "\"" + selectedFromValue + "\"";
1188
                  fq = "&fq=" + StringUtils.URIEncode(fq);
1189
                } else if (selectedToValue) {
1190
                  let equalityOp = this.fieldIdsMap[this.rangeFields[i][1]].equalityOperator;
1191
                  if(equalityOp == " = ") {
1192
                    equalityOp = " <= ";
1193
                  }
1194
                  fq += (fq.length > 0 ? " " + filterOp + " " : "") + this.rangeFields[i][0] + equalityOp + "\"" + selectedToValue + "\"";
1195
                  fq = "&fq=" + StringUtils.URIEncode(fq);
1196
                }
1197
              } else {
1198
                let equalityOpFrom = this.fieldIdsMap[this.rangeFields[i][0]].equalityOperator;
1199
                let equalityOpTo = this.fieldIdsMap[this.rangeFields[i][1]].equalityOperator;
1200
1201
                if (selectedFromValue) {
1202
                  fq += (fq.length > 0 ? " " + filterOp + " " : "") + this.rangeFields[i][0] + equalityOpFrom + "\"" + selectedFromValue + "\"";
1203
                  // fq = "&fq=" + StringUtils.URIEncode(fq);
1204
                }
1205
                if (selectedToValue) {
1206
                  fq += (fq.length > 0 ? " " + filterOp + " " : "") + this.rangeFields[i][1] + equalityOpTo + "\"" + selectedToValue + "\"";
1207
                  // fq = "&fq=" + StringUtils.URIEncode(fq);
1208
                }
1209
                if(selectedFromValue || selectedToValue) {
1210
                  fq = "&fq=" + StringUtils.URIEncode(fq);
1211
                }
1212
              }*/
1213
              fq = NewSearchPageComponent.createRangeFilterQuery(this.rangeFields[i], selectedFromValue, selectedToValue, this.fieldIdsMap[filterId].equalityOperator, this.fieldIdsMap[this.rangeFields[i][0]].equalityOperator, this.fieldIdsMap[this.rangeFields[i][1]].equalityOperator, filterOp );
1214
            }
1215
          }
1216
        }
1217
        allFqs += fq +fqFrom + fqTo;
1218
      }
1219
    }
1220
1221
    return allFqs;
1222
1223
  }
1224
  // createRangeFilterQuery(this.rangeFields[i], selectedFromValue, selectedToValue, this.fieldIdsMap[this.rangeFields[i][0]].equalityOperator, this.fieldIdsMap[this.rangeFields[i][1]].equalityOperator; filterOp )
1225
public static createRangeFilterQuery(rangeField,selectedFromValue, selectedToValue, equalityOp, equalityOpFrom, equalityOpTo, filterOp ){
1226
    let fq="";
1227
  if(rangeField[0] == rangeField[1]) {
1228
    //console.log(selectedFromValue + " - "+selectedToValue);
1229
    if (selectedFromValue && selectedToValue) {
1230
      fq += (fq.length > 0 ? " " + filterOp + " " : "") + rangeField[0] + equalityOp + "\"" + selectedFromValue + " " + selectedToValue + "\"";
1231
      fq = "&fq=" + StringUtils.URIEncode(fq);
1232
    } else if (selectedFromValue) {
1233
      if(equalityOpFrom == " = ") {
1234
        equalityOpFrom = " >= ";
1235
      }
1236
      fq += (fq.length > 0 ? " " + filterOp + " " : "") + rangeField[0] + equalityOpFrom + "\"" + selectedFromValue + "\"";
1237
      fq = "&fq=" + StringUtils.URIEncode(fq);
1238
    } else if (selectedToValue) {
1239
      if(equalityOpTo == " = ") {
1240
        equalityOpTo = " <= ";
1241
      }
1242
      fq += (fq.length > 0 ? " " + filterOp + " " : "") + rangeField[0] + equalityOpTo + "\"" + selectedToValue + "\"";
1243
      fq = "&fq=" + StringUtils.URIEncode(fq);
1244
    }
1245
  } else {
1246
1247
    if (selectedFromValue) {
1248
      fq += (fq.length > 0 ? " " + filterOp + " " : "") + rangeField[0] + equalityOpFrom + "\"" + selectedFromValue + "\"";
1249
      // fq = "&fq=" + StringUtils.URIEncode(fq);
1250
    }
1251
    if (selectedToValue) {
1252
      fq += (fq.length > 0 ? " " + filterOp + " " : "") + rangeField[1] + equalityOpTo + "\"" + selectedToValue + "\"";
1253
      // fq = "&fq=" + StringUtils.URIEncode(fq);
1254
    }
1255
    if(selectedFromValue || selectedToValue) {
1256
      fq = "&fq=" + StringUtils.URIEncode(fq);
1257
    }
1258
1259
  }
1260
  return fq;
1261
}
1262
  /**
1263
   * Sets parameterNames and parameterValues arrays
1264
   * used in paging, advanced search link, Goto()
1265
   * @param filters either query filters or filters defined by the URL parameters
1266
   * @param rangeFilters defined by the URL parameters
1267
   * @param includePage
1268
   */
1269
  buildPageURLParameters(filters:Filter[], rangeFilters: RangeFilter[], includePage: boolean) {
1270
    this.parameterNames.splice(0, this.parameterNames.length);
1271
    this.parameterValues.splice(0, this.parameterValues.length);
1272
    for (var i = 0; i < this.selectedFields.length; i++) {
1273
      //default operator is and
1274
      if((this.selectedFields[i].value && this.selectedFields[i].value.length > 0) || this.selectedFields[i].type == "date") {
1275
        this.parameterNames.push("f" + i);
1276
        this.parameterValues.push(this.selectedFields[i].id + (this.selectedFields[i].operatorId != 'and' ? ("," + this.selectedFields[i].operatorId) : ''));
1277
        this.parameterNames.push("fv" + i);
1278
      }
1279
      if (this.selectedFields[i].type == "date") {
1280
1281
        if (this.selectedFields[i].dateValue.type == "range") {
1282
          this.parameterValues.push(StringUtils.URIEncode("range" + Dates.getDateToString(this.selectedFields[i].dateValue.from) + ":" + Dates.getDateToString(this.selectedFields[i].dateValue.to)));
1283
        } else {
1284
          this.parameterValues.push(StringUtils.URIEncode(this.selectedFields[i].dateValue.type));
1285
        }
1286
1287
      } else if(this.selectedFields[i].value && this.selectedFields[i].value.length > 0) {
1288
        // console.log(this.selectedFields[i].value +" " + StringUtils.URIEncode(this.selectedFields[i].value))
1289
        this.parameterValues.push(StringUtils.URIEncode(this.selectedFields[i].value));
1290
      }
1291
    }
1292
    if (includePage && this.searchUtils.page != 1) {
1293
      this.parameterNames.push("page");
1294
      this.parameterValues.push("" + this.searchUtils.page);
1295
    }
1296
1297
    //if (this.searchUtils.size != this.resultsPerPage) {
1298
    if (this.resultsPerPageChanged && this.searchUtils.size != this.resultsPerPageChanged) {
1299
      this.parameterNames.push("size");
1300
      //this.parameterValues.push("" + this.searchUtils.size);
1301
      this.parameterValues.push("" + this.resultsPerPageChanged);
1302
    }
1303
1304
    //if (this.sort && this.searchUtils.sortBy) {
1305
    if (this.sort && this.sortedByChanged && this.sortedByChanged.length > 0) {
1306
      this.parameterNames.push("sortBy");
1307
      //this.parameterValues.push(this.searchUtils.sortBy);
1308
      this.parameterValues.push(this.sortedByChanged);
1309
    }
1310
    if (this.resultTypes && (this.entityType == 'publication' || this.entityType == 'dataset' || this.entityType == 'software' || this.entityType == 'other' || this.entityType == "result")) {
1311
      let values = [];
1312
      for(let value of this.resultTypes.values){
1313
        if(value.selected) {
1314
          values.push(value.id);
1315
        }
1316
      }
1317
      this.selectedTypesNum = 0;
1318
      if (values.length > 0 && values.length != 4) {
1319
        this.parameterNames.push("type");
1320
        this.parameterValues.push(values.join(","));
1321
        this.selectedTypesNum = values.length;
1322
      }
1323
      //
1324
      /*      if(this.quickFilter) {
1325
              this.parameterNames.push("qf");
1326
              this.parameterValues.push("" + this.quickFilter.selected);
1327
            }*/
1328
    }
1329
    for (let filter of filters) {
1330
      var filterLimits = "";
1331
      if (filter.countSelectedValues > 0) {
1332
        for (let value of filter.values) {
1333
          if (value.selected == true) {
1334
            filterLimits += ((filterLimits.length == 0) ? '' : ',') + '"' + StringUtils.URIEncode(value.id) + '"';
1335
          }
1336
        }
1337
        if (filterLimits.length > 0) {
1338
          this.parameterNames.push(filter.filterId);
1339
          this.parameterValues.push(filterLimits);
1340
        }
1341
      }
1342
    }
1343
    for (let filter of rangeFilters) {
1344
      var filterLimits = "";
1345
      let yearFrom: string = (Dates.isValidYear(filter.selectedFromValue) ? filter.selectedFromValue : null);
1346
      let yearTo: string = (Dates.isValidYear(filter.selectedToValue) ? filter.selectedToValue : null);
1347
      if(yearFrom || yearTo) {
1348
        this.parameterNames.push(filter.filterId);
1349
        this.parameterValues.push("range" + (yearFrom ? yearFrom : "") + ":" + (yearTo ? yearTo : ""));
1350
      }
1351
      // if (filter.countSelectedValues > 0) {
1352
      //   for (let value of filter.values) {
1353
      //     if (value.selected == true) {
1354
      //       filterLimits += ((filterLimits.length == 0) ? '' : ',') + '"' + (value.id) + '"';
1355
      //     }
1356
      //   }
1357
      //   if (filterLimits.length > 0) {
1358
      //     this.parameterNames.push(filter.filterId);
1359
      //     this.parameterValues.push(filterLimits);
1360
      //   }
1361
      // }
1362
    }
1363
    if (this.searchUtils.keyword.length > 0) {
1364
      this.parameterNames.push("keyword");
1365
      this.parameterValues.push(this.searchUtils.keyword);
1366
    }
1367
1368
1369
    if(this.customFilterEnabled){
1370
      this.parameterNames.push("cf");
1371
      this.parameterValues.push("true");
1372
    }
1373
    // if (this.searchUtils.size != this.resultsPerPage) {
1374
    //   // allLimits += ((allLimits.length == 0) ? '?' : '&') + 'size=' + this.searchUtils.size;
1375
    //   this.parameterNames.push("size");
1376
    //   this.parameterValues.push("" + this.searchUtils.size);
1377
    // }
1378
    // if (this.sort && this.searchUtils.sortBy) {
1379
    //   // allLimits += ((allLimits.length == 0) ? '?' : '&') + 'sortBy=' + this.searchUtils.sortBy;
1380
    //   this.parameterNames.push("sortBy");
1381
    //   this.parameterValues.push(this.searchUtils.sortBy);
1382
    // }
1383
    // console.log(this.parameterNames)
1384
    // console.log(this.parameterValues)
1385
  }
1386
1387
  /**
1388
   * create filters based on URL params
1389
   * @param URLparams
1390
   */
1391
  getRefineFiltersFromURL(URLparams) {
1392
    let fields = new SearchFields();
1393
    let filters: Filter[] = [];
1394
    for (let i = 0; i < this.refineFields.length; i++) {
1395
      let filterId = this.refineFields[i];
1396
      if (URLparams[filterId] != undefined) {
1397
        let filter = new Filter();
1398
        filter.title = fields.getFieldName(filterId, this.entityType);
1399
        filter.filterId = filterId;
1400
        filter.originalFilterId = filterId;
1401
        filter.values = [];
1402
        let values = StringUtils.URIDecode(URLparams[filterId]).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
1403
        for (let value of values) {
1404
1405
          let v: Value = new Value();
1406
          v.name = RefineResultsUtils.keepPartAfterCharacters(StringUtils.unquote(value), "||");
1407
          v.name = (v.name.indexOf("::")!=-1)?v.name.substring(v.name.indexOf("::")+2).split("::").join("|"):v.name; // for funding streams
1408
          v.id = StringUtils.unquote(value);
1409
          v.selected = true;
1410
          filter.values.push(v);
1411
          // console.log(v)
1412
          filter.countSelectedValues++;
1413
        }
1414
        filters.push(filter)
1415
      }
1416
    }
1417
1418
/*    if (this.quickFilter) {
1419
      if (this.entityType == "result" && (URLparams[this.quickFilter.filterId] == undefined) && (URLparams["qf"] == undefined || URLparams["qf"] == "true")) {
1420
        let filter = new Filter();
1421
        filter.title = fields.getFieldName(this.quickFilter.filterId, this.entityType);
1422
        filter.filterId = this.quickFilter.filterId;
1423
        filter.originalFilterId = this.quickFilter.filterId;
1424
        filter.values = [];
1425
        let v: Value = new Value();
1426
        v.name = this.quickFilter.value;
1427
        v.id = this.quickFilter.value;
1428
        v.selected = true;
1429
        filter.values.push(v);
1430
        filter.countSelectedValues = 1;
1431
        filters.push(filter)
1432
      }
1433
    }*/
1434
    if ((this.entityType == 'publication' || this.entityType == 'dataset' || this.entityType == 'software' || this.entityType == 'other' || this.entityType == "result")) {
1435
      this.resultTypes = {values:[],filterId:"type", countSelectedValues: 0, filterType: 'checkbox', originalFilterId: "", valueIsExact: true, title: "Result Types",filterOperator:"or"};
1436
      if (URLparams["type"]) {
1437
        let types = URLparams["type"];
1438
        types = Array.isArray(types) ? types.join(',').split(","):types.split(",");
1439
        for(let type of types){
1440
          if(["publications", "datasets","software", "other"].indexOf(StringUtils.unquote(type))!=-1 && this.resultTypeOptions[StringUtils.unquote(type)]){
1441
            this.resultTypes.values.push({name: this.resultTypeOptions[StringUtils.unquote(type)].name , id:StringUtils.unquote(type),selected:true, number:0});
1442
            this.resultTypes.countSelectedValues++;
1443
            }
1444
          }
1445
1446
      }
1447
1448
    }
1449
1450
    this.URLCreatedFilters = filters;
1451
  }
1452
1453
  /**
1454
   * create range filters based on URL params
1455
   * @param URLparams
1456
   */
1457
  getRangeFiltersFromURL(URLparams) {
1458
    let fields = new SearchFields();
1459
    let filters: RangeFilter[] = [];
1460
    for (let i = 0; i < this.rangeFields.length; i++) {
1461
      let filterId = this.rangeFields[i][0]+"-range-"+this.rangeFields[i][1];
1462
      let filterParam = fields.getFieldParam(filterId, this.entityType);
1463
      //console.log("rangeFilter (from url): filterId - filterParam");
1464
      //console.log(filterId + " - "+ filterParam);
1465
      if (URLparams[filterParam] != undefined) {
1466
        let filter = new RangeFilter();
1467
        filter.title = fields.getFieldName(filterId, this.entityType);
1468
        filter.filterId = filterParam;
1469
        filter.originalFilterIdFrom = this.rangeFields[i][0];
1470
        filter.originalFilterIdTo = this.rangeFields[i][1];
1471
1472
1473
        let values = (decodeURIComponent(URLparams[filterParam])).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
1474
        for (let j = 0; j < values.length; j++) {
1475
          if (this.fieldIdsMap[filterId].filterType == "range") {
1476
            let value: string = StringUtils.unquote(values[j]);
1477
            let validDates: boolean = true;
1478
            // if (value.length < 14) {
1479
            //   validDates = false;
1480
            // } else {
1481
            //   if (!Dates.isValidYear(value.substring(5, 9)) || !Dates.isValidYear(value.substring(10, 14))) {
1482
            //     validDates = false;
1483
            //   } else {
1484
            //     filter.selectedFromValue = value.substring(5, 9);
1485
            //     filter.selectedToValue = value.substring(10, 14);
1486
            //   }
1487
            // }
1488
            let years: string[] = (value.substring(5)).split(":");
1489
            let yearFrom: string = (Dates.isValidYear(years[0]) ? years[0] : null);
1490
            let yearTo: string = (Dates.isValidYear(years[1]) ? years[1] : null);
1491
            //console.log("getRangeFiltersFromURL: yearFrom: " + yearFrom + " - yearTo: "+yearTo);
1492
            if(yearFrom) {
1493
              filter.selectedFromValue = yearFrom;
1494
              //filter.selectedFromAndToValues = yearFrom;
1495
            }
1496
            /*if(yearFrom && yearTo) {
1497
              filter.selectedFromAndToValues += "-";
1498
            }*/
1499
            if(yearTo) {
1500
              filter.selectedToValue = yearTo;
1501
              //filter.selectedFromAndToValues += yearTo;
1502
            }
1503
            //console.log("filter.selectedFromAndToValues: "+filter.selectedFromAndToValues);
1504
            if(!yearFrom && !yearTo) {
1505
              validDates = false;
1506
            }
1507
1508
          }
1509
        }
1510
        //console.log(filters);
1511
        filters.push(filter)
1512
      }
1513
    }
1514
    // console.log("Empty Filters");
1515
    // console.log(filters);
1516
    this.URLCreatedRangeFilters = filters;
1517
    // return filters;
1518
1519
  }
1520
1521
  /**
1522
   * Checks if query has no results, display Filters from URL parameters
1523
   * Mark checked  the selected filters
1524
   * Count the checked
1525
   * @param filters
1526
   */
1527
  public prepareFiltersToShow(filters: Filter[], totalResults): Filter[] {
1528
    if (this.URLCreatedFilters.length > 0 && totalResults == 0) {
1529
      this.showUnknownFilters = true;
1530
      this.filters = this.URLCreatedFilters;
1531
    } else if (totalResults != 0) {
1532
      this.showUnknownFilters = false;
1533
      this.filters = filters;
1534
    }else if((this.URLCreatedFilters.length == 0 && totalResults == 0)){
1535
      this.showUnknownFilters = true;
1536
      this.filters = filters;
1537
    }
1538
1539
    this.buildPageURLParameters(this.URLCreatedFilters, this.URLCreatedRangeFilters, true);
1540
    //this.checkSelectedRangeFilters(this.rangeFilters);
1541
1542
    this.checkSelectedFilters(this.filters);
1543
    this.countSelectedFilters(this.filters);
1544
    this.updateMeta(this.pageTitle)
1545
    return this.filters;
1546
  }
1547
1548
  /**
1549
   * Mark checked  the selected range filters
1550
   */
1551
  public prepareRangeFiltersToShow() {
1552
    this.rangeFilters = RangeFilter.parse(this.rangeFields, this.entityType); // OK
1553
1554
    //this.buildPageURLRangeParameters(this.rangeFilters, true);
1555
    this.checkSelectedRangeFilters(this.rangeFilters);
1556
    this.countSelectedRangeFilters(this.rangeFilters);
1557
    return this.rangeFilters;
1558
  }
1559
1560
  /**
1561
   * Used to set the variables and search page, and prepare it before the getResults query
1562
   * @param fieldIds
1563
   * @param selectedFields
1564
   * @param refineFields
1565
   * @param rangeFields
1566
   * @param fieldIdsMap
1567
   * @param customFilter
1568
   * @param params
1569
   * @param entityType
1570
   * @param quickFilter
1571
   */
1572
  prepareSearchPage(fieldIds, selectedFields, refineFields, rangeFields, fieldIdsMap, customFilter, params, entityType, quickFilter=null){
1573
    // console.log(this.refineFields);
1574
    this.entityType = entityType;
1575
    this.fieldIds = fieldIds;
1576
    this.selectedFields = selectedFields;
1577
    this.refineFields = refineFields;
1578
    this.rangeFields = rangeFields;
1579
    this.fieldIdsMap = fieldIdsMap;
1580
    this.customFilter = customFilter;
1581
    this.quickFilter = quickFilter;
1582
    this.getRangeFiltersFromURL(params);
1583
    this.getRefineFiltersFromURL(params);
1584
    this.createAdvancedSearchSelectedFiltersFromURLParameters(params);
1585
  }
1586
1587
  removeResultType(type){
1588
    for(let value of this.resultTypes.values){
1589
      if(type == value.id && value.selected){
1590
        value.selected = false;
1591
        this.goTo(1);
1592
        break;
1593
      }
1594
    }
1595
  }
1596
}