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() pageTitle = "";
25
  @Input() results = [];
26
  @Input() type;
27
  @Input() entityType;
28
  @Input() searchUtils: SearchUtilsClass = new SearchUtilsClass();
29
  @Input() fieldIds: string[];
30
  @Input() fieldIdsMap;//:{ [key:string]:{ name:string, operator:string, type:string, indexField:string, equalityOperator:string  }} ;
31
  @Input() selectedFields: AdvancedField[];
32
  @Input() simpleSearchUrl: string;
33
  @ViewChild(ModalLoading) loading: ModalLoading;
34
  @Input() csvParams: string;
35
  @Input() csvPath: string;
36
  @Input() simpleSearchLink: string = "";
37
  @Input() disableForms: boolean = false;
38
  @Input() loadPaging: boolean = true;
39
  @Input() oldTotalResults: number = 0;
40
  @Input() openaireLink: string;
41
  @Input() customFilter: SearchCustomFilter = null;
42
  @Input() sort: boolean = false;
43
  @Input() searchFormClass: string = "searchForm";
44
  piwiksub: any;
45
  public parameterNames: string[] = [];
46
  public parameterValues: string[] = [];
47

    
48
  public baseURLWithParameters: string = '';
49

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

    
60
  url = null;
61
  @Output() queryChange = new EventEmitter();
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 title = "Advanced search " + this.pageTitle;
93
    var description = "Openaire, search, repositories, open access, type, content provider, funder, project, " + this.pageTitle;
94

    
95
    this.updateTitle(title);
96
    this.updateDescription(description);
97

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

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

    
103

    
104
  }
105

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

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

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

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

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

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

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

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

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

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

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

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

    
193
  private createUrlParameters(includePage: boolean) {
194
    var params = "";
195
    this.parameterNames.splice(0, this.parameterNames.length);
196
    this.parameterValues.splice(0, this.parameterValues.length);
197
    var fields: { [key: string]: { values: string[], operators: string[] } } = {};
198
    for (var i = 0; i < this.selectedFields.length; i++) {
199
      if (this.fieldIdsMap[this.selectedFields[i].id] != undefined && (this.selectedFields[i].value.length > 0 || this.selectedFields[i].type == "date")) {
200
        if (!fields[this.selectedFields[i].id]) {
201
          fields[this.selectedFields[i].id] = {values: [], operators: []};
202
          fields[this.selectedFields[i].id].values = [];
203
          fields[this.selectedFields[i].id].operators = [];
204
        }
205
        if (this.selectedFields[i].type == "date") {
206
          if (this.selectedFields[i].dateValue.type == "range") {
207
            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))));
208
          } else {
209
            fields[this.selectedFields[i].id].values.push(StringUtils.quote(StringUtils.URIEncode(this.selectedFields[i].dateValue.type)));
210
          }
211
        } else {
212
          fields[this.selectedFields[i].id].values.push(StringUtils.quote(StringUtils.URIEncode(this.selectedFields[i].value)));
213
        }
214
        fields[this.selectedFields[i].id].operators.push(this.selectedFields[i].operatorId);
215

    
216
      }
217
    }
218
    for (var i = 0; i < this.fieldIds.length; i++) {
219
      if (fields[this.fieldIds[i]]) {
220

    
221
        params += "&" + this.fieldIdsMap[this.fieldIds[i]].param + "=" + fields[this.fieldIds[i]].values.join() +
222
          "&" + this.fieldIdsMap[this.fieldIds[i]].operator + "=" + fields[this.fieldIds[i]].operators.join()
223
        this.parameterNames.push(this.fieldIdsMap[this.fieldIds[i]].param);
224
        this.parameterValues.push(fields[this.fieldIds[i]].values.join());
225
        this.parameterNames.push(this.fieldIdsMap[this.fieldIds[i]].operator);
226
        this.parameterValues.push(fields[this.fieldIds[i]].operators.join());
227
      }
228
    }
229
    if (includePage && this.searchUtils.page != 1) {
230
      params += "&page=" + this.searchUtils.page;
231
    }
232

    
233
    if (this.searchUtils.size != 10) {
234
      params += ((params.length == 0) ? '' : '&') + 'size=' + this.searchUtils.size;
235
      this.parameterNames.push("size");
236
      this.parameterValues.push("" + this.searchUtils.size);
237
    }
238

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

    
245
    return '?' + params;
246
  }
247

    
248
  public createQueryParameters() {
249
    var params = "";
250
    var countParams = 0;
251
    for (var i = 0; i < this.selectedFields.length; i++) {
252
      if (this.fieldIdsMap[this.selectedFields[i].id] != undefined && (this.selectedFields[i].value != "" || this.selectedFields[i].type == "date")) {
253
        //console.log("createQueryParameters::"+this.selectedFields[i].type);
254
        if (this.selectedFields[i].type == "date") {
255
          if (this.selectedFields[i].dateValue.type != "any") {
256
            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)) + " "
257
              + StringUtils.URIEncode(Dates.getDateToString(this.selectedFields[i].dateValue.to)) + '"' + " ";
258
          }
259
        } else {
260
          if (this.selectedFields[i].id == "q") {
261
            var op = "";
262
            // if()
263
            params += (countParams == 0 ? "" : this.selectedFields[i].operatorId) + " " + '"' + StringUtils.URIEncode(this.selectedFields[i].value) + '"' + " ";
264
          } else if (countParams == 0 && this.selectedFields[i].operatorId == "not") {
265
            params += " " + this.selectedFields[i].id + " <> " + '"' + StringUtils.URIEncode(this.selectedFields[i].value) + '"' + " ";
266
          } else {
267
            params += (countParams == 0 ? "" : this.selectedFields[i].operatorId + " ") + this.selectedFields[i].id + this.fieldIdsMap[this.selectedFields[i].id].equalityOperator + '"' + encodeURIComponent(this.selectedFields[i].value) + '"' + " ";
268

    
269
          }
270
        }
271
        countParams++;
272
      }
273
    }
274

    
275
    if (this.customFilter) {
276
      params += (countParams == 0 ? "" : " and ") + this.customFilter.queryFieldName + " exact " + StringUtils.quote((this.customFilter.valueId));
277
    }
278
    return params;
279

    
280
  }
281

    
282
  clearFilters() {
283
  }
284

    
285
  goTo(page: number = 1) {
286
    this.searchUtils.page = page;
287
    var urlParameters = this.createUrlParameters(true);
288
    var queryParameters = this.createQueryParameters();
289
    //this.location.go(location.pathname,urlParameters);
290
    this.router.navigate([this.searchUtils.baseUrl], {queryParams: this.routerHelper.createQueryParams(this.parameterNames, this.parameterValues)});
291

    
292
    this.queryChange.emit({
293
      value: queryParameters
294
    });
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/45)