using System.Globalization;
using System.Text;
namespace Khaemhat.Core.Treasury;
///
/// Reads the CSV exports of home banking with a , and guesses the layout from the header
/// row of the common Italian and English exports.
///
///
///
/// - The file is UTF-8 (with or without BOM); when it is not valid UTF-8 it is read as Windows-1252.
/// - Fields may be quoted, with doubled quotes inside; quoted fields may span lines.
/// - Empty rows and the are skipped; so are rows without a date and
/// without an amount (titles, totals without figures). A row with a date and no amount, or an amount and no date, is an
/// error that names the row.
/// - Numbers may carry a leading or trailing sign and the currency (€, EUR); the debit column is read as
/// money out whatever its sign.
///
///
public static class CsvStatementReader
{
// The common date formats tried when the layout format does not fit (never month-first, which is ambiguous).
private static readonly string[] FallbackDateFormats = ["dd/MM/yyyy", "d/M/yyyy", "dd/MM/yy", "yyyy-MM-dd", "dd-MM-yyyy", "dd.MM.yyyy"];
// Windows-1252 differs from Latin-1 in 0x80-0x9F; the undefined positions stay as they are.
private static readonly char[] Windows1252High =
[
'€', '\u0081', '‚', 'ƒ', '„', '…', '†', '‡', 'ˆ', '‰', 'Š', '‹', 'Œ', '\u008D', 'Ž', '\u008F',
'\u0090', '‘', '’', '“', '”', '•', '–', '—', '˜', '™', 'š', '›', 'œ', '\u009D', 'ž', 'Ÿ',
];
private static readonly string[] BookingDateNames = ["data contabile", "booking date", "data operazione", "data registrazione", "data", "date"];
private static readonly string[] ValueDateNames = ["data valuta", "valuta", "value date"];
private static readonly string[] DescriptionNames = ["descrizione operazione", "descrizione", "description", "causale", "dettagli", "details"];
private static readonly string[] AmountNames = ["importo", "amount"];
private static readonly string[] CreditNames = ["entrate", "avere", "accrediti", "accredito", "importo avere", "credit", "credits"];
private static readonly string[] DebitNames = ["uscite", "dare", "addebiti", "addebito", "importo dare", "debit", "debits"];
private static readonly string[] ReferenceNames = ["riferimento", "cro", "reference", "riferimento banca", "cro/trn"];
private static readonly string[] EnglishNames = ["booking date", "value date", "description", "details", "amount", "credit", "credits", "debit", "debits", "reference", "date"];
/// Reads a statement.
/// The file.
/// Its columns.
/// The statement: no account, currency or balances, the period from the booking dates.
/// A row cannot be read; the message names it.
public static StatementFile Read(Stream content, CsvStatementLayout layout)
{
ArgumentNullException.ThrowIfNull(content);
ArgumentNullException.ThrowIfNull(layout);
if (layout.AmountColumn is null && layout.CreditColumn is null && layout.DebitColumn is null)
{
throw new BankFileException("The CSV layout has no amount column.");
}
var movements = new List();
var index = 0;
foreach (var (row, fields) in Records(Decode(content), layout.Separator))
{
if (index++ < layout.HeaderRows || fields.All(string.IsNullOrWhiteSpace))
{
continue;
}
var date = ParseDate(Field(fields, layout.DateColumn), layout.DateFormat);
var amount = Amount(fields, layout, row);
if (date is null)
{
if (amount is null)
{
continue;
}
throw new BankFileException(string.Create(CultureInfo.InvariantCulture, $"Row {row}: the date '{Field(fields, layout.DateColumn)}' is not in the format {layout.DateFormat}."));
}
if (amount is null)
{
throw new BankFileException(string.Create(CultureInfo.InvariantCulture, $"Row {row}: there is no amount."));
}
var valueDate = layout.ValueDateColumn is { } valueColumn ? ParseDate(Field(fields, valueColumn), layout.DateFormat) : null;
var reference = layout.ReferenceColumn is { } referenceColumn ? OneLine(Field(fields, referenceColumn)) : string.Empty;
movements.Add(new StatementMovement(
date.Value,
valueDate,
amount.Value,
OneLine(Field(fields, layout.DescriptionColumn)),
reference.Length == 0 ? null : reference));
}
return new StatementFile(
StatementFormat.Csv,
null,
null,
movements.Count == 0 ? null : movements.Min(m => m.BookingDate),
movements.Count == 0 ? null : movements.Max(m => m.BookingDate),
null,
null,
movements);
}
///
/// Guesses the layout from the header row: the separator (;, tab or ,) and the columns from their
/// Italian or English names, without case and accents. Italian headers mean decimal comma, English ones decimal point;
/// the date format is dd/MM/yyyy (the reader also tries the other common day-first formats).
///
/// The first row of the file.
/// The layout with one header row, or when a date, a description or an amount column is missing.
public static CsvStatementLayout? Detect(string headerLine)
{
if (string.IsNullOrWhiteSpace(headerLine))
{
return null;
}
var line = headerLine.TrimStart('').TrimEnd('\r', '\n');
var separator = GuessSeparator(line);
var names = Records(line, separator).FirstOrDefault().Fields?.Select(NormalizeName).ToList() ?? [];
var date = Find(names, BookingDateNames);
var description = Find(names, DescriptionNames);
var amount = Find(names, AmountNames);
var credit = Find(names, CreditNames);
var debit = Find(names, DebitNames);
if (date is null || description is null || (amount is null && credit is null && debit is null))
{
return null;
}
var valueDate = Find(names, ValueDateNames, except: date);
var reference = Find(names, ReferenceNames);
var english = EnglishNames.Contains(names[date.Value], StringComparer.Ordinal);
return new CsvStatementLayout(
separator,
HeaderRows: 1,
date.Value,
valueDate,
description.Value,
amount,
amount is null ? credit : null,
amount is null ? debit : null,
reference,
"dd/MM/yyyy",
DecimalComma: !english);
}
/// Reads a number as the bank writes it.
/// The text, such as -1.234,56, 1.234,56-, +12,00 €.
/// Whether the decimal separator is the comma.
/// The number, or for an empty field.
/// The text is not a number.
public static decimal? ParseAmount(string? text, bool decimalComma)
{
var value = (text ?? string.Empty)
.Replace("EUR", string.Empty, StringComparison.OrdinalIgnoreCase)
.Replace("€", string.Empty, StringComparison.Ordinal)
.Replace(" ", string.Empty, StringComparison.Ordinal)
.Replace(" ", string.Empty, StringComparison.Ordinal)
.Replace("'", string.Empty, StringComparison.Ordinal);
if (value.Length == 0)
{
return null;
}
var negative = false;
if (value.StartsWith('(') && value.EndsWith(')'))
{
negative = true;
value = value[1..^1];
}
if (value.Length > 0 && value[0] is '-' or '+')
{
negative ^= value[0] == '-';
value = value[1..];
}
else if (value.Length > 0 && value[^1] is '-' or '+')
{
negative ^= value[^1] == '-';
value = value[..^1];
}
value = decimalComma
? value.Replace(".", string.Empty, StringComparison.Ordinal).Replace(',', '.')
: value.Replace(",", string.Empty, StringComparison.Ordinal);
if (value.Length == 0 || !value.All(c => char.IsAsciiDigit(c) || c == '.')
|| !decimal.TryParse(value, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var number))
{
throw new FormatException($"'{text}' is not an amount.");
}
return negative ? -number : number;
}
private static decimal? Amount(string[] fields, CsvStatementLayout layout, int row)
{
try
{
if (layout.AmountColumn is { } amountColumn)
{
return ParseAmount(Field(fields, amountColumn), layout.DecimalComma);
}
var credit = layout.CreditColumn is { } creditColumn ? ParseAmount(Field(fields, creditColumn), layout.DecimalComma) : null;
var debit = layout.DebitColumn is { } debitColumn ? ParseAmount(Field(fields, debitColumn), layout.DecimalComma) : null;
return credit is null && debit is null ? null : Math.Abs(credit ?? 0m) - Math.Abs(debit ?? 0m);
}
catch (FormatException ex)
{
throw new BankFileException(string.Create(CultureInfo.InvariantCulture, $"Row {row}: {ex.Message}"), ex);
}
}
private static DateOnly? ParseDate(string text, string format)
{
var value = text.Trim();
if (value.Length == 0)
{
return null;
}
string[] candidates = value.Contains(' ', StringComparison.Ordinal) ? [value, value[..value.IndexOf(' ', StringComparison.Ordinal)]] : [value];
foreach (var candidate in candidates)
{
if (DateOnly.TryParseExact(candidate, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out var date)
|| DateOnly.TryParseExact(candidate, FallbackDateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
return date;
}
}
return null;
}
private static string Field(string[] fields, int column) => column >= 0 && column < fields.Length ? fields[column] : string.Empty;
private static string Decode(Stream content)
{
using var buffer = new MemoryStream();
content.CopyTo(buffer);
var bytes = buffer.ToArray();
var start = bytes.Length >= 3 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF ? 3 : 0;
try
{
return new UTF8Encoding(false, throwOnInvalidBytes: true).GetString(bytes, start, bytes.Length - start);
}
catch (DecoderFallbackException)
{
var text = Encoding.Latin1.GetString(bytes).ToCharArray();
for (var i = 0; i < text.Length; i++)
{
if (text[i] is >= '\u0080' and <= '\u009F')
{
text[i] = Windows1252High[text[i] - 0x80];
}
}
return new string(text);
}
}
// The records of the text with the row number where each starts (from 1); quoted fields may contain separators,
// doubled quotes and line breaks.
private static IEnumerable<(int Row, string[] Fields)> Records(string text, char separator)
{
var fields = new List();
var field = new StringBuilder();
var quoted = false;
var line = 1;
var start = 1;
for (var i = 0; i < text.Length; i++)
{
var c = text[i];
if (quoted)
{
if (c == '"')
{
if (i + 1 < text.Length && text[i + 1] == '"')
{
field.Append('"');
i++;
}
else
{
quoted = false;
}
}
else
{
if (c == '\n')
{
line++;
}
field.Append(c);
}
continue;
}
if (c == '"' && field.ToString().Trim().Length == 0)
{
field.Clear();
quoted = true;
}
else if (c == separator)
{
fields.Add(field.ToString());
field.Clear();
}
else if (c is '\r' or '\n')
{
if (c == '\r' && i + 1 < text.Length && text[i + 1] == '\n')
{
i++;
}
fields.Add(field.ToString());
field.Clear();
yield return (start, fields.ToArray());
fields.Clear();
line++;
start = line;
}
else
{
field.Append(c);
}
}
if (field.Length > 0 || fields.Count > 0)
{
fields.Add(field.ToString());
yield return (start, fields.ToArray());
}
}
private static char GuessSeparator(string line)
{
int semicolons = 0, tabs = 0, commas = 0;
var quoted = false;
foreach (var c in line)
{
if (c == '"')
{
quoted = !quoted;
}
else if (!quoted)
{
semicolons += c == ';' ? 1 : 0;
tabs += c == '\t' ? 1 : 0;
commas += c == ',' ? 1 : 0;
}
}
return tabs > 0 && tabs >= semicolons && tabs >= commas ? '\t' : semicolons > 0 && semicolons >= commas ? ';' : ',';
}
private static int? Find(List names, string[] candidates, int? except = null)
{
foreach (var candidate in candidates)
{
var index = names.FindIndex(n => string.Equals(n, candidate, StringComparison.Ordinal));
if (index >= 0 && index != except)
{
return index;
}
}
return null;
}
// Lower case, no accents, no currency or parenthesised notes, single spaces: "Importo (EUR)" is "importo".
private static string NormalizeName(string name)
{
var builder = new StringBuilder(name.Length);
var depth = 0;
foreach (var c in name.Normalize(NormalizationForm.FormD))
{
if (c == '(')
{
depth++;
}
else if (c == ')')
{
depth = Math.Max(0, depth - 1);
}
else if (depth == 0 && CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark)
{
builder.Append(char.IsLetterOrDigit(c) || c == '/' ? char.ToLowerInvariant(c) : ' ');
}
}
var words = builder.ToString().Split(' ', StringSplitOptions.RemoveEmptyEntries).Where(w => w is not ("eur" or "euro")).ToArray();
return string.Join(" ", words);
}
private static string OneLine(string text) => string.Join(" ", text.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries));
}