What is the process for deducting the ordered quantity from the available quantity once an order is confirmed

Although I'm not a fan of hard coding, I've been struggling to find a solution to my problem and some explanations are just not clicking for me.

The issue at hand involves three data products in the cart, product details, and placed order data from firestore. My goal is to decrease the available quantity from the product details based on the products in the cart, and then 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
        }
      ]
        };

Answer №1

If you want to ensure accurate order processing, make sure to follow these steps:

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

It's important to double-check the availability of products before subtracting quantities from the inventory. Make sure that items in the cart have sufficient stock levels to fulfill the order.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can you explain the significance of "=>" in a context other than function invocation?

Working my way through the freeCodeCamp JavaScript course has left me quite puzzled about arrow functions. I know how to write a function using arrow notation, like this: const myFunc = () => "value"; However, in one of the later challenges, ...

Automatically activate a button when it comes into view while scrolling

I am currently working in Joomla, which makes it challenging to create a fiddle, but here is the concept: My website displays a mosaic grid of 12 articles upon loading, along with a 'Load More' button. When this button is clicked, an additional ...

add the closing </div> tag using jquery only

Having a slight issue here, it seems that jQuery is being overly clever. Within my HTML code, I am attempting to insert this string into a div container: </div><div class="something"> You'll notice that the closing tag comes first, foll ...

Create a fresh trail underneath the overlay image

When utilizing fabric.js to draw a new path with isDrawingMode: true enabled (seen on the right side of the screenshot), I am encountering an issue where the path appears above my overlay image, which is a transparent png. https://i.stack.imgur.com/R3fGn. ...

What is the best way to save a webpage when a user clicks a button before leaving the page with Javascript

I've exhausted all my options in trying to find a way to trigger a button that saves the page upon exit, but it never seems to work. I need the event to occur even if the button is not visible at the time of the page exit. The new security protocols o ...

Ways to rearrange an object with javascript

I am looking to restructure my object by removing a nesting. How can I achieve this using JavaScript? Actual: var a = [ { clickedEvents: { 'event-element': 'a', 'event-description': & ...

Creating a div overlay triggered by the addition of a child tag

Using the Paypal zoid feature, I have a button that opens an iframe in the parent div when clicked. However, the iframe causes the other contents of the website to shift around, making it look messy. I'm wondering if there is a way to make the parent ...

Developing a Node.js system for mapping ids to sockets and back again

Managing multiple socket connections in my application is proving to be a challenge. The app functions as an HTTP server that receives posts and forwards them to a socket. When clients establish a socket connection, they send a connect message with an ID: ...

The event listener for browser.menus.onClicked is dysfunctional in Firefox

Currently, I am in the process of developing my own Firefox extension and I have encountered an issue with adding a listener to an onclick event for a context menu item. manifest.json { "manifest_version": 2, "name": "My exten ...

Creating a personalized context menu in Javascript: The ultimate guide to incorporating copy and paste features

We are developing a unique context menu for our online text editor, complete with copy/paste options. However, we encountered difficulties accessing the system clipboard from within the browser. It once seemed impossible to achieve this, as discussed in th ...

What is the best way to anticipate the vue.js created hook?

I have a vue.js application where I am facing an issue with awaiting a call to the Prismic API. The call is initiated from the created hook, but I am unsure of how to make Vue await the hook itself. Here is an example of the code: ... async created() { ...

Comparing Encrypted Passwords with Bcrypt

Encountering an issue with comparing passwords despite accurately storing the hashed password during registration. Database - MongoDB Node.js version - v18.17.0 Bcrypt version - 5.1.1 Below is my userSchema: const userSchema = new mongoose.Schema({ u ...

Scrolling to an id within dynamically loaded content using jQuery after an ajax request

After loading content via ajax, I am unable to scroll to the item, as the page remains at the top. Strangely, when I refresh the page dynamically with content caching enabled, the page scrolls to the desired target. var startPageLoader = function( pid, si ...

Using AngularJS to iterate through JSON data

I received JSON data from my Facebook account and saved it in a file called facebook.json. Next step is to retrieve and process the data from the JSON file in my controller. app.controller('Ctrl', function($scope, $http) { $http({metho ...

Implement the click event binding using classes in Angular 2

If I have the template below, how can I use TypeScript to bind a click event by class? My goal is to retrieve attributes of the clicked element. <ul> <li id="1" class="selectModal">First</li> <li id="2" class="selectModal">Seco ...

What is the predefined value for a multi-select generated by the ng-for directive in Angular?

I am having trouble setting default selected values for the multi-select. Despite trying various methods such as initializing the ngModel to bind the variable and using [selected] = "selectedSegment == 'S1'", none of them seem to be effective fo ...

What is the method for retrieving a value from my Node.js module once it has been modified by an asynchronous function?

Apologies, but as a beginner developer, I'm struggling to see how this relates directly to the questions already mentioned. I have no understanding of ajax and I'm unsure how to adapt the solutions provided to my own situation. Currently, I&apos ...

Having trouble with v-for in Vue js on vsCode?

https://i.stack.imgur.com/u3vzh.png It seems that I always encounter this issue when utilizing v-for in my projects. While I didn't face any problems with it previously, I've noticed that it has become a frequent error as of late. Why is it tha ...

Checking authentication globally using Vue.js

In the main blade file, I have the following code snippet: <script> window.App = {!! json_encode([ 'csrfToken' => csrf_token(), 'user' => Auth::user(), 'signedIn' => Auth::check() ...

How can I adjust the vertical position of Material-UI Popper element using the popper.js library?

https://i.stack.imgur.com/ZUYa4.png Utilizing a material-ui (v 4.9.5) Popper for a pop-out menu similar to the one shown above has been my recent project. The anchorElement is set as the chosen ListItem on the left side. My goal is to have the Popper alig ...