enterPurchase.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. window.enterPurchaseObj = {
  2. isPopulated: false,
  3. display: function(){
  4. clearScreen();
  5. document.querySelector("#enterPurchaseAction").style.display = "flex";
  6. if(!this.isPopulated){
  7. this.populateTable();
  8. }
  9. },
  10. populateTable: function(){
  11. let tbody = document.querySelector("#enterPurchaseStrand tbody");
  12. while(tbody.children.length > 0){
  13. tbody.removeChild(tbody.firstChild);
  14. }
  15. for(let item of merchant.inventory){
  16. let row = document.createElement("tr");
  17. row._id = item.ingredient._id;
  18. tbody.appendChild(row);
  19. let nameTd = document.createElement("td");
  20. nameTd.innerText = item.ingredient.name;
  21. row.appendChild(nameTd);
  22. let quantityTd = document.createElement("td");
  23. row.appendChild(quantityTd);
  24. let quantityInput = document.createElement("input");
  25. quantityInput.type = "number";
  26. quantityInput.step = "1";
  27. quantityInput.value = 0;
  28. quantityTd.appendChild(quantityInput);
  29. }
  30. },
  31. submit: function(){
  32. let tbody = document.querySelector("#enterPurchaseStrand tbody");
  33. let purchases = [];
  34. for(let row of tbody.children){
  35. let quantity = row.children[1].children[0].value;
  36. if(validator.ingredient.quantity(quantity)){
  37. if(quantity > 0){
  38. let purchase = {
  39. ingredient: row._id,
  40. quantity: row.children[1].children[0].value
  41. }
  42. purchases.push(purchase);
  43. }else if(quantity < 0){
  44. banner.createError("Cannot contain negative numbers");
  45. return;
  46. }
  47. }else{
  48. return;
  49. }
  50. }
  51. axios.post("/purchases/create", purchases)
  52. .then((response)=>{
  53. if(typeof(response.data) === "string"){
  54. banner.createError(response.data);
  55. }else{
  56. for(let purchase of purchases){
  57. let merchantIngredient = merchant.inventory.find(i => i.ingredient._id === purchase.ingredient);
  58. merchantIngredient.quantity = Number(merchantIngredient.quantity) + Number(purchase.quantity);
  59. }
  60. inventoryObj.isPopulated = false;
  61. this.isPopulated = false;
  62. inventoryObj.display();
  63. }
  64. })
  65. .catch((err)=>{
  66. console.log(err);
  67. banner.createError("Something went wrong and changes could not be made");
  68. });
  69. }
  70. }