83f51c6a23
Added shopping cart and items Added quotes Refactored relatinoships Migrated changes Refactored cqrs commands and queries Refactored mappings
39 lines
1.7 KiB
C#
39 lines
1.7 KiB
C#
using LiteCharms.Infrastructure.Database;
|
|
|
|
namespace LiteCharms.Features.Refunds.Commands.Handlers;
|
|
|
|
public class RefundCustomerCommandHandler(IDbContextFactory<LeadGeneratorDbContext> 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));
|
|
}
|
|
}
|
|
}
|