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,442 @@
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.ImportExport;
/// <summary>
/// An entity of the guided import and export (SPEC §12.12): its columns, the check of the rows as if typed in its
/// record, the writing through its own service, and the export with the same columns so that a file exported can be
/// imported again.
/// </summary>
public interface IImportTarget
{
/// <summary>The key in addresses and texts (<c>clienti</c>, <c>piano-dei-conti</c>).</summary>
string Key { get; }
/// <summary>The licence module the entity belongs to.</summary>
string ModuleCode { get; }
/// <summary>The permission to import it (the write permission of its record).</summary>
string Permission { get; }
/// <summary>The permission to export it (besides the <i>can export</i> flag of the user).</summary>
string ExportPermission { get; }
/// <summary>Whether rows can be written now; otherwise the file is only checked (opening stock until M6, chart of accounts until M7).</summary>
bool CanApply { get; }
/// <summary>Whether there are records to export now.</summary>
bool CanExport { get; }
/// <summary>The columns, in the order of templates and exports.</summary>
IReadOnlyList<ImportField> Fields { get; }
/// <summary>Checks the rows without writing.</summary>
/// <param name="context">Who, where, how.</param>
/// <param name="rows">The rows.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A result per row, in order.</returns>
Task<IReadOnlyList<ImportRowResult>> CheckAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken);
/// <summary>Writes the rows without errors, each like a save of its record.</summary>
/// <param name="context">Who, where, how.</param>
/// <param name="rows">The rows.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A result per row, in order, with what was done.</returns>
Task<IReadOnlyList<ImportRowResult>> ApplyAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken);
/// <summary>The records as rows of cells in the order of <see cref="Fields"/>.</summary>
/// <param name="context">Who, where.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The rows.</returns>
Task<IReadOnlyList<IReadOnlyList<object?>>> ExportAsync(ImportContext context, CancellationToken cancellationToken);
}
/// <summary>Reads the cells of a row as values, adding a remark for every cell that is not what its field wants.</summary>
/// <param name="row">The row.</param>
/// <param name="messages">Where the remarks go.</param>
public sealed class CellReader(ImportRow row, List<ImportMessage> messages)
{
/// <summary>The row.</summary>
public ImportRow Row => row;
/// <summary>The remarks so far.</summary>
public List<ImportMessage> Messages => messages;
/// <summary>Whether the cell has a value.</summary>
/// <param name="key">The field.</param>
/// <returns><see langword="true"/> when not empty.</returns>
public bool Has(string key) => row[key] is not null;
/// <summary>The text of a cell.</summary>
/// <param name="key">The field.</param>
/// <returns>The text, or <see langword="null"/>.</returns>
public string? Text(string key) => row[key];
/// <summary>A number.</summary>
/// <param name="key">The field.</param>
/// <returns>The number, or <see langword="null"/> when empty or wrong (with a remark).</returns>
public decimal? Number(string key)
{
if (row[key] is not { } text)
{
return null;
}
if (ImportValues.TryNumber(text, out var value))
{
return value;
}
messages.Add(new(key, ImportErrors.Number, Value: text));
return null;
}
/// <summary>A date.</summary>
/// <param name="key">The field.</param>
/// <returns>The date, or <see langword="null"/> when empty or wrong (with a remark).</returns>
public DateOnly? Date(string key)
{
if (row[key] is not { } text)
{
return null;
}
if (ImportValues.TryDate(text, out var value))
{
return value;
}
messages.Add(new(key, ImportErrors.Date, Value: text));
return null;
}
/// <summary>Yes or no.</summary>
/// <param name="key">The field.</param>
/// <returns>The value, or <see langword="null"/> when empty or wrong (with a remark).</returns>
public bool? Boolean(string key)
{
if (row[key] is not { } text)
{
return null;
}
if (ImportValues.TryBoolean(text, out var value))
{
return value;
}
messages.Add(new(key, ImportErrors.Boolean, Value: text));
return null;
}
/// <summary>One of the words of a field.</summary>
/// <param name="field">The field with its choices.</param>
/// <returns>The position of the word, or <see langword="null"/> when empty or unknown (with a remark).</returns>
public int? Choice(ImportField field)
{
ArgumentNullException.ThrowIfNull(field);
if (row[field.Key] is not { } text)
{
return null;
}
var choices = field.Choices ?? [];
var index = ImportValues.Choice(text, choices);
if (index >= 0)
{
return index;
}
messages.Add(new(field.Key, ImportErrors.Choice, Value: string.Join(", ", choices)));
return null;
}
/// <summary>The id of a code of another archive or table.</summary>
/// <param name="key">The field.</param>
/// <param name="index">The codes.</param>
/// <returns>The id, or <see langword="null"/> when empty or unknown (with a remark).</returns>
public long? Code(string key, CodeIndex index)
{
ArgumentNullException.ThrowIfNull(index);
if (row[key] is not { } code)
{
return null;
}
if (index.Find(code) is { } id)
{
return id;
}
messages.Add(new(key, ImportErrors.CodeUnknown, Value: code));
return null;
}
}
/// <summary>The ids of the records of an archive or table by code, ignoring case.</summary>
public sealed class CodeIndex
{
private readonly Dictionary<string, long> _ids = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<long, string> _codes = [];
/// <summary>Creates an index.</summary>
/// <param name="entries">The codes with their ids.</param>
public CodeIndex(IEnumerable<(string Code, long Id)> entries)
{
ArgumentNullException.ThrowIfNull(entries);
foreach (var (code, id) in entries)
{
_ids.TryAdd(code, id);
_codes[id] = code;
}
}
/// <summary>The number of codes.</summary>
public int Count => _ids.Count;
/// <summary>Loads the codes of a table of the company.</summary>
/// <typeparam name="T">The table.</typeparam>
/// <param name="uow">The unit of work.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The index.</returns>
public static async Task<CodeIndex> LoadAsync<T>(IUnitOfWork uow, CancellationToken cancellationToken)
where T : CodedEntity, new()
{
ArgumentNullException.ThrowIfNull(uow);
var rows = await uow.Repository<T, long>().ListAsync(Query.For<T>(), cancellationToken).ConfigureAwait(false);
return new CodeIndex(rows.Items.Select(r => (r.Code, r.Id)));
}
/// <summary>The id of a code.</summary>
/// <param name="code">The code.</param>
/// <returns>The id, or <see langword="null"/>.</returns>
public long? Find(string? code) => code is not null && _ids.TryGetValue(code.Trim(), out var id) ? id : null;
/// <summary>The code of an id.</summary>
/// <param name="id">The id.</param>
/// <returns>The code, or <see langword="null"/>.</returns>
public string? CodeOf(long? id) => id is { } key && _codes.TryGetValue(key, out var code) ? code : null;
/// <summary>Adds a code written meanwhile.</summary>
/// <param name="code">The code.</param>
/// <param name="id">The id.</param>
public void Add(string code, long id)
{
ArgumentNullException.ThrowIfNull(code);
_ids[code] = id;
_codes[id] = code;
}
}
/// <summary>
/// The common steps of the entities written as records (parties, items): each row becomes a record, new or read by its
/// code, checked by the service of the record and saved by it, so the import obeys the same rules as the screen.
/// </summary>
/// <typeparam name="TRecord">The record.</typeparam>
/// <typeparam name="TState">What is loaded once per check or import (codes of tables and archives).</typeparam>
public abstract class RecordImportTarget<TRecord, TState> : IImportTarget
where TRecord : class
{
/// <inheritdoc />
public abstract string Key { get; }
/// <inheritdoc />
public abstract string ModuleCode { get; }
/// <inheritdoc />
public abstract string Permission { get; }
/// <inheritdoc />
public abstract string ExportPermission { get; }
/// <inheritdoc />
public bool CanApply => true;
/// <inheritdoc />
public bool CanExport => true;
/// <inheritdoc />
public abstract IReadOnlyList<ImportField> Fields { get; }
/// <summary>The column with the code of the record.</summary>
protected virtual string CodeField => "codice";
/// <inheritdoc />
public Task<IReadOnlyList<ImportRowResult>> CheckAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken) =>
RunAsync(context, rows, write: false, cancellationToken);
/// <inheritdoc />
public Task<IReadOnlyList<ImportRowResult>> ApplyAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken) =>
RunAsync(context, rows, write: true, cancellationToken);
/// <inheritdoc />
public abstract Task<IReadOnlyList<IReadOnlyList<object?>>> ExportAsync(ImportContext context, CancellationToken cancellationToken);
/// <summary>Loads what every row needs, checking a permission.</summary>
/// <param name="context">Who, where, how.</param>
/// <param name="permission">The permission demanded (to import or to export).</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The state.</returns>
protected abstract Task<TState> LoadAsync(ImportContext context, string permission, CancellationToken cancellationToken);
/// <summary>The id of an existing record with a code, or <see langword="null"/>; a remark refuses the code (another kind).</summary>
/// <param name="state">The state.</param>
/// <param name="code">The code.</param>
/// <param name="messages">Where remarks go.</param>
/// <returns>The id.</returns>
protected abstract long? Existing(TState state, string code, List<ImportMessage> messages);
/// <summary>A new record, or an existing one read by id.</summary>
/// <param name="context">Who, where.</param>
/// <param name="id">The id, or <see langword="null"/> for a new record.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The record.</returns>
protected abstract Task<TRecord?> OpenAsync(ImportContext context, long? id, CancellationToken cancellationToken);
/// <summary>Copies the cells of a row into the record; a code given for a new record is set too.</summary>
/// <param name="context">Who, where, how.</param>
/// <param name="state">The state.</param>
/// <param name="record">The record.</param>
/// <param name="cells">The row with its remarks.</param>
/// <param name="isNew">Whether the record is new.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
protected abstract Task FillAsync(ImportContext context, TState state, TRecord record, CellReader cells, bool isNew, CancellationToken cancellationToken);
/// <summary>Checks a record with the rules of its service.</summary>
/// <param name="context">Who, where.</param>
/// <param name="record">The record.</param>
/// <param name="isNew">Whether the record is new (its code is checked against the code rules).</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The problems.</returns>
protected abstract Task<IReadOnlyList<TableProblem>> ValidateAsync(ImportContext context, TRecord record, bool isNew, CancellationToken cancellationToken);
/// <summary>Saves a record with its service.</summary>
/// <param name="context">Who, where, how.</param>
/// <param name="record">The record.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The code and id given by the save.</returns>
protected abstract Task<(string Code, long Id)> SaveAsync(ImportContext context, TRecord record, CancellationToken cancellationToken);
/// <summary>What identifies the row in the preview (code, else description).</summary>
/// <param name="row">The row.</param>
/// <returns>The text.</returns>
protected abstract string Label(ImportRow row);
/// <summary>Records a code saved, so that later rows find it.</summary>
/// <param name="state">The state.</param>
/// <param name="code">The code.</param>
/// <param name="id">The id.</param>
protected abstract void Remember(TState state, string code, long id);
/// <summary>The column of a field of the service (<c>VatNumber</c>, <c>Fiscal.RecipientCode</c>); empty for the row.</summary>
/// <param name="serviceField">The field named by the service.</param>
/// <returns>The column key.</returns>
protected abstract string ColumnOf(string serviceField);
private async Task<IReadOnlyList<ImportRowResult>> RunAsync(ImportContext context, IReadOnlyList<ImportRow> rows, bool write, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
ArgumentNullException.ThrowIfNull(rows);
var state = await LoadAsync(context, Permission, cancellationToken).ConfigureAwait(false);
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var results = new List<ImportRowResult>(rows.Count);
foreach (var row in rows)
{
cancellationToken.ThrowIfCancellationRequested();
var messages = new List<ImportMessage>();
var cells = new CellReader(row, messages);
var code = row[CodeField];
long? id = null;
if (code is not null)
{
if (!seen.Add(code))
{
messages.Add(new(CodeField, ImportErrors.CodeRepeated, Value: code));
results.Add(new(row.Line, Label(row), ImportAction.Skip, messages));
continue;
}
id = Existing(state, code, messages);
if (messages.Count > 0)
{
results.Add(new(row.Line, Label(row), ImportAction.Skip, messages));
continue;
}
if (id is not null && context.Options.Existing == ExistingCodeAction.Skip)
{
results.Add(new(row.Line, Label(row), ImportAction.Skip, [new(CodeField, ImportErrors.CodeExists, IsWarning: true, Value: code)]));
continue;
}
}
else if (context.Options.Missing == MissingCodeAction.Refuse)
{
messages.Add(new(CodeField, ImportErrors.CodeMissing));
results.Add(new(row.Line, Label(row), ImportAction.Skip, messages));
continue;
}
var isNew = id is null;
var action = isNew ? ImportAction.Create : ImportAction.Update;
var record = await OpenAsync(context, id, cancellationToken).ConfigureAwait(false);
if (record is null)
{
messages.Add(new(CodeField, ImportErrors.WriteFailed, Value: code));
results.Add(new(row.Line, Label(row), ImportAction.Skip, messages));
continue;
}
await FillAsync(context, state, record, cells, isNew, cancellationToken).ConfigureAwait(false);
if (isNew)
{
messages.AddRange(Fields.Where(f => f.Required && !cells.Has(f.Key) && messages.All(m => m.Field != f.Key))
.Select(f => new ImportMessage(f.Key, ImportErrors.Required)));
}
if (messages.All(m => m.IsWarning))
{
messages.AddRange((await ValidateAsync(context, record, isNew, cancellationToken).ConfigureAwait(false))
.Select(p => new ImportMessage(ColumnOf(p.Field), p.Code, p.IsWarning)));
}
if (write && messages.All(m => m.IsWarning))
{
try
{
var (savedCode, savedId) = await SaveAsync(context, record, cancellationToken).ConfigureAwait(false);
Remember(state, savedCode, savedId);
}
catch (ValidationFailedException ex)
{
messages.AddRange(ex.Errors.Select(TableErrors.Split).Select(e => new ImportMessage(ColumnOf(e.Field), e.Code)));
}
catch (Core.Common.ConcurrencyException)
{
messages.Add(new(string.Empty, ImportErrors.WriteFailed));
}
}
results.Add(new(row.Line, Label(row), messages.Any(m => !m.IsWarning) ? ImportAction.Skip : action, messages));
}
return results;
}
}
/// <summary>Splits the <c>Field:code</c> errors of <see cref="ValidationFailedException"/>.</summary>
internal static class TableErrors
{
/// <summary>Splits an error.</summary>
/// <param name="error">The error.</param>
/// <returns>The field (empty for the record) and the code.</returns>
public static (string Field, string Code) Split(string error)
{
var colon = error.LastIndexOf(':');
return colon < 0 ? (string.Empty, error) : (error[..colon], error[(colon + 1)..]);
}
}