Advertisement
stanly65

h_ex_market

Aug 20th, 2017
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function startApp() {
  2.     const kinveyBaseUrl = "https://baas.kinvey.com/";
  3.     const kinveyAppKey = "kid_rk5XQ_qHg";
  4.     const kinveyAppSecret = "d93aef2f8fed46d2b5613c7608774d8e";
  5.     const kinveyAppAuthHeaders = {
  6.         "Authorization": "Basic " + btoa(kinveyAppKey + ":" + kinveyAppSecret)
  7.     };
  8.  
  9.     sessionStorage.clear();
  10.     showHideMenuLinks();
  11.     showAppHomeView();
  12.  
  13.     $('#linkMenuAppHome').click(showAppHomeView);
  14.     $('#linkMenuLogin').click(showLoginView);
  15.     $('#linkMenuRegister').click(showRegisterView);
  16.  
  17.     $('#linkMenuUserHome').click(showUserHomeView);
  18.     $('#linkMenuLogout').click(logoutUser);
  19.  
  20.     $('#formRegister').submit(registerUser);
  21.     $('#formLogin').submit(loginUser);
  22.  
  23.     $('#linkMenuShop, #linkUserHomeShop').click(showShop);
  24.     $('#linkMenuCart, #linkUserHomeCart').click(showCart);
  25.  
  26.     $('#infoBox, #errorBox').click(function () {
  27.         $(this).fadeOut();
  28.     });
  29.  
  30.     $(document).on({
  31.         ajaxStart: function () {
  32.             $('#loadingBox').show();
  33.         },
  34.         ajaxStop: function () {
  35.             $('#loadingBox').hide();
  36.         }
  37.     });
  38.  
  39.     function showHideMenuLinks() {
  40.         $('main > div').hide();
  41.         if(sessionStorage.getItem('authToken')){
  42.             $('.useronly').show();
  43.             $('.anonymous').hide();
  44.         } else {
  45.             $('.anonymous').show();
  46.             $('.useronly').hide();
  47.         }
  48.     }
  49.  
  50.     function showView(viewName) {
  51.         $('main > section').hide();
  52.         $('#' + viewName).show();
  53.     }
  54.  
  55.     function showAppHomeView() {
  56.         showView('viewAppHome');
  57.     }
  58.  
  59.     function showLoginView() {
  60.         showView('viewLogin');
  61.     }
  62.  
  63.     function showRegisterView() {
  64.         showView('viewRegister');
  65.     }
  66.  
  67.     function showUserHomeView() {
  68.         showView('viewUserHome');
  69.     }
  70.  
  71.     function showShopView() {
  72.         showView('viewShop');
  73.     }
  74.  
  75.     function showCartView() {
  76.         showView('viewCart');
  77.     }
  78.  
  79.  
  80.     function handleAjaxError(response) {
  81.         let errorMsg = JSON.stringify(response);
  82.         if(response.readyState === 0) {
  83.             errorMsg = "Cannot connect due to network error.";
  84.         }
  85.         if(response.responseJSON && response.responseJSON.description) {
  86.             errorMsg = response.responseJSON.description;
  87.         }
  88.  
  89.         showError(errorMsg);
  90.     }
  91.  
  92.     function showInfo(message) {
  93.         $('#infoBox').text(message);
  94.         $('#infoBox').show();
  95.         setTimeout(function () {
  96.             $('#infoBox').fadeOut();
  97.         }, 3000);
  98.     }
  99.  
  100.     function showError(errorMsg) {
  101.         $('#errorBox').text("Error: " + errorMsg);
  102.         $('#errorBox').show();
  103.     }
  104.  
  105.     function registerUser(event) {
  106.         event.preventDefault();
  107.         let userData = {
  108.             username: $('#formRegister input[name=username]').val(),
  109.             password: $('#formRegister input[name=password]').val(),
  110.             name: $('#formRegister input[name=name]').val(),
  111.             cart: {}
  112.         };
  113.  
  114.         $.ajax({
  115.             method: "POST",
  116.             url: kinveyBaseUrl + "user/" + kinveyAppKey + "/",
  117.             headers: kinveyAppAuthHeaders,
  118.             data: userData,
  119.             success: registerSuccess,
  120.             error: handleAjaxError
  121.         });
  122.  
  123.         function registerSuccess(userInfo) {
  124.             $('form input[type=text], form input[type=password]').val('');
  125.             saveAuthInSession(userInfo);
  126.             showHideMenuLinks();
  127.             showUserHomeView();
  128.             showInfo('User registration successful.');
  129.         }
  130.     }
  131.  
  132.     function saveAuthInSession(userInfo) {
  133.         let userAuth = userInfo._kmd.authtoken;
  134.         sessionStorage.setItem('authToken', userAuth);
  135.         let id = userInfo._id;
  136.         sessionStorage.setItem('id', id);
  137.         let username = userInfo.username;
  138.         sessionStorage.setItem('username', username);
  139.         $('#spanMenuLoggedInUser').text("Welcome, " + username + "!");
  140.         $('#viewUserHomeHeading').text("Welcome, " + username + "!");
  141.     }
  142.  
  143.     function loginUser(event) {
  144.         event.preventDefault();
  145.  
  146.         let userData = {
  147.             username: $('#formLogin input[name=username]').val(),
  148.             password: $('#formLogin input[name=password]').val()
  149.         };
  150.  
  151.         $.ajax({
  152.             method: "POST",
  153.             url: kinveyBaseUrl + "user/" + kinveyAppKey + "/login",
  154.             headers: kinveyAppAuthHeaders,
  155.             data: userData,
  156.             success: loginSuccess,
  157.             error: handleAjaxError
  158.         });
  159.  
  160.         function loginSuccess(userInfo) {
  161.             $('form input[type=text], form input[type=password]').val('');
  162.             saveAuthInSession(userInfo);
  163.             showHideMenuLinks();
  164.             showUserHomeView();
  165.             showInfo('Login successful.');
  166.         }
  167.     }
  168.  
  169.     function logoutUser() {
  170.         $.ajax({
  171.             method: "POST",
  172.             url: kinveyBaseUrl + "user/" + kinveyAppKey + "/_logout",
  173.             headers: getKinveyUserAuthHeaders(),
  174.             success: logoutSuccess,
  175.             error: handleAjaxError
  176.         });
  177.  
  178.         function logoutSuccess() {
  179.             sessionStorage.clear();
  180.             showHideMenuLinks();
  181.             showAppHomeView();
  182.             showInfo("Logout successful.");
  183.         }
  184.     }
  185.  
  186.     function getKinveyUserAuthHeaders() {
  187.         return {
  188.             "Authorization": "Kinvey " + sessionStorage.getItem('authToken')
  189.         };
  190.     }
  191.  
  192.     function showShop() {
  193.         $.ajax({
  194.             method: "GET",
  195.             url: kinveyBaseUrl + "appdata/" + kinveyAppKey + "/products",
  196.             headers: getKinveyUserAuthHeaders(),
  197.             success: showShopSuccess,
  198.             error: handleAjaxError
  199.         });
  200.  
  201.         function showShopSuccess(products) {
  202.             products = products.sort((a,b) => a._id.localeCompare(b._id));
  203.             $('#shopProducts table tbody').empty();
  204.  
  205.             for(let product of products){
  206.                 let purchaseLink = $('<button>').text('Purchase').click(() => purchaseItem(product));
  207.                 $('#shopProducts table tbody')
  208.                     .append($('<tr>')
  209.                         .append($('<td>').text(product.name))
  210.                         .append($('<td>').text(product.description))
  211.                         .append($('<td>').text(product.price.toFixed(2)))
  212.                         .append($('<td>').append(purchaseLink))
  213.                     );
  214.             }
  215.  
  216.             showShopView();
  217.         }
  218.     }
  219.  
  220.     function showCart() {
  221.         $.ajax({
  222.             method: "GET",
  223.             url: kinveyBaseUrl + "user/" + kinveyAppKey + "/" + sessionStorage.getItem('id'),
  224.             headers: getKinveyUserAuthHeaders(),
  225.             success: showCartSuccess,
  226.             error: handleAjaxError
  227.         });
  228.  
  229.         function showCartSuccess(user) {
  230.             $('#cartProducts table tbody').empty();
  231.  
  232.             if(! user.cart){
  233.                 user.cart = {};
  234.             }
  235.  
  236.             for(let productId of Object.keys(user.cart)){
  237.                 let discardLink = $('<button>').text('Discard').click(() => discardItem(user, productId));
  238.                 $('#cartProducts table tbody')
  239.                     .append($('<tr>')
  240.                         .append($('<td>').text(user.cart[productId].product.name))
  241.                         .append($('<td>').text(user.cart[productId].product.description))
  242.                         .append($('<td>').text(user.cart[productId].quantity))
  243.                         .append($('<td>').text((Number(user.cart[productId].product.price) * Number(user.cart[productId].quantity)).toFixed(2)))
  244.                         .append($('<td>').append(discardLink))
  245.                     );
  246.             }
  247.  
  248.             showCartView();
  249.         }
  250.     }
  251.  
  252.     function purchaseItem(product) {
  253.         $.ajax({
  254.             method: "GET",
  255.             url: kinveyBaseUrl + "user/" + kinveyAppKey + "/" + sessionStorage.getItem('id'),
  256.             headers: getKinveyUserAuthHeaders(),
  257.             success: loadUserSuccess,
  258.             error: handleAjaxError
  259.         });
  260.  
  261.         function loadUserSuccess(user) {
  262.             if(! user.cart){
  263.                 user.cart = {};
  264.             }
  265.  
  266.             if(! user.cart[product._id]){
  267.                 user.cart[product._id] = {};
  268.                 user.cart[product._id].product = {};
  269.                 user.cart[product._id].product.name = product.name;
  270.                 user.cart[product._id].product.description = product.description;
  271.                 user.cart[product._id].product.price = product.price;
  272.                 user.cart[product._id].quantity = 1;
  273.             } else {
  274.                 user.cart[product._id].quantity = Number(user.cart[product._id].quantity) + 1;
  275.             }
  276.  
  277.             let userdata = user;
  278.  
  279.             $.ajax({
  280.                 method: "PUT",
  281.                 url: kinveyBaseUrl + "user/" + kinveyAppKey + "/" + sessionStorage.getItem('id'),
  282.                 headers: getKinveyUserAuthHeaders(),
  283.                 data: userdata,
  284.                 success: updateUserSuccess,
  285.                 error: handleAjaxError
  286.             });
  287.            
  288.             function updateUserSuccess() {
  289.                 showCart();
  290.                 showInfo('Product purchased.')
  291.             }
  292.         }
  293.     }
  294.  
  295.     function discardItem(user, productId){
  296.         delete user.cart[productId];
  297.  
  298.         $.ajax({
  299.             method: "PUT",
  300.             url: kinveyBaseUrl + "user/" + kinveyAppKey + "/" + sessionStorage.getItem('id'),
  301.             headers: getKinveyUserAuthHeaders(),
  302.             data: user,
  303.             success: updateUserSuccess,
  304.             error: handleAjaxError
  305.         });
  306.  
  307.         function updateUserSuccess() {
  308.             showCart();
  309.             showInfo('Product discarded.');
  310.         }
  311.     }
  312. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement