Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (function () {
- 'use strict';
- angular.module('loginApp', [
- // application dependencies
- 'ngRoute',
- 'ngAnimate',
- 'ui.bootstrap',
- 'ui.select',
- 'angularModalService',
- 'vcRecaptcha',
- 'app.env'
- ]).run(initialize);
- initialize.$inject = [
- '$rootScope',
- '$location',
- '$window'
- ];
- function initialize($rootScope,
- $location,
- $window) {
- }
- })();
- (function () {
- 'use strict';
- angular
- .module('loginApp')
- .config(config);
- function config($routeProvider, $httpProvider) {
- $httpProvider.defaults.useXDomain = true;
- delete $httpProvider.defaults.headers.common['X-Requested-With'];
- $routeProvider
- .when('/login', {
- templateUrl: 'app/login/login.html',
- controller: 'LoginController',
- controllerAs: 'vm'
- })
- .otherwise({
- redirectTo: '/login'
- });
- $httpProvider.interceptors.push('authInterceptor');
- }
- }());
- (function () {
- 'use strict';
- //Activate password
- angular.module('loginApp').controller('ActivateCtl',
- function ($scope, $location, $window, Activation, Messages, User, authService) {
- var token = $location.search().token,
- q = $location.search().q,
- nu = $location.search().nu,
- sn = $location.search().sn;
- if (!token) {
- Messages.setMessage({
- header: "Invalid Token",
- text: "Token is empty. Please check your link or contact support"
- });
- Messages.sendMessage();
- return;
- }
- if (!sn) {
- Activation.postActivateToken({"token": token}, function (data) {
- if (data.status == 204) {
- if (nu == 1) pixelCompleteRegistration();
- $location.path('/password').search({token: token, q: q});
- //if need to show questions form forward parameter q=1
- } else if (data.status == 404) {
- Messages.setMessage({
- header: "Your session has expired",
- 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."
- });
- Messages.sendMessage();
- } else {
- Messages.setMessage({
- header: "Internal sever error",
- text: "Please try again later. If you have the problem again please contact support."
- });
- Messages.sendMessage();
- }
- });
- } else if (sn) {
- Activation.postActivateToken({"token": token, "token_type": sn}, function (data) {
- if (data.status == 204) {
- if (nu == 1) pixelCompleteRegistration();
- $window.localStorage.access_token = token;
- authService.setToken(token);
- User.getUserInfo(token).then(function (mapped) {
- Messages.setMessage({
- header: "Welcome " + mapped.name,
- text: "You have been successfully logged."
- });
- Messages.sendMessage();
- });
- } else {
- Messages.sendError(data);
- }
- });
- }
- function pixelCompleteRegistration() {
- fbq('track', 'CompleteRegistration');
- }
- });
- // Enter new password
- angular.module('loginApp').controller('PasswordCtl',
- function ($location, ModalService, authService) {
- var token = $location.search().token;
- activate();
- function activate() {
- if (authService.isLoggedIn()) {
- $location.path('/profile');
- $location.url($location.path()); // clear query string
- } else {
- showPasswordPopup();
- }
- }
- function showPasswordPopup() {
- ModalService.showModal({
- templateUrl: "views/modal-set-password.html",
- controller: "SetPasswordController",
- controllerAs: "vm",
- inputs: {
- params: {
- token: token
- }
- }
- }).then(function (modal) {
- modal.element.modal({
- backdrop: 'static', // if you want prevent close modal
- keyboard: false
- });
- // after show modal actions here...
- });
- }
- });
- }());
- 'use strict';
- //Login
- angular.module('loginApp').factory("Login", function ($http,
- userService,
- userMapper,
- errorsMapper) {
- var serviceBase = '/rest/user/login',
- obj = {};
- //Send login and password to backend
- obj.postLoginForm = function (login, callbackStatus) {
- $http.post(serviceBase, {email: login.email, password: login.password})
- .then(function successCallback(response) {
- var user = response.user = userMapper.mapFromServer(response.data);
- userService.setUser(user);
- callbackStatus(response);
- }, function errorCallback(response) {
- response.errors = errorsMapper.mapArrayFromServer(response);
- callbackStatus(response);
- });
- };
- return obj;
- });
- // User methods
- angular.module('loginApp').factory("User", function ($http, userMapper, userService, Endpoints, apiService) {
- var currentUser;
- return {
- /**
- * Returns User Information (name, surname, image and etc)
- * @param {string} token
- * @returns {promise}
- */
- getUserInfo: function (token) {
- return $http({
- url: apiService.wrap(Endpoints.profileInfo),
- method: "GET",
- params: {"token": token}
- }).then(function (response) {
- currentUser = userMapper.mapFromServer(response.data);
- userService.setUser(currentUser);
- return currentUser;
- });
- },
- refreshToken: function () {
- return $http.post(apiService.wrap(Endpoints.refreshToken), {})
- .then(
- function (response) {
- return response;
- },
- function (response) {
- return response;
- }
- );
- },
- currentUser: function () {
- return currentUser;
- }
- };
- });
- //SignUp
- angular.module('loginApp').factory("SignUp", function ($http, Endpoints, apiService) {
- return {
- postSignUpForm: function (signup, recaptchaResponse, callbackStatus) {
- $http.post(apiService.wrap(Endpoints.signUp), {
- 'first_name': signup.first_name,
- 'last_name': signup.last_name,
- 'email': signup.email,
- 'password': signup.password,
- 'g-recaptcha-response': recaptchaResponse
- }).then(function successCallback(response) {
- callbackStatus(response);
- }, function errorCallback(response) {
- callbackStatus(response);
- });
- },
- postForgot: function (email, callbackStatus) {
- $http.post(apiService.wrap(Endpoints.resetPassword), {email: email})
- .then(function successCallback(response) {
- callbackStatus(response);
- }, function errorCallback(response) {
- callbackStatus(response);
- });
- },
- checkEmailExists: function (email) {
- return $http.post(apiService.wrap(Endpoints.userExists), {email: email}).then(function successCallback(response) {
- return response;
- }, function errorCallback(response) {
- return response;
- });
- }
- };
- });
- //Secret questions
- angular.module('loginApp').factory("Questions", function ($http, apiService) {
- return {
- getQuestions: function (callbackStatus) {
- $http.post(apiService.wrap('/rest/user/questions-list'))
- .then(function successCallback(response) {
- callbackStatus(response);
- }, function errorCallback(response) {
- callbackStatus(response);
- });
- },
- postQuestionsForm: function (answers, callbackStatus) {
- $http.post(apiService.wrap('/rest/user/save-answers'), {
- 'answers': answers
- }).then(function successCallback(response) {
- callbackStatus(response);
- }, function errorCallback(response) {
- callbackStatus(response);
- });
- }
- };
- });
- //Authorization
- angular.module('loginApp').factory('authInterceptor', function ($q, $window, $location, authService, HttpStatuses) {
- return {
- request: function (config) {
- if (authService.isLoggedIn()) {
- //HttpBearerAuth
- config.headers.Authorization = 'Bearer ' + authService.getToken();
- }
- return config;
- },
- responseError: function (rejection) {
- if (rejection.status === HttpStatuses.AUTH_FAILED) {
- authService.logout();
- //$location.path('/index').replace();
- }
- return $q.reject(rejection);
- }
- };
- });
- //Activation password
- angular.module('loginApp').factory("Activation", function ($http, apiService) {
- var obj = {};
- //Send token for activation
- obj.postActivateToken = function (params, callbackStatus) {
- $http.post(apiService.wrap('/rest/user/authorization-link'), params)
- .then(function successCallback(response) {
- callbackStatus(response);
- }, function errorCallback(response) {
- callbackStatus(response);
- });
- };
- return obj;
- });
- //Set new password
- angular.module('loginApp').factory("Password", function ($http, apiService) {
- return {
- //Send new password
- postPasswords: function (passwd, callbackStatus) {
- $http.post(apiService.wrap('/rest/user/update-password'), {
- token: passwd.token,
- password: passwd.password,
- password_again: passwd.password_again
- })
- .then(function successCallback(response) {
- callbackStatus(response);
- }, function errorCallback(response) {
- callbackStatus(response);
- });
- }
- }
- });
- /**
- * Social Network service for link fetching
- */
- angular.module('loginApp').factory("SocialNetwork", function ($http, socialNetworkMapper, apiService) {
- return {
- /**
- * Get social network oAuth2 link
- * @param {string} type
- * @returns {promise}
- */
- getNetworkPath: function (type) {
- return $http.post(
- apiService.wrap('/rest/oauth/get-link'),
- $.param({type:type}),
- {
- headers: {
- 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
- }
- }
- ).then(function (response) {
- return socialNetworkMapper.mapFromServer(response.data);
- });
- }
- };
- });
- angular.module('loginApp').factory("Geo", function ($http, Endpoints, apiService) {
- return {
- statesList: function () {
- return $http.get(apiService.wrap(Endpoints.statesList)).then(function (response) {
- return response.data;
- });
- }
- };
- });
- // Profile methods
- angular.module('loginApp').factory("Profile", function (apiService, $http, Endpoints, $rootScope, userMapper, resourceMapper, educationMapper, employmentsMapper, userActivityMapper) {
- var userInfoPath = apiService.wrap(Endpoints.profileInfo),
- educationInfoPath = apiService.wrap(Endpoints.profileEducation),
- employmentsInfoPath = apiService.wrap(Endpoints.profileEmployments),
- passwordInfoPath = apiService.wrap("/rest/profile/password"),
- self = this;
- return {
- /**
- * Returns Profile Information (name, surname, image and etc)
- * @returns {promise}
- */
- getProfileInfo: function () {
- return $http.get(userInfoPath).then(function (response) {
- return userMapper.mapFromServer(response.data);
- });
- },
- /**
- * Update Profile Information (name, surname, image and etc)
- * @param {object} profile
- * @returns {promise}
- */
- updateProfileInfo: function (profile) {
- profile = userMapper.mapToServer(profile);
- return $http.post(userInfoPath, profile).then(function (response) {
- return response;
- },
- function (response) {
- return response;
- }
- );
- },
- /**
- * Returns Information about Education
- * @params
- * @returns {promise}
- */
- getEducationInfo: function () {
- return $http.get(apiService.wrap(Endpoints.profileEducation))
- .then(
- function (response) {
- response.educationList = educationMapper.mapArrayFromServer(response.data);
- return response;
- },
- function (response) {
- return response;
- }
- );
- },
- /**
- * Returns Information about User Recent Activity
- * @params
- * @returns {promise}
- */
- getUserActivity: function () {
- return $http.get(apiService.wrap(Endpoints.userActivity))
- .then(
- function (response) {
- response.userActivity = userActivityMapper.mapArrayFromServer(response.data);
- return response;
- },
- function (response) {
- return response;
- }
- );
- },
- /**
- * Get Employments collection
- * @returns {promise}
- */
- getEmploymentsInfo: function () {
- return $http.get(apiService.wrap(Endpoints.profileEmployments))
- .then(
- function (response) {
- response.employmentsList = employmentsMapper.mapArrayFromServer(response.data);
- return response;
- },
- function (response) {
- return response;
- }
- );
- },
- insertEducationInfo: function (education) {
- return $http.put(educationInfoPath, educationMapper.mapToServer(education)).then(
- function (response) {
- // success callback
- return response;
- },
- function (response) {
- // failure callback
- return response;
- }
- );
- },
- deleteEducationInfo: function (education_id) {
- return $http.delete(educationInfoPath, {params: {education_id: education_id}})
- .then(
- function (response) {
- // success callback
- return response;
- },
- function (response) {
- // failure callback
- return response;
- }
- );
- },
- insertEmploymentsInfo: function (employments) {
- return $http.put(employmentsInfoPath, employmentsMapper.mapToServer(employments))
- .then(
- function (response) {
- // success callback
- return response;
- },
- function (response) {
- // failure callback
- return response;
- }
- );
- },
- updateEmploymentsInfo: function (employments) {
- return $http.post(employmentsInfoPath, employmentsMapper.mapToServer(employments))
- .then(
- function (response) {
- // success callback
- return response;
- },
- function (response) {
- // failure callback
- return response;
- }
- );
- },
- updateEducationInfo: function (education) {
- return $http.post(educationInfoPath, educationMapper.mapToServer(education))
- .then(
- function (response) {
- // success callback
- return response;
- },
- function (response) {
- // failure callback
- return response;
- }
- );
- },
- deleteEmploymentsInfo: function (employment_id) {
- return $http.delete(employmentsInfoPath, {params: {employment_id: employment_id}})
- .then(
- function (response) {
- // success callback
- return response;
- },
- function (response) {
- // failure callback
- return response;
- }
- );
- },
- changePassword: function (password) {//deprecated method
- return $http.post(passwordInfoPath, {
- current_password: password.current_password,
- new_password: password.new_password,
- confirm_password: password.confirm_password
- })
- .then(
- function (response) {
- // success callback
- return response;
- },
- function (response) {
- // failure callback
- return response;
- }
- );
- },
- /**
- * Save photo
- * @param {object} fileReader
- * @returns {promise}
- */
- sendPhotoFile: function (fileReader) {
- var Profile = this;
- fileReader.append('type', 'photo');
- return $http
- .post(
- apiService.wrap(Endpoints.profileFile),
- fileReader, {
- transformRequest: angular.identity,
- headers: {
- 'Content-Type': undefined
- }
- }
- )
- .success(function (response) {
- var resource = resourceMapper.mapFromServer(response);
- Profile.sendPhotoLink(resource.link);
- return resource;
- })
- .error(function (response) {
- return response;
- }).then(function (response) {
- // only if transform request
- return resourceMapper.mapFromServer(response.data);
- });
- },
- sendVideoFile: function (fileReader) {
- var Profile = this;
- fileReader.append('type', 'video');
- return $http
- .post(
- apiService.wrap(Endpoints.profileFile),
- fileReader, {
- transformRequest: angular.identity,
- headers: {
- 'Content-Type': undefined
- }
- }
- )
- .success(function (response) {
- var resource = resourceMapper.mapFromServer(response);
- Profile.sendVideoLink(resource.link);
- return response;
- })
- .error(function (response) {
- return response;
- })
- .then(function (response) {
- // only if transform request
- return response;
- });
- },
- sendVideoLink: function (link) {
- return $http.post(apiService.wrap(Endpoints.profileResourceLink), {
- video: link
- }).then(
- function (response) {
- return response;
- },
- function (response) {
- return response;
- }
- );
- },
- sendPhotoLink: function (link) {
- return $http.post(apiService.wrap(Endpoints.profileResourceLink), {
- photo: link
- }).then(
- function (response) {
- // success callback
- return response;
- },
- function (response) {
- // failure callback
- return response;
- }
- );
- }
- };
- });
- (function () {
- 'use strict';
- angular
- .module('loginApp')
- .controller('LoginController', LoginController);
- LoginController.$inject = [
- '$scope',
- '$window',
- '$location',
- 'Messages',
- 'HttpStatuses',
- 'SocialNetwork',
- 'SignUp',
- 'appConstants',
- 'spinnerService',
- 'Login'
- ];
- function LoginController($scope,
- $window,
- $location,
- Messages,
- HttpStatuses,
- SocialNetwork,
- SignUp,
- appConstants,
- spinnerService,
- Login) {
- var vm = this;
- var event = {};
- $scope.forgot = {};
- $scope.signUp = {};
- $scope.login = {};
- $scope.emailSentView = false;
- $scope.forgotPasswordView = false;
- // methods
- vm.closeModal = closeModal;
- vm.redirectToExternalService = redirectToExternalService;
- vm.postForgot = postForgot;
- vm.checkForgottenEmail = checkForgottenEmail;
- vm.checkEmail = checkEmail;
- vm.showForgotPassword = showForgotPassword;
- vm.postLogin = postLogin;
- activate();
- function activate() {
- // constructor
- }
- function closeModal(result, $event) {
- $event && $event.preventDefault();
- $element.modal('hide');
- close(result, 500);
- }
- //Redirect to social network oAuth
- function redirectToExternalService(type) {
- SocialNetwork.getNetworkPath(type).then(function (data) {
- $window.location = data.redirectLink;
- });
- }
- //post Forgot Password
- function postForgot() {
- SignUp.postForgot($scope.forgot.email, function (data) {
- if (data.status === HttpStatuses.OK_WITHOUT_DATA) {
- $scope.emailSentView = true;
- $scope.forgotPasswordView = false;
- } else {
- Messages.setHeader("Error");
- Messages.setText("We could not find your email address. Please try again.");
- Messages.sendMessage();
- }
- });
- }
- //Check email exists
- function checkForgottenEmail() {
- var email;
- if (!$scope.forgotForm.email.$invalid) {
- email = $scope.forgot.email;
- $scope.emailExistsStatus = SignUp.checkEmailExists(email).then(function (response) {
- if (response.status === HttpStatuses.OK_WITHOUT_DATA) {
- $scope.forgot.emailStatus = "";
- $scope.forgot.emailWrong = "";
- vm.postForgot();
- } else if (response.status >= HttpStatuses.BAD_REQUEST ||
- response.status < HttpStatuses.APPLICATION_ERROR) {
- Messages.sendError(response);
- } else {
- Messages.setHeader("Error");
- Messages.setText("Internal Service Error");
- Messages.sendMessage();
- }
- });
- }
- }
- function showForgotPassword($event) {
- $scope.signUp.emailStatus = '';
- $event.preventDefault();
- $scope.forgotPasswordView = true;
- $scope.forgot.email = '';
- console.log(1);
- }
- //Check email exists
- function checkEmail() {
- var email = $scope.signUp.email;
- return SignUp.checkEmailExists(email).then(function (response) {
- var status = response.status;
- if (status === HttpStatuses.OK_WITHOUT_DATA) {
- $scope.signUp.emailStatus = "Email was registered earlier. Forgot the password?";
- $scope.signUp.emailWrong = "";
- } else if (status === HttpStatuses.VALIDATION_FAILED) {
- $scope.signUp.emailWrong = "Wrong email format.";
- $scope.signUp.emailStatus = "";
- } else {
- $scope.signUp.emailStatus = "";
- $scope.signUp.emailWrong = "";
- }
- return response;
- });
- }
- $scope.testEmail = function () {
- return appConstants.EMAIL_REGEX.test($scope.signUp.email);
- };
- $scope.showSignUpForm = function ($event) {
- $event.preventDefault();
- $scope.signUp.first_name = '';
- $scope.signUp.last_name = '';
- $scope.signUp.email = '';
- $scope.emailSentView = false;
- $scope.forgotPasswordView = false;
- };
- //Send credentials
- function postLogin() {
- spinnerService.show();
- Login.postLoginForm($scope.login, function (response) {
- var user;
- if (response.status === HttpStatuses.OK) {
- user = UserModel.build(response.user);
- $window.localStorage.setItem('access_token', user.token);
- Messages.setHeader("Welcome " + user.name);
- Messages.setText("You have been successfully logged.");
- Messages.sendMessage();
- event.name = 'successLogin';
- event.params = {user: user.email};
- $location.path('/profile').replace();
- setTimeout(function () {
- $window.location.reload();
- }, 0);
- } else {
- spinnerService.hide();
- if ('errors' in response) {
- event.name = 'failedLogin';
- event.params = {error: response.data.errors[0].detail};
- Messages.sendError(response);
- }
- }
- });
- }
- }
- }());
- (function () {
- "use strict";
- angular
- .module("loginApp")
- .constant("appConstants", {
- "DEFAULT_AVATAR": "common/images/app/default-avatar.jpg",
- "SEARCH_INPUT_TIMEOUT": 700,
- "PER_PAGE_DEFAULT": 10,
- "PER_PAGE_NOTIFICATIONS_DEFAULT": 6,
- "PER_PAGE_REQUESTS_DEFAULT": 6,
- "SRC_REGEX": 'src\=\"([A-Za-z0-9\S_\\/\/:.-]*)\"',
- "EMAIL_REGEX": /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/,
- "G_RECAPTCHA_KEY": '6LeiFiMTAAAAAPVl1d54uz8c7RxjWYYoyBTYr3hN',
- "PROLONG_TOKEN_INTERVAL": 120000,
- "SEEK_NOTIFICATIONS_INTERVAL": 20000,
- "FACEBOOK_APP_ID": '1731517977115865',
- "SHARING_LOGO_URL": 'https://loangifting.com/common/images/v2/lg-red-small-logo.png',
- "BASE_SITE_URL": "https://loans.gifts"
- });
- }());
- (function () {
- "use strict";
- angular
- .module("loginApp")
- .constant("colorsConstants", {
- "red": "#FF0000",
- "darked": "#8B0000",
- "tomato": "#FF6347",
- "crimson": "#DC143C",
- "firebrick": "#B22222",
- "lightcoral": "#F08080",
- "gray": "#F1F1F1"
- });
- }());
- (function () {
- "use strict";
- angular
- .module("loginApp")
- .constant("Endpoints", {
- // Authentication endpoints
- "login": "/rest/user/login",
- "refreshToken": "/rest/user/token-extend",
- "userExists": "/rest/user/exist",
- "signUp": "/rest/user/signup",
- "resetPassword": "/rest/user/reset-password",
- // profile endpoints
- "profileInfo": "/rest/profile/info",
- "accountInfo": "/rest/profile/account-info",
- "isAdmin": "/rest/profile/is-admin",
- "profileEducation": "/rest/profile/education",
- "profileEmployments": "/rest/profile/employments",
- "profileFile": "/rest/profile/file",
- "profileResourceLink": "/rest/profile/resource-link",
- "statesList": "data/states-hash.json", // temporary json-hash solution
- "passwordInfoPath": "/rest/profile/password",
- "deleteAccount": "/rest/profile/account",
- "privacySettings": "/rest/privacy/settings",
- "userActivity": "/rest/information/user-recent-activity",
- // payment
- "acceptPayment": "/rest/payments/accept", // post
- "payPalLink": "/rest/payments/pay-pal-payment-link", // get
- //gifting
- "giftingHistory": "/rest/gifts/history",
- "giftTemplates": "data/gifting/gift-templates.json",
- "backgrounds": "data/gifting/backgrounds.json",
- //thank
- "thankTemplates": "data/thank/thank-templates.json",
- "thankBackgrounds": "data/thank/thank-backgrounds.json",
- //support
- "supportMessage": "/rest/information/support",
- //subscribe
- "subscribe": "/rest/information/subscription",
- //Static pages
- "aboutUS": "data/about-us.json",
- //oauth
- importContactsLink: "/rest/oauth/get-import-contacts-link",
- contactsFromSocialNetwork: "/rest/oauth/get-contacts"
- });
- }());
- (function () {
- "use strict";
- angular
- .module("loginApp")
- .constant("HttpStatuses", {
- OK: 200,
- OK_CREATED: 201,
- OK_WITHOUT_DATA: 204,
- NOT_MODIFIED: 304,
- BAD_REQUEST: 400,
- AUTH_FAILED: 401,
- HAVE_NOT_ACCESS: 403,
- NOT_FOUND: 404,
- NOT_ALLOWED: 405,
- INVALID_CONTENT_TYPE: 415,
- VALIDATION_FAILED: 422,
- TOO_MANY_REQUEST: 429,
- APPLICATION_ERROR: 500,
- okCodes: [
- 200,
- 201,
- 204
- ]
- });
- }());
- // jscs: disable
- /**
- * disable code style for external code methods only
- */
- (function () {
- "use strict";
- angular
- .module("loginApp")
- .factory("BaseHelper", BaseHelper);
- function BaseHelper() {
- return {
- /**
- * Creates and returns a blob from a data URL (either base64 encoded or not).
- *
- * @param {string} dataURL The data URL to convert.
- * @return {Blob} A blob representing the array buffer data.
- */
- dataURLToBlob: function (dataURL) {
- var BASE64_MARKER = ';base64,';
- if (dataURL.indexOf(BASE64_MARKER) == -1) {
- var parts = dataURL.split(',');
- var contentType = parts[0].split(':')[1];
- var raw = decodeURIComponent(parts[1]);
- return new Blob([raw], {type: contentType});
- }
- var parts = dataURL.split(BASE64_MARKER);
- var contentType = parts[0].split(':')[1];
- var raw = window.atob(parts[1]);
- var rawLength = raw.length;
- var uInt8Array = new Uint8Array(rawLength);
- for (var i = 0; i < rawLength; ++i) {
- uInt8Array[i] = raw.charCodeAt(i);
- }
- return new Blob([uInt8Array], {type: contentType});
- }
- };
- }
- })();
- (function () {
- "use strict";
- angular
- .module("loginApp")
- .factory("cacheHelper", cacheHelper);
- cacheHelper.$inject = [
- '$window',
- '$q',
- '$http'
- ];
- function cacheHelper($window,
- $q,
- $http) {
- return {
- /**
- * Cache data from request
- * @param {string} restUrl
- * @param {string} namespace
- * @param {object|boolean} params
- * @param {boolean} reCache - drop cache and reload data
- * @returns {Promise}
- */
- getFromStorage: function (restUrl, namespace, params, reCache) {
- if (params) {
- params = {params: params};
- }
- if (!$window.localStorage[namespace]) {
- return $http.get(restUrl, params).then(function (response) {
- $window.localStorage[namespace] = JSON.stringify(response.data);
- return JSON.parse($window.localStorage[namespace]);
- });
- } else {
- return $q(function (resolve) {
- return resolve(JSON.parse($window.localStorage[namespace]));
- });
- }
- },
- /**
- * Delete storing data from localStorage by key
- * @param {string} namespace
- * @returns {boolean}
- */
- unsetStorageByKey: function (namespace) {
- return delete $window.localStorage[namespace];
- }
- };
- }
- })();
- (function () {
- "use strict";
- angular
- .module("loginApp")
- .factory("DebounceHelper", DebounceHelper);
- function DebounceHelper() {
- return {
- getWrapper: function (f, ms) {
- var state = null,
- COOLDOWN = 1;
- return function () {
- if (state) {
- return;
- }
- f.apply(this, arguments);
- state = COOLDOWN;
- setTimeout(function () {
- state = null
- }, ms);
- }
- }
- };
- }
- })();
- (function () {
- "use strict";
- angular
- .module("loginApp")
- .factory("fakeRequestHelper", fakeRequestHelper);
- fakeRequestHelper.$inject = [
- '$timeout',
- '$q',
- '$rootScope'
- ];
- function fakeRequestHelper($timeout, $q, $rootScope) {
- return {
- // with spinner
- backendSimulator: function (data, delay) {
- $timeout(function () {
- $rootScope.spinner.show();
- });
- return $q(function (resolve) {
- return setTimeout(function () {
- $rootScope.spinner.hide();
- return resolve(data);
- }, delay || 1000);
- });
- },
- // simple promise simulation
- getPromise: function (data, delay) {
- var deferred = $q.defer();
- $timeout(function () {
- deferred.resolve(data);
- }, delay || 1000);
- return deferred.promise;
- }
- };
- }
- })();
- (function () {
- 'use strict';
- angular
- .module('loginApp')
- .factory('focusInput', function ($timeout, $window) {
- return function (el) {
- // timeout makes sure that it is invoked after any other event has been triggered.
- // e.g. click events that need to run before the focus or
- // inputs elements that are in a disabled state but are enabled when those events
- // are triggered.
- $timeout(function () {
- if (el) {
- el.find('input').focus();
- }
- });
- };
- });
- })();
- (function () {
- "use strict";
- angular
- .module("loginApp")
- .factory("randomHelper", randomHelper);
- randomHelper.$inject = [];
- function randomHelper() {
- var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
- return {
- generateCode: function (length) {
- var text = "", i;
- for (i = 0; i < length; i++) {
- text += possible.charAt(Math.floor(Math.random() * possible.length));
- }
- return text;
- }
- };
- }
- })();
- (function () {
- "use strict";
- angular
- .module("loginApp")
- .factory("ThrottleHelper", ThrottleHelper);
- function ThrottleHelper() {
- return {
- getWrapper: function (func, ms) {
- var isThrottled = false,
- savedArgs,
- savedThis;
- function wrapper() {
- if (isThrottled) {
- savedArgs = arguments;
- savedThis = this;
- return;
- }
- func.apply(this, arguments);
- isThrottled = true;
- setTimeout(function () {
- isThrottled = false;
- if (savedArgs) {
- wrapper.apply(savedThis, savedArgs);
- savedArgs = savedThis = null;
- }
- }, ms);
- }
- return wrapper;
- }
- };
- }
- })();
- (function () {
- 'use strict';
- angular
- .module("loginApp")
- .factory('BaseMapper', BaseMapper);
- BaseMapper.$inject = [
- 'dateService'
- ];
- function BaseMapper(dateService) {
- function Base() {}
- function attributesDateStringModifier(attributes) {
- var k;
- for (k in attributes) {
- if (attributes.hasOwnProperty(k)) {
- if (dateService.testDate(attributes[k])) {
- attributes[k] = dateService.datePatcher(attributes[k]);
- }
- }
- }
- return attributes;
- }
- Base.prototype.baseMapFromServer = function (data) {
- var mappedDataItem = null;
- if ('data' in data) {
- data = data.data;
- }
- if (data && data.length) {
- data = data[0];
- mappedDataItem = data.attributes;
- mappedDataItem = attributesDateStringModifier(mappedDataItem);
- }
- return mappedDataItem;
- };
- Base.prototype.baseMapArrayFromServer = function (data) {
- var mappedDataArray = [];
- if ('data' in data) {
- data = data.data;
- }
- if (data && data.length) {
- data.map(function (value, index) {
- mappedDataArray[index] = value.attributes;
- mappedDataArray[index] = attributesDateStringModifier(mappedDataArray[index]);
- });
- }
- return mappedDataArray;
- };
- Base.prototype.baseGetMetaInformation = function (data) {
- var metaObject = {};
- if ('meta' in data) {
- metaObject = data.meta;
- }
- return metaObject;
- };
- Base.prototype.baseMapErrorsFromServer = function (data) {
- var mappedDataArray = [];
- if ('errors' in data) {
- data = data.errors;
- }
- if (data && data.length) {
- data.map(function (value, index) {
- mappedDataArray[index] = value;
- });
- }
- return mappedDataArray;
- };
- Base.prototype.getPagination = function (data) {
- var meta = this.baseGetMetaInformation(data);
- return {
- currentCount: +meta.current_count,
- perPage: +meta.per_page,
- totalCount: +meta.total_count
- };
- };
- return Base;
- }
- })();
- (function () {
- 'use strict';
- angular
- .module("loginApp")
- .factory('errorsMapper', errorsMapper);
- errorsMapper.$inject = ['BaseMapper'];
- function errorsMapper(BaseMapper) {
- ErrorsMapper.prototype = BaseMapper.prototype;
- function ErrorsMapper() {
- this.mapArrayFromServer = mapArrayFromServer;
- function mapArrayFromServer(data) {
- var errors = this.baseMapErrorsFromServer(data);
- return errors.map(function (item) {
- return {
- detail: item.detail,
- fieldName: item.field_name
- }
- });
- }
- }
- return new ErrorsMapper();
- }
- })();
- (function () {
- 'use strict';
- angular
- .module("loginApp")
- .factory('SocialNetworkModel', SocialNetworkModel);
- SocialNetworkModel.$inject = [];
- function SocialNetworkModel() {
- function SocialNetwork() {
- this.redirectLink = '/';
- }
- return SocialNetwork;
- }
- })();
- (function () {
- 'use strict';
- angular
- .module("loginApp")
- .factory('socialNetworkMapper', socialNetworkMapper);
- socialNetworkMapper.$inject = ['BaseMapper'];
- function socialNetworkMapper(BaseMapper) {
- SocialNetworkMapper.prototype = BaseMapper.prototype;
- function SocialNetworkMapper() {
- var self = this;
- BaseMapper.apply(this);
- this.mapFromServer = mapFromServer;
- function mapFromServer(data) {
- var attributes = self.baseMapFromServer(data);
- return {
- redirectLink: attributes.link
- }
- }
- }
- return new SocialNetworkMapper();
- }
- })();
- (function () {
- "use strict";
- angular
- .module("loginApp")
- .constant("socialNetworksEnum", {
- "google": 4,
- "microsoft": 6,
- "yahoo": 7
- });
- }());
- (function () {
- 'use strict';
- angular
- .module('loginApp')
- .factory('timeService', timeService);
- timeService.$inject = [];
- function timeService() {
- return {
- timeAgo: function (date) {
- var seconds,
- interval;
- // format into locale time
- date = date - this.getMsOffset();
- seconds = Math.floor((new Date() - new Date(date)) / 1000);
- interval = Math.floor(seconds / 31536000);
- if (interval > 1) {
- return interval + " years ago";
- }
- interval = Math.floor(seconds / 2592000);
- if (interval > 1) {
- return interval + " months ago";
- }
- interval = Math.floor(seconds / 604800);
- if (interval > 1) {
- return interval + " weeks ago";
- }
- interval = Math.floor(seconds / 86400);
- if (interval > 1) {
- return interval + " days ago";
- }
- interval = Math.floor(seconds / 3600);
- if (interval > 1) {
- return interval + " hours ago";
- }
- interval = Math.floor(seconds / 60);
- if (interval > 1) {
- return interval + " minutes ago";
- }
- return Math.floor(seconds) + " seconds ago";
- },
- getMsOffset: function () {
- var minutesOffset = (new Date()).getTimezoneOffset();
- return minutesOffset * 60 * 1000 + 3600000;
- },
- isValidDate: function (date) { //Time format 'YYYY-MM-DD'
- var matches = /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/.exec(date);
- if (matches == null) {
- return false;
- }
- var y = matches[1];
- var m = matches[2];
- var d = matches[3];
- var composedDate = new Date(y, m, d);
- return composedDate.getDate() == d &&
- composedDate.getMonth() == m &&
- composedDate.getFullYear() == y;
- },
- getDaysDiffBetweenDates: function (firstDate, secondDate) {
- var date1 = new Date(firstDate),
- date2 = new Date(secondDate),
- timeDiff = date2.getTime() - date1.getTime(),
- diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
- return diffDays;
- },
- getApproximateDaysFromMonths: function (months) {
- months = +(months.toFixed(2));
- if (months < 1.03) {
- months = 0;
- }
- // approximate days per one month 30.4
- return Math.ceil(months * 30.4);
- },
- changeDateByDaysDiff: function (date, days) {
- var d = new Date(date);
- d.setDate(d.getDate() + days);
- return d;
- },
- changeDateByMonthsDiff: function (date, months) {
- var d = new Date(date);
- return d.setMonth(d.getMonth() - months);
- },
- getMonthsDiffBetweenDates: function (firstDate, secondDate) {
- var months;
- months = (secondDate.getFullYear() - firstDate.getFullYear()) * 12;
- months -= firstDate.getMonth() + 1;
- months += secondDate.getMonth();
- return months <= 0 ? 0 : months;
- }
- }
- }
- })();
- (function () {
- 'use strict';
- angular
- .module('loginApp')
- .factory('allocationService', allocationService);
- allocationService.$inject = [
- 'spinnerService',
- 'loanService'
- ];
- function allocationService(spinnerService,
- loanService) {
- return {
- distributeDeletedAllocation: function (loans, percents, loanId) {
- var length = 0;
- loans = loans.filter(function (loan) {
- if (loan.loanId !== loanId) {
- if (loan.isCorrectInformation()) {
- length += 1;
- }
- return loan;
- }
- });
- var loansLength = length,
- modulo = percents % loansLength,
- wholePartsPercents = percents - modulo,
- equalPart = wholePartsPercents / loansLength,
- i;
- // distribute equal parts
- loans = loans.map(function (loan) {
- if (loan.isCorrectInformation()) {
- loan.allocatedPercentage += equalPart;
- if (modulo) {
- loan.allocatedPercentage += modulo;
- modulo = 0; // clear modulo after sum
- }
- }
- return loan;
- });
- return loans;
- },
- saveAllocation: function (loans) {
- spinnerService.show();
- loanService.updateLoansDistribution(loans).then(function (response) {
- spinnerService.hide();
- });
- },
- /**
- * method helps to resolve loans trouble
- * with allocation on non correct loans
- * allocation
- */
- fixCollectionAllocation: function (loans) {
- var hasTrouble = false,
- filtered = [],
- badLoan;
- if (loans.length === 1) {
- return loans;
- }
- filtered = loans.filter(function (loan) {
- if (!loan.isCorrectInformation() && +loan.allocatedPercentage === 100) {
- hasTrouble = true;
- return loan;
- }
- });
- if (hasTrouble && filtered.length) {
- badLoan = filtered[0];
- loans = loans.map(function (loan) {
- if (loan.loanId === badLoan.loanId) {
- loan.allocatedPercentage = 0;
- }
- if (loan.loanId !== badLoan.loanId && hasTrouble) {
- loan.allocatedPercentage = 100;
- hasTrouble = false;
- }
- return loan;
- });
- this.saveAllocation(loans);
- }
- return loans;
- }
- };
- }
- })();
- (function () {
- 'use strict';
- angular
- .module('loginApp')
- .factory('apiService', apiService);
- apiService.$inject = [
- 'APIEndpoint'
- ];
- function apiService(APIEndpoint) {
- return {
- wrap: function (path) {
- return APIEndpoint + path;
- }
- };
- }
- })();
- (function () {
- 'use strict';
- angular
- .module('loginApp')
- .factory('authService', authService);
- authService.$inject = [
- '$window'
- ];
- function authService($window) {
- return {
- logout: function () {
- $window.localStorage.removeItem('access_token');
- $window.localStorage.removeItem('is_admin');
- },
- setToken: function (tokenString) {
- $window.localStorage.setItem('access_token', tokenString)
- },
- getToken: function () {
- return $window.localStorage.getItem('access_token');
- },
- isLoggedIn: function () {
- var token = $window.localStorage.getItem('access_token');
- return (!!token) ? token : null;
- },
- setAdmin: function () {
- $window.localStorage.setItem('is_admin', 1);
- },
- isAdmin: function () {
- var token = $window.localStorage.getItem('is_admin');
- return (!!token) ? token : null;
- }
- };
- }
- })();
- (function () {
- 'use strict';
- angular
- .module('loginApp')
- .factory('dateService', dateService);
- dateService.$inject = [];
- function dateService() {
- return {
- getDaysDiffBetweenDates: function (firstDate, secondDate) {
- var date1 = new Date(firstDate),
- date2 = new Date(secondDate),
- timeDiff = date2.getTime() - date1.getTime(),
- diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
- return diffDays;
- },
- getApproximateDaysFromMonths: function (months) {
- months = +(months.toFixed(2));
- if (months < 1.03) {
- months = 0;
- }
- // approximate days per one month 30.4
- return Math.ceil(months * 30.4);
- },
- changeDateByDaysDiff: function (date, days) {
- var d = new Date(date);
- d.setDate(d.getDate() + days);
- return d;
- },
- changeDateByMonthsDiff: function (date, months) {
- var d = new Date(date);
- return d.setMonth(d.getMonth() - months);
- },
- getMonthsDiffBetweenDates: function (firstDate, secondDate) {
- var months;
- months = (secondDate.getFullYear() - firstDate.getFullYear()) * 12;
- months -= firstDate.getMonth() + 1;
- months += secondDate.getMonth();
- return months <= 0 ? 0 : months;
- },
- getTimezoneOffset: function () {
- return +(new Date().getTimezoneOffset()) * 60000 + 3600000;
- },
- testDate: function (str) {
- var dateTimeRegexp = /\d{4}-\d{1,2}-\d{1,2}(\s\d+:\d+:\d+)?$/;
- return dateTimeRegexp.test(str);
- },
- updateToUTCString: function (dateString) {
- var date, time, dateTimeObject, parts;
- if (~dateString.indexOf(':')) {
- parts = dateString.split(" ");
- date = parts[0].split("-");
- time = parts[1].split(":");
- dateTimeObject = new Date();
- dateTimeObject.setUTCFullYear(date[0], date[1] - 1, date[2]);
- dateTimeObject.setUTCHours(time[0], time[1], time[2], 0);
- } else {
- date = dateString.split("-");
- dateTimeObject = new Date();
- dateTimeObject.setUTCFullYear(date[0], date[1] - 1, date[2]);
- dateTimeObject.setUTCHours(0, 0, 0, 0);
- }
- return dateTimeObject;
- },
- getTimeWithoutOffset: function (dateTimeObject) {
- var offset = this.getTimezoneOffset();
- return new Date(dateTimeObject.getTime() + offset);
- },
- datePatcher: function (dateString) {
- var dateTimeObject = this.updateToUTCString(dateString);
- dateTimeObject = this.getTimeWithoutOffset(dateTimeObject);
- return dateTimeObject;
- }
- };
- }
- })();
- (function () {
- 'use strict';
- angular
- .module('loginApp')
- .factory('donutChartService', donutChartService);
- donutChartService.$inject = [
- 'colorsConstants'
- ];
- function donutChartService(colorsConstants) {
- return {
- /**
- * Returns object for configuring donut-chart directive
- * @param {[Object, Object, ...]} loansCollection
- * @returns {{labels: Array, datasets: Array}}
- */
- getDataOptions: function (loansCollection) {
- var colors = [], savedColors = [], k, i,
- totalLoan = 0,
- hoverBg = '#F1F1F1',
- labels = [],
- data = [],
- balance = 0,
- remainingAmount = 0,
- backgroundColor = [],
- hoverBackgroundColor = [],
- chartData = {
- labels: [],
- datasets: []
- };
- loansCollection = loansCollection || [];
- for (k in colorsConstants) {
- colorsConstants.hasOwnProperty(k) && colors.push(colorsConstants[k]);
- }
- savedColors = angular.copy(colors);
- for (i = 0; i < loansCollection.length; i++) {
- balance = Math.ceil(+loansCollection[i].balance);
- remainingAmount = +loansCollection[i].remainingAmount;
- // skip loan for chart painting
- if (balance === 0) {
- continue;
- }
- if (colors.length === 1) {
- colors = savedColors;
- }
- labels.push(loansCollection[i].bankName);
- data.push(balance);
- backgroundColor.push(colors.shift());
- hoverBackgroundColor.push(hoverBg);
- totalLoan += Math.ceil(remainingAmount);
- }
- // last push total loan
- labels.push('loan');
- data.push(totalLoan);
- backgroundColor.push(savedColors[savedColors.length - 1]);
- hoverBackgroundColor.push(hoverBg);
- chartData.labels = labels;
- chartData.datasets.push({
- data: data,
- backgroundColor: backgroundColor,
- hoverBackgroundColor: hoverBackgroundColor
- });
- return chartData;
- },
- getTotalDataOptions: function (loansCollection) {
- var colors = [], k, i,
- totalBalance = 0,
- totalLoan = 0,
- hoverBg = '#F1F1F1',
- labels = [],
- data = [],
- backgroundColor = [],
- hoverBackgroundColor = [],
- chartData = {
- labels: [],
- datasets: []
- };
- for (k in colorsConstants) {
- colorsConstants.hasOwnProperty(k) && colors.push(colorsConstants[k]);
- }
- for (i = 0; i < loansCollection.length; i++) {
- totalBalance += Math.ceil(+loansCollection[i].balance);
- totalLoan += Math.ceil(+loansCollection[i].remainingAmount);
- }
- // first push total balance chart
- labels.push('total paid');
- data.push(totalBalance);
- backgroundColor.push(colors[0]);
- hoverBackgroundColor.push(hoverBg);
- // last push total loan
- labels.push('loan');
- data.push(totalLoan);
- backgroundColor.push(colors[colors.length - 1]);
- hoverBackgroundColor.push(hoverBg);
- chartData.labels = labels;
- chartData.datasets.push({
- data: data,
- backgroundColor: backgroundColor,
- hoverBackgroundColor: hoverBackgroundColor
- });
- return chartData;
- },
- /**
- * get percentage representation of loan completion
- * @returns {string} eq float number
- */
- getCompletePercent: function (totalOwed, totalPaid) {
- if (totalOwed > 0) {
- return Number(100 / (totalOwed / totalPaid)).toFixed(0);
- } else {
- return '0';
- }
- },
- getCompletePercentFromCollection: function (loans, trace) {
- var totalOwed = 0, totalPaid = 0;
- if (!loans || !loans.length) {
- return;
- }
- loans.forEach(function (loan) {
- totalOwed += Math.ceil(+loan.originalAmount);
- totalPaid += Math.ceil(+loan.balance);
- });
- if (!trace) {
- return this.getCompletePercent(totalOwed, totalPaid);
- } else {
- return {
- complete: this.getCompletePercent(totalOwed, totalPaid),
- paid: totalPaid,
- owed: totalOwed
- }
- }
- }
- };
- }
- })();
- (function (angular) {
- 'use strict';
- angular
- .module('loginApp')
- .factory('EventsService', EventsService);
- EventsService.$inject = [
- '$rootScope'
- ];
- function EventsService($rootScope) {
- return {
- sendPixelEvent: function (event) {
- fbq('track', event.name, event.params);
- },
- sendCustomPixelEvent: function (event) {
- fbq('trackCustom', event.name, event.params);
- },
- sendIntercomEvent: function (event) {
- var time = +new Date;
- window.Intercom("boot", {
- app_id: "heoqdjs2",
- name: event.name, // Full name
- email: event.email, // Email address
- created_at: time // Signup date as a Unix timestamp
- });
- },
- identifyFS: function (event) {
- FS.identify(event.email, {
- displayName: event.name
- });
- }
- };
- }
- })(angular);
- (function (angular) {
- 'use strict';
- angular
- .module('loginApp')
- .factory('introService', introService);
- introService.$inject = [
- '$rootScope',
- '$window'
- ];
- function introService($rootScope, $window) {
- return {
- enableIntro: function () {
- $window.localStorage.setItem('intro_value', 1);
- },
- disableIntro: function () {
- $window.localStorage.setItem('intro_value', 2);
- },
- isIntroEnabled: function () {
- var value = $window.localStorage.getItem('intro_value');
- return +value === 1;
- },
- unsetIntroValue: function () {
- $window.localStorage.removeItem('intro_value');
- },
- introPopupWasShowed: function () {
- var val = $window.localStorage.getItem('intro_value');
- return (!!val) ? val : null;
- },
- setCampaignLoaded: function () {
- $window.localStorage.setItem('campaign_loaded', 1);
- },
- wasCampaignLoaded: function () {
- var value = $window.localStorage.getItem('campaign_loaded');
- return +value === 1;
- },
- setProfileLoaded: function () {
- $window.localStorage.setItem('profile_loaded', 1);
- },
- wasProfileLoaded: function () {
- var value = $window.localStorage.getItem('profile_loaded');
- return +value === 1;
- },
- setLoanLoaded: function () {
- $window.localStorage.setItem('loan_loaded', 1);
- },
- wasLoanLoaded: function () {
- var value = $window.localStorage.getItem('loan_loaded');
- return +value === 1;
- },
- getWrappedIntro: function (steps) {
- return {
- steps: steps,
- showStepNumbers: false,
- exitOnOverlayClick: true,
- exitOnEsc:true,
- showBullets: false,
- showProgress: true,
- nextLabel: 'Next',
- prevLabel: 'Previous',
- skipLabel: 'Skip',
- doneLabel: 'Done',
- scrollToElement: true
- };
- }
- };
- }
- })(angular);
- (function (angular) {
- 'use strict';
- angular
- .module('loginApp')
- .factory('Messages', Messages);
- Messages.$inject = [
- '$rootScope',
- 'ModalService'
- ];
- function Messages($rootScope,
- ModalService) {
- var messageHeader = 'Error', // default
- messageText = 'Server Internal Error', // default
- bufferedString = [],
- callback = function (result) {};
- return {
- types: {
- CONFIRM_TYPE: 1,
- ALERT_TYPE: 2,
- DEFAULT_TYPE: 3
- },
- //Header setter
- setHeader: function (header) {
- messageHeader = header;
- },
- //Header getter
- getHeader: function () {
- return messageHeader;
- },
- //Text setter
- setText: function (text) {
- messageText = text;
- },
- pushText: function (text) {
- bufferedString.push(text);
- },
- setErrors: function (errors) {
- var self = this;
- errors.forEach(function (error) {
- self.pushText(error.fieldName + ': ' + error.detail);
- });
- },
- clearBuffer: function () {
- bufferedString = [];
- },
- //Text getter
- getText: function () {
- return messageText;
- },
- /**
- * Set header and text
- * @param {object} params.header
- * @param {object} params.text
- */
- setMessage: function (params) {
- var text = '';
- this.setHeader(params.header);
- if (typeof params.text === 'object') {
- params.text.forEach(function (item) {
- text += item.detail;
- });
- } else {
- text = params.text;
- }
- this.setText(text);
- },
- sendMessage: function () {
- var message = {};
- message.header = this.getHeader();
- message.text = this.getText();
- this.showMessage(message);
- },
- sendError: function (response) {
- var text = '';
- this.setHeader("Error " + response.status);
- response.data.errors && response.data.errors.forEach(function (item) {
- text += item.detail;
- });
- this.setText(text);
- this.sendMessage();
- },
- getModalCallback: function () {
- return callback;
- },
- setModalCallback: function (fn) {
- callback = fn;
- },
- /**
- * Set controller and send message event
- * @param {object} message.header
- * @param {object} message.text
- */
- showMessage: function (message) {
- ModalService.showModal({
- templateUrl: "views/modal-message.html",
- controller: "MessagesController",
- controllerAs: "vm",
- inputs: {
- params: {
- header: this.getHeader(),
- text: this.getText(),
- bufferedString: bufferedString,
- modalCallback: this.getModalCallback()
- }
- }
- }).then(function (modal) {
- modal.element.modal && modal.element.modal();
- modal.close.then(function (result) {
- callback.call(modal, result);
- });
- });
- // clear after show
- bufferedString = [];
- }
- };
- }
- })(angular);
- (function () {
- 'use strict';
- angular
- .module('loginApp')
- .factory('oauthService', oauthService);
- oauthService.$inject = [
- 'Endpoints',
- '$http',
- 'socialNetworkMapper',
- 'socialNetworksEnum',
- 'importMapper'
- ];
- function oauthService(Endpoints,
- $http,
- socialNetworkMapper,
- socialNetworksEnum,
- importMapper) {
- var user = null;
- return {
- getImportContactsLink: function (enumValue) {
- var networkName = this.getNetworkNameByEnum(enumValue);
- return $http.post(Endpoints.importContactsLink, {type: networkName})
- .then(
- function suc(response) {
- response.redirectLink = socialNetworkMapper.mapFromServer(response.data).redirectLink;
- return response;
- },
- function err(response) {
- return response;
- }
- );
- },
- getContactsFromSocialNetwork: function (token, networkName) {
- return $http.post(Endpoints.contactsFromSocialNetwork,
- {token: token, type: networkName}).then(
- function suc(response) {
- response.contacts = importMapper.mapArrayFromServer(response.data);
- return response;
- },
- function err(response) {
- return response;
- })
- },
- getNetworkNameByEnum: function (enumValue) {
- var networkName;
- switch (enumValue) {
- case socialNetworksEnum.google:
- networkName = 'google';
- break;
- case socialNetworksEnum.yahoo:
- networkName = 'yahoo';
- break;
- case socialNetworksEnum.microsoft:
- networkName = 'microsoft';
- break;
- }
- return networkName;
- }
- };
- }
- })();
- (function () {
- 'use strict';
- angular
- .module('loginApp')
- .factory('paymentSimulatorService', paymentSimulatorService);
- paymentSimulatorService.$inject = [];
- function paymentSimulatorService() {
- return {
- getMinimumPayment: function (amount, months, interest) {
- // R = P × r / [1 - (1 + r)-n]
- return (amount * ((interest / 100) / 12)) / (1 - (Math.pow((1 + ((interest / 100) / 12)), -months)));
- },
- getPaymentPeriod: function (amount, minimumAmountDue, interest) {
- // n = log[x / (x – P × r)] / log (1 + r)
- return Math.log(minimumAmountDue / (minimumAmountDue - amount * (interest / 100) / 12)) / Math.log(1 + (interest / 100) / 12);
- }
- };
- }
- })();
- (function () {
- 'use strict';
- angular
- .module('loginApp')
- .factory('scrollService', scrollService);
- scrollService.$inject = [
- '$timeout'
- ];
- function scrollService($timeout) {
- return {
- scrollTo: function (selector) {
- var target = $(selector),
- page = $("body, html");
- page.on("scroll mousedown wheel DOMMouseScroll mousewheel keyup touchmove", function () {
- page.stop();
- });
- page.animate({scrollTop: target.offset().top}, "normal", function () {
- page.off("scroll mousedown wheel DOMMouseScroll mousewheel keyup touchmove");
- });
- }
- };
- }
- })();
- (function () {
- 'use strict';
- angular
- .module('loginApp')
- .factory('socialService', socialService);
- socialService.$inject = [
- '$location',
- 'appConstants',
- 'Socialshare'
- ];
- function socialService($location, appConstants, Socialshare) {
- function concatenateDomainAndPath(passedPath) {
- var baseSiteUrl = $location.protocol() + '://' + $location.host() + '/#',
- path = passedPath || location.path();
- return baseSiteUrl + path;
- }
- function getGiftProfileUrlById(id) {
- return concatenateDomainAndPath('/gift/' + id);
- }
- return {
- shareProfileAtFacebook: function (vm, text) {
- var id = vm.profile.userId,
- story = vm.profile.story,
- media = $location.protocol() + ':' + vm.profile.photoLink,
- description = story || text || 'Profile — ' + vm.profile.getFullName();
- Socialshare.share({
- provider: 'facebook',
- attrs: {
- socialshareType: 'share',
- socialshareVia: appConstants.FACEBOOK_APP_ID,
- socialshareUrl: getGiftProfileUrlById(id),
- socialshareDescription: description,
- socialshareTitle: 'A better, faster way to pay off your student loans',
- socialshareMedia: media
- }
- });
- },
- shareProfileAtTwitter: function (vm, text) {
- var id = vm.profile.userId,
- story = vm.profile.story || text || 'LoanGifting Profile — ' + vm.profile.getFullName();
- Socialshare.share({
- provider: 'twitter',
- attrs: {
- socialshareUrl: getGiftProfileUrlById(id),
- socialshareText: story
- }
- });
- },
- shareProfileAtGoogle: function (vm) {
- var id = vm.profile.userId;
- Socialshare.share({
- provider: 'google',
- attrs: {
- socialshareUrl: getGiftProfileUrlById(id)
- }
- });
- },
- shareProfileAtLinkedIn: function (vm, text) {
- var id = vm.profile.userId,
- story = vm.profile.story || text || 'LoanGifting Profile — ' + vm.profile.getFullName();
- Socialshare.share({
- provider: 'linkedin',
- attrs: {
- socialshareUrl: getGiftProfileUrlById(id),
- socialshareText: "A better, faster way to pay off your student loans. " + story
- }
- });
- }
- };
- }
- })();
- (function () {
- 'use strict';
- angular
- .module('loginApp')
- .factory('spinnerService', spinnerService);
- spinnerService.$inject = [
- '$timeout'
- ];
- function spinnerService($timeout) {
- var timeoutId = null;
- return {
- show: function () {
- if (timeoutId) {
- clearTimeout(timeoutId);
- }
- angular
- .element(document.querySelector('#XHRFixedWrapper'))
- .css('display', 'block');
- },
- hide: function () {
- timeoutId = setTimeout(function () {
- angular
- .element(document.querySelector('#XHRFixedWrapper'))
- .css('display', 'none');
- }, 100);
- }
- };
- }
- })();
- (function () {
- 'use strict';
- angular
- .module('loginApp')
- .factory('userService', userService);
- userService.$inject = [
- 'userMapper',
- 'Endpoints',
- '$http',
- '$q'
- ];
- function userService(userMapper,
- Endpoints,
- $http) {
- var user = null;
- return {
- fetchUser: function () {
- return $http.get(Endpoints.profileInfo)
- .then(function (response) {
- user = userMapper.mapFromServer(response.data);
- return user;
- }).catch(function (error) {
- return error;
- });
- },
- getUser: function () {
- return user;
- },
- setUser: function (u) {
- user = u;
- },
- setProperty: function (field, value) {
- if (user) {
- user[field] = value;
- }
- },
- getProperty: function (field) {
- var result;
- if (user) {
- result = user[field];
- }else {
- result = null;
- }
- return result;
- },
- isAdmin: function () {
- return $http.get(Endpoints.isAdmin)
- .then(function (response) {
- return response;
- },
- function (response) {
- return response;
- });
- },
- unsetUser: function () {
- user = null;
- }
- };
- }
- })();
- (function () {
- 'use strict';
- angular
- .module("loginApp")
- .factory('userMapper', userMapper);
- userMapper.$inject = ['BaseMapper'];
- function userMapper(BaseMapper) {
- UserMapper.prototype = BaseMapper.prototype;
- function UserMapper() {
- this.mapFromServer = mapFromServer;
- this.mapToServer = mapToServer;
- function mapFromServer(data) {
- var attributes = this.baseMapFromServer(data);
- return {
- userId: attributes.user_id,
- firstName: attributes.first_name,
- lastName: attributes.last_name,
- name: attributes.name,
- story: attributes.story,
- token: attributes.token,
- gender: +attributes.gender,
- videoLink: attributes.video,
- photoLink: attributes.photo,
- isHasPassword: attributes.has_password,
- isHasQuestions: attributes.has_questions,
- isHasLoans: attributes.has_loans,
- months: attributes.months,
- birthday: attributes.birthday,
- country: attributes.country,
- state: attributes.state,
- zip: attributes.zip,
- city: attributes.city,
- phone: attributes.phone,
- email: attributes.email
- }
- }
- function mapToServer(UserModel) {
- return {
- first_name: UserModel.firstName,
- last_name: UserModel.lastName,
- birthday: UserModel.concatenateBirthday(),
- gender: UserModel.gender,
- story: UserModel.story,
- country: UserModel.country,
- state: UserModel.state,
- phone: UserModel.phone,
- zip: UserModel.zip
- };
- }
- }
- return new UserMapper();
- }
- })();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement