36 lines
1.5 KiB
C#
36 lines
1.5 KiB
C#
using LiteCharms.Features.Shop.Postgres;
|
|
|
|
namespace LiteCharms.Features.Quotes.Commands.Handlers;
|
|
|
|
public class AssignQuoteToOrderCommandHandler(IDbContextFactory<ShopDbContext> contextFactory) : IRequestHandler<AssignQuoteToOrderCommand, Result>
|
|
{
|
|
public async ValueTask<Result> Handle(AssignQuoteToOrderCommand request, CancellationToken cancellationToken)
|
|
{
|
|
try
|
|
{
|
|
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
|
|
|
var order = await context.Orders.FirstOrDefaultAsync(o => o.Id == request.OrderId, cancellationToken);
|
|
|
|
if (order is null)
|
|
return Result.Fail(new Error($"Order with id {request.OrderId} not found"));
|
|
|
|
if(!await context.Quotes.AnyAsync(q => q.Id == request.OrderId, cancellationToken))
|
|
return Result.Fail(new Error($"Quote with id {request.QuoteId} not found"));
|
|
|
|
if(order.QuoteId == request.QuoteId)
|
|
return Result.Fail(new Error($"Quote with id {request.QuoteId} is already assigned to order with id {request.OrderId}"));
|
|
|
|
order.QuoteId = request.QuoteId;
|
|
|
|
return await context.SaveChangesAsync(cancellationToken) > 0
|
|
? Result.Ok()
|
|
: Result.Fail(new Error($"Failed to assign quote with id {request.QuoteId} to order with id {request.OrderId}"));
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
return Result.Fail(new Error(ex.Message).CausedBy(ex));
|
|
}
|
|
}
|
|
}
|