diff --git a/app.py b/app.py index 75b5cd2..9e92cd4 100644 --- a/app.py +++ b/app.py @@ -1,10 +1,15 @@ import os -from flask import Flask, request, json, abort +from flask import Flask, request, json, abort, jsonify, make_response from flask_cors import CORS import sentry_sdk from sentry_sdk.integrations.flask import FlaskIntegration +class InventoryError(Exception): + def __init__(self, message, item_id=None): + super().__init__(message) + self.item_id = item_id + sentry_sdk.init( dsn="https://2ba68720d38e42079b243c9c5774e05c@sentry.io/1316515", integrations=[FlaskIntegration()], @@ -37,13 +42,19 @@ def unhandled_exception(): def process_order(cart): global Inventory - tempInventory = Inventory + tempInventory = Inventory.copy() for item in cart: - if Inventory[item['id']] <= 0: - raise Exception("Not enough inventory for " + item['id']) + item_id = item['id'] + quantity = item.get('quantity', 1) + + if tempInventory[item_id] < quantity: + raise InventoryError( + f"Not enough inventory for '{item_id}'. Requested: {quantity}, Available: {tempInventory[item_id]}", + item_id + ) else: - tempInventory[item['id']] -= 1 - print 'Success: ' + item['id'] + ' was purchased, remaining stock is ' + str(tempInventory[item['id']]) + tempInventory[item_id] -= quantity + print('Success: ' + item_id + ' was purchased, remaining stock is ' + str(tempInventory[item_id])) Inventory = tempInventory @app.before_request @@ -65,11 +76,16 @@ def sentry_event_context(): @app.route('/checkout', methods=['POST']) def checkout(): + try: + order = json.loads(request.data) + print("Processing order for: " + order["email"]) + cart = order["cart"] + + process_order(cart) - order = json.loads(request.data) - print "Processing order for: " + order["email"] - cart = order["cart"] - - process_order(cart) - - return 'Success' + return jsonify(message="Order processed successfully"), 200 + except InventoryError as ie: + return make_response(jsonify(error=str(ie), itemId=ie.item_id), 400) + except Exception as e: + sentry_sdk.capture_exception(e) + return make_response(jsonify(error="An unexpected server error occurred..."), 500)