Companies starting on Khaemhat need to bring their master data from another system or a spreadsheet, and the chart of accounts has no Italian exchange standard, so SPEC 12.12 asks for a guided wizard and an own layout. - Administration > Import / export: CSV (separator and encoding guessed), XLSX (in-house reader, first sheet) and JSON, automatic column mapping with aliases, row-by-row check, error report, import confirmation and log entry. - Rows go through PartyService, ItemService and PriceListService, so the import has exactly the rules, error codes and history of the forms; options cover existing and missing codes, VIES and city from postal code. - Export writes the same columns as the import, plus empty templates. - Opening stock and the chart of accounts (khaemhat-coa layout, natura, tipo, flag) are check-only until M6 and M7 add the ledgers to write into. - PartyService.SaveAsync takes an explicit VIES switch for the import. - ADR 0031, wiki Import-Export, CHANGELOG and STATUS updated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
174 lines
9.0 KiB
C#
174 lines
9.0 KiB
C#
using System.Text;
|
|
using Khaemhat.Application.ImportExport;
|
|
using Khaemhat.Core.Accounting;
|
|
|
|
namespace Khaemhat.Application.Tests;
|
|
|
|
/// <summary>The pure parts of the guided import (issue #44, ADR 0031): values, files, mapping and the chart of accounts.</summary>
|
|
[TestClass]
|
|
public sealed class ImportRulesTests
|
|
{
|
|
[TestMethod]
|
|
[DataRow("1.234,56", "1234.56")]
|
|
[DataRow("1234,56", "1234.56")]
|
|
[DataRow("1234.56", "1234.56")]
|
|
[DataRow("1,234.56", "1234.56")]
|
|
[DataRow("1.234.567", "1234567")]
|
|
[DataRow("€ 12,5", "12.5")]
|
|
[DataRow("22 %", "22")]
|
|
[DataRow("-3", "-3")]
|
|
[DataRow("1E3", "1000")]
|
|
public void TryNumber_ReadsItalianAndMachineNotation(string text, string expected)
|
|
{
|
|
Assert.IsTrue(ImportValues.TryNumber(text, out var value), text);
|
|
Assert.AreEqual(decimal.Parse(expected, System.Globalization.CultureInfo.InvariantCulture), value);
|
|
}
|
|
|
|
[TestMethod]
|
|
[DataRow("")]
|
|
[DataRow("dodici")]
|
|
[DataRow("12a")]
|
|
public void TryNumber_RefusesText(string text) => Assert.IsFalse(ImportValues.TryNumber(text, out _));
|
|
|
|
[TestMethod]
|
|
[DataRow("12/11/2026")]
|
|
[DataRow("12/11/26")]
|
|
[DataRow("2026-11-12")]
|
|
[DataRow("20261112")]
|
|
[DataRow("12.11.2026")]
|
|
[DataRow("2026-11-12T08:30:00")]
|
|
[DataRow("46338")]
|
|
public void TryDate_ReadsTheCommonForms(string text)
|
|
{
|
|
Assert.IsTrue(ImportValues.TryDate(text, out var value), text);
|
|
Assert.AreEqual(new DateOnly(2026, 11, 12), value);
|
|
}
|
|
|
|
[TestMethod]
|
|
public void TryBoolean_AndChoice_IgnoreCaseAndAccents()
|
|
{
|
|
Assert.IsTrue(ImportValues.TryBoolean("Sì", out var yes) && yes);
|
|
Assert.IsTrue(ImportValues.TryBoolean("VERO", out var vero) && vero);
|
|
Assert.IsTrue(ImportValues.TryBoolean("x", out var x) && x);
|
|
Assert.IsTrue(ImportValues.TryBoolean("FALSO", out var no) && !no);
|
|
Assert.IsFalse(ImportValues.TryBoolean("forse", out _));
|
|
Assert.AreEqual(4, ImportValues.Choice("Extra UE", PartiesImportTarget.SubjectWords));
|
|
Assert.AreEqual(2, ImportValues.Choice("P.A.", PartiesImportTarget.SubjectWords));
|
|
Assert.AreEqual(-1, ImportValues.Choice("altro", PartiesImportTarget.SubjectWords));
|
|
Assert.AreEqual("partita_iva", ImportValues.Normalize(" Partita IVA "));
|
|
Assert.AreEqual("citta", ImportValues.Normalize("Città"));
|
|
}
|
|
|
|
[TestMethod]
|
|
public void Csv_GuessesSeparatorAndEncoding_AndRemovesTheFormulaGuard()
|
|
{
|
|
var utf8 = ImportFileReader.ReadCsv("clienti.csv", [.. Encoding.UTF8.GetPreamble(), .. Encoding.UTF8.GetBytes("Codice;Città;Note\r\nC1;Forlì;'=SOMMA\r\n;;\r\nC2;Aosta\r\n")]);
|
|
Assert.AreEqual("UTF-8", utf8.Encoding);
|
|
Assert.AreEqual(';', utf8.Separator);
|
|
CollectionAssert.AreEqual(new[] { "Codice", "Città", "Note" }, utf8.Headers.ToArray());
|
|
Assert.AreEqual(2, utf8.Count, "The empty row is skipped.");
|
|
Assert.AreEqual("=SOMMA", utf8.Rows[0][2], "The apostrophe of the export goes away.");
|
|
Assert.AreEqual(string.Empty, utf8.Rows[1][2], "Short rows are padded.");
|
|
|
|
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
|
|
var ansi = ImportFileReader.ReadCsv("vecchio.csv", Encoding.GetEncoding(1252).GetBytes("codice,città\nA,Forlì\n"));
|
|
Assert.AreEqual("Windows-1252", ansi.Encoding);
|
|
Assert.AreEqual(',', ansi.Separator);
|
|
Assert.AreEqual("Forlì", ansi.Rows[0][1]);
|
|
|
|
Assert.AreEqual(ImportErrors.FileEmpty, Assert.ThrowsExactly<ImportFileException>(() => ImportFileReader.ReadCsv("vuoto.csv", [])).Code);
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task Json_ReadsArraysAndTheChartFile()
|
|
{
|
|
var array = await ReadJsonAsync("""[{"codice":"A","prezzo":12.5,"attivo":true},{"codice":"B","note":null}]""");
|
|
CollectionAssert.AreEqual(new[] { "codice", "prezzo", "attivo", "note" }, array.Headers.ToArray());
|
|
CollectionAssert.AreEqual(new[] { "A", "12.5", "true", string.Empty }, array.Rows[0].ToArray());
|
|
Assert.IsNull(array.Sections);
|
|
|
|
var chart = await ReadJsonAsync("""{"format":"khaemhat-coa","version":1,"accounts":[{"codice":"01"}],"statementLines":[{},{}],"mappings":[]}""");
|
|
Assert.AreEqual(1, chart.Count);
|
|
Assert.AreEqual(2, chart.Sections!["statementLines"]);
|
|
Assert.AreEqual(0, chart.Sections["mappings"]);
|
|
|
|
var wrong = await Assert.ThrowsExactlyAsync<ImportFileException>(() => ReadJsonAsync("""{"codice":"A"}"""));
|
|
Assert.AreEqual(ImportErrors.FileUnreadable, wrong.Code);
|
|
var format = await Assert.ThrowsExactlyAsync<ImportFileException>(() => ImportFileReader.ReadAsync("dati.pdf", new MemoryStream([1, 2])));
|
|
Assert.AreEqual(ImportErrors.FileFormat, format.Code);
|
|
}
|
|
|
|
[TestMethod]
|
|
public void Mapping_UsesNamesThenAliases_EachFieldOnce()
|
|
{
|
|
var target = new ChartOfAccountsImportTarget(null!);
|
|
var mapping = ImportService.SuggestMapping(target, ["Conto", "Descrizione", "Codice", "Natura", "Colore", "descr"]);
|
|
CollectionAssert.AreEqual(new[] { null, "descrizione", "codice", "natura", null, null }, mapping.ToArray(), "The exact name wins over the alias.");
|
|
|
|
var file = new ImportFile("x.csv", TransferFormat.Csv, "UTF-8", ';', ["Codice", "Descrizione"], [["01", " Attivo "], ["", ""]]);
|
|
var rows = ImportService.Rows(file, ["codice", "descrizione"]);
|
|
Assert.AreEqual(2, rows[0].Line, "The header is line 1.");
|
|
Assert.AreEqual("Attivo", rows[0]["descrizione"]);
|
|
Assert.IsNull(rows[1]["codice"], "Empty cells are left out.");
|
|
}
|
|
|
|
[TestMethod]
|
|
public void Chart_AcceptsATreeOfThreeLevels()
|
|
{
|
|
var (results, accounts) = ChartOfAccountsImportValidator.Check(
|
|
[
|
|
Row(2, ("codice", "01"), ("descrizione", "Attivo"), ("natura", "attivo")),
|
|
Row(3, ("codice", "01.10"), ("descrizione", "Crediti"), ("livello", "2")),
|
|
Row(4, ("codice", "01.10.001"), ("descrizione", "Clienti Italia"), ("tipo", "clienti"), ("flag", "M,P")),
|
|
Row(5, ("codice", "02"), ("descrizione", "Costi"), ("natura", "costo")),
|
|
Row(6, ("codice", "02.01"), ("descrizione", "Acquisti"), ("padre", "02"), ("flag", "MI")),
|
|
]);
|
|
|
|
Assert.IsTrue(results.All(r => r.Outcome == ImportOutcome.Ok), string.Join("; ", results.SelectMany(r => r.Messages).Select(m => m.Field + ":" + m.Code)));
|
|
Assert.HasCount(5, accounts);
|
|
var customers = accounts.Single(a => a.Code == "01.10.001");
|
|
Assert.AreEqual(3, customers.Level);
|
|
Assert.AreEqual("01.10", customers.ParentCode);
|
|
Assert.AreEqual(AccountNature.Asset, customers.Nature, "The nature comes from the ancestor.");
|
|
Assert.AreEqual(AccountType.Customers, customers.Type);
|
|
Assert.IsTrue(customers.Postable && customers.SubLedger && !customers.VatRelevant);
|
|
Assert.IsTrue(accounts.Single(a => a.Code == "02.01").VatRelevant);
|
|
}
|
|
|
|
[TestMethod]
|
|
public void Chart_RefusesWhatTheTreeDoesNotAllow()
|
|
{
|
|
var (results, accounts) = ChartOfAccountsImportValidator.Check(
|
|
[
|
|
Row(2, ("codice", "01"), ("descrizione", "Attivo"), ("natura", "attivo"), ("flag", "M")),
|
|
Row(3, ("codice", "01.01"), ("descrizione", "Cassa"), ("natura", "passivo"), ("flag", "M")),
|
|
Row(4, ("codice", "03.01"), ("descrizione", "Orfano"), ("natura", "ricavo"), ("flag", "M")),
|
|
Row(5, ("codice", "01.01.01.01"), ("descrizione", "Troppo"), ("flag", "M")),
|
|
Row(6, ("codice", "01"), ("descrizione", "Doppio"), ("natura", "attivo")),
|
|
Row(7, ("codice", "04"), ("descrizione", "Senza natura")),
|
|
Row(8, ("codice", "05"), ("descrizione", "Lettera"), ("natura", "ordine"), ("flag", "MZ")),
|
|
Row(9, ("codice", "01.02"), ("descrizione", "Foglia"), ("livello", "3")),
|
|
]);
|
|
|
|
string[] Codes(int line) => [.. results.Single(r => r.Line == line).Messages.Select(m => m.Code)];
|
|
CollectionAssert.Contains(Codes(2), ImportErrors.AccountPostable);
|
|
CollectionAssert.Contains(Codes(3), ImportErrors.AccountNature);
|
|
CollectionAssert.Contains(Codes(4), ImportErrors.AccountParent);
|
|
CollectionAssert.Contains(Codes(5), ImportErrors.AccountLevel);
|
|
CollectionAssert.Contains(Codes(6), ImportErrors.CodeRepeated);
|
|
CollectionAssert.Contains(Codes(7), ImportErrors.Required);
|
|
CollectionAssert.Contains(Codes(8), ImportErrors.AccountFlag);
|
|
CollectionAssert.Contains(Codes(9), ImportErrors.AccountLevel);
|
|
Assert.IsTrue(results.Single(r => r.Line == 9).Messages.Any(m => m.Code == ImportErrors.AccountLeaf && m.IsWarning));
|
|
Assert.IsFalse(accounts.Any(a => a.Code is "01" or "01.01" or "03.01"), "Only rows without errors become accounts.");
|
|
}
|
|
|
|
private static ImportRow Row(int line, params (string Key, string Value)[] cells) => new(line, cells.ToDictionary(c => c.Key, c => c.Value));
|
|
|
|
private static async Task<ImportFile> ReadJsonAsync(string json)
|
|
{
|
|
using var stream = new MemoryStream(Encoding.UTF8.GetBytes(json));
|
|
return await ImportFileReader.ReadAsync("dati.json", stream);
|
|
}
|
|
}
|