Advertisement
Guest User

market

a guest
Aug 17th, 2017
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.51 KB | None | 0 0
  1. function startApp() {
  2. $('header').find("a").show();
  3. function showView(view) {
  4. $('section').hide();
  5. switch (view) {
  6. case 'home':
  7. $('#viewAppHome').show();
  8. break;
  9. case 'login':
  10. $('#viewLogin').show();
  11. break;
  12. case 'register':
  13. $('#viewRegister').show();
  14. break;
  15. case 'userHome':
  16. $('#viewUserHome').show();
  17. break;
  18. case 'cart':
  19. $('#viewCart').show();
  20. showCart();
  21. break;
  22. case 'shop':
  23. $('#viewShop').show();
  24. loadAllProducts();
  25. break;
  26. }
  27. }
  28.  
  29. $('#linkMenuAppHome').click(() => showView('home'));
  30. $('#linkMenuLogin').click(() => showView('login'));
  31. $('#linkMenuRegister').click(() => showView('register'));
  32. $('#linkMenuUserHome').click(() => showView('userHome'));
  33. $('#linkMenuShop').click(() => showView('shop'));
  34. $('#linkMenuCart').click(() => showView('cart'));
  35. $('#linkUserHomeShop').click(() => showView('shop'));
  36. $('#linkUserHomeCart').click(() => showView('cart'))
  37. $('#linkMenuLogout').click(logout);
  38. $('#formRegister').submit(register);
  39. $('#formLogin').submit(login);
  40.  
  41.  
  42. $(document).on({
  43. ajaxStart: () => $('#loadingBox').show(),
  44. ajaxStop: () => $('#loadingBox').fadeOut()
  45. });
  46.  
  47. $('#infoBox').click((event) => $(event.target).hide());
  48. $('#errorBox').click((event) => $(event.target).hide());
  49.  
  50. function showInfo(message) {
  51. $('#infoBox').text(message);
  52. $('#infoBox').show();
  53. setTimeout(() => $('#infoBox').fadeOut(), 3000);
  54. }
  55.  
  56. function showError(message) {
  57. $('#errorBox').text(message);
  58. $('#errorBox').show();
  59. }
  60.  
  61. function handleError(reason) {
  62. showError(reason.responseJSON.description);
  63. }
  64.  
  65. function userLoggedIn() {
  66. $('header').find("a").show();
  67. $('#linkMenuRegister').hide();
  68. $('#linkMenuUserHome').show();
  69. $('#linkMenuLogin').hide();
  70. $('#linkMenuAppHome').hide();
  71. $('#spanMenuLoggedInUser').text(`Welcome, ${localStorage.getItem('username')}!!`);
  72. $('#spanMenuLoggedInUser').show();
  73. $('#viewUserHomeHeading').text(`Welcome, ${localStorage.getItem('username')}!!`);
  74. $('#viewUserHomeHeading').show();
  75. showView('userHome');
  76. }
  77.  
  78. function userLoggedOut() {
  79. $('#spanMenuLoggedInUser').text('');
  80. $('#spanMenuLoggedInUser').hide();
  81. $('header').find("a").hide();
  82. $('#linkMenuAppHome').show();
  83. $('#linkMenuRegister').show();
  84. $('#linkMenuLogin').show();
  85.  
  86. }
  87.  
  88. function saveSession(data) {
  89. localStorage.setItem('username', data.username);
  90. localStorage.setItem('id', data._id);
  91. localStorage.setItem('name', data['name']);
  92. localStorage.setItem('authtoken', data._kmd.authtoken);
  93. }
  94.  
  95. showView('home');
  96. let requester = (() => {
  97.  
  98. const baseUrl = "https://baas.kinvey.com/";
  99. const appKey = "kid_Hk-uWafuW";
  100. const appSecret = "209f016b34104ba7be0d9dc5fe62b3f2";
  101.  
  102. function makeAuth(type) {
  103. if (type === "basic") return "Basic " + btoa(appKey + ":" + appSecret);
  104. else return 'Kinvey ' + localStorage.getItem('authtoken');
  105. }
  106.  
  107. function makeRequest(method, module, url, auth) {
  108.  
  109. return req = {
  110. url: baseUrl + module + "/" + appKey + '/' + url,
  111. method,
  112. headers: {
  113. 'Authorization': makeAuth(auth)
  114. }
  115. };
  116. }
  117.  
  118. function get(module, url, auth) {
  119. return $.ajax(makeRequest("GET", module, url, auth));
  120. }
  121.  
  122. function post(module, url, data, auth) {
  123. let req = makeRequest("POST", module, url, auth);
  124. req.data = JSON.stringify(data);
  125. req.headers['Content-Type'] = 'application/json';
  126. return $.ajax(req);
  127. }
  128.  
  129. function update(module, url, data, auth) {
  130. let req = makeRequest("PUT", module, url, auth);
  131. req.data = data;
  132. return $.ajax(req);
  133. }
  134.  
  135. function remove(module, url, data, auth) {
  136. return $.ajax(makeRequest("DELETE", module, url, auth));
  137. }
  138.  
  139. return {get, post, update, remove}
  140. })();
  141.  
  142. if (localStorage.getItem('authtoken') !== null && localStorage.getItem('username') !== null) {
  143. userLoggedIn();
  144. } else {
  145. userLoggedOut();
  146. }
  147.  
  148. async function register(ev) {
  149. ev.preventDefault();
  150. let username = $('#registerUsername').val();
  151. let password =$('#registerPasswd').val();
  152. let name = $('#registerName').val();
  153. try {
  154. let data = await requester.post('user', '', {username, password, name}, "basic");
  155. saveSession(data);
  156. showInfo("Successfully register!! Please logIn");
  157. showView('login');
  158. } catch (err) {
  159. handleError(err);
  160. }
  161. }
  162.  
  163. async function login(ev) {
  164. ev.preventDefault();
  165. let form = $('#formLogin');
  166. let username = $('#loginUsername').val();
  167. let password = $('#loginPasswd').val();
  168.  
  169. try {
  170. let data = await requester.post('user', "login", {username, password}, "basic");
  171. saveSession(data);
  172. userLoggedIn();
  173. showInfo("Successfully login");
  174. showView('viewUserHome');
  175. } catch (err) {
  176. handleError(err);
  177. }
  178. }
  179.  
  180. async function logout() {
  181. try {
  182. let data = await requester.post('user', '_logout', {authtoken: localStorage.getItem('authtoken')});
  183. localStorage.clear();
  184. showView("home");
  185. showInfo("Successfully logout!!");
  186. userLoggedOut();
  187. } catch (err) {
  188. handleError(err);
  189. }
  190. }
  191.  
  192. async function loadAllProducts() {
  193. let data = await requester.get('appdata', 'products');
  194. if(data.length === 0){
  195. $('#shopProducts').append("<p>No products in database</p>");
  196. return;
  197. }
  198. for (let product of data) {
  199. $('#shopProducts>table>tbody').append($('<tr>')
  200. .append($('<td>').text(product.name))
  201. .append($('<td>').text(product.description))
  202. .append($('<td>').text(Math.ceil(product.price).toFixed(2)))
  203. .append($('<td>').append($('<button>').text('Purchase').click(() => {
  204. purchaseItem(product);
  205. }))))
  206. }
  207. }
  208. function showCart() {
  209. try {
  210. requester.get('user', localStorage.getItem("id")).then(showCartSuccess);
  211. } catch (err) {
  212. handleError(err);
  213. }
  214.  
  215. function showCartSuccess(user) {
  216. $('#cartProducts table tbody').empty();
  217.  
  218. if(! user.cart){
  219. user.cart = {};
  220. }
  221.  
  222. for(let productId of Object.keys(user.cart)){
  223. let discardLink = $('<button>').text('Discard').click(() => discardItem(user, productId));
  224. $('#cartProducts table tbody')
  225. .append($('<tr>')
  226. .append($('<td>').text(user.cart[productId].product.name))
  227. .append($('<td>').text(user.cart[productId].product.description))
  228. .append($('<td>').text(user.cart[productId].quantity))
  229. .append($('<td>').text((Number(user.cart[productId].product.price) * Number(user.cart[productId].quantity)).toFixed(2)))
  230. .append($('<td>').append(discardLink))
  231. );
  232. }
  233. }
  234. }
  235.  
  236. function purchaseItem(product) {
  237. try {
  238. requester.get('user', localStorage.getItem("id")).then(loadUserSuccess);
  239. } catch (err) {
  240. handleError(err);
  241. }
  242.  
  243. function loadUserSuccess(user) {
  244. if(! user.cart){
  245. user.cart = {};
  246. }
  247.  
  248. if(! user.cart[product._id]){
  249. user.cart[product._id] = {};
  250. user.cart[product._id].product = {};
  251. user.cart[product._id].product.name = product.name;
  252. user.cart[product._id].product.description = product.description;
  253. user.cart[product._id].product.price = product.price;
  254. user.cart[product._id].quantity = 1;
  255. } else {
  256. user.cart[product._id].quantity = Number(user.cart[product._id].quantity) + 1;
  257. }
  258.  
  259. let userdata = user;
  260.  
  261. try {
  262. requester.update('user', localStorage.getItem("id"), userdata).then(updateUserSuccess);
  263. } catch (err) {
  264. handleError(err);
  265. }
  266.  
  267. function updateUserSuccess() {
  268. showView('cart');
  269. showInfo('Product purchased.')
  270. }
  271. }
  272. }
  273.  
  274. function discardItem(productId, user){
  275. try {
  276. requester.update('user', localStorage.getItem("id"), user).then(updateUserSuccesss);
  277. } catch (err) {
  278. handleError(err);
  279. }
  280.  
  281. function updateUserSuccesss() {
  282. showView('cart');
  283. showInfo('Product discarded.');
  284. }
  285. }
  286. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement