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,332 @@
using Khaemhat.Application.Modules;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Accounting;
using Khaemhat.Core.Items;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.ImportExport;
/// <summary>An account of the chart read from a file.</summary>
/// <param name="Code">The code, parts separated by points (<c>01.02.003</c>).</param>
/// <param name="Description">The description.</param>
/// <param name="Level">The level, 1 to 3: the number of parts of the code.</param>
/// <param name="ParentCode">The code without its last part.</param>
/// <param name="Nature">The nature.</param>
/// <param name="Type">The use.</param>
/// <param name="Postable">Postings go on it (only leaves).</param>
/// <param name="VatRelevant">Relevant for VAT.</param>
/// <param name="SubLedger">With a sub-ledger of customers or suppliers.</param>
/// <param name="ClosesAutomatically">Closed by the year end.</param>
/// <param name="Disabled">Not used any more.</param>
public sealed record ImportedAccount(
string Code, string Description, int Level, string? ParentCode, AccountNature Nature, AccountType Type, bool Postable, bool VatRelevant, bool SubLedger,
bool ClosesAutomatically, bool Disabled);
/// <summary>
/// The checks of a chart of accounts from a file (SPEC §12.12, ADR 0031): codes of one to three parts separated by
/// points, each account under the account whose code is its own without the last part, with the same nature; only
/// leaves are postable. Pure, so that M7 writes what this checks.
/// </summary>
public static class ChartOfAccountsImportValidator
{
/// <summary>The words of <c>natura</c>, in the order of <see cref="AccountNature"/>.</summary>
public static readonly IReadOnlyList<string> NatureWords = ["attivo", "passivo", "costo", "ricavo", "ordine"];
/// <summary>The words of <c>tipo</c>, in the order of <see cref="AccountType"/>.</summary>
public static readonly IReadOnlyList<string> TypeWords = ["generico", "clienti", "fornitori", "banca", "cassa", "iva", "erario"];
/// <summary>The flag letters: postable, VAT relevant, sub-ledger, automatic closing, disabled.</summary>
public const string FlagLetters = "MIPCX";
/// <summary>The deepest level.</summary>
public const int MaxLevel = 3;
/// <summary>The columns of the chart.</summary>
public static IReadOnlyList<ImportField> Fields { get; } =
[
new("codice", ImportFieldKind.Code, Required: true, Aliases: ["conto", "codice_conto", "cod_conto"]),
new("descrizione", Required: true, Aliases: ["descr", "denominazione"]),
new("livello", ImportFieldKind.Number, Aliases: ["liv"]),
new("padre", ImportFieldKind.Code, Aliases: ["conto_padre", "mastro"]),
new("natura", ImportFieldKind.Choice, Aliases: ["sezione"], Choices: NatureWords),
new("tipo", ImportFieldKind.Choice, Aliases: ["tipo_conto"], Choices: TypeWords),
new("voce_cee", Aliases: ["cee", "voce_bilancio"]),
new("riclassifica", Aliases: ["riclassificazione"]),
new("flag", Aliases: ["flags", "attributi"]),
];
/// <summary>Checks the rows of a chart.</summary>
/// <param name="rows">The rows.</param>
/// <returns>A result per row, and the accounts without errors.</returns>
public static (IReadOnlyList<ImportRowResult> Results, IReadOnlyList<ImportedAccount> Accounts) Check(IReadOnlyList<ImportRow> rows)
{
ArgumentNullException.ThrowIfNull(rows);
// First pass: every code with its nature as written, to check parents wherever they are in the file.
var natures = new Dictionary<string, AccountNature?>(StringComparer.OrdinalIgnoreCase);
foreach (var row in rows)
{
if (row["codice"] is { } code)
{
natures.TryAdd(code, Choice(row["natura"], NatureWords) is { } n ? (AccountNature)n : null);
}
}
var parents = natures.Keys.Select(ParentOf).Where(p => p is not null).ToHashSet(StringComparer.OrdinalIgnoreCase);
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var results = new List<ImportRowResult>(rows.Count);
var accounts = new List<ImportedAccount>();
foreach (var row in rows)
{
var messages = new List<ImportMessage>();
var cells = new CellReader(row, messages);
var code = row["codice"];
messages.AddRange(Fields.Where(f => f.Required && !cells.Has(f.Key)).Select(f => new ImportMessage(f.Key, ImportErrors.Required)));
if (code is null)
{
results.Add(new(row.Line, row["descrizione"] ?? string.Empty, ImportAction.Skip, messages));
continue;
}
if (!seen.Add(code))
{
results.Add(new(row.Line, code, ImportAction.Skip, [new("codice", ImportErrors.CodeRepeated, Value: code)]));
continue;
}
var parts = code.Split('.');
var level = parts.Length;
if (level > MaxLevel || parts.Any(p => p.Length == 0 || !p.All(char.IsAsciiLetterOrDigit)))
{
messages.Add(new("codice", ImportErrors.AccountLevel, Value: code));
}
else if (cells.Number("livello") is { } written && written != level)
{
messages.Add(new("livello", ImportErrors.AccountLevel, Value: level.ToString(System.Globalization.CultureInfo.InvariantCulture)));
}
var parent = ParentOf(code);
if (row["padre"] is { } named && !string.Equals(named, parent, StringComparison.OrdinalIgnoreCase))
{
messages.Add(new("padre", ImportErrors.AccountParent, Value: parent ?? string.Empty));
}
else if (parent is not null && !natures.ContainsKey(parent))
{
messages.Add(new("padre", ImportErrors.AccountParent, Value: parent));
}
var nature = NatureOf(code, natures);
if (nature is null)
{
messages.Add(new("natura", cells.Has("natura") ? ImportErrors.Choice : ImportErrors.Required, Value: cells.Has("natura") ? string.Join(", ", NatureWords) : null));
}
else if (parent is not null && natures.ContainsKey(parent) && NatureOf(parent, natures) is { } parentNature && parentNature != nature)
{
messages.Add(new("natura", ImportErrors.AccountNature, Value: NatureWords[(int)parentNature]));
}
var type = cells.Choice(Fields[5]) is { } t ? (AccountType)t : AccountType.Generic;
var flags = (row["flag"] ?? string.Empty).ToUpperInvariant().Where(c => !char.IsWhiteSpace(c) && c is not ',' and not ';').ToList();
if (flags.FirstOrDefault(c => !FlagLetters.Contains(c, StringComparison.Ordinal)) is var bad && bad != default)
{
messages.Add(new("flag", ImportErrors.AccountFlag, Value: bad.ToString()));
}
var postable = flags.Contains('M');
var leaf = !parents.Contains(code);
if (postable && !leaf)
{
messages.Add(new("flag", ImportErrors.AccountPostable));
}
else if (!postable && leaf && level > 1)
{
messages.Add(new("flag", ImportErrors.AccountLeaf, IsWarning: true));
}
if (messages.All(m => m.IsWarning) && nature is { } valid)
{
accounts.Add(new(code, row["descrizione"] ?? string.Empty, level, parent, valid, type, postable, flags.Contains('I'), flags.Contains('P'), flags.Contains('C'),
flags.Contains('X')));
}
results.Add(new(row.Line, code, messages.Any(m => !m.IsWarning) ? ImportAction.Skip : ImportAction.Create, messages));
}
return (results, accounts);
}
/// <summary>The code without its last part, or <see langword="null"/> for a first level account.</summary>
/// <param name="code">The code.</param>
/// <returns>The parent code.</returns>
public static string? ParentOf(string code)
{
ArgumentNullException.ThrowIfNull(code);
var point = code.LastIndexOf('.');
return point <= 0 ? null : code[..point];
}
// The nature written on the account, else the one of the nearest ancestor that has one.
private static AccountNature? NatureOf(string code, Dictionary<string, AccountNature?> natures)
{
for (var current = code; current is not null; current = ParentOf(current))
{
if (natures.TryGetValue(current, out var nature) && nature is not null)
{
return nature;
}
}
return null;
}
private static int? Choice(string? text, IReadOnlyList<string> words) => text is null ? null : ImportValues.Choice(text, words) is var i and >= 0 ? i : null;
}
/// <summary>
/// The chart of accounts (<c>piano-dei-conti</c>): CSV, XLSX or <c>khaemhat-coa.json</c>. Until the ledger exists (M7)
/// the file is only checked; M7 writes the accounts this check accepts.
/// </summary>
/// <param name="permissions">Checks the permission.</param>
public sealed class ChartOfAccountsImportTarget(PermissionService permissions) : IImportTarget
{
/// <summary>The permission to change the chart of accounts.</summary>
public const string WritePermission = "ledger.account.write";
/// <inheritdoc />
public string Key => "piano-dei-conti";
/// <inheritdoc />
public string ModuleCode => ModuleCodes.Accounting;
/// <inheritdoc />
public string Permission => WritePermission;
/// <inheritdoc />
public string ExportPermission => "ledger.account.read";
/// <inheritdoc />
public bool CanApply => false;
/// <inheritdoc />
public bool CanExport => false;
/// <inheritdoc />
public IReadOnlyList<ImportField> Fields => ChartOfAccountsImportValidator.Fields;
/// <inheritdoc />
public async Task<IReadOnlyList<ImportRowResult>> CheckAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
await CompanyGuard.DemandAsync(permissions, context.Actor, context.CompanyCode, Permission, cancellationToken).ConfigureAwait(false);
return ChartOfAccountsImportValidator.Check(rows).Results;
}
/// <inheritdoc />
public Task<IReadOnlyList<ImportRowResult>> ApplyAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken) =>
throw new InvalidOperationException(ImportErrors.CheckOnly);
/// <inheritdoc />
public Task<IReadOnlyList<IReadOnlyList<object?>>> ExportAsync(ImportContext context, CancellationToken cancellationToken) =>
Task.FromResult<IReadOnlyList<IReadOnlyList<object?>>>([]);
}
/// <summary>
/// The opening stock (<c>giacenze-iniziali</c>): item, warehouse, quantity and unit cost. Until the stock entries exist
/// (M6) the file is only checked; M6 writes the opening entry from the rows this check accepts.
/// </summary>
/// <param name="factory">Opens the company databases.</param>
/// <param name="permissions">Checks the permission.</param>
public sealed class OpeningStockImportTarget(IUnitOfWorkFactory factory, PermissionService permissions) : IImportTarget
{
private static readonly ImportField[] StockFields =
[
new("articolo", ImportFieldKind.Code, Required: true, Aliases: ["codice_articolo", "codice", "cod_articolo", "sku"]),
new("deposito", ImportFieldKind.Code, Aliases: ["magazzino", "codice_magazzino"]),
new("quantita", ImportFieldKind.Number, Required: true, Aliases: ["qta", "qty", "giacenza", "esistenza"]),
new("costo_unitario", ImportFieldKind.Number, Aliases: ["costo", "valore_unitario", "prezzo_acquisto"]),
];
/// <inheritdoc />
public string Key => "giacenze-iniziali";
/// <inheritdoc />
public string ModuleCode => ModuleCodes.Core;
/// <inheritdoc />
public string Permission => "inventory.entry.write";
/// <inheritdoc />
public string ExportPermission => "inventory.stock.read";
/// <inheritdoc />
public bool CanApply => false;
/// <inheritdoc />
public bool CanExport => false;
/// <inheritdoc />
public IReadOnlyList<ImportField> Fields => StockFields;
/// <inheritdoc />
public async Task<IReadOnlyList<ImportRowResult>> CheckAsync(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 = (await uow.Repository<Item, long>().ListAsync(Query.For<Item>(), cancellationToken).ConfigureAwait(false)).Items;
var codes = new CodeIndex(items.Select(i => (i.Code, i.Id)));
var byId = items.ToDictionary(i => i.Id);
var warehouses = await CodeIndex.LoadAsync<Warehouse>(uow, cancellationToken).ConfigureAwait(false);
var seen = new HashSet<(long, long)>();
var results = new List<ImportRowResult>(rows.Count);
foreach (var row in rows)
{
var messages = new List<ImportMessage>();
var cells = new CellReader(row, messages);
messages.AddRange(StockFields.Where(f => f.Required && !cells.Has(f.Key)).Select(f => new ImportMessage(f.Key, ImportErrors.Required)));
var item = cells.Code("articolo", codes) is { } id ? byId[id] : null;
var warehouse = cells.Code("deposito", warehouses) ?? (cells.Has("deposito") ? null : item?.WarehouseId);
if (item is not null && (item.Kind != ItemKind.Goods || !item.Stocked))
{
messages.Add(new("articolo", ImportErrors.NotStocked, Value: item.Code));
}
if (item is not null && warehouse is null && !cells.Has("deposito"))
{
messages.Add(new("deposito", ImportErrors.Required));
}
if (cells.Number("quantita") is <= 0)
{
messages.Add(new("quantita", ImportErrors.Positive));
}
if (cells.Number("costo_unitario") is < 0)
{
messages.Add(new("costo_unitario", Items.ItemService.NotNegative));
}
var label = row["articolo"] ?? string.Empty;
if (item is not null && warehouse is { } w && !seen.Add((item.Id, w)))
{
messages.Add(new("articolo", ImportErrors.CodeRepeated, Value: label));
}
results.Add(new(row.Line, label, messages.Any(m => !m.IsWarning) ? ImportAction.Skip : ImportAction.Create, messages));
}
return results;
}
/// <inheritdoc />
public Task<IReadOnlyList<ImportRowResult>> ApplyAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken) =>
throw new InvalidOperationException(ImportErrors.CheckOnly);
/// <inheritdoc />
public Task<IReadOnlyList<IReadOnlyList<object?>>> ExportAsync(ImportContext context, CancellationToken cancellationToken) =>
Task.FromResult<IReadOnlyList<IReadOnlyList<object?>>>([]);
}
@@ -0,0 +1,255 @@
using System.Globalization;
using System.Text;
using System.Text.Json;
using Khaemhat.Infrastructure.Files;
namespace Khaemhat.Application.ImportExport;
/// <summary>A file the import cannot use; <see cref="Code"/> is one of the <c>import.file.*</c> codes.</summary>
public sealed class ImportFileException : Exception
{
/// <summary>Creates the exception.</summary>
public ImportFileException()
{
Code = ImportErrors.FileUnreadable;
}
/// <summary>Creates the exception.</summary>
/// <param name="message">What went wrong.</param>
public ImportFileException(string message)
: base(message)
{
Code = ImportErrors.FileUnreadable;
}
/// <summary>Creates the exception.</summary>
/// <param name="message">What went wrong.</param>
/// <param name="innerException">The cause.</param>
public ImportFileException(string message, Exception innerException)
: base(message, innerException)
{
Code = ImportErrors.FileUnreadable;
}
/// <summary>Creates the exception with a code.</summary>
/// <param name="code">The text code.</param>
/// <param name="message">What went wrong.</param>
/// <param name="innerException">The cause.</param>
public ImportFileException(string code, string message, Exception? innerException)
: base(message, innerException)
{
Code = code;
}
/// <summary>The text code.</summary>
public string Code { get; }
}
/// <summary>
/// Reads the files of the guided import (SPEC §12.12): CSV (UTF-8 with or without byte order mark, else Windows-1252;
/// separator <c>;</c>, <c>,</c> or tab guessed from the header), XLSX (first sheet) and JSON (an array of objects, or the
/// object of <c>khaemhat-coa.json</c> with its <c>accounts</c>). The first row holds the headers.
/// </summary>
public static class ImportFileReader
{
/// <summary>The most data rows an import takes.</summary>
public const int MaxRows = 50_000;
/// <summary>The format name written in <c>khaemhat-coa.json</c>.</summary>
public const string ChartFormat = "khaemhat-coa";
private static readonly UTF8Encoding StrictUtf8 = new(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);
/// <summary>The format of a file from its name.</summary>
/// <param name="fileName">The name.</param>
/// <returns>The format, or <see langword="null"/> when not supported.</returns>
public static TransferFormat? FormatOf(string? fileName) => Path.GetExtension(fileName ?? string.Empty).ToUpperInvariant() switch
{
".CSV" or ".TXT" => TransferFormat.Csv,
".XLSX" => TransferFormat.Xlsx,
".JSON" => TransferFormat.Json,
_ => null,
};
/// <summary>Reads a file.</summary>
/// <param name="fileName">The name, which gives the format.</param>
/// <param name="content">The content.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The file with headers and rows.</returns>
/// <exception cref="ImportFileException">The format is not supported, or the file is empty, damaged or too large.</exception>
public static async Task<ImportFile> ReadAsync(string fileName, Stream content, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(fileName);
ArgumentNullException.ThrowIfNull(content);
var format = FormatOf(fileName) ?? throw new ImportFileException(ImportErrors.FileFormat, "Not CSV, XLSX or JSON: " + fileName, null);
using var buffer = new MemoryStream();
await content.CopyToAsync(buffer, cancellationToken).ConfigureAwait(false);
buffer.Position = 0;
return format switch
{
TransferFormat.Xlsx => await ReadXlsxAsync(fileName, buffer, cancellationToken).ConfigureAwait(false),
TransferFormat.Json => ReadJson(fileName, buffer.ToArray()),
_ => ReadCsv(fileName, buffer.ToArray()),
};
}
/// <summary>Reads CSV bytes.</summary>
/// <param name="fileName">The name.</param>
/// <param name="bytes">The content.</param>
/// <returns>The file.</returns>
/// <exception cref="ImportFileException">Empty or too large.</exception>
public static ImportFile ReadCsv(string fileName, byte[] bytes)
{
ArgumentNullException.ThrowIfNull(bytes);
string text;
string encoding;
var start = bytes.Length >= 3 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF ? 3 : 0;
try
{
text = StrictUtf8.GetString(bytes, start, bytes.Length - start);
encoding = "UTF-8";
}
catch (DecoderFallbackException)
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
text = Encoding.GetEncoding(1252).GetString(bytes);
encoding = "Windows-1252";
}
var separator = Guess(text);
var lines = CsvReader.Parse(text, separator);
return Build(fileName, TransferFormat.Csv, encoding, separator, lines, null);
}
private static async Task<ImportFile> ReadXlsxAsync(string fileName, Stream content, CancellationToken cancellationToken)
{
try
{
var rows = await XlsxReader.ReadAsync(content, cancellationToken).ConfigureAwait(false);
return Build(fileName, TransferFormat.Xlsx, null, null, rows, null);
}
catch (XlsxReadException ex)
{
throw new ImportFileException(ImportErrors.FileUnreadable, ex.Message, ex);
}
}
private static ImportFile ReadJson(string fileName, byte[] bytes)
{
JsonDocument document;
try
{
document = JsonDocument.Parse(bytes, new JsonDocumentOptions { MaxDepth = 16, AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip });
}
catch (JsonException ex)
{
throw new ImportFileException(ImportErrors.FileUnreadable, ex.Message, ex);
}
using (document)
{
var root = document.RootElement;
Dictionary<string, int>? sections = null;
JsonElement records;
if (root.ValueKind == JsonValueKind.Array)
{
records = root;
}
else if (root.ValueKind == JsonValueKind.Object && root.TryGetProperty("accounts", out var accounts) && accounts.ValueKind == JsonValueKind.Array)
{
records = accounts;
sections = new Dictionary<string, int>(StringComparer.Ordinal);
foreach (var property in root.EnumerateObject())
{
if (property.Name != "accounts" && property.Value.ValueKind == JsonValueKind.Array)
{
sections[property.Name] = property.Value.GetArrayLength();
}
}
}
else
{
throw new ImportFileException(ImportErrors.FileUnreadable, "Neither an array of objects nor a chart of accounts.", null);
}
var headers = new List<string>();
var index = new Dictionary<string, int>(StringComparer.Ordinal);
var objects = new List<Dictionary<string, string>>();
foreach (var element in records.EnumerateArray())
{
if (element.ValueKind != JsonValueKind.Object)
{
throw new ImportFileException(ImportErrors.FileUnreadable, "An entry is not an object.", null);
}
var values = new Dictionary<string, string>(StringComparer.Ordinal);
foreach (var property in element.EnumerateObject())
{
if (index.TryAdd(property.Name, headers.Count))
{
headers.Add(property.Name);
}
values[property.Name] = Cell(property.Value);
}
objects.Add(values);
}
var rows = new List<IReadOnlyList<string>> { headers };
rows.AddRange(objects.Select(o => (IReadOnlyList<string>)[.. headers.Select(h => o.GetValueOrDefault(h, string.Empty))]));
return Build(fileName, TransferFormat.Json, "UTF-8", null, rows, sections);
}
}
private static string Cell(JsonElement value) => value.ValueKind switch
{
JsonValueKind.String => value.GetString() ?? string.Empty,
JsonValueKind.Number => value.GetRawText(),
JsonValueKind.True => "true",
JsonValueKind.False => "false",
JsonValueKind.Null or JsonValueKind.Undefined => string.Empty,
_ => value.GetRawText(),
};
private static ImportFile Build(string fileName, TransferFormat format, string? encoding, char? separator, IReadOnlyList<IReadOnlyList<string>> lines,
IReadOnlyDictionary<string, int>? sections)
{
if (lines.Count == 0 || lines[0].All(string.IsNullOrWhiteSpace))
{
throw new ImportFileException(ImportErrors.FileEmpty, "No header.", null);
}
if (lines.Count - 1 > MaxRows)
{
throw new ImportFileException(ImportErrors.FileTooLarge, "More than " + MaxRows.ToString(CultureInfo.InvariantCulture) + " rows.", null);
}
var headers = lines[0].Select((h, i) => string.IsNullOrWhiteSpace(h) ? "colonna_" + (i + 1).ToString(CultureInfo.InvariantCulture) : h.Trim()).ToList();
var rows = new List<IReadOnlyList<string>>(lines.Count - 1);
foreach (var line in lines.Skip(1))
{
if (line.All(string.IsNullOrWhiteSpace))
{
continue;
}
rows.Add([.. Enumerable.Range(0, headers.Count).Select(i => i < line.Count ? Unprotect(line[i]) : string.Empty)]);
}
return new ImportFile(Path.GetFileName(fileName), format, encoding, separator, headers, rows, sections);
}
// The apostrophe the export puts before text that a spreadsheet would read as a formula (CsvWriter).
private static string Unprotect(string cell) =>
cell.Length > 1 && cell[0] == '\'' && cell[1] is '=' or '+' or '-' or '@' ? cell[1..].Trim() : cell.Trim();
private static char Guess(string text)
{
var end = text.IndexOfAny(['\r', '\n']);
var first = end < 0 ? text : text[..end];
return Separators.OrderByDescending(s => first.Count(c => c == s)).First();
}
private static readonly char[] Separators = [';', ',', '\t'];
}
@@ -0,0 +1,197 @@
using Khaemhat.Application.Security;
namespace Khaemhat.Application.ImportExport;
/// <summary>The formats of the guided import and export (SPEC §12.12).</summary>
public enum TransferFormat
{
/// <summary>Text with <c>;</c>, UTF-8 (other separators and Windows-1252 are recognized when reading).</summary>
Csv = 0,
/// <summary>Excel workbook, first sheet, headers in the first row.</summary>
Xlsx = 1,
/// <summary>JSON: an array of objects keyed by column, or the object of <c>khaemhat-coa.json</c>.</summary>
Json = 2,
}
/// <summary>The kind of value of a column, for reading and writing it.</summary>
public enum ImportFieldKind
{
/// <summary>Free text.</summary>
Text = 0,
/// <summary>A code of another archive or table.</summary>
Code = 1,
/// <summary>A decimal number (Italian or invariant notation).</summary>
Number = 2,
/// <summary>A date (<c>dd/MM/yyyy</c>, ISO or a spreadsheet serial).</summary>
Date = 3,
/// <summary>Yes or no.</summary>
Boolean = 4,
/// <summary>One of a list of words.</summary>
Choice = 5,
}
/// <summary>A column an entity accepts.</summary>
/// <param name="Key">The column name used in files and templates (<c>partita_iva</c>).</param>
/// <param name="Kind">The kind of value.</param>
/// <param name="Required">Whether a new record needs it.</param>
/// <param name="Aliases">Other headers recognized by the automatic mapping, already normalized.</param>
/// <param name="Choices">The words accepted for <see cref="ImportFieldKind.Choice"/>.</param>
public sealed record ImportField(string Key, ImportFieldKind Kind = ImportFieldKind.Text, bool Required = false, IReadOnlyList<string>? Aliases = null,
IReadOnlyList<string>? Choices = null);
/// <summary>A file read for the import.</summary>
/// <param name="Name">The file name.</param>
/// <param name="Format">The format.</param>
/// <param name="Encoding">The text encoding (CSV), such as <c>UTF-8</c>.</param>
/// <param name="Separator">The separator (CSV).</param>
/// <param name="Headers">The headers of the columns.</param>
/// <param name="Rows">The rows under the headers, each as long as the headers.</param>
/// <param name="Sections">For <c>khaemhat-coa.json</c>: the other sections with their number of entries.</param>
public sealed record ImportFile(string Name, TransferFormat Format, string? Encoding, char? Separator, IReadOnlyList<string> Headers,
IReadOnlyList<IReadOnlyList<string>> Rows, IReadOnlyDictionary<string, int>? Sections = null)
{
/// <summary>The number of data rows.</summary>
public int Count => Rows.Count;
}
/// <summary>What happens to a row whose code is already in the archive.</summary>
public enum ExistingCodeAction
{
/// <summary>The record is updated with the non empty cells of the row.</summary>
Update = 0,
/// <summary>The row is skipped.</summary>
Skip = 1,
}
/// <summary>What happens to a row without a code.</summary>
public enum MissingCodeAction
{
/// <summary>The code comes from the automatic code rules.</summary>
Generate = 0,
/// <summary>The row is an error.</summary>
Refuse = 1,
}
/// <summary>The options of an import (mockup 077, step 1).</summary>
public sealed record ImportOptions
{
/// <summary>Rows whose code exists.</summary>
public ExistingCodeAction Existing { get; init; } = ExistingCodeAction.Update;
/// <summary>Rows without a code.</summary>
public MissingCodeAction Missing { get; init; } = MissingCodeAction.Generate;
/// <summary>Check the VAT numbers of EU parties on VIES while importing.</summary>
public bool VerifyVat { get; init; }
/// <summary>Fill the city from the postal code (and the postal code from the city) when one is missing.</summary>
public bool FillFromPostalCode { get; init; } = true;
}
/// <summary>Who imports, where and how: what a target needs besides the rows.</summary>
/// <param name="Actor">Who imports.</param>
/// <param name="CompanyCode">The company.</param>
/// <param name="Options">The options.</param>
public sealed record ImportContext(Actor Actor, string CompanyCode, ImportOptions Options);
/// <summary>A row of the file with the cells of the mapped columns by field key.</summary>
/// <param name="Line">The line in the file, counting the header as line 1.</param>
/// <param name="Values">The trimmed cells by field key; empty cells are left out.</param>
public sealed record ImportRow(int Line, IReadOnlyDictionary<string, string> Values)
{
/// <summary>The cell of a field, or <see langword="null"/> when empty or not mapped.</summary>
/// <param name="key">The field.</param>
/// <returns>The text.</returns>
public string? this[string key] => Values.TryGetValue(key, out var value) ? value : null;
}
/// <summary>The outcome of a row in the preview (mockup 077: OK, avviso, errore).</summary>
public enum ImportOutcome
{
/// <summary>Importable.</summary>
Ok = 0,
/// <summary>Importable, with a correction proposed or a remark.</summary>
Warning = 1,
/// <summary>Not importable.</summary>
Error = 2,
}
/// <summary>What the import does with a row.</summary>
public enum ImportAction
{
/// <summary>A new record.</summary>
Create = 0,
/// <summary>An existing record changes.</summary>
Update = 1,
/// <summary>Nothing (existing code to skip, or an error).</summary>
Skip = 2,
}
/// <summary>A remark on a row: a text code with the field it concerns.</summary>
/// <param name="Field">The field key, or empty for the whole row.</param>
/// <param name="Code">The text code (an error code of the services or <c>import.*</c>).</param>
/// <param name="IsWarning">A warning instead of an error.</param>
/// <param name="Value">A value to show in the text (<c>{0}</c>), such as the code not found or the city proposed.</param>
public sealed record ImportMessage(string Field, string Code, bool IsWarning = false, string? Value = null);
/// <summary>The check of a row.</summary>
/// <param name="Line">The line in the file.</param>
/// <param name="Key">The code or description that identifies the row in the preview.</param>
/// <param name="Action">What the import will do.</param>
/// <param name="Messages">The remarks.</param>
public sealed record ImportRowResult(int Line, string Key, ImportAction Action, IReadOnlyList<ImportMessage> Messages)
{
/// <summary>The outcome from the remarks.</summary>
public ImportOutcome Outcome =>
Messages.Any(m => !m.IsWarning) ? ImportOutcome.Error : Messages.Count > 0 ? ImportOutcome.Warning : ImportOutcome.Ok;
}
/// <summary>The preview of an import (mockup 077, steps 3 and 4).</summary>
/// <param name="Target">The entity.</param>
/// <param name="Rows">The checked rows, in file order.</param>
/// <param name="CanApply">Whether the entity can be written now (opening stock and chart of accounts only check, until M6 and M7).</param>
public sealed record ImportPreview(string Target, IReadOnlyList<ImportRowResult> Rows, bool CanApply)
{
/// <summary>Rows that will create a record.</summary>
public int Creates => Rows.Count(r => r.Outcome != ImportOutcome.Error && r.Action == ImportAction.Create);
/// <summary>Rows that will update a record.</summary>
public int Updates => Rows.Count(r => r.Outcome != ImportOutcome.Error && r.Action == ImportAction.Update);
/// <summary>Rows skipped on purpose.</summary>
public int Skips => Rows.Count(r => r.Outcome != ImportOutcome.Error && r.Action == ImportAction.Skip);
/// <summary>Rows with errors.</summary>
public int Errors => Rows.Count(r => r.Outcome == ImportOutcome.Error);
/// <summary>Rows with warnings only.</summary>
public int Warnings => Rows.Count(r => r.Outcome == ImportOutcome.Warning);
/// <summary>Rows the import writes.</summary>
public int Importable => Creates + Updates;
}
/// <summary>The result of an import.</summary>
/// <param name="Target">The entity.</param>
/// <param name="Created">Records created.</param>
/// <param name="Updated">Records updated.</param>
/// <param name="Skipped">Rows skipped on purpose.</param>
/// <param name="Rows">Every row with its final outcome; rows refused while writing carry their errors.</param>
public sealed record ImportReport(string Target, int Created, int Updated, int Skipped, IReadOnlyList<ImportRowResult> Rows)
{
/// <summary>Rows not imported because of errors.</summary>
public int Failed => Rows.Count(r => r.Outcome == ImportOutcome.Error);
}
@@ -0,0 +1,375 @@
using System.Text.Json;
using Khaemhat.Application.Licensing;
using Khaemhat.Application.Security;
using Khaemhat.Core.Logging;
using Khaemhat.Infrastructure.Files;
using Microsoft.Extensions.Logging;
namespace Khaemhat.Application.ImportExport;
/// <summary>
/// The guided import and export (SPEC §11.7, §12.12, mockup 077, ADR 0031): the entities the licence allows, the
/// automatic mapping of the columns, the preview that checks every row as if typed in its record, the import of the
/// rows without errors, the error report, the export with the same columns and the empty templates.
/// </summary>
public sealed partial class ImportService
{
private static readonly JsonWriterOptions JsonOptions = new() { Indented = true };
private readonly IReadOnlyList<IImportTarget> _targets;
private readonly ILicenseGate _license;
private readonly PermissionService _permissions;
private readonly ILogger<ImportService> _logger;
/// <summary>Creates the service.</summary>
/// <param name="targets">The entities.</param>
/// <param name="license">The licence.</param>
/// <param name="permissions">The permissions and the user flags.</param>
/// <param name="logger">The log.</param>
public ImportService(IEnumerable<IImportTarget> targets, ILicenseGate license, PermissionService permissions, ILogger<ImportService> logger)
{
ArgumentNullException.ThrowIfNull(targets);
ArgumentNullException.ThrowIfNull(license);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(logger);
_targets = [.. targets];
_license = license;
_permissions = permissions;
_logger = logger;
}
/// <summary>The entities whose module is licensed, in the order of the screen.</summary>
public IReadOnlyList<IImportTarget> Targets => [.. _targets.Where(t => _license.IsModuleActive(t.ModuleCode))];
/// <summary>A licensed entity by key.</summary>
/// <param name="key">The key.</param>
/// <returns>The entity.</returns>
/// <exception cref="ImportFileException">Unknown or not licensed (<see cref="ImportErrors.TargetUnknown"/>).</exception>
public IImportTarget Target(string key) =>
Targets.FirstOrDefault(t => string.Equals(t.Key, key, StringComparison.OrdinalIgnoreCase))
?? throw new ImportFileException(ImportErrors.TargetUnknown, "Unknown import: " + key, null);
/// <summary>
/// The field of each column of a file, by name or alias ignoring case, accents and punctuation; a field goes to one
/// column only.
/// </summary>
/// <param name="target">The entity.</param>
/// <param name="headers">The headers.</param>
/// <returns>The field key per column, or <see langword="null"/> for columns to ignore.</returns>
public static IReadOnlyList<string?> SuggestMapping(IImportTarget target, IReadOnlyList<string> headers)
{
ArgumentNullException.ThrowIfNull(target);
ArgumentNullException.ThrowIfNull(headers);
var taken = new HashSet<string>(StringComparer.Ordinal);
var mapping = new string?[headers.Count];
for (var pass = 0; pass < 2; pass++)
{
for (var i = 0; i < headers.Count; i++)
{
if (mapping[i] is not null)
{
continue;
}
var header = ImportValues.Normalize(headers[i]);
var field = target.Fields.FirstOrDefault(f => !taken.Contains(f.Key)
&& (pass == 0 ? f.Key == header : (f.Aliases ?? []).Any(a => ImportValues.Normalize(a) == header)));
if (field is not null)
{
mapping[i] = field.Key;
taken.Add(field.Key);
}
}
}
return mapping;
}
/// <summary>The rows of a file with the cells of the mapped columns.</summary>
/// <param name="file">The file.</param>
/// <param name="mapping">The field key per column, or <see langword="null"/>.</param>
/// <returns>The rows, line numbers counting the header as line 1.</returns>
public static IReadOnlyList<ImportRow> Rows(ImportFile file, IReadOnlyList<string?> mapping)
{
ArgumentNullException.ThrowIfNull(file);
ArgumentNullException.ThrowIfNull(mapping);
var rows = new List<ImportRow>(file.Count);
for (var r = 0; r < file.Count; r++)
{
var values = new Dictionary<string, string>(StringComparer.Ordinal);
var cells = file.Rows[r];
for (var c = 0; c < mapping.Count && c < cells.Count; c++)
{
if (mapping[c] is { } key && !string.IsNullOrWhiteSpace(cells[c]))
{
values.TryAdd(key, cells[c].Trim());
}
}
rows.Add(new ImportRow(r + 2, values));
}
return rows;
}
/// <summary>Checks a file without writing (steps 2 and 3 of the screen).</summary>
/// <param name="actor">Who imports.</param>
/// <param name="companyCode">The company.</param>
/// <param name="targetKey">The entity.</param>
/// <param name="file">The file.</param>
/// <param name="mapping">The field per column.</param>
/// <param name="options">The options.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The preview.</returns>
public async Task<ImportPreview> PreviewAsync(Actor actor, string companyCode, string targetKey, ImportFile file, IReadOnlyList<string?> mapping, ImportOptions options,
CancellationToken cancellationToken = default)
{
var target = Target(targetKey);
var context = new ImportContext(actor, companyCode, options ?? new ImportOptions());
var rows = await target.CheckAsync(context, Rows(file, mapping), cancellationToken).ConfigureAwait(false);
return new ImportPreview(target.Key, rows, target.CanApply);
}
/// <summary>Imports the rows without errors (step 4); rows with errors are left out and reported.</summary>
/// <param name="actor">Who imports.</param>
/// <param name="companyCode">The company.</param>
/// <param name="targetKey">The entity.</param>
/// <param name="file">The file.</param>
/// <param name="mapping">The field per column.</param>
/// <param name="options">The options.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>What was done.</returns>
/// <exception cref="ImportFileException">The entity is only checked for now (<see cref="ImportErrors.CheckOnly"/>).</exception>
public async Task<ImportReport> ImportAsync(Actor actor, string companyCode, string targetKey, ImportFile file, IReadOnlyList<string?> mapping, ImportOptions options,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
ArgumentNullException.ThrowIfNull(file);
var target = Target(targetKey);
if (!target.CanApply)
{
throw new ImportFileException(ImportErrors.CheckOnly, "Only checked for now: " + target.Key, null);
}
var context = new ImportContext(actor, companyCode, options ?? new ImportOptions());
var rows = await target.ApplyAsync(context, Rows(file, mapping), cancellationToken).ConfigureAwait(false);
var report = new ImportReport(
target.Key,
rows.Count(r => r.Outcome != ImportOutcome.Error && r.Action == ImportAction.Create),
rows.Count(r => r.Outcome != ImportOutcome.Error && r.Action == ImportAction.Update),
rows.Count(r => r.Outcome != ImportOutcome.Error && r.Action == ImportAction.Skip),
rows);
using (_logger.BeginScope(LogSections.Scope(LogSection.System)))
{
LogImported(_logger, target.Key, file.Name, companyCode, actor.UserName, report.Created, report.Updated, report.Skipped, report.Failed);
}
return report;
}
/// <summary>Writes the rows with errors and warnings as CSV (button <i>Scarica report errori</i>).</summary>
/// <param name="rows">The checked rows.</param>
/// <param name="text">The text of a remark, in the language of the user.</param>
/// <param name="labels">The headers: line, key, column, outcome, message.</param>
/// <param name="output">Where to write.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public static async Task WriteErrorReportAsync(IReadOnlyList<ImportRowResult> rows, Func<ImportRowResult, ImportMessage, (string Outcome, string Message)> text,
IReadOnlyList<string> labels, Stream output, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(rows);
ArgumentNullException.ThrowIfNull(text);
ArgumentNullException.ThrowIfNull(labels);
await using var csv = new CsvWriter(output, CsvOptions.Italian, leaveOpen: true);
await csv.WriteRowAsync(labels, cancellationToken).ConfigureAwait(false);
foreach (var row in rows)
{
foreach (var message in row.Messages)
{
var (outcome, line) = text(row, message);
await csv.WriteRowAsync([row.Line, row.Key, message.Field, outcome, line], cancellationToken).ConfigureAwait(false);
}
}
await csv.FlushAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>Exports an entity with the columns of its import, so that the file can be imported again.</summary>
/// <param name="actor">Who exports: needs the export permission of the entity and the <i>can export</i> flag.</param>
/// <param name="companyCode">The company.</param>
/// <param name="targetKey">The entity.</param>
/// <param name="format">The format.</param>
/// <param name="output">Where to write.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The number of records written.</returns>
/// <exception cref="AccessDeniedException">The user cannot export.</exception>
public async Task<int> ExportAsync(Actor actor, string companyCode, string targetKey, TransferFormat format, Stream output, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var target = Target(targetKey);
if (!(await _permissions.GetAsync(actor, cancellationToken).ConfigureAwait(false)).Flags.CanExport)
{
throw new AccessDeniedException(SecurityErrors.PermissionDenied, "The user cannot export.");
}
var rows = target.CanExport
? await target.ExportAsync(new ImportContext(actor, companyCode, new ImportOptions()), cancellationToken).ConfigureAwait(false)
: [];
await WriteAsync(target, format, rows, output, cancellationToken).ConfigureAwait(false);
using (_logger.BeginScope(LogSections.Scope(LogSection.System)))
{
LogExported(_logger, target.Key, format, companyCode, actor.UserName, rows.Count);
}
return rows.Count;
}
/// <summary>Writes the empty template of an entity: the headers only (for JSON, one object with empty values).</summary>
/// <param name="target">The entity.</param>
/// <param name="format">The format.</param>
/// <param name="output">Where to write.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public static Task WriteTemplateAsync(IImportTarget target, TransferFormat format, Stream output, CancellationToken cancellationToken = default) =>
WriteAsync(target, format, [], output, cancellationToken);
/// <summary>The name of an export or template file (<c>clienti-2026-11-12.csv</c>, <c>modello-clienti.xlsx</c>).</summary>
/// <param name="targetKey">The entity.</param>
/// <param name="format">The format.</param>
/// <param name="date">The day of an export, or <see langword="null"/> for a template.</param>
/// <returns>The file name.</returns>
public static string FileName(string targetKey, TransferFormat format, DateOnly? date)
{
var extension = format switch
{
TransferFormat.Xlsx => ".xlsx",
TransferFormat.Json => ".json",
_ => ".csv",
};
return date is { } day
? targetKey + "-" + day.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture) + extension
: "modello-" + targetKey + extension;
}
/// <summary>The media type of a format.</summary>
/// <param name="format">The format.</param>
/// <returns>The media type.</returns>
public static string MediaType(TransferFormat format) => format switch
{
TransferFormat.Xlsx => XlsxWriter.MediaType,
TransferFormat.Json => "application/json",
_ => "text/csv",
};
private static async Task WriteAsync(IImportTarget target, TransferFormat format, IReadOnlyList<IReadOnlyList<object?>> rows, Stream output, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(target);
ArgumentNullException.ThrowIfNull(output);
var headers = target.Fields.Select(f => f.Key).ToList();
switch (format)
{
case TransferFormat.Xlsx:
await using (var xlsx = await XlsxWriter.CreateAsync(output, leaveOpen: true, cancellationToken: cancellationToken).ConfigureAwait(false))
{
await xlsx.StartSheetAsync(target.Key, [.. target.Fields.Select(Column)], cancellationToken).ConfigureAwait(false);
foreach (var row in rows)
{
await xlsx.WriteRowAsync(row, cancellationToken).ConfigureAwait(false);
}
await xlsx.CompleteAsync(cancellationToken).ConfigureAwait(false);
}
break;
case TransferFormat.Json:
await WriteJsonAsync(target, headers, rows, output, cancellationToken).ConfigureAwait(false);
break;
default:
await using (var csv = new CsvWriter(output, CsvOptions.Italian, leaveOpen: true))
{
await csv.WriteRowAsync(headers, cancellationToken).ConfigureAwait(false);
foreach (var row in rows)
{
await csv.WriteRowAsync(row, cancellationToken).ConfigureAwait(false);
}
await csv.FlushAsync(cancellationToken).ConfigureAwait(false);
}
break;
}
}
private static XlsxColumn Column(ImportField field) => new(field.Key, field.Kind switch
{
ImportFieldKind.Text => 28,
ImportFieldKind.Number or ImportFieldKind.Date => 14,
_ => 16,
});
private static async Task WriteJsonAsync(IImportTarget target, List<string> headers, IReadOnlyList<IReadOnlyList<object?>> rows, Stream output,
CancellationToken cancellationToken)
{
await using var json = new Utf8JsonWriter(output, JsonOptions);
var chart = target is ChartOfAccountsImportTarget;
if (chart)
{
json.WriteStartObject();
json.WriteString("format", ImportFileReader.ChartFormat);
json.WriteNumber("version", 1);
json.WritePropertyName("accounts");
}
json.WriteStartArray();
IEnumerable<IReadOnlyList<object?>> objects = rows.Count > 0 ? rows : [new object?[headers.Count]];
foreach (var row in objects)
{
json.WriteStartObject();
for (var i = 0; i < headers.Count; i++)
{
var value = i < row.Count ? row[i] : null;
switch (value)
{
case null:
json.WriteString(headers[i], string.Empty);
break;
case decimal number:
json.WriteNumber(headers[i], number);
break;
case bool flag:
json.WriteBoolean(headers[i], flag);
break;
case DateOnly day:
json.WriteString(headers[i], day.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture));
break;
default:
json.WriteString(headers[i], Convert.ToString(value, System.Globalization.CultureInfo.InvariantCulture));
break;
}
}
json.WriteEndObject();
}
json.WriteEndArray();
if (chart)
{
foreach (var section in new[] { "statementLines", "journalTemplates", "mappings" })
{
json.WriteStartArray(section);
json.WriteEndArray();
}
json.WriteEndObject();
}
await json.FlushAsync(cancellationToken).ConfigureAwait(false);
}
[LoggerMessage(EventId = 7101, Level = LogLevel.Information,
Message = "Import {Target} from {File} in {Company} by {User}: {Created} created, {Updated} updated, {Skipped} skipped, {Failed} with errors")]
private static partial void LogImported(ILogger logger, string target, string file, string company, string user, int created, int updated, int skipped, int failed);
[LoggerMessage(EventId = 7102, Level = LogLevel.Information, Message = "Export {Target} as {Format} from {Company} by {User}: {Count} records")]
private static partial void LogExported(ILogger logger, string target, TransferFormat format, string company, string user, int count);
}
@@ -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)..]);
}
}
@@ -0,0 +1,274 @@
using System.Globalization;
using System.Text;
namespace Khaemhat.Application.ImportExport;
/// <summary>The text codes of the import remarks (<c>import.*</c>), shown by the screen with the field and the value.</summary>
public static class ImportErrors
{
/// <summary>The file is not CSV, XLSX or JSON.</summary>
public const string FileFormat = "import.file.format";
/// <summary>The file has no header or no rows.</summary>
public const string FileEmpty = "import.file.empty";
/// <summary>The file cannot be read (damaged spreadsheet, invalid JSON).</summary>
public const string FileUnreadable = "import.file.unreadable";
/// <summary>The file has more rows than an import takes.</summary>
public const string FileTooLarge = "import.file.too-large";
/// <summary>The entity is unknown or not licensed.</summary>
public const string TargetUnknown = "import.target.unknown";
/// <summary>The entity is only checked for now (opening stock until M6, chart of accounts until M7).</summary>
public const string CheckOnly = "import.target.check-only";
/// <summary>A required column of a new record is empty or not mapped.</summary>
public const string Required = "import.value.required";
/// <summary>Not a number.</summary>
public const string Number = "import.value.number";
/// <summary>Not a date.</summary>
public const string Date = "import.value.date";
/// <summary>Not yes or no.</summary>
public const string Boolean = "import.value.boolean";
/// <summary>Not one of the words accepted (<c>{0}</c> lists them).</summary>
public const string Choice = "import.value.choice";
/// <summary>A code of another archive or table that does not exist (<c>{0}</c>).</summary>
public const string CodeUnknown = "import.value.code-unknown";
/// <summary>The row has no code and the options do not generate it.</summary>
public const string CodeMissing = "import.code.missing";
/// <summary>The same code is on an earlier row of the file.</summary>
public const string CodeRepeated = "import.code.repeated";
/// <summary>The code exists and the options skip existing codes (a remark, not an error).</summary>
public const string CodeExists = "import.code.exists";
/// <summary>The code belongs to a party of another kind (a supplier among the customers).</summary>
public const string OtherKind = "import.party.other-kind";
/// <summary>The city was filled from the postal code (<c>{0}</c>).</summary>
public const string CityFilled = "import.filled.city";
/// <summary>The postal code was filled from the city (<c>{0}</c>).</summary>
public const string PostalCodeFilled = "import.filled.postal-code";
/// <summary>A price row names both a list and a customer, or neither.</summary>
public const string PriceTarget = "import.price.target";
/// <summary>Opening stock of an item that is not stocked goods.</summary>
public const string NotStocked = "import.stock.not-stocked";
/// <summary>The quantity must be more than zero.</summary>
public const string Positive = "import.value.positive";
/// <summary>The record could not be written (someone changed it meanwhile, or an unexpected rule).</summary>
public const string WriteFailed = "import.write.failed";
/// <summary>The level of an account is not 1 to 3, or not the number of parts of its code.</summary>
public const string AccountLevel = "import.coa.level";
/// <summary>The parent of an account is not the code without its last part, or is not in the file (<c>{0}</c>).</summary>
public const string AccountParent = "import.coa.parent";
/// <summary>An account has a nature other than its parent's.</summary>
public const string AccountNature = "import.coa.nature";
/// <summary>An account with sub-accounts is marked as postable.</summary>
public const string AccountPostable = "import.coa.postable";
/// <summary>A leaf account is not marked as postable (a remark).</summary>
public const string AccountLeaf = "import.coa.leaf";
/// <summary>A flag letter is not M, I, P, C or X (<c>{0}</c>).</summary>
public const string AccountFlag = "import.coa.flag";
}
/// <summary>The cells of the import as values, and the values of the export as cells.</summary>
public static class ImportValues
{
private static readonly CultureInfo Italian = CultureInfo.GetCultureInfo("it-IT");
private static readonly string[] DateFormats =
["dd/MM/yyyy", "d/M/yyyy", "dd/MM/yy", "d/M/yy", "dd-MM-yyyy", "d-M-yyyy", "dd.MM.yyyy", "yyyy-MM-dd", "yyyy/MM/dd", "yyyyMMdd", "yyyy-MM-ddTHH:mm:ss"];
private static readonly HashSet<string> Yes = new(StringComparer.Ordinal) { "si", "s", "yes", "y", "x", "1", "true", "vero", "v" };
private static readonly HashSet<string> No = new(StringComparer.Ordinal) { "no", "n", "0", "false", "falso", "f", "-" };
private static readonly DateTime Epoch = new(1899, 12, 30, 0, 0, 0, DateTimeKind.Unspecified);
/// <summary>
/// A header or a word as compared by the mapping and the choices: lower case, no accents, every run of other
/// characters as one underscore (<c>Partita IVA</c> and <c>partita-iva</c> both give <c>partita_iva</c>).
/// </summary>
/// <param name="text">The text.</param>
/// <returns>The normalized text.</returns>
public static string Normalize(string? text)
{
if (string.IsNullOrWhiteSpace(text))
{
return string.Empty;
}
var builder = new StringBuilder(text.Length);
var underscore = false;
foreach (var c in text.Trim().Normalize(NormalizationForm.FormD))
{
if (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.NonSpacingMark)
{
continue;
}
if (char.IsAsciiLetterOrDigit(c))
{
if (underscore && builder.Length > 0)
{
builder.Append('_');
}
builder.Append(char.ToLowerInvariant(c));
underscore = false;
}
else
{
underscore = true;
}
}
return builder.ToString();
}
/// <summary>
/// Reads a number written the Italian way (<c>1.234,56</c>, <c>€ 12,5</c>) or the machine way (<c>1234.56</c>):
/// with both marks the last one is the decimal one; a single point alone is the decimal mark (as spreadsheets and JSON
/// write it), several points alone group thousands; percent signs, currency signs and spaces are ignored.
/// </summary>
/// <param name="text">The cell.</param>
/// <param name="value">The number.</param>
/// <returns><see langword="true"/> when the cell is a number.</returns>
public static bool TryNumber(string? text, out decimal value)
{
value = 0;
if (string.IsNullOrWhiteSpace(text))
{
return false;
}
var clean = new StringBuilder(text.Length);
foreach (var c in text)
{
if (char.IsAsciiDigit(c) || c is ',' or '.' or '-' or '+' or 'e' or 'E')
{
clean.Append(c);
}
else if (!char.IsWhiteSpace(c) && c is not ('€' or '%' or '\'' or ' ' or ' '))
{
return false;
}
}
var s = clean.ToString();
var comma = s.LastIndexOf(',');
var point = s.LastIndexOf('.');
if (comma >= 0 && point >= 0)
{
s = comma > point ? s.Replace(".", string.Empty, StringComparison.Ordinal).Replace(',', '.') : s.Replace(",", string.Empty, StringComparison.Ordinal);
}
else if (comma >= 0)
{
s = s.Count(c => c == ',') > 1 ? s.Replace(",", string.Empty, StringComparison.Ordinal) : s.Replace(',', '.');
}
else if (point >= 0 && s.Count(c => c == '.') > 1)
{
s = s.Replace(".", string.Empty, StringComparison.Ordinal);
}
return decimal.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out value);
}
/// <summary>Reads a date: <c>dd/MM/yyyy</c> and its variants, ISO, or a spreadsheet serial number.</summary>
/// <param name="text">The cell.</param>
/// <param name="value">The date.</param>
/// <returns><see langword="true"/> when the cell is a date.</returns>
public static bool TryDate(string? text, out DateOnly value)
{
value = default;
if (string.IsNullOrWhiteSpace(text))
{
return false;
}
var s = text.Trim();
if (s.Length > 10 && s[10] is ' ' or 'T')
{
s = s[..10];
}
if (DateTime.TryParseExact(s, DateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out var day))
{
value = DateOnly.FromDateTime(day);
return true;
}
if (s.All(char.IsAsciiDigit) && s.Length <= 5 && int.TryParse(s, NumberStyles.None, CultureInfo.InvariantCulture, out var serial) && serial > 0)
{
value = DateOnly.FromDateTime(Epoch.AddDays(serial));
return true;
}
return false;
}
/// <summary>Reads yes or no: <c>sì</c>, <c>x</c>, <c>1</c>, <c>VERO</c>, <c>true</c>... and <c>no</c>, <c>0</c>, <c>FALSO</c>...</summary>
/// <param name="text">The cell.</param>
/// <param name="value">The value.</param>
/// <returns><see langword="true"/> when the cell is yes or no.</returns>
public static bool TryBoolean(string? text, out bool value)
{
var word = Normalize(text);
value = Yes.Contains(word);
return value || No.Contains(word);
}
/// <summary>Finds a word among the choices of a field, ignoring case, accents, spaces and punctuation (<c>P.A.</c> is <c>pa</c>).</summary>
/// <param name="text">The cell.</param>
/// <param name="choices">The words accepted, in the order of the values they stand for.</param>
/// <returns>The position of the word, or -1.</returns>
public static int Choice(string? text, IReadOnlyList<string> choices)
{
ArgumentNullException.ThrowIfNull(choices);
var word = Normalize(text).Replace("_", string.Empty, StringComparison.Ordinal);
for (var i = 0; i < choices.Count; i++)
{
if (Normalize(choices[i]).Replace("_", string.Empty, StringComparison.Ordinal) == word)
{
return i;
}
}
return -1;
}
/// <summary>A number for a text cell of the export, the Italian way without thousands marks (<c>1234,5</c>).</summary>
/// <param name="value">The number.</param>
/// <returns>The text, or <see langword="null"/>.</returns>
public static string? Text(decimal? value) => value?.ToString("0.############", Italian);
/// <summary>A date for a text cell of the export (<c>dd/MM/yyyy</c>).</summary>
/// <param name="value">The date.</param>
/// <returns>The text, or <see langword="null"/>.</returns>
public static string? Text(DateOnly? value) => value?.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
/// <summary>Yes or no for a text cell of the export.</summary>
/// <param name="value">The value.</param>
/// <returns><c>sì</c> or <c>no</c>.</returns>
public static string Text(bool value) => value ? "sì" : "no";
}
@@ -0,0 +1,274 @@
using Khaemhat.Application.Items;
using Khaemhat.Application.Modules;
using Khaemhat.Application.Querying;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Items;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.ImportExport;
/// <summary>
/// The items (SPEC §12.12): each row is an item read by its code, or a new one with the values proposed by the record,
/// filled with the cells of the row, checked and saved by <see cref="ItemService"/>. Empty cells keep the values of an
/// existing item; units, bar codes, prices and suppliers of the record are left as they are.
/// </summary>
/// <param name="items">The items.</param>
/// <param name="codes">The automatic codes.</param>
/// <param name="factory">Opens the company databases (codes of the tables).</param>
/// <param name="permissions">Checks the permission to import.</param>
public sealed class ItemsImportTarget(ItemService items, CodeRuleService codes, IUnitOfWorkFactory factory, PermissionService permissions)
: RecordImportTarget<ItemRecord, ItemsImportTarget.State>
{
/// <summary>The words of <c>tipo</c>, in the order of <see cref="ItemKind"/>.</summary>
public static readonly IReadOnlyList<string> KindWords = ["merce", "servizio", "spesa", "descrittivo", "cespite"];
private static readonly ImportField[] ItemFields =
[
new("codice", ImportFieldKind.Code, Aliases: ["cod", "codice_articolo", "cod_articolo", "sku", "code"]),
new("descrizione", Required: true, Aliases: ["descr", "description", "nome"]),
new("descrizione_estesa", Aliases: ["descrizione_lunga", "note_descrizione"]),
new("tipo", ImportFieldKind.Choice, Aliases: ["tipologia", "tipo_articolo"], Choices: KindWords),
new("categoria", ImportFieldKind.Code, Aliases: ["famiglia", "categoria_merceologica"]),
new("um", ImportFieldKind.Code, Aliases: ["unita_misura", "unita_di_misura", "u_m"]),
new("iva_vendite", ImportFieldKind.Code, Aliases: ["iva", "aliquota_iva", "codice_iva"]),
new("iva_acquisti", ImportFieldKind.Code),
new("ean", Aliases: ["barcode", "codice_a_barre", "ean13", "gtin"]),
new("nc8", Aliases: ["nomenclatura", "codice_doganale", "taric"]),
new("marca", Aliases: ["brand"]),
new("produttore", Aliases: ["fabbricante", "manufacturer"]),
new("peso_netto", ImportFieldKind.Number),
new("peso_lordo", ImportFieldKind.Number, Aliases: ["peso"]),
new("a_magazzino", ImportFieldKind.Boolean, Aliases: ["gestito_a_magazzino", "movimenta_magazzino"]),
new("magazzino", ImportFieldKind.Code, Aliases: ["deposito"]),
new("scorta_minima", ImportFieldKind.Number, Aliases: ["scorta"]),
new("punto_riordino", ImportFieldKind.Number),
new("lotto_riordino", ImportFieldKind.Number),
new("prezzo", ImportFieldKind.Number, Aliases: ["prezzo_vendita", "prezzo_base", "price"]),
new("costo_standard", ImportFieldKind.Number, Aliases: ["costo"]),
new("conto_ricavo", Aliases: ["conto_ricavi"]),
new("conto_costo", Aliases: ["conto_costi"]),
new("note", Aliases: ["annotazioni", "notes"]),
];
private static readonly Dictionary<string, string> Columns = new(StringComparer.Ordinal)
{
["Code"] = "codice",
["Description"] = "descrizione",
["ExtendedDescription"] = "descrizione_estesa",
["Kind"] = "tipo",
["CategoryId"] = "categoria",
["UnitOfMeasureId"] = "um",
["SalesTaxCodeId"] = "iva_vendite",
["PurchaseTaxCodeId"] = "iva_acquisti",
["Barcode"] = "ean",
["CustomsCode"] = "nc8",
["Brand"] = "marca",
["Manufacturer"] = "produttore",
["NetWeight"] = "peso_netto",
["GrossWeight"] = "peso_lordo",
["Stocked"] = "a_magazzino",
["WarehouseId"] = "magazzino",
["MinimumStock"] = "scorta_minima",
["ReorderPoint"] = "punto_riordino",
["ReorderLot"] = "lotto_riordino",
["Price"] = "prezzo",
["StandardCost"] = "costo_standard",
["RevenueAccountCode"] = "conto_ricavo",
["CostAccountCode"] = "conto_costo",
["Notes"] = "note",
};
/// <inheritdoc />
public override string Key => "articoli";
/// <inheritdoc />
public override string ModuleCode => ModuleCodes.Core;
/// <inheritdoc />
public override string Permission => ItemService.WritePermission;
/// <inheritdoc />
public override string ExportPermission => ItemService.ReadPermission;
/// <inheritdoc />
public override IReadOnlyList<ImportField> Fields => ItemFields;
/// <inheritdoc />
public override async Task<IReadOnlyList<IReadOnlyList<object?>>> ExportAsync(ImportContext context, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
var state = await LoadAsync(context, ExportPermission, cancellationToken).ConfigureAwait(false);
var rows = new List<IReadOnlyList<object?>>();
var offset = 0;
while (true)
{
var page = await items.ListAsync(context.Actor, context.CompanyCode, new ListQuery { Offset = offset, Limit = 500, Sort = [new ListSort("code")] }, cancellationToken)
.ConfigureAwait(false);
foreach (var row in page.Items)
{
if (await items.GetAsync(context.Actor, context.CompanyCode, row.Id, cancellationToken).ConfigureAwait(false) is { } record)
{
rows.Add(Cells(state, record.Item));
}
}
offset += page.Items.Count;
if (page.Items.Count == 0 || offset >= page.Total)
{
break;
}
}
return rows;
}
/// <inheritdoc />
protected override async Task<State> LoadAsync(ImportContext context, string permission, CancellationToken cancellationToken)
{
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 all = (await uow.Repository<Item, long>().ListAsync(Query.For<Item>(), cancellationToken).ConfigureAwait(false)).Items;
return new State
{
Items = new CodeIndex(all.Select(i => (i.Code, i.Id))),
Categories = await CodeIndex.LoadAsync<ItemCategory>(uow, cancellationToken).ConfigureAwait(false),
Units = await CodeIndex.LoadAsync<UnitOfMeasure>(uow, cancellationToken).ConfigureAwait(false),
TaxCodes = await CodeIndex.LoadAsync<TaxCode>(uow, cancellationToken).ConfigureAwait(false),
Warehouses = await CodeIndex.LoadAsync<Warehouse>(uow, cancellationToken).ConfigureAwait(false),
};
}
/// <inheritdoc />
protected override long? Existing(State state, string code, List<ImportMessage> messages)
{
ArgumentNullException.ThrowIfNull(state);
return state.Items.Find(code);
}
/// <inheritdoc />
protected override async Task<ItemRecord?> OpenAsync(ImportContext context, long? id, CancellationToken cancellationToken) =>
id is { } key
? await items.GetAsync(context.Actor, context.CompanyCode, key, cancellationToken).ConfigureAwait(false)
: await items.NewAsync(context.Actor, context.CompanyCode, cancellationToken).ConfigureAwait(false);
/// <inheritdoc />
protected override Task FillAsync(ImportContext context, State state, ItemRecord record, CellReader cells, bool isNew, CancellationToken cancellationToken)
{
var item = record.Item;
if (isNew && cells.Text("codice") is { } code)
{
item.Code = code;
}
if (cells.Choice(ItemFields[3]) is { } kind)
{
item.Kind = (ItemKind)kind;
if (isNew && item.Kind != ItemKind.Goods)
{
item.Stocked = false;
}
}
Set(cells, "descrizione", v => item.Description = v);
Set(cells, "descrizione_estesa", v => item.ExtendedDescription = v);
Set(cells, "ean", v => item.Barcode = v);
Set(cells, "nc8", v => item.CustomsCode = v);
Set(cells, "marca", v => item.Brand = v);
Set(cells, "produttore", v => item.Manufacturer = v);
Set(cells, "conto_ricavo", v => item.RevenueAccountCode = v);
Set(cells, "conto_costo", v => item.CostAccountCode = v);
Set(cells, "note", v => item.Notes = v);
item.CategoryId = cells.Code("categoria", state.Categories) ?? item.CategoryId;
item.UnitOfMeasureId = cells.Code("um", state.Units) ?? item.UnitOfMeasureId;
item.SalesTaxCodeId = cells.Code("iva_vendite", state.TaxCodes) ?? item.SalesTaxCodeId;
item.PurchaseTaxCodeId = cells.Code("iva_acquisti", state.TaxCodes) ?? item.PurchaseTaxCodeId;
item.WarehouseId = cells.Code("magazzino", state.Warehouses) ?? item.WarehouseId;
item.Stocked = cells.Boolean("a_magazzino") ?? item.Stocked;
item.NetWeight = cells.Number("peso_netto") ?? item.NetWeight;
item.GrossWeight = cells.Number("peso_lordo") ?? item.GrossWeight;
item.MinimumStock = cells.Number("scorta_minima") ?? item.MinimumStock;
item.ReorderPoint = cells.Number("punto_riordino") ?? item.ReorderPoint;
item.ReorderLot = cells.Number("lotto_riordino") ?? item.ReorderLot;
item.Price = cells.Number("prezzo") ?? item.Price;
item.StandardCost = cells.Number("costo_standard") ?? item.StandardCost;
return Task.CompletedTask;
}
/// <inheritdoc />
protected override async Task<IReadOnlyList<TableProblem>> ValidateAsync(ImportContext context, ItemRecord record, bool isNew, CancellationToken cancellationToken)
{
var problems = (await items.ValidateAsync(context.Actor, context.CompanyCode, record, cancellationToken).ConfigureAwait(false)).ToList();
if (isNew && record.Item.Code.Length > 0)
{
var rule = await codes.RuleAsync(context.CompanyCode, ItemService.CodeRule, cancellationToken).ConfigureAwait(false);
if (CodeRuleService.CheckManual(rule, record.Item.Code) is { } manual)
{
problems.Add(new(nameof(Item.Code), manual));
}
}
return problems;
}
/// <inheritdoc />
protected override async Task<(string Code, long Id)> SaveAsync(ImportContext context, ItemRecord record, CancellationToken cancellationToken)
{
var saved = await items.SaveAsync(context.Actor, context.CompanyCode, record, cancellationToken).ConfigureAwait(false);
return (saved.Item.Code, saved.Item.Id);
}
/// <inheritdoc />
protected override string Label(ImportRow row)
{
ArgumentNullException.ThrowIfNull(row);
return row["codice"] ?? row["descrizione"] ?? string.Empty;
}
/// <inheritdoc />
protected override void Remember(State state, string code, long id)
{
ArgumentNullException.ThrowIfNull(state);
state.Items.Add(code, id);
}
/// <inheritdoc />
protected override string ColumnOf(string serviceField) => Columns.GetValueOrDefault(serviceField ?? string.Empty, string.Empty);
private static void Set(CellReader cells, string key, Action<string> set)
{
if (cells.Text(key) is { } value)
{
set(value);
}
}
private static object?[] Cells(State state, Item item) =>
[
item.Code, item.Description, item.ExtendedDescription, KindWords[(int)item.Kind], state.Categories.CodeOf(item.CategoryId), state.Units.CodeOf(item.UnitOfMeasureId),
state.TaxCodes.CodeOf(item.SalesTaxCodeId), state.TaxCodes.CodeOf(item.PurchaseTaxCodeId), item.Barcode, item.CustomsCode, item.Brand, item.Manufacturer,
item.NetWeight, item.GrossWeight, item.Stocked, state.Warehouses.CodeOf(item.WarehouseId), item.MinimumStock, item.ReorderPoint, item.ReorderLot, item.Price,
item.StandardCost, item.RevenueAccountCode, item.CostAccountCode, item.Notes,
];
/// <summary>What a check or an import of items loads once.</summary>
public sealed class State
{
/// <summary>The items.</summary>
public required CodeIndex Items { get; init; }
/// <summary>The categories.</summary>
public required CodeIndex Categories { get; init; }
/// <summary>The units of measure.</summary>
public required CodeIndex Units { get; init; }
/// <summary>The VAT codes.</summary>
public required CodeIndex TaxCodes { get; init; }
/// <summary>The warehouses.</summary>
public required CodeIndex Warehouses { get; init; }
}
}
@@ -0,0 +1,429 @@
using System.Globalization;
using Khaemhat.Application.Parties;
using Khaemhat.Application.Querying;
using Khaemhat.Application.Tables;
using Khaemhat.Application.Modules;
using Khaemhat.Application.Security;
using Khaemhat.Core.Parties;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.ImportExport;
/// <summary>
/// The customers or the suppliers (SPEC §12.12): each row is a party read by its code, or a new one, filled with the
/// cells of the row, checked and saved by <see cref="PartyService"/>, so the import obeys the rules of the record
/// (fiscal checks, automatic codes, duplicates). Empty cells keep the values of an existing party.
/// </summary>
/// <param name="kind">Customers or suppliers.</param>
/// <param name="parties">The parties.</param>
/// <param name="codes">The automatic codes.</param>
/// <param name="autoFill">The places by postal code.</param>
/// <param name="factory">Opens the company databases (codes of the tables).</param>
/// <param name="permissions">Checks the permission to import.</param>
public sealed class PartiesImportTarget(
PartyKind kind, PartyService parties, CodeRuleService codes, AutoFillService autoFill, IUnitOfWorkFactory factory, PermissionService permissions)
: RecordImportTarget<PartyRecord, PartiesImportTarget.State>
{
/// <summary>The words of <c>tipo_soggetto</c>, in the order of <see cref="SubjectType"/>.</summary>
public static readonly IReadOnlyList<string> SubjectWords = ["impresa", "privato", "pa", "ue", "extra-ue", "forfettario"];
private static readonly ImportField[] Common =
[
new("codice", ImportFieldKind.Code, Aliases: ["cod", "codice_cliente", "codice_fornitore", "code"]),
new("ragione_sociale", Aliases: ["denominazione", "nome_ditta", "ragione", "rag_sociale", "name"]),
new("nome", Aliases: ["first_name"]),
new("cognome", Aliases: ["last_name"]),
new("tipo_soggetto", ImportFieldKind.Choice, Aliases: ["tipo", "soggetto"], Choices: SubjectWords),
new("partita_iva", Aliases: ["p_iva", "piva", "partitaiva", "vat", "vat_number"]),
new("codice_fiscale", Aliases: ["cf", "c_f", "cod_fiscale", "codicefiscale"]),
new("rea", Aliases: ["numero_rea"]),
new("indirizzo", Aliases: ["via", "address"]),
new("civico", Aliases: ["numero_civico", "n_civico"]),
new("cap", Aliases: ["c_a_p", "codice_postale", "postal_code"]),
new("comune", Aliases: ["citta", "localita", "city"]),
new("provincia", Aliases: ["prov", "pr", "sigla_provincia"]),
new("nazione", Aliases: ["paese", "stato", "country", "codice_nazione"]),
new("telefono", Aliases: ["tel", "phone"]),
new("email", Aliases: ["e_mail", "mail"]),
new("pec", Aliases: ["email_pec", "posta_certificata"]),
new("sito", Aliases: ["sito_web", "web", "website"]),
new("codice_destinatario", Aliases: ["codice_sdi", "sdi", "codice_univoco"]),
new("categoria", ImportFieldKind.Code),
];
private static readonly ImportField[] CustomerFields =
[
.. Common,
new("agente", ImportFieldKind.Code, Aliases: ["venditore"]),
new("pagamento", ImportFieldKind.Code, Aliases: ["condizioni_pagamento", "cod_pagamento"]),
new("listino", ImportFieldKind.Code),
new("sconto1", ImportFieldKind.Number, Aliases: ["sconto", "sconto_1"]),
new("sconto2", ImportFieldKind.Number, Aliases: ["sconto_2"]),
new("fido", ImportFieldKind.Number, Aliases: ["limite_fido", "fido_massimo"]),
new("iban", Aliases: ["codice_iban"]),
new("note", Aliases: ["annotazioni", "notes"]),
];
private static readonly ImportField[] SupplierFields =
[
.. Common,
new("pagamento", ImportFieldKind.Code, Aliases: ["condizioni_pagamento", "cod_pagamento"]),
new("iban", Aliases: ["codice_iban"]),
new("note", Aliases: ["annotazioni", "notes"]),
];
private static readonly Dictionary<string, string> Columns = new(StringComparer.Ordinal)
{
["Code"] = "codice",
["Name"] = "ragione_sociale",
["FirstName"] = "nome",
["LastName"] = "cognome",
["SubjectType"] = "tipo_soggetto",
["VatNumber"] = "partita_iva",
["TaxCode"] = "codice_fiscale",
["Rea"] = "rea",
["Address"] = "indirizzo",
["StreetNumber"] = "civico",
["PostalCode"] = "cap",
["City"] = "comune",
["Province"] = "provincia",
["CountryCode"] = "nazione",
["Phone"] = "telefono",
["Email"] = "email",
["Pec"] = "pec",
["Website"] = "sito",
["CategoryId"] = "categoria",
["SalespersonId"] = "agente",
["Notes"] = "note",
["Fiscal.RecipientCode"] = "codice_destinatario",
["Sales.PaymentTermId"] = "pagamento",
["Purchase.PaymentTermId"] = "pagamento",
["Sales.PriceListId"] = "listino",
["Sales.Discount1"] = "sconto1",
["Sales.Discount2"] = "sconto2",
["Sales.CreditLimit"] = "fido",
};
/// <inheritdoc />
public override string Key => kind == PartyKind.Supplier ? "fornitori" : "clienti";
/// <inheritdoc />
public override string ModuleCode => ModuleCodes.Core;
/// <inheritdoc />
public override string Permission => PartyService.WritePermission;
/// <inheritdoc />
public override string ExportPermission => "parties.party.export";
/// <inheritdoc />
public override IReadOnlyList<ImportField> Fields => kind == PartyKind.Supplier ? SupplierFields : CustomerFields;
private bool IsCustomer => kind != PartyKind.Supplier;
/// <inheritdoc />
public override async Task<IReadOnlyList<IReadOnlyList<object?>>> ExportAsync(ImportContext context, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
var state = await LoadAsync(context, ExportPermission, cancellationToken).ConfigureAwait(false);
var archive = IsCustomer ? PartyArchive.Customers : PartyArchive.Suppliers;
var rows = new List<IReadOnlyList<object?>>();
var offset = 0;
while (true)
{
var page = await parties.ListAsync(context.Actor, context.CompanyCode, archive, new ListQuery { Offset = offset, Limit = 500, Sort = [new ListSort("code")] },
cancellationToken).ConfigureAwait(false);
foreach (var row in page.Items.Where(r => r.Kind == kind))
{
if (await parties.GetAsync(context.Actor, context.CompanyCode, row.Id, cancellationToken).ConfigureAwait(false) is { } record)
{
rows.Add(Cells(state, record));
}
}
offset += page.Items.Count;
if (page.Items.Count == 0 || offset >= page.Total)
{
break;
}
}
return rows;
}
/// <inheritdoc />
protected override async Task<State> LoadAsync(ImportContext context, string permission, CancellationToken cancellationToken)
{
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 all = (await uow.Repository<Party, long>().ListAsync(Query.For<Party>(), cancellationToken).ConfigureAwait(false)).Items;
return new State
{
Kinds = all.GroupBy(p => p.Code, StringComparer.OrdinalIgnoreCase).ToDictionary(g => g.Key, g => (g.First().Id, g.First().Kind), StringComparer.OrdinalIgnoreCase),
Categories = await CodeIndex.LoadAsync<PartyCategory>(uow, cancellationToken).ConfigureAwait(false),
Salespeople = await CodeIndex.LoadAsync<Salesperson>(uow, cancellationToken).ConfigureAwait(false),
PaymentTerms = await CodeIndex.LoadAsync<PaymentTerm>(uow, cancellationToken).ConfigureAwait(false),
PriceLists = await CodeIndex.LoadAsync<PriceList>(uow, cancellationToken).ConfigureAwait(false),
};
}
/// <inheritdoc />
protected override long? Existing(State state, string code, List<ImportMessage> messages)
{
if (!state.Kinds.TryGetValue(code, out var found))
{
return null;
}
if (found.Kind != kind)
{
messages.Add(new("codice", ImportErrors.OtherKind, Value: code));
return null;
}
return found.Id;
}
/// <inheritdoc />
protected override Task<PartyRecord?> OpenAsync(ImportContext context, long? id, CancellationToken cancellationToken) =>
id is { } key
? parties.GetAsync(context.Actor, context.CompanyCode, key, cancellationToken)
: NewAsync(context, cancellationToken);
/// <inheritdoc />
protected override async Task FillAsync(ImportContext context, State state, PartyRecord record, CellReader cells, bool isNew, CancellationToken cancellationToken)
{
var party = record.Party;
if (isNew && cells.Text("codice") is { } code)
{
party.Code = code;
}
if (cells.Choice(Fields.First(f => f.Key == "tipo_soggetto")) is { } subject)
{
party.SubjectType = (SubjectType)subject;
}
else if (isNew && !cells.Has("tipo_soggetto") && !cells.Has("ragione_sociale") && cells.Has("cognome"))
{
party.SubjectType = SubjectType.Person;
}
Set(cells, "ragione_sociale", v => party.Name = v);
Set(cells, "nome", v => party.FirstName = v);
Set(cells, "cognome", v => party.LastName = v);
if (party.SubjectType == SubjectType.Person && !cells.Has("ragione_sociale") && (cells.Has("nome") || cells.Has("cognome")))
{
party.Name = string.Empty;
}
Set(cells, "partita_iva", v => party.VatNumber = v);
Set(cells, "codice_fiscale", v => party.TaxCode = v.ToUpperInvariant());
Set(cells, "rea", v => party.Rea = v);
Set(cells, "indirizzo", v => party.Address = v);
Set(cells, "civico", v => party.StreetNumber = v);
Set(cells, "cap", v => party.PostalCode = v);
Set(cells, "comune", v => party.City = v);
Set(cells, "provincia", v => party.Province = v.ToUpperInvariant());
Set(cells, "nazione", v => party.CountryCode = v.ToUpperInvariant());
Set(cells, "telefono", v => party.Phone = v);
Set(cells, "email", v => party.Email = v);
Set(cells, "pec", v => party.Pec = v);
Set(cells, "sito", v => party.Website = v);
Set(cells, "codice_destinatario", v => record.Fiscal.RecipientCode = v.ToUpperInvariant());
Set(cells, "note", v => party.Notes = v);
if (cells.Code("categoria", state.Categories) is { } category)
{
party.CategoryId = category;
}
if (cells.Code("pagamento", state.PaymentTerms) is { } payment)
{
if (IsCustomer)
{
record.Sales.PaymentTermId = payment;
}
else
{
record.Purchase.PaymentTermId = payment;
}
}
if (IsCustomer)
{
if (cells.Code("agente", state.Salespeople) is { } salesperson)
{
party.SalespersonId = salesperson;
}
if (cells.Code("listino", state.PriceLists) is { } list)
{
record.Sales.PriceListId = list;
}
record.Sales.Discount1 = cells.Number("sconto1") ?? record.Sales.Discount1;
record.Sales.Discount2 = cells.Number("sconto2") ?? record.Sales.Discount2;
record.Sales.CreditLimit = cells.Number("fido") ?? record.Sales.CreditLimit;
}
if (cells.Text("iban") is { } text)
{
var iban = string.Concat(text.Where(c => !char.IsWhiteSpace(c))).ToUpperInvariant();
if (!record.BankAccounts.Any(b => string.Equals(b.Iban, iban, StringComparison.OrdinalIgnoreCase)))
{
record.BankAccounts.Add(new PartyBankAccount { Iban = iban, IsDefault = !record.BankAccounts.Any(b => b.IsDefault) });
}
}
if (context.Options.FillFromPostalCode && (cells.Has("cap") || cells.Has("comune")))
{
await FillPlaceAsync(context, state, party, cells, cancellationToken).ConfigureAwait(false);
}
}
/// <inheritdoc />
protected override async Task<IReadOnlyList<TableProblem>> ValidateAsync(ImportContext context, PartyRecord record, bool isNew, CancellationToken cancellationToken)
{
var problems = (await parties.ValidateAsync(context.Actor, context.CompanyCode, record, cancellationToken).ConfigureAwait(false)).ToList();
if (isNew && record.Party.Code.Length > 0 && CodeRuleService.CheckManual(await RuleAsync(context, cancellationToken).ConfigureAwait(false), record.Party.Code) is { } manual)
{
problems.Add(new(nameof(Party.Code), manual));
}
return problems;
}
/// <inheritdoc />
protected override async Task<(string Code, long Id)> SaveAsync(ImportContext context, PartyRecord record, CancellationToken cancellationToken)
{
var saved = await parties.SaveAsync(context.Actor, context.CompanyCode, record, context.Options.VerifyVat, cancellationToken).ConfigureAwait(false);
return (saved.Party.Code, saved.Party.Id);
}
/// <inheritdoc />
protected override string Label(ImportRow row)
{
ArgumentNullException.ThrowIfNull(row);
return row["codice"] ?? row["ragione_sociale"] ?? string.Join(' ', new[] { row["cognome"], row["nome"] }.Where(n => n is not null));
}
/// <inheritdoc />
protected override void Remember(State state, string code, long id)
{
ArgumentNullException.ThrowIfNull(state);
state.Kinds[code] = (id, kind);
}
/// <inheritdoc />
protected override string ColumnOf(string serviceField)
{
ArgumentNullException.ThrowIfNull(serviceField);
if (Columns.TryGetValue(serviceField, out var column))
{
return column;
}
return serviceField.StartsWith("BankAccounts.", StringComparison.Ordinal) ? "iban" : string.Empty;
}
private static void Set(CellReader cells, string key, Action<string> set)
{
if (cells.Text(key) is { } value)
{
set(value);
}
}
private object?[] Cells(State state, PartyRecord record)
{
var p = record.Party;
var common = new object?[]
{
p.Code, p.SubjectType == SubjectType.Person ? null : p.Name, p.FirstName, p.LastName, SubjectWords[(int)p.SubjectType], p.VatNumber, p.TaxCode, p.Rea,
p.Address, p.StreetNumber, p.PostalCode, p.City, p.Province, p.CountryCode, p.Phone, p.Email, p.Pec, p.Website, record.Fiscal.RecipientCode,
state.Categories.CodeOf(p.CategoryId),
};
var iban = record.BankAccounts.OrderByDescending(b => b.IsDefault).FirstOrDefault()?.Iban;
return IsCustomer
?
[
.. common, state.Salespeople.CodeOf(p.SalespersonId), state.PaymentTerms.CodeOf(record.Sales.PaymentTermId), state.PriceLists.CodeOf(record.Sales.PriceListId),
record.Sales.Discount1, record.Sales.Discount2, record.Sales.CreditLimit, iban, p.Notes,
]
: [.. common, state.PaymentTerms.CodeOf(record.Purchase.PaymentTermId), iban, p.Notes];
}
private async Task<PartyRecord?> NewAsync(ImportContext context, CancellationToken cancellationToken) =>
await parties.NewAsync(context.Actor, context.CompanyCode, kind, cancellationToken).ConfigureAwait(false);
private async Task<CodeRule> RuleAsync(ImportContext context, CancellationToken cancellationToken) =>
await codes.RuleAsync(context.CompanyCode, PartyService.CodeRuleOf(kind), cancellationToken).ConfigureAwait(false);
// City from the postal code and postal code from the city, only for Italian addresses and only when one place fits.
private async Task FillPlaceAsync(ImportContext context, State state, Party party, CellReader cells, CancellationToken cancellationToken)
{
if (!string.Equals(party.CountryCode, "IT", StringComparison.OrdinalIgnoreCase))
{
return;
}
if (party.PostalCode is { } cap && string.IsNullOrWhiteSpace(party.City))
{
if (!state.ByPostalCode.TryGetValue(cap, out var places))
{
places = await autoFill.PlacesByPostalCodeAsync(context.Actor, context.CompanyCode, cap, cancellationToken).ConfigureAwait(false);
state.ByPostalCode[cap] = places;
}
if (places.Count == 1)
{
party.City = places[0].Name;
party.Province ??= places[0].ProvinceCode;
cells.Messages.Add(new("comune", ImportErrors.CityFilled, IsWarning: true, Value: places[0].Name));
}
}
else if (party.City is { } city && string.IsNullOrWhiteSpace(party.PostalCode))
{
var key = city.ToUpper(CultureInfo.InvariantCulture);
if (!state.ByName.TryGetValue(key, out var places))
{
places = await autoFill.PlacesByNameAsync(context.Actor, context.CompanyCode, city, cancellationToken).ConfigureAwait(false);
state.ByName[key] = places;
}
var exact = places.Where(p => string.Equals(p.Name, city, StringComparison.OrdinalIgnoreCase)).ToList();
if (exact.Count == 1 && exact[0].PostalCode is { } postalCode)
{
party.PostalCode = postalCode;
party.Province ??= exact[0].ProvinceCode;
cells.Messages.Add(new("cap", ImportErrors.PostalCodeFilled, IsWarning: true, Value: postalCode));
}
}
}
/// <summary>What a check or an import of parties loads once.</summary>
public sealed class State
{
/// <summary>The id and kind of every party by code.</summary>
public required Dictionary<string, (long Id, PartyKind Kind)> Kinds { get; init; }
/// <summary>The categories.</summary>
public required CodeIndex Categories { get; init; }
/// <summary>The salespeople.</summary>
public required CodeIndex Salespeople { get; init; }
/// <summary>The payment terms.</summary>
public required CodeIndex PaymentTerms { get; init; }
/// <summary>The price lists.</summary>
public required CodeIndex PriceLists { get; init; }
/// <summary>Places found by postal code.</summary>
public Dictionary<string, IReadOnlyList<PlaceSuggestion>> ByPostalCode { get; } = new(StringComparer.Ordinal);
/// <summary>Places found by name.</summary>
public Dictionary<string, IReadOnlyList<PlaceSuggestion>> ByName { get; } = new(StringComparer.Ordinal);
}
}
@@ -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);
}
@@ -362,7 +362,19 @@ public sealed class PartyService
/// <returns>The saved record, read back.</returns>
/// <exception cref="ValidationFailedException">A rule failed; errors are <c>Field:code</c>.</exception>
/// <exception cref="Core.Common.ConcurrencyException">Someone else changed the party meanwhile.</exception>
public async Task<PartyRecord> SaveAsync(Actor actor, string companyCode, PartyRecord record, CancellationToken cancellationToken = default)
public Task<PartyRecord> SaveAsync(Actor actor, string companyCode, PartyRecord record, CancellationToken cancellationToken = default) =>
SaveAsync(actor, companyCode, record, null, cancellationToken);
/// <summary>Saves a party with its details, choosing whether to check an EU VAT number on VIES (the import asks it in its options).</summary>
/// <param name="actor">Who saves.</param>
/// <param name="companyCode">The company.</param>
/// <param name="record">The record.</param>
/// <param name="verifyVat">Check on VIES; <see langword="null"/>: as the automatic filling option of the company says.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The saved record, read back.</returns>
/// <exception cref="ValidationFailedException">A rule failed; errors are <c>Field:code</c>.</exception>
/// <exception cref="Core.Common.ConcurrencyException">Someone else changed the party meanwhile.</exception>
public async Task<PartyRecord> SaveAsync(Actor actor, string companyCode, PartyRecord record, bool? verifyVat, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(record);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false);
@@ -399,7 +411,7 @@ public sealed class PartyService
if (party.SubjectType == SubjectType.EuCompany && party.VatNumber is { Length: > 0 }
&& (before is null || before.Party.VatNumber != party.VatNumber || before.Party.CountryCode != party.CountryCode || before.Party.VatCheck == VatCheckStatus.None)
&& await _autoFill.IsOnAsync(company, AutoFillService.Vies, cancellationToken).ConfigureAwait(false))
&& (verifyVat ?? await _autoFill.IsOnAsync(company, AutoFillService.Vies, cancellationToken).ConfigureAwait(false)))
{
await CheckVatCoreAsync(company, id, actor.UserName, cancellationToken).ConfigureAwait(false);
}