newTransaction.js 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. let newTransaction = {
  2. display: function(Transaction){
  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. document.getElementById("submitNewTransaction").onclick = ()=>{this.submit(Transaction)};
  15. },
  16. submit: function(Transaction){
  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 data = {
  24. date: date,
  25. recipes: [],
  26. ingredientUpdates: {}
  27. };
  28. for(let i = 0; i < recipeDivs.children.length; i++){
  29. let quantity = recipeDivs.children[i].children[1].value;
  30. const recipe = recipeDivs.children[i].recipe;
  31. if(quantity !== "" && quantity > 0){
  32. data.recipes.push({
  33. recipe: recipe.id,
  34. quantity: quantity
  35. });
  36. }else if(quantity < 0){
  37. banner.createError("CANNOT HAVE NEGATIVE VALUES");
  38. return;
  39. }
  40. }
  41. if(data.recipes.length > 0){
  42. let loader = document.getElementById("loaderContainer");
  43. loader.style.display = "flex";
  44. fetch("/transaction/create", {
  45. method: "post",
  46. headers: {
  47. "Content-Type": "application/json;charset=utf-8"
  48. },
  49. body: JSON.stringify(data)
  50. })
  51. .then(response => response.json())
  52. .then((response)=>{
  53. if(typeof(response) === "string"){
  54. banner.createError(response);
  55. }else{
  56. const transaction = new Transaction(
  57. response._id,
  58. response.date,
  59. response.recipes,
  60. merchant
  61. );
  62. merchant.addTransaction(transaction);
  63. banner.createNotification("NEW TRANSACTION CREATED, INGREDIENTS UPDATED ACCORDINGLY");
  64. }
  65. })
  66. .catch((err)=>{
  67. banner.createError("SOMETHING WENT WRONG. PLEASE REFRESH THE PAGE");
  68. })
  69. .finally(()=>{
  70. loader.style.display = "none";
  71. });
  72. }
  73. }
  74. }
  75. module.exports = newTransaction;