72 lines
2.2 KiB
C#
72 lines
2.2 KiB
C#
using System.Text;
|
|
using AutoMapper;
|
|
using MediatR;
|
|
using Newtonsoft.Json;
|
|
using Newtonsoft.Json.Serialization;
|
|
using ExpenseTracker.Application.Common.Interfaces;
|
|
using ExpenseTracker.Application.Common.Interfaces.Services;
|
|
using ExpenseTracker.Domain.Entities;
|
|
|
|
namespace ExpenseTracker.Application.Accounts.Commands.Import.Json.One;
|
|
|
|
public class ImportJsonAccountQueryHandler : IRequestHandler<ImportJsonAccountQuery>
|
|
{
|
|
private readonly IMapper _mapper;
|
|
private readonly IUnitOfWork _unitOfWork;
|
|
private readonly ISessionUserService _sessionUserService;
|
|
|
|
public ImportJsonAccountQueryHandler(
|
|
IMapper mapper,
|
|
IUnitOfWork unitOfWork,
|
|
ISessionUserService sessionUserService)
|
|
{
|
|
_mapper = mapper;
|
|
_unitOfWork = unitOfWork;
|
|
_sessionUserService = sessionUserService;
|
|
}
|
|
|
|
public async Task Handle(ImportJsonAccountQuery request, CancellationToken cancellationToken)
|
|
{
|
|
string json;
|
|
|
|
using (var memoryStream = new MemoryStream(request.File))
|
|
{
|
|
using (var streamReader = new StreamReader(memoryStream, Encoding.UTF8))
|
|
{
|
|
json = await streamReader.ReadToEndAsync(cancellationToken);
|
|
}
|
|
}
|
|
|
|
var jsonSerializerSettings = new JsonSerializerSettings()
|
|
{
|
|
ContractResolver = new CamelCasePropertyNamesContractResolver()
|
|
};
|
|
|
|
var accountDto = JsonConvert.DeserializeObject<AccountJsonDto>(json, jsonSerializerSettings);
|
|
|
|
var account = _mapper.Map<Account>(accountDto);
|
|
|
|
account.Id = Guid.NewGuid().ToString();
|
|
account.UserId = _sessionUserService.Id;
|
|
|
|
foreach (var transaction in account.Transactions)
|
|
{
|
|
transaction.Id = Guid.NewGuid().ToString();
|
|
transaction.AccountId = account.Id;
|
|
}
|
|
|
|
var tasks = new List<Task>();
|
|
|
|
tasks.Add(_unitOfWork.AccountRepository.AddOneAsync(account, cancellationToken));
|
|
|
|
if (account.Transactions.Count() != 0)
|
|
{
|
|
tasks.Add(_unitOfWork.TransactionRepository.AddManyAsync(account.Transactions, cancellationToken));
|
|
}
|
|
|
|
await Task.WhenAll(tasks);
|
|
|
|
await _unitOfWork.SaveAsync(cancellationToken);
|
|
}
|
|
}
|