minister-reports.ts 21.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
        <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>

        <!--
66
        <div
67
          class = "loading" *ngIf="(!validCreator && reportId)" >
68
        </div>
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
        -->

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

        <div class="col-md-1">
          <!--
          <button type="button" class="btn btn-alert"  (click)="createReport('/ministry/general-report/', regsel)" [hidden]="minedu_userName == ''" >
          <i class="fa fa-file-text"></i>
              Κατανομή Μαθητών με Βάση τη Σειρά Προτίμησης
          </button>
          <br><br>
          <button type="button" class="btn btn-alert"  (click)="createReport('/ministry/report-completeness/', regsel)" [hidden]="minedu_userName == ''" >
          <i class="fa fa-file-text"></i>
              Πληρότητα Σχολείων
          </button>
          <br><br>
          <button type="button" class="btn btn-alert"  (click)="createReport('/ministry/report-all-stat/', regsel)" [hidden]="minedu_userName == ''" >
          <i class="fa fa-file-text"></i>
              Μαθητές ανά Τάξη/Τομέα/Ειδικότητα
          </button>
          <br><br>
          -->
          <button type="button" class="btn btn-alert"  (click)="selectreport(1)" [hidden]="minedu_userName == ''" >
          <i class="fa fa-file-text"></i>
              Κατανομή Μαθητών με Βάση τη Σειρά Προτίμησης
          </button>
          <br><br>
          <button type="button" class="btn btn-alert"  (click)="selectreport(2)" [hidden]="minedu_userName == ''" >
          <i class="fa fa-file-text"></i>
              Πληρότητα Σχολείων
          </button>
          <br><br>
          <button type="button" class="btn btn-alert"  (click)="selectreport(3)" [hidden]="minedu_userName == ''" >
          <i class="fa fa-file-text"></i>
              Μαθητές ανά Τάξη/Τομέα/Ειδικότητα
          </button>
          <br><br>

        </div>

        <!--
        <button type="submit" class="btn btn-default btn-block"  (click)="showFilters()" [hidden]="minedu_userName == ''" >
112
            Μαθητές ανά Τάξη/Τομέα/Ειδικότητα
113
        </button>
114
        -->
115

116

117 118 119 120 121
        <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>
122
        </div>
123

124 125
        <button type="button" class="alert alert-info pull-right" (click)="export2Csv()" [hidden]="!validCreator">
        <i class="fa fa-download"></i>
126 127
            Εξαγωγή σε csv
        </button>
128
        <button type="button" class="alert alert-info pull-left" (click)="createDiagram()" [hidden]="!validCreator ||  charIsHidden() ">
129 130 131
        <i class="fa fa-bar-chart"></i>
            Διάγραμμα
        </button>
132

133 134
    </div>

135
    <div class="d3-chart" *ngIf = "!charIsHidden() && validCreator" #chart>
136 137
    </div>

138 139


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

142 143 144 145 146
   `
})

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

147
    public formGroup: FormGroup;
148 149 150
    loginInfo$: BehaviorSubject<ILoginInfo>;
    loginInfoSub: Subscription;
    private generalReport$: BehaviorSubject<any>;
151 152 153
    private RegionSelections$: BehaviorSubject<any>;
    private AdminAreaSelections$: BehaviorSubject<any>;
    private SchoolSelections$: BehaviorSubject<any>;
154
    private generalReportSub: Subscription;
155 156 157
    private RegionSelectionsSub: Subscription;
    private AdminAreaSelectionsSub: Subscription;
    private SchoolSelectionsSub: Subscription;
158 159 160 161
    private apiEndPoint = API_ENDPOINT;
    private minedu_userName: string;
    private minedu_userPassword: string;
    private distStatus = "READY";
162 163
    private data;
    private validCreator: boolean;
164
    private createGraph: boolean;
165 166
    private reportId: number;
    private source: LocalDataSource;
167 168 169
    private showAdminList: BehaviorSubject<boolean>;
    private adminAreaSelected: number;
    private schSelected: number;
170 171 172 173

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

175 176 177 178 179 180 181 182 183 184 185 186 187
    //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;
188

189
    constructor(private fb: FormBuilder,
190 191 192 193 194
        private _ngRedux: NgRedux<IAppState>,
        private _hds: HelperDataService,
        private activatedRoute: ActivatedRoute,
        private router: Router) {

195 196 197 198 199
          this.formGroup = this.fb.group({
              region: ['', []],
              adminarea: ['', []],
              schoollist: ['', []],
          });
200 201 202

          this.loginInfo$ = new BehaviorSubject(LOGININFO_INITIAL_STATE);
          this.generalReport$ = new BehaviorSubject([{}]);
203 204 205
          this.RegionSelections$ = new BehaviorSubject([{}]);
          this.AdminAreaSelections$ = new BehaviorSubject([{}]);
          this.SchoolSelections$ = new BehaviorSubject([{}]);
206 207
          this.minedu_userName = '';
          this.validCreator = false;
208
          this.createGraph = false;
209
          this.reportId = 0;
210 211 212 213
          this.showAdminList = new BehaviorSubject(false);
          this.adminAreaSelected = 0;
          this.schSelected = 0;
          //this.showAdminList = false;
214
          //this.source = new LocalDataSource(this.data);
215 216 217 218 219 220 221

    }

    ngOnDestroy() {

      if (this.loginInfoSub)
        this.loginInfoSub.unsubscribe();
222
      //this.loginInfo$.unsubscribe();
223 224
      if (this.generalReportSub)
          this.generalReportSub.unsubscribe();
225 226 227 228 229 230 231 232 233
      //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();
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249

    }

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

250
      this.showFilters();
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266




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

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

267 268
    }

269 270 271 272 273 274
selectreport(repId)  {
  this.reportId = repId;
  console.log("...");
  console.log(repId);
}

275

276
createReport(routePath, regionSel) {
277

278
  //this.reportId = 0;
279
  this.validCreator = false;
280 281
  this.createGraph = false;

282
  /*
283 284 285 286 287 288
  if (routePath === "/ministry/general-report/")  {
    this.reportId = 1;
    this.settings = this.reportSchema.genReportSchema;
  }
  else if (routePath === "/ministry/report-completeness/")  {
    this.reportId = 2;
289 290 291 292 293
    this.settings = this.reportSchema.reportCompletenessSchema;
  }
  else if (routePath === "/ministry/report-all-stat/")  {
    this.reportId = 3;
    this.settings = this.reportSchema.reportAllStatSchema;
294
  }
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
  */
  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;
317

318 319 320 321 322 323 324 325 326 327 328 329 330 331
//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 => {
332 333
      this.generalReport$.next(data);
      this.data = data;
334 335 336 337
      console.log("Let see..");
      //console.log(this.data);
      //console.log(this.data[0].name);
      //console.log(this.data.length);
338 339 340 341 342 343 344 345 346 347 348 349
  },
    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;
350 351
      this.columnMap = new Map<string,TableColumn>();
      //columnMap: Map<string,TableColumn> = new Map<string,TableColumn>();
352
      this.prepareColumnMap();
353 354 355 356

      //this.generateData2();
      //this.createChart();
      //this.updateChart();
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 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
  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;

  }


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 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
  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 + '",'
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 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
      });
      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];
    }
538
  }
539 540
}

541

542 543
createDiagram() {
  if (!this.createGraph)  {
544 545 546 547 548
    this.generateGraphData();
    this.createChart();
    this.updateChart();
    this.createGraph = true;
  }
549
}
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571

/*
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η Προτίμηση");
572
      labelsX.push("Μη τοποθετημένοι");
573
      //for (let i = 0; i <  this.data.length; i++) {
574
      for (let i = 1; i <=  4; i++) {
575 576 577
        this.d3data.push([
          //this.data[i].name,
          labelsX[i-1],
578
          this.data[i].numStudents /   this.data[0].numStudents,
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601
        ]);
      }
    }
  }

 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])];
602
     //let yDomain = [0, 1000];
603 604 605 606

     // 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]);
607
     //this.yScale = d3.scaleLinear().domain(yDomain).range([1000, 0]);
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 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663

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

664 665 666 667
  charIsHidden() {
    if (this.reportId === 2 || this.reportId === 3)
      return true;
  }
668 669 670


}