Skip to content

@patrickgod Bug in StoreCartItems Method in the Server's CartService.cs  #5

Description

@abouchrit

Issue:

Assume that a user, let us call it USER_A, has a product P with a quantity x in its stored shoping cart.
Immagine that USER_A logged out from the session and went to the cart page. The current shopping list will be empty as expected.
Now, the user decided to add another product P with quantity z then he rememberd to log in. The current implementation will override the quantity of product P to z quantity.

Suggestion:

I belive that the quantity of product P should be the sum of (z+x). To achive that I implemented the StoredCartItems as below.
Code:

public async Task<ServiceResponse<List<CartProductResponse>>> StoreCartItems(List<CartItem> cartItems)
{
	cartItems.ForEach(cartItem => cartItem.UserId = GetUserId());
	// Get Stored Cart Items for the User
	var cartItemsFromDB = await _context.CartItems
		.Where(ci => ci.UserId == GetUserId())
		.ToListAsync();

	// If the locally stored cartItem is equal to the DB stored items then update quantity
	// otherwise add the cartItem to the DB
	foreach (var cartItem in cartItems)
	{
		var sameItem = cartItemsFromDB.Find(dbItem => dbItem.ProductId == cartItem.ProductId
		&& dbItem.ProductTypeId == cartItem.ProductTypeId);
		if (sameItem != null){
			sameItem.Quantity += cartItem.Quantity;
			// Update Existing item quantity
			_context.CartItems.Update(sameItem);
		}
		else
		{
			// Add the new item to the DB
			_context.CartItems.Add(cartItem);
		}
	}

	await _context.SaveChangesAsync();
	return await GetDbCartProducts();
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions