Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
abouchrit opened this issue Jun 17, 2023 · 0 comments

Comments

@abouchrit
Copy link

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();
}
@abouchrit abouchrit changed the title Bug in StoreCartItems Method in the Server's CartService.cs @patrickgod Bug in StoreCartItems Method in the Server's CartService.cs Jun 17, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant