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:
Alby96andClaude Opus 5.5 committed 2026-11-12 11:52:59 +01:00
1 parent 3dbbaba86e
commit caa33a2cee
29 files changed
+4783 -90

No files matched your search

@@ -0,0 +1,187 @@
using Khaemhat.Application.Items;
using Khaemhat.Application.Modules;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Items;
using Khaemhat.Core.Parties;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.ImportExport;
/// <summary>
/// The prices of the lists and the net prices of the customers (SPEC §12.12): each row is the price of an item in a list
/// or for a customer, valid from a day; the same item, list or customer and day replaces the price, another day adds a
/// dated price as the price grid does. All rows are written by <see cref="PriceListService"/> in one transaction.
/// </summary>
/// <param name="prices">The price lists.</param>
/// <param name="factory">Opens the company databases.</param>
/// <param name="permissions">Checks the permission.</param>
public sealed class PricesImportTarget(PriceListService prices, IUnitOfWorkFactory factory, PermissionService permissions) : IImportTarget
{
private static readonly ImportField[] PriceFields =
[
new("articolo", ImportFieldKind.Code, Required: true, Aliases: ["codice_articolo", "codice", "cod_articolo", "sku"]),
new("listino", ImportFieldKind.Code, Aliases: ["codice_listino", "cod_listino"]),
new("cliente", ImportFieldKind.Code, Aliases: ["codice_cliente", "cod_cliente"]),
new("prezzo", ImportFieldKind.Number, Required: true, Aliases: ["prezzo_netto", "price"]),
new("valido_dal", ImportFieldKind.Date, Aliases: ["validita", "data_inizio", "dal", "decorrenza"]),
];
/// <inheritdoc />
public string Key => "listini";
/// <inheritdoc />
public string ModuleCode => ModuleCodes.Core;
/// <inheritdoc />
public string Permission => ItemService.WritePermission;
/// <inheritdoc />
public string ExportPermission => ItemService.ReadPermission;
/// <inheritdoc />
public bool CanApply => true;
/// <inheritdoc />
public bool CanExport => true;
/// <inheritdoc />
public IReadOnlyList<ImportField> Fields => PriceFields;
/// <inheritdoc />
public async Task<IReadOnlyList<ImportRowResult>> CheckAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken) =>
(await PlanAsync(context, rows, cancellationToken).ConfigureAwait(false)).Results;
/// <inheritdoc />
public async Task<IReadOnlyList<ImportRowResult>> ApplyAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken)
{
var plan = await PlanAsync(context, rows, cancellationToken).ConfigureAwait(false);
if (plan.Edits.Count == 0)
{
return plan.Results;
}
try
{
await prices.SaveAsync(context.Actor, context.CompanyCode, [.. plan.Edits.Select(e => e.Edit)], cancellationToken).ConfigureAwait(false);
return plan.Results;
}
catch (ValidationFailedException ex)
{
// The rows were checked already: an error here is a change made meanwhile; it goes on its row and nothing is written.
var results = plan.Results.ToList();
foreach (var (index, code) in ex.Errors.Select(TableErrors.Split))
{
var position = int.TryParse(index, out var i) && i >= 0 && i < plan.Edits.Count ? plan.Edits[i].Result : -1;
if (position >= 0)
{
var row = results[position];
results[position] = row with { Action = ImportAction.Skip, Messages = [.. row.Messages, new ImportMessage("prezzo", code)] };
}
}
return [.. results.Select(r => r.Outcome == ImportOutcome.Error ? r : r with { Action = ImportAction.Skip, Messages = [.. r.Messages, new ImportMessage(string.Empty, ImportErrors.WriteFailed)] })];
}
}
/// <inheritdoc />
public async Task<IReadOnlyList<IReadOnlyList<object?>>> ExportAsync(ImportContext context, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
var company = await CompanyGuard.DemandAsync(permissions, context.Actor, context.CompanyCode, ExportPermission, cancellationToken).ConfigureAwait(false);
await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var items = new CodeIndex((await uow.Repository<Item, long>().ListAsync(Query.For<Item>(), cancellationToken).ConfigureAwait(false)).Items.Select(i => (i.Code, i.Id)));
var parties = new CodeIndex((await uow.Repository<Party, long>().ListAsync(Query.For<Party>(), cancellationToken).ConfigureAwait(false)).Items.Select(p => (p.Code, p.Id)));
var lists = await CodeIndex.LoadAsync<PriceList>(uow, cancellationToken).ConfigureAwait(false);
var rows = (await uow.Repository<ItemPrice, long>().ListAsync(Query.For<ItemPrice>(), cancellationToken).ConfigureAwait(false)).Items;
return
[
.. rows.Select(p => (IReadOnlyList<object?>)[items.CodeOf(p.ItemId), lists.CodeOf(p.PriceListId), parties.CodeOf(p.PartyId), p.Price, p.ValidFrom])
.OrderBy(r => (string?)r[0], StringComparer.OrdinalIgnoreCase)
.ThenBy(r => (string?)r[1] ?? "~" + (string?)r[2], StringComparer.OrdinalIgnoreCase)
.ThenBy(r => (DateOnly?)r[4]),
];
}
private async Task<Plan> PlanAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
ArgumentNullException.ThrowIfNull(rows);
var company = await CompanyGuard.DemandAsync(permissions, context.Actor, context.CompanyCode, Permission, cancellationToken).ConfigureAwait(false);
await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var items = new CodeIndex((await uow.Repository<Item, long>().ListAsync(Query.For<Item>(), cancellationToken).ConfigureAwait(false)).Items.Select(i => (i.Code, i.Id)));
var allParties = (await uow.Repository<Party, long>().ListAsync(Query.For<Party>(), cancellationToken).ConfigureAwait(false)).Items;
var customers = new CodeIndex(allParties.Where(p => p.IsCustomer).Select(p => (p.Code, p.Id)));
var others = new HashSet<string>(allParties.Where(p => !p.IsCustomer).Select(p => p.Code), StringComparer.OrdinalIgnoreCase);
var lists = await CodeIndex.LoadAsync<PriceList>(uow, cancellationToken).ConfigureAwait(false);
var existing = (await uow.Repository<ItemPrice, long>().ListAsync(Query.For<ItemPrice>(), cancellationToken).ConfigureAwait(false)).Items
.Select(p => (p.ItemId, p.PriceListId, p.PartyId, p.ValidFrom)).ToHashSet();
var seen = new HashSet<(long, long?, long?, DateOnly?)>();
var results = new List<ImportRowResult>(rows.Count);
var edits = new List<(PriceEdit Edit, int Result)>();
foreach (var row in rows)
{
var messages = new List<ImportMessage>();
var cells = new CellReader(row, messages);
var item = cells.Code("articolo", items);
long? list = null;
long? party = null;
if (cells.Has("listino") == cells.Has("cliente"))
{
messages.Add(new(cells.Has("listino") ? "cliente" : "listino", ImportErrors.PriceTarget));
}
else if (cells.Has("listino"))
{
list = cells.Code("listino", lists);
}
else if (row["cliente"] is { } customer && others.Contains(customer))
{
messages.Add(new("cliente", ImportErrors.OtherKind, Value: customer));
}
else
{
party = cells.Code("cliente", customers);
}
var price = cells.Number("prezzo");
if (price < 0)
{
messages.Add(new("prezzo", ItemService.NotNegative));
}
var from = cells.Date("valido_dal");
messages.AddRange(PriceFields.Where(f => f.Required && !cells.Has(f.Key)).Select(f => new ImportMessage(f.Key, ImportErrors.Required)));
var label = row["articolo"] ?? string.Empty;
if (messages.Any(m => !m.IsWarning) || item is not { } itemId || price is not { } value)
{
results.Add(new(row.Line, label, ImportAction.Skip, messages));
continue;
}
var key = (itemId, list, party, from);
if (!seen.Add(key))
{
messages.Add(new("articolo", ImportErrors.CodeRepeated, Value: label));
results.Add(new(row.Line, label, ImportAction.Skip, messages));
continue;
}
var update = existing.Contains(key);
if (update && context.Options.Existing == ExistingCodeAction.Skip)
{
results.Add(new(row.Line, label, ImportAction.Skip, [new("articolo", ImportErrors.CodeExists, IsWarning: true, Value: label)]));
continue;
}
edits.Add((new PriceEdit(itemId, list, party, value, from), results.Count));
results.Add(new(row.Line, label, update ? ImportAction.Update : ImportAction.Create, messages));
}
return new Plan(results, edits);
}
private sealed record Plan(IReadOnlyList<ImportRowResult> Results, IReadOnlyList<(PriceEdit Edit, int Result)> Edits);
}