Project

General

Profile

1
import {Component, Input, Output, EventEmitter, ViewChild} from '@angular/core';
2
import {Observable}       from 'rxjs';
3
import { ActivatedRoute} from '@angular/router';
4
import {AlertModal} from '../../utils/modal/alert';
5
import {ReportsService} from '../../services/reports.service';
6
import {ModalLoading} from '../../utils/modal/loading.component';
7
import {PiwikService} from '../../utils/piwik/piwik.service';
8
import{EnvProperties} from '../../utils/properties/env-properties';
9
import {ErrorCodes} from '../../utils/properties/errorCodes';
10

    
11
import 'rxjs' ;
12

    
13
@Component({
14
    selector: 'search-download',
15
    template: `
16
        <a uk-tooltip="title: Download results in csv file" class="" *ngIf="totalResults > 0 && totalResults <= csvLimit">
17
            <span class="clickable" (click)="downloadfile(downloadURLAPI+'?type='+type+'&format=csv'+csvParams,type+'-report-'+totalResults)">
18
            <!--a [href]="downloadURLAPI+'s'+'?type='+type+'&format=csv'+csvParams" target="_blank"-->
19
                <span aria-hidden="true" class="glyphicon glyphicon-download"></span>
20
                <span  class="uk-icon"><svg width="20" height="20" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg" icon="download" ratio="1"><polyline fill="none" stroke="#000" points="14,10 9.5,14.5 5,10"></polyline><rect x="3" y="17" width="13" height="1"></rect><line fill="none" stroke="#000" x1="9.5" y1="13.91" x2="9.5" y2="3"></line></svg></span> (CSV)
21
            <!--/a-->
22
            </span>
23
        </a>
24
        <!--*ngIf="totalResults > csvLimit" -->
25
        <!-- [attr.uk-tooltip]="'pos:right'" -->
26
        <span class="cursor-not-allowed " *ngIf="(!loadPaging && oldTotalResults > 0 && searchUtils.status == errorCodes.LOADING) || totalResults > csvLimit"
27
                    [attr.uk-tooltip]="'pos:top'"
28
                    [title]="'Download up to '+csvLimit+' results'">
29
            <span aria-hidden="true" class="glyphicon glyphicon-download"></span>
30
            <span  class="uk-icon"><svg width="20" height="20" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg" icon="download" ratio="1"><polyline fill="none" stroke="#000" points="14,10 9.5,14.5 5,10"></polyline><rect x="3" y="17" width="13" height="1"></rect><line fill="none" stroke="#000" x1="9.5" y1="13.91" x2="9.5" y2="3"></line></svg></span> (CSV)
31
        </span>
32
    <modal-loading></modal-loading>
33
    <modal-alert #AlertModalCsvError></modal-alert>
34
    `
35
})
36

    
37
export class SearchDownloadComponent {
38
    @Input() searchUtils;
39
    @Input() oldTotalResults:number = 0;
40
    @Input() loadPaging: boolean = true;
41
    @Input() totalResults:number = 0;
42
    @Input() csvParams: string;
43
    @Input() type: string;
44
    @ViewChild(AlertModal) alertApplyAll;
45
    private downloadURLAPI: string;
46

    
47
    sub: any;
48
    downloadFilePiwikSub: any;
49

    
50
    public csvLimit: number = 0;
51

    
52
    @ViewChild (ModalLoading) loading : ModalLoading ;
53
    // Alert box when something is wrong with CSV requests
54
    @ViewChild('AlertModalCsvError') alertCsvError;
55
    public isPiwikEnabled;
56
    public properties:EnvProperties;
57
    public errorCodes:ErrorCodes = new ErrorCodes();
58

    
59
    constructor (private route: ActivatedRoute, private _reportsService: ReportsService, private _piwikService:PiwikService) {}
60

    
61
    ngOnInit() {
62
      this.route.data
63
        .subscribe((data: { envSpecific: EnvProperties }) => {
64
          this.properties = data.envSpecific;
65
          this.csvLimit = data.envSpecific.csvLimit;
66
          this.downloadURLAPI = data.envSpecific.csvAPIURL;
67
          this.isPiwikEnabled = data.envSpecific.enablePiwikTrack;
68
        });
69
    }
70

    
71
    ngOnDestroy() {
72
      if(this.sub) {
73
        this.sub.unsubscribe();
74
      }
75
      if(this.downloadFilePiwikSub) {
76
        this.downloadFilePiwikSub.unsubscribe();
77
      }
78
    }
79

    
80
    denialOfDownload() {
81
        this.alertApplyAll.isOpen = true;
82
        this.alertApplyAll.cancelButton = true;
83
        this.alertApplyAll.okButton = false;
84
        this.alertApplyAll.alertTitle = "Download Results in CSV";
85
        this.alertApplyAll.message = "Sorry, but the results are too many! Use the api instead!";
86
        this.alertApplyAll.cancelButtonText = "Ok";
87

    
88
        console.error("Error downloading file. Results are too many!");
89
        //this.handleError("Error downloading file. Results are too many!", err);
90
    }
91
    downloadfile(url:string,filename:string){
92
      //var newWindow = window.open("", "_parent");
93
      //var newWindow = window.open();
94
      //console.log("Downloading file: "+ url);
95
      this.openLoading();
96
      this.setMessageLoading("Downloading CSV file");
97

    
98
      this._reportsService.downloadCSVFile(url).subscribe(
99
          data => {
100
              this.closeLoading();
101
              //window.open(window.URL.createObjectURL(data),filename+".csv");
102
              //console.info("Fill window with data for csv");
103
            if(typeof document !== 'undefined'){
104
              var url = window.URL.createObjectURL(data);
105
              var a = window.document.createElement('a');
106
              window.document.body.appendChild(a);
107
              a.setAttribute('style', 'display: none');
108
              a.href = url;
109
              a.download = filename+".csv";
110
              a.click();
111
              window.URL.revokeObjectURL(url);
112
              a.remove(); // remove the element
113
            }
114
              //newWindow.location.assign(window.URL.createObjectURL(data));
115

    
116
              //window.location.href = window.URL.createObjectURL(data);
117

    
118
              if(this.isPiwikEnabled && (typeof document !== 'undefined')){
119
                this.downloadFilePiwikSub = this._piwikService.trackDownload(this.properties, url).subscribe();
120
              }
121
          },
122
          error => {
123
            //console.error("Error downloading the file.");
124
            this.handleError("Error downloading file: "+filename, error);
125

    
126
            //newWindow.close();
127
            this.closeLoading();
128
            this.confirmOpenCsvError();
129
          }/*,
130
          () => {
131
            console.log('Completed file download.');
132
            //setTimeout(function(){ newWindow.close(); }, 500);
133
          }*/
134
      );
135
    }
136

    
137

    
138
    public openLoading(){
139
      if(this.loading){
140
        this.loading.open();
141
      }
142
    }
143
    public closeLoading(){
144
      if(this.loading){
145
        this.loading.close();
146
      }
147
    }
148
    public setMessageLoading(message: string){
149
      if(this.loading){
150
        this.loading.message = message;
151
      }
152
    }
153

    
154
    public confirmOpenCsvError(){
155
      this.alertCsvError.cancelButton = false;
156
      this.alertCsvError.okButton = true;
157
      this.alertCsvError.alertTitle = "ERROR DOWNLOADING CSV FILE";
158
      this.alertCsvError.message = "There was an error in csv downloading. Please try again later.";
159
      this.alertCsvError.okButtonText = "OK";
160
      this.alertCsvError.open();
161
    }
162

    
163
    private handleError(message: string, error) {
164
      console.error("Search Download (component): "+message, error);
165
    }
166
}
(18-18/45)