using System.Globalization;
using System.Text;
using System.Text.Json;
using Khaemhat.Infrastructure.Files;
namespace Khaemhat.Application.ImportExport;
/// A file the import cannot use; is one of the import.file.* codes.
public sealed class ImportFileException : Exception
{
/// Creates the exception.
public ImportFileException()
{
Code = ImportErrors.FileUnreadable;
}
/// Creates the exception.
/// What went wrong.
public ImportFileException(string message)
: base(message)
{
Code = ImportErrors.FileUnreadable;
}
/// Creates the exception.
/// What went wrong.
/// The cause.
public ImportFileException(string message, Exception innerException)
: base(message, innerException)
{
Code = ImportErrors.FileUnreadable;
}
/// Creates the exception with a code.
/// The text code.
/// What went wrong.
/// The cause.
public ImportFileException(string code, string message, Exception? innerException)
: base(message, innerException)
{
Code = code;
}
/// The text code.
public string Code { get; }
}
///
/// Reads the files of the guided import (SPEC ยง12.12): CSV (UTF-8 with or without byte order mark, else Windows-1252;
/// separator ;, , or tab guessed from the header), XLSX (first sheet) and JSON (an array of objects, or the
/// object of khaemhat-coa.json with its accounts). The first row holds the headers.
///
public static class ImportFileReader
{
/// The most data rows an import takes.
public const int MaxRows = 50_000;
/// The format name written in khaemhat-coa.json.
public const string ChartFormat = "khaemhat-coa";
private static readonly UTF8Encoding StrictUtf8 = new(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);
/// The format of a file from its name.
/// The name.
/// The format, or when not supported.
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,
};
/// Reads a file.
/// The name, which gives the format.
/// The content.
/// Cancellation.
/// The file with headers and rows.
/// The format is not supported, or the file is empty, damaged or too large.
public static async Task 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()),
};
}
/// Reads CSV bytes.
/// The name.
/// The content.
/// The file.
/// Empty or too large.
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 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? 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(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();
var index = new Dictionary(StringComparer.Ordinal);
var objects = new List>();
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(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> { headers };
rows.AddRange(objects.Select(o => (IReadOnlyList)[.. 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> lines,
IReadOnlyDictionary? 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>(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'];
}