Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Created by synerzip on 23/11/16.
- */
- import { push, replace } from 'react-router-redux';
- import { checkStatus, parseJSON } from 'utils/api';
- import { getUrlParams } from 'utils/app';
- import { getURLParameter } from 'utils/app';
- import { request, requestComplete } from 'actions/common';
- import Constants from 'constants';
- import _ from 'lodash';
- import UserConfig from 'config';
- import 'leaflet';
- import CryptoJS from 'crypto-js';
- // import * as ESRILeaflet from 'esri-leaflet';
- // import divisionData from 'divisionDetailData';
- const getCircuits = () => fetch(`${UserConfig.GeoSpatialServiceAddress}LookUpService.svc/Circuits/Type=TREES_TRASMISSION`, {
- method: 'get',
- credentials: 'include'
- });
- const getWorkOrderStatuses = () => fetch(`${UserConfig.GeoSpatialServiceAddress}LookUpService.svc/WorkOrderStatuses`, {
- method: 'get',
- credentials: 'include'
- });
- const getWorkOrderTypes = () => fetch(`${UserConfig.GeoSpatialServiceAddress}LookUpService.svc/WorkOrderTypes`, {
- method: 'get',
- credentials: 'include'
- });
- const getObjectTypes = () => fetch(`${UserConfig.GeoSpatialServiceAddress}LookUpService.svc/ObjectTypes/Type=ALL`, {
- method: 'get',
- credentials: 'include'
- });
- const getCompanyList = userId => fetch(`${UserConfig.GeoSpatialServiceAddress}UserManagementService.svc/GetClientsByUserId`, {
- method: 'POST',
- headers: {
- Accept: 'application/json',
- 'Content-Type': 'application/json;charset=utf-8'
- },
- credentials: 'include',
- body: JSON.stringify({
- UserId: userId
- })
- });
- const getTreeFilters = userId =>
- fetch(`${UserConfig.GeoSpatialServiceAddress}DistributionService.svc/GetFilter/UserID=${userId}&Type=TREES`, {
- method: 'get',
- credentials: 'include'
- });
- const getFilters = userId => fetch(`${UserConfig.GeoSpatialServiceAddress}DistributionService.svc/GetFilter/UserID=${userId}&Type=TRANS_TREE_DASHBOARD`, {
- method: 'get',
- credentials: 'include'
- });
- const getDivisions = () => fetch(`${UserConfig.GeoSpatialServiceAddress}DistributionService.svc/Division`, {
- method: 'get',
- credentials: 'include'
- });
- const getAccountTypes = () => fetch(UserConfig.exportAccountTypeXMLUrl, {
- method: 'get',
- credentials: 'include'
- });
- const getArcGisToken = () => {
- const params = {
- username: UserConfig.ArcGISUsername,
- password: UserConfig.ArcGISPassword,
- f: 'json',
- expiration: UserConfig.ArcGISTokenExpiration,
- client: 'requestip'
- };
- const tokenParams = Object.keys(params).map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`).join('&');
- return fetch(UserConfig.getArcGISToken, {
- method: 'POST',
- headers: {
- Accept: 'application/json',
- 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
- },
- credentials: 'include',
- body: tokenParams
- });
- };
- const dispatchFailure = dispatch => {
- // If any of the passed in promises rejects, the all Promise immediately rejects with the value
- // of the promise that rejected, discarding all the other promises whether or not they have
- // resolved.
- // For now, dispatching all requests as failed if any one is failed.
- dispatch({ type: Constants.DIVISIONS_FETCH_FAILED });
- dispatch({ type: Constants.CIRCUIT_FETCH_FAILED });
- dispatch({ type: Constants.FILTERS_FETCH_FAILED });
- dispatch({
- type: Constants.ON_COMPANY_LIST_RECEIVED,
- payload: []
- });
- dispatch({ type: Constants.FILTERS_FETCH_FAILED });
- dispatch({ type: Constants.OBJECT_TYPE_RECEIVED, payload: [] });
- dispatch({ type: Constants.WORK_ORDER_TYPE_RECEIVED, payload: [] });
- dispatch({ type: Constants.WORK_ORDER_STATUS_RECEIVED, payload: [] });
- dispatch({ type: Constants.ACCOUNT_TYPES_FAILED });
- // TODO cause of preliminary data fetch is failed, we are asserting that login is failed.
- // This is not true and needs different strategy to assert the failure
- dispatch({ type: Constants.LOGIN_FAILURE, payload: 'Failed to load inital data.' });
- dispatch(requestComplete());
- };
- const requestData = (data, query) => {
- console.log(data);
- // TODO - Revisit
- // localStorage.setItem('userId', emailId);
- // localStorage.setItem('password', password);
- localStorage.setItem('Id', data.Id);
- localStorage.setItem('token', data.LoginToken);
- localStorage.setItem('clientId', data.clientId);
- localStorage.setItem('userDetails', JSON.stringify(data));
- // if (objParams.serverUrl) {
- // dispatch({
- // type: Constants.SERVER_URL_RECEIVED,
- // payload: objParams.serverUrl
- // });
- // }
- return dispatch => {
- const tasks = [getDivisions(), getCircuits(),
- getFilters(data.Id), getCompanyList(data.Id),
- getTreeFilters(data.Id), getObjectTypes(), getWorkOrderTypes(),
- getWorkOrderStatuses(), getAccountTypes(), getArcGisToken()];
- Promise.all(tasks)
- .then(responses => Promise.all(responses.map(checkStatus)))
- .then(statuses => Promise.all(statuses.map(parseJSON)))
- .then(results => {
- // division
- const divisions = JSON.parse(results[0]);
- dispatch({
- type: Constants.DIVISIONS_RECEIVED,
- payload: divisions
- });
- // circuit
- dispatch({
- type: Constants.CIRCUIT_RECEIVED,
- payload: _.uniqBy(JSON.parse(results[1]), 'LINE_ID')
- });
- // filter
- const filterArray = JSON.parse(results[2]);
- let defaultFilterId = '';
- let selectedDetectionType = 'Routine';
- let circuitOrProject = 'Circuit';
- _.each(filterArray, filterData => {
- const filter = filterData;
- if (!defaultFilterId) {
- filter.FILTER_JSON = JSON.parse(filter.FILTER_JSON);
- if (filter.IS_DEFAULT) {
- defaultFilterId = filter.ID;
- if (filter.FILTER_TYPE &&
- filter.FILTER_TYPE === 'TRANS_ORCHARD_DASHBOARD') {
- selectedDetectionType = 'Orchard';
- }
- if (filter.FILTER_JSON
- && filter.FILTER_JSON.CircuitOrProject) {
- circuitOrProject = filter.FILTER_JSON.CircuitOrProject;
- }
- }
- }
- });
- dispatch({
- type: Constants.FILTERS_RECEIVED,
- payload: {
- filters: filterArray,
- defaultFilter: defaultFilterId,
- selectedDetectionType,
- selectedCircuitOrProject: circuitOrProject
- }
- });
- // company list
- dispatch({
- type: Constants.ON_COMPANY_LIST_RECEIVED,
- payload: JSON
- .parse(results[3].GetClientsByUserIdResult.ClientDetails)
- });
- // treefilter
- const treeFilterArray = JSON.parse(results[4]);
- _.each(treeFilterArray, treeFilterData => {
- const treeFilter = treeFilterData;
- treeFilter.FILTER_JSON = JSON.parse(treeFilter.FILTER_JSON);
- });
- dispatch({
- type: Constants.TREE_FILTERS_RECEIVED,
- payload: treeFilterArray
- });
- // object types
- dispatch({
- type: Constants.OBJECT_TYPE_RECEIVED,
- payload: JSON.parse(results[5])
- });
- // Work Order Types
- dispatch({
- type: Constants.WORK_ORDER_TYPE_RECEIVED,
- payload: JSON.parse(results[6])
- });
- // Work Order Status
- dispatch({
- type: Constants.WORK_ORDER_STATUS_RECEIVED,
- payload: JSON.parse(results[7])
- });
- // Account Types
- dispatch({
- type: Constants.ACCOUNT_TYPES_RECEIVED,
- payload: JSON.parse(results[8])
- });
- // ArcGIS Token
- const ArcGISToken = results[9];
- localStorage.setItem('ArcGISToken', ArcGISToken.token);
- dispatch({
- type: Constants.ARCGIS_TOKEN_RECEIVED,
- payload: ArcGISToken
- });
- setTimeout(() => {
- dispatch({
- type: Constants.LOGIN_SUCCESS,
- payload: {
- loginData: data
- }
- });
- if (query && query.redirect && query.redirect !== '/') {
- dispatch(push(query.redirect));
- } else {
- dispatch(push('/'));
- }
- }, 100);
- // login success dispatch
- }, () => dispatchFailure(dispatch))
- .catch(() => dispatchFailure(dispatch));
- }
- }
- export function setTempUserId() {
- return {
- type: Constants.SET_TEMP_USER_ID
- };
- }
- export function login(query) {
- const objParams = getUrlParams(window.location.href);
- const config = {
- method: 'get',
- headers: {
- accept: 'application/json',
- 'content-type': 'application/json'
- }
- };
- const clientId = localStorage.getItem('clientId');
- const userDetails = JSON.parse(localStorage.getItem('userDetails'));
- // console.log(userDetails);
- // if(clientId) {
- // return;
- // }
- // console.log(clientId);
- // if(userDetails) {
- // console.log(JSON.parse(userDetails));
- // }
- if(objParams) {
- return dispatch => {
- dispatch(request());
- if(! clientId) {
- fetch(`${UserConfig.UserServiceByTokenUrl} ${objParams.Token}`, config)
- .then(checkStatus)
- .then(parseJSON)
- .then(result => {
- let data = {};
- data = JSON.parse(result);
- if (!data.Id) {
- dispatch({
- type: Constants.LOGIN_FAILURE,
- payload: data.LoginURL
- });
- dispatch(requestComplete());
- } else {
- requestData(data, query);
- }
- })
- .catch(() => {
- dispatch(requestComplete());
- });
- } else {
- requestData(userDetails, query);
- }
- }
- } else {
- logout('https://test-platform.quantumspatial.com/index.html');
- }
- }
- export function logout(serverUrl) {
- replace(serverUrl)
- // window.location = serverUrl;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement