Advertisement
Guest User

Untitled

a guest
Dec 21st, 2016
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.22 KB | None | 0 0
  1. /**
  2. * Created by Merrie on 12/20/16.
  3. */
  4. function startApp() {
  5. const kinveyBaseUrl = "https://baas.kinvey.com/";
  6. const kinveyAppKey = "kid_BkgrHyPNx";
  7. const kinveyAppSecret = "0a80d7870a094292ab4f8e89484ccf62";
  8. const kinveyAppAuthHeaders = {
  9. 'Authorization': "Basic " + btoa(kinveyAppKey + ":" + kinveyAppSecret),
  10. };
  11.  
  12. //Hide status boxes
  13. $('#infoBox').hide();
  14. $('#errorBox').hide();
  15. $('#loadingBox').hide();
  16.  
  17. sessionStorage.clear(); // Clear user auth data
  18.  
  19. showHideMenuLinks();
  20.  
  21. if(sessionStorage.getItem('authToken')) {
  22. $('#spanMenuLoggedInUser').text('Welcome, ' + sessionStorage.getItem('name') + '!');
  23. showUserHomeView()
  24. }else {
  25. $('#spanMenuLoggedInUser').empty();
  26. showAppHomeView();
  27. }
  28.  
  29. //Bind menu links with views
  30. $("#linkMenuAppHome").click(showAppHomeView);
  31. $("#linkMenuLogin").click(showLoginView);
  32. $("#linkMenuRegister").click(showRegisterView);
  33.  
  34. $("#linkMenuUserHome").click(showUserHomeView);
  35. $("#linkMenuShop").click(showShopView);
  36. $("#linkMenuCart").click(showCartView);
  37. $("#linkMenuLogout").click(logoutUser);
  38.  
  39. // Bind the form submit buttons
  40. $(`#formLogin input[type="submit"]`).click(loginUser);
  41. $(`#formRegister input[type="submit"]`).click(registerUser);
  42.  
  43.  
  44. $("#infoBox, #errorBox").click(function () {
  45. $(this).fadeOut();
  46. });
  47.  
  48. // Attach AJAX "loading" event listener
  49. $(document).on({
  50. ajaxStart: function () {
  51. $("#loadingBox").show()
  52. },
  53. ajaxStop: function () {
  54. $("#loadingBox").hide()
  55. }
  56. });
  57.  
  58. function showHideMenuLinks() {
  59. if (sessionStorage.getItem('authToken')) {
  60. // We have logged in user
  61. $("#linkMenuAppHome").hide();
  62. $("#linkMenuLogin").hide();
  63. $("#linkMenuRegister").hide();
  64. $("#linkMenuUserHome").show();
  65. $("#linkMenuShop").show();
  66. $("#linkMenuCart").show();
  67. $("#linkMenuLogout").show();
  68. } else {
  69. // No logged in user
  70. $("#linkMenuAppHome").show();
  71. $("#linkMenuLogin").show();
  72. $("#linkMenuRegister").show();
  73. $("#linkMenuUserHome").hide();
  74. $("#linkMenuShop").hide();
  75. $("#linkMenuCart").hide();
  76. $("#linkMenuLogout").hide();
  77. }
  78. }
  79.  
  80. function showView(viewName) {
  81. // Hide all views and show the selected view only
  82. $('main > section').hide();
  83. $('#' + viewName).show();
  84. }
  85.  
  86. function showAppHomeView() {
  87. //Bind the user home buttons
  88. $("#linkUserHomeShop").click(showShopView);
  89. $("#linkUserHomeCart").click(showCartView);
  90. showView('viewAppHome');
  91. }
  92.  
  93. function showUserHomeView() {
  94. $('#viewUserHomeHeading').text('Welcome, ' + sessionStorage.getItem('name') + '!');
  95. showView('viewUserHome');
  96. }
  97.  
  98. function showLoginView() {
  99. showView('viewLogin');
  100. $('#formLogin').trigger('reset');
  101. }
  102.  
  103. function showRegisterView() {
  104. $('#formRegister').trigger('reset');
  105. showView('viewRegister');
  106. }
  107.  
  108. function showShopView() {
  109. $('#viewShop').empty();
  110. const getShopUrl = kinveyBaseUrl + "appdata/" + kinveyAppKey + `/products`;
  111. let table = $('<table>').append(
  112. `<thead>
  113. <tr>
  114. <th>Product</th>
  115. <th>Description</th>
  116. <th>Price</th>
  117. <th>Actions</th>
  118. </tr>
  119. </thead>`);
  120. $.ajax({
  121. method: "GET",
  122. url: getShopUrl,
  123. headers: getKinveyUserAuthHeaders(),
  124. success: fillTable,
  125. error: handleAjaxError
  126. });
  127. function fillTable(products) {
  128. if (products.length == 0) {
  129. $('#viewShop').empty();
  130. $('#viewShop').text('No products found.')
  131. }
  132. else {
  133. let tbody = $('<tbody>');
  134. for (let prd of products) {
  135. let prcBtn = $('<button>').text("Purchase");
  136. prcBtn.click(x => purchaseProduct(prd._id));
  137. tbody.append($('<tr>')
  138. .append($(`<td>`).text(prd.name))
  139. .append($(`<td>`).text(prd.description))
  140. .append($(`<td>`).text(prd.price.toFixed(2)))
  141. .append($('<td>').append(prcBtn)));
  142. }
  143.  
  144. table.append(tbody);
  145. $('#viewShop').empty();
  146. $('#viewShop').append(table);
  147. }
  148. }
  149. showView('viewShop');
  150. }
  151.  
  152. function showCartView() {
  153. $('#viewCart').empty();
  154. const getCartUrl = kinveyBaseUrl + "appdata/" + kinveyAppKey + `/shoppingCart`;
  155. let table = $('<table>').append(
  156. `<thead>
  157. <tr>
  158. <th>Product</th>
  159. <th>Description</th>
  160. <th>Quantity</th>
  161. <th>Total Price</th>
  162. <th>Actions</th>
  163. </tr>
  164. </thead>`);
  165. $.ajax({
  166. method: "GET",
  167. url: getCartUrl,
  168. headers: getKinveyUserAuthHeaders(),
  169. success: fillTable,
  170. error: handleAjaxError
  171. });
  172. function fillTable(products) {
  173. if (products.length == 0) {
  174. $('#viewCart').empty();
  175. $('#viewCart').text('No products found.')
  176. }
  177. else {
  178. let tbody = $('<tbody>');
  179. for (let prd of products) {
  180. let prcBtn = $('<button>').text("Discard");
  181. prcBtn.click(x => discardProduct(prd._id));
  182. tbody.append($('<tr>')
  183. .append($(`<td>`).text(prd.name))
  184. .append($(`<td>`).text(prd.description))
  185. .append($('<td>').text(prd.quantity))
  186. .append($(`<td>`).text(prd.totalPrice.toFixed(2)))
  187. .append($('<td>').append(prcBtn)));
  188. }
  189.  
  190. table.append(tbody);
  191. $('#viewCart').empty();
  192. $('#viewCart').append(table);
  193. }
  194. }
  195. showView('viewCart');
  196. }
  197.  
  198. function purchaseProduct(id) {
  199.  
  200.  
  201. let cartUrl = kinveyBaseUrl + "appdata/" + kinveyAppKey + "/shoppingCart";
  202.  
  203. $.ajax({
  204. method: "GET",
  205. url: cartUrl,
  206. headers: getKinveyUserAuthHeaders(),
  207. success: successGet,
  208. error: handleAjaxError
  209.  
  210. });
  211.  
  212. function successGet(data){
  213. console.log("Got the whole cart");
  214. console.log(data);
  215. }
  216.  
  217. data = data.filter(x => x.UserId == userId && x.ProductId == id);
  218.  
  219. if(data){
  220.  
  221. data[0].Quantity = Number(data[0].Quantity) + 1;
  222.  
  223. $.ajax({
  224. method: "PUT",
  225. url: cartUrl,
  226. headers: getKinveyUserAuthHeaders(),
  227. body: JSON.stringify(data[0])
  228. });
  229.  
  230. } else {
  231. let productData = {
  232. UserId: sessionStorage.getItem('userId'),
  233. ProductId: id,
  234. Quantity: 1
  235. };
  236.  
  237. $.ajax({
  238. method: "POST",
  239. url: cartUrl,
  240. data: productData,
  241. headers: getKinveyUserAuthHeaders(),
  242. success: purchaseSuccess,
  243. error: handleAjaxError
  244. });
  245. }
  246.  
  247. function successGet(){
  248. console.log("Got the whole cart");
  249. }
  250.  
  251. function purchaseSuccess(){
  252. showInfo('Product purchased.');
  253. }
  254.  
  255. }
  256.  
  257. function loginUser(newUser) {
  258. newUser.preventDefault();
  259. let userData = {
  260. username: $('#loginUsername').val(),
  261. password: $('#loginPasswd').val()
  262. };
  263.  
  264. $.ajax({
  265. method: "POST",
  266. url: kinveyBaseUrl + "user/" + kinveyAppKey + "/login",
  267. headers: kinveyAppAuthHeaders,
  268. data: userData,
  269. success: loginSuccess,
  270. error: handleAjaxError
  271. });
  272.  
  273. function loginSuccess(userInfo) {
  274. saveAuthInSession(userInfo);
  275. showHideMenuLinks();
  276. $('#spanMenuLoggedInUser').text("Welcome, " + sessionStorage.getItem('name') + '!');
  277. showUserHomeView();
  278. showInfo('Login successful.');
  279. }
  280. }
  281. function registerUser(newUser) {
  282. newUser.preventDefault();
  283. let userData = {
  284. username: $('#registerUsername').val(),
  285. password: $('#registerPasswd').val(),
  286. name: $('#registerName').val()
  287. };
  288. $.ajax({
  289. method: "POST",
  290. url: kinveyBaseUrl + "user/" + kinveyAppKey + "/",
  291. headers: kinveyAppAuthHeaders,
  292. data: userData,
  293. success: registerSuccess,
  294. error: handleAjaxError
  295. });
  296.  
  297. function registerSuccess(userInfo) {
  298. saveAuthInSession(userInfo);
  299. showHideMenuLinks();
  300. showUserHomeView();
  301. showInfo('User registration successful.');
  302. }
  303. }
  304.  
  305. function logoutUser() {
  306. sessionStorage.clear();
  307. $('#spanMenuLoggedInUser').empty();
  308. showHideMenuLinks();
  309. showView('viewAppHome');
  310. showInfo('Logout successful.');
  311. }
  312.  
  313.  
  314. function getKinveyUserAuthHeaders() {
  315. return {
  316. 'Authorization': "Kinvey " +
  317. sessionStorage.getItem('authToken'),
  318. };
  319. }
  320.  
  321. function saveAuthInSession(userInfo) {
  322. let userAuth = userInfo._kmd.authtoken;
  323. sessionStorage.setItem('authToken', userAuth);
  324. let userId = userInfo._id;
  325. sessionStorage.setItem('userId', userId);
  326. let username = userInfo.username;
  327. sessionStorage.setItem('username', username);
  328. let name = userInfo.name;
  329. sessionStorage.setItem('name', name);
  330. $('#loggedInUser').text(
  331. "Welcome, " + username + "!");
  332. }
  333.  
  334. function handleAjaxError(response) {
  335. let errorMsg = JSON.stringify(response);
  336. if (response.readyState === 0)
  337. errorMsg = "Cannot connect due to network error.";
  338. if (response.responseJSON &&
  339. response.responseJSON.description)
  340. errorMsg = response.responseJSON.description;
  341. showError(errorMsg);
  342. }
  343. function showInfo(message) {
  344. $('#infoBox').text(message);
  345. $('#infoBox').show();
  346. setTimeout(function () {
  347. $('#infoBox').fadeOut();
  348. }, 2000);
  349. }
  350. function showError(errorMsg) {
  351. $('#errorBox').text("Error: " + errorMsg);
  352. $('#errorBox').show();
  353. setTimeout(function () {
  354. $('#errorBox').fadeOut();
  355. }, 2000);
  356. }
  357.  
  358. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement