application.submit.ts 11.7 KB
Newer Older
1 2 3 4 5 6 7 8
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';
//import { StudentDataFieldsActions } from '../../actions/studentdatafields.actions';
9 10 11 12 13 14 15 16 17 18 19
import { IStudentDataFields } from '../../store/studentdatafields/studentdatafields.types';
//import { RegionSchoolsActions } from '../../actions/regionschools.actions';
import { IRegions } from '../../store/regionschools/regionschools.types';
//import { CriteriaActions } from '../../actions/criteria.actions';
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';
20 21 22 23 24 25
import {AppSettings} from '../../app.settings';

@Component({
    selector: 'application-submit',
    template: `
      <application-preview-select></application-preview-select>
26 27 28 29 30 31 32 33 34 35 36

      <div *ngFor="let loginInfoToken$ of loginInfo$ | async;"> </div>
      <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 criter$ of criteria$ | async; let i=index"> </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>
      <div *ngFor="let epalclass$ of epalclasses$ | async;"> </div>

37 38 39 40 41
      <button type="button" class="btn-primary btn-lg pull-center" (click)="submitNow()">Υποβολή</button>
  `
})

@Injectable() export default class ApplicationSubmit implements OnInit {
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
    //private studentepalchosen;
    //private studentcoursechosen;
    //private studentsectorchosen;
    //private studentcriteriachosen;

    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;

    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>;
63 64 65 66 67 68 69 70

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

    ngOnInit() {
71 72 73 74 75 76 77 78 79
      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;
      });
80

81 82 83 84 85 86 87 88 89 90 91
      this.epalclasses$ = this._ngRedux.select(state => {
        if (state.epalclasses.size > 0) {
            state.epalclasses.reduce(({}, epalclass) => {
                this.classSelected = epalclass.name;
                console.log("Hey!");
                console.log(this.classSelected);
                return epalclass;
            }, {});
        }
        return state.epalclasses;
      });
92

93 94 95 96
      this.studentDataFields$ = this._ngRedux.select(state => {
          if (state.studentDataFields.size > 0) {
              state.studentDataFields.reduce(({}, studentDataField) => {
                  this.student = studentDataField;
97 98
                  return studentDataField;
              }, {});
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
          }
          return state.studentDataFields;
      });

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

117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
      this.criteria$ = this._ngRedux.select(state => {
          if (state.criter.size > 0) {
              state.criter.reduce(({}, criteria) => {
                  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);
                  console.log("Criteria");
                    console.log(this.studentCriteria);
142

143 144
                  return criteria;
              }, {});
145
          }
146 147
          return state.criter;
      });
148

149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
      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;
      });

      this.sectorFields$ = this._ngRedux.select(state => {
          state.sectorFields.reduce(({}, sectorField) =>{
            if (sectorField.selected === true) {
              this.sectorSelected = sectorField.id
166
            }
167 168 169 170
            return sectorField;
          }, {});
          return state.sectorFields;
      });
171 172


173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
    };

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

          console.log(aitisiObj);

          this.submitRecord(aitisiObj);
202 203
  }

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

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


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
  submitRecord(record) {
    console.log("Here...");
    console.log(this.authToken);
    let auth_str = this.authToken + ":" + this.authToken;
    let auth_str2 = "nkatsaounos" + ":" + "zemraime";
    console.log(auth_str);
    console.log(auth_str2);
    let s = btoa(auth_str);
    let s2 = btoa(auth_str2);
    console.log(s);
    console.log(s2);


    this.authToken = auth_str2;

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

    //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`;
    let connectionString = `${AppSettings.API_ENDPOINT}/epal/appsubmit`;
    //this.http.post(`${AppSettings.API_ENDPOINT}/entity/epal_student`, this.student, options)
    //this.http.post(connectionString, { "search": "person" }, 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("Επιτυχές post στο route υποβολής " ); console.log("success post"); }, // put the data returned from the server in our variable
      error => {alert("Αποτυχές post στο route υποβολής " ); 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);

  }


274
}
275 276 277 278 279 280 281 282 283 284


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