minister-reports.ts 13.4 KB
Newer Older
1
import { Component, OnInit, OnDestroy, ElementRef, ViewChild, Input, ViewEncapsulation } from "@angular/core";
2 3 4 5 6 7 8 9 10 11
import { Injectable } from "@angular/core";
import { AppSettings } from '../../app.settings';
import { HelperDataService } from '../../services/helper-data-service';
import { Observable} from "rxjs/Observable";
import { Http, Headers, RequestOptions} from '@angular/http';
import { NgRedux, select } from 'ng2-redux';
import { IAppState } from '../../store/store';
import { Router, ActivatedRoute, Params} from '@angular/router';
import { BehaviorSubject, Subscription } from 'rxjs/Rx';
import { ILoginInfo } from '../../store/logininfo/logininfo.types';
12
import { Ng2SmartTableModule, LocalDataSource } from 'ng2-smart-table';
13 14
import { LOGININFO_INITIAL_STATE } from '../../store/logininfo/logininfo.initial-state';

15
import {reportsSchema, TableColumn} from './reports-schema';
16

17
import * as d3 from 'd3';
18 19


20
//import * as _ from '..';
21 22 23 24 25

import { API_ENDPOINT } from '../../app.settings';

@Component({
    selector: 'minister-reports',
26
    encapsulation: ViewEncapsulation.None,
27 28
    template: `

29
  <div>
30

31 32 33 34
        <div
          class = "loading" *ngIf="!validCreator && reportId" >
        </div>
        <button type="submit" class="btn btn-default btn-block"  (click)="createReport('/ministry/general-report/')" [hidden]="minedu_userName == ''" >
35
            Κατανομή Μαθητών με Βάση τη Σειρά Προτίμησης
36
        </button>
37
        <button type="submit" class="btn btn-default btn-block"  (click)="createReport('/ministry/report-completeness/')" [hidden]="minedu_userName == ''" >
38 39 40 41
            Πληρότητα Σχολείων
        </button>
        <button type="submit" class="btn btn-default btn-block"  (click)="createReport('/ministry/report-all-stat/')" [hidden]="minedu_userName == ''" >
            Μαθητές ανά Τάξη/Τομέα/Ειδικότητα
42 43
        </button>

44

45 46 47 48 49
        <div *ngIf="validCreator ">
          <input #search class="search" type="text" placeholder="Αναζήτηση..." (keydown.enter)="onSearch(search.value)">
          <div class="smart-table-container" reportScroll>
            <ng2-smart-table [settings]="settings" [source]="source"></ng2-smart-table>
          </div>
50
        </div>
51

52 53
        <button type="button" class="alert alert-info pull-right" (click)="export2Csv()" [hidden]="!validCreator">
        <i class="fa fa-download"></i>
54 55
            Εξαγωγή σε csv
        </button>
56
        <button type="button" class="alert alert-info pull-left" (click)="createDiagram()" [hidden]="!validCreator ||  charIsHidden() ">
57 58 59
        <i class="fa fa-bar-chart"></i>
            Διάγραμμα
        </button>
60

61 62
    </div>

63
    <div class="d3-chart" *ngIf = "!charIsHidden() && validCreator" #chart>
64 65 66 67
    </div>

      <!--<div *ngFor="let generalReports$  of generalReport$ | async; let i=index">-->

68 69 70 71 72
   `
})

@Injectable() export default class MinisterReports implements OnInit, OnDestroy {

73
    //public formGroup: FormGroup;
74 75 76 77 78 79 80 81
    loginInfo$: BehaviorSubject<ILoginInfo>;
    loginInfoSub: Subscription;
    private generalReport$: BehaviorSubject<any>;
    private generalReportSub: Subscription;
    private apiEndPoint = API_ENDPOINT;
    private minedu_userName: string;
    private minedu_userPassword: string;
    private distStatus = "READY";
82 83
    private data;
    private validCreator: boolean;
84
    private createGraph: boolean;
85 86 87 88 89 90
    private reportId: number;
    private source: LocalDataSource;

    columnMap: Map<string,TableColumn> = new Map<string,TableColumn>();
    @Input() settings: any;
    private reportSchema = new  reportsSchema();
91

92 93 94 95 96 97 98 99 100 101 102 103 104
    //d3 test
    @ViewChild('chart') private chartContainer: ElementRef;
    //@Input() private d3data: Array<any>;
    private d3data: Array<any>;
    private margin: any = { top: 20, bottom: 20, left: 20, right: 20};
    private chart: any;
    private width: number;
    private height: number;
    private xScale: any;
    private yScale: any;
    private colors: any;
    private xAxis: any;
    private yAxis: any;
105 106 107


    constructor(/*private fb: FormBuilder,*/
108 109 110 111 112
        private _ngRedux: NgRedux<IAppState>,
        private _hds: HelperDataService,
        private activatedRoute: ActivatedRoute,
        private router: Router) {

113
          //this.formGroup = this.fb.group({
114

115
          //});
116 117 118

          this.loginInfo$ = new BehaviorSubject(LOGININFO_INITIAL_STATE);
          this.generalReport$ = new BehaviorSubject([{}]);
119 120
          this.minedu_userName = '';
          this.validCreator = false;
121
          this.createGraph = false;
122 123
          this.reportId = 0;
          //this.source = new LocalDataSource(this.data);
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151

    }

    ngOnDestroy() {

      if (this.loginInfoSub)
        this.loginInfoSub.unsubscribe();
      this.loginInfo$.unsubscribe();

      if (this.generalReportSub)
          this.generalReportSub.unsubscribe();
      this.generalReport$.unsubscribe();

    }

    ngOnInit() {

      this.loginInfoSub = this._ngRedux.select(state => {
          if (state.loginInfo.size > 0) {
              state.loginInfo.reduce(({}, loginInfoToken) => {
                this.minedu_userName = loginInfoToken.minedu_username;
                this.minedu_userPassword = loginInfoToken.minedu_userpassword;
                  return loginInfoToken;
              }, {});
          }
          return state.loginInfo;
      }).subscribe(this.loginInfo$);

152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168





      /*
      setTimeout(() => {
        this.generateData();
        // change the data periodically
        setInterval(() => this.generateData(), 3000);
      }, 1000);
      */

      //this.generateData();
      //this.createChart();
      //this.updateChart();

169 170 171 172
    }


createReport(routePath) {
173

174
  this.reportId = 0;
175
  this.validCreator = false;
176 177
  this.createGraph = false;

178 179 180 181 182 183
  if (routePath === "/ministry/general-report/")  {
    this.reportId = 1;
    this.settings = this.reportSchema.genReportSchema;
  }
  else if (routePath === "/ministry/report-completeness/")  {
    this.reportId = 2;
184 185 186 187 188
    this.settings = this.reportSchema.reportCompletenessSchema;
  }
  else if (routePath === "/ministry/report-all-stat/")  {
    this.reportId = 3;
    this.settings = this.reportSchema.reportAllStatSchema;
189
  }
190

191 192 193
  this.generalReportSub = this._hds.makeReport(this.minedu_userName, this.minedu_userPassword, routePath).subscribe(data => {
      this.generalReport$.next(data);
      this.data = data;
194 195 196 197
      console.log("Let see..");
      //console.log(this.data);
      //console.log(this.data[0].name);
      //console.log(this.data.length);
198 199 200 201 202 203 204 205 206 207 208 209
  },
    error => {
      this.generalReport$.next([{}]);
      console.log("Error Getting generalReport");
    },
    () => {
      console.log("Getting generalReport");
      this.validCreator = true;
      this.source = new LocalDataSource(this.data);
      //this.source.load(this.data);
      //this.settings = _.merge(this.defaultSettings, this.report1Schema);
      //this.settings = this.report1Schema;
210 211
      this.columnMap = new Map<string,TableColumn>();
      //columnMap: Map<string,TableColumn> = new Map<string,TableColumn>();
212
      this.prepareColumnMap();
213 214 215 216

      //this.generateData2();
      //this.createChart();
      //this.updateChart();
217
    }
218
  )
219

220
}
221 222


223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
  onSearch(query: string = '') {

    this.source.setFilter([
      // fields we want to include in the search
      {
        field: 'name',
        search: query
      }
    ], false);


  // second parameter specifying whether to perform 'AND' or 'OR' search
  // (meaning all columns should contain search query or at least one)
  // 'AND' by default, so changing to 'OR' by setting false here
}


export2Csv(): void {

  const columns: TableColumn[] = Array.from(this.columnMap.values());

  let encodedStr = columns.reduce((acct, current: TableColumn) => {

    if (current.isExport != false) {
      return acct += '"' + current.title + '",';
    }
    else {
      return acct;
    }
  }, '');
  encodedStr = encodedStr.slice(0, -1);
  encodedStr += '\r\n';

  let fields: string[] = columns.reduce((acct, column: TableColumn) => {

    if (column.isExport != false) {
      acct.push(column.field);
    }
    return acct;
  }, []);

  this.source.getAll().then((rows) => {

    rows.forEach((row) => {
      fields.forEach((field) => {
        if (row.hasOwnProperty(field)) {
          let value = row[field];

          if (!value) {
            value = "";
          }
          let valuePrepare = this.columnMap.get(field).valuePrepareFunction;
          if (valuePrepare) {
            value = valuePrepare.call(null, value, row);
          }
          encodedStr += '"' + value + '",'
279
        }
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
      });
      encodedStr = encodedStr.slice(0, -1);
      encodedStr += '\r\n';
    });

    let a = document.createElement("a");
    a.setAttribute('style', 'display:none;');
    document.body.appendChild(a);

    //Set utf-8 header to let excel recognize its encoding
    let blob = new Blob(["\ufeff", encodedStr], {type: 'text/csv'});
    a.href = window.URL.createObjectURL(blob);
    a.download = (this.settings.fileName || 'eplaSystemReport') + this.reportId +  '.csv';
    a.click();
  });
}


prepareColumnMap(): void {

  for (const key in this.settings.columns) {

    if (!this.settings.columns.hasOwnProperty(key)) {
      continue;
    }

    const title: string = this.settings.columns[key]['title'];
    let column: TableColumn = new TableColumn();
    column.type = this.settings.columns[key]['type'];
    column.title = this.settings.columns[key]['title'];
    column.field = key;
    column.isDisplay = this.settings.columns[key]['isDisplay'];
    column.isExport = this.settings.columns[key]['isExport'];
    column.valuePrepareFunction = this.settings.columns[key]['valuePrepareFunction'];
    this.columnMap.set(column.field, column);

    if (this.settings.columns[key].isDisplay == false) {
      delete this.settings.columns[key];
    }
319
  }
320 321
}

322

323 324
createDiagram() {
  if (!this.createGraph)  {
325 326 327 328 329
    this.generateGraphData();
    this.createChart();
    this.updateChart();
    this.createGraph = true;
  }
330
}
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352

/*
generateData() {
   this.d3data = [];
   for (let i = 0; i < (8 + Math.floor(Math.random() * 10)); i++) {
     this.d3data.push([
       `Index ${i}`,
       Math.floor(Math.random() * 100)
     ]);
   }
 }
 */

 generateGraphData() {

    this.d3data = [];

    if (this.reportId === 1)  {
      let labelsX = [];
      labelsX.push("1η Προτίμηση");
      labelsX.push("2η Προτίμηση");
      labelsX.push("3η Προτίμηση");
353
      labelsX.push("Μη τοποθετημένοι");
354
      //for (let i = 0; i <  this.data.length; i++) {
355
      for (let i = 1; i <=  4; i++) {
356 357 358
        this.d3data.push([
          //this.data[i].name,
          labelsX[i-1],
359
          this.data[i].numStudents /   this.data[0].numStudents,
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
        ]);
      }
    }
  }

 createChart() {
     let element = this.chartContainer.nativeElement;
     this.width = element.offsetWidth - this.margin.left - this.margin.right;
     this.height = element.offsetHeight - this.margin.top - this.margin.bottom;
     let svg = d3.select(element).append('svg')
       .attr('width', element.offsetWidth)
       .attr('height', element.offsetHeight);

     // chart plot area

     this.chart = svg.append('g')
       .attr('class', 'bars')
       .attr('transform', `translate(${this.margin.left}, ${this.margin.top})`);


     // define X & Y domains
     let xDomain = this.d3data.map(d => d[0]);
     let yDomain = [0, d3.max(this.d3data, d => d[1])];
383
     //let yDomain = [0, 1000];
384 385 386 387

     // create scales
     this.xScale = d3.scaleBand().padding(0.1).domain(xDomain).rangeRound([0, this.width]);
     this.yScale = d3.scaleLinear().domain(yDomain).range([this.height, 0]);
388
     //this.yScale = d3.scaleLinear().domain(yDomain).range([1000, 0]);
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444

     // bar colors
     this.colors = d3.scaleLinear().domain([0, this.d3data.length]).range(<any[]>['red', 'blue']);


     // x & y axis
     this.xAxis = svg.append('g')
       .attr('class', 'axis axis-x')
       .attr('transform', `translate(${this.margin.left}, ${this.margin.top + this.height})`)
       .call(d3.axisBottom(this.xScale));

     this.yAxis = svg.append('g')
       .attr('class', 'axis axis-y')
       .attr('transform', `translate(${this.margin.left}, ${this.margin.top})`)
       .call(d3.axisLeft(this.yScale));

   }

   updateChart() {
    // update scales & axis
    this.xScale.domain(this.d3data.map(d => d[0]));
    this.yScale.domain([0, d3.max(this.d3data, d => d[1])]);
    this.colors.domain([0, this.d3data.length]);
    this.xAxis.transition().call(d3.axisBottom(this.xScale));
    this.yAxis.transition().call(d3.axisLeft(this.yScale));

    let update = this.chart.selectAll('.bar')
      .data(this.d3data);

    // remove exiting bars
    update.exit().remove();

    // update existing bars
    this.chart.selectAll('.bar').transition()
      .attr('x', d => this.xScale(d[0]))
      .attr('y', d => this.yScale(d[1]))
      .attr('width', d => this.xScale.bandwidth())
      .attr('height', d => this.height - this.yScale(d[1]))
      .style('fill', (d, i) => this.colors(i));

    // add new bars
    update
      .enter()
      .append('rect')
      .attr('class', 'bar')
      .attr('x', d => this.xScale(d[0]))
      .attr('y', d => this.yScale(0))
      .attr('width', this.xScale.bandwidth())
      .attr('height', 0)
      .style('fill', (d, i) => this.colors(i))
      .transition()
      .delay((d, i) => i * 10)
      .attr('y', d => this.yScale(d[1]))
      .attr('height', d => this.height - this.yScale(d[1]));
  }

445 446 447 448
  charIsHidden() {
    if (this.reportId === 2 || this.reportId === 3)
      return true;
  }
449 450 451


}