48 lines
1.6 KiB
C#
48 lines
1.6 KiB
C#
using AutoMapper;
|
|
using MediatR;
|
|
using ExpenseTracker.Application.Common.Exceptions;
|
|
using ExpenseTracker.Application.Common.Interfaces;
|
|
using ExpenseTracker.Application.Common.Interfaces.Repositories;
|
|
using ExpenseTracker.Domain.Entities;
|
|
using ExpenseTracker.Domain.Enums;
|
|
|
|
namespace ExpenseTracker.Application.Transactions.Commands.Update;
|
|
|
|
public class UpdateTransactionCommandHandler : IRequestHandler<UpdateTransactionCommand, TransactionDto>
|
|
{
|
|
private readonly IMapper _mapper;
|
|
private readonly IUnitOfWork _unitOfWork;
|
|
|
|
public UpdateTransactionCommandHandler(IMapper mapper, IUnitOfWork unitOfWork)
|
|
{
|
|
_mapper = mapper;
|
|
_unitOfWork = unitOfWork;
|
|
}
|
|
|
|
public async Task<TransactionDto> Handle(UpdateTransactionCommand request, CancellationToken cancellationToken)
|
|
{
|
|
var databaseEntity = _unitOfWork.TransactionRepository.Queryable.FirstOrDefault(e => e.Id == request.Id);
|
|
|
|
if (databaseEntity == null)
|
|
{
|
|
throw new NotFoundException();
|
|
}
|
|
|
|
var updatedEntity = new Transaction()
|
|
{
|
|
Id = request.Id,
|
|
Amount = request.Amount ?? databaseEntity.Amount,
|
|
Category = Category.FromName(request.Category) ?? databaseEntity.Category,
|
|
Time = request.Time ?? databaseEntity.Time,
|
|
Description = request.Description,
|
|
AccountId = request.AccountId
|
|
};
|
|
|
|
databaseEntity = await _unitOfWork.TransactionRepository.UpdateOneAsync(updatedEntity, cancellationToken);
|
|
|
|
await _unitOfWork.SaveAsync(cancellationToken);
|
|
|
|
return _mapper.Map<TransactionDto>(databaseEntity);
|
|
}
|
|
}
|