diff --git a/app.py b/app.py index 75b5cd2..09ef2bb 100644 --- a/app.py +++ b/app.py @@ -35,15 +35,32 @@ def unhandled_exception(): 'hammer': 1 } +product_mapping = { + 3: "wrench", + 4: "nails", + 5: "hammer" +} + def process_order(cart): global Inventory - tempInventory = Inventory - for item in cart: - if Inventory[item['id']] <= 0: - raise Exception("Not enough inventory for " + item['id']) + tempInventory = Inventory.copy() + quantities = cart["quantities"] + + for item in cart["items"]: + product_id = item['id'] + product_name = product_mapping.get(product_id) + + if not product_name or product_name not in tempInventory: + raise Exception("Product not found: " + str(product_id)) + + requested_quantity = int(quantities.get(str(product_id), 0)) + + if tempInventory[product_name] < requested_quantity: + raise Exception("Not enough inventory for " + product_name) else: - tempInventory[item['id']] -= 1 - print 'Success: ' + item['id'] + ' was purchased, remaining stock is ' + str(tempInventory[item['id']]) + tempInventory[product_name] -= requested_quantity + print(f"Success: {requested_quantity} of {product_name} were purchased, remaining stock is {tempInventory[product_name]}") + Inventory = tempInventory @app.before_request @@ -65,11 +82,9 @@ def sentry_event_context(): @app.route('/checkout', methods=['POST']) def checkout(): - order = json.loads(request.data) - print "Processing order for: " + order["email"] - cart = order["cart"] + print("Processing order for: " + order.get("email", "Unknown")) - process_order(cart) + process_order(order) return 'Success'