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; /// /// 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. /// public sealed partial class ImportService { private static readonly JsonWriterOptions JsonOptions = new() { Indented = true }; private readonly IReadOnlyList _targets; private readonly ILicenseGate _license; private readonly PermissionService _permissions; private readonly ILogger _logger; /// Creates the service. /// The entities. /// The licence. /// The permissions and the user flags. /// The log. public ImportService(IEnumerable targets, ILicenseGate license, PermissionService permissions, ILogger logger) { ArgumentNullException.ThrowIfNull(targets); ArgumentNullException.ThrowIfNull(license); ArgumentNullException.ThrowIfNull(permissions); ArgumentNullException.ThrowIfNull(logger); _targets = [.. targets]; _license = license; _permissions = permissions; _logger = logger; } /// The entities whose module is licensed, in the order of the screen. public IReadOnlyList Targets => [.. _targets.Where(t => _license.IsModuleActive(t.ModuleCode))]; /// A licensed entity by key. /// The key. /// The entity. /// Unknown or not licensed (). public IImportTarget Target(string key) => Targets.FirstOrDefault(t => string.Equals(t.Key, key, StringComparison.OrdinalIgnoreCase)) ?? throw new ImportFileException(ImportErrors.TargetUnknown, "Unknown import: " + key, null); /// /// The field of each column of a file, by name or alias ignoring case, accents and punctuation; a field goes to one /// column only. /// /// The entity. /// The headers. /// The field key per column, or for columns to ignore. public static IReadOnlyList SuggestMapping(IImportTarget target, IReadOnlyList headers) { ArgumentNullException.ThrowIfNull(target); ArgumentNullException.ThrowIfNull(headers); var taken = new HashSet(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; } /// The rows of a file with the cells of the mapped columns. /// The file. /// The field key per column, or . /// The rows, line numbers counting the header as line 1. public static IReadOnlyList Rows(ImportFile file, IReadOnlyList mapping) { ArgumentNullException.ThrowIfNull(file); ArgumentNullException.ThrowIfNull(mapping); var rows = new List(file.Count); for (var r = 0; r < file.Count; r++) { var values = new Dictionary(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; } /// Checks a file without writing (steps 2 and 3 of the screen). /// Who imports. /// The company. /// The entity. /// The file. /// The field per column. /// The options. /// Cancellation. /// The preview. public async Task PreviewAsync(Actor actor, string companyCode, string targetKey, ImportFile file, IReadOnlyList 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); } /// Imports the rows without errors (step 4); rows with errors are left out and reported. /// Who imports. /// The company. /// The entity. /// The file. /// The field per column. /// The options. /// Cancellation. /// What was done. /// The entity is only checked for now (). public async Task ImportAsync(Actor actor, string companyCode, string targetKey, ImportFile file, IReadOnlyList 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; } /// Writes the rows with errors and warnings as CSV (button Scarica report errori). /// The checked rows. /// The text of a remark, in the language of the user. /// The headers: line, key, column, outcome, message. /// Where to write. /// Cancellation. /// A task. public static async Task WriteErrorReportAsync(IReadOnlyList rows, Func text, IReadOnlyList 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); } /// Exports an entity with the columns of its import, so that the file can be imported again. /// Who exports: needs the export permission of the entity and the can export flag. /// The company. /// The entity. /// The format. /// Where to write. /// Cancellation. /// The number of records written. /// The user cannot export. public async Task 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; } /// Writes the empty template of an entity: the headers only (for JSON, one object with empty values). /// The entity. /// The format. /// Where to write. /// Cancellation. /// A task. public static Task WriteTemplateAsync(IImportTarget target, TransferFormat format, Stream output, CancellationToken cancellationToken = default) => WriteAsync(target, format, [], output, cancellationToken); /// The name of an export or template file (clienti-2026-11-12.csv, modello-clienti.xlsx). /// The entity. /// The format. /// The day of an export, or for a template. /// The file name. 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; } /// The media type of a format. /// The format. /// The media type. 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> 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 headers, IReadOnlyList> 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> 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); }