helper-data-service.ts 17.1 KB
Newer Older
1
import {Http, Headers, RequestOptions} from '@angular/http';
2 3 4 5
import {Injectable} from '@angular/core';
import {Observable} from "rxjs/Observable";
import 'rxjs/add/operator/map';
import { ICourseField } from '../store/coursefields/coursefields.types';
6
import { ISectorField } from '../store/sectorfields/sectorfields.types';
7
import { IRegion, IRegions, IRegionSchool } from '../store/regionschools/regionschools.types';
8
import { ISector, ISectors, ISectorCourse } from '../store/sectorcourses/sectorcourses.types';
Open Source Developer's avatar
Open Source Developer committed
9
//import { IClassField } from '../store/classfields/classfields.types';
10
import { AppSettings } from '../app.settings';
11 12
import { NgRedux, select } from 'ng2-redux';
import { IAppState } from '../store/store';
13
import { ILoginInfo, ILoginInfoToken } from '../store/logininfo/logininfo.types';
14 15 16 17 18 19


const HEADER = { headers: new Headers({ 'Content-Type': 'application/json' }) };

@Injectable()
export class HelperDataService {
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36

    private authToken: string;
    private loginInfo$: Observable<ILoginInfo>;

    constructor(
        private http: Http,
        private _ngRedux: NgRedux<IAppState>) {
            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;
            });

37
    };
38 39

    createAuthorizationHeader(headers: Headers) {
40
        headers.append('Authorization', 'Basic ' + btoa(this.authToken + ':' + this.authToken));
41 42
    }

43 44 45 46 47 48 49 50 51 52 53 54 55
    getEpalUserData() {
        this.loginInfo$.forEach(loginInfoToken => {
            this.authToken = loginInfoToken.get(0).auth_token;
        });
        let headers = new Headers({
            "Content-Type": "application/json",
        });
        this.createAuthorizationHeader(headers);
        let options = new RequestOptions({ headers: headers });
        return this.http.get(`${AppSettings.API_ENDPOINT}/epal/userdata`, options)
            .map(response => response.json());
    };

56 57 58 59 60 61 62 63 64 65 66 67 68 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
    sendVerificationCode(email) {
        this.loginInfo$.forEach(loginInfoToken => {
            this.authToken = loginInfoToken.get(0).auth_token;
        });
        let headers = new Headers({
           "Content-Type": "application/json",
//            "Accept": "*/*",
//            "Access-Control-Allow-Credentials": "true",
        });
        this.createAuthorizationHeader(headers);
//        let options = new RequestOptions({ headers: headers, withCredentials: true });
        let options = new RequestOptions({ headers: headers });
        return new Promise((resolve, reject) => {
            this.http.post(`${AppSettings.API_ENDPOINT}/epal/user/sendvercode`, {userEmail: email}, options)
            .map(response => response.json())
            .subscribe(data => {
                resolve(data);
            }, // put the data returned from the server in our variable
            error => {
                console.log("Error Sending Verification Code"); // in case of failure show this message
                reject("Error Sending Verification Code");
            },
            () => console.log("Sending Verification Code"));//run this code in all cases); */
        });
    }

    verifyVerificationCode(verificationCode) {
        this.loginInfo$.forEach(loginInfoToken => {
            this.authToken = loginInfoToken.get(0).auth_token;
        });
        let headers = new Headers({
           "Content-Type": "application/json",
//            "Accept": "*/*",
//            "Access-Control-Allow-Credentials": "true",
        });
        this.createAuthorizationHeader(headers);
//        let options = new RequestOptions({ headers: headers, withCredentials: true });
        let options = new RequestOptions({ headers: headers });
        return new Promise((resolve, reject) => {
            console.log("verificationCode=" + verificationCode);
            this.http.post(`${AppSettings.API_ENDPOINT}/epal/user/verifyvercode`, {verificationCode: verificationCode}, options)
            .map(response => response.json())
            .subscribe(data => {
                resolve(<any>data);
            }, // put the data returned from the server in our variable
            error => {
                console.log("Error Verifying Verification Code"); // in case of failure show this message
                reject("Error Verifying Verification Code");
            },
            () => console.log("Verifying Verification Code"));//run this code in all cases); */
        });
    }

109
    getCourseFields() {
110 111 112 113

        this.loginInfo$.forEach(loginInfoToken => {
            this.authToken = loginInfoToken.get(0).auth_token;
        });
114 115 116
        let headers = new Headers({
            //"Authorization": "Basic cmVzdHVzZXI6czNjckV0MFAwdWwwJA==", // encoded user:pass
            // "Authorization": "Basic bmthdHNhb3Vub3M6emVtcmFpbWU=",
117

118 119 120 121
            "Content-Type": "application/json",
            // "Content-Type": "text/plain",  // try to skip preflight
            //"X-CSRF-Token": "hVtACDJjFRSyE4bgGJENHbXY0B9yNhF71Fw-cYHSDNY"
            //"X-CSRF-Token": "fj1QtF_Z_p6kE19EdCnN08zoSjVfcT4Up-ciW6I0IG8"
122 123 124
            "X-CSRF-Token": "EHu964c7gN7M399UfHiHHv06x1Tx5cl-P-9ZyMdmGbw",
//            "X-oauth-enabled": "true",
//            "X-Auth-Token": this.authToken
125
        });
126
        this.createAuthorizationHeader(headers);
127
        let options = new RequestOptions({ headers: headers });
128
        return new Promise((resolve, reject) => {
129
            this.http.get(`${AppSettings.API_ENDPOINT}/coursefields/list`, options)
130 131 132 133 134 135 136 137
            .map(response => <ICourseField[]>response.json())
            .subscribe(data => {
                resolve(data);
            }, // put the data returned from the server in our variable
            error => {
                console.log("Error HTTP GET Service"); // in case of failure show this message
                reject("Error HTTP GET Service");
            },
138
            () => console.log("Course Fields Received"));//run this code in all cases); */
139 140
        });
    };
141

142
    getSectorFields() {
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
        this.loginInfo$.forEach(loginInfoToken => {
            this.authToken = loginInfoToken.get(0).auth_token;
        });
        let headers = new Headers({
            //"Authorization": "Basic cmVzdHVzZXI6czNjckV0MFAwdWwwJA==", // encoded user:pass
            // "Authorization": "Basic bmthdHNhb3Vub3M6emVtcmFpbWU=",
            "Content-Type": "application/json",
            // "Content-Type": "text/plain",  // try to skip preflight
            //"X-CSRF-Token": "hVtACDJjFRSyE4bgGJENHbXY0B9yNhF71Fw-cYHSDNY"
            //"X-CSRF-Token": "fj1QtF_Z_p6kE19EdCnN08zoSjVfcT4Up-ciW6I0IG8"
            "X-CSRF-Token": "LU92FaWYfImfZxfldkF5eVnssdHoV7Aa9fg8K1bWYUc",
//            "X-oauth-enabled": "true",
//            "X-Auth-Token": this.authToken
        });
        this.createAuthorizationHeader(headers);
        let options = new RequestOptions({ headers: headers });
159
        return new Promise((resolve, reject) => {
160
            this.http.get(`${AppSettings.API_ENDPOINT}/sectorfields/list`, options)
161 162 163 164 165 166 167 168 169 170 171 172
            .map(response => <ISectorField[]>response.json())
            .subscribe(data => {
                resolve(data);
            }, // put the data returned from the server in our variable
            error => {
                console.log("Error HTTP GET Service"); // in case of failure show this message
                reject("Error HTTP GET Service");
            },
            () => console.log("Sector Fields Received"));//run this code in all cases); */
        });
    };

173
    getRegionsWithSchools(classActive,courseActive) {
174 175 176
        this.loginInfo$.forEach(loginInfoToken => {
            this.authToken = loginInfoToken.get(0).auth_token;
        });
177 178 179 180 181 182 183 184
        let headers = new Headers({
            //"Authorization": "Basic cmVzdHVzZXI6czNjckV0MFAwdWwwJA==", // encoded user:pass
            // "Authorization": "Basic bmthdHNhb3Vub3M6emVtcmFpbWU=",
            "Content-Type": "application/json",
            // "Content-Type": "text/plain",  // try to skip preflight
            //"X-CSRF-Token": "hVtACDJjFRSyE4bgGJENHbXY0B9yNhF71Fw-cYHSDNY"
            //"X-CSRF-Token": "fj1QtF_Z_p6kE19EdCnN08zoSjVfcT4Up-ciW6I0IG8"
            "X-CSRF-Token": "LU92FaWYfImfZxfldkF5eVnssdHoV7Aa9fg8K1bWYUc",
185 186
//            "X-oauth-enabled": "true",
//            "X-Auth-Token": this.authToken
187
        });
188
        this.createAuthorizationHeader(headers);
189
        let options = new RequestOptions({ headers: headers });
190
        return new Promise((resolve, reject) => {
191
            let getConnectionString = null;
192 193 194

            //if (courseActive === -1)
            if (classActive === 1)
195
              getConnectionString = `${AppSettings.API_ENDPOINT}/regions/list`;
196 197 198
              else if (classActive === 2)
                  getConnectionString = `${AppSettings.API_ENDPOINT}/sectorsperschool/list?sector_id=${courseActive}`;
            else if (classActive === 3)
199 200
              getConnectionString = `${AppSettings.API_ENDPOINT}/coursesperschool/list?course_id=${courseActive}`;

201
            this.http.get(getConnectionString, options)
202 203 204 205 206 207 208 209 210
                .map(response => response.json())
                .subscribe(data => {
                    resolve(this.transformRegionSchoolsSchema(data));
                }, // put the data returned from the server in our variable
                error => {
                    console.log("Error HTTP GET Service"); // in case of failure show this message
                    reject("Error HTTP GET Service");
                },
                () => console.log("region schools service"));//run this code in all cases); */
211 212 213
        });
    };

214
    getSectorsWithCourses() {
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
        this.loginInfo$.forEach(loginInfoToken => {
            this.authToken = loginInfoToken.get(0).auth_token;
        });
        let headers = new Headers({
            //"Authorization": "Basic cmVzdHVzZXI6czNjckV0MFAwdWwwJA==", // encoded user:pass
            // "Authorization": "Basic bmthdHNhb3Vub3M6emVtcmFpbWU=",
            "Content-Type": "application/json",
            // "Content-Type": "text/plain",  // try to skip preflight
            //"X-CSRF-Token": "hVtACDJjFRSyE4bgGJENHbXY0B9yNhF71Fw-cYHSDNY"
            //"X-CSRF-Token": "fj1QtF_Z_p6kE19EdCnN08zoSjVfcT4Up-ciW6I0IG8"
            "X-CSRF-Token": "LU92FaWYfImfZxfldkF5eVnssdHoV7Aa9fg8K1bWYUc",
//            "X-oauth-enabled": "true",
//            "X-Auth-Token": this.authToken
        });
        this.createAuthorizationHeader(headers);
        let options = new RequestOptions({ headers: headers });
231
        return new Promise((resolve, reject) => {
232
            this.http.get(`${AppSettings.API_ENDPOINT}/coursesectorfields/list`, options)
233 234 235 236 237 238 239 240 241 242 243 244
            .map(response => response.json())
            .subscribe(data => {
                resolve(this.transformSectorCoursesSchema(data));
            }, // put the data returned from the server in our variable
            error => {
                console.log("Error HTTP GET Service"); // in case of failure show this message
                reject("Error HTTP GET Service");
            },
            () => console.log("region schools service"));//run this code in all cases); */
        });
    };

245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
    transformRegionSchoolsSchema(regionSchools: any) {
        let rsa = Array<IRegion>();
        let trackRegionId: string;
        let trackIndex: number;

        trackRegionId = "";
        trackIndex = -1;

        let j=0;
        regionSchools.forEach(regionSchool => {
            if (trackRegionId !== regionSchool.region_id) {
                trackIndex++;
                rsa.push(<IRegion>{'region_id': regionSchool.region_id, 'region_name': regionSchool.region_name, 'epals': Array<IRegionSchool>()});
                trackRegionId = regionSchool.region_id;
            }
260
            rsa[trackIndex].epals.push(<IRegionSchool>{'epal_id': regionSchool.epal_id, 'epal_name': regionSchool.epal_name, 'globalIndex': j, 'selected': false, 'order_id': 0});
261 262 263 264 265
            j++;
        });
        return rsa;
    }

266 267 268 269 270 271 272 273 274 275 276 277
    transformSectorCoursesSchema(sectorCourses: any) {
        let rsa = Array<ISector>();
        let trackSectorId: string;
        let trackIndex: number;

        trackSectorId = "";
        trackIndex = -1;

        let j=0;
        sectorCourses.forEach(sectorCourse => {
            if (trackSectorId !== sectorCourse.sector_id) {
                trackIndex++;
278
                rsa.push(<ISector>{'sector_id': sectorCourse.sector_id, 'sector_name': sectorCourse.sector_name, 'sector_selected': false, 'courses': Array<ISectorCourse>()});
279 280 281 282 283 284 285 286
                trackSectorId = sectorCourse.sector_id;
            }
            rsa[trackIndex].courses.push(<ISectorCourse>{'course_id': sectorCourse.course_id, 'course_name': sectorCourse.course_name, 'globalIndex': j, 'selected': false});
            j++;
        });
        return rsa;
    }

287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
    getCriteria() {
        this.loginInfo$.forEach(loginInfoToken => {
            console.log(loginInfoToken.get(0));
            this.authToken = loginInfoToken.get(0).auth_token;
        });
        let headers = new Headers({
            "Content-Type": "application/json",
            "X-CSRF-Token": "LU92FaWYfImfZxfldkF5eVnssdHoV7Aa9fg8K1bWYUc",
        });
        this.createAuthorizationHeader(headers);
        let options = new RequestOptions({ headers: headers });
        return new Promise((resolve, reject) => {
            this.http.get(`${AppSettings.API_ENDPOINT}/criteria/list`, options)
            .map(response => <ISectorField[]>response.json())
            .subscribe(data => {
                resolve(data);
            }, // put the data returned from the server in our variable
            error => {
                console.log("Error HTTP GET Service"); // in case of failure show this message
                reject("Error HTTP GET Service");
            },
            () => console.log("Sector Fields Received"));//run this code in all cases); */
        });
    };
Open Source Developer's avatar
Open Source Developer committed
311

312
    getCurrentUser(oauthtoken, oauthrole) {
Open Source Developer's avatar
Open Source Developer committed
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327

        this.authToken = oauthtoken;
        let headers = new Headers({
            //"Authorization": "Basic cmVzdHVzZXI6czNjckV0MFAwdWwwJA==", // encoded user:pass
            // "Authorization": "Basic bmthdHNhb3Vub3M6emVtcmFpbWU=",
            "Content-Type": "application/json",
            // "Content-Type": "text/plain",  // try to skip preflight
            //"X-CSRF-Token": "hVtACDJjFRSyE4bgGJENHbXY0B9yNhF71Fw-cYHSDNY"
            //"X-CSRF-Token": "fj1QtF_Z_p6kE19EdCnN08zoSjVfcT4Up-ciW6I0IG8"
            "X-CSRF-Token": "LU92FaWYfImfZxfldkF5eVnssdHoV7Aa9fg8K1bWYUc",
//            "X-oauth-enabled": "true",
//            "X-Auth-Token": this.authToken
        });
        this.createAuthorizationHeader(headers);
        let options = new RequestOptions({ headers: headers });
328
           return new Promise((resolve, reject) => {
Open Source Developer's avatar
Open Source Developer committed
329
            this.http.get(`${AppSettings.API_ENDPOINT}/epal/curuser`, options)
Open Source Developer's avatar
Open Source Developer committed
330 331
            .map(response => response.json())
            .subscribe(data => {
332
                resolve(this.transformUserSchema(data, oauthtoken, oauthrole));
Open Source Developer's avatar
Open Source Developer committed
333
            }, // put the data returned from the server in our variable
Open Source Developer's avatar
Open Source Developer committed
334
            error => {
Open Source Developer's avatar
Open Source Developer committed
335
                console.log("Error HTTP GET Service"); // in case of failure show this message
Open Source Developer's avatar
Open Source Developer committed
336 337
                reject("Error HTTP GET Service");
            },
338
            () => console.log("UserName Received"));
Open Source Developer's avatar
Open Source Developer committed
339
        });
340
}
Open Source Developer's avatar
Open Source Developer committed
341

Open Source Developer's avatar
Open Source Developer committed
342 343

transformUserSchema(userlogin:any,oauthtoken:string, oauthrole:string){
344
        let rsa = Array<ILoginInfoToken>();
345

346 347
            rsa.push(<ILoginInfoToken>{'auth_token': oauthtoken, 'auth_role': oauthrole, 'cu_name':userlogin.name});
        return rsa;
348

349
        }
Open Source Developer's avatar
Open Source Developer committed
350

351
    signOut() {
352 353 354 355 356 357
        this.loginInfo$.forEach(loginInfoToken => {
            this.authToken = loginInfoToken.get(0).auth_token;
        });
        let headers = new Headers({
            //"Authorization": "Basic cmVzdHVzZXI6czNjckV0MFAwdWwwJA==", // encoded user:pass
            // "Authorization": "Basic bmthdHNhb3Vub3M6emVtcmFpbWU=",
Open Source Developer's avatar
Open Source Developer committed
358 359


Open Source Developer's avatar
Open Source Developer committed
360
           "Content-Type": "application/json",
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
            "Accept": "*/*",
            "Access-Control-Allow-Credentials": "true",
            // "Content-Type": "text/plain",  // try to skip preflight
            //"X-CSRF-Token": "hVtACDJjFRSyE4bgGJENHbXY0B9yNhF71Fw-cYHSDNY"
            //"X-CSRF-Token": "fj1QtF_Z_p6kE19EdCnN08zoSjVfcT4Up-ciW6I0IG8"
            "X-CSRF-Token": "EoAZ0APpIbbewK5MNzRrCFkvEeZZoGQsBslWFTrZ8bI",
//            "X-oauth-enabled": "true",
//            "X-Auth-Token": this.authToken
        });
        this.createAuthorizationHeader(headers);
        let options = new RequestOptions({ headers: headers, withCredentials: true });
        return new Promise((resolve, reject) => {
            this.http.post(`${AppSettings.API_ENDPOINT}/oauth/logout`, {}, options)
            .map(response => response)
            .subscribe(data => {
                resolve(data);
            }, // put the data returned from the server in our variable
            error => {
                console.log("Error Logout"); // in case of failure show this message
                reject("Error Logout");
            },
            () => console.log("Logging out"));//run this code in all cases); */
        });
    }
Open Source Developer's avatar
Open Source Developer committed
385 386


387
}