feat: guided import and export for parties, items, prices, opening stock and chart of accounts (#44)
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>
This commit is contained in:
1 parent
3dbbaba86e
commit
caa33a2cee
29 files changed
+4783
-90
No files matched your search
@@ -0,0 +1,173 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
using System.IO.Compression;
|
||||
using System.Text;
|
||||
using Khaemhat.Infrastructure.Files;
|
||||
|
||||
namespace Khaemhat.Infrastructure.Tests.Files;
|
||||
|
||||
/// <summary>The XLSX reader of the guided import (issue #44): what the writer produces comes back as text.</summary>
|
||||
[TestClass]
|
||||
public sealed class XlsxReaderTests
|
||||
{
|
||||
[TestMethod]
|
||||
[DataRow(false)]
|
||||
[DataRow(true)]
|
||||
public async Task ReadsBackWhatTheWriterWrites(bool sharedStrings)
|
||||
{
|
||||
using var buffer = new MemoryStream();
|
||||
await using (var writer = await XlsxWriter.CreateAsync(buffer, new XlsxOptions { UseSharedStrings = sharedStrings }, leaveOpen: true))
|
||||
{
|
||||
await writer.StartSheetAsync("clienti", [new("codice"), new("prezzo"), new("dal"), new("attivo"), new("note")]);
|
||||
await writer.WriteRowAsync(["C001", 1234.5m, new DateOnly(2026, 11, 12), true, null]);
|
||||
await writer.WriteRowAsync([null, null, null, null, null]);
|
||||
await writer.WriteRowAsync(["C002", -3m, null, false, "Via \"Roma\" & co. <1>"]);
|
||||
await writer.CompleteAsync();
|
||||
}
|
||||
|
||||
buffer.Position = 0;
|
||||
var rows = await XlsxReader.ReadAsync(buffer);
|
||||
|
||||
Assert.HasCount(3, rows, "Header and two rows: the empty row is skipped.");
|
||||
CollectionAssert.AreEqual(new[] { "codice", "prezzo", "dal", "attivo", "note" }, rows[0].ToArray());
|
||||
Assert.AreEqual("C001", rows[1][0]);
|
||||
Assert.AreEqual("1234.5", rows[1][1], "Numbers come in invariant notation.");
|
||||
Assert.AreEqual("2026-11-12", rows[1][2], "Date-styled numbers come back as ISO dates.");
|
||||
Assert.AreEqual("true", rows[1][3]);
|
||||
Assert.AreEqual("-3", rows[2][1]);
|
||||
Assert.AreEqual(string.Empty, rows[2][2], "A gap between cells is an empty cell.");
|
||||
Assert.AreEqual("false", rows[2][3]);
|
||||
Assert.AreEqual("Via \"Roma\" & co. <1>", rows[2][4]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task NotAWorkbook_IsRefused()
|
||||
{
|
||||
using var text = new MemoryStream(Encoding.UTF8.GetBytes("codice;descrizione\nA;B\n"));
|
||||
await Assert.ThrowsExactlyAsync<XlsxReadException>(() => XlsxReader.ReadAsync(text));
|
||||
|
||||
using var zip = new MemoryStream();
|
||||
using (var archive = new ZipArchive(zip, ZipArchiveMode.Create, leaveOpen: true))
|
||||
{
|
||||
archive.CreateEntry("readme.txt");
|
||||
}
|
||||
|
||||
zip.Position = 0;
|
||||
await Assert.ThrowsExactlyAsync<XlsxReadException>(() => XlsxReader.ReadAsync(zip));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("A1", 0)]
|
||||
[DataRow("C7", 2)]
|
||||
[DataRow("Z10", 25)]
|
||||
[DataRow("AA1", 26)]
|
||||
[DataRow("AB12", 27)]
|
||||
public void ColumnOf_ReadsTheLetters(string reference, int column) => Assert.AreEqual(column, XlsxReader.ColumnOf(reference));
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
using System.Text;
|
||||
using Khaemhat.Application.ImportExport;
|
||||
using Khaemhat.Application.Items;
|
||||
using Khaemhat.Application.Parties;
|
||||
using Khaemhat.Application.Querying;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Application.Tables;
|
||||
using Khaemhat.Core.Parties;
|
||||
using Khaemhat.Core.Security;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Web.Tests.Hosting;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Khaemhat.Web.Tests.ImportExport;
|
||||
|
||||
/// <summary>The guided import and export on a real instance (issue #44, ADR 0031).</summary>
|
||||
[TestClass]
|
||||
public sealed class ImportServiceTests
|
||||
{
|
||||
private static readonly Actor Root = new(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null);
|
||||
|
||||
[TestMethod]
|
||||
public async Task Customers_AreCheckedAsTypedInTheRecord_AndOnlyRowsWithoutErrorsAreWritten()
|
||||
{
|
||||
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
|
||||
await using (app)
|
||||
{
|
||||
var imports = app.Services.GetRequiredService<ImportService>();
|
||||
var parties = app.Services.GetRequiredService<PartyService>();
|
||||
var file = Csv(
|
||||
"Codice;Ragione sociale;P.IVA;CAP;Comune;Pagamento;Tipo soggetto;Cognome;Nome;IBAN",
|
||||
"CLI001;Rossi Impianti S.r.l.;01234567897;47121;;;impresa;;;IT60 X054 2811 1010 0000 0123 456",
|
||||
"CLI002;;;;;;privato;Bianchi;Anna;",
|
||||
"CLI001;Doppione S.r.l.;02345678904;;;;;;;",
|
||||
";Verdi S.p.A.;02345678904;;;XX;;;;",
|
||||
";Neri S.r.l.;01234567890;;;;;;;");
|
||||
var mapping = ImportService.SuggestMapping(imports.Target("clienti"), file.Headers);
|
||||
Assert.IsFalse(mapping.Contains(null), "Every header of the file has a field: " + string.Join(", ", mapping));
|
||||
|
||||
var preview = await imports.PreviewAsync(Root, company, "clienti", file, mapping, new ImportOptions());
|
||||
string[] Codes(int line) => [.. preview.Rows.Single(r => r.Line == line).Messages.Select(m => m.Field + ":" + m.Code)];
|
||||
Assert.AreEqual(ImportAction.Create, preview.Rows[0].Action);
|
||||
CollectionAssert.Contains(Codes(3), "codice_fiscale:" + PartyService.TaxCodeMissing, "A private customer without tax code is a warning.");
|
||||
CollectionAssert.Contains(Codes(4), "codice:" + ImportErrors.CodeRepeated);
|
||||
CollectionAssert.Contains(Codes(5), "pagamento:" + ImportErrors.CodeUnknown);
|
||||
Assert.IsTrue(Codes(6).Any(c => c.StartsWith("partita_iva:", StringComparison.Ordinal)), "The VAT number check of the fiscal pack: " + string.Join(", ", Codes(6)));
|
||||
Assert.AreEqual(2, preview.Creates);
|
||||
Assert.AreEqual(3, preview.Errors);
|
||||
|
||||
var report = await imports.ImportAsync(Root, company, "clienti", file, mapping, new ImportOptions());
|
||||
Assert.AreEqual(2, report.Created);
|
||||
Assert.AreEqual(3, report.Failed);
|
||||
var rossi = (await parties.SearchAsync(Root, company, PartyArchive.Customers, "CLI001")).Single();
|
||||
var record = (await parties.GetAsync(Root, company, rossi.Id))!;
|
||||
Assert.AreEqual("Rossi Impianti S.r.l.", record.Party.Name);
|
||||
Assert.AreEqual("IT60X0542811101000000123456", record.BankAccounts.Single().Iban);
|
||||
Assert.AreEqual("Bianchi Anna", (await parties.SearchAsync(Root, company, PartyArchive.Customers, "CLI002")).Single().Name);
|
||||
|
||||
// Updating: empty cells keep what is there; skipping leaves the record alone; a supplier cannot take a customer's code.
|
||||
var update = Csv("codice;telefono;ragione_sociale", "CLI001;0543 123456;");
|
||||
var updated = await imports.ImportAsync(Root, company, "clienti", update, ["codice", "telefono", "ragione_sociale"], new ImportOptions());
|
||||
Assert.AreEqual(1, updated.Updated);
|
||||
record = (await parties.GetAsync(Root, company, rossi.Id))!;
|
||||
StringAssert.Contains(record.Party.Phone, "123456");
|
||||
Assert.AreEqual("Rossi Impianti S.r.l.", record.Party.Name);
|
||||
var skipped = await imports.PreviewAsync(Root, company, "clienti", update, ["codice", "telefono", null], new ImportOptions { Existing = ExistingCodeAction.Skip });
|
||||
Assert.AreEqual(ImportErrors.CodeExists, skipped.Rows.Single().Messages.Single().Code);
|
||||
Assert.AreEqual(1, skipped.Skips);
|
||||
var supplier = await imports.PreviewAsync(Root, company, "fornitori", update, ["codice", "telefono", null], new ImportOptions());
|
||||
Assert.AreEqual(ImportErrors.OtherKind, supplier.Rows.Single().Messages.Single().Code);
|
||||
var refused = await imports.PreviewAsync(Root, company, "fornitori", Csv("ragione_sociale;partita_iva", "Bianchi Forniture;02345678904"), ["ragione_sociale", "partita_iva"],
|
||||
new ImportOptions { Missing = MissingCodeAction.Refuse });
|
||||
Assert.AreEqual(ImportErrors.CodeMissing, refused.Rows.Single().Messages.Single().Code);
|
||||
await app.StopAsync();
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Items_Prices_AndTheExport_GoRoundTrip()
|
||||
{
|
||||
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
|
||||
await using (app)
|
||||
{
|
||||
var imports = app.Services.GetRequiredService<ImportService>();
|
||||
var tables = app.Services.GetRequiredService<TableService>();
|
||||
await tables.SaveAsync(Root, company, new ItemCategory { Code = "VALV", Description = "Valvolame" });
|
||||
var baseList = (await tables.ListAsync<PriceList>(Root, company, new ListQuery { Limit = 100 })).Items.Single(l => l.IsBase).Code;
|
||||
var parties = app.Services.GetRequiredService<PartyService>();
|
||||
var customer = await parties.NewAsync(Root, company, PartyKind.Customer);
|
||||
(customer.Party.Code, customer.Party.Name, customer.Party.VatNumber) = ("C1", "Rossi Impianti S.r.l.", "01234567897");
|
||||
await parties.SaveAsync(Root, company, customer);
|
||||
|
||||
var items = Csv(
|
||||
"codice;descrizione;categoria;um;prezzo;tipo;a_magazzino",
|
||||
"A-1;Valvola a sfera;VALV;PZ;12,50;merce;sì",
|
||||
";Manodopera;VALV;PZ;38;servizio;",
|
||||
"A-2;;VALV;PZ;1;merce;forse");
|
||||
var mapping = ImportService.SuggestMapping(imports.Target("articoli"), items.Headers);
|
||||
var report = await imports.ImportAsync(Root, company, "articoli", items, mapping, new ImportOptions());
|
||||
Assert.AreEqual(2, report.Created);
|
||||
var bad = report.Rows.Single(r => r.Line == 4).Messages.Select(m => m.Field + ":" + m.Code).ToList();
|
||||
CollectionAssert.Contains(bad, "descrizione:" + ImportErrors.Required);
|
||||
CollectionAssert.Contains(bad, "a_magazzino:" + ImportErrors.Boolean);
|
||||
var itemService = app.Services.GetRequiredService<ItemService>();
|
||||
var labour = (await itemService.SearchAsync(Root, company, "Manodopera")).Single();
|
||||
StringAssert.StartsWith(labour.Code, "VALV", "The code comes from the rule of the items.");
|
||||
Assert.IsFalse(labour.Stocked, "A service is not stocked.");
|
||||
|
||||
var prices = Csv(
|
||||
"articolo;listino;cliente;prezzo;valido_dal",
|
||||
$"A-1;{baseList};;10;01/01/2026",
|
||||
"A-1;;C1;9,5;",
|
||||
$"A-1;{baseList};C1;5;",
|
||||
$"A-9;{baseList};;5;");
|
||||
var pricesMapping = ImportService.SuggestMapping(imports.Target("listini"), prices.Headers);
|
||||
var priced = await imports.ImportAsync(Root, company, "listini", prices, pricesMapping, new ImportOptions());
|
||||
Assert.AreEqual(2, priced.Created);
|
||||
CollectionAssert.Contains(priced.Rows.Single(r => r.Line == 4).Messages.Select(m => m.Code).ToList(), ImportErrors.PriceTarget);
|
||||
CollectionAssert.Contains(priced.Rows.Single(r => r.Line == 5).Messages.Select(m => m.Code).ToList(), ImportErrors.CodeUnknown);
|
||||
var again = await imports.PreviewAsync(Root, company, "listini", prices, pricesMapping, new ImportOptions());
|
||||
Assert.AreEqual(ImportAction.Update, again.Rows[0].Action, "The same item, list and day replace the price.");
|
||||
|
||||
// The export has the columns of the import: imported again, every row updates and nothing fails.
|
||||
foreach (var format in new[] { TransferFormat.Csv, TransferFormat.Xlsx, TransferFormat.Json })
|
||||
{
|
||||
using var buffer = new MemoryStream();
|
||||
Assert.AreEqual(2, await imports.ExportAsync(Root, company, "articoli", format, buffer));
|
||||
buffer.Position = 0;
|
||||
var exported = await ImportFileReader.ReadAsync(ImportService.FileName("articoli", format, new DateOnly(2026, 11, 12)), buffer);
|
||||
CollectionAssert.AreEqual(imports.Target("articoli").Fields.Select(f => f.Key).ToArray(), exported.Headers.ToArray(), format.ToString());
|
||||
var back = await imports.PreviewAsync(Root, company, "articoli", exported, ImportService.SuggestMapping(imports.Target("articoli"), exported.Headers),
|
||||
new ImportOptions());
|
||||
Assert.AreEqual(0, back.Errors, format + ": " + string.Join("; ", back.Rows.SelectMany(r => r.Messages).Select(m => m.Field + ":" + m.Code)));
|
||||
Assert.AreEqual(2, back.Updates, format.ToString());
|
||||
}
|
||||
|
||||
using var priceExport = new MemoryStream();
|
||||
Assert.AreEqual(2, await imports.ExportAsync(Root, company, "listini", TransferFormat.Csv, priceExport));
|
||||
var priceText = Encoding.UTF8.GetString(priceExport.ToArray());
|
||||
StringAssert.Contains(priceText, "A-1;" + baseList + ";;10;01/01/2026");
|
||||
StringAssert.Contains(priceText, "A-1;;C1;9,5;");
|
||||
|
||||
using var template = new MemoryStream();
|
||||
await ImportService.WriteTemplateAsync(imports.Target("listini"), TransferFormat.Csv, template);
|
||||
Assert.AreEqual("articolo;listino;cliente;prezzo;valido_dal", Encoding.UTF8.GetString(template.ToArray()).Trim('', '\r', '\n'));
|
||||
await app.StopAsync();
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task OpeningStock_IsOnlyChecked_UntilTheStockEntriesExist()
|
||||
{
|
||||
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
|
||||
await using (app)
|
||||
{
|
||||
var imports = app.Services.GetRequiredService<ImportService>();
|
||||
var tables = app.Services.GetRequiredService<TableService>();
|
||||
await tables.SaveAsync(Root, company, new ItemCategory { Code = "VALV", Description = "Valvolame" });
|
||||
var items = Csv("codice;descrizione;categoria;tipo", "A-1;Valvola;VALV;merce", "S-1;Manodopera;VALV;servizio");
|
||||
await imports.ImportAsync(Root, company, "articoli", items, ImportService.SuggestMapping(imports.Target("articoli"), items.Headers), new ImportOptions());
|
||||
|
||||
var stock = Csv("articolo;deposito;quantita;costo_unitario", "A-1;;5;3,20", "S-1;;1;", "A-1;;0;", "B-9;;1;");
|
||||
var mapping = ImportService.SuggestMapping(imports.Target("giacenze-iniziali"), stock.Headers);
|
||||
var preview = await imports.PreviewAsync(Root, company, "giacenze-iniziali", stock, mapping, new ImportOptions());
|
||||
Assert.IsFalse(preview.CanApply);
|
||||
Assert.AreEqual(ImportOutcome.Ok, preview.Rows[0].Outcome, string.Join("; ", preview.Rows[0].Messages.Select(m => m.Field + ":" + m.Code)));
|
||||
Assert.AreEqual(ImportErrors.NotStocked, preview.Rows[1].Messages.Single().Code);
|
||||
CollectionAssert.Contains(preview.Rows[2].Messages.Select(m => m.Code).ToList(), ImportErrors.Positive);
|
||||
Assert.AreEqual(ImportErrors.CodeUnknown, preview.Rows[3].Messages.Single().Code);
|
||||
var refused = await Assert.ThrowsExactlyAsync<ImportFileException>(() => imports.ImportAsync(Root, company, "giacenze-iniziali", stock, mapping, new ImportOptions()));
|
||||
Assert.AreEqual(ImportErrors.CheckOnly, refused.Code);
|
||||
await app.StopAsync();
|
||||
}
|
||||
}
|
||||
|
||||
private static ImportFile Csv(params string[] lines) =>
|
||||
ImportFileReader.ReadCsv("prova.csv", Encoding.UTF8.GetBytes(string.Join("\r\n", lines) + "\r\n"));
|
||||
}
|
||||
@@ -271,6 +271,6 @@ public sealed partial class LocalizationRulesTests
|
||||
[GeneratedRegex(@"&[a-zA-Z]+;|&#\d+;")]
|
||||
private static partial Regex EntityPattern();
|
||||
|
||||
[GeneratedRegex("\"((?:Shell|Pages|Auth|Common|Ui|Dashboard|Parties|Items)\\.[A-Za-z0-9_.]+)\"")]
|
||||
[GeneratedRegex("\"((?:Shell|Pages|Auth|Common|Ui|Dashboard|Parties|Items|ImportExport)\\.[A-Za-z0-9_.]+)\"")]
|
||||
private static partial Regex KeyPattern();
|
||||
}
|
||||
Reference in new issue
Block a user