68 lines
2.2 KiB
C#
68 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.Many;
|
|
|
|
public class ImportJsonAccountsQueryHandler : IRequestHandler<ImportJsonAccountsQuery>
|
|
{
|
|
private readonly IMapper _mapper;
|
|
private readonly IUnitOfWork _unitOfWork;
|
|
private readonly ISessionUserService _sessionUserService;
|
|
|
|
public ImportJsonAccountsQueryHandler(
|
|
IMapper mapper,
|
|
IUnitOfWork unitOfWork,
|
|
ISessionUserService sessionUserService)
|
|
{
|
|
_mapper = mapper;
|
|
_unitOfWork = unitOfWork;
|
|
_sessionUserService = sessionUserService;
|
|
}
|
|
|
|
public async Task Handle(ImportJsonAccountsQuery 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 accountDtos = JsonConvert.DeserializeObject<IEnumerable<AccountJsonDto>>(json, jsonSerializerSettings);
|
|
|
|
var accounts = _mapper.ProjectTo<Account>(accountDtos.AsQueryable());
|
|
|
|
foreach (var account in accounts)
|
|
{
|
|
account.Id = Guid.NewGuid().ToString();
|
|
account.UserId = _sessionUserService.Id;
|
|
|
|
foreach (var transaction in account.Transactions)
|
|
{
|
|
transaction.Id = Guid.NewGuid().ToString();
|
|
transaction.AccountId = account.Id;
|
|
|
|
await _unitOfWork.TransactionRepository.AddOneAsync(transaction, cancellationToken);
|
|
}
|
|
|
|
await _unitOfWork.AccountRepository.AddOneAsync(account, cancellationToken);
|
|
}
|
|
|
|
await _unitOfWork.SaveAsync(cancellationToken);
|
|
}
|
|
}
|