Stock, stock take and reorder screens under /magazzino, with valuation, rebuild and the movements of an item; the understock dashboard widget. Supplier e-invoices (XML, p7m, ZIP) become draft purchase invoices with supplier, items and tax codes matched, the file attached and duplicates refused; the TD code mapping stays in the Italian fiscal pack. Purchase invoices show price differences against the order and the self-invoice still to issue, with a pending list on the self-invoice screen. The opening stock import now writes an opening movement. The demo company gets purchases, an opening stock, a pending self-invoice and a stock take being counted. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
183 lines
12 KiB
C#
183 lines
12 KiB
C#
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_LoadsTheWarehouse_WithAnOpeningMovement()
|
||
{
|
||
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
|
||
await using (app)
|
||
{
|
||
var imports = app.Services.GetRequiredService<ImportService>();
|
||
var tables = app.Services.GetRequiredService<TableService>();
|
||
var stockService = app.Services.GetRequiredService<Khaemhat.Application.Inventory.InventoryService>();
|
||
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.IsTrue(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 report = await imports.ImportAsync(Root, company, "giacenze-iniziali", stock, mapping, new ImportOptions());
|
||
Assert.AreEqual(1, report.Created);
|
||
var row = (await stockService.StockAsync(Root, company, new Khaemhat.Application.Inventory.StockFilter())).Single();
|
||
Assert.AreEqual((5m, 3.2m), (row.OnHand, row.AverageCost));
|
||
await app.StopAsync();
|
||
}
|
||
}
|
||
|
||
private static ImportFile Csv(params string[] lines) =>
|
||
ImportFileReader.ReadCsv("prova.csv", Encoding.UTF8.GetBytes(string.Join("\r\n", lines) + "\r\n"));
|
||
}
|