Project

General

Profile

1
import {Component, EventEmitter, 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} from '../searchUtils/searchHelperClasses.class';
7
import {SearchCustomFilter, SearchUtilsClass} from './searchUtils.class';
8
import {ModalLoading} from '../../utils/modal/loading.component';
9
import {Dates, 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

    
18
@Component({
19
  selector: 'advanced-search-page',
20
  templateUrl: 'advancedSearchPage.component.html'
21
})
22
export class AdvancedSearchPageComponent {
23
  @Input() piwikSiteId = null;
24
  @Input() hasPrefix: boolean = true;
25
  @Input() pageTitle = "";
26
  @Input() results = [];
27
  @Input() type;
28
  @Input() entityType;
29
  @Input() searchUtils: SearchUtilsClass = new SearchUtilsClass();
30
  @Input() fieldIds: string[];
31
  @Input() fieldIdsMap;//:{ [key:string]:{ name:string, operator:string, type:string, indexField:string, equalityOperator:string  }} ;
32
  @Input() selectedFields: AdvancedField[];
33
  @Input() simpleSearchUrl: string;
34
  @ViewChild(ModalLoading) loading: ModalLoading;
35
  @Input() csvParams: string;
36
  @Input() csvPath: string;
37
  @Input() simpleSearchLink: string = "";
38
  @Input() disableForms: boolean = false;
39
  @Input() loadPaging: boolean = true;
40
  @Input() oldTotalResults: number = 0;
41
  @Input() openaireLink: string;
42
  @Input() customFilter: SearchCustomFilter = null;
43
  @Input() sort: boolean = false;
44
  @Input() searchFormClass: string = "searchForm";
45
  piwiksub: any;
46
  public parameterNames: string[] = [];
47
  public parameterValues: string[] = [];
48

    
49
  public baseURLWithParameters: string = '';
50

    
51
  public csvLimit: number = 0;
52
  public pagingLimit: number = 0;
53
  public resultsPerPage: number = 0;
54
  isPiwikEnabled = false;
55
  properties: EnvProperties;
56
  public pageContents = null;
57
  public divContents = null;
58
  public routerHelper: RouterHelper = new RouterHelper();
59
  public errorCodes: ErrorCodes = new ErrorCodes();
60

    
61
  url = null;
62

    
63
  constructor(private route: ActivatedRoute,
64
              private location: Location,
65
              private _meta: Meta,
66
              private _title: Title,
67
              private _piwikService: PiwikService,
68
              private router: Router,
69
              private seoService: SEOService,
70
              private helper: HelperService) {
71
  }
72

    
73
  ngOnInit() {
74
    this.route.data
75
      .subscribe((data: { envSpecific: EnvProperties }) => {
76
        this.properties = data.envSpecific;
77
        //this.getDivContents();
78
        this.getPageContents();
79
        this.pagingLimit = data.envSpecific.pagingLimit;
80
        this.resultsPerPage = data.envSpecific.resultsPerPage;
81
        this.csvLimit = data.envSpecific.csvLimit;
82
        this.isPiwikEnabled = data.envSpecific.enablePiwikTrack;
83
        if (typeof window !== 'undefined') {
84
          this.updateUrl(data.envSpecific.baseLink + location.pathname);
85
          this.url = data.envSpecific.baseLink + location.pathname
86
        }
87
        if (typeof document !== 'undefined' && this.isPiwikEnabled) {
88
          this.piwiksub = this._piwikService.trackView(this.properties, this.pageTitle, this.piwikSiteId).subscribe();
89
        }
90
      });
91

    
92
    var description = "Openaire, search, repositories, open access, type, content provider, funder, project, " + this.pageTitle;
93

    
94
    this.updateTitle(this.pageTitle);
95
    this.updateDescription(description);
96

    
97
    this.searchUtils.baseUrl = "/" + this.searchUtils.baseUrl;
98

    
99
    this.updateBaseUrlWithParameters();
100
    this.seoService.createLinkForCanonicalURL(this.properties.baseLink + this.router.url, false);
101

    
102

    
103
  }
104

    
105
  private getPageContents() {
106
    this.helper.getPageHelpContents(this.properties, (this.customFilter)?this.customFilter.valueId:null, this.router.url).subscribe(contents => {
107

    
108
      this.pageContents = contents;
109
    })
110
  }
111

    
112
  private getDivContents() {
113
    this.helper.getDivHelpContents(this.properties, (this.customFilter)?this.customFilter.valueId:null, this.router.url).subscribe(contents => {
114
      this.divContents = contents;
115
    })
116
  }
117

    
118
  ngOnDestroy() {
119
    if (this.piwiksub) {
120
      this.piwiksub.unsubscribe();
121
    }
122
  }
123

    
124
  updateDescription(description: string) {
125
    this._meta.updateTag({content: description}, "name='description'");
126
    this._meta.updateTag({content: description}, "property='og:description'");
127
  }
128

    
129
  updateTitle(title: string) {
130
    var _prefix = "";
131
    if(this.hasPrefix) {
132
      _prefix = "OpenAIRE | ";
133
    }
134
    var _title = _prefix + ((title.length > 50) ? title.substring(0, 50) : title);
135
    this._title.setTitle(_title);
136
    this._meta.updateTag({content: _title}, "property='og:title'");
137
  }
138

    
139
  updateUrl(url: string) {
140
    this._meta.updateTag({content: url}, "property='og:url'");
141
  }
142

    
143
  public getSelectedFiltersFromUrl(params) {
144
    for (var i = 0; i < this.fieldIds.length; i++) {
145

    
146
      var fieldId = this.fieldIds[i];
147
      var fieldparam = (this.fieldIdsMap[fieldId]) ? this.fieldIdsMap[fieldId].param : "";
148
      if (!this.fieldIdsMap[fieldId]) {
149

    
150
        console.error("Field: " + fieldId + " not found in fieldIds map");
151
      }
152

    
153
      var operatorId = this.getOperatorParameter(fieldparam);
154
      if (params[fieldparam] != undefined && params[operatorId] != undefined) {
155
        var values: string [] = StringUtils.URIDecode(params[fieldparam]).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
156
        var operators: string [] = (StringUtils.URIDecode(params[operatorId])).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
157
        if (values.length == operators.length) {
158
          for (var j = 0; j < values.length; j++) {
159
            if (this.fieldIdsMap[fieldId].type == "date") {
160
              var value: string = StringUtils.unquote(values[j]);
161
              var validDates: boolean = true;
162
              var dateField: AdvancedField = new AdvancedField(fieldId, fieldparam, this.fieldIdsMap[fieldId].name, this.fieldIdsMap[fieldId].type, value, operators[j]);
163
              if (value.indexOf("range") != -1) {
164
                dateField.dateValue.type = "range";
165
                if (value.length < 26) {
166
                  validDates = false;
167
                } else {
168
                  if (!Dates.isValidDate(value.substring(5, 15)) || !Dates.isValidDate(value.substring(16, 26))) {
169
                    validDates = false;
170
                  } else {
171
                    dateField.dateValue.from = Dates.getDateFromString(value.substring(5, 15));
172
                    dateField.dateValue.to = Dates.getDateFromString(value.substring(16, 26));
173
                  }
174
                }
175
                //  "rangeYYYY-MM-DD:YYYY-MM-DD"
176
              } else {
177
                dateField.dateValue.setDatesByType(value);
178
              }
179
              if (validDates) {
180
                this.selectedFields.push(dateField);
181
              }
182

    
183
            } else {
184
              this.selectedFields.push(new AdvancedField(fieldId, fieldparam, this.fieldIdsMap[fieldId].name, this.fieldIdsMap[fieldId].type, StringUtils.unquote(values[j]), operators[j]));
185
            }
186
          }
187
        }
188
      }
189
    }
190
    if (this.selectedFields.length == 0) {
191
      this.selectedFields.push(new AdvancedField(this.fieldIds[0], fieldparam, this.fieldIdsMap[this.fieldIds[0]].name, this.fieldIdsMap[this.fieldIds[0]].type, "", "and"));
192
    }
193
  }
194

    
195
  /**
196
   * Create Page URL parameters based on the selected fields of the advanced form
197
   * @param includePage
198
   */
199
  private createUrlParameters(includePage: boolean) {
200
    var params = "";
201
    this.parameterNames.splice(0, this.parameterNames.length);
202
    this.parameterValues.splice(0, this.parameterValues.length);
203
    var fields: { [key: string]: { values: string[], operators: string[] } } = {};
204
    for (var i = 0; i < this.selectedFields.length; i++) {
205
      if (this.fieldIdsMap[this.selectedFields[i].id] != undefined && (this.selectedFields[i].value.length > 0 || this.selectedFields[i].type == "date")) {
206
        if (!fields[this.selectedFields[i].id]) {
207
          fields[this.selectedFields[i].id] = {values: [], operators: []};
208
          fields[this.selectedFields[i].id].values = [];
209
          fields[this.selectedFields[i].id].operators = [];
210
        }
211
        if (this.selectedFields[i].type == "date") {
212
          if (this.selectedFields[i].dateValue.type == "range") {
213
            fields[this.selectedFields[i].id].values.push(StringUtils.quote(StringUtils.URIEncode("range" + Dates.getDateToString(this.selectedFields[i].dateValue.from) + ":" + Dates.getDateToString(this.selectedFields[i].dateValue.to))));
214
          } else {
215
            fields[this.selectedFields[i].id].values.push(StringUtils.quote(StringUtils.URIEncode(this.selectedFields[i].dateValue.type)));
216
          }
217
        } else {
218
          fields[this.selectedFields[i].id].values.push(StringUtils.quote(StringUtils.URIEncode(this.selectedFields[i].value)));
219
        }
220
        fields[this.selectedFields[i].id].operators.push(this.selectedFields[i].operatorId);
221

    
222
      }
223
    }
224
    for (var i = 0; i < this.fieldIds.length; i++) {
225
      if (fields[this.fieldIds[i]]) {
226

    
227
        params += "&" + this.fieldIdsMap[this.fieldIds[i]].param + "=" + fields[this.fieldIds[i]].values.join() +
228
          "&" + this.fieldIdsMap[this.fieldIds[i]].operator + "=" + fields[this.fieldIds[i]].operators.join()
229
        this.parameterNames.push(this.fieldIdsMap[this.fieldIds[i]].param);
230
        this.parameterValues.push(fields[this.fieldIds[i]].values.join());
231
        this.parameterNames.push(this.fieldIdsMap[this.fieldIds[i]].operator);
232
        this.parameterValues.push(fields[this.fieldIds[i]].operators.join());
233
      }
234
    }
235
    if (includePage && this.searchUtils.page != 1) {
236
      params += "&page=" + this.searchUtils.page;
237
    }
238

    
239
    if (this.searchUtils.size != 10) {
240
      params += ((params.length == 0) ? '' : '&') + 'size=' + this.searchUtils.size;
241
      this.parameterNames.push("size");
242
      this.parameterValues.push("" + this.searchUtils.size);
243
    }
244

    
245
    if (this.sort && this.searchUtils.sortBy) {
246
      params += ((params.length == 0) ? '' : '&') + 'sortBy=' + this.searchUtils.sortBy;
247
      this.parameterNames.push("sortBy");
248
      this.parameterValues.push(this.searchUtils.sortBy);
249
    }
250

    
251
    return '?' + params;
252
  }
253

    
254
  /**
255
   * Create Search API query based on the selected fields of the advanced form
256
   */
257
  public createQueryParameters() {
258
    var params = "";
259
    var countParams = 0;
260
    for (var i = 0; i < this.selectedFields.length; i++) {
261
      if (this.fieldIdsMap[this.selectedFields[i].id] != undefined && (this.selectedFields[i].value != "" || this.selectedFields[i].type == "date")) {
262
        //console.log("createQueryParameters::"+this.selectedFields[i].type);
263
        if (this.selectedFields[i].type == "date") {
264
          if (this.selectedFields[i].dateValue.type != "any") {
265
            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)) + " "
266
              + StringUtils.URIEncode(Dates.getDateToString(this.selectedFields[i].dateValue.to)) + '"' + " ";
267
          }
268
        } else {
269
          if (this.selectedFields[i].id == "q") {
270
            var op = "";
271
            // if()
272
            params += (countParams == 0 ? "" : this.selectedFields[i].operatorId) + " " + '"' + StringUtils.URIEncode(this.selectedFields[i].value) + '"' + " ";
273
          } else if (countParams == 0 && this.selectedFields[i].operatorId == "not") {
274
            params += " " + this.selectedFields[i].id + " <> " + '"' + StringUtils.URIEncode(this.selectedFields[i].value) + '"' + " ";
275
          } else {
276
            params += (countParams == 0 ? "" : this.selectedFields[i].operatorId + " ") + this.selectedFields[i].id + this.fieldIdsMap[this.selectedFields[i].id].equalityOperator + '"' + encodeURIComponent(this.selectedFields[i].value) + '"' + " ";
277

    
278
          }
279
        }
280
        countParams++;
281
      }
282
    }
283

    
284
    if (this.customFilter) {
285
      params += (countParams == 0 ? "" : " and ") + this.customFilter.queryFieldName + " exact " + StringUtils.quote((this.customFilter.valueId));
286
    }
287
    return params;
288

    
289
  }
290

    
291
  goTo(page: number = 1) {
292
    this.searchUtils.page = page;
293
    this.createUrlParameters(true);
294
    this.router.navigate([this.searchUtils.baseUrl], {queryParams: this.routerHelper.createQueryParams(this.parameterNames, this.parameterValues)});
295
    /* Code For Piwik*/
296
    if (typeof localStorage !== 'undefined') {
297
      //console.log("In PreviousRouteRecorder : "+this.router.url );
298
      localStorage.setItem('previousRoute', this.router.url);
299
    }
300
    if (this.isPiwikEnabled && (typeof document !== 'undefined')) {
301
      this.piwiksub = this._piwikService.trackView(this.properties, this.pageTitle, this.piwikSiteId).subscribe();
302
    }
303
    /* End Piwik Code */
304
  }
305

    
306
  queryChanged($event) {
307

    
308
    this.goTo(1);
309
  }
310

    
311
  pageChanged($event) {
312
    this.searchUtils.page = +$event.value;
313
    this.goTo(this.searchUtils.page);
314
  }
315

    
316
  sizeChanged($event) {
317
    this.searchUtils.size = $event.value;
318
    this.goTo(1);
319
  }
320

    
321
  sortByChanged($event) {
322
    this.searchUtils.sortBy = $event.value;
323
    this.goTo(1);
324
  }
325

    
326
  /*
327
  * Update the url with proper parameters. This is used as base url in Paging Component
328
  */
329
  public updateBaseUrlWithParameters() {
330
    this.baseURLWithParameters = this.searchUtils.baseUrl + this.createUrlParameters(false);
331
  }
332

    
333
  getOperatorParameter(parameter: string): string {
334
    for (let id of this.fieldIds) {
335
      if (this.fieldIdsMap[id]["param"] == parameter) {
336
        return this.fieldIdsMap[id]["operator"];
337
      }
338
    }
339
  }
340

    
341
  // for loading
342
  public openLoading() {
343
    this.loading.open();
344
  }
345

    
346
  public closeLoading() {
347
    this.loading.close();
348
  }
349
}
(5-5/55)