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>
376 lines
18 KiB
C#
376 lines
18 KiB
C#
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);
|
|
}
|