application.submit.ts 13 KB
Newer Older
1 2 3 4 5 6 7
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Http, Response, RequestOptions, Headers } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { Injectable } from "@angular/core";
import { NgRedux, select } from 'ng2-redux';
import { IAppState } from '../../store/store';
8 9 10 11 12 13 14 15 16
import { IStudentDataFields } from '../../store/studentdatafields/studentdatafields.types';
import { IRegions } from '../../store/regionschools/regionschools.types';
import { ICriter } from '../../store/criteria/criteria.types';
import { ISectors } from '../../store/sectorcourses/sectorcourses.types';
import { ISectorFields } from '../../store/sectorfields/sectorfields.types';
import { IEpalClasses } from '../../store/epalclasses/epalclasses.types';
import { ILoginInfo } from '../../store/logininfo/logininfo.types';

import { Student, StudentEpalChosen, StudentCourseChosen, StudentSectorChosen, StudentCriteriaChosen } from '../students/student';
17 18 19 20 21 22
import {AppSettings} from '../../app.settings';

@Component({
    selector: 'application-submit',
    template: `
      <application-preview-select></application-preview-select>
23

24 25 26 27 28 29 30 31 32
      <div class = "loading" *ngIf="showLoaderLogin$ | async"></div>
      <div class = "loading" *ngIf="showLoaderClasses$ | async"></div>
      <div class = "loading" *ngIf="showLoaderStudent$ | async"></div>
      <div class = "loading" *ngIf="showLoaderSchools$ | async"></div>
      <div class = "loading" *ngIf="showLoaderCriteria$ | async"></div>
      <div class = "loading" *ngIf="showLoaderCourses$ | async"></div>
      <div class = "loading" *ngIf="showLoaderSectors$ | async"></div>

      <!--
33
      <div *ngFor="let loginInfoToken$ of loginInfo$ | async;"> </div>
34
      <div *ngFor="let epalclass$ of epalclasses$ | async;"> </div>
35 36 37 38 39 40
      <div *ngFor="let studentDataField$ of studentDataFields$ | async; "> </div>
      <div *ngFor="let region$ of regions$ | async;">
        <div *ngFor="let epal$ of region$.epals "> </div> </div>
      <div *ngFor="let sector$ of sectors$ | async;">
        <div *ngFor="let course$ of sector$.courses;"> </div> </div>
      <div *ngFor="let sectorField$ of sectorFields$ | async;"></div>
41 42
      <div *ngFor="let criter$ of criteria$ | async;"> </div>
      -->
43

44
      <button type="button" class="btn-primary btn-lg pull-center" (click)="submitNow()">Υποβολή</button>
45
      
46 47 48 49
  `
})

@Injectable() export default class ApplicationSubmit implements OnInit {
50 51 52 53 54 55 56 57 58 59

    private authToken;
    private student;
    private epalSelected: Array<number> = new Array();
    private epalSelectedOrder: Array<number> = new Array();
    private studentCriteria: Array<number> = new Array();
    private courseSelected;
    private sectorSelected;
    private classSelected;

60 61 62 63 64 65 66 67
    private showLoaderLogin$: Observable<boolean>;
    private showLoaderClasses$: Observable<boolean>;
    private showLoaderStudent$: Observable<boolean>;
    private showLoaderSchools$: Observable<boolean>;
    private showLoaderCriteria$: Observable<boolean>;
    private showLoaderCourses$: Observable<boolean>;
    private showLoaderSectors$: Observable<boolean>;

68 69 70 71 72 73 74
    private studentDataFields$: Observable<IStudentDataFields>;
    private regions$: Observable<IRegions>;
    private criteria$: Observable<ICriter>;
    private sectors$: Observable<ISectors>;
    private sectorFields$: Observable<ISectorFields>;
    private epalclasses$: Observable<IEpalClasses>;
    private loginInfo$: Observable<ILoginInfo>;
75 76 77 78 79 80 81 82

    constructor(private _ngRedux: NgRedux<IAppState>,
                private router: Router,
                private http: Http
            ) {
    };

    ngOnInit() {
83 84 85 86 87 88 89 90 91
      this.loginInfo$ = this._ngRedux.select(state => {
          if (state.loginInfo.size > 0) {
              state.loginInfo.reduce(({}, loginInfoToken) => {
                  this.authToken = loginInfoToken.auth_token;
                  return loginInfoToken;
              }, {});
          }
          return state.loginInfo;
      });
92
      this.showLoaderLogin$ = this.loginInfo$.map(loginInfo => loginInfo.size === 0);
93

94 95 96 97 98 99 100 101 102
      this.epalclasses$ = this._ngRedux.select(state => {
        if (state.epalclasses.size > 0) {
            state.epalclasses.reduce(({}, epalclass) => {
                this.classSelected = epalclass.name;
                return epalclass;
            }, {});
        }
        return state.epalclasses;
      });
103
      this.showLoaderClasses$ = this.epalclasses$.map(epalclasses => epalclasses.size === 0);
104

105 106 107 108
      this.studentDataFields$ = this._ngRedux.select(state => {
          if (state.studentDataFields.size > 0) {
              state.studentDataFields.reduce(({}, studentDataField) => {
                  this.student = studentDataField;
109 110
                  return studentDataField;
              }, {});
111 112 113
          }
          return state.studentDataFields;
      });
114
      this.showLoaderStudent$ = this.studentDataFields$.map(studentDataFields => studentDataFields.size === 0);
115 116 117 118 119 120 121 122 123 124 125 126 127 128

      this.regions$ = this._ngRedux.select(state => {
          state.regions.reduce((prevRegion, region) =>{
              region.epals.reduce((prevEpal, epal) =>{
                  if (epal.selected === true) {
                    this.epalSelected.push(Number(epal.epal_id));
                    this.epalSelectedOrder.push(epal.order_id);
                  }
                  return epal;
              }, {});
              return region;
          }, {});
          return state.regions;
      });
129
      this.showLoaderSchools$ = this.regions$.map(regions => regions.size === 0);
130

131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
      this.criteria$ = this._ngRedux.select(state => {
          if (state.criter.size > 0) {
              state.criter.reduce(({}, criteria) => {
                //code to be replaced in next version
                  if (criteria.selected === true && Number(criteria.id) !== 11)
                      this.studentCriteria.push(Number(criteria.id));

                  return criteria;
              }, {});
          }
          return state.criter;
      });
      this.showLoaderCriteria$ = this.criteria$.map(criter => criter.size === 0);

      /*
146 147 148
      this.criteria$ = this._ngRedux.select(state => {
          if (state.criter.size > 0) {
              state.criter.reduce(({}, criteria) => {
149
                //code to be replaced in next version
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
                  if (criteria.orphanmono === true)
                    this.studentCriteria.push(6);
                  else if (criteria.orphantwice === true)
                    this.studentCriteria.push(1);
                  if (criteria.threechildren === true)
                    this.studentCriteria.push(11);
                  else if (criteria.manychildren === true)
                    this.studentCriteria.push(2);
                  if (criteria.twins === true)
                    this.studentCriteria.push(3);
                  if (criteria.disability === true)
                    this.studentCriteria.push(5);
                  if (criteria.studies === true)
                    this.studentCriteria.push(4);
                  if (criteria.income === '<= 3000 Ευρώ')
                    this.studentCriteria.push(7);
                  else if (criteria.income === '<= 6000 Ευρώ')
                    this.studentCriteria.push(8);
                  else if (criteria.income === '<= 9000 Ευρώ')
                    this.studentCriteria.push(9);
170

171 172
                  return criteria;
              }, {});
173
          }
174 175
          return state.criter;
      });
176
      this.showLoaderCriteria$ = this.criteria$.map(criter => criter.size === 0);
177
      */
178

179 180 181 182 183 184 185 186 187 188 189 190
      this.sectors$ = this._ngRedux.select(state => {
          state.sectors.reduce((prevSector, sector) =>{
              sector.courses.reduce((prevCourse, course) =>{
                  if (course.selected === true) {
                    this.courseSelected = course.course_id
                  }
                  return course;
              }, {});
              return sector;
          }, {});
          return state.sectors;
      });
191
      this.showLoaderCourses$ = this.sectors$.map(sectors => sectors.size === 0 && this.classSelected === "Γ' Λυκείου");
192 193 194 195 196

      this.sectorFields$ = this._ngRedux.select(state => {
          state.sectorFields.reduce(({}, sectorField) =>{
            if (sectorField.selected === true) {
              this.sectorSelected = sectorField.id
197
            }
198 199 200 201
            return sectorField;
          }, {});
          return state.sectorFields;
      });
202

203 204
      this.showLoaderSectors$ = this.sectorFields$.map(sectorFields => sectorFields.size === 0 && this.classSelected === "Β' Λυκείου");

205

206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
    };

