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>
256 lines
10 KiB
C#
256 lines
10 KiB
C#
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'];
|
|
}
|