Skip to content

Commit

Permalink
Merge pull request #76 from anion0278/dev
Browse files Browse the repository at this point in the history
Dev
  • Loading branch information
anion0278 authored Apr 3, 2024
2 parents 04022f0 + cea38af commit 0b9394f
Show file tree
Hide file tree
Showing 60 changed files with 2,498 additions and 280 deletions.
6 changes: 4 additions & 2 deletions Mapp.BusinessLogic.Invoices.Tests/IntegrationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,12 @@
using Moq;
using VerifyXunit;
using Xunit;
using Xunit.Categories;

namespace Mapp.BusinessLogic.Invoices.Tests
{
[UsesVerify]
[IntegrationTest]
public class IntegrationTests: VerifyBase
{
// TODO add multi-file import test
Expand Down Expand Up @@ -82,7 +84,7 @@ private async Task IntegrationTestBase(string testCaseDataDirName, int startingO

ApplicationConstants.Rounding = 2; // TODO solve by intoducing settings context

var jsonManager = new JsonManager();
var jsonManager = new JsonManager(configMock.Object, new FileManager());
var invoiceXmlXmlManager = new InvoicesXmlManager(Mock.Of<IDialogService>(), configMock.Object) ;
var currencyLoader = new CsvLoader(configMock.Object);
var autocompleteDataLoader = new AutocompleteDataLoader(jsonManager, configMock.Object);
Expand Down Expand Up @@ -114,6 +116,6 @@ private async Task IntegrationTestBase(string testCaseDataDirName, int startingO
//Assert.Equal(expectedResult, result);
}

public IntegrationTests(): base(){ }
public IntegrationTests() : base() { }
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
Expand All @@ -16,6 +16,7 @@
<PackageReference Include="System.Text.Encoding.CodePages" Version="5.0.0" />
<PackageReference Include="Verify.Xunit" Version="16.3.6" />
<PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="xunit.categories" Version="2.0.8" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
<inv:date>2021-10-20</inv:date>
<inv:dateTax>2021-10-25</inv:dateTax>
<inv:dateAccounting>2021-10-20</inv:dateAccounting>
<inv:dateDue>2021-10-23</inv:dateDue>
<inv:dateDue>2022-10-23</inv:dateDue>
<inv:accounting>
<typ:ids>3Fv</typ:ids>
</inv:accounting>
Expand Down
51 changes: 26 additions & 25 deletions Mapp.BusinessLogic.Invoices/Transactions/GpcGenerator.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mapp.Common;
using Mapp.DataAccess;

namespace Mapp.BusinessLogic.Transactions
{
Expand All @@ -16,45 +18,44 @@ public class GpcGenerator : IGpcGenerator
"0740000002001353907Czech Goods s.r.o. 01111900000013280900+00000016514842+000000461730770000000494070190011{0}FIO ";

private string _transactionBase = "07500000020013539{0}000000000000000000000000000000000{1}{2}{3}00000000000000000000000000{4}000124{5}";
private readonly IFileManager _fileManager;
private readonly IDateTimeManager _dateTimeManager;

public GpcGenerator(IFileManager fileManager, IDateTimeManager dateTimeManager)
{
_fileManager = fileManager;
_dateTimeManager = dateTimeManager;
}

public void SaveTransactions(IEnumerable<Transaction> transactions, string fileName)
{
DateTime endOfCurrentMonth = GetEndOfCurrentMonth();

string firstLine = string.Format(_intitialLine, endOfCurrentMonth.ToString("ddMMyy"));

using (System.IO.StreamWriter file = new System.IO.StreamWriter(fileName))
var outputText = new StringBuilder();

outputText.AppendLine(firstLine);
foreach (var transaction in transactions.Where(t => !t.Type.Equals(TransactionTypes.ServiceFee)))
{
file.WriteLine(firstLine);
foreach (var transaction in transactions.Where(t => !t.Type.Equals(TransactionTypes.ServiceFee)))
{
file.WriteLine(GetTransactionLine(transaction));
}
outputText.AppendLine(GetTransactionLine(transaction));
}
}

private string GetShortVariableCodeForRefund(string fullVariableCode) // TODO remove repetition
{
// refunds are filled manually in pohoda, so there is no need to care about invoice symVar
string filteredCode = fullVariableCode.RemoveAll("-");
filteredCode = filteredCode.Substring(0, 10);
return filteredCode;
_fileManager.WriteAllTextToFile(fileName, outputText.ToString());
}

private string GetTransactionLine(Transaction transaction)
{
var shortVariableCode = Invoice.GetShortVariableCode(transaction.OrderId, out var zerosRemoved);
var shortVariableCode = VariableCode.GetShortVariableCode(transaction.OrderId);
if (transaction.Type == TransactionTypes.Refund) // Refunds have short variable codes from first 10 symbols
{
shortVariableCode = GetShortVariableCodeForRefund(transaction.OrderId);
zerosRemoved = 0;
shortVariableCode = VariableCode.GetShortVariableCode(transaction.OrderId);
}

string type = ((int) transaction.Type).ToString();
// in case that order ID contained zeros at the beginning
type = type.PadRight(type.Length + zerosRemoved, '0');
shortVariableCode = shortVariableCode.PadLeft(VariableCode.ShortVariableCodeLength, '0');

string type = ((int)transaction.Type).ToString();

string marketPlace = transaction.MarketplaceId.ToString().PadLeft(2, '0');
string marketPlace = transaction.MarketplaceId.ToString().PadLeft(2, '0'); // max 2

string orderId = transaction.OrderId.PadRight(19, '0');

Expand All @@ -65,7 +66,7 @@ private string GetTransactionLine(Transaction transaction)
string formatted = string.Format(_transactionBase,
marketPlace,
price,
type,
type,
shortVariableCode,
orderId,
date);
Expand All @@ -78,13 +79,13 @@ private string GetTransactionLine(Transaction transaction)

private string FormatPrice(decimal price)
{
string priceFormatted = Math.Abs(price).ToString("N2").RemoveAll(".").RemoveAll(",").PadLeft(8,'0');
string priceFormatted = Math.Abs(price).ToString("N2").RemoveAll(".").RemoveAll(",").PadLeft(8, '0');
return priceFormatted;
}

private static DateTime GetEndOfCurrentMonth()
private DateTime GetEndOfCurrentMonth()
{
var today = DateTime.Today;
var today = _dateTimeManager.Today;
return today.AddDays(1 - today.Day).AddMonths(1).AddDays(-1).Date;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;

namespace Mapp.BusinessLogic.Transactions
{
[DebuggerDisplay("{Name}")]
public class MarketPlaceTransactionsConfig
{
public string Name { get; set; }

public MarketPlaceTransactionsConfig(string dateCultureInfoName, string dateSubstring, int marketPlaceId)
{
DateCultureInfoName = dateCultureInfoName;
Expand Down Expand Up @@ -48,7 +52,7 @@ public CultureInfo DateCultureInfo
}

// it is decided to use this phrase because parameter Market place can be unavailable (no transactions)
public string DistinctionPhrase { get; set; }
public IEnumerable<string> DistinctionPhrases { get; set; }

public string DateSubstring { get; }

Expand Down
47 changes: 26 additions & 21 deletions Mapp.BusinessLogic.Invoices/Transactions/TransactionsReader.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Text.RegularExpressions;
using AutoMapper;
Expand All @@ -14,9 +15,6 @@ namespace Mapp.BusinessLogic.Transactions
public interface ITransactionsReader
{
IEnumerable<Transaction> ReadTransactionsFromMultipleFiles(IEnumerable<string> fileNames);
DateTime ParseDate(string dateString, MarketPlaceTransactionsConfig settings);
IEnumerable<Transaction> ReadTransactions(string fileName);
TransactionTypes ParseTransactionType(string transactionType, MarketPlaceTransactionsConfig settings);
}

public class TransactionsReader : ITransactionsReader
Expand Down Expand Up @@ -45,20 +43,20 @@ private IEnumerable<MarketPlaceTransactionsConfig> GetAvailableMarketplaceConfig
{
// TODO load only once
var mapperConfiguration = new MapperConfiguration(cfg => {
cfg.CreateMap<MarketPlaceTransactionsConfigDTO, MarketPlaceTransactionsConfig>();
cfg.CreateMap<MarketPlaceTransactionsConfigData, MarketPlaceTransactionsConfig>();
});
IMapper mapper = mapperConfiguration.CreateMapper();

var configDtos = _jsonManager.LoadTransactionsConfigs();
var configsData = _jsonManager.LoadTransactionsConfigs();

var configs = configDtos.Select<MarketPlaceTransactionsConfigDTO, MarketPlaceTransactionsConfig>(dto =>
mapper.Map<MarketPlaceTransactionsConfigDTO, MarketPlaceTransactionsConfig>(dto));
var configs = configsData.Select(data =>
mapper.Map<MarketPlaceTransactionsConfigData, MarketPlaceTransactionsConfig>(data));

var marketPlaceIds = configs.Select(s => s.MarketPlaceId).ToList();
if (marketPlaceIds.Distinct().Count() != marketPlaceIds.Count())
{
throw new ArgumentException($"Chyba, duplicitni hodnota {nameof(marketPlaceIds)} v JSON konfiguracich!");
}
//if (marketPlaceIds.Distinct().Count() != marketPlaceIds.Count()) // commented because we now have PaypalCZ and paypal
//{
// throw new ArgumentException($"Chyba, duplicitni hodnota {nameof(marketPlaceIds)} v JSON konfiguracich!");
//}

return configs;
}
Expand All @@ -84,13 +82,13 @@ private IReadOnlyList<string[]> GetFileLines(string fileName, string encodingCod
return lineItems;
}

public DateTime ParseDate(string dateString, MarketPlaceTransactionsConfig settings)
private DateTime ParseDate(string dateString, MarketPlaceTransactionsConfig config)
{
var match = Regex.Match(dateString, settings.DateSubstring);
return DateTime.Parse(match.Groups[1].Value, settings.DateCultureInfo);
var match = Regex.Match(dateString, config.DateSubstring);
return DateTime.Parse(match.Groups[1].Value, config.DateCultureInfo);
}

public IEnumerable<Transaction> ReadTransactions(string fileName)
private IEnumerable<Transaction> ReadTransactions(string fileName)
{
var lines = GetFileLines(fileName);

Expand All @@ -117,12 +115,13 @@ public IEnumerable<Transaction> ReadTransactions(string fileName)
{
string columnNameKey = validLines[0][columnIndex].Trim(); //tolower?
transactionsDict.Add(columnNameKey, validLines.Skip(1).Select(l => l[columnIndex]).ToArray());
}
}

var transactions = new List<Transaction>();
for (int index = 0; index < transactionsDict.First().Value.Count(); index++)
{
string orderId = transactionsDict[marketPlaceSetting.OrderIdColumnName][index];
orderId = new string(orderId.ToCharArray().Where(c => char.IsDigit(c) || c == '-').ToArray()); // we only need to take numbers, since for Shoppify order is smth like #3214, however '-' should be ok
if (string.IsNullOrEmpty(orderId))
orderId = "0000000000000000000";

Expand All @@ -131,7 +130,8 @@ public IEnumerable<Transaction> ReadTransactions(string fileName)
decimal transactionTotalValue = 0;
foreach (var compColumnName in marketPlaceSetting.ValueComponentsColumnName)
{
transactionTotalValue += decimal.Parse(transactionsDict[compColumnName][index], marketPlaceSetting.DateCultureInfo);
string val = transactionsDict[compColumnName][index];
transactionTotalValue += decimal.Parse(val, marketPlaceSetting.DateCultureInfo);
}

var transactionType = ParseTransactionType(transactionsDict[marketPlaceSetting.TransactionTypeColumnName][index], marketPlaceSetting);
Expand All @@ -142,7 +142,7 @@ public IEnumerable<Transaction> ReadTransactions(string fileName)
}

// DATE
string dateComplete = String.Empty;
string dateComplete = string.Empty;
foreach (var columnName in marketPlaceSetting.DateTimeColumnNames)
{
dateComplete += transactionsDict[columnName][index] + " ";
Expand Down Expand Up @@ -174,7 +174,7 @@ public IEnumerable<Transaction> ReadTransactions(string fileName)
return transactions;
}

public TransactionTypes ParseTransactionType(string transactionType, MarketPlaceTransactionsConfig settings)
private TransactionTypes ParseTransactionType(string transactionType, MarketPlaceTransactionsConfig settings)
{
// TODO refactoring AWFUL CODE
if (settings.OrderTypeNames.Any(n => n.EqualsIgnoreCase(transactionType)))
Expand All @@ -195,13 +195,18 @@ private MarketPlaceTransactionsConfig GetMarketPlaceSetting(IReadOnlyList<string
// put into factory
foreach (var marketPlace in _marketplaceConfigs)
{
var found = dataLines.SingleOrDefault(l => l.First().EqualsIgnoreCase(marketPlace.DistinctionPhrase));
if (found != null)
var isFound = IsFirstLineCorrespondToConfig(dataLines, marketPlace);
if (isFound)
{
return marketPlace;
}
}
throw new ArgumentException("Nerozpoznany typ souboru");
}

private static bool IsFirstLineCorrespondToConfig(IReadOnlyList<string[]> dataLines, MarketPlaceTransactionsConfig marketPlace)
{
return dataLines.Any(l => !marketPlace.DistinctionPhrases.Except(l).Any());
}
}
}
Loading

0 comments on commit 0b9394f

Please sign in to comment.