Advertisement
Guest User

Untitled

a guest
Apr 14th, 2017
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 81.26 KB | None | 0 0
  1. (function () {
  2. 'use strict';
  3.  
  4. angular.module('loginApp', [
  5. // application dependencies
  6. 'ngRoute',
  7. 'ngAnimate',
  8. 'ui.bootstrap',
  9. 'ui.select',
  10. 'angularModalService',
  11. 'vcRecaptcha',
  12. 'app.env'
  13. ]).run(initialize);
  14.  
  15. initialize.$inject = [
  16. '$rootScope',
  17. '$location',
  18. '$window'
  19. ];
  20.  
  21. function initialize($rootScope,
  22. $location,
  23. $window) {
  24.  
  25. }
  26. })();
  27.  
  28. (function () {
  29.  
  30. 'use strict';
  31.  
  32. angular
  33. .module('loginApp')
  34. .config(config);
  35.  
  36. function config($routeProvider, $httpProvider) {
  37.  
  38. $httpProvider.defaults.useXDomain = true;
  39. delete $httpProvider.defaults.headers.common['X-Requested-With'];
  40.  
  41. $routeProvider
  42. .when('/login', {
  43. templateUrl: 'app/login/login.html',
  44. controller: 'LoginController',
  45. controllerAs: 'vm'
  46. })
  47. .otherwise({
  48. redirectTo: '/login'
  49. });
  50.  
  51. $httpProvider.interceptors.push('authInterceptor');
  52. }
  53.  
  54. }());
  55. (function () {
  56. 'use strict';
  57.  
  58. //Activate password
  59. angular.module('loginApp').controller('ActivateCtl',
  60. function ($scope, $location, $window, Activation, Messages, User, authService) {
  61. var token = $location.search().token,
  62. q = $location.search().q,
  63. nu = $location.search().nu,
  64. sn = $location.search().sn;
  65.  
  66. if (!token) {
  67. Messages.setMessage({
  68. header: "Invalid Token",
  69. text: "Token is empty. Please check your link or contact support"
  70. });
  71. Messages.sendMessage();
  72. return;
  73. }
  74.  
  75. if (!sn) {
  76. Activation.postActivateToken({"token": token}, function (data) {
  77. if (data.status == 204) {
  78. if (nu == 1) pixelCompleteRegistration();
  79. $location.path('/password').search({token: token, q: q});
  80. //if need to show questions form forward parameter q=1
  81. } else if (data.status == 404) {
  82. Messages.setMessage({
  83. header: "Your session has expired",
  84. text: "Please login again. If you can't login, you can restore your password in main page. If you have other problems please contact support."
  85. });
  86. Messages.sendMessage();
  87. } else {
  88. Messages.setMessage({
  89. header: "Internal sever error",
  90. text: "Please try again later. If you have the problem again please contact support."
  91. });
  92. Messages.sendMessage();
  93. }
  94. });
  95. } else if (sn) {
  96. Activation.postActivateToken({"token": token, "token_type": sn}, function (data) {
  97. if (data.status == 204) {
  98. if (nu == 1) pixelCompleteRegistration();
  99. $window.localStorage.access_token = token;
  100. authService.setToken(token);
  101. User.getUserInfo(token).then(function (mapped) {
  102. Messages.setMessage({
  103. header: "Welcome " + mapped.name,
  104. text: "You have been successfully logged."
  105. });
  106. Messages.sendMessage();
  107. });
  108. } else {
  109. Messages.sendError(data);
  110. }
  111. });
  112. }
  113.  
  114. function pixelCompleteRegistration() {
  115. fbq('track', 'CompleteRegistration');
  116. }
  117. });
  118.  
  119. // Enter new password
  120. angular.module('loginApp').controller('PasswordCtl',
  121. function ($location, ModalService, authService) {
  122. var token = $location.search().token;
  123.  
  124. activate();
  125.  
  126. function activate() {
  127. if (authService.isLoggedIn()) {
  128. $location.path('/profile');
  129. $location.url($location.path()); // clear query string
  130. } else {
  131. showPasswordPopup();
  132. }
  133. }
  134.  
  135. function showPasswordPopup() {
  136. ModalService.showModal({
  137. templateUrl: "views/modal-set-password.html",
  138. controller: "SetPasswordController",
  139. controllerAs: "vm",
  140. inputs: {
  141. params: {
  142. token: token
  143. }
  144. }
  145. }).then(function (modal) {
  146. modal.element.modal({
  147. backdrop: 'static', // if you want prevent close modal
  148. keyboard: false
  149. });
  150. // after show modal actions here...
  151. });
  152. }
  153. });
  154.  
  155. }());
  156.  
  157. 'use strict';
  158.  
  159. //Login
  160. angular.module('loginApp').factory("Login", function ($http,
  161. userService,
  162. userMapper,
  163. errorsMapper) {
  164. var serviceBase = '/rest/user/login',
  165. obj = {};
  166. //Send login and password to backend
  167. obj.postLoginForm = function (login, callbackStatus) {
  168. $http.post(serviceBase, {email: login.email, password: login.password})
  169. .then(function successCallback(response) {
  170. var user = response.user = userMapper.mapFromServer(response.data);
  171. userService.setUser(user);
  172. callbackStatus(response);
  173. }, function errorCallback(response) {
  174. response.errors = errorsMapper.mapArrayFromServer(response);
  175. callbackStatus(response);
  176. });
  177. };
  178.  
  179. return obj;
  180. });
  181.  
  182. // User methods
  183. angular.module('loginApp').factory("User", function ($http, userMapper, userService, Endpoints, apiService) {
  184. var currentUser;
  185.  
  186. return {
  187. /**
  188. * Returns User Information (name, surname, image and etc)
  189. * @param {string} token
  190. * @returns {promise}
  191. */
  192. getUserInfo: function (token) {
  193. return $http({
  194. url: apiService.wrap(Endpoints.profileInfo),
  195. method: "GET",
  196. params: {"token": token}
  197. }).then(function (response) {
  198. currentUser = userMapper.mapFromServer(response.data);
  199. userService.setUser(currentUser);
  200. return currentUser;
  201. });
  202. },
  203.  
  204. refreshToken: function () {
  205. return $http.post(apiService.wrap(Endpoints.refreshToken), {})
  206. .then(
  207. function (response) {
  208. return response;
  209. },
  210. function (response) {
  211. return response;
  212. }
  213. );
  214. },
  215.  
  216. currentUser: function () {
  217. return currentUser;
  218. }
  219. };
  220. });
  221.  
  222. //SignUp
  223. angular.module('loginApp').factory("SignUp", function ($http, Endpoints, apiService) {
  224.  
  225. return {
  226. postSignUpForm: function (signup, recaptchaResponse, callbackStatus) {
  227. $http.post(apiService.wrap(Endpoints.signUp), {
  228. 'first_name': signup.first_name,
  229. 'last_name': signup.last_name,
  230. 'email': signup.email,
  231. 'password': signup.password,
  232. 'g-recaptcha-response': recaptchaResponse
  233. }).then(function successCallback(response) {
  234. callbackStatus(response);
  235. }, function errorCallback(response) {
  236. callbackStatus(response);
  237. });
  238. },
  239.  
  240. postForgot: function (email, callbackStatus) {
  241. $http.post(apiService.wrap(Endpoints.resetPassword), {email: email})
  242. .then(function successCallback(response) {
  243. callbackStatus(response);
  244. }, function errorCallback(response) {
  245. callbackStatus(response);
  246. });
  247. },
  248.  
  249. checkEmailExists: function (email) {
  250. return $http.post(apiService.wrap(Endpoints.userExists), {email: email}).then(function successCallback(response) {
  251. return response;
  252. }, function errorCallback(response) {
  253. return response;
  254. });
  255. }
  256. };
  257. });
  258.  
  259. //Secret questions
  260. angular.module('loginApp').factory("Questions", function ($http, apiService) {
  261. return {
  262.  
  263. getQuestions: function (callbackStatus) {
  264. $http.post(apiService.wrap('/rest/user/questions-list'))
  265. .then(function successCallback(response) {
  266. callbackStatus(response);
  267. }, function errorCallback(response) {
  268. callbackStatus(response);
  269. });
  270. },
  271.  
  272. postQuestionsForm: function (answers, callbackStatus) {
  273. $http.post(apiService.wrap('/rest/user/save-answers'), {
  274. 'answers': answers
  275. }).then(function successCallback(response) {
  276. callbackStatus(response);
  277. }, function errorCallback(response) {
  278. callbackStatus(response);
  279. });
  280. }
  281. };
  282. });
  283.  
  284. //Authorization
  285. angular.module('loginApp').factory('authInterceptor', function ($q, $window, $location, authService, HttpStatuses) {
  286. return {
  287. request: function (config) {
  288. if (authService.isLoggedIn()) {
  289. //HttpBearerAuth
  290. config.headers.Authorization = 'Bearer ' + authService.getToken();
  291. }
  292. return config;
  293. },
  294. responseError: function (rejection) {
  295. if (rejection.status === HttpStatuses.AUTH_FAILED) {
  296. authService.logout();
  297. //$location.path('/index').replace();
  298. }
  299. return $q.reject(rejection);
  300. }
  301. };
  302. });
  303.  
  304. //Activation password
  305. angular.module('loginApp').factory("Activation", function ($http, apiService) {
  306. var obj = {};
  307. //Send token for activation
  308. obj.postActivateToken = function (params, callbackStatus) {
  309. $http.post(apiService.wrap('/rest/user/authorization-link'), params)
  310. .then(function successCallback(response) {
  311. callbackStatus(response);
  312. }, function errorCallback(response) {
  313. callbackStatus(response);
  314. });
  315. };
  316.  
  317. return obj;
  318. });
  319.  
  320. //Set new password
  321. angular.module('loginApp').factory("Password", function ($http, apiService) {
  322. return {
  323. //Send new password
  324. postPasswords: function (passwd, callbackStatus) {
  325. $http.post(apiService.wrap('/rest/user/update-password'), {
  326. token: passwd.token,
  327. password: passwd.password,
  328. password_again: passwd.password_again
  329. })
  330. .then(function successCallback(response) {
  331. callbackStatus(response);
  332. }, function errorCallback(response) {
  333. callbackStatus(response);
  334. });
  335. }
  336. }
  337. });
  338.  
  339. /**
  340. * Social Network service for link fetching
  341. */
  342. angular.module('loginApp').factory("SocialNetwork", function ($http, socialNetworkMapper, apiService) {
  343. return {
  344. /**
  345. * Get social network oAuth2 link
  346. * @param {string} type
  347. * @returns {promise}
  348. */
  349. getNetworkPath: function (type) {
  350. return $http.post(
  351. apiService.wrap('/rest/oauth/get-link'),
  352. $.param({type:type}),
  353. {
  354. headers: {
  355. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  356. }
  357. }
  358. ).then(function (response) {
  359. return socialNetworkMapper.mapFromServer(response.data);
  360. });
  361. }
  362. };
  363. });
  364.  
  365. angular.module('loginApp').factory("Geo", function ($http, Endpoints, apiService) {
  366. return {
  367. statesList: function () {
  368. return $http.get(apiService.wrap(Endpoints.statesList)).then(function (response) {
  369. return response.data;
  370. });
  371. }
  372. };
  373. });
  374.  
  375. // Profile methods
  376. angular.module('loginApp').factory("Profile", function (apiService, $http, Endpoints, $rootScope, userMapper, resourceMapper, educationMapper, employmentsMapper, userActivityMapper) {
  377. var userInfoPath = apiService.wrap(Endpoints.profileInfo),
  378. educationInfoPath = apiService.wrap(Endpoints.profileEducation),
  379. employmentsInfoPath = apiService.wrap(Endpoints.profileEmployments),
  380. passwordInfoPath = apiService.wrap("/rest/profile/password"),
  381. self = this;
  382.  
  383. return {
  384. /**
  385. * Returns Profile Information (name, surname, image and etc)
  386. * @returns {promise}
  387. */
  388. getProfileInfo: function () {
  389. return $http.get(userInfoPath).then(function (response) {
  390. return userMapper.mapFromServer(response.data);
  391. });
  392. },
  393.  
  394. /**
  395. * Update Profile Information (name, surname, image and etc)
  396. * @param {object} profile
  397. * @returns {promise}
  398. */
  399. updateProfileInfo: function (profile) {
  400. profile = userMapper.mapToServer(profile);
  401.  
  402. return $http.post(userInfoPath, profile).then(function (response) {
  403. return response;
  404. },
  405. function (response) {
  406. return response;
  407. }
  408. );
  409. },
  410. /**
  411. * Returns Information about Education
  412. * @params
  413. * @returns {promise}
  414. */
  415. getEducationInfo: function () {
  416. return $http.get(apiService.wrap(Endpoints.profileEducation))
  417. .then(
  418. function (response) {
  419. response.educationList = educationMapper.mapArrayFromServer(response.data);
  420. return response;
  421. },
  422. function (response) {
  423. return response;
  424. }
  425. );
  426. },
  427.  
  428. /**
  429. * Returns Information about User Recent Activity
  430. * @params
  431. * @returns {promise}
  432. */
  433. getUserActivity: function () {
  434. return $http.get(apiService.wrap(Endpoints.userActivity))
  435. .then(
  436. function (response) {
  437. response.userActivity = userActivityMapper.mapArrayFromServer(response.data);
  438. return response;
  439. },
  440. function (response) {
  441. return response;
  442. }
  443. );
  444. },
  445. /**
  446. * Get Employments collection
  447. * @returns {promise}
  448. */
  449. getEmploymentsInfo: function () {
  450. return $http.get(apiService.wrap(Endpoints.profileEmployments))
  451. .then(
  452. function (response) {
  453. response.employmentsList = employmentsMapper.mapArrayFromServer(response.data);
  454. return response;
  455. },
  456. function (response) {
  457. return response;
  458. }
  459. );
  460. },
  461.  
  462. insertEducationInfo: function (education) {
  463. return $http.put(educationInfoPath, educationMapper.mapToServer(education)).then(
  464. function (response) {
  465. // success callback
  466. return response;
  467. },
  468. function (response) {
  469. // failure callback
  470. return response;
  471. }
  472. );
  473. },
  474. deleteEducationInfo: function (education_id) {
  475. return $http.delete(educationInfoPath, {params: {education_id: education_id}})
  476. .then(
  477. function (response) {
  478. // success callback
  479. return response;
  480. },
  481. function (response) {
  482. // failure callback
  483. return response;
  484. }
  485. );
  486. },
  487. insertEmploymentsInfo: function (employments) {
  488. return $http.put(employmentsInfoPath, employmentsMapper.mapToServer(employments))
  489. .then(
  490. function (response) {
  491. // success callback
  492. return response;
  493. },
  494. function (response) {
  495. // failure callback
  496. return response;
  497. }
  498. );
  499. },
  500. updateEmploymentsInfo: function (employments) {
  501. return $http.post(employmentsInfoPath, employmentsMapper.mapToServer(employments))
  502. .then(
  503. function (response) {
  504. // success callback
  505. return response;
  506. },
  507. function (response) {
  508. // failure callback
  509. return response;
  510. }
  511. );
  512. },
  513. updateEducationInfo: function (education) {
  514. return $http.post(educationInfoPath, educationMapper.mapToServer(education))
  515. .then(
  516. function (response) {
  517. // success callback
  518. return response;
  519. },
  520. function (response) {
  521. // failure callback
  522. return response;
  523. }
  524. );
  525. },
  526. deleteEmploymentsInfo: function (employment_id) {
  527. return $http.delete(employmentsInfoPath, {params: {employment_id: employment_id}})
  528. .then(
  529. function (response) {
  530. // success callback
  531. return response;
  532. },
  533. function (response) {
  534. // failure callback
  535. return response;
  536. }
  537. );
  538. },
  539. changePassword: function (password) {//deprecated method
  540. return $http.post(passwordInfoPath, {
  541. current_password: password.current_password,
  542. new_password: password.new_password,
  543. confirm_password: password.confirm_password
  544. })
  545. .then(
  546. function (response) {
  547. // success callback
  548. return response;
  549. },
  550. function (response) {
  551. // failure callback
  552. return response;
  553. }
  554. );
  555. },
  556.  
  557. /**
  558. * Save photo
  559. * @param {object} fileReader
  560. * @returns {promise}
  561. */
  562. sendPhotoFile: function (fileReader) {
  563. var Profile = this;
  564.  
  565. fileReader.append('type', 'photo');
  566. return $http
  567. .post(
  568. apiService.wrap(Endpoints.profileFile),
  569. fileReader, {
  570. transformRequest: angular.identity,
  571. headers: {
  572. 'Content-Type': undefined
  573. }
  574. }
  575. )
  576. .success(function (response) {
  577. var resource = resourceMapper.mapFromServer(response);
  578. Profile.sendPhotoLink(resource.link);
  579. return resource;
  580. })
  581. .error(function (response) {
  582. return response;
  583. }).then(function (response) {
  584. // only if transform request
  585. return resourceMapper.mapFromServer(response.data);
  586. });
  587. },
  588.  
  589. sendVideoFile: function (fileReader) {
  590. var Profile = this;
  591.  
  592. fileReader.append('type', 'video');
  593. return $http
  594. .post(
  595. apiService.wrap(Endpoints.profileFile),
  596. fileReader, {
  597. transformRequest: angular.identity,
  598. headers: {
  599. 'Content-Type': undefined
  600. }
  601. }
  602. )
  603. .success(function (response) {
  604. var resource = resourceMapper.mapFromServer(response);
  605. Profile.sendVideoLink(resource.link);
  606. return response;
  607. })
  608. .error(function (response) {
  609. return response;
  610. })
  611. .then(function (response) {
  612. // only if transform request
  613. return response;
  614. });
  615. },
  616.  
  617. sendVideoLink: function (link) {
  618. return $http.post(apiService.wrap(Endpoints.profileResourceLink), {
  619. video: link
  620. }).then(
  621. function (response) {
  622. return response;
  623. },
  624. function (response) {
  625. return response;
  626. }
  627. );
  628. },
  629.  
  630. sendPhotoLink: function (link) {
  631. return $http.post(apiService.wrap(Endpoints.profileResourceLink), {
  632. photo: link
  633. }).then(
  634. function (response) {
  635. // success callback
  636. return response;
  637. },
  638. function (response) {
  639. // failure callback
  640. return response;
  641. }
  642. );
  643. }
  644.  
  645. };
  646. });
  647.  
  648. (function () {
  649. 'use strict';
  650.  
  651. angular
  652. .module('loginApp')
  653. .controller('LoginController', LoginController);
  654.  
  655. LoginController.$inject = [
  656. '$scope',
  657. '$window',
  658. '$location',
  659. 'Messages',
  660. 'HttpStatuses',
  661. 'SocialNetwork',
  662. 'SignUp',
  663. 'appConstants',
  664. 'spinnerService',
  665. 'Login'
  666. ];
  667.  
  668. function LoginController($scope,
  669. $window,
  670. $location,
  671. Messages,
  672. HttpStatuses,
  673. SocialNetwork,
  674. SignUp,
  675. appConstants,
  676. spinnerService,
  677. Login) {
  678. var vm = this;
  679. var event = {};
  680. $scope.forgot = {};
  681. $scope.signUp = {};
  682. $scope.login = {};
  683. $scope.emailSentView = false;
  684. $scope.forgotPasswordView = false;
  685.  
  686. // methods
  687. vm.closeModal = closeModal;
  688. vm.redirectToExternalService = redirectToExternalService;
  689. vm.postForgot = postForgot;
  690. vm.checkForgottenEmail = checkForgottenEmail;
  691. vm.checkEmail = checkEmail;
  692. vm.showForgotPassword = showForgotPassword;
  693. vm.postLogin = postLogin;
  694.  
  695. activate();
  696.  
  697. function activate() {
  698. // constructor
  699. }
  700.  
  701. function closeModal(result, $event) {
  702. $event && $event.preventDefault();
  703. $element.modal('hide');
  704. close(result, 500);
  705. }
  706.  
  707. //Redirect to social network oAuth
  708. function redirectToExternalService(type) {
  709. SocialNetwork.getNetworkPath(type).then(function (data) {
  710. $window.location = data.redirectLink;
  711. });
  712. }
  713.  
  714. //post Forgot Password
  715. function postForgot() {
  716. SignUp.postForgot($scope.forgot.email, function (data) {
  717. if (data.status === HttpStatuses.OK_WITHOUT_DATA) {
  718. $scope.emailSentView = true;
  719. $scope.forgotPasswordView = false;
  720. } else {
  721. Messages.setHeader("Error");
  722. Messages.setText("We could not find your email address. Please try again.");
  723. Messages.sendMessage();
  724. }
  725. });
  726. }
  727.  
  728. //Check email exists
  729. function checkForgottenEmail() {
  730. var email;
  731. if (!$scope.forgotForm.email.$invalid) {
  732. email = $scope.forgot.email;
  733. $scope.emailExistsStatus = SignUp.checkEmailExists(email).then(function (response) {
  734. if (response.status === HttpStatuses.OK_WITHOUT_DATA) {
  735. $scope.forgot.emailStatus = "";
  736. $scope.forgot.emailWrong = "";
  737. vm.postForgot();
  738. } else if (response.status >= HttpStatuses.BAD_REQUEST ||
  739. response.status < HttpStatuses.APPLICATION_ERROR) {
  740. Messages.sendError(response);
  741. } else {
  742. Messages.setHeader("Error");
  743. Messages.setText("Internal Service Error");
  744. Messages.sendMessage();
  745. }
  746. });
  747. }
  748. }
  749.  
  750. function showForgotPassword($event) {
  751. $scope.signUp.emailStatus = '';
  752. $event.preventDefault();
  753. $scope.forgotPasswordView = true;
  754. $scope.forgot.email = '';
  755. console.log(1);
  756. }
  757.  
  758. //Check email exists
  759. function checkEmail() {
  760. var email = $scope.signUp.email;
  761. return SignUp.checkEmailExists(email).then(function (response) {
  762. var status = response.status;
  763. if (status === HttpStatuses.OK_WITHOUT_DATA) {
  764. $scope.signUp.emailStatus = "Email was registered earlier. Forgot the password?";
  765. $scope.signUp.emailWrong = "";
  766. } else if (status === HttpStatuses.VALIDATION_FAILED) {
  767. $scope.signUp.emailWrong = "Wrong email format.";
  768. $scope.signUp.emailStatus = "";
  769. } else {
  770. $scope.signUp.emailStatus = "";
  771. $scope.signUp.emailWrong = "";
  772. }
  773.  
  774. return response;
  775. });
  776. }
  777.  
  778. $scope.testEmail = function () {
  779. return appConstants.EMAIL_REGEX.test($scope.signUp.email);
  780. };
  781.  
  782. $scope.showSignUpForm = function ($event) {
  783. $event.preventDefault();
  784. $scope.signUp.first_name = '';
  785. $scope.signUp.last_name = '';
  786. $scope.signUp.email = '';
  787. $scope.emailSentView = false;
  788. $scope.forgotPasswordView = false;
  789. };
  790.  
  791. //Send credentials
  792. function postLogin() {
  793. spinnerService.show();
  794. Login.postLoginForm($scope.login, function (response) {
  795. var user;
  796.  
  797. if (response.status === HttpStatuses.OK) {
  798. user = UserModel.build(response.user);
  799. $window.localStorage.setItem('access_token', user.token);
  800. Messages.setHeader("Welcome " + user.name);
  801. Messages.setText("You have been successfully logged.");
  802. Messages.sendMessage();
  803. event.name = 'successLogin';
  804. event.params = {user: user.email};
  805. $location.path('/profile').replace();
  806.  
  807. setTimeout(function () {
  808. $window.location.reload();
  809. }, 0);
  810.  
  811. } else {
  812. spinnerService.hide();
  813. if ('errors' in response) {
  814. event.name = 'failedLogin';
  815. event.params = {error: response.data.errors[0].detail};
  816.  
  817. Messages.sendError(response);
  818. }
  819. }
  820. });
  821. }
  822. }
  823. }());
  824.  
  825. (function () {
  826. "use strict";
  827.  
  828. angular
  829. .module("loginApp")
  830. .constant("appConstants", {
  831. "DEFAULT_AVATAR": "common/images/app/default-avatar.jpg",
  832. "SEARCH_INPUT_TIMEOUT": 700,
  833. "PER_PAGE_DEFAULT": 10,
  834. "PER_PAGE_NOTIFICATIONS_DEFAULT": 6,
  835. "PER_PAGE_REQUESTS_DEFAULT": 6,
  836. "SRC_REGEX": 'src\=\"([A-Za-z0-9\S_\\/\/:.-]*)\"',
  837. "EMAIL_REGEX": /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/,
  838. "G_RECAPTCHA_KEY": '6LeiFiMTAAAAAPVl1d54uz8c7RxjWYYoyBTYr3hN',
  839. "PROLONG_TOKEN_INTERVAL": 120000,
  840. "SEEK_NOTIFICATIONS_INTERVAL": 20000,
  841. "FACEBOOK_APP_ID": '1731517977115865',
  842. "SHARING_LOGO_URL": 'https://loangifting.com/common/images/v2/lg-red-small-logo.png',
  843. "BASE_SITE_URL": "https://loans.gifts"
  844. });
  845. }());
  846.  
  847. (function () {
  848. "use strict";
  849.  
  850. angular
  851. .module("loginApp")
  852. .constant("colorsConstants", {
  853. "red": "#FF0000",
  854. "darked": "#8B0000",
  855. "tomato": "#FF6347",
  856. "crimson": "#DC143C",
  857. "firebrick": "#B22222",
  858. "lightcoral": "#F08080",
  859. "gray": "#F1F1F1"
  860. });
  861. }());
  862.  
  863. (function () {
  864. "use strict";
  865.  
  866. angular
  867. .module("loginApp")
  868. .constant("Endpoints", {
  869. // Authentication endpoints
  870. "login": "/rest/user/login",
  871. "refreshToken": "/rest/user/token-extend",
  872. "userExists": "/rest/user/exist",
  873. "signUp": "/rest/user/signup",
  874. "resetPassword": "/rest/user/reset-password",
  875. // profile endpoints
  876. "profileInfo": "/rest/profile/info",
  877. "accountInfo": "/rest/profile/account-info",
  878. "isAdmin": "/rest/profile/is-admin",
  879. "profileEducation": "/rest/profile/education",
  880. "profileEmployments": "/rest/profile/employments",
  881. "profileFile": "/rest/profile/file",
  882. "profileResourceLink": "/rest/profile/resource-link",
  883. "statesList": "data/states-hash.json", // temporary json-hash solution
  884. "passwordInfoPath": "/rest/profile/password",
  885. "deleteAccount": "/rest/profile/account",
  886. "privacySettings": "/rest/privacy/settings",
  887. "userActivity": "/rest/information/user-recent-activity",
  888. // payment
  889. "acceptPayment": "/rest/payments/accept", // post
  890. "payPalLink": "/rest/payments/pay-pal-payment-link", // get
  891.  
  892. //gifting
  893. "giftingHistory": "/rest/gifts/history",
  894. "giftTemplates": "data/gifting/gift-templates.json",
  895. "backgrounds": "data/gifting/backgrounds.json",
  896.  
  897. //thank
  898. "thankTemplates": "data/thank/thank-templates.json",
  899. "thankBackgrounds": "data/thank/thank-backgrounds.json",
  900.  
  901. //support
  902. "supportMessage": "/rest/information/support",
  903.  
  904. //subscribe
  905. "subscribe": "/rest/information/subscription",
  906.  
  907. //Static pages
  908. "aboutUS": "data/about-us.json",
  909.  
  910. //oauth
  911. importContactsLink: "/rest/oauth/get-import-contacts-link",
  912. contactsFromSocialNetwork: "/rest/oauth/get-contacts"
  913.  
  914. });
  915. }());
  916.  
  917. (function () {
  918. "use strict";
  919.  
  920. angular
  921. .module("loginApp")
  922. .constant("HttpStatuses", {
  923. OK: 200,
  924. OK_CREATED: 201,
  925. OK_WITHOUT_DATA: 204,
  926. NOT_MODIFIED: 304,
  927. BAD_REQUEST: 400,
  928. AUTH_FAILED: 401,
  929. HAVE_NOT_ACCESS: 403,
  930. NOT_FOUND: 404,
  931. NOT_ALLOWED: 405,
  932. INVALID_CONTENT_TYPE: 415,
  933. VALIDATION_FAILED: 422,
  934. TOO_MANY_REQUEST: 429,
  935. APPLICATION_ERROR: 500,
  936. okCodes: [
  937. 200,
  938. 201,
  939. 204
  940. ]
  941. });
  942. }());
  943.  
  944. // jscs: disable
  945. /**
  946. * disable code style for external code methods only
  947. */
  948. (function () {
  949. "use strict";
  950.  
  951. angular
  952. .module("loginApp")
  953. .factory("BaseHelper", BaseHelper);
  954.  
  955. function BaseHelper() {
  956. return {
  957. /**
  958. * Creates and returns a blob from a data URL (either base64 encoded or not).
  959. *
  960. * @param {string} dataURL The data URL to convert.
  961. * @return {Blob} A blob representing the array buffer data.
  962. */
  963. dataURLToBlob: function (dataURL) {
  964. var BASE64_MARKER = ';base64,';
  965. if (dataURL.indexOf(BASE64_MARKER) == -1) {
  966. var parts = dataURL.split(',');
  967. var contentType = parts[0].split(':')[1];
  968. var raw = decodeURIComponent(parts[1]);
  969.  
  970. return new Blob([raw], {type: contentType});
  971. }
  972.  
  973. var parts = dataURL.split(BASE64_MARKER);
  974. var contentType = parts[0].split(':')[1];
  975. var raw = window.atob(parts[1]);
  976. var rawLength = raw.length;
  977.  
  978. var uInt8Array = new Uint8Array(rawLength);
  979.  
  980. for (var i = 0; i < rawLength; ++i) {
  981. uInt8Array[i] = raw.charCodeAt(i);
  982. }
  983.  
  984. return new Blob([uInt8Array], {type: contentType});
  985. }
  986. };
  987. }
  988. })();
  989.  
  990. (function () {
  991. "use strict";
  992.  
  993. angular
  994. .module("loginApp")
  995. .factory("cacheHelper", cacheHelper);
  996.  
  997. cacheHelper.$inject = [
  998. '$window',
  999. '$q',
  1000. '$http'
  1001. ];
  1002.  
  1003. function cacheHelper($window,
  1004. $q,
  1005. $http) {
  1006. return {
  1007. /**
  1008. * Cache data from request
  1009. * @param {string} restUrl
  1010. * @param {string} namespace
  1011. * @param {object|boolean} params
  1012. * @param {boolean} reCache - drop cache and reload data
  1013. * @returns {Promise}
  1014. */
  1015. getFromStorage: function (restUrl, namespace, params, reCache) {
  1016. if (params) {
  1017. params = {params: params};
  1018. }
  1019.  
  1020. if (!$window.localStorage[namespace]) {
  1021. return $http.get(restUrl, params).then(function (response) {
  1022. $window.localStorage[namespace] = JSON.stringify(response.data);
  1023. return JSON.parse($window.localStorage[namespace]);
  1024. });
  1025. } else {
  1026. return $q(function (resolve) {
  1027. return resolve(JSON.parse($window.localStorage[namespace]));
  1028. });
  1029. }
  1030. },
  1031.  
  1032. /**
  1033. * Delete storing data from localStorage by key
  1034. * @param {string} namespace
  1035. * @returns {boolean}
  1036. */
  1037. unsetStorageByKey: function (namespace) {
  1038. return delete $window.localStorage[namespace];
  1039. }
  1040. };
  1041. }
  1042. })();
  1043.  
  1044. (function () {
  1045. "use strict";
  1046.  
  1047. angular
  1048. .module("loginApp")
  1049. .factory("DebounceHelper", DebounceHelper);
  1050.  
  1051. function DebounceHelper() {
  1052. return {
  1053. getWrapper: function (f, ms) {
  1054.  
  1055. var state = null,
  1056. COOLDOWN = 1;
  1057.  
  1058. return function () {
  1059. if (state) {
  1060. return;
  1061. }
  1062.  
  1063. f.apply(this, arguments);
  1064.  
  1065. state = COOLDOWN;
  1066.  
  1067. setTimeout(function () {
  1068. state = null
  1069. }, ms);
  1070. }
  1071. }
  1072. };
  1073. }
  1074. })();
  1075.  
  1076. (function () {
  1077. "use strict";
  1078.  
  1079. angular
  1080. .module("loginApp")
  1081. .factory("fakeRequestHelper", fakeRequestHelper);
  1082.  
  1083. fakeRequestHelper.$inject = [
  1084. '$timeout',
  1085. '$q',
  1086. '$rootScope'
  1087. ];
  1088.  
  1089. function fakeRequestHelper($timeout, $q, $rootScope) {
  1090. return {
  1091. // with spinner
  1092. backendSimulator: function (data, delay) {
  1093. $timeout(function () {
  1094. $rootScope.spinner.show();
  1095. });
  1096. return $q(function (resolve) {
  1097. return setTimeout(function () {
  1098. $rootScope.spinner.hide();
  1099. return resolve(data);
  1100. }, delay || 1000);
  1101. });
  1102. },
  1103. // simple promise simulation
  1104. getPromise: function (data, delay) {
  1105. var deferred = $q.defer();
  1106. $timeout(function () {
  1107. deferred.resolve(data);
  1108. }, delay || 1000);
  1109.  
  1110. return deferred.promise;
  1111. }
  1112. };
  1113. }
  1114. })();
  1115.  
  1116. (function () {
  1117. 'use strict';
  1118.  
  1119. angular
  1120. .module('loginApp')
  1121. .factory('focusInput', function ($timeout, $window) {
  1122. return function (el) {
  1123. // timeout makes sure that it is invoked after any other event has been triggered.
  1124. // e.g. click events that need to run before the focus or
  1125. // inputs elements that are in a disabled state but are enabled when those events
  1126. // are triggered.
  1127. $timeout(function () {
  1128. if (el) {
  1129. el.find('input').focus();
  1130. }
  1131. });
  1132. };
  1133. });
  1134. })();
  1135.  
  1136.  
  1137. (function () {
  1138. "use strict";
  1139.  
  1140. angular
  1141. .module("loginApp")
  1142. .factory("randomHelper", randomHelper);
  1143.  
  1144. randomHelper.$inject = [];
  1145.  
  1146. function randomHelper() {
  1147. var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  1148.  
  1149. return {
  1150. generateCode: function (length) {
  1151. var text = "", i;
  1152.  
  1153. for (i = 0; i < length; i++) {
  1154. text += possible.charAt(Math.floor(Math.random() * possible.length));
  1155. }
  1156.  
  1157. return text;
  1158. }
  1159. };
  1160. }
  1161. })();
  1162.  
  1163. (function () {
  1164. "use strict";
  1165.  
  1166. angular
  1167. .module("loginApp")
  1168. .factory("ThrottleHelper", ThrottleHelper);
  1169.  
  1170. function ThrottleHelper() {
  1171. return {
  1172. getWrapper: function (func, ms) {
  1173.  
  1174. var isThrottled = false,
  1175. savedArgs,
  1176. savedThis;
  1177.  
  1178. function wrapper() {
  1179.  
  1180. if (isThrottled) {
  1181. savedArgs = arguments;
  1182. savedThis = this;
  1183. return;
  1184. }
  1185.  
  1186. func.apply(this, arguments);
  1187.  
  1188. isThrottled = true;
  1189.  
  1190. setTimeout(function () {
  1191. isThrottled = false;
  1192. if (savedArgs) {
  1193. wrapper.apply(savedThis, savedArgs);
  1194. savedArgs = savedThis = null;
  1195. }
  1196. }, ms);
  1197. }
  1198.  
  1199. return wrapper;
  1200. }
  1201. };
  1202. }
  1203. })();
  1204.  
  1205. (function () {
  1206. 'use strict';
  1207.  
  1208. angular
  1209. .module("loginApp")
  1210. .factory('BaseMapper', BaseMapper);
  1211.  
  1212. BaseMapper.$inject = [
  1213. 'dateService'
  1214. ];
  1215.  
  1216. function BaseMapper(dateService) {
  1217.  
  1218. function Base() {}
  1219.  
  1220. function attributesDateStringModifier(attributes) {
  1221. var k;
  1222.  
  1223. for (k in attributes) {
  1224. if (attributes.hasOwnProperty(k)) {
  1225. if (dateService.testDate(attributes[k])) {
  1226. attributes[k] = dateService.datePatcher(attributes[k]);
  1227. }
  1228. }
  1229. }
  1230.  
  1231. return attributes;
  1232. }
  1233.  
  1234. Base.prototype.baseMapFromServer = function (data) {
  1235. var mappedDataItem = null;
  1236.  
  1237. if ('data' in data) {
  1238. data = data.data;
  1239. }
  1240.  
  1241. if (data && data.length) {
  1242. data = data[0];
  1243. mappedDataItem = data.attributes;
  1244. mappedDataItem = attributesDateStringModifier(mappedDataItem);
  1245. }
  1246.  
  1247. return mappedDataItem;
  1248. };
  1249.  
  1250. Base.prototype.baseMapArrayFromServer = function (data) {
  1251. var mappedDataArray = [];
  1252. if ('data' in data) {
  1253. data = data.data;
  1254. }
  1255.  
  1256. if (data && data.length) {
  1257. data.map(function (value, index) {
  1258. mappedDataArray[index] = value.attributes;
  1259. mappedDataArray[index] = attributesDateStringModifier(mappedDataArray[index]);
  1260. });
  1261. }
  1262.  
  1263. return mappedDataArray;
  1264. };
  1265.  
  1266. Base.prototype.baseGetMetaInformation = function (data) {
  1267. var metaObject = {};
  1268.  
  1269. if ('meta' in data) {
  1270. metaObject = data.meta;
  1271. }
  1272.  
  1273. return metaObject;
  1274. };
  1275.  
  1276. Base.prototype.baseMapErrorsFromServer = function (data) {
  1277. var mappedDataArray = [];
  1278. if ('errors' in data) {
  1279. data = data.errors;
  1280. }
  1281.  
  1282. if (data && data.length) {
  1283. data.map(function (value, index) {
  1284. mappedDataArray[index] = value;
  1285. });
  1286. }
  1287.  
  1288. return mappedDataArray;
  1289. };
  1290.  
  1291. Base.prototype.getPagination = function (data) {
  1292. var meta = this.baseGetMetaInformation(data);
  1293.  
  1294. return {
  1295. currentCount: +meta.current_count,
  1296. perPage: +meta.per_page,
  1297. totalCount: +meta.total_count
  1298. };
  1299. };
  1300.  
  1301. return Base;
  1302. }
  1303. })();
  1304.  
  1305. (function () {
  1306. 'use strict';
  1307.  
  1308. angular
  1309. .module("loginApp")
  1310. .factory('errorsMapper', errorsMapper);
  1311.  
  1312. errorsMapper.$inject = ['BaseMapper'];
  1313.  
  1314. function errorsMapper(BaseMapper) {
  1315.  
  1316. ErrorsMapper.prototype = BaseMapper.prototype;
  1317.  
  1318. function ErrorsMapper() {
  1319. this.mapArrayFromServer = mapArrayFromServer;
  1320.  
  1321. function mapArrayFromServer(data) {
  1322. var errors = this.baseMapErrorsFromServer(data);
  1323. return errors.map(function (item) {
  1324. return {
  1325. detail: item.detail,
  1326. fieldName: item.field_name
  1327. }
  1328. });
  1329. }
  1330. }
  1331.  
  1332. return new ErrorsMapper();
  1333. }
  1334. })();
  1335.  
  1336. (function () {
  1337. 'use strict';
  1338.  
  1339. angular
  1340. .module("loginApp")
  1341. .factory('SocialNetworkModel', SocialNetworkModel);
  1342.  
  1343. SocialNetworkModel.$inject = [];
  1344.  
  1345. function SocialNetworkModel() {
  1346.  
  1347. function SocialNetwork() {
  1348. this.redirectLink = '/';
  1349. }
  1350.  
  1351. return SocialNetwork;
  1352. }
  1353. })();
  1354.  
  1355. (function () {
  1356. 'use strict';
  1357.  
  1358. angular
  1359. .module("loginApp")
  1360. .factory('socialNetworkMapper', socialNetworkMapper);
  1361.  
  1362. socialNetworkMapper.$inject = ['BaseMapper'];
  1363.  
  1364. function socialNetworkMapper(BaseMapper) {
  1365.  
  1366. SocialNetworkMapper.prototype = BaseMapper.prototype;
  1367.  
  1368. function SocialNetworkMapper() {
  1369. var self = this;
  1370. BaseMapper.apply(this);
  1371. this.mapFromServer = mapFromServer;
  1372.  
  1373. function mapFromServer(data) {
  1374. var attributes = self.baseMapFromServer(data);
  1375. return {
  1376. redirectLink: attributes.link
  1377. }
  1378. }
  1379. }
  1380.  
  1381. return new SocialNetworkMapper();
  1382. }
  1383. })();
  1384.  
  1385. (function () {
  1386. "use strict";
  1387.  
  1388. angular
  1389. .module("loginApp")
  1390. .constant("socialNetworksEnum", {
  1391.  
  1392. "google": 4,
  1393.  
  1394. "microsoft": 6,
  1395.  
  1396. "yahoo": 7
  1397.  
  1398. });
  1399. }());
  1400.  
  1401. (function () {
  1402. 'use strict';
  1403.  
  1404. angular
  1405. .module('loginApp')
  1406. .factory('timeService', timeService);
  1407.  
  1408. timeService.$inject = [];
  1409.  
  1410. function timeService() {
  1411. return {
  1412. timeAgo: function (date) {
  1413. var seconds,
  1414. interval;
  1415.  
  1416. // format into locale time
  1417. date = date - this.getMsOffset();
  1418. seconds = Math.floor((new Date() - new Date(date)) / 1000);
  1419. interval = Math.floor(seconds / 31536000);
  1420.  
  1421. if (interval > 1) {
  1422. return interval + " years ago";
  1423. }
  1424. interval = Math.floor(seconds / 2592000);
  1425. if (interval > 1) {
  1426. return interval + " months ago";
  1427. }
  1428. interval = Math.floor(seconds / 604800);
  1429. if (interval > 1) {
  1430. return interval + " weeks ago";
  1431. }
  1432. interval = Math.floor(seconds / 86400);
  1433. if (interval > 1) {
  1434. return interval + " days ago";
  1435. }
  1436. interval = Math.floor(seconds / 3600);
  1437. if (interval > 1) {
  1438. return interval + " hours ago";
  1439. }
  1440. interval = Math.floor(seconds / 60);
  1441. if (interval > 1) {
  1442. return interval + " minutes ago";
  1443. }
  1444. return Math.floor(seconds) + " seconds ago";
  1445. },
  1446.  
  1447. getMsOffset: function () {
  1448. var minutesOffset = (new Date()).getTimezoneOffset();
  1449.  
  1450. return minutesOffset * 60 * 1000 + 3600000;
  1451. },
  1452.  
  1453. isValidDate: function (date) { //Time format 'YYYY-MM-DD'
  1454.  
  1455. var matches = /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/.exec(date);
  1456. if (matches == null) {
  1457. return false;
  1458. }
  1459. var y = matches[1];
  1460. var m = matches[2];
  1461. var d = matches[3];
  1462.  
  1463. var composedDate = new Date(y, m, d);
  1464. return composedDate.getDate() == d &&
  1465. composedDate.getMonth() == m &&
  1466. composedDate.getFullYear() == y;
  1467. },
  1468.  
  1469. getDaysDiffBetweenDates: function (firstDate, secondDate) {
  1470. var date1 = new Date(firstDate),
  1471. date2 = new Date(secondDate),
  1472. timeDiff = date2.getTime() - date1.getTime(),
  1473. diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
  1474.  
  1475. return diffDays;
  1476. },
  1477.  
  1478. getApproximateDaysFromMonths: function (months) {
  1479. months = +(months.toFixed(2));
  1480. if (months < 1.03) {
  1481. months = 0;
  1482. }
  1483.  
  1484. // approximate days per one month 30.4
  1485. return Math.ceil(months * 30.4);
  1486. },
  1487.  
  1488. changeDateByDaysDiff: function (date, days) {
  1489. var d = new Date(date);
  1490. d.setDate(d.getDate() + days);
  1491. return d;
  1492. },
  1493.  
  1494. changeDateByMonthsDiff: function (date, months) {
  1495. var d = new Date(date);
  1496. return d.setMonth(d.getMonth() - months);
  1497. },
  1498.  
  1499. getMonthsDiffBetweenDates: function (firstDate, secondDate) {
  1500. var months;
  1501. months = (secondDate.getFullYear() - firstDate.getFullYear()) * 12;
  1502. months -= firstDate.getMonth() + 1;
  1503. months += secondDate.getMonth();
  1504. return months <= 0 ? 0 : months;
  1505. }
  1506.  
  1507. }
  1508. }
  1509.  
  1510. })();
  1511.  
  1512. (function () {
  1513. 'use strict';
  1514.  
  1515. angular
  1516. .module('loginApp')
  1517. .factory('allocationService', allocationService);
  1518.  
  1519. allocationService.$inject = [
  1520. 'spinnerService',
  1521. 'loanService'
  1522. ];
  1523.  
  1524. function allocationService(spinnerService,
  1525. loanService) {
  1526.  
  1527. return {
  1528. distributeDeletedAllocation: function (loans, percents, loanId) {
  1529. var length = 0;
  1530.  
  1531. loans = loans.filter(function (loan) {
  1532. if (loan.loanId !== loanId) {
  1533. if (loan.isCorrectInformation()) {
  1534. length += 1;
  1535. }
  1536. return loan;
  1537. }
  1538. });
  1539.  
  1540. var loansLength = length,
  1541. modulo = percents % loansLength,
  1542. wholePartsPercents = percents - modulo,
  1543. equalPart = wholePartsPercents / loansLength,
  1544. i;
  1545.  
  1546. // distribute equal parts
  1547. loans = loans.map(function (loan) {
  1548. if (loan.isCorrectInformation()) {
  1549. loan.allocatedPercentage += equalPart;
  1550. if (modulo) {
  1551. loan.allocatedPercentage += modulo;
  1552. modulo = 0; // clear modulo after sum
  1553. }
  1554. }
  1555.  
  1556. return loan;
  1557. });
  1558.  
  1559. return loans;
  1560. },
  1561.  
  1562. saveAllocation: function (loans) {
  1563. spinnerService.show();
  1564. loanService.updateLoansDistribution(loans).then(function (response) {
  1565. spinnerService.hide();
  1566. });
  1567. },
  1568.  
  1569. /**
  1570. * method helps to resolve loans trouble
  1571. * with allocation on non correct loans
  1572. * allocation
  1573. */
  1574. fixCollectionAllocation: function (loans) {
  1575. var hasTrouble = false,
  1576. filtered = [],
  1577. badLoan;
  1578.  
  1579. if (loans.length === 1) {
  1580. return loans;
  1581. }
  1582.  
  1583. filtered = loans.filter(function (loan) {
  1584. if (!loan.isCorrectInformation() && +loan.allocatedPercentage === 100) {
  1585. hasTrouble = true;
  1586. return loan;
  1587. }
  1588. });
  1589.  
  1590. if (hasTrouble && filtered.length) {
  1591. badLoan = filtered[0];
  1592.  
  1593. loans = loans.map(function (loan) {
  1594. if (loan.loanId === badLoan.loanId) {
  1595. loan.allocatedPercentage = 0;
  1596. }
  1597.  
  1598. if (loan.loanId !== badLoan.loanId && hasTrouble) {
  1599. loan.allocatedPercentage = 100;
  1600. hasTrouble = false;
  1601. }
  1602.  
  1603. return loan;
  1604. });
  1605.  
  1606. this.saveAllocation(loans);
  1607. }
  1608.  
  1609. return loans;
  1610. }
  1611. };
  1612. }
  1613.  
  1614. })();
  1615.  
  1616. (function () {
  1617. 'use strict';
  1618.  
  1619. angular
  1620. .module('loginApp')
  1621. .factory('apiService', apiService);
  1622.  
  1623. apiService.$inject = [
  1624. 'APIEndpoint'
  1625. ];
  1626.  
  1627. function apiService(APIEndpoint) {
  1628.  
  1629. return {
  1630. wrap: function (path) {
  1631. return APIEndpoint + path;
  1632. }
  1633. };
  1634. }
  1635.  
  1636. })();
  1637.  
  1638. (function () {
  1639. 'use strict';
  1640.  
  1641. angular
  1642. .module('loginApp')
  1643. .factory('authService', authService);
  1644.  
  1645. authService.$inject = [
  1646. '$window'
  1647. ];
  1648.  
  1649. function authService($window) {
  1650.  
  1651. return {
  1652. logout: function () {
  1653. $window.localStorage.removeItem('access_token');
  1654. $window.localStorage.removeItem('is_admin');
  1655. },
  1656.  
  1657. setToken: function (tokenString) {
  1658. $window.localStorage.setItem('access_token', tokenString)
  1659. },
  1660.  
  1661. getToken: function () {
  1662. return $window.localStorage.getItem('access_token');
  1663. },
  1664.  
  1665. isLoggedIn: function () {
  1666. var token = $window.localStorage.getItem('access_token');
  1667. return (!!token) ? token : null;
  1668. },
  1669.  
  1670. setAdmin: function () {
  1671. $window.localStorage.setItem('is_admin', 1);
  1672. },
  1673.  
  1674. isAdmin: function () {
  1675. var token = $window.localStorage.getItem('is_admin');
  1676. return (!!token) ? token : null;
  1677. }
  1678. };
  1679. }
  1680.  
  1681. })();
  1682.  
  1683. (function () {
  1684. 'use strict';
  1685.  
  1686. angular
  1687. .module('loginApp')
  1688. .factory('dateService', dateService);
  1689.  
  1690. dateService.$inject = [];
  1691.  
  1692. function dateService() {
  1693.  
  1694. return {
  1695. getDaysDiffBetweenDates: function (firstDate, secondDate) {
  1696. var date1 = new Date(firstDate),
  1697. date2 = new Date(secondDate),
  1698. timeDiff = date2.getTime() - date1.getTime(),
  1699. diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
  1700.  
  1701. return diffDays;
  1702. },
  1703.  
  1704. getApproximateDaysFromMonths: function (months) {
  1705. months = +(months.toFixed(2));
  1706. if (months < 1.03) {
  1707. months = 0;
  1708. }
  1709.  
  1710. // approximate days per one month 30.4
  1711. return Math.ceil(months * 30.4);
  1712. },
  1713.  
  1714. changeDateByDaysDiff: function (date, days) {
  1715. var d = new Date(date);
  1716. d.setDate(d.getDate() + days);
  1717. return d;
  1718. },
  1719.  
  1720. changeDateByMonthsDiff: function (date, months) {
  1721. var d = new Date(date);
  1722. return d.setMonth(d.getMonth() - months);
  1723. },
  1724.  
  1725. getMonthsDiffBetweenDates: function (firstDate, secondDate) {
  1726. var months;
  1727. months = (secondDate.getFullYear() - firstDate.getFullYear()) * 12;
  1728. months -= firstDate.getMonth() + 1;
  1729. months += secondDate.getMonth();
  1730. return months <= 0 ? 0 : months;
  1731. },
  1732.  
  1733. getTimezoneOffset: function () {
  1734. return +(new Date().getTimezoneOffset()) * 60000 + 3600000;
  1735. },
  1736.  
  1737. testDate: function (str) {
  1738. var dateTimeRegexp = /\d{4}-\d{1,2}-\d{1,2}(\s\d+:\d+:\d+)?$/;
  1739. return dateTimeRegexp.test(str);
  1740. },
  1741.  
  1742. updateToUTCString: function (dateString) {
  1743. var date, time, dateTimeObject, parts;
  1744.  
  1745. if (~dateString.indexOf(':')) {
  1746. parts = dateString.split(" ");
  1747. date = parts[0].split("-");
  1748. time = parts[1].split(":");
  1749. dateTimeObject = new Date();
  1750. dateTimeObject.setUTCFullYear(date[0], date[1] - 1, date[2]);
  1751. dateTimeObject.setUTCHours(time[0], time[1], time[2], 0);
  1752. } else {
  1753. date = dateString.split("-");
  1754. dateTimeObject = new Date();
  1755. dateTimeObject.setUTCFullYear(date[0], date[1] - 1, date[2]);
  1756. dateTimeObject.setUTCHours(0, 0, 0, 0);
  1757. }
  1758.  
  1759. return dateTimeObject;
  1760. },
  1761.  
  1762. getTimeWithoutOffset: function (dateTimeObject) {
  1763. var offset = this.getTimezoneOffset();
  1764. return new Date(dateTimeObject.getTime() + offset);
  1765. },
  1766.  
  1767. datePatcher: function (dateString) {
  1768. var dateTimeObject = this.updateToUTCString(dateString);
  1769. dateTimeObject = this.getTimeWithoutOffset(dateTimeObject);
  1770.  
  1771. return dateTimeObject;
  1772. }
  1773. };
  1774. }
  1775.  
  1776. })();
  1777.  
  1778. (function () {
  1779. 'use strict';
  1780.  
  1781. angular
  1782. .module('loginApp')
  1783. .factory('donutChartService', donutChartService);
  1784.  
  1785. donutChartService.$inject = [
  1786. 'colorsConstants'
  1787. ];
  1788.  
  1789. function donutChartService(colorsConstants) {
  1790.  
  1791. return {
  1792.  
  1793. /**
  1794. * Returns object for configuring donut-chart directive
  1795. * @param {[Object, Object, ...]} loansCollection
  1796. * @returns {{labels: Array, datasets: Array}}
  1797. */
  1798. getDataOptions: function (loansCollection) {
  1799. var colors = [], savedColors = [], k, i,
  1800. totalLoan = 0,
  1801. hoverBg = '#F1F1F1',
  1802. labels = [],
  1803. data = [],
  1804. balance = 0,
  1805. remainingAmount = 0,
  1806. backgroundColor = [],
  1807. hoverBackgroundColor = [],
  1808. chartData = {
  1809. labels: [],
  1810. datasets: []
  1811. };
  1812.  
  1813. loansCollection = loansCollection || [];
  1814.  
  1815. for (k in colorsConstants) {
  1816. colorsConstants.hasOwnProperty(k) && colors.push(colorsConstants[k]);
  1817. }
  1818.  
  1819. savedColors = angular.copy(colors);
  1820.  
  1821. for (i = 0; i < loansCollection.length; i++) {
  1822.  
  1823. balance = Math.ceil(+loansCollection[i].balance);
  1824. remainingAmount = +loansCollection[i].remainingAmount;
  1825.  
  1826. // skip loan for chart painting
  1827. if (balance === 0) {
  1828. continue;
  1829. }
  1830.  
  1831. if (colors.length === 1) {
  1832. colors = savedColors;
  1833. }
  1834.  
  1835. labels.push(loansCollection[i].bankName);
  1836. data.push(balance);
  1837. backgroundColor.push(colors.shift());
  1838. hoverBackgroundColor.push(hoverBg);
  1839. totalLoan += Math.ceil(remainingAmount);
  1840. }
  1841.  
  1842. // last push total loan
  1843. labels.push('loan');
  1844. data.push(totalLoan);
  1845. backgroundColor.push(savedColors[savedColors.length - 1]);
  1846. hoverBackgroundColor.push(hoverBg);
  1847.  
  1848. chartData.labels = labels;
  1849. chartData.datasets.push({
  1850. data: data,
  1851. backgroundColor: backgroundColor,
  1852. hoverBackgroundColor: hoverBackgroundColor
  1853. });
  1854.  
  1855. return chartData;
  1856. },
  1857.  
  1858. getTotalDataOptions: function (loansCollection) {
  1859. var colors = [], k, i,
  1860. totalBalance = 0,
  1861. totalLoan = 0,
  1862. hoverBg = '#F1F1F1',
  1863. labels = [],
  1864. data = [],
  1865. backgroundColor = [],
  1866. hoverBackgroundColor = [],
  1867. chartData = {
  1868. labels: [],
  1869. datasets: []
  1870. };
  1871.  
  1872. for (k in colorsConstants) {
  1873. colorsConstants.hasOwnProperty(k) && colors.push(colorsConstants[k]);
  1874. }
  1875.  
  1876. for (i = 0; i < loansCollection.length; i++) {
  1877. totalBalance += Math.ceil(+loansCollection[i].balance);
  1878. totalLoan += Math.ceil(+loansCollection[i].remainingAmount);
  1879. }
  1880.  
  1881. // first push total balance chart
  1882. labels.push('total paid');
  1883. data.push(totalBalance);
  1884. backgroundColor.push(colors[0]);
  1885. hoverBackgroundColor.push(hoverBg);
  1886.  
  1887. // last push total loan
  1888. labels.push('loan');
  1889. data.push(totalLoan);
  1890. backgroundColor.push(colors[colors.length - 1]);
  1891. hoverBackgroundColor.push(hoverBg);
  1892.  
  1893. chartData.labels = labels;
  1894. chartData.datasets.push({
  1895. data: data,
  1896. backgroundColor: backgroundColor,
  1897. hoverBackgroundColor: hoverBackgroundColor
  1898. });
  1899.  
  1900. return chartData;
  1901. },
  1902.  
  1903. /**
  1904. * get percentage representation of loan completion
  1905. * @returns {string} eq float number
  1906. */
  1907. getCompletePercent: function (totalOwed, totalPaid) {
  1908. if (totalOwed > 0) {
  1909. return Number(100 / (totalOwed / totalPaid)).toFixed(0);
  1910. } else {
  1911. return '0';
  1912. }
  1913. },
  1914.  
  1915. getCompletePercentFromCollection: function (loans, trace) {
  1916. var totalOwed = 0, totalPaid = 0;
  1917.  
  1918. if (!loans || !loans.length) {
  1919. return;
  1920. }
  1921.  
  1922. loans.forEach(function (loan) {
  1923. totalOwed += Math.ceil(+loan.originalAmount);
  1924. totalPaid += Math.ceil(+loan.balance);
  1925. });
  1926.  
  1927. if (!trace) {
  1928. return this.getCompletePercent(totalOwed, totalPaid);
  1929. } else {
  1930. return {
  1931. complete: this.getCompletePercent(totalOwed, totalPaid),
  1932. paid: totalPaid,
  1933. owed: totalOwed
  1934. }
  1935. }
  1936.  
  1937. }
  1938. };
  1939. }
  1940.  
  1941. })();
  1942.  
  1943. (function (angular) {
  1944. 'use strict';
  1945.  
  1946. angular
  1947. .module('loginApp')
  1948. .factory('EventsService', EventsService);
  1949.  
  1950. EventsService.$inject = [
  1951. '$rootScope'
  1952. ];
  1953.  
  1954. function EventsService($rootScope) {
  1955.  
  1956. return {
  1957.  
  1958. sendPixelEvent: function (event) {
  1959. fbq('track', event.name, event.params);
  1960. },
  1961. sendCustomPixelEvent: function (event) {
  1962. fbq('trackCustom', event.name, event.params);
  1963. },
  1964. sendIntercomEvent: function (event) {
  1965. var time = +new Date;
  1966. window.Intercom("boot", {
  1967. app_id: "heoqdjs2",
  1968. name: event.name, // Full name
  1969. email: event.email, // Email address
  1970. created_at: time // Signup date as a Unix timestamp
  1971. });
  1972. },
  1973. identifyFS: function (event) {
  1974. FS.identify(event.email, {
  1975. displayName: event.name
  1976. });
  1977. }
  1978. };
  1979. }
  1980.  
  1981. })(angular);
  1982.  
  1983. (function (angular) {
  1984. 'use strict';
  1985.  
  1986. angular
  1987. .module('loginApp')
  1988. .factory('introService', introService);
  1989.  
  1990. introService.$inject = [
  1991. '$rootScope',
  1992. '$window'
  1993. ];
  1994.  
  1995. function introService($rootScope, $window) {
  1996.  
  1997. return {
  1998. enableIntro: function () {
  1999. $window.localStorage.setItem('intro_value', 1);
  2000. },
  2001.  
  2002. disableIntro: function () {
  2003. $window.localStorage.setItem('intro_value', 2);
  2004. },
  2005.  
  2006. isIntroEnabled: function () {
  2007. var value = $window.localStorage.getItem('intro_value');
  2008. return +value === 1;
  2009. },
  2010.  
  2011. unsetIntroValue: function () {
  2012. $window.localStorage.removeItem('intro_value');
  2013. },
  2014.  
  2015. introPopupWasShowed: function () {
  2016. var val = $window.localStorage.getItem('intro_value');
  2017. return (!!val) ? val : null;
  2018. },
  2019.  
  2020. setCampaignLoaded: function () {
  2021. $window.localStorage.setItem('campaign_loaded', 1);
  2022. },
  2023.  
  2024. wasCampaignLoaded: function () {
  2025. var value = $window.localStorage.getItem('campaign_loaded');
  2026. return +value === 1;
  2027. },
  2028.  
  2029. setProfileLoaded: function () {
  2030. $window.localStorage.setItem('profile_loaded', 1);
  2031. },
  2032.  
  2033. wasProfileLoaded: function () {
  2034. var value = $window.localStorage.getItem('profile_loaded');
  2035. return +value === 1;
  2036. },
  2037.  
  2038. setLoanLoaded: function () {
  2039. $window.localStorage.setItem('loan_loaded', 1);
  2040. },
  2041.  
  2042. wasLoanLoaded: function () {
  2043. var value = $window.localStorage.getItem('loan_loaded');
  2044. return +value === 1;
  2045. },
  2046.  
  2047. getWrappedIntro: function (steps) {
  2048. return {
  2049. steps: steps,
  2050. showStepNumbers: false,
  2051. exitOnOverlayClick: true,
  2052. exitOnEsc:true,
  2053. showBullets: false,
  2054. showProgress: true,
  2055. nextLabel: 'Next',
  2056. prevLabel: 'Previous',
  2057. skipLabel: 'Skip',
  2058. doneLabel: 'Done',
  2059. scrollToElement: true
  2060. };
  2061. }
  2062. };
  2063. }
  2064.  
  2065. })(angular);
  2066.  
  2067. (function (angular) {
  2068. 'use strict';
  2069.  
  2070. angular
  2071. .module('loginApp')
  2072. .factory('Messages', Messages);
  2073.  
  2074. Messages.$inject = [
  2075. '$rootScope',
  2076. 'ModalService'
  2077. ];
  2078.  
  2079. function Messages($rootScope,
  2080. ModalService) {
  2081.  
  2082. var messageHeader = 'Error', // default
  2083. messageText = 'Server Internal Error', // default
  2084. bufferedString = [],
  2085. callback = function (result) {};
  2086.  
  2087. return {
  2088. types: {
  2089. CONFIRM_TYPE: 1,
  2090. ALERT_TYPE: 2,
  2091. DEFAULT_TYPE: 3
  2092. },
  2093.  
  2094. //Header setter
  2095. setHeader: function (header) {
  2096. messageHeader = header;
  2097. },
  2098. //Header getter
  2099. getHeader: function () {
  2100. return messageHeader;
  2101. },
  2102. //Text setter
  2103. setText: function (text) {
  2104. messageText = text;
  2105. },
  2106. pushText: function (text) {
  2107. bufferedString.push(text);
  2108. },
  2109. setErrors: function (errors) {
  2110. var self = this;
  2111. errors.forEach(function (error) {
  2112. self.pushText(error.fieldName + ': ' + error.detail);
  2113. });
  2114. },
  2115. clearBuffer: function () {
  2116. bufferedString = [];
  2117. },
  2118. //Text getter
  2119. getText: function () {
  2120. return messageText;
  2121. },
  2122. /**
  2123. * Set header and text
  2124. * @param {object} params.header
  2125. * @param {object} params.text
  2126. */
  2127. setMessage: function (params) {
  2128. var text = '';
  2129. this.setHeader(params.header);
  2130. if (typeof params.text === 'object') {
  2131. params.text.forEach(function (item) {
  2132. text += item.detail;
  2133. });
  2134. } else {
  2135. text = params.text;
  2136. }
  2137. this.setText(text);
  2138. },
  2139. sendMessage: function () {
  2140. var message = {};
  2141. message.header = this.getHeader();
  2142. message.text = this.getText();
  2143. this.showMessage(message);
  2144. },
  2145. sendError: function (response) {
  2146. var text = '';
  2147. this.setHeader("Error " + response.status);
  2148. response.data.errors && response.data.errors.forEach(function (item) {
  2149. text += item.detail;
  2150. });
  2151. this.setText(text);
  2152. this.sendMessage();
  2153. },
  2154. getModalCallback: function () {
  2155. return callback;
  2156. },
  2157. setModalCallback: function (fn) {
  2158. callback = fn;
  2159. },
  2160. /**
  2161. * Set controller and send message event
  2162. * @param {object} message.header
  2163. * @param {object} message.text
  2164. */
  2165. showMessage: function (message) {
  2166. ModalService.showModal({
  2167. templateUrl: "views/modal-message.html",
  2168. controller: "MessagesController",
  2169. controllerAs: "vm",
  2170. inputs: {
  2171. params: {
  2172. header: this.getHeader(),
  2173. text: this.getText(),
  2174. bufferedString: bufferedString,
  2175. modalCallback: this.getModalCallback()
  2176. }
  2177. }
  2178. }).then(function (modal) {
  2179. modal.element.modal && modal.element.modal();
  2180.  
  2181. modal.close.then(function (result) {
  2182. callback.call(modal, result);
  2183. });
  2184. });
  2185.  
  2186. // clear after show
  2187. bufferedString = [];
  2188. }
  2189. };
  2190. }
  2191.  
  2192. })(angular);
  2193.  
  2194. (function () {
  2195. 'use strict';
  2196.  
  2197. angular
  2198. .module('loginApp')
  2199. .factory('oauthService', oauthService);
  2200.  
  2201. oauthService.$inject = [
  2202. 'Endpoints',
  2203. '$http',
  2204. 'socialNetworkMapper',
  2205. 'socialNetworksEnum',
  2206. 'importMapper'
  2207. ];
  2208.  
  2209. function oauthService(Endpoints,
  2210. $http,
  2211. socialNetworkMapper,
  2212. socialNetworksEnum,
  2213. importMapper) {
  2214.  
  2215. var user = null;
  2216.  
  2217. return {
  2218. getImportContactsLink: function (enumValue) {
  2219. var networkName = this.getNetworkNameByEnum(enumValue);
  2220. return $http.post(Endpoints.importContactsLink, {type: networkName})
  2221. .then(
  2222. function suc(response) {
  2223. response.redirectLink = socialNetworkMapper.mapFromServer(response.data).redirectLink;
  2224. return response;
  2225. },
  2226. function err(response) {
  2227. return response;
  2228. }
  2229. );
  2230. },
  2231.  
  2232. getContactsFromSocialNetwork: function (token, networkName) {
  2233. return $http.post(Endpoints.contactsFromSocialNetwork,
  2234. {token: token, type: networkName}).then(
  2235. function suc(response) {
  2236. response.contacts = importMapper.mapArrayFromServer(response.data);
  2237. return response;
  2238. },
  2239. function err(response) {
  2240. return response;
  2241. })
  2242. },
  2243.  
  2244. getNetworkNameByEnum: function (enumValue) {
  2245. var networkName;
  2246. switch (enumValue) {
  2247. case socialNetworksEnum.google:
  2248. networkName = 'google';
  2249. break;
  2250.  
  2251. case socialNetworksEnum.yahoo:
  2252. networkName = 'yahoo';
  2253. break;
  2254.  
  2255. case socialNetworksEnum.microsoft:
  2256. networkName = 'microsoft';
  2257. break;
  2258. }
  2259.  
  2260. return networkName;
  2261. }
  2262. };
  2263. }
  2264.  
  2265. })();
  2266.  
  2267. (function () {
  2268. 'use strict';
  2269.  
  2270. angular
  2271. .module('loginApp')
  2272. .factory('paymentSimulatorService', paymentSimulatorService);
  2273.  
  2274. paymentSimulatorService.$inject = [];
  2275.  
  2276. function paymentSimulatorService() {
  2277.  
  2278. return {
  2279. getMinimumPayment: function (amount, months, interest) {
  2280. // R = P × r / [1 - (1 + r)-n]
  2281. return (amount * ((interest / 100) / 12)) / (1 - (Math.pow((1 + ((interest / 100) / 12)), -months)));
  2282. },
  2283.  
  2284. getPaymentPeriod: function (amount, minimumAmountDue, interest) {
  2285. // n = log[x / (x – P × r)] / log (1 + r)
  2286. return Math.log(minimumAmountDue / (minimumAmountDue - amount * (interest / 100) / 12)) / Math.log(1 + (interest / 100) / 12);
  2287. }
  2288. };
  2289. }
  2290.  
  2291. })();
  2292.  
  2293. (function () {
  2294. 'use strict';
  2295.  
  2296. angular
  2297. .module('loginApp')
  2298. .factory('scrollService', scrollService);
  2299.  
  2300. scrollService.$inject = [
  2301. '$timeout'
  2302. ];
  2303.  
  2304. function scrollService($timeout) {
  2305.  
  2306. return {
  2307. scrollTo: function (selector) {
  2308. var target = $(selector),
  2309. page = $("body, html");
  2310.  
  2311. page.on("scroll mousedown wheel DOMMouseScroll mousewheel keyup touchmove", function () {
  2312. page.stop();
  2313. });
  2314.  
  2315. page.animate({scrollTop: target.offset().top}, "normal", function () {
  2316. page.off("scroll mousedown wheel DOMMouseScroll mousewheel keyup touchmove");
  2317. });
  2318. }
  2319. };
  2320. }
  2321.  
  2322. })();
  2323.  
  2324. (function () {
  2325. 'use strict';
  2326.  
  2327. angular
  2328. .module('loginApp')
  2329. .factory('socialService', socialService);
  2330.  
  2331. socialService.$inject = [
  2332. '$location',
  2333. 'appConstants',
  2334. 'Socialshare'
  2335. ];
  2336.  
  2337. function socialService($location, appConstants, Socialshare) {
  2338.  
  2339. function concatenateDomainAndPath(passedPath) {
  2340. var baseSiteUrl = $location.protocol() + '://' + $location.host() + '/#',
  2341. path = passedPath || location.path();
  2342.  
  2343. return baseSiteUrl + path;
  2344. }
  2345.  
  2346. function getGiftProfileUrlById(id) {
  2347. return concatenateDomainAndPath('/gift/' + id);
  2348. }
  2349.  
  2350. return {
  2351. shareProfileAtFacebook: function (vm, text) {
  2352. var id = vm.profile.userId,
  2353. story = vm.profile.story,
  2354. media = $location.protocol() + ':' + vm.profile.photoLink,
  2355. description = story || text || 'Profile — ' + vm.profile.getFullName();
  2356.  
  2357. Socialshare.share({
  2358. provider: 'facebook',
  2359. attrs: {
  2360. socialshareType: 'share',
  2361. socialshareVia: appConstants.FACEBOOK_APP_ID,
  2362. socialshareUrl: getGiftProfileUrlById(id),
  2363. socialshareDescription: description,
  2364. socialshareTitle: 'A better, faster way to pay off your student loans',
  2365. socialshareMedia: media
  2366. }
  2367. });
  2368. },
  2369.  
  2370. shareProfileAtTwitter: function (vm, text) {
  2371. var id = vm.profile.userId,
  2372. story = vm.profile.story || text || 'LoanGifting Profile — ' + vm.profile.getFullName();
  2373.  
  2374. Socialshare.share({
  2375. provider: 'twitter',
  2376. attrs: {
  2377. socialshareUrl: getGiftProfileUrlById(id),
  2378. socialshareText: story
  2379. }
  2380. });
  2381. },
  2382.  
  2383. shareProfileAtGoogle: function (vm) {
  2384. var id = vm.profile.userId;
  2385. Socialshare.share({
  2386. provider: 'google',
  2387. attrs: {
  2388. socialshareUrl: getGiftProfileUrlById(id)
  2389. }
  2390. });
  2391. },
  2392.  
  2393. shareProfileAtLinkedIn: function (vm, text) {
  2394. var id = vm.profile.userId,
  2395. story = vm.profile.story || text || 'LoanGifting Profile — ' + vm.profile.getFullName();
  2396. Socialshare.share({
  2397. provider: 'linkedin',
  2398. attrs: {
  2399. socialshareUrl: getGiftProfileUrlById(id),
  2400. socialshareText: "A better, faster way to pay off your student loans. " + story
  2401. }
  2402. });
  2403. }
  2404. };
  2405. }
  2406.  
  2407. })();
  2408.  
  2409. (function () {
  2410. 'use strict';
  2411.  
  2412. angular
  2413. .module('loginApp')
  2414. .factory('spinnerService', spinnerService);
  2415.  
  2416. spinnerService.$inject = [
  2417. '$timeout'
  2418. ];
  2419.  
  2420. function spinnerService($timeout) {
  2421.  
  2422. var timeoutId = null;
  2423.  
  2424. return {
  2425. show: function () {
  2426. if (timeoutId) {
  2427. clearTimeout(timeoutId);
  2428. }
  2429. angular
  2430. .element(document.querySelector('#XHRFixedWrapper'))
  2431. .css('display', 'block');
  2432. },
  2433. hide: function () {
  2434. timeoutId = setTimeout(function () {
  2435. angular
  2436. .element(document.querySelector('#XHRFixedWrapper'))
  2437. .css('display', 'none');
  2438. }, 100);
  2439. }
  2440. };
  2441. }
  2442.  
  2443. })();
  2444.  
  2445. (function () {
  2446. 'use strict';
  2447.  
  2448. angular
  2449. .module('loginApp')
  2450. .factory('userService', userService);
  2451.  
  2452. userService.$inject = [
  2453. 'userMapper',
  2454. 'Endpoints',
  2455. '$http',
  2456. '$q'
  2457. ];
  2458.  
  2459. function userService(userMapper,
  2460. Endpoints,
  2461. $http) {
  2462.  
  2463. var user = null;
  2464.  
  2465. return {
  2466. fetchUser: function () {
  2467. return $http.get(Endpoints.profileInfo)
  2468. .then(function (response) {
  2469. user = userMapper.mapFromServer(response.data);
  2470. return user;
  2471. }).catch(function (error) {
  2472. return error;
  2473. });
  2474. },
  2475.  
  2476. getUser: function () {
  2477. return user;
  2478. },
  2479.  
  2480. setUser: function (u) {
  2481. user = u;
  2482. },
  2483.  
  2484. setProperty: function (field, value) {
  2485. if (user) {
  2486. user[field] = value;
  2487. }
  2488. },
  2489.  
  2490. getProperty: function (field) {
  2491. var result;
  2492. if (user) {
  2493. result = user[field];
  2494. }else {
  2495. result = null;
  2496. }
  2497. return result;
  2498. },
  2499.  
  2500. isAdmin: function () {
  2501. return $http.get(Endpoints.isAdmin)
  2502. .then(function (response) {
  2503. return response;
  2504. },
  2505. function (response) {
  2506. return response;
  2507. });
  2508. },
  2509.  
  2510. unsetUser: function () {
  2511. user = null;
  2512. }
  2513. };
  2514. }
  2515.  
  2516. })();
  2517.  
  2518. (function () {
  2519. 'use strict';
  2520.  
  2521. angular
  2522. .module("loginApp")
  2523. .factory('userMapper', userMapper);
  2524.  
  2525. userMapper.$inject = ['BaseMapper'];
  2526.  
  2527. function userMapper(BaseMapper) {
  2528.  
  2529. UserMapper.prototype = BaseMapper.prototype;
  2530.  
  2531. function UserMapper() {
  2532. this.mapFromServer = mapFromServer;
  2533. this.mapToServer = mapToServer;
  2534.  
  2535. function mapFromServer(data) {
  2536. var attributes = this.baseMapFromServer(data);
  2537. return {
  2538. userId: attributes.user_id,
  2539. firstName: attributes.first_name,
  2540. lastName: attributes.last_name,
  2541. name: attributes.name,
  2542. story: attributes.story,
  2543. token: attributes.token,
  2544. gender: +attributes.gender,
  2545. videoLink: attributes.video,
  2546. photoLink: attributes.photo,
  2547. isHasPassword: attributes.has_password,
  2548. isHasQuestions: attributes.has_questions,
  2549. isHasLoans: attributes.has_loans,
  2550. months: attributes.months,
  2551. birthday: attributes.birthday,
  2552. country: attributes.country,
  2553. state: attributes.state,
  2554. zip: attributes.zip,
  2555. city: attributes.city,
  2556. phone: attributes.phone,
  2557. email: attributes.email
  2558.  
  2559. }
  2560. }
  2561.  
  2562. function mapToServer(UserModel) {
  2563. return {
  2564. first_name: UserModel.firstName,
  2565. last_name: UserModel.lastName,
  2566. birthday: UserModel.concatenateBirthday(),
  2567. gender: UserModel.gender,
  2568. story: UserModel.story,
  2569. country: UserModel.country,
  2570. state: UserModel.state,
  2571. phone: UserModel.phone,
  2572. zip: UserModel.zip
  2573. };
  2574. }
  2575. }
  2576.  
  2577. return new UserMapper();
  2578. }
  2579. })();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement