Files
CMS/src/CMSMicroservice.Application/UserCartsCQ/Commands/ClearCart/ClearCartCommandHandler.cs
masoodafar-web f0f48118e7 Add validators and services for Product Galleries and Product Tags
- Implemented Create, Delete, Get, and Update validators for Product Galleries.
- Added Create, Delete, Get, and Update validators for Product Tags.
- Created service classes for handling Discount Categories, Discount Orders, Discount Products, Discount Shopping Cart, Product Categories, Product Galleries, and Product Tags.
- Each service class integrates with CQRS for command and query handling.
- Established mapping profiles for Product Galleries.
2025-12-04 02:40:49 +03:30

53 lines
1.7 KiB
C#

using CMSMicroservice.Domain.Events;
namespace CMSMicroservice.Application.UserCartsCQ.Commands.ClearCart;
public class ClearCartCommandHandler : IRequestHandler<ClearCartCommand, ClearCartResponseDto>
{
private readonly IApplicationDbContext _context;
public ClearCartCommandHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<ClearCartResponseDto> Handle(ClearCartCommand request, CancellationToken cancellationToken)
{
// پیدا کردن تمام آیتم‌های سبد خرید کاربر
var cartItems = await _context.UserCarts
.Where(c => c.UserId == request.UserId)
.ToListAsync(cancellationToken);
if (!cartItems.Any())
{
return new ClearCartResponseDto
{
UserId = request.UserId,
RemovedItemsCount = 0,
Message = "سبد خرید خالی است"
};
}
var itemsCount = cartItems.Count;
// حذف تمام آیتم‌ها
_context.UserCarts.RemoveRange(cartItems);
// ثبت Event
// می‌تونیم یک Event برای هر آیتم یا یک Event کلی بفرستیم
foreach (var item in cartItems)
{
item.AddDomainEvent(new ClearCartEvent(item));
}
await _context.SaveChangesAsync(cancellationToken);
return new ClearCartResponseDto
{
UserId = request.UserId,
RemovedItemsCount = itemsCount,
Message = $"{itemsCount} آیتم از سبد خرید حذف شد"
};
}
}