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,414 @@
using System.Globalization;
using System.IO.Compression;
using System.Xml;
namespace Khaemhat.Infrastructure.Files;
/// <summary>A spreadsheet that cannot be read: not an Office Open XML workbook, damaged, or too large.</summary>
public sealed class XlsxReadException : Exception
{
/// <summary>Creates the exception.</summary>
public XlsxReadException()
{
}
/// <summary>Creates the exception.</summary>
/// <param name="message">What went wrong.</param>
public XlsxReadException(string message)
: base(message)
{
}
/// <summary>Creates the exception.</summary>
/// <param name="message">What went wrong.</param>
/// <param name="innerException">The cause.</param>
public XlsxReadException(string message, Exception innerException)
: base(message, innerException)
{
}
}
/// <summary>
/// Reads the first sheet of an Office Open XML workbook (<c>.xlsx</c>, SPEC §12.12) with <see cref="ZipArchive"/> and
/// <see cref="XmlReader"/>: shared, inline and formula strings, numbers as written in the file (invariant culture),
/// booleans as <c>true</c>/<c>false</c>, and numbers with a date format as ISO dates (<c>yyyy-MM-dd</c>). Empty cells in
/// the middle of a row are kept by their column letter; empty rows are skipped. Formulas are not computed: the cached
/// value saved by the spreadsheet is read.
/// </summary>
public static class XlsxReader
{
/// <summary>The largest uncompressed part read, against archives that expand to fill the memory.</summary>
public const long MaxPartBytes = 256L * 1024 * 1024;
private const string RelationshipNamespace = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
// The built-in number formats that show a date (ECMA-376 §18.8.30).
private static readonly HashSet<int> DateFormats = [14, 15, 16, 17, 18, 19, 20, 21, 22, 27, 30, 36, 45, 46, 47, 50, 57];
private static readonly DateTime Epoch = new(1899, 12, 30, 0, 0, 0, DateTimeKind.Unspecified);
/// <summary>Reads the rows of the first sheet.</summary>
/// <param name="content">The workbook; it is copied to memory when not seekable.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The rows, each with its cells from column A.</returns>
/// <exception cref="XlsxReadException">The file is not a readable workbook.</exception>
public static async Task<IReadOnlyList<IReadOnlyList<string>>> ReadAsync(Stream content, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(content);
var source = content;
MemoryStream? copy = null;
if (!content.CanSeek)
{
copy = new MemoryStream();
await content.CopyToAsync(copy, cancellationToken).ConfigureAwait(false);
copy.Position = 0;
source = copy;
}
try
{
using var zip = new ZipArchive(source, ZipArchiveMode.Read, leaveOpen: true);
var sheetPath = FirstSheetPath(zip);
var strings = SharedStrings(zip);
var dateStyles = DateStyles(zip);
var sheet = zip.GetEntry(sheetPath) ?? throw new XlsxReadException("The first sheet is missing: " + sheetPath);
return ReadSheet(sheet, strings, dateStyles, cancellationToken);
}
catch (InvalidDataException ex)
{
throw new XlsxReadException("Not a workbook.", ex);
}
catch (XmlException ex)
{
throw new XlsxReadException("A part of the workbook is not valid XML.", ex);
}
finally
{
if (copy is not null)
{
await copy.DisposeAsync().ConfigureAwait(false);
}
}
}
/// <summary>The zero-based column of a cell reference such as <c>AB12</c>.</summary>
/// <param name="reference">The reference.</param>
/// <returns>The column, or -1 when the reference has no letters.</returns>
public static int ColumnOf(string? reference)
{
if (string.IsNullOrEmpty(reference))
{
return -1;
}
var column = 0;
var letters = 0;
foreach (var c in reference)
{
if (!char.IsAsciiLetter(c))
{
break;
}
column = (column * 26) + (char.ToUpperInvariant(c) - 'A' + 1);
letters++;
}
return letters == 0 ? -1 : column - 1;
}
private static XmlReader Open(ZipArchiveEntry entry)
{
if (entry.Length > MaxPartBytes)
{
throw new XlsxReadException("A part of the workbook is too large: " + entry.FullName);
}
return XmlReader.Create(entry.Open(), new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null, IgnoreWhitespace = false });
}
private static string FirstSheetPath(ZipArchive zip)
{
var workbook = zip.GetEntry("xl/workbook.xml") ?? throw new XlsxReadException("xl/workbook.xml is missing.");
string? relationship = null;
using (var reader = Open(workbook))
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "sheet")
{
relationship = reader.GetAttribute("id", RelationshipNamespace);
break;
}
}
}
if (relationship is null)
{
throw new XlsxReadException("The workbook has no sheet.");
}
var rels = zip.GetEntry("xl/_rels/workbook.xml.rels");
if (rels is not null)
{
using var reader = Open(rels);
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "Relationship" && reader.GetAttribute("Id") == relationship
&& reader.GetAttribute("Target") is { } target)
{
target = target.Replace('\\', '/');
return target.StartsWith('/') ? target.TrimStart('/') : "xl/" + target;
}
}
}
return "xl/worksheets/sheet1.xml";
}
private static List<string> SharedStrings(ZipArchive zip)
{
var strings = new List<string>();
var entry = zip.GetEntry("xl/sharedStrings.xml");
if (entry is null)
{
return strings;
}
using var reader = Open(entry);
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "si")
{
strings.Add(ReadText(reader));
}
}
return strings;
}
// The concatenated <t> of an <si> or <is> element, without the phonetic runs; the reader ends on its end tag.
private static string ReadText(XmlReader reader)
{
if (reader.IsEmptyElement)
{
return string.Empty;
}
var depth = reader.Depth;
var text = new System.Text.StringBuilder();
var skip = -1;
while (reader.Read() && !(reader.NodeType == XmlNodeType.EndElement && reader.Depth == depth))
{
if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "rPh" && !reader.IsEmptyElement)
{
skip = reader.Depth;
}
else if (reader.NodeType == XmlNodeType.EndElement && reader.Depth == skip)
{
skip = -1;
}
else if (skip < 0 && reader.NodeType == XmlNodeType.Element && reader.LocalName == "t" && !reader.IsEmptyElement)
{
text.Append(reader.ReadElementContentAsString());
if (reader.NodeType == XmlNodeType.EndElement && reader.Depth == depth)
{
break;
}
}
}
return text.ToString();
}
// The indexes of the cell styles (cellXfs) whose number format shows a date.
private static HashSet<int> DateStyles(ZipArchive zip)
{
var styles = new HashSet<int>();
var entry = zip.GetEntry("xl/styles.xml");
if (entry is null)
{
return styles;
}
var custom = new HashSet<int>();
using var reader = Open(entry);
var inCellXfs = false;
var index = 0;
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "numFmt"
&& int.TryParse(reader.GetAttribute("numFmtId"), NumberStyles.Integer, CultureInfo.InvariantCulture, out var id)
&& IsDateFormat(reader.GetAttribute("formatCode")))
{
custom.Add(id);
}
else if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "cellXfs")
{
inCellXfs = !reader.IsEmptyElement;
}
else if (reader.NodeType == XmlNodeType.EndElement && reader.LocalName == "cellXfs")
{
inCellXfs = false;
}
else if (inCellXfs && reader.NodeType == XmlNodeType.Element && reader.LocalName == "xf")
{
if (int.TryParse(reader.GetAttribute("numFmtId"), NumberStyles.Integer, CultureInfo.InvariantCulture, out var format)
&& (DateFormats.Contains(format) || custom.Contains(format)))
{
styles.Add(index);
}
index++;
}
}
return styles;
}
// A custom format shows a date when, outside quoted text and brackets, it has a day, month or year code.
private static bool IsDateFormat(string? code)
{
if (string.IsNullOrEmpty(code))
{
return false;
}
var quoted = false;
var bracket = false;
foreach (var c in code)
{
switch (c)
{
case '"':
quoted = !quoted;
break;
case '[' when !quoted:
bracket = true;
break;
case ']' when !quoted:
bracket = false;
break;
case 'd' or 'D' or 'y' or 'Y' or 'm' or 'M' when !quoted && !bracket:
return true;
}
}
return false;
}
private static List<IReadOnlyList<string>> ReadSheet(ZipArchiveEntry sheet, List<string> strings, HashSet<int> dateStyles, CancellationToken cancellationToken)
{
var rows = new List<IReadOnlyList<string>>();
using var reader = Open(sheet);
List<string>? row = null;
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "row")
{
cancellationToken.ThrowIfCancellationRequested();
row = [];
if (reader.IsEmptyElement)
{
row = null;
}
}
else if (reader.NodeType == XmlNodeType.EndElement && reader.LocalName == "row" && row is not null)
{
while (row.Count > 0 && row[^1].Length == 0)
{
row.RemoveAt(row.Count - 1);
}
if (row.Count > 0)
{
rows.Add(row);
}
row = null;
}
else if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "c" && row is not null)
{
var column = ColumnOf(reader.GetAttribute("r"));
var type = reader.GetAttribute("t");
var style = int.TryParse(reader.GetAttribute("s"), NumberStyles.Integer, CultureInfo.InvariantCulture, out var s) ? s : -1;
var value = reader.IsEmptyElement ? string.Empty : ReadCell(reader, type, strings, dateStyles.Contains(style));
if (column < 0)
{
column = row.Count;
}
while (row.Count < column)
{
row.Add(string.Empty);
}
if (row.Count == column)
{
row.Add(value);
}
else
{
row[column] = value;
}
}
}
return rows;
}
// The value of a <c> element; the reader ends on its end tag.
private static string ReadCell(XmlReader reader, string? type, List<string> strings, bool date)
{
var depth = reader.Depth;
string? raw = null;
string? inline = null;
while (reader.Read() && !(reader.NodeType == XmlNodeType.EndElement && reader.Depth == depth))
{
if (reader.NodeType != XmlNodeType.Element)
{
continue;
}
if (reader.LocalName == "v" && !reader.IsEmptyElement)
{
raw = reader.ReadElementContentAsString();
if (reader.NodeType == XmlNodeType.EndElement && reader.Depth == depth)
{
break;
}
}
else if (reader.LocalName == "is")
{
inline = ReadText(reader);
}
}
return type switch
{
"inlineStr" => inline ?? string.Empty,
"s" => int.TryParse(raw, NumberStyles.Integer, CultureInfo.InvariantCulture, out var index) && index >= 0 && index < strings.Count ? strings[index] : string.Empty,
"b" => raw == "1" ? "true" : "false",
"str" or "e" => raw ?? string.Empty,
_ => Number(raw, date),
};
}
private static string Number(string? raw, bool date)
{
if (string.IsNullOrEmpty(raw))
{
return string.Empty;
}
if (date && double.TryParse(raw, NumberStyles.Float, CultureInfo.InvariantCulture, out var serial) && serial is > 0 and < 2958466)
{
var day = Epoch.AddDays(Math.Floor(serial));
return day.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
}
return decimal.TryParse(raw, NumberStyles.Float, CultureInfo.InvariantCulture, out var number)
? number.ToString(CultureInfo.InvariantCulture)
: raw;
}
}