Advertisement
Guest User

Untitled

a guest
Apr 25th, 2017
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.57 KB | None | 0 0
  1. /**
  2. * Created by synerzip on 23/11/16.
  3. */
  4. import { push, replace } from 'react-router-redux';
  5. import { checkStatus, parseJSON } from 'utils/api';
  6. import { getUrlParams } from 'utils/app';
  7. import { getURLParameter } from 'utils/app';
  8. import { request, requestComplete } from 'actions/common';
  9. import Constants from 'constants';
  10. import _ from 'lodash';
  11. import UserConfig from 'config';
  12. import 'leaflet';
  13. import CryptoJS from 'crypto-js';
  14. // import * as ESRILeaflet from 'esri-leaflet';
  15. // import divisionData from 'divisionDetailData';
  16.  
  17. const getCircuits = () => fetch(`${UserConfig.GeoSpatialServiceAddress}LookUpService.svc/Circuits/Type=TREES_TRASMISSION`, {
  18. method: 'get',
  19. credentials: 'include'
  20. });
  21.  
  22. const getWorkOrderStatuses = () => fetch(`${UserConfig.GeoSpatialServiceAddress}LookUpService.svc/WorkOrderStatuses`, {
  23. method: 'get',
  24. credentials: 'include'
  25. });
  26.  
  27. const getWorkOrderTypes = () => fetch(`${UserConfig.GeoSpatialServiceAddress}LookUpService.svc/WorkOrderTypes`, {
  28. method: 'get',
  29. credentials: 'include'
  30. });
  31.  
  32. const getObjectTypes = () => fetch(`${UserConfig.GeoSpatialServiceAddress}LookUpService.svc/ObjectTypes/Type=ALL`, {
  33. method: 'get',
  34. credentials: 'include'
  35. });
  36.  
  37. const getCompanyList = userId => fetch(`${UserConfig.GeoSpatialServiceAddress}UserManagementService.svc/GetClientsByUserId`, {
  38. method: 'POST',
  39. headers: {
  40. Accept: 'application/json',
  41. 'Content-Type': 'application/json;charset=utf-8'
  42. },
  43. credentials: 'include',
  44. body: JSON.stringify({
  45. UserId: userId
  46. })
  47. });
  48.  
  49. const getTreeFilters = userId =>
  50. fetch(`${UserConfig.GeoSpatialServiceAddress}DistributionService.svc/GetFilter/UserID=${userId}&Type=TREES`, {
  51. method: 'get',
  52. credentials: 'include'
  53. });
  54.  
  55. const getFilters = userId => fetch(`${UserConfig.GeoSpatialServiceAddress}DistributionService.svc/GetFilter/UserID=${userId}&Type=TRANS_TREE_DASHBOARD`, {
  56. method: 'get',
  57. credentials: 'include'
  58. });
  59.  
  60. const getDivisions = () => fetch(`${UserConfig.GeoSpatialServiceAddress}DistributionService.svc/Division`, {
  61. method: 'get',
  62. credentials: 'include'
  63. });
  64.  
  65. const getAccountTypes = () => fetch(UserConfig.exportAccountTypeXMLUrl, {
  66. method: 'get',
  67. credentials: 'include'
  68. });
  69.  
  70. const getArcGisToken = () => {
  71. const params = {
  72. username: UserConfig.ArcGISUsername,
  73. password: UserConfig.ArcGISPassword,
  74. f: 'json',
  75. expiration: UserConfig.ArcGISTokenExpiration,
  76. client: 'requestip'
  77. };
  78. const tokenParams = Object.keys(params).map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`).join('&');
  79.  
  80. return fetch(UserConfig.getArcGISToken, {
  81. method: 'POST',
  82. headers: {
  83. Accept: 'application/json',
  84. 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
  85. },
  86. credentials: 'include',
  87. body: tokenParams
  88. });
  89. };
  90.  
  91. const dispatchFailure = dispatch => {
  92. // If any of the passed in promises rejects, the all Promise immediately rejects with the value
  93. // of the promise that rejected, discarding all the other promises whether or not they have
  94. // resolved.
  95. // For now, dispatching all requests as failed if any one is failed.
  96. dispatch({ type: Constants.DIVISIONS_FETCH_FAILED });
  97. dispatch({ type: Constants.CIRCUIT_FETCH_FAILED });
  98. dispatch({ type: Constants.FILTERS_FETCH_FAILED });
  99. dispatch({
  100. type: Constants.ON_COMPANY_LIST_RECEIVED,
  101. payload: []
  102. });
  103. dispatch({ type: Constants.FILTERS_FETCH_FAILED });
  104. dispatch({ type: Constants.OBJECT_TYPE_RECEIVED, payload: [] });
  105. dispatch({ type: Constants.WORK_ORDER_TYPE_RECEIVED, payload: [] });
  106. dispatch({ type: Constants.WORK_ORDER_STATUS_RECEIVED, payload: [] });
  107. dispatch({ type: Constants.ACCOUNT_TYPES_FAILED });
  108. // TODO cause of preliminary data fetch is failed, we are asserting that login is failed.
  109. // This is not true and needs different strategy to assert the failure
  110. dispatch({ type: Constants.LOGIN_FAILURE, payload: 'Failed to load inital data.' });
  111. dispatch(requestComplete());
  112. };
  113.  
  114. const requestData = (data, query) => {
  115. console.log(data);
  116. // TODO - Revisit
  117. // localStorage.setItem('userId', emailId);
  118. // localStorage.setItem('password', password);
  119. localStorage.setItem('Id', data.Id);
  120. localStorage.setItem('token', data.LoginToken);
  121. localStorage.setItem('clientId', data.clientId);
  122. localStorage.setItem('userDetails', JSON.stringify(data));
  123.  
  124. // if (objParams.serverUrl) {
  125. // dispatch({
  126. // type: Constants.SERVER_URL_RECEIVED,
  127. // payload: objParams.serverUrl
  128. // });
  129. // }
  130. return dispatch => {
  131. const tasks = [getDivisions(), getCircuits(),
  132. getFilters(data.Id), getCompanyList(data.Id),
  133. getTreeFilters(data.Id), getObjectTypes(), getWorkOrderTypes(),
  134. getWorkOrderStatuses(), getAccountTypes(), getArcGisToken()];
  135. Promise.all(tasks)
  136. .then(responses => Promise.all(responses.map(checkStatus)))
  137. .then(statuses => Promise.all(statuses.map(parseJSON)))
  138. .then(results => {
  139. // division
  140. const divisions = JSON.parse(results[0]);
  141. dispatch({
  142. type: Constants.DIVISIONS_RECEIVED,
  143. payload: divisions
  144. });
  145.  
  146. // circuit
  147. dispatch({
  148. type: Constants.CIRCUIT_RECEIVED,
  149. payload: _.uniqBy(JSON.parse(results[1]), 'LINE_ID')
  150. });
  151.  
  152. // filter
  153. const filterArray = JSON.parse(results[2]);
  154. let defaultFilterId = '';
  155. let selectedDetectionType = 'Routine';
  156. let circuitOrProject = 'Circuit';
  157. _.each(filterArray, filterData => {
  158. const filter = filterData;
  159. if (!defaultFilterId) {
  160. filter.FILTER_JSON = JSON.parse(filter.FILTER_JSON);
  161. if (filter.IS_DEFAULT) {
  162. defaultFilterId = filter.ID;
  163. if (filter.FILTER_TYPE &&
  164. filter.FILTER_TYPE === 'TRANS_ORCHARD_DASHBOARD') {
  165. selectedDetectionType = 'Orchard';
  166. }
  167. if (filter.FILTER_JSON
  168. && filter.FILTER_JSON.CircuitOrProject) {
  169. circuitOrProject = filter.FILTER_JSON.CircuitOrProject;
  170. }
  171. }
  172. }
  173. });
  174. dispatch({
  175. type: Constants.FILTERS_RECEIVED,
  176. payload: {
  177. filters: filterArray,
  178. defaultFilter: defaultFilterId,
  179. selectedDetectionType,
  180. selectedCircuitOrProject: circuitOrProject
  181. }
  182. });
  183.  
  184. // company list
  185. dispatch({
  186. type: Constants.ON_COMPANY_LIST_RECEIVED,
  187. payload: JSON
  188. .parse(results[3].GetClientsByUserIdResult.ClientDetails)
  189. });
  190.  
  191. // treefilter
  192. const treeFilterArray = JSON.parse(results[4]);
  193. _.each(treeFilterArray, treeFilterData => {
  194. const treeFilter = treeFilterData;
  195. treeFilter.FILTER_JSON = JSON.parse(treeFilter.FILTER_JSON);
  196. });
  197. dispatch({
  198. type: Constants.TREE_FILTERS_RECEIVED,
  199. payload: treeFilterArray
  200. });
  201.  
  202. // object types
  203. dispatch({
  204. type: Constants.OBJECT_TYPE_RECEIVED,
  205. payload: JSON.parse(results[5])
  206. });
  207.  
  208. // Work Order Types
  209. dispatch({
  210. type: Constants.WORK_ORDER_TYPE_RECEIVED,
  211. payload: JSON.parse(results[6])
  212. });
  213.  
  214. // Work Order Status
  215. dispatch({
  216. type: Constants.WORK_ORDER_STATUS_RECEIVED,
  217. payload: JSON.parse(results[7])
  218. });
  219.  
  220. // Account Types
  221. dispatch({
  222. type: Constants.ACCOUNT_TYPES_RECEIVED,
  223. payload: JSON.parse(results[8])
  224. });
  225.  
  226. // ArcGIS Token
  227. const ArcGISToken = results[9];
  228.  
  229. localStorage.setItem('ArcGISToken', ArcGISToken.token);
  230.  
  231. dispatch({
  232. type: Constants.ARCGIS_TOKEN_RECEIVED,
  233. payload: ArcGISToken
  234. });
  235.  
  236. setTimeout(() => {
  237. dispatch({
  238. type: Constants.LOGIN_SUCCESS,
  239. payload: {
  240. loginData: data
  241. }
  242. });
  243.  
  244. if (query && query.redirect && query.redirect !== '/') {
  245. dispatch(push(query.redirect));
  246. } else {
  247. dispatch(push('/'));
  248. }
  249. }, 100);
  250.  
  251. // login success dispatch
  252. }, () => dispatchFailure(dispatch))
  253. .catch(() => dispatchFailure(dispatch));
  254. }
  255. }
  256.  
  257. export function setTempUserId() {
  258. return {
  259. type: Constants.SET_TEMP_USER_ID
  260. };
  261. }
  262.  
  263. export function login(query) {
  264. const objParams = getUrlParams(window.location.href);
  265. const config = {
  266. method: 'get',
  267. headers: {
  268. accept: 'application/json',
  269. 'content-type': 'application/json'
  270. }
  271. };
  272. const clientId = localStorage.getItem('clientId');
  273. const userDetails = JSON.parse(localStorage.getItem('userDetails'));
  274.  
  275. // console.log(userDetails);
  276. // if(clientId) {
  277. // return;
  278. // }
  279. // console.log(clientId);
  280. // if(userDetails) {
  281. // console.log(JSON.parse(userDetails));
  282. // }
  283. if(objParams) {
  284. return dispatch => {
  285. dispatch(request());
  286. if(! clientId) {
  287. fetch(`${UserConfig.UserServiceByTokenUrl} ${objParams.Token}`, config)
  288. .then(checkStatus)
  289. .then(parseJSON)
  290. .then(result => {
  291. let data = {};
  292. data = JSON.parse(result);
  293. if (!data.Id) {
  294. dispatch({
  295. type: Constants.LOGIN_FAILURE,
  296. payload: data.LoginURL
  297. });
  298. dispatch(requestComplete());
  299. } else {
  300. requestData(data, query);
  301. }
  302. })
  303. .catch(() => {
  304. dispatch(requestComplete());
  305. });
  306. } else {
  307. requestData(userDetails, query);
  308. }
  309. }
  310. } else {
  311. logout('https://test-platform.quantumspatial.com/index.html');
  312. }
  313. }
  314.  
  315. export function logout(serverUrl) {
  316. replace(serverUrl)
  317. // window.location = serverUrl;
  318. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement