feat: Add ClearCart command and response, implement CancelOrder command with validation, and enhance DeliveryStatus and User models
This commit is contained in:
@@ -0,0 +1,52 @@
|
||||
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.UserCartss
|
||||
.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.UserCartss.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} آیتم از سبد خرید حذف شد"
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user