45 lines
1.6 KiB
C#
45 lines
1.6 KiB
C#
using AutoMapper;
|
|
using MediatR;
|
|
using ExpenseTracker.Application.Common.Interfaces.Repositories;
|
|
using ExpenseTracker.Domain.Entities;
|
|
using ExpenseTracker.Domain.Enums;
|
|
using ExpenseTracker.Application.Common.Interfaces.Services;
|
|
using ExpenseTracker.Application.Common.Interfaces;
|
|
|
|
namespace ExpenseTracker.Application.Transactions.Commands.Create;
|
|
|
|
public class CreateTransactionCommandHandler : IRequestHandler<CreateTransactionCommand, TransactionDto>
|
|
{
|
|
private readonly IMapper _mapper;
|
|
private readonly IUnitOfWork _unitOfWork;
|
|
private readonly ISessionUserService _sessionUserService;
|
|
|
|
public CreateTransactionCommandHandler(IMapper mapper, IUnitOfWork unitOfWork, ISessionUserService sessionUserService)
|
|
{
|
|
_mapper = mapper;
|
|
_unitOfWork = unitOfWork;
|
|
_sessionUserService = sessionUserService;
|
|
}
|
|
|
|
public async Task<TransactionDto> Handle(CreateTransactionCommand request, CancellationToken cancellationToken)
|
|
{
|
|
// TODO: Add UserId validation. Throw NotFoundException when there is no user with given UserId
|
|
|
|
var newEntity = new Transaction()
|
|
{
|
|
Id = Guid.NewGuid().ToString(),
|
|
Amount = request.Amount,
|
|
Category = Category.FromName(request.Category),
|
|
Time = request.Time,
|
|
AccountId = request.AccountId,
|
|
Description = request.Description,
|
|
};
|
|
|
|
var databaseEntity = await _unitOfWork.TransactionRepository.AddOneAsync(newEntity, cancellationToken);
|
|
|
|
await _unitOfWork.SaveAsync(cancellationToken);
|
|
|
|
return _mapper.Map<TransactionDto>(databaseEntity);
|
|
}
|
|
}
|