newTransaction.js 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. module.exports = {
  2. display: function(){
  3. let recipeList = document.getElementById("newTransactionRecipes");
  4. let template = document.getElementById("createTransaction").content.children[0];
  5. while(recipeList.children.length > 0){
  6. recipeList.removeChild(recipeList.firstChild);
  7. }
  8. for(let i = 0; i < merchant.recipes.length; i++){
  9. let recipeDiv = template.cloneNode(true);
  10. recipeDiv.recipe = merchant.recipes[i];
  11. recipeList.appendChild(recipeDiv);
  12. recipeDiv.children[0].innerText = merchant.recipes[i].name;
  13. }
  14. openSidebar(document.getElementById("newTransaction"));
  15. },
  16. submit: function(){
  17. let recipeDivs = document.getElementById("newTransactionRecipes");
  18. let date = document.getElementById("newTransactionDate").valueAsDate;
  19. if(date > new Date()){
  20. banner.createError("CANNOT HAVE A DATE IN THE FUTURE");
  21. return;
  22. }
  23. let newTransaction = {
  24. date: date,
  25. recipes: []
  26. };
  27. for(let i = 0; i < recipeDivs.children.length; i++){
  28. let quantity = recipeDivs.children[i].children[1].value;
  29. if(quantity !== "" && quantity > 0){
  30. newTransaction.recipes.push({
  31. recipe: recipeDivs.children[i].recipe.id,
  32. quantity: quantity
  33. });
  34. }else if(quantity < 0){
  35. banner.createError("CANNOT HAVE NEGATIVE VALUES");
  36. return;
  37. }
  38. }
  39. if(newTransaction.recipes.length > 0){
  40. let loader = document.getElementById("loaderContainer");
  41. loader.style.display = "flex";
  42. fetch("/transaction/create", {
  43. method: "post",
  44. headers: {
  45. "Content-Type": "application/json;charset=utf-8"
  46. },
  47. body: JSON.stringify(newTransaction)
  48. })
  49. .then(response => response.json())
  50. .then((response)=>{
  51. if(typeof(response) === "string"){
  52. banner.createError(response);
  53. }else{
  54. let transaction = new Transaction(
  55. response._id,
  56. response.date,
  57. response.recipes,
  58. merchant
  59. );
  60. merchant.editTransactions(transaction);
  61. banner.createNotification("NEW TRANSACTION CREATED");
  62. }
  63. })
  64. .catch((err)=>{
  65. banner.createError("SOMETHING WENT WRONG. PLEASE REFRESH THE PAGE");
  66. })
  67. .finally(()=>{
  68. loader.style.display = "none";
  69. });
  70. }
  71. }
  72. }