How to Subtract available quantity from ordered quantity when order confirmed?

Viewed 65

First of all, I am not really into hard coding and such, I really did try to search for a solution to my problem but I am not getting some of the explanation.

I'm having three data products in the cart, product details, and placed Ordered data from firestore. I need to reduce the available quantity from product details from the product in the cart data and update the available quantity in the firestore.

Product in the cart data:

var  Cart= [{
  ProdName : "Smartphone",
  ProdID  : "0n7TZQrgpbfs8hPDKc7n",
  ProductQuantity : 2,
  ProductPrice  : 1500
},{
  ProdName : "Charger",
  ProdID  : "11VOxRvH2dc8cxyR4AYG",
  ProductQuantity : 1,
  ProductPrice  : 600
}];

Product details data

  var  Products= [{
      Name : "Smartphone",
      ID  : "0n7TZQrgpbfs8hPDKc7n",
      AvailableQuantity : 100,
      Price  : 1500,
      Category : "Tech"
    },{
      Name : "Charger",
      ID  : "11VOxRvH2dc8cxyR4AYG",
      AvailableQuantity : 150,
      Price  : 600,
      Category : "Tech"
    }];

placed order Data

  var  Order= {
      UserName : "Rakesh",
      UserID  : "CcojGJPh3mIyoCZmParw",
      OrderID :"H2Fbh3jTQ2XL7B9ttXBz",
      UserPhone : 9840184150,
      PlacedDate: "date",
      ProductsPlaced : [
       {
        ProdName : "Smartphone",
        ProdID  : "0n7TZQrgpbfs8hPDKc7n",
        ProductQuantity : 2,
        ProductPrice  : 1500
        },{
        ProdName : "Charger",
        ProdID  : "11VOxRvH2dc8cxyR4AYG",
        ProductQuantity : 1,
        ProductPrice  : 600
        }
      ]
        };
1 Answers

Upon checking out you would want this:

Order.ProductsPlaced.forEach( i => { 
  console.log(i); 
  var _idx = Products.findIndex( p => p.ID === i.ProdID); 
  if (_idx < 0) {
    console.log("Index Not Found"); 
    return; 
  } 
  Products[_idx].AvailableQuantity =  Products[_idx].AvailableQuantity - i.ProductQuantity;
});

Because of the way you are doing it, you need to do a lookup on the product IDs to find the right product and then do subtraction. This has no logic for items which you put in cart but have less available than what is needed. So take that into account.

Related