application.submit.ts 12.6 KB
Newer Older
1
import { Component, OnInit, OnDestroy } from '@angular/core';
2 3
import { Router } from '@angular/router';
import { Http, Response, RequestOptions, Headers } from '@angular/http';
4
import { BehaviorSubject, Subscription } from 'rxjs/Rx';
5 6 7
import { Injectable } from "@angular/core";
import { NgRedux, select } from 'ng2-redux';
import { IAppState } from '../../store/store';
8 9 10 11 12 13 14
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';
15 16 17 18 19 20 21
import { STUDENT_DATA_FIELDS_INITIAL_STATE } from '../../store/studentdatafields/studentdatafields.initial-state';
import { CRITERIA_INITIAL_STATE } from '../../store/criteria/criteria.initial-state';
import { REGION_SCHOOLS_INITIAL_STATE } from '../../store/regionschools/regionschools.initial-state';
import { EPALCLASSES_INITIAL_STATE } from '../../store/epalclasses/epalclasses.initial-state';
import { SECTOR_COURSES_INITIAL_STATE } from '../../store/sectorcourses/sectorcourses.initial-state';
import { SECTOR_FIELDS_INITIAL_STATE } from '../../store/sectorfields/sectorfields.initial-state';
import { LOGININFO_INITIAL_STATE } from '../../store/logininfo/logininfo.initial-state';
22
import { Student, StudentEpalChosen, StudentCourseChosen, StudentSectorChosen, StudentCriteriaChosen } from '../students/student';
23 24 25 26 27
import {AppSettings} from '../../app.settings';

@Component({
    selector: 'application-submit',
    template: `
28 29 30
        <div class = "loading" *ngIf="(studentDataFields$ | async).size === 0 || (criteria$ | async).size === 0 || (regions$ | async).size === 0 || (epalclasses$ | async).size === 0 || (loginInfo$ | async).size === 0"></div>
        <application-preview-select></application-preview-select>
        <button type="button button-lg pull-right" *ngIf="(studentDataFields$ | async).size > 0 && (criteria$ | async).size > 0 && (regions$ | async).size > 0 && (epalclasses$ | async).size > 0 && (loginInfo$ | async).size > 0" class="btn-primary btn-lg pull-center" (click)="submitNow()">Υποβολή</button>
31 32 33 34
  `
})

@Injectable() export default class ApplicationSubmit implements OnInit {
35 36 37 38 39 40 41 42 43

    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;
44
    private totalPoints=  <number>0;
45 46 47 48 49 50 51 52 53 54 55 56 57 58
    private studentDataFields$: BehaviorSubject<IStudentDataFields>;
    private regions$: BehaviorSubject<IRegions>;
    private criteria$: BehaviorSubject<ICriter>;
    private sectors$: BehaviorSubject<ISectors>;
    private sectorFields$: BehaviorSubject<ISectorFields>;
    private epalclasses$: BehaviorSubject<IEpalClasses>;
    private loginInfo$: BehaviorSubject<ILoginInfo>;
    private studentDataFieldsSub: Subscription;
    private regionsSub: Subscription;
    private criteriaSub: Subscription;
    private sectorsSub: Subscription;
    private sectorFieldsSub: Subscription;
    private epalclassesSub: Subscription;
    private loginInfoSub: Subscription;
59 60 61 62 63

    constructor(private _ngRedux: NgRedux<IAppState>,
                private router: Router,
                private http: Http
            ) {
64 65 66 67 68 69 70 71 72

                this.regions$ = new BehaviorSubject(REGION_SCHOOLS_INITIAL_STATE);
                this.epalclasses$ = new BehaviorSubject(EPALCLASSES_INITIAL_STATE);
                this.sectors$ = new BehaviorSubject(SECTOR_COURSES_INITIAL_STATE);
                this.sectorFields$ = new BehaviorSubject(SECTOR_FIELDS_INITIAL_STATE);
                this.studentDataFields$ = new BehaviorSubject(STUDENT_DATA_FIELDS_INITIAL_STATE);
                this.criteria$ = new BehaviorSubject(CRITERIA_INITIAL_STATE);
                this.loginInfo$ = new BehaviorSubject(LOGININFO_INITIAL_STATE);

73 74 75
    };

    ngOnInit() {
76
      this.loginInfoSub = this._ngRedux.select(state => {
77 78 79 80 81 82 83
          if (state.loginInfo.size > 0) {
              state.loginInfo.reduce(({}, loginInfoToken) => {
                  this.authToken = loginInfoToken.auth_token;
                  return loginInfoToken;
              }, {});
          }
          return state.loginInfo;
84
      }).subscribe(this.loginInfo$);
85

86
      this.epalclassesSub = this._ngRedux.select(state => {
87 88 89 90 91 92 93
        if (state.epalclasses.size > 0) {
            state.epalclasses.reduce(({}, epalclass) => {
                this.classSelected = epalclass.name;
                return epalclass;
            }, {});
        }
        return state.epalclasses;
94
      }).subscribe(this.epalclasses$);
95

96
      this.studentDataFieldsSub = this._ngRedux.select(state => {
97 98 99
          if (state.studentDataFields.size > 0) {
              state.studentDataFields.reduce(({}, studentDataField) => {
                  this.student = studentDataField;
100 101
                  return studentDataField;
              }, {});
102 103
          }
          return state.studentDataFields;
104
      }).subscribe(this.studentDataFields$);
105

106
      this.regionsSub = this._ngRedux.select(state => {
107 108 109 110 111 112 113 114 115 116 117
          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;
118
      }).subscribe(this.regions$);
119

120
      this.criteriaSub = this._ngRedux.select(state => {
121 122 123
          if (state.criter.size > 0) {
              state.criter.reduce(({}, criteria) => {
                //code to be replaced in next version
124 125
                  //if (criteria.selected === true && Number(criteria.id) !== 11)
                  if (criteria.selected === true )  {
126
                      this.studentCriteria.push(Number(criteria.id));
127 128
                      this.totalPoints = this.totalPoints + Number(criteria.points);
                    }
129 130 131 132 133

                  return criteria;
              }, {});
          }
          return state.criter;
134
      }).subscribe(this.criteria$);
135

136
      this.sectorsSub = this._ngRedux.select(state => {
137 138 139 140 141 142 143 144 145 146
          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;
147
      }).subscribe(this.sectors$);
148

149
      this.sectorFieldsSub = this._ngRedux.select(state => {
150 151 152
          state.sectorFields.reduce(({}, sectorField) =>{
            if (sectorField.selected === true) {
              this.sectorSelected = sectorField.id
153
            }
154 155 156
            return sectorField;
          }, {});
          return state.sectorFields;
157
      }).subscribe(this.sectorFields$);
158

159 160
    };

161 162 163 164 165 166 167 168
    ngOnDestroy() {
        if (this.studentDataFieldsSub) this.studentDataFieldsSub.unsubscribe();
        if (this.criteriaSub) this.criteriaSub.unsubscribe();
        if (this.regionsSub) this.regionsSub.unsubscribe();
        if (this.sectorsSub) this.sectorsSub.unsubscribe();
        if (this.sectorFieldsSub) this.sectorFieldsSub.unsubscribe();
        if (this.epalclassesSub) this.epalclassesSub.unsubscribe();
        if (this.loginInfoSub) this.loginInfoSub.unsubscribe();
169 170 171 172 173 174 175
        this.regions$.unsubscribe();
        this.epalclasses$.unsubscribe();
        this.sectors$.unsubscribe();
        this.sectorFields$.unsubscribe();
        this.studentDataFields$.unsubscribe();
        this.criteria$.unsubscribe();
        this.loginInfo$.unsubscribe();
176 177
    }

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

          aitisiObj[0] = this.student;
185
          //console.log(aitisiObj[0]['studentbirthdate']);
186 187
          aitisiObj[0]['currentclass'] = this.classSelected;
          //aitisiObj[0]['studentamka'] = ...;
188
          aitisiObj[0]['points'] = this.totalPoints;
189 190 191 192 193 194 195 196 197 198 199 200 201 202

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

203
          //console.log(aitisiObj);
204 205

          this.submitRecord(aitisiObj);
206 207
  }

208
  submitRecord_ver1(entityName, record)  {
209 210 211 212 213 214
      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
215
        "X-CSRF-Token": "Me9oRh6jrAOAJ2rsnu_3lOLxqA_WMoJLeJ7dhe4HTBA"
216 217 218 219 220 221 222 223 224 225 226 227 228 229
      });

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


230 231
  submitRecord(record) {
    let auth_str = this.authToken + ":" + this.authToken;
232 233
    //let authTokenPost = "nkatsaounos" + ":" + "...";
    let authTokenPost = this.authToken + ":" + this.authToken;
234 235

    let headers = new Headers({
236
       "Authorization": "Basic " + btoa(authTokenPost),
237 238 239
       "Accept": "*/*",
       "Access-Control-Allow-Credentials": "true",
       "Content-Type": "application/json",
240
      // "X-CSRF-Token": "Pz3psGTGpc-EGNLm3tgzCpqEMg3HW0fCKf8xOnQLAsc"
241 242 243 244 245 246 247 248 249 250 251 252 253
    });

    //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`;
254

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

263
      );//run this code in all cases);
264

265 266 267
  //});

  }
268

269
}
270 271 272 273 274 275 276 277 278 279


//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();
*/