Skip to content

Instantly share code, notes, and snippets.

@dcomartin
Created November 30, 2023 16:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dcomartin/d10a7183d70e2e43bd2418c8b6e061ac to your computer and use it in GitHub Desktop.
Save dcomartin/d10a7183d70e2e43bd2418c8b6e061ac to your computer and use it in GitHub Desktop.
public class CreateTransactionCommandHandler : IRequestHandler<CreateTransactionCommand, int>
{
private readonly IUnitOfWork _unitOfWork;
public CreateTransactionCommandHandler(IUnitOfWork unitOfWork)
=> _unitOfWork = unitOfWork;
public async Task<int> Handle(CreateTransactionCommand request, CancellationToken cancellationToken)
{
var partner = await _unitOfWork.Partners.GetByIdAsync(request.PartnerId)
?? throw new InputValidationException((nameof(request.PartnerId), $"Partner (id: {request.PartnerId}) was not found."));
// Try not to confuse DB transaction with the "Transaction" domain entity. :)
await _unitOfWork.BeginTransactionAsync();
int createdTransactionId = 0;
try
{
var orderedProductIds = request.TransactionLines.Select(x => x.ProductId).Distinct();
var orderedProducts = await _unitOfWork.Products.GetFiltered(x => orderedProductIds.Contains(x.Id));
var validLines = request.TransactionLines.Select(line =>
(
product: orderedProducts.FirstOrDefault(p => p.Id == line.ProductId)
?? throw new InputValidationException((nameof(line.ProductId), $"Product (id: {line.ProductId}) was not found.")),
qty: line.ProductQuantity
)
);
var transaction = request.TransactionType switch
{
TransactionType.Sales => partner.SellTo(validLines),
TransactionType.Procurement => partner.ProcureFrom(validLines),
_ => throw new InvalidEnumArgumentException($"No operation is defined for {nameof(TransactionType)} of '{request.TransactionType}'.")
};
await _unitOfWork.SaveChanges();
createdTransactionId = transaction.Id;
}
catch
{
await _unitOfWork.RollbackTransactionAsync();
throw;
}
await _unitOfWork.CommitTransactionAsync();
return createdTransactionId;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment