Files
components/LiteCharms.Features/Refunds/Commands/Handlers/RefundCustomerCommandHandler.cs
T
Khwezi Mngoma ff34326a53
continuous-integration/drone/pr Build is passing
Refactored database references
2026-05-09 16:58:34 +02:00

39 lines
1.7 KiB
C#

using LiteCharms.Infrastructure.Database;
namespace LiteCharms.Features.Refunds.Commands.Handlers;
public class RefundCustomerCommandHandler(IDbContextFactory<ShopDbContext> contextFactory) : IRequestHandler<RefundCustomerCommand, Result<Guid>>
{
public async ValueTask<Result<Guid>> Handle(RefundCustomerCommand request, CancellationToken cancellationToken)
{
try
{
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
if(!await context.Orders.AnyAsync(o => o.Id == request.OrderId, cancellationToken))
return Result.Fail<Guid>(new Error($"Order with Id: {request.OrderId} does not exist"));
if (!await context.Customers.AnyAsync(c => c.Id == request.CustomerId, cancellationToken))
return Result.Fail<Guid>(new Error($"Customer with Id: {request.CustomerId} does not exist"));
if(!await context.Orders.AnyAsync(o => o.Id == request.OrderId && o.CustomerId == request.CustomerId, cancellationToken))
return Result.Fail<Guid>(new Error($"Order with Id: {request.OrderId} does not belong to Customer with Id: {request.CustomerId}"));
var refund = context.OrderRefunds.Add(new Entities.OrderRefund
{
OrderId = request.OrderId,
Reason = request.Reason,
Amount = request.Amount
});
return await context.SaveChangesAsync(cancellationToken) > 0
? Result.Ok(refund.Entity.Id)
: Result.Fail<Guid>(new Error($"Failed to create refund for OrderId: {request.OrderId}"));
}
catch (Exception ex)
{
return Result.Fail<Guid>(new Error(ex.Message).CausedBy(ex));
}
}
}