    submitNow() {
          //αποστολή στοιχείων μαθητή στο entity: epal_student
          let aitisiObj: Array<Student | StudentEpalChosen[] | StudentCriteriaChosen[] | StudentCourseChosen | StudentSectorChosen > = [];
          let epalObj: Array<StudentEpalChosen> = [];
          let criteriaObj: Array<StudentCriteriaChosen> = [];

          //aitisiObj[0] = studentDataFields["_tail"]["array"][0];
          aitisiObj[0] = this.student;
          aitisiObj[0]['currentclass'] = this.classSelected;
          //aitisiObj[0]['studentamka'] = ...;

          for (let i=0; i < this.epalSelected.length; i++)
            epalObj[i] =new StudentEpalChosen(null, this.epalSelected[i] , this.epalSelectedOrder[i]);
          aitisiObj['1'] =   epalObj;

          for (let i=0; i < this.studentCriteria.length; i++)
            criteriaObj[i] =new StudentCriteriaChosen(null, null, this.studentCriteria[i]);
          aitisiObj['2'] = criteriaObj;

          if (aitisiObj[0]['currentclass'] === "Β' Λυκείου" )
            aitisiObj['3'] =  new StudentSectorChosen(null, this.sectorSelected);
          else if (aitisiObj[0]['currentclass'] === "Γ' Λυκείου" )
            aitisiObj['3'] =  new StudentCourseChosen(null, this.courseSelected);

232
          //console.log(aitisiObj);
233 234

          this.submitRecord(aitisiObj);
235 236
  }

237
  submitRecord_ver1(entityName, record)  {
238 239 240 241 242 243
      let headers = new Headers({
         "Authorization": "Basic bmthdHNhb3Vub3M6emVtcmFpbWU=",
        "Accept": "*/*",
        "Access-Control-Allow-Credentials": "true",
        "Content-Type": "application/json",
        // "Content-Type": "text/plain",  // try to skip preflight
244
        "X-CSRF-Token": "Me9oRh6jrAOAJ2rsnu_3lOLxqA_WMoJLeJ7dhe4HTBA"
245 246 247 248 249 250 251 252 253 254 255 256 257 258
      });

      let options = new RequestOptions({ headers: headers, withCredentials: true });
      let connectionString = `${AppSettings.API_ENDPOINT}/entity/` + entityName;
      //this.http.post(`${AppSettings.API_ENDPOINT}/entity/epal_student`, this.student, options)
      this.http.post(connectionString, record, options)
        // Call map on the response observable to get the parsed people object
        .map((res: Response) => res.json())
        .subscribe(success => {alert("Επιτυχής αποστολή στοιχείων στο entity: " + entityName); console.log("success post")}, // put the data returned from the server in our variable
        error => {alert("Αποτυχία αποστολής στοιχείων στο entity: " + entityName); console.log("Error HTTP POST Service")}, // in case of failure show this message
        () => console.log("write this message anyway"));//run this code in all cases);
  }


259 260
  submitRecord(record) {
    let auth_str = this.authToken + ":" + this.authToken;
261 262
    //let authTokenPost = "nkatsaounos" + ":" + "...";
    let authTokenPost = this.authToken + ":" + this.authToken;
263 264

    let headers = new Headers({
265
       "Authorization": "Basic " + btoa(authTokenPost),
266 267 268
       "Accept": "*/*",
       "Access-Control-Allow-Credentials": "true",
       "Content-Type": "application/json",
269
      // "X-CSRF-Token": "Pz3psGTGpc-EGNLm3tgzCpqEMg3HW0fCKf8xOnQLAsc"
270 271 272 273 274 275 276 277 278 279 280 281 282
    });

    //let headers = new Headers({
    //   "Authorization": "Basic bmthdHNhb3Vub3M6emVtcmFpbWU=",
    //  "Accept": "*/*",
    //  "Access-Control-Allow-Credentials": "true",
    //  "Content-Type": "application/json",
    //  "X-CSRF-Token": "Pz3psGTGpc-EGNLm3tgzCpqEMg3HW0fCKf8xOnQLAsc"
    //});


    let options = new RequestOptions({ headers: headers,  method: "post", withCredentials: true });
    let connectionString = `${AppSettings.API_ENDPOINT}/epal/appsubmit`;
283

284 285 286
    this.http.post(connectionString, record, options)
      // Call map on the response observable to get the parsed people object
      .map((res: Response) => res.json())
287 288
      .subscribe(
      success => {alert("Επιτυχές post στο route υποβολής " ); console.log("success post"); }, // put the data returned from the server in our variable
289
      error => {alert("Αποτυχές post στο route υποβολής " ); console.log("Error HTTP POST Service")}, // in case of failure show this message
290
      () => console.log("write this message anyway"),
291

292
      );//run this code in all cases);
293

294 295 296
  //});

  }
297

298
}
299 300 301 302 303 304 305 306 307 308


//Get Data - sync methods
/*
const { studentDataFields } = this._ngRedux.getState();
const { epalclasses } = this._ngRedux.getState();
const { regions } = this._ngRedux.getState();
const { amkafills } = this._ngRedux.getState();
const { sectors } = this._ngRedux.getState();
*/