newTransaction.js 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. controller.openStrand("transactions");
  64. banner.createNotification("TRANSACTION CREATED");
  65. }
  66. })
  67. .catch((err)=>{
  68. banner.createError("SOMETHING WENT WRONG. PLEASE REFRESH THE PAGE");
  69. })
  70. .finally(()=>{
  71. loader.style.display = "none";
  72. });
  73. }
  74. }
  75. }
  76. module.exports = newTransaction;