minister-reports.ts 20.2 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 18 19 20 21 22 23 24
import {
    FormBuilder,
    FormGroup,
    FormControl,
    FormArray,
    Validators,
} from '@angular/forms';

25
import * as d3 from 'd3';
26 27


28
//import * as _ from '..';
29 30 31 32 33

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

@Component({
    selector: 'minister-reports',
34
    encapsulation: ViewEncapsulation.None,
35 36
    template: `

37
  <div>
38

39
        <!--
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
        <form [formGroup]="formGroup"  #form>
          <h5> >Επιλογή Φίλτρων <br><br></h5>
          <div class="form-group">
                <label>Περιφερειακή Διεύθυνση</label>
                <select #regsel class="form-control" (change)="checkregion(regsel)" formControlName="region">
                  <option *ngFor="let RegionSelection$  of RegionSelections$ | async; let i=index"  [value] = "RegionSelection$.id"> {{RegionSelection$.name}} </option>
                </select>
          </div>
          <div class="form-group">
                <label *ngIf="showAdminList | async">Διεύθυνση Εκπαίδευσης</label>
                <select #admsel class="form-control"  *ngIf="showAdminList | async"  (change)="checkadminarea(admsel)" formControlName="adminarea">
                  <option *ngFor="let AdminAreaSelection$  of AdminAreaSelections$ | async; let i=index" [value] = "AdminAreaSelection$.id"> {{AdminAreaSelection$.name}} {{AdminAreaSelection$.id}}</option>
                </select>
          </div>
          <div class="form-group">
                <label *ngIf="showAdminList | async">Σχολείο</label>
                <select #schsel class="form-control"  *ngIf="showAdminList | async"  (change)="checkschool(schsel)" formControlName="schoollist">
                  <option *ngFor="let SchoolSelection$  of SchoolSelections$ | async; let i=index" [value] = "SchoolSelection$.epal_id"> {{SchoolSelection$.epal_name}} </option>
                </select>
          </div>
          <button type="submit" class="btn btn-alert"  (click)="createReport(reportId, regsel)" [hidden]="minedu_userName == ''" >
          <i class="fa fa-file-text"></i>
              Δημιουργία Αναφοράς
          </button>
        </form>
        -->

67 68 69 70 71





72 73 74 75
        <h5><br> >Επιλογή Αναφοράς<br><br></h5>
        <!-- btn-block "btn btn-default  -->

        <div class="col-md-1">
76
          <button type="button" class="btn btn-alert"  (click)="nav_to_reportpath(1)" [hidden]="minedu_userName == ''" >
77 78 79 80
          <i class="fa fa-file-text"></i>
              Κατανομή Μαθητών με Βάση τη Σειρά Προτίμησης
          </button>
          <br><br>
81
          <button type="button" class="btn btn-alert"  (click)="nav_to_reportpath(2)" [hidden]="minedu_userName == ''" >
82 83 84 85
          <i class="fa fa-file-text"></i>
              Πληρότητα Σχολείων
          </button>
          <br><br>
86
          <button type="button" class="btn btn-alert"  (click)="nav_to_reportpath(3)" [hidden]="minedu_userName == ''" >
87 88 89 90 91 92 93
          <i class="fa fa-file-text"></i>
              Μαθητές ανά Τάξη/Τομέα/Ειδικότητα
          </button>
          <br><br>
        </div>

        <!--
94 95 96 97 98
        <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>
99
        </div>
100

101 102
        <button type="button" class="alert alert-info pull-right" (click)="export2Csv()" [hidden]="!validCreator">
        <i class="fa fa-download"></i>
103 104
            Εξαγωγή σε csv
        </button>
105
        <button type="button" class="alert alert-info pull-left" (click)="createDiagram()" [hidden]="!validCreator ||  charIsHidden() ">
106 107 108
        <i class="fa fa-bar-chart"></i>
            Διάγραμμα
        </button>
109
        -->
110

111 112
    </div>

113
    <!--
114
    <div class="d3-chart" *ngIf = "!charIsHidden() && validCreator" #chart>
115
    </div>
116
    -->
117

118 119


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

122 123 124 125 126
   `
})

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

127
    public formGroup: FormGroup;
128 129 130
    loginInfo$: BehaviorSubject<ILoginInfo>;
    loginInfoSub: Subscription;
    private generalReport$: BehaviorSubject<any>;
131 132 133
    private RegionSelections$: BehaviorSubject<any>;
    private AdminAreaSelections$: BehaviorSubject<any>;
    private SchoolSelections$: BehaviorSubject<any>;
134
    private generalReportSub: Subscription;
135 136 137
    private RegionSelectionsSub: Subscription;
    private AdminAreaSelectionsSub: Subscription;
    private SchoolSelectionsSub: Subscription;
138 139 140 141
    private apiEndPoint = API_ENDPOINT;
    private minedu_userName: string;
    private minedu_userPassword: string;
    private distStatus = "READY";
142 143
    private data;
    private validCreator: boolean;
144
    private createGraph: boolean;
145 146
    private reportId: number;
    private source: LocalDataSource;
147 148 149
    private showAdminList: BehaviorSubject<boolean>;
    private adminAreaSelected: number;
    private schSelected: number;
150 151 152 153

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

155 156 157 158 159 160 161 162 163 164 165 166 167
    //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;
168

169
    constructor(private fb: FormBuilder,
170 171 172 173 174
        private _ngRedux: NgRedux<IAppState>,
        private _hds: HelperDataService,
        private activatedRoute: ActivatedRoute,
        private router: Router) {

175 176 177 178 179
          this.formGroup = this.fb.group({
              region: ['', []],
              adminarea: ['', []],
              schoollist: ['', []],
          });
180 181 182

          this.loginInfo$ = new BehaviorSubject(LOGININFO_INITIAL_STATE);
          this.generalReport$ = new BehaviorSubject([{}]);
183 184 185
          this.RegionSelections$ = new BehaviorSubject([{}]);
          this.AdminAreaSelections$ = new BehaviorSubject([{}]);
          this.SchoolSelections$ = new BehaviorSubject([{}]);
186 187
          this.minedu_userName = '';
          this.validCreator = false;
188
          this.createGraph = false;
189
          this.reportId = 0;
190 191 192 193
          this.showAdminList = new BehaviorSubject(false);
          this.adminAreaSelected = 0;
          this.schSelected = 0;
          //this.showAdminList = false;
194
          //this.source = new LocalDataSource(this.data);
195 196 197 198 199 200 201

    }

    ngOnDestroy() {

      if (this.loginInfoSub)
        this.loginInfoSub.unsubscribe();
202
      //this.loginInfo$.unsubscribe();
203 204
      if (this.generalReportSub)
          this.generalReportSub.unsubscribe();
205 206 207 208 209 210 211 212 213
      //this.generalReport$.unsubscribe();
      if (this.RegionSelectionsSub)
          this.RegionSelectionsSub.unsubscribe();
      if (this.AdminAreaSelectionsSub)
          this.AdminAreaSelectionsSub.unsubscribe();
      if (this.SchoolSelectionsSub)
          this.SchoolSelectionsSub.unsubscribe();
      if (this.showAdminList)
          this.showAdminList.unsubscribe();
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229

    }

    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$);

230
      this.showFilters();
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246




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

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

247 248
    }

249 250 251


nav_to_reportpath(repId) {
252
  this.reportId = repId;
253 254 255 256 257
  if (this.reportId == 1)
    this.router.navigate(['/ministry/report-general', this.reportId]);
  if (this.reportId == 2 || this.reportId == 3)
    this.router.navigate(['/ministry/report-all-stat', this.reportId]);

258 259
}

260

261
createReport(routePath, regionSel) {
262

263
  //this.reportId = 0;
264
  this.validCreator = false;
265 266
  this.createGraph = false;

267
  /*
268 269 270 271 272 273
  if (routePath === "/ministry/general-report/")  {
    this.reportId = 1;
    this.settings = this.reportSchema.genReportSchema;
  }
  else if (routePath === "/ministry/report-completeness/")  {
    this.reportId = 2;
274 275 276 277 278
    this.settings = this.reportSchema.reportCompletenessSchema;
  }
  else if (routePath === "/ministry/report-all-stat/")  {
    this.reportId = 3;
    this.settings = this.reportSchema.reportAllStatSchema;
279
  }
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
  */
  let route;
  if (routePath === 1)  {
    route = "/ministry/general-report/";
    this.settings = this.reportSchema.genReportSchema;
  }
  else if (routePath === 2)  {
    route = "/ministry/report-completeness/";
    this.settings = this.reportSchema.reportCompletenessSchema;
  }
  else if (routePath === 3)  {
    route = "/ministry/report-all-stat/";
    this.settings = this.reportSchema.reportAllStatSchema;
  }



 let regSel = 0;
 //let admSel = 0, schSel = 0;

 if (regionSel.value != 0)
  regSel = regionSel.value;
302

303 304 305 306 307 308 309 310 311 312 313 314 315 316
//For some reason, template #vars can not work..
 /*
 if (typeof adminSel !== 'undefined') {
  console.log("YES2");
  admSel = adminSel.value;
  console.log("YES3");
}
if (typeof schoolSel !== 'undefined')
  schSel = schoolSel.value;
*/


  //this.generalReportSub = this._hds.makeReport(this.minedu_userName, this.minedu_userPassword, routePath, regSel, this.adminAreaSelected, this.schSelected).subscribe(data => {
  this.generalReportSub = this._hds.makeReport(this.minedu_userName, this.minedu_userPassword, route, regSel, this.adminAreaSelected, this.schSelected).subscribe(data => {
317 318
      this.generalReport$.next(data);
      this.data = data;
319 320 321 322
      console.log("Let see..");
      //console.log(this.data);
      //console.log(this.data[0].name);
      //console.log(this.data.length);
323 324 325 326 327 328 329 330 331 332 333 334
  },
    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;
335 336
      this.columnMap = new Map<string,TableColumn>();
      //columnMap: Map<string,TableColumn> = new Map<string,TableColumn>();
337
      this.prepareColumnMap();
338 339 340 341

      //this.generateData2();
      //this.createChart();
      //this.updateChart();
342
    }
343
  )
344

345
}
346

347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 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
  showFilters() {
    //this.reportId = 3;

    this.RegionSelectionsSub = this._hds.getRegions(this.minedu_userName, this.minedu_userPassword).subscribe(data => {
        this.RegionSelections$.next(data);
    },
        error => {
            this.RegionSelections$.next([{}]);
            console.log("Error Getting RegionSelections");
        },
        () => console.log("Success Getting RegionSelectionsSub"));

  }

  checkregion(regionId) {

    this.adminAreaSelected = 0;
    this.schSelected = 0;

    this.AdminAreaSelectionsSub = this._hds.getAdminAreas(this.minedu_userName, this.minedu_userPassword, regionId.value).subscribe(data => {
        this.AdminAreaSelections$.next(data);
    },
        error => {
            this.AdminAreaSelections$.next([{}]);
            console.log("Error Getting AdminAreaSelections");
        },
        () => {
          console.log("Success Getting AdminAreaSelectionsSub");
          this.showAdminList.next(true);
        }
      );

      this.SchoolSelectionsSub = this._hds.getSchoolsPerRegion(this.minedu_userName, this.minedu_userPassword, regionId.value).subscribe(data => {
          this.SchoolSelections$.next(data);
      },
          error => {
              this.SchoolSelections$.next([{}]);
              console.log("Error Getting SchoolSelections");
          },
          () => {
            console.log("Success Getting SchoolSelectionsSub");
            this.showAdminList.next(true);
          }

        );

  }

  checkadminarea(adminId) {

    this.schSelected = 0;

    console.log("TI EINAI;")
    console.log(adminId);
    console.log(adminId.value);

    this.adminAreaSelected = adminId.value;
    this.SchoolSelectionsSub = this._hds.getSchoolsPerAdminArea(this.minedu_userName, this.minedu_userPassword, adminId.value).subscribe(data => {
        this.SchoolSelections$.next(data);
    },
        error => {
            this.SchoolSelections$.next([{}]);
            console.log("Error Getting SchoolSelections");
        },
        () => {
          console.log("Success Getting SchoolSelectionsSub");
          this.showAdminList.next(true);
        }

      );
  }

  checkschool(schId) {

      this.schSelected = schId.value;

  }


426

427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
  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 + '",'
483
        }
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
      });
      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];
    }
523
  }
524 525
}

526

527 528
createDiagram() {
  if (!this.createGraph)  {
529 530 531 532 533
    this.generateGraphData();
    this.createChart();
    this.updateChart();
    this.createGraph = true;
  }
534
}
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556

/*
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η Προτίμηση");
557
      labelsX.push("Μη τοποθετημένοι");
558
      //for (let i = 0; i <  this.data.length; i++) {
559
      for (let i = 1; i <=  4; i++) {
560 561 562
        this.d3data.push([
          //this.data[i].name,
          labelsX[i-1],
563
          this.data[i].numStudents /   this.data[0].numStudents,
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
        ]);
      }
    }
  }

 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])];
587
     //let yDomain = [0, 1000];
588 589 590 591

     // 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]);
592
     //this.yScale = d3.scaleLinear().domain(yDomain).range([1000, 0]);
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648

     // 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]));
  }

649 650 651 652
  charIsHidden() {
    if (this.reportId === 2 || this.reportId === 3)
      return true;
  }
653 654 655


}