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

feat: cart quantity with dropdown #10

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 16 additions & 2 deletions BookShoppingCartMvcUI/Controllers/CartController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,13 @@ public async Task<IActionResult> GetUserCart()
return View(cart);
}

public async Task<IActionResult> GetTotalItemInCart()
public async Task<IActionResult> GetTotalItemInCart()
{
int cartItem = await _cartRepo.GetCartItemCount();
return Ok(cartItem);
}

public IActionResult Checkout()
public IActionResult Checkout()
{
return View();
}
Expand All @@ -63,5 +63,19 @@ public IActionResult OrderFailure()
return View();
}

public async Task<IActionResult> UpdateCartItem(int bookId, int qty)
{
try
{
await _cartRepo.UpdateCartQuantity(bookId, qty);
}
catch (Exception ex)
{
// log error here
TempData["errorMessage"] = "Error on updating cart item";
}
return RedirectToAction(nameof(GetUserCart));
}

}
}
58 changes: 50 additions & 8 deletions BookShoppingCartMvcUI/Repositories/CartRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ public async Task<int> GetCartItemCount(string userId = "")
var data = await (from cart in _db.ShoppingCarts
join cartDetail in _db.CartDetails
on cart.Id equals cartDetail.ShoppingCartId
where cart.UserId==userId // updated line
where cart.UserId == userId // updated line
select new { cartDetail.Id }
).ToListAsync();
return data.Count;
Expand Down Expand Up @@ -155,17 +155,17 @@ public async Task<bool> DoCheckout(CheckoutModel model)
{
UserId = userId,
CreateDate = DateTime.UtcNow,
Name=model.Name,
Email=model.Email,
MobileNumber=model.MobileNumber,
PaymentMethod=model.PaymentMethod,
Address=model.Address,
IsPaid=false,
Name = model.Name,
Email = model.Email,
MobileNumber = model.MobileNumber,
PaymentMethod = model.PaymentMethod,
Address = model.Address,
IsPaid = false,
OrderStatusId = pendingRecord.Id
};
_db.Orders.Add(order);
_db.SaveChanges();
foreach(var item in cartDetail)
foreach (var item in cartDetail)
{
var orderDetail = new OrderDetail
{
Expand Down Expand Up @@ -213,6 +213,48 @@ private string GetUserId()
return userId;
}

public async Task UpdateCartQuantity(int bookId, int qty)
{
if (qty < 1)
{
throw new ArgumentException("Quantity should be greater than 0", nameof(qty));
}
string userId = GetUserId();
if (string.IsNullOrEmpty(userId))
{
throw new UnauthorizedAccessException("User is not logged-in");
}
// var cart = await GetCart(userId);
// if (cart is null)
// {
// throw new InvalidOperationException("Cart does not exists");
// }
// var cartItem = _db.CartDetails
// .FirstOrDefault(a => a.ShoppingCartId == cart.Id && a.BookId == bookId);
// if (cartItem == null)
// {
// throw new InvalidOperationException("Cart item can not be null");
// }

var cart = _db.ShoppingCarts
.Include(c => c.CartDetails)
.FirstOrDefault(a => a.UserId == userId);
if (cart == null)
{
throw new InvalidOperationException("Cart does not exist.");
}

var cartItem = cart.CartDetails.FirstOrDefault(item => item.BookId == bookId);
if (cartItem == null)
{
throw new InvalidOperationException("Cart item can not be null");
}

cartItem.Quantity = qty;

await _db.SaveChangesAsync();
}


}
}
1 change: 1 addition & 0 deletions BookShoppingCartMvcUI/Repositories/ICartRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,6 @@ public interface ICartRepository
Task<int> GetCartItemCount(string userId = "");
Task<ShoppingCart> GetCart(string userId);
Task<bool> DoCheckout(CheckoutModel model);
Task UpdateCartQuantity(int bookId, int qty);
}
}
37 changes: 35 additions & 2 deletions BookShoppingCartMvcUI/Views/Cart/GetUserCart.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
ViewData["Title"] = "GetUserCart";
}


<div style="width:90%;margin:auto" class="mt-2">
@if (Model != null && Model.CartDetails != null && Model.CartDetails.Count > 0)
{
Expand Down Expand Up @@ -35,8 +36,21 @@
<td>@item.Book.Price X @item.Quantity</td>
<td>@(item.Book.Price * item.Quantity)</td>
<td>
<select class="form-control quantity-selector" data-book-id="@item.BookId">
@for(int q=1;q<10;q++)
{
@if(item.Quantity==q)
{
<option selected value="@q">@q</option>
}
else
{
<option value="@q">@q</option>
}
}
</select>
@* Increase Quantity button should be invisible if not enough stock*@
@if (item.Quantity < item.Book.Stock.Quantity)
@* @if (item.Quantity < item.Book.Stock.Quantity)
{
<a class="btn btn-info" href="/Cart/AddItem?bookId=@item.BookId&&redirect=1">+</a>
}
Expand All @@ -45,7 +59,7 @@
<span style="border: 1px solid;padding: 8px 8px;color: red;border-radius: 5px;margin-right:4px">Out of stock </span>
}
@* Decrement button *@
<a class="btn btn-info" href="/cart/removeitem?bookid=@item.BookId">-</a>
@*<a class="btn btn-info" href="/cart/removeitem?bookid=@item.BookId">-</a> *@
</td>
</tr>
}
Expand All @@ -67,3 +81,22 @@
}
</div>

<script>
document.addEventListener('DOMContentLoaded', (event) => {
const qtySelectors = document.querySelectorAll('.quantity-selector');
qtySelectors.forEach(
selectElement=>{
console.log(selectElement);
selectElement.addEventListener('change',function(){
let selectedQuantity=this.value;
let bookId=this.getAttribute('data-book-id');
if(selectedQuantity && bookId)
{
window.location.href=`/Cart/UpdateCartItem?bookId=${bookId}&qty=${selectedQuantity}`;
}
})
}
)

});
</script>