Project

General

Profile

1
import {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

    
25
declare var UIkit: any;
26

    
27
@Component({
28
  selector: 'new-search-page',
29
  templateUrl: 'newSearchPage.component.html'
30
})
31
export class NewSearchPageComponent {
32
  @ViewChild('offcanvas_element') offcanvasElement: ElementRef;
33

    
34
  @Input() piwikSiteId = null;
35
  @Input() hasPrefix: boolean = true;
36
  @Input() pageTitle = "";
37
  @Input() results = [];
38
  @Input() type;
39
  @Input() entityType;
40
  @Input() searchUtils: SearchUtilsClass = new SearchUtilsClass();
41
  @Input() fieldIds: string[];
42
  @Input() fieldIdsMap;//:{ [key:string]:{ name:string, operator:string, type:string, indexField:string, equalityOperator:string  }} ;
43
  @Input() selectedFields: AdvancedField[];
44
  @ViewChild(ModalLoading) loading: ModalLoading;
45
  @Input() csvParams: string;
46
  @Input() csvPath: string;
47
  @Input() simpleSearchLink: string = "";
48
  @Input() advancedSearchLink: string = "";
49
  @Input() disableForms: boolean = false;
50
  @Input() loadPaging: boolean = true;
51
  @Input() oldTotalResults: number = 0;
52
  @Input() openaireLink: string;
53
  @Input() customFilter: SearchCustomFilter;
54
  @Input() sort: boolean = true;
55
  @Input() searchFormClass: string = "searchForm";
56
  //From simple:
57
  @Input() rangeFilters: RangeFilter[] = [];
58
  @Input() rangeFields: string[][] = [];
59
  @Input() refineFields = [];
60
  @Input() filters = [];
61
  selectedFilters: number = 0;
62
  selectedRangeFilters: number = 0;
63
  private searchFieldsHelper: SearchFields = new SearchFields();
64
  @Input() newQueryButton: boolean = true;
65
  public showUnknownFilters: boolean = false; // when a filter exists in query but has no results, so no filters returned from the query
66
  URLCreatedFilters: Filter[] = [];
67
  URLCreatedRangeFilters: RangeFilter[] = [];
68
  @Input() showRefine: boolean = true;
69
  @Input() tableViewLink: string;
70
  @Input() usedBy: string = "search";
71
  @Input() public zenodoInformation: ZenodoInformationClass = new ZenodoInformationClass();
72
  @Input() showLastIndex: boolean = true;
73
  @Input() showResultCount: boolean = true;
74
  @Input() showMoreFilterValuesInline: boolean = true;
75
  @Input() filterValuesNum: number = 6;
76
  @Input() keywordFields = [];
77
  @Input() simpleView: boolean = true;
78
  @Input() formPlaceholderText = "Type Keywords...";
79
  @Input() resultTypes = null;
80
  resultTypeOptions = [{"id":"publication", "name":"Publications"},{"id":"dataset", "name":"Research data"},
81
    {"id":"software", "name":"Software"},{"id":"other", "name":" Other research products"}];
82
  selectedTypesNum = 0;
83
  @Input() quickFilter: { filter: Filter, selected: boolean, filterId: string, value: string };
84
  @Input() includeOnlyResultsAndFilter:boolean = false;
85
  @Input() showBreadcrumb:boolean = false;
86
  @Input() lastIndex: boolean = true;
87
  public dashboard: boolean = properties.isDashboard;
88

    
89
  piwiksub: any;
90
  public parameterNames: string[] = [];
91
  public parameterValues: string[] = [];
92

    
93
  public csvLimit: number = 0;
94
  public pagingLimit: number = 0;
95
  public resultsPerPage: number = 0;
96
  isPiwikEnabled = false;
97
  properties: EnvProperties;
98
  public pageContents = null;
99
  public divContents = null;
100
  public routerHelper: RouterHelper = new RouterHelper();
101
  public errorCodes: ErrorCodes = new ErrorCodes();
102
  breadcrumbs:Breadcrumb[] = [];
103
  url = null;
104

    
105
  @Input() entitiesSelection:boolean = true;
106
  @Input() showAdvancedSearchLink:boolean = true;
107

    
108
  //Dashboard
109
  filterToggle = false;
110
  customFilterEnabled:boolean =  false;
111
  constructor(private route: ActivatedRoute,
112
              private location: Location,
113
              private _meta: Meta,
114
              private _title: Title,
115
              private _piwikService: PiwikService,
116
              private router: Router,
117
              private seoService: SEOService,
118
              private helper: HelperService) {
119
  }
120

    
121
  ngOnInit() {
122
    this.route.data
123
      .subscribe((data: { envSpecific: EnvProperties }) => {
124
        this.properties = data.envSpecific;
125
        //this.getDivContents();
126
        this.getPageContents();
127
        this.pagingLimit = data.envSpecific.pagingLimit;
128
        this.resultsPerPage = data.envSpecific.resultsPerPage;
129
        this.csvLimit = data.envSpecific.csvLimit;
130
        this.isPiwikEnabled = data.envSpecific.enablePiwikTrack;
131
        if (typeof window !== 'undefined') {
132
          this.updateUrl(data.envSpecific.baseLink + location.pathname);
133
          this.url = data.envSpecific.baseLink + location.pathname
134
        }
135
        if (typeof document !== 'undefined' && this.isPiwikEnabled) {
136
          this.piwiksub = this._piwikService.trackView(this.properties, this.pageTitle, this.piwikSiteId).subscribe();
137
        }
138
      });
139
    this.route.queryParams.subscribe(params => {
140
      if (params['page'] && params['page']!=1) {
141
        HelperFunctions.scrollToId("searchForm");
142
      }
143
      this.customFilterEnabled = params['cf'] && params['cf'] == "true";
144
    });
145
    var description = "Openaire, search, repositories, open access, type, content provider, funder, project, " + this.pageTitle;
146

    
147
    this.updateTitle(this.pageTitle);
148
    this.updateDescription(description);
149

    
150
    this.searchUtils.baseUrl = "/" + this.searchUtils.baseUrl;
151
    this.seoService.createLinkForCanonicalURL(this.properties.baseLink + this.router.url, false);
152
    this.breadcrumbs.push({name: 'home', route: '/'});
153
    if(this.simpleView) {
154
      this.breadcrumbs.push( {name: "Search", route: null});
155
    }else if(!this.simpleView && this.advancedSearchLink) {
156
      this.breadcrumbs.push({name: "Advanced Search", route: null});
157
    }
158
  }
159

    
160
  private getPageContents() {
161
    if((this.customFilter && this.customFilter.queryFieldName == "communityId") && this.properties.adminToolsCommunity !== "monitor") {
162
      this.helper.getPageHelpContents(this.properties, (this.customFilter) ? this.customFilter.valueId : this.properties.adminToolsCommunity, this.router.url).subscribe(contents => {
163
        this.pageContents = contents;
164
      });
165
    }
166
  }
167

    
168
  private getDivContents() {
169
    if((this.customFilter && this.customFilter.queryFieldName == "communityId") && this.properties.adminToolsCommunity !== "monitor") {
170
      this.helper.getDivHelpContents(this.properties, (this.customFilter) ? this.customFilter.valueId : this.properties.adminToolsCommunity, this.router.url).subscribe(contents => {
171
        this.divContents = contents;
172
      });
173
    }
174
  }
175

    
176
  ngOnDestroy() {
177
    if (this.piwiksub) {
178
      this.piwiksub.unsubscribe();
179
    }
180
  }
181

    
182
  updateDescription(description: string) {
183
    this._meta.updateTag({content: description}, "name='description'");
184
    this._meta.updateTag({content: description}, "property='og:description'");
185
  }
186

    
187
  updateTitle(title: string) {
188
    var _prefix = "";
189
    if (this.hasPrefix) {
190
      _prefix = "OpenAIRE | ";
191
    }
192
    var _title = _prefix + ((title.length > 50) ? title.substring(0, 50) : title);
193
    this._title.setTitle(_title);
194
    this._meta.updateTag({content: _title}, "property='og:title'");
195
  }
196

    
197
  updateUrl(url: string) {
198
    this._meta.updateTag({content: url}, "property='og:url'");
199
  }
200

    
201

    
202
  clearFilters() {
203
    for (var i = 0; i < this.filters.length; i++) {
204
      for (var j = 0; j < this.filters[i].countSelectedValues; j++) {
205
        if (this.filters[i].values[j].selected) {
206
          this.filters[i].values[j].selected = false;
207
        }
208
        this.filters[i].countSelectedValues = 0;
209
      }
210
    }
211
    this.selectedFilters = 0;
212
    for(let i = 0; i < this.rangeFilters.length; i++) {
213
      this.rangeFilters[i].selectedFromValue = null;
214
      this.rangeFilters[i].selectedToValue = null;
215
    }
216
    this.selectedRangeFilters = 0;
217
    if (this.quickFilter) {
218
      this.removeValueFromQuickFilter();
219
    }
220
    this.goTo(1);
221
    // this.clearKeywords();
222
  }
223

    
224
  goTo(page: number = 1, scroll:boolean = true) {
225
    if(this.properties.isDashboard && this.filterToggle){
226
      this.filterToggle=false;
227
    }
228
    if(this.offcanvasElement) {
229
      UIkit.offcanvas(this.offcanvasElement.nativeElement).hide();
230
    }
231

    
232
    this.searchUtils.page = page;
233
    this.buildPageURLParameters(this.filters, this.rangeFilters, true);
234
    this.router.navigate([this.searchUtils.baseUrl], {queryParams: this.routerHelper.createQueryParams(this.parameterNames, this.parameterValues)});
235
    if(scroll) {
236
      HelperFunctions.scrollToId("searchForm");
237
    }
238
    /* Code For Piwik*/
239
    if (typeof localStorage !== 'undefined') {
240
      //console.log("In PreviousRouteRecorder : "+this.router.url );
241
      localStorage.setItem('previousRoute', this.router.url);
242
    }
243
    if (this.isPiwikEnabled && (typeof document !== 'undefined')) {
244
      this.piwiksub = this._piwikService.trackView(this.properties, this.pageTitle, this.piwikSiteId).subscribe();
245
    }
246
    /* End Piwik Code */
247
  }
248

    
249
  queryChanged() {
250

    
251
    this.goTo(1, false);
252
  }
253

    
254

    
255
  sizeChanged($event) {
256
    this.searchUtils.size = $event.value;
257
    this.goTo(1);
258
  }
259

    
260
  sortByChanged($event) {
261
    this.searchUtils.sortBy = $event.value;
262
    this.goTo(1);
263
  }
264

    
265

    
266
  getOperatorParameter(parameter: string): string {
267
    for (let id of this.fieldIds) {
268
      if (this.fieldIdsMap[id]["param"] == parameter) {
269
        return this.fieldIdsMap[id]["operator"];
270
      }
271
    }
272
  }
273

    
274
  /*
275
* Get A sub-array of this.refineFields array, which contains the ids of the selected filters
276
*/
277
  public getSelectedFilters(): string[] {
278
    var selected: string[] = [];
279
    var filters= (this.filters.length > 0)?this.filters:this.URLCreatedFilters;
280
    for (var i = 0; i < filters.length; i++) {
281
      var filter: Filter = filters[i];
282
      if (filter.countSelectedValues > 0) {
283
        selected.push(filter.filterId);
284
      }
285
    }
286
    return selected;
287
  }
288

    
289
  /*
290
    * Get A sub-array of this.refineFields array, which contains the ids of the selected parameters
291
    */
292
  private getSelectedParameters(): string[] {
293
    var selected: string[] = [];
294
    for (var i = 0; i < this.refineFields.length; i++) {
295
      if (this.parameterNames.indexOf(this.refineFields[i]) != -1) {
296
        selected.push(this.refineFields[i]);
297
      }
298
    }
299
    return selected;
300
  }
301

    
302
  /*
303
  * 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 )
304
  */
305
  public getFields(): string[] {
306
    var selected_filters: string[] = this.getSelectedFilters();
307
    if (selected_filters.length == 0) {
308
      selected_filters = this.getSelectedParameters();
309
    }
310
    var fields: string[] = [];
311
    for (var i = 0; i < this.refineFields.length; i++) {
312
      var dependentTo = this.searchFieldsHelper.DEPENDENT_FIELDS[this.refineFields[i]];
313

    
314
      //if filter is not marked as hidden OR it is hidden but it is dependent to a field that it IS selected
315
      if (this.searchFieldsHelper.HIDDEN_FIELDS.indexOf(this.refineFields[i]) == -1 || (selected_filters.indexOf(dependentTo) != -1) || (selected_filters.indexOf(this.refineFields[i]) != -1)) {
316
        fields.push(this.refineFields[i]);
317
      }
318
    }
319
    return fields;
320
  }
321

    
322
  /*
323
  * Get a query  string of all fields, that want to get from search (e.g. &fields=funderid&fields=projectstartyear&...))
324
  */
325
  public getRefineFieldsQuery(): string {
326

    
327
    var fields: string[] = this.getFields();
328
    var fieldsStr = ""
329
    for (var i = 0; i < fields.length; i++) {
330
      fieldsStr += "&fields=" + fields[i];
331
    }
332
    return "&refine=true" + fieldsStr;
333
  }
334

    
335

    
336
  /*
337
  * Mark as check the new filters that are selected, when you get them from search
338
  */
339
  public checkSelectedFilters(filters: Filter[]) {
340
    this.filters = filters;
341
    for (var i = 0; i < filters.length; i++) {
342
      var filter: Filter = filters[i];
343
      filter.countSelectedValues = 0;
344
      if (this.parameterNames.indexOf(filter.filterId) != -1) {
345
        let values = (decodeURIComponent(this.parameterValues[this.parameterNames.indexOf(filter.filterId)])).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
346
        for (let filterValue of filter.values) {
347
          if (values.indexOf(StringUtils.quote(filterValue.id)) > -1) {
348
            filterValue.selected = true;
349
            filter.countSelectedValues++;
350
          } else {
351
            filterValue.selected = false;
352

    
353
          }
354
        }
355
      } else if (this.quickFilter && this.quickFilter.filterId == filter.filterId && this.quickFilter.selected) {
356
        for (let filterValue of filter.values) {
357
          if (filterValue.id == this.quickFilter.value) {
358
            filterValue.selected = true;
359
            filter.countSelectedValues++;
360
          } else {
361
            filterValue.selected = false;
362
          }
363
        }
364
      } else {
365
        for (let filterValue of filter.values) {
366
          filterValue.selected = false;
367
        }
368
      }
369
      if (this.quickFilter && filter.filterId == this.quickFilter.filterId) {
370
        this.quickFilter.filter = filter;
371
      }
372
    }
373
    this.filterFilterValues(this.filters);
374
    return filters;
375
  }
376

    
377
  /*
378
* Mark as check the new range filters that are selected
379
*/
380
  public checkSelectedRangeFilters(filters: RangeFilter[]) {
381
    //console.log("checkSelectedRangeFilters: parameterNames.length: "+this.parameterNames.length);
382

    
383
    this.rangeFilters = filters;
384
    for (let i = 0; i < filters.length; i++) {
385
      let filter: RangeFilter = filters[i];
386

    
387
      if (this.parameterNames.indexOf(filter.filterId) != -1) {
388
        //console.log(filter.filterId + " "+this.parameterNames.indexOf(filter.filterId) );
389
        let values = (decodeURIComponent(this.parameterValues[this.parameterNames.indexOf(filter.filterId)])).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
390
        let operators: string [] = (StringUtils.URIDecode(this.parameterValues[this.parameterNames.indexOf(filter.filterId)])).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
391
        if (values.length == operators.length) {
392
          for (let j = 0; j < values.length; j++) {
393
            if (this.fieldIdsMap[filter.originalFilterIdFrom+"-range-"+filter.originalFilterIdTo].filterType == "range") {
394
              let value: string = StringUtils.unquote(values[j]);
395
              let validDates: boolean = true;
396

    
397
              let years: string[] = (value.substring(5)).split(":");
398
              let yearFrom: string = (Dates.isValidYear(years[0]) ? years[0] : null);
399
              let yearTo: string = (Dates.isValidYear(years[1]) ? years[1] : null);
400
              //console.log("checkSelectedRangeFilters: yearFrom: " + yearFrom + " - yearTo: "+yearTo);
401
              if(yearFrom) {
402
                filter.selectedFromValue = yearFrom;
403
              }
404
              if(yearTo) {
405
                filter.selectedToValue = yearTo;
406
              }
407
              if(yearFrom && yearTo) {
408
                filter.selectedFromAndToValues = yearFrom + "-" + yearTo;
409
              } else if(yearFrom) {
410
                filter.selectedFromAndToValues = "From " + yearFrom;
411
              } else if(yearTo) {
412
                filter.selectedFromAndToValues = "Until " + yearTo;
413
              }
414

    
415
              if(!yearFrom && !yearTo) {
416
                validDates = false;
417
              }
418

    
419
              // if (value.length < 14) {
420
              //   validDates = false;
421
              //   console.log("not valid (length<14)");
422
              // } else {
423
              //   if (!Dates.isValidYear(value.substring(5, 9)) || !Dates.isValidYear(value.substring(10, 14))) {
424
              //     validDates = false;
425
              //     console.log("not valid years");
426
              //   } else {
427
              //     filter.selectedFromValue = value.substring(5, 9);
428
              //     filter.selectedToValue = value.substring(10, 14);
429
              //     console.log(filter);
430
              //   }
431
              // }
432
            }
433
          }
434
        }
435
      } else {
436
        filter.selectedFromValue = null;
437
        filter.selectedToValue = null;
438
      }
439
    }
440
    return this.rangeFilters;
441
  }
442

    
443
  /*
444
  * For Funder filters - if funder selected
445
  */
446
  public filterFilterValues(filters: Filter[]) {
447
    var funders = [];
448
    var funder_prefix = [];
449
    for (var i = 0; i < filters.length; i++) {
450

    
451
      var filter: Filter = filters[i];
452
      //  console.log(filter.filterId);
453
      if (filter.filterId.indexOf("funder") != -1 && this.parameterNames.indexOf(filter.filterId) != -1) {
454
        let funders = (decodeURIComponent(this.parameterValues[this.parameterNames.indexOf(filter.filterId)])).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
455
        for (let funder of funders) {
456
          funder_prefix.push(StringUtils.unquote(funder).split("____")[0]);
457
        }
458
        //  console.log(funder_prefix );
459
      } else if (filter.filterId.indexOf("funding") != -1) {
460
        //  console.log(" funding: "+filter.filterId );
461
        var filteredValues = []
462
        for (let filterValue of filter.values) {
463
          var value_prefix = filterValue.id.split("____")[0];
464
          //  console.log("Value prefix: "+value_prefix );
465
          if (funder_prefix.indexOf(value_prefix) != -1) {
466
            //  console.log("here" + value_prefix);
467
            filteredValues.push(filterValue);
468
          }
469

    
470
        }
471
        if (filteredValues.length > 0) {
472
          filter.values = filteredValues;
473
        }
474
      }
475

    
476
    }
477

    
478
    return filters;
479
  }
480

    
481
  public countSelectedFilters(filters: Filter[]): number {
482
    this.selectedFilters = 0;
483
    for (let filter of filters) {
484
      if (filter.countSelectedValues > 0) {
485
        this.selectedFilters += filter.countSelectedValues;
486
      }
487
    }
488
    return this.selectedFilters;
489
  }
490

    
491
  public countSelectedRangeFilters(rangeFilters: RangeFilter[]) : number {
492
    this.selectedRangeFilters = 0;
493
    for(let filter of rangeFilters) {
494
      if(filter.selectedFromValue || filter.selectedToValue) {
495
        this.selectedRangeFilters++;
496
      }
497
    }
498
    return this.selectedRangeFilters;
499
  }
500

    
501
  private clearKeywords() {
502
    if (this.searchUtils.keyword.length > 0) {
503
      this.searchUtils.keyword = '';
504
    }
505
    this.goTo(1);
506
  }
507

    
508
  public removeFilter(value: Value, filter: Filter) {
509
    filter.countSelectedValues--;
510
    this.selectedFilters--;
511
    if (value.selected == true) {
512
      value.selected = false;
513
    }
514
    if (this.quickFilter && this.quickFilter.filterId == filter.filterId) {
515
      this.removeValueFromQuickFilter();
516
    }
517
    this.goTo(1);
518
  }
519

    
520
  public removeRangeFilter(filter: RangeFilter) {
521
    filter.selectedFromValue = null;
522
    filter.selectedToValue = null;
523
    this.goTo(1);
524
  }
525

    
526
  getSelectedValues(filter): any {
527
    var selected = [];
528
    if (filter.countSelectedValues > 0) {
529
      for (var i = 0; i < filter.values.length; i++) {
530
        if (filter.values[i].selected) {
531
          selected.push(filter.values[i]);
532
        }
533
      }
534
    }
535
    return selected;
536

    
537
  }
538

    
539
  filterChanged($event) {
540
    if (this.quickFilter && this.quickFilter.filter) {
541
      this.removeValueFromQuickFilter();
542
    }
543
    this.goTo(1);
544

    
545
  }
546

    
547
  /**
548
   * if there is a change in the values of the quick filter, this function has to be run, to also update the quickFilter
549
   */
550
  removeValueFromQuickFilter() {
551
    if (this.quickFilter.filter.countSelectedValues == 0) {
552
      this.quickFilter.selected = false;
553
    } else {
554
      let isQuickEnabled = false;
555
      for (let filterValue of this.quickFilter.filter.values) {
556
        isQuickEnabled = (filterValue.name == this.quickFilter.value)
557
      }
558
      this.quickFilter.selected = (isQuickEnabled && this.quickFilter.filter.countSelectedValues == 1);
559
    }
560
  }
561

    
562
  // for loading
563
  public openLoading() {
564
    this.loading.open();
565
  }
566

    
567
  public closeLoading() {
568
    this.loading.close();
569
  }
570

    
571
  /**
572
   * Build advanced search Filters based on the URL parameters
573
   * @param params
574
   */
575
  createAdvancedSearchSelectedFiltersFromNewURLParameters(params) {
576
    for (let i = 0; i < Object.keys(params).length; i++) {
577
      if(params["f"+i] && params["fv"+i]   ) {
578
        let fieldId = params["f" + i].split(",")[0];
579
        let operator = (params["f" + i].split(",").length  >1 )?params["f" + i].split(",")[1]:"and";
580
        let fieldparam = (this.fieldIdsMap[fieldId]) ? this.fieldIdsMap[fieldId].param : "";
581

    
582
        if (!this.fieldIdsMap[fieldId]) {
583
          console.error("Field: " + fieldId + " not found in fieldIds map");
584
          continue;
585
        }
586
        let value: string = StringUtils.URIDecode(params["fv"+i]);
587
        if (this.fieldIdsMap[fieldId].type == "date") {
588
            let validDates: boolean = true;
589
            let dateField: AdvancedField = new AdvancedField(fieldId, fieldparam, this.fieldIdsMap[fieldId].name, this.fieldIdsMap[fieldId].type, value, operator);
590
            if (value.indexOf("range") != -1) {
591
              dateField.dateValue.type = "range";
592
              if (value.length < 26) {
593
                validDates = false;
594
              } else {
595
                if (!Dates.isValidDate(value.substring(5, 15)) || !Dates.isValidDate(value.substring(16, 26))) {
596
                  validDates = false;
597
                } else {
598
                  dateField.dateValue.from = Dates.getDateFromString(value.substring(5, 15));
599
                  dateField.dateValue.to = Dates.getDateFromString(value.substring(16, 26));
600
                }
601
              }
602
              //  "rangeYYYY-MM-DD:YYYY-MM-DD"
603
            } else {
604
              dateField.dateValue.setDatesByType(value);
605
            }
606
            if (validDates) {
607
              this.selectedFields.push(dateField);
608
            }
609

    
610
          } else {
611
            this.selectedFields.push(new AdvancedField(fieldId, fieldparam, this.fieldIdsMap[fieldId].name, this.fieldIdsMap[fieldId].type,value, operator));
612
          }
613

    
614
        }
615
      }
616
  }
617
  /**
618
   * Build advanced search Filters based on the URL parameters
619
   * @param params
620
   */
621
  createAdvancedSearchSelectedFiltersFromURLParameters(params) {
622
    this.createAdvancedSearchSelectedFiltersFromNewURLParameters(params);
623
    for (var i = 0; i < this.fieldIds.length; i++) {
624
      var fieldId = this.fieldIds[i];
625
      var fieldparam = (this.fieldIdsMap[fieldId]) ? this.fieldIdsMap[fieldId].param : "";
626
      if (!this.fieldIdsMap[fieldId]) {
627
        console.error("Field: " + fieldId + " not found in fieldIds map");
628
        continue;
629
      }
630

    
631
      var operatorId = this.getOperatorParameter(fieldparam);
632
      if (params[fieldparam] != undefined && params[operatorId] != undefined) {
633
        var values: string [] = StringUtils.URIDecode(params[fieldparam]).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
634
        var operators: string [] = (StringUtils.URIDecode(params[operatorId])).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
635
        if (values.length == operators.length) {
636
          for (var j = 0; j < values.length; j++) {
637
            if (this.fieldIdsMap[fieldId].type == "date") {
638
              var value: string = StringUtils.unquote(values[j]);
639
              var validDates: boolean = true;
640
              var dateField: AdvancedField = new AdvancedField(fieldId, fieldparam, this.fieldIdsMap[fieldId].name, this.fieldIdsMap[fieldId].type, value, operators[j]);
641
              if (value.indexOf("range") != -1) {
642
                dateField.dateValue.type = "range";
643
                if (value.length < 26) {
644
                  validDates = false;
645
                } else {
646
                  if (!Dates.isValidDate(value.substring(5, 15)) || !Dates.isValidDate(value.substring(16, 26))) {
647
                    validDates = false;
648
                  } else {
649
                    dateField.dateValue.from = Dates.getDateFromString(value.substring(5, 15));
650
                    dateField.dateValue.to = Dates.getDateFromString(value.substring(16, 26));
651
                  }
652
                }
653
                //  "rangeYYYY-MM-DD:YYYY-MM-DD"
654
              } else {
655
                dateField.dateValue.setDatesByType(value);
656
              }
657
              if (validDates) {
658
                this.selectedFields.push(dateField);
659
              }
660

    
661
            } else {
662
              this.selectedFields.push(new AdvancedField(fieldId, fieldparam, this.fieldIdsMap[fieldId].name, this.fieldIdsMap[fieldId].type, values[j], operators[j]));
663
            }
664
          }
665
        }
666
      }
667
    }
668
    if (params['keyword'] && params['keyword'].length > 0) {
669
      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"));
670
    }
671
    if (this.selectedFields.length == 0) {
672
      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"));
673
    }
674
  }
675

    
676
  /**
677
   * Create Search API query based on the selected fields of the advanced form
678
   */
679
  getSearchAPIQueryForAdvancedSearhFields() {
680

    
681
    var params = "";
682
    var countParams = 0;
683
    for (var i = 0; i < this.selectedFields.length; i++) {
684
      if (this.fieldIdsMap[this.selectedFields[i].id] != undefined && (this.selectedFields[i].value != "" || this.selectedFields[i].type == "date")) {
685
        //console.log("createQueryParameters::"+this.selectedFields[i].type);
686
        if (this.selectedFields[i].type == "date") {
687
          if (this.selectedFields[i].dateValue.type != "any") {
688
            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)) + " "
689
              + StringUtils.URIEncode(Dates.getDateToString(this.selectedFields[i].dateValue.to)) + '"' + " ";
690
          }
691
        } else {
692
          if (this.selectedFields[i].id == "q") {
693
            // console.log(this.selectedFields[i].value)
694
/*            var op = "";
695
            var doisParams = "";
696
            if ((this.entityType == 'publication' || this.entityType == 'dataset' || this.entityType == 'software' || this.entityType == 'other' || this.entityType == "result")) {
697
              var DOIs: Identifier[] = Identifier.getIdentifiersFromString(this.selectedFields[i].value);
698
              for (let identifier of DOIs) {
699
                // console.log(identifier)
700
                // pidclassid exact \"doi\" and pid exact \"10.1016/j.nima.2015.11.134\"
701
                //and (authorid exact \"0000-0001-7291-3210 \" )"
702
                if(identifier.class == "ORCID"){
703
                  doisParams += (doisParams.length > 0 ? " or " : "") +'(authorid="' + identifier.id + '")';
704
                }else{
705
                  doisParams += (doisParams.length > 0 ? " or " : "") +'(pidclassid exact "' + identifier.class + '" and pid="' +  identifier.id + '")';
706
                }
707
              }
708
            }
709
            if (doisParams.length > 0) {
710
              params += this.createQuotedKeywordQuery(this.selectedFields[i].value, this.selectedFields[i].id, this.selectedFields[i].operatorId ,countParams,true, true) + " or " + doisParams;
711
            } else {
712
              params += this.createQuotedKeywordQuery(this.selectedFields[i].value, this.selectedFields[i].id, this.selectedFields[i].operatorId,countParams,true);
713
            }*/
714
            params += NewSearchPageComponent.createKeywordQuery(this.entityType,this.selectedFields[i].value, this.selectedFields[i].id, this.selectedFields[i].operatorId, countParams);
715
            //TODO deposit case
716
            // console.log(this.usedBy)
717
            // console.log(this.keywordFields)
718

    
719
            if(this.usedBy == "deposit") {
720

    
721
              if(this.keywordFields.length > 0) {
722
                params += " or ("
723
              }
724
              for(let j=0; j< this.keywordFields.length ; j++) {
725
                if(j > 0) {
726
                  params += " or "
727
                }
728
                params += NewSearchPageComponent.createQuotedKeywordQuery(this.selectedFields[i].value, this.keywordFields[j].name, " or ", countParams,false);
729
                // let field = this.keywordFields[i];
730
                //keywordQuery += field.name+field.equalityOperator+StringUtils.URIEncode(keyword);
731
                // params += field.name+field.equalityOperator+StringUtils.quote(StringUtils.URIEncode(keyword));
732
              }
733
              if(this.keywordFields.length > 0) {
734
                params += " ) "
735
              }
736
            }
737

    
738
          } else if (countParams == 0 && this.selectedFields[i].operatorId == "not" && this.fieldIdsMap[this.selectedFields[i].id].equalityOperator != "=") {
739
            params += " " + this.selectedFields[i].id + " <> " + '"' + StringUtils.URIEncode(this.selectedFields[i].value) + '"' + " ";
740
          } else if(this.fieldIdsMap[this.selectedFields[i].id].equalityOperator == "=") {
741
            params+=NewSearchPageComponent.createQuotedKeywordQuery(this.selectedFields[i].value, this.selectedFields[i].id, this.selectedFields[i].operatorId, countParams, false);
742
          }else{
743
              params += (countParams == 0 ? "" : " " + this.selectedFields[i].operatorId + " ") + this.selectedFields[i].id + this.fieldIdsMap[this.selectedFields[i].id].equalityOperator + '"' + encodeURIComponent(this.selectedFields[i].value) + '"' + " ";
744

    
745
          }
746
        }
747
        countParams++;
748
      }
749
    }
750

    
751
    // console.log("ParameterS:")
752
    // console.log(params)
753
    return params;
754
  }
755
  public static createKeywordQuery(entityType:string, value:string, id, operatorId, countParams=0){
756
    let params = "";
757
    let doisParams = "";
758
    var DOIs: Identifier[] = Identifier.getIdentifiersFromString(value);
759
    if ((entityType == 'publication' || entityType == 'dataset' || entityType == 'software' || entityType == 'other' || entityType == "result")) {
760
      for (let identifier of DOIs) {
761
        // console.log(identifier)
762
        // pidclassid exact \"doi\" and pid exact \"10.1016/j.nima.2015.11.134\"
763
        //and (authorid exact \"0000-0001-7291-3210 \" )"
764
        if(identifier.class == "ORCID"){
765
          doisParams += (doisParams.length > 0 ? " or " : "") +'(authorid="' + identifier.id + '")';
766
        }else{
767
          doisParams += (doisParams.length > 0 ? " or " : "") +'(pidclassid exact "' + identifier.class + '" and pid="' +  identifier.id + '")';
768
        }
769
      }
770
    }
771
    if (doisParams.length > 0) {
772
      params += "(" + this.createQuotedKeywordQuery(value, id, operatorId ,countParams,true, true) + " or " + doisParams+")";
773
    } else {
774
      //if it is PIDs but no doisquery produced, forced to use quotes as the query will fail due to special characters
775
      params += this.createQuotedKeywordQuery(value, id, operatorId,countParams,true,
776
        (DOIs.length > 0 && doisParams.length == 0) );
777
    }
778
    return params;
779

    
780
  }
781
  private static createQuotedKeywordQuery(fieldValue, fieldId, fieldOperator, countParams:number, isSearchAll:boolean, forceQuotted:boolean=false){
782
    let params = "";
783
    let countQuote = (fieldValue.match(/'/g) || []).length;
784
    let countDoubleQuote = (fieldValue.match(/"/g) || []).length;
785
    let quotedParts = [];
786
    if(countQuote % 2 == 0 && countDoubleQuote % 2 ==0){
787
      quotedParts = (fieldValue)?fieldValue.match(/(["'])(.*?)*?\1/g):[];
788
    }
789
    params+= (countParams == 0 ? "" : fieldOperator);
790
    params+=   " (";
791
    if(forceQuotted){
792
      return this.getQuotedQueryPart(fieldId, '"'+ fieldValue+'"',isSearchAll);
793
    }
794
    if(quotedParts && quotedParts.length == 1 && quotedParts[0] == fieldValue ){
795
      params+=this.getQuotedQueryPart(fieldId, fieldValue,isSearchAll);
796
    }else if( quotedParts && quotedParts.length > 0){
797
      for(let i=0; i< quotedParts.length; i++){
798
        params+=(i>0)?" and ":"";
799
        params+=this.getQuotedQueryPart(fieldId, quotedParts[i],isSearchAll);
800
      }
801
      let startPoint = 0;
802
      let endPoint = 0;
803
      for(let i=0; i< quotedParts.length; i++){
804
        let index = fieldValue.indexOf(quotedParts[i]);
805
        endPoint = (i+1<quotedParts.length)? fieldValue.indexOf(quotedParts[i+1]):fieldValue.length;
806
        // console.log(fieldValue.indexOf(quotedParts[i+1]) +" - "+fieldValue.length);
807
        // console.log(" SP "+ startPoint+" EP: "+endPoint);
808
        if(index==startPoint){
809
          startPoint +=quotedParts[i].length;
810
        }else if(startPoint < index){
811
          endPoint = index;
812
        }
813
        // console.log(" SP "+ startPoint+" EP: "+endPoint);
814
        if(decodeURIComponent(fieldValue.substring(startPoint,endPoint)).split(" ").join("").length > 0) {
815
          params += " and " + this.getNoQuotedQueryPart(fieldId, fieldValue.substring(startPoint, endPoint), isSearchAll);
816
        }
817
        // console.log("For "+i+"  " +params+" SP "+ startPoint+" EP: "+endPoint);
818
        // startPoint = (i+1<quotedParts.length)? fieldValue.indexOf(quotedParts[i+i]):fieldValue.length;//(startPoint<index  )?(index + quotedParts[i].length):fieldValue.length;
819
        startPoint = ((i+1<quotedParts.length)?(fieldValue.indexOf(quotedParts[i+1])+quotedParts[i+1].length):(endPoint== index?(index+quotedParts[i].length):endPoint));
820
      }
821
      if(startPoint !=fieldValue.length && decodeURIComponent(fieldValue.substring(startPoint,fieldValue.length)).split(" ").join("").length > 0){
822
        params+=" and " + this.getNoQuotedQueryPart(fieldId, fieldValue.substring(startPoint,fieldValue.length),isSearchAll);
823
      }
824
    }else{
825
      params+=this.getNoQuotedQueryPart(fieldId, fieldValue,isSearchAll);
826
    }
827
    params += ")";
828
    return params;
829
  }
830

    
831
  private static getQuotedQueryPart(fieldId:string, value:string,  isSearchAll:boolean){
832
      return (isSearchAll?"__all":fieldId)+" exact "+StringUtils.URIEncode(value);
833
  }
834
  private static getNoQuotedQueryPart(fieldId:string, value:string,  isSearchAll:boolean){
835
    if(isSearchAll){
836
      return StringUtils.URIEncode(value);
837
    }else{
838
      return fieldId+"="+ StringUtils.URIEncode(value);
839
    }
840
  }
841

    
842
  /**
843
   * Create Search API query based on the filters of refine fields
844
   * @param URLparams
845
   * @param firstLoad
846
   */
847
  getSearchAPIQueryForRefineFields(URLparams, firstLoad: boolean) {
848

    
849
    var allFqs = "";
850
    // console.log(this.refineFields)
851
    for (var i = 0; i < this.refineFields.length; i++) {
852
      var filterId = this.refineFields[i];
853

    
854
      if (URLparams[filterId] != undefined) {
855
        let values = (StringUtils.URIDecode(StringUtils.URIDecode(URLparams[filterId]))).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
856
        var countvalues = 0;
857
        var fq = "";
858
        let filterOp: string = this.searchFieldsHelper.getFieldOperator(filterId);
859
        // console.info(filterId, filterOp);
860
        for (let value of values) {
861
          countvalues++;
862
          var paramId = this.fieldIdsMap[filterId].param;
863
          // parameters+='&' + paramId+ '='+ value;//+"&" + this.fieldIdsMap[paramId].operator + "="+((countvalues == 1)?"and":"or");
864
          fq += (fq.length > 0 ? " " + filterOp + " " : "") + filterId + " exact " + (value);
865
        }
866
        if (countvalues > 0) {
867
          fq = "&fq=" + StringUtils.URIEncode(fq);
868
        }
869
        allFqs += fq;
870
      }
871
    }
872
    this.customFilterEnabled = URLparams["cf"] == "true";
873
    if(this.customFilter && (this.customFilter.isHiddenFilter || (this.refineFields.indexOf(this.customFilter.queryFieldName) == -1 && this.customFilterEnabled))){
874
      allFqs += "&fq=" + StringUtils.URIEncode(this.customFilter.queryFieldName + " exact " + StringUtils.quote((this.customFilter.valueId)));
875
    }
876

    
877
    if (this.quickFilter && this.entityType == "result") {
878
      if((firstLoad && URLparams[this.quickFilter.filterId] == undefined && URLparams["qf"] == undefined)   || URLparams["qf"] == "true"
879
        || ((URLparams[this.quickFilter.filterId] != undefined && StringUtils.URIDecode(URLparams[this.quickFilter.filterId]).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1).indexOf(StringUtils.quote(this.quickFilter.value)) != -1))) {
880
        this.quickFilter.selected = true;
881
      } else {
882
        this.quickFilter.selected = false;
883
      }
884
      if ((firstLoad && URLparams[this.quickFilter.filterId] == undefined && URLparams["qf"] == undefined)
885
      ||( URLparams[this.quickFilter.filterId] == undefined && URLparams["qf"] == "true")) {
886
        allFqs += "&fq=resultbestaccessright exact " + StringUtils.quote(this.quickFilter.value);
887
      }
888
    }
889

    
890
    if (this.entityType == "result") {
891
      if (URLparams["type"]) {
892
        let types = URLparams["type"].split(",");
893
        if(types.indexOf("publications")!=-1 && types.indexOf("datasets")!=-1 && types.indexOf("software")!=-1 && types.indexOf("other")!=-1 ){
894
          allFqs += "&type=results";
895
        }else{
896
          for (let type of types) {
897
            allFqs += "&type=" + type;
898
          }
899
        }
900
      }else{
901
        allFqs += "&type=results";
902
      }
903
    } else if (this.entityType == "publication") {
904
      allFqs += "&type=publications";
905
    } else if (this.entityType == "dataset") {
906
      allFqs += "&type=datasets";
907
    } else if (this.entityType == "software") {
908
      allFqs += "&type=software";
909
    } else if (this.entityType == "other") {
910
      allFqs += "&type=other";
911
    } else if(this.entityType == "project") {
912
      allFqs += "&type=projects";
913
    } else if(this.entityType == "organization") {
914
      allFqs += "&type=organizations";
915
    } else if(this.entityType == "dataprovider") {
916
      allFqs += "&type=datasources";
917
    }
918
    // console.log("AllFqs (check type): "+allFqs);
919
    // console.log("type: "+this.entityType);
920
    // var keyword = URLparams['keyword'];
921
    // var doiQuery = "";
922
    // var keywordQuery = "";
923
    // if((keyword && keyword.length > 0)){
924
    //   if((this.type == 'publications' ||this.type == 'research data' || this.type == 'software' || this.type == 'other research products')){
925
    //     var DOIs:string[] = DOI.getDOIsFromString(keyword);
926
    //     var doisParams = "";
927
    //
928
    //     for(var i =0 ;i < DOIs.length; i++){
929
    //       doisParams+=(doisParams.length > 0?"&":"")+'doi="'+ DOIs[i]+'"';
930
    //     }
931
    //     if(doisParams.length > 0){
932
    //       doiQuery += "&"+doisParams;
933
    //     }else {
934
    //       keywordQuery += "&q="+StringUtils.URIEncode(keyword);
935
    //     }
936
    //   }else{
937
    //     if(this.usedBy == "deposit") {
938
    //       if(this.keywordFields.length > 0) {
939
    //         keywordQuery = "&fq=";
940
    //       }
941
    //
942
    //       for(let i=0; i< this.keywordFields.length ; i++) {
943
    //         if(i > 0) {
944
    //           keywordQuery += " or ";
945
    //         }
946
    //         let field = this.keywordFields[i];
947
    //         //keywordQuery += field.name+field.equalityOperator+StringUtils.URIEncode(keyword);
948
    //         keywordQuery += field.name+field.equalityOperator+StringUtils.quote(StringUtils.URIEncode(keyword));
949
    //       }
950
    //     } else {
951
    //       keywordQuery += "&q=" + StringUtils.URIEncode(keyword);
952
    //     }
953
    //
954
    //   }
955
    // }
956
    //TODO add DOI?
957
     return allFqs;
958

    
959
  }
960

    
961
  /**
962
   * Create Search API query based on the filters of refine fields
963
   * @param URLparams
964
   */
965
  getSearchAPIQueryForRangeFields(URLparams) {
966
    let allFqs = "";
967
    for (let i = 0; i < this.rangeFields.length; i++) {
968
      let filterId = this.rangeFields[i][0]+"-range-"+this.rangeFields[i][1];
969
      let filterParam = this.searchFieldsHelper.getFieldParam(filterId, this.entityType);
970

    
971
      if (URLparams[filterParam] != undefined) {
972
        let values = (StringUtils.URIDecode(StringUtils.URIDecode(URLparams[filterParam]))).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
973
        var countvalues = 0;
974
        var fq = "";
975
        var fqFrom = "";
976
        var fqTo = "";
977
        let filterOp: string = this.searchFieldsHelper.getFieldOperator(filterId);
978

    
979
        for (let value of values) {
980
          if (this.fieldIdsMap[filterId].filterType == "range") {
981

    
982
            let selectedFromValue;
983
            let selectedToValue;
984

    
985
            let years: string[] = (value.substring(5)).split(":");
986
            let yearFrom: string = (Dates.isValidYear(years[0]) ? years[0] : null);
987
            //(Number.isInteger(parseInt(years[0], 10)) ? years[0] : null);
988
            let yearTo: string = (Dates.isValidYear(years[1]) ? years[1] : null);
989
            //console.log("getSearchAPIQueryForRangeFields: yearFrom: " + yearFrom + " - yearTo: "+yearTo);
990
            if(yearFrom) {
991
              selectedFromValue = yearFrom;
992
            }
993
            if(yearTo) {
994
              selectedToValue = yearTo;
995
            }
996
            if(yearFrom || yearTo) {
997

    
998
            // if (value.length <= 14) {
999
            //   if(Dates.isValidYear(value.substring(5, 9))) {
1000
            //     selectedFromValue = value.substring(5, 9);
1001
            //   }
1002
            //   if(Dates.isValidYear(value.substring(10, 14))) {
1003
            //     selectedToValue = value.substring(10, 14);
1004
            //   }
1005

    
1006
              /*if(this.rangeFields[i][0] == this.rangeFields[i][1]) {
1007
                //console.log(selectedFromValue + " - "+selectedToValue);
1008
                if (selectedFromValue && selectedToValue) {
1009
                  let equalityOp = this.fieldIdsMap[filterId].equalityOperator;
1010
                  fq += (fq.length > 0 ? " " + filterOp + " " : "") + this.rangeFields[i][0] + equalityOp + "\"" + selectedFromValue + " " + selectedToValue + "\"";
1011
                  fq = "&fq=" + StringUtils.URIEncode(fq);
1012
                } else if (selectedFromValue) {
1013
                  let equalityOp = this.fieldIdsMap[this.rangeFields[i][0]].equalityOperator;
1014
                  if(equalityOp == " = ") {
1015
                    equalityOp = " >= ";
1016
                  }
1017
                  fq += (fq.length > 0 ? " " + filterOp + " " : "") + this.rangeFields[i][0] + equalityOp + "\"" + selectedFromValue + "\"";
1018
                  fq = "&fq=" + StringUtils.URIEncode(fq);
1019
                } else if (selectedToValue) {
1020
                  let equalityOp = this.fieldIdsMap[this.rangeFields[i][1]].equalityOperator;
1021
                  if(equalityOp == " = ") {
1022
                    equalityOp = " <= ";
1023
                  }
1024
                  fq += (fq.length > 0 ? " " + filterOp + " " : "") + this.rangeFields[i][0] + equalityOp + "\"" + selectedToValue + "\"";
1025
                  fq = "&fq=" + StringUtils.URIEncode(fq);
1026
                }
1027
              } else {
1028
                let equalityOpFrom = this.fieldIdsMap[this.rangeFields[i][0]].equalityOperator;
1029
                let equalityOpTo = this.fieldIdsMap[this.rangeFields[i][1]].equalityOperator;
1030

    
1031
                if (selectedFromValue) {
1032
                  fq += (fq.length > 0 ? " " + filterOp + " " : "") + this.rangeFields[i][0] + equalityOpFrom + "\"" + selectedFromValue + "\"";
1033
                  // fq = "&fq=" + StringUtils.URIEncode(fq);
1034
                }
1035
                if (selectedToValue) {
1036
                  fq += (fq.length > 0 ? " " + filterOp + " " : "") + this.rangeFields[i][1] + equalityOpTo + "\"" + selectedToValue + "\"";
1037
                  // fq = "&fq=" + StringUtils.URIEncode(fq);
1038
                }
1039
                if(selectedFromValue || selectedToValue) {
1040
                  fq = "&fq=" + StringUtils.URIEncode(fq);
1041
                }
1042
              }*/
1043
              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 );
1044
            }
1045
          }
1046
        }
1047
        allFqs += fq +fqFrom + fqTo;
1048
      }
1049
    }
1050

    
1051
    return allFqs;
1052

    
1053
  }
1054
  // createRangeFilterQuery(this.rangeFields[i], selectedFromValue, selectedToValue, this.fieldIdsMap[this.rangeFields[i][0]].equalityOperator, this.fieldIdsMap[this.rangeFields[i][1]].equalityOperator; filterOp )
1055
public static createRangeFilterQuery(rangeField,selectedFromValue, selectedToValue, equalityOp, equalityOpFrom, equalityOpTo, filterOp ){
1056
    let fq="";
1057
  if(rangeField[0] == rangeField[1]) {
1058
    //console.log(selectedFromValue + " - "+selectedToValue);
1059
    if (selectedFromValue && selectedToValue) {
1060
      fq += (fq.length > 0 ? " " + filterOp + " " : "") + rangeField[0] + equalityOp + "\"" + selectedFromValue + " " + selectedToValue + "\"";
1061
      fq = "&fq=" + StringUtils.URIEncode(fq);
1062
    } else if (selectedFromValue) {
1063
      if(equalityOpFrom == " = ") {
1064
        equalityOpFrom = " >= ";
1065
      }
1066
      fq += (fq.length > 0 ? " " + filterOp + " " : "") + rangeField[0] + equalityOpFrom + "\"" + selectedFromValue + "\"";
1067
      fq = "&fq=" + StringUtils.URIEncode(fq);
1068
    } else if (selectedToValue) {
1069
      if(equalityOpTo == " = ") {
1070
        equalityOpTo = " <= ";
1071
      }
1072
      fq += (fq.length > 0 ? " " + filterOp + " " : "") + rangeField[0] + equalityOpTo + "\"" + selectedToValue + "\"";
1073
      fq = "&fq=" + StringUtils.URIEncode(fq);
1074
    }
1075
  } else {
1076

    
1077
    if (selectedFromValue) {
1078
      fq += (fq.length > 0 ? " " + filterOp + " " : "") + rangeField[0] + equalityOpFrom + "\"" + selectedFromValue + "\"";
1079
      // fq = "&fq=" + StringUtils.URIEncode(fq);
1080
    }
1081
    if (selectedToValue) {
1082
      fq += (fq.length > 0 ? " " + filterOp + " " : "") + rangeField[1] + equalityOpTo + "\"" + selectedToValue + "\"";
1083
      // fq = "&fq=" + StringUtils.URIEncode(fq);
1084
    }
1085
    if(selectedFromValue || selectedToValue) {
1086
      fq = "&fq=" + StringUtils.URIEncode(fq);
1087
    }
1088

    
1089
  }
1090
  return fq;
1091
}
1092
  /**
1093
   * Sets parameterNames and parameterValues arrays
1094
   * used in paging, advanced search link, Goto()
1095
   * @param filters either query filters or filters defined by the URL parameters
1096
   * @param rangeFilters defined by the URL parameters
1097
   * @param includePage
1098
   */
1099
  buildPageURLParameters(filters:Filter[], rangeFilters: RangeFilter[], includePage: boolean) {
1100
    this.parameterNames.splice(0, this.parameterNames.length);
1101
    this.parameterValues.splice(0, this.parameterValues.length);
1102
    for (var i = 0; i < this.selectedFields.length; i++) {
1103
      //default operator is and
1104
      this.parameterNames.push("f"+i);
1105
      this.parameterValues.push(this.selectedFields[i].id + (this.selectedFields[i].operatorId!='and'?(","+this.selectedFields[i].operatorId):''));
1106
      this.parameterNames.push("fv"+i);
1107
      if (this.selectedFields[i].type == "date") {
1108

    
1109
        if (this.selectedFields[i].dateValue.type == "range") {
1110
          this.parameterValues.push(StringUtils.URIEncode("range" + Dates.getDateToString(this.selectedFields[i].dateValue.from) + ":" + Dates.getDateToString(this.selectedFields[i].dateValue.to)));
1111
        } else {
1112
          this.parameterValues.push(StringUtils.URIEncode(this.selectedFields[i].dateValue.type));
1113
        }
1114

    
1115
      } else {
1116
        // console.log(this.selectedFields[i].value +" " + StringUtils.URIEncode(this.selectedFields[i].value))
1117
        this.parameterValues.push(StringUtils.URIEncode(this.selectedFields[i].value));
1118
      }
1119
    }
1120
    if (includePage && this.searchUtils.page != 1) {
1121
      this.parameterNames.push("page");
1122
      this.parameterValues.push("" + this.searchUtils.page);
1123
    }
1124

    
1125
    if (this.searchUtils.size != this.resultsPerPage) {
1126
      this.parameterNames.push("size");
1127
      this.parameterValues.push("" + this.searchUtils.size);
1128
    }
1129

    
1130
    if (this.sort && this.searchUtils.sortBy) {
1131
      this.parameterNames.push("sortBy");
1132
      this.parameterValues.push(this.searchUtils.sortBy);
1133
    }
1134
    for (let filter of filters) {
1135
      var filterLimits = "";
1136
      if (filter.countSelectedValues > 0) {
1137
        for (let value of filter.values) {
1138
          if (value.selected == true) {
1139
            filterLimits += ((filterLimits.length == 0) ? '' : ',') + '"' + (value.id) + '"';
1140
          }
1141
        }
1142
        if (filterLimits.length > 0) {
1143
          this.parameterNames.push(filter.filterId);
1144
          this.parameterValues.push(filterLimits);
1145
        }
1146
      }
1147
    }
1148
    for (let filter of rangeFilters) {
1149
      var filterLimits = "";
1150
      let yearFrom: string = (Dates.isValidYear(filter.selectedFromValue) ? filter.selectedFromValue : null);
1151
      let yearTo: string = (Dates.isValidYear(filter.selectedToValue) ? filter.selectedToValue : null);
1152
      if(yearFrom || yearTo) {
1153
        this.parameterNames.push(filter.filterId);
1154
        this.parameterValues.push("range" + (yearFrom ? yearFrom : "") + ":" + (yearTo ? yearTo : ""));
1155
      }
1156
      // if (filter.countSelectedValues > 0) {
1157
      //   for (let value of filter.values) {
1158
      //     if (value.selected == true) {
1159
      //       filterLimits += ((filterLimits.length == 0) ? '' : ',') + '"' + (value.id) + '"';
1160
      //     }
1161
      //   }
1162
      //   if (filterLimits.length > 0) {
1163
      //     this.parameterNames.push(filter.filterId);
1164
      //     this.parameterValues.push(filterLimits);
1165
      //   }
1166
      // }
1167
    }
1168
    if (this.searchUtils.keyword.length > 0) {
1169
      this.parameterNames.push("keyword");
1170
      this.parameterValues.push(this.searchUtils.keyword);
1171
    }
1172

    
1173
    if (this.resultTypes && this.entityType == "result") {
1174
      let values = [];
1175
      if (this.resultTypes.publication) {
1176
        values.push("publications");
1177
      }
1178
      if (this.resultTypes.dataset) {
1179
        values.push("datasets");
1180
      }
1181
      if (this.resultTypes.software) {
1182
        values.push("software");
1183
      }
1184
      if (this.resultTypes.other) {
1185
        values.push("other");
1186
      }
1187
      this.selectedTypesNum = 0;
1188
      if (values.length > 0 && values.length != 4) {
1189
        this.parameterNames.push("type");
1190
        this.parameterValues.push(values.join(","));
1191
        this.selectedTypesNum = values.length;
1192
      }
1193
      if(this.quickFilter) {
1194
        this.parameterNames.push("qf");
1195
        this.parameterValues.push("" + this.quickFilter.selected);
1196
      }
1197
    }
1198
    if(this.customFilterEnabled){
1199
      this.parameterNames.push("cf");
1200
      this.parameterValues.push("true");
1201
    }
1202
    // if (this.searchUtils.size != this.resultsPerPage) {
1203
    //   // allLimits += ((allLimits.length == 0) ? '?' : '&') + 'size=' + this.searchUtils.size;
1204
    //   this.parameterNames.push("size");
1205
    //   this.parameterValues.push("" + this.searchUtils.size);
1206
    // }
1207
    // if (this.sort && this.searchUtils.sortBy) {
1208
    //   // allLimits += ((allLimits.length == 0) ? '?' : '&') + 'sortBy=' + this.searchUtils.sortBy;
1209
    //   this.parameterNames.push("sortBy");
1210
    //   this.parameterValues.push(this.searchUtils.sortBy);
1211
    // }
1212
    // console.log(this.parameterNames)
1213
    // console.log(this.parameterValues)
1214
  }
1215

    
1216
  /**
1217
   * create filters based on URL params
1218
   * @param URLparams
1219
   */
1220
  getRefineFiltersFromURL(URLparams) {
1221
    let fields = new SearchFields();
1222
    let filters: Filter[] = [];
1223
    for (let i = 0; i < this.refineFields.length; i++) {
1224
      let filterId = this.refineFields[i];
1225
      if (URLparams[filterId] != undefined) {
1226
        let filter = new Filter();
1227
        filter.title = fields.getFieldName(filterId, this.entityType);
1228
        filter.filterId = filterId;
1229
        filter.originalFilterId = filterId;
1230
        filter.values = [];
1231
        let values = StringUtils.URIDecode(URLparams[filterId]).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
1232
        for (let value of values) {
1233

    
1234
          let v: Value = new Value();
1235
          v.name = RefineResultsUtils.keepPartAfterCharacters(StringUtils.unquote(value), "||");
1236
          v.name = (v.name.indexOf("::")!=-1)?v.name.substring(v.name.indexOf("::")+2).split("::").join("|"):v.name; // for funding streams
1237
          v.id = StringUtils.unquote(value);
1238
          v.selected = true;
1239
          filter.values.push(v);
1240
          // console.log(v)
1241
          filter.countSelectedValues++;
1242
        }
1243
        filters.push(filter)
1244
      }
1245
    }
1246

    
1247
    if (this.quickFilter) {
1248
      if (this.entityType == "result" && (URLparams[this.quickFilter.filterId] == undefined) && (URLparams["qf"] == undefined || URLparams["qf"] == "true")) {
1249
        let filter = new Filter();
1250
        filter.title = fields.getFieldName(this.quickFilter.filterId, this.entityType);
1251
        filter.filterId = this.quickFilter.filterId;
1252
        filter.originalFilterId = this.quickFilter.filterId;
1253
        filter.values = [];
1254
        let v: Value = new Value();
1255
        v.name = this.quickFilter.value;
1256
        v.id = this.quickFilter.value;
1257
        v.selected = true;
1258
        filter.values.push(v);
1259
        filter.countSelectedValues = 1;
1260
        filters.push(filter)
1261
      }
1262
    }
1263
    if (this.entityType == "result") {
1264
      this.resultTypes = null;
1265
      this.resultTypes = {
1266

    
1267
      };
1268

    
1269
      if (URLparams["type"]) {
1270

    
1271
        this.resultTypes['publication'] = (URLparams["type"].split(",").indexOf("publications") != -1);
1272
        this.resultTypes['dataset'] = (URLparams["type"].split(",").indexOf("datasets") != -1);
1273
        this.resultTypes['software'] = (URLparams["type"].split(",").indexOf("software") != -1);
1274
        this.resultTypes['other'] = (URLparams["type"].split(",").indexOf("other") != -1);
1275

    
1276
      } else {
1277
        this.resultTypes['publication'] = false;
1278
        this.resultTypes['dataset'] = false;
1279
        this.resultTypes['software'] = false;
1280
        this.resultTypes['other'] = false;
1281
      }
1282

    
1283
    }
1284

    
1285
    this.URLCreatedFilters = filters;
1286
  }
1287

    
1288
  /**
1289
   * create range filters based on URL params
1290
   * @param URLparams
1291
   */
1292
  getRangeFiltersFromURL(URLparams) {
1293
    let fields = new SearchFields();
1294
    let filters: RangeFilter[] = [];
1295
    for (let i = 0; i < this.rangeFields.length; i++) {
1296
      let filterId = this.rangeFields[i][0]+"-range-"+this.rangeFields[i][1];
1297
      let filterParam = fields.getFieldParam(filterId, this.entityType);
1298
      //console.log("rangeFilter (from url): filterId - filterParam");
1299
      //console.log(filterId + " - "+ filterParam);
1300
      if (URLparams[filterParam] != undefined) {
1301
        let filter = new RangeFilter();
1302
        filter.title = fields.getFieldName(filterId, this.entityType);
1303
        filter.filterId = filterParam;
1304
        filter.originalFilterIdFrom = this.rangeFields[i][0];
1305
        filter.originalFilterIdTo = this.rangeFields[i][1];
1306

    
1307

    
1308
        let values = (decodeURIComponent(URLparams[filterParam])).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
1309
        for (let j = 0; j < values.length; j++) {
1310
          if (this.fieldIdsMap[filterId].filterType == "range") {
1311
            let value: string = StringUtils.unquote(values[j]);
1312
            let validDates: boolean = true;
1313
            // if (value.length < 14) {
1314
            //   validDates = false;
1315
            // } else {
1316
            //   if (!Dates.isValidYear(value.substring(5, 9)) || !Dates.isValidYear(value.substring(10, 14))) {
1317
            //     validDates = false;
1318
            //   } else {
1319
            //     filter.selectedFromValue = value.substring(5, 9);
1320
            //     filter.selectedToValue = value.substring(10, 14);
1321
            //   }
1322
            // }
1323
            let years: string[] = (value.substring(5)).split(":");
1324
            let yearFrom: string = (Dates.isValidYear(years[0]) ? years[0] : null);
1325
            let yearTo: string = (Dates.isValidYear(years[1]) ? years[1] : null);
1326
            //console.log("getRangeFiltersFromURL: yearFrom: " + yearFrom + " - yearTo: "+yearTo);
1327
            if(yearFrom) {
1328
              filter.selectedFromValue = yearFrom;
1329
              //filter.selectedFromAndToValues = yearFrom;
1330
            }
1331
            /*if(yearFrom && yearTo) {
1332
              filter.selectedFromAndToValues += "-";
1333
            }*/
1334
            if(yearTo) {
1335
              filter.selectedToValue = yearTo;
1336
              //filter.selectedFromAndToValues += yearTo;
1337
            }
1338
            //console.log("filter.selectedFromAndToValues: "+filter.selectedFromAndToValues);
1339
            if(!yearFrom && !yearTo) {
1340
              validDates = false;
1341
            }
1342

    
1343
          }
1344
        }
1345
        //console.log(filters);
1346
        filters.push(filter)
1347
      }
1348
    }
1349
    // console.log("Empty Filters");
1350
    // console.log(filters);
1351
    this.URLCreatedRangeFilters = filters;
1352
    // return filters;
1353

    
1354
  }
1355

    
1356
  /**
1357
   * Checks if query has no results, display Filters from URL parameters
1358
   * Mark checked  the selected filters
1359
   * Count the checked
1360
   * @param filters
1361
   */
1362
  public prepareFiltersToShow(filters: Filter[], totalResults): Filter[] {
1363
    if (this.URLCreatedFilters.length > 0 && totalResults == 0) {
1364
      this.showUnknownFilters = true;
1365
      this.filters = this.URLCreatedFilters;
1366
    } else if (totalResults != 0) {
1367
      this.showUnknownFilters = false;
1368
      this.filters = filters;
1369
    }else if((this.URLCreatedFilters.length == 0 && totalResults == 0)){
1370
      this.showUnknownFilters = true;
1371
      this.filters = filters;
1372
    }
1373
    this.buildPageURLParameters(this.URLCreatedFilters, this.URLCreatedRangeFilters, true);
1374
    //this.checkSelectedRangeFilters(this.rangeFilters);
1375

    
1376
    this.checkSelectedFilters(this.filters);
1377
    this.countSelectedFilters(this.filters);
1378
    return this.filters;
1379
  }
1380

    
1381
  /**
1382
   * Mark checked  the selected range filters
1383
   */
1384
  public prepareRangeFiltersToShow() {
1385
    this.rangeFilters = RangeFilter.parse(this.rangeFields, this.entityType); // OK
1386

    
1387
    //this.buildPageURLRangeParameters(this.rangeFilters, true);
1388
    this.checkSelectedRangeFilters(this.rangeFilters);
1389
    this.countSelectedRangeFilters(this.rangeFilters);
1390
    return this.rangeFilters;
1391
  }
1392

    
1393
  /**
1394
   * Used to set the variables and search page, and prepare it before the getResults query
1395
   * @param fieldIds
1396
   * @param selectedFields
1397
   * @param refineFields
1398
   * @param rangeFields
1399
   * @param fieldIdsMap
1400
   * @param customFilter
1401
   * @param params
1402
   * @param entityType
1403
   * @param quickFilter
1404
   */
1405
  prepareSearchPage(fieldIds, selectedFields, refineFields, rangeFields, fieldIdsMap, customFilter, params, entityType, quickFilter=null){
1406
    // console.log(this.refineFields);
1407
    this.entityType = entityType;
1408
    this.fieldIds = fieldIds;
1409
    this.selectedFields = selectedFields;
1410
    this.refineFields = refineFields;
1411
    this.rangeFields = rangeFields;
1412
    this.fieldIdsMap = fieldIdsMap;
1413
    this.customFilter = customFilter;
1414
    this.quickFilter = quickFilter;
1415
    this.getRangeFiltersFromURL(params);
1416
    this.getRefineFiltersFromURL(params);
1417
    this.createAdvancedSearchSelectedFiltersFromURLParameters(params);
1418
  }
1419

    
1420
  removeResultType(type){
1421
    if(this.resultTypes && this.resultTypes[type]){
1422
      this.resultTypes[type]=false;
1423
      this.goTo(1);
1424
    }
1425
  }
1426
}
(17-17/55)