Database Reference
In-Depth Information
Modifying the quantity in the cart
Often, a user will wish to modify the quantity of a particular SKU in their cart. Our system
needs to ensure that when a user increases the quantity of an item, there is sufficient inventory.
Additionally, the carted attribute in the product collection needs to be updated to reflect the
new quantity in the cart.
Our basic approach here is the same as when adding a new line item:
1. Update the cart (optimistically assuming there is sufficient inventory).
2. Update the product collection if there is sufficient inventory .
3. Roll back the cart update if there is insufficient inventory and raise an exception.
Our code, then, looks like the following:
def
def update_quantity ( cart_id , sku , old_qty , new_qty ):
now = datetime . utcnow ()
delta_qty = new_qty - old_qty
# Make sure the cart is still active and add the line item
result = db . cart . update (
{ '_id' : cart_id , 'status' : 'active' , 'items.sku' : sku },
{ '$set' : { 'last_modified' : now },
'$inc' : { 'items.$.qty' : delta_qty }
})
iif not
not result [ 'updatedExisting' ]:
raise
raise CartInactive ()
# Update the inventory
result = db . product . update (
{ '_id' : sku ,
'carted.cart_id' : cart_id ,
'qty' : { '$gte' : delta_qty } },
{ '$inc' : { 'qty' : - delta_qty },
'$set' : { 'carted.$.qty' : new_qty , 'timestamp' : now } })
iif not
not result [ 'updatedExisting' ]:
# Roll back our cart update
db . cart . update (
{ '_id' : cart_id , 'items.sku' : sku },
{ '$inc' : { 'items.$.qty' : - delta_qty } })
raise
raise InadequateInventory ()
 
 
 
 
Search WWH ::




Custom Search