Project

General

Profile

1
import {Component, Input, ViewChild} from '@angular/core';
2
import {SearchCrossrefService} from '../../claim-utils/service/searchCrossref.service';
3
import {SearchDataciteService} from '../../claim-utils/service/searchDatacite.service';
4

    
5
import {ModalLoading} from '../../../utils/modal/loading.component';
6
import {Dates, DOI} from '../../../utils/string-utils.class';
7
import {EnvProperties} from '../../../utils/properties/env-properties';
8
import {ClaimEntity} from "../../claim-utils/claimHelper.class";
9

    
10
declare var UIkit: any;
11

    
12

    
13
@Component({
14
  selector: 'bulk-claim',
15
  template: `
16
    <div class="uk-animation uk-text-center" style=" ">
17
      <form class=" ">
18

    
19
        <div>
20
          <div>
21
            <!--div class="uk-text-lead">Upload a DOI csv file <helper  div="link-result-bulk" tooltip=true ></helper></div>
22
            <label for="exampleInputFile">Select a file: </label-->
23
            <div class="js-upload" uk-form-custom>
24
              <input id="exampleInputFile" class="uk-width-medium" type="file" (change)="fileChangeEvent($event)"/>
25
              <span class="uk-link " style="text-decoration: underline;">Upload a DOI's CSV file </span>
26
              <!--button class="uk-button  portal-button" type="button" tabindex="-1" [class.disabled]="!enableUpload" ><span class="uk-margin-small-right uk-icon"  >
27
              <svg width="20" height="20" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"> <polyline fill="none" stroke="#000" points="5 8 9.5 3.5 14 8 "></polyline> <rect x="3" y="17" width="13" height="1"></rect>
28
               <line fill="none" stroke="#000" x1="9.5" y1="15" x2="9.5" y2="4"></line></svg></span> Select</button-->
29
              <!--helper  div="link-result-bulk" tooltip=true ></helper-->
30
            </div>
31
            <span class=" " title="{{tooltip}}" uk-tooltip><span class="uk-icon" uk-icon="icon: info; ratio: 0.8">&nbsp; </span> </span>
32
            <div *ngIf="showReport" uk-alert class="uk-alert-primary">
33
              <a class="uk-alert-close" uk-close></a>
34
              <div>Uploaded file contains <span
35
                class="uk-text-bold">{{allIds.length}} {{((allIds.length == 1) ? 'DOI' : 'DOIs')}}</span>.
36
                <span
37
                  *ngIf="exceedsLimit">
38
                  <div class="uk-text-danger">Basket exceeds  the size limit.</div>
39
                  <span *ngIf="allIds.length > 0 && foundIds.length > 0">Only </span>
40
                  <span *ngIf="allIds.length > 0 && foundIds.length == 0">No results added.</span>
41
                   </span>
42
                <span
43
                  *ngIf="allIds.length > 0 && foundIds.length > 0">{{foundIds.length}} {{((foundIds.length == 1) ? 'result was' : 'results were')}} succefully  fetched from 
44
                  <span class="uk-text-bold">CrossRef</span>{{ ' and ' }}<span
45
                    class="uk-text-bold">Datacite</span>.</span>
46

    
47
              </div>
48
              <div
49
                *ngIf="duplicateIds.length > 0">{{duplicateIds.length | number}} duplicate DOIs in {{((duplicateIds.length == 1) ? 'line' : 'lines')}} {{duplicateIdsRow}}.
50
              </div>
51
              <div *ngIf="notFoundIds.length > 0">Couldn't be fetched:
52
                <ul class="">
53
                  <li *ngFor="let id of notFoundIds; let i = index">"{{id}}" in line {{notFoundIdsRow[i]}}</li>
54
                </ul>
55
              </div>
56
              <div *ngIf="noValidIds.length > 0">No valid DOIs:
57
                <ul class="">
58
                  <li *ngFor="let id of noValidIds; let i = index">"{{id}}" in line {{noValidIdsRow[i]}}</li>
59
                </ul>
60
              </div>
61
              <div
62
                *ngIf="allIds.length == 0 || (foundIds.length == 0 && !exceedsLimit)"> Please make sure that the uploaded file, is a csv file with the proper format.
63
              </div>
64

    
65
            </div>
66
            <div *ngIf="errorMessage.length > 0 " uk-alert class="uk-alert uk-alert-danger" role="alert">
67
              <a class="uk-alert-close" uk-close></a>
68
              {{errorMessage}}</div>
69

    
70
          </div>
71
          <!--helper  div="link-result-bulk" ></helper-->
72
        </div>
73
      </form>
74

    
75

    
76
    </div>
77
    <div class="uk-width-1-1">
78
      <modal-loading
79
        [message]="'Uploading, reading your documet and fetching results. Please give us a moment..'"></modal-loading>
80
    </div>
81
  `
82

    
83
})
84
export class BulkClaimComponent {
85
  filesToUpload: Array<File>;
86
  source: string = "crossref";
87
  type: string = "publication";
88
  @Input() public select: boolean = true;
89
  @Input() public results;
90
  @Input() public properties: EnvProperties;
91

    
92
  allIds: string[] = [];
93
  foundIds: string[] = [];
94
  existedIds: string[] = [];
95
  duplicateIds: string[] = [];
96
  duplicateIdsRow: number[] = [];
97
  notFoundIds: string[] = [];
98
  notFoundIdsRow: number[] = [];
99
  noValidIds: string[] = [];
100
  noValidIdsRow: number[] = [];
101
  showReport: boolean = false;
102
  @ViewChild(ModalLoading) loading: ModalLoading;
103
  errorMessage = "";
104
  enableUpload: boolean = true;
105
  @Input() localStoragePrefix: string = "";
106
  exceedsLimit = false;
107
  @Input() basketLimit ;
108
  tooltip = `
109
  <div class="uk-padding-small uk-padding-remove-right uk-padding-remove-left">
110
    <div >
111
         <div><span class="uk-text-bold">CSV format:</span> <br>&quot;DOI&quot;,&quot;ACCESS_MODE&quot;,&quot;DATE&quot;</div>
112
         <br>
113
      <div class="  uk-text-small">
114
        <div>- DOI is required</div>
115
        <div>- Access mode: <br> OPEN, CLOSED, EMBARGO</div>
116
        <div>- Embargo end date:<br> YYYY-MM-DD </div>
117
      </div>     
118
    </div>
119
</div>`;
120
  constructor(private _searchCrossrefService: SearchCrossrefService, private _searchDataciteService: SearchDataciteService) {
121
    this.filesToUpload = [];
122
  }
123

    
124
  ngOnInit() {
125
  }
126

    
127
  upload() {
128
    this.enableUpload = false;
129
    this.showReport = false;
130
    this.errorMessage = "";
131
    console.log(this.filesToUpload);
132
    if (this.filesToUpload.length == 0) {
133
      this.errorMessage = "There is no selected file to upload.";
134
      return;
135
    } else {
136
      if (this.filesToUpload[0].name.indexOf(".csv") == -1 ||
137
        (this.filesToUpload[0].type != "text/csv" && this.filesToUpload[0].type != "application/vnd.ms-excel")) {
138
        this.errorMessage = "No valid file type. The required type is CSV";
139
        return;
140
      }
141
    }
142
    this.loading.open();
143

    
144
    this.makeFileRequest(this.properties.utilsService + '/upload', [], this.filesToUpload).then((result) => {
145
      const rows = (result as any).split('\n');  // I have used space, you can use any thing.
146
      this.exceedsLimit = false;
147
      let invalid_rows = 0;
148
      this.duplicateIds = [];
149
      this.existedIds = [];
150
      this.allIds = [];
151
      this.foundIds = [];
152
      this.noValidIds = [];
153
      this.results.slice(0, this.results.length);
154
      this.notFoundIds = [];
155
      let currentLength = this.results.length;
156
      for (let i = 0; i < ( rows.length); i++) {
157
        if (rows[i] && rows[i] != null && rows[i]!="") {
158
          const values = rows[i].split(',');
159

    
160
          const id = BulkClaimComponent.removeDoubleQuotes(values[0]);
161
          if (DOI.isValidDOI(id)) {
162
            let accessMode = (values[1] != undefined) ? BulkClaimComponent.removeDoubleQuotes(values[1]) : "OPEN";
163
            accessMode = (BulkClaimComponent.validateAccessMode(accessMode) ? accessMode : "OPEN");
164
            let embargoDate = (values[2] != undefined) ? Dates.getDateFromString(BulkClaimComponent.removeDoubleQuotes(values[2])) : Dates.getDateToday();
165
            if (this.allIds.indexOf(id) > -1) {
166
              this.duplicateIds.push(id);
167
              this.duplicateIdsRow.push(i + 1);
168
            } else {
169
              this.allIds.push(id);
170
              if (currentLength < this.basketLimit){
171
                currentLength++;
172
                this.fetchResult(id, accessMode, Dates.getDateToString(embargoDate), i + 1);
173
              }else{
174
                this.exceedsLimit = true;
175
              }
176
            }
177
          } else {
178
            this.noValidIds.push(id);
179
            this.noValidIdsRow.push(i + 1);
180
          }
181
        } else {
182
          invalid_rows++;
183
        }
184

    
185
      }
186
      if (rows.length == 0 || rows.length == invalid_rows || rows.length == (invalid_rows + this.noValidIds.length) || this.basketLimit <= this.results.length) {
187
        this.endOfFetching();
188
      }
189

    
190
    }, (error) => {
191
      this.enableUpload = true;
192
      this.loading.close();
193
      this.errorMessage = "An error occured.";
194
      BulkClaimComponent.handleError("Error uploading file", error);
195
    });
196
  }
197

    
198
  private static removeDoubleQuotes(value) {
199
    if (value.indexOf('"') == 0) {
200
      value = value.substring(1, value.length);
201
    }
202
    const index = +value.indexOf('"');
203
    if (index == (value.length - 1) || index == (value.length - 2)) {
204
      value = value.substring(0, index);
205
    }
206
    return value;
207
  }
208

    
209
  private static validateAccessMode(value) {
210
    const accessModes = ["OPEN", "CLOSED", "EMBARGO"];
211
    return accessModes.indexOf(value) > -1;
212
  }
213

    
214
  fileChangeEvent(fileInput: any) {
215
    this.filesToUpload = <Array<File>>fileInput.target.files;
216
    this.upload();
217
  }
218

    
219
  makeFileRequest(url: string, params: Array<string>, files: Array<File>) {
220
    return new Promise((resolve, reject) => {
221
      const formData: any = new FormData();
222
      const xhr = new XMLHttpRequest();
223
      for (let i = 0; i < files.length; i++) {
224
        formData.append("uploads[]", files[i], files[i].name);
225
      }
226
      xhr.onreadystatechange = function () {
227
        if (xhr.readyState == 4) {
228
          if (xhr.status == 200) {
229
            resolve(xhr.response);
230
          } else {
231
            reject(xhr.response);
232
          }
233
        }
234
      }
235
      xhr.open("POST", url, true);
236
      xhr.send(formData);
237
    });
238
  }
239

    
240
  fetchResult(id: string, accessMode: string, date: string, row: number) {
241
    this._searchCrossrefService.searchCrossrefByDOIs([id], this.properties, true).subscribe(
242
      data => {
243

    
244
        const result:ClaimEntity = data[1][0];
245
        if (data[1].length > 0) {
246
          this.foundIds.push(id);
247
          result.result.accessRights = accessMode;
248
          result.result.embargoEndDate = date;
249
          if(!this.isSelected(result)){
250
            this.results.push(result);
251
          }else{
252
            this.existedIds.push(id);
253
          }
254
          this.endOfFetching();
255
        } else {
256
          this.searchInDatacite(id, accessMode, date, row);
257
          // this.notFoundIds.push(id);
258
        }
259
      },
260
      err => {
261
        //console.log(err);
262
        BulkClaimComponent.handleError("Error getting crossref by DOIs: " + id, err);
263
        this.notFoundIds.push(id);
264
        this.notFoundIdsRow.push(row);
265
        this.endOfFetching();
266
      }
267
    );
268
  }
269

    
270
  searchInDatacite(id: string, accessMode: string, date: string, row: number) {
271
    this._searchDataciteService.getDataciteResultByDOI(id, this.properties, true).subscribe(
272
      result => {
273

    
274
        if (result) {
275
          this.foundIds.push(id);
276
          result.result.accessRights = accessMode;
277
          result.result.embargoEndDate = date;
278
          if(!this.isSelected(result)){
279
            this.results.push(result);
280
          }else{
281
            this.existedIds.push(id);
282
          }
283
        } else {
284
          this.notFoundIds.push(id);
285
          this.notFoundIdsRow.push(row);
286
        }
287
        this.endOfFetching();
288
      },
289
      err => {
290
        //console.log(err);
291
        BulkClaimComponent.handleError("Error getting datacite resultentityI: " + id, err);
292
        this.notFoundIds.push(id);
293
        this.notFoundIdsRow.push(row);
294
        this.endOfFetching();
295
      }
296
    );
297
  }
298

    
299
  endOfFetching() {
300
    // if (this.basketLimit <= this.results.length) {
301
    //   this.enableUpload = true;
302
    //   this.loading.close();
303
    //   return;
304
    // }
305
    // console.log(this.allIds.length+" "+this.foundIds.length +" "+ this.notFoundIds.length+" "+this.existedIds.length + " " + this.results.length);
306
    if (this.allIds.length == this.foundIds.length + this.notFoundIds.length || this.basketLimit <= (this.results.length+this.existedIds.length+this.notFoundIds.length)) {
307
      this.showReport = true;
308
      this.enableUpload = true;
309
      this.loading.close();
310
      if (this.results != null) {
311
        localStorage.setItem(this.localStoragePrefix, JSON.stringify(this.results));
312
      }
313
    }
314

    
315
  }
316

    
317
  private static handleError(message: string, error) {
318
    console.error("Bulk Claim (component): " + message, error);
319
  }
320

    
321
  private isSelected(result: ClaimEntity) {
322

    
323
    let found: boolean = false;
324
    const id = result.id;
325
    for (let _i = 0; _i < this.results.length; _i++) {
326
      let item = this.results[_i];
327
      if (item.id && item.id == id) {
328
        found = true;
329
        break;
330
      }
331
    }
332
    return found;
333
    // indexOf doesn't work when results came from
334
    // return this.selectedResults.indexOf(entity)!=-1;
335
  }
336
}
(1-1/2)