Implemented shopping carts functionality elements

This commit is contained in:
Khwezi Mngoma
2026-05-06 10:48:02 +02:00
parent 83f51c6a23
commit 4321b03735
13 changed files with 341 additions and 5 deletions
@@ -0,0 +1,32 @@
using LiteCharms.Infrastructure.Database;
namespace LiteCharms.Features.ShoppingCarts.Commands.Handlers;
public class EmptyShoppingCartCommandHandler(IDbContextFactory<LeadGeneratorDbContext> contextFactory) : IRequestHandler<EmptyShoppingCartCommand, Result>
{
public async ValueTask<Result> Handle(EmptyShoppingCartCommand request, CancellationToken cancellationToken)
{
try
{
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
if (!await context.ShoppingCarts.AnyAsync(c => c.Id == request.ShoppingCartId, cancellationToken))
return Result.Fail($"Shopping could not be found with id {request.ShoppingCartId}");
if (await context.ShoppingCartItems.CountAsync(i => i.ShoppingCartId == request.ShoppingCartId, cancellationToken) == 0)
return Result.Ok();
var cartItems = await context.ShoppingCartItems.Where(i => i.ShoppingCartId == request.ShoppingCartId).ToListAsync(cancellationToken);
context.RemoveRange(cartItems);
return await context.SaveChangesAsync(cancellationToken) > 0
? Result.Ok()
: Result.Fail($"Could not empty cart with id {request.ShoppingCartId}");
}
catch (Exception ex)
{
return Result.Fail(new Error(ex.Message).CausedBy(ex));
}
}
}