Search code examples
node.jsmongodbalgorithmbusiness-logic

How to calculate limit order per day in nodejs


I have a business scenario where Limit order per day is necessary. For eg,

product schema: productName, limitPerDay=2,....

A owner can set limitPerDay for a product.

Users can either order the product or reserve the products(for 1 hour). If the limit has been exceeded, users will be able to see LIMIT EXCEEDED label on product listings.

For ex. there are three users Adam, Bob and Tom . Adam reserves the product LAPTOP, Bob orders the product LAPTOP. Tom will not be able to reserve or order LAPTOP because the limit has been exceeded (TOM can see the product but will see the label LIMIT EXCEEDED and limit will open after 1 hours because Adam has reserved for 1 hour).

Scenario 1: One hour passes, Adam did not make purchase and his reservation is now over. TOM can see the availability and orders the product.

Scenario 2: Adam makes a purchase from it reserved list, now ADAM and BOB both have ordered. TOM will have to wait for next 24 hours to purchase the product.

How do I store these purchase and reservations to enable the logic which I would be needing. I am using MongoDb to store data


Solution

  • Most website doesn't reflect real-time changes. Usually user has to do refresh page, In order to see recent changes.

    Our database schema would be:

    {
        _id: <product_id>,
        orders: [<user_id>],
        order_count: number,
        reserves: [reserved],
        reserves_count: number,
    }
    
    reserved {
        _id : <user_id>,
        time: Data,
    }
    

    So when user request the product, then server need to do check up,

    • currentTime - product.reserves.reserver.time = if more then 1 hour then update reserves_count
    • limitedOrderRequest - product.order_count + product.reserves_count = 0; user has to wait 24h...

    When updating document:

    • limitedOrderRequest - product.order_count = if 0 then user can't order
    • limitedreserveRequest - product.reserves_count = if 0 then user can't reserve.