using Khaemhat.Application.Modules;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Accounting;
using Khaemhat.Data;
namespace Khaemhat.Application.ImportExport;
/// An account of the chart read from a file.
/// The code, parts separated by points (01.02.003).
/// The description.
/// The level, 1 to 3: the number of parts of the code.
/// The code without its last part.
/// The nature.
/// The use.
/// Postings go on it (only leaves).
/// Relevant for VAT.
/// With a sub-ledger of customers or suppliers.
/// Closed by the year end.
/// Not used any more.
/// The line of the legal statements (voce CEE).
/// The line of the reclassified statements.
public sealed record ImportedAccount(
string Code, string Description, int Level, string? ParentCode, AccountNature Nature, AccountType Type, bool Postable, bool VatRelevant, bool SubLedger,
bool ClosesAutomatically, bool Disabled, string? StatementLine = null, string? Reclassification = null);
///
/// The checks of a chart of accounts from a file (SPEC ยง12.12, ADR 0031): codes of one to three parts separated by
/// points, each account under the account whose code is its own without the last part, with the same nature; only
/// leaves are postable. Pure, so that M7 writes what this checks.
///
public static class ChartOfAccountsImportValidator
{
/// The words of natura, in the order of .
public static readonly IReadOnlyList NatureWords = ["attivo", "passivo", "costo", "ricavo", "ordine"];
/// The words of tipo, in the order of .
public static readonly IReadOnlyList TypeWords = ["generico", "clienti", "fornitori", "banca", "cassa", "iva", "erario"];
/// The flag letters: postable, VAT relevant, sub-ledger, automatic closing, disabled.
public const string FlagLetters = "MIPCX";
/// The deepest level.
public const int MaxLevel = 3;
/// The columns of the chart.
public static IReadOnlyList Fields { get; } =
[
new("codice", ImportFieldKind.Code, Required: true, Aliases: ["conto", "codice_conto", "cod_conto"]),
new("descrizione", Required: true, Aliases: ["descr", "denominazione"]),
new("livello", ImportFieldKind.Number, Aliases: ["liv"]),
new("padre", ImportFieldKind.Code, Aliases: ["conto_padre", "mastro"]),
new("natura", ImportFieldKind.Choice, Aliases: ["sezione"], Choices: NatureWords),
new("tipo", ImportFieldKind.Choice, Aliases: ["tipo_conto"], Choices: TypeWords),
new("voce_cee", Aliases: ["cee", "voce_bilancio"]),
new("riclassifica", Aliases: ["riclassificazione"]),
new("flag", Aliases: ["flags", "attributi"]),
];
/// Checks the rows of a chart.
/// The rows.
/// A result per row, and the accounts without errors.
public static (IReadOnlyList Results, IReadOnlyList Accounts) Check(IReadOnlyList rows)
{
ArgumentNullException.ThrowIfNull(rows);
// First pass: every code with its nature as written, to check parents wherever they are in the file.
var natures = new Dictionary(StringComparer.OrdinalIgnoreCase);
foreach (var row in rows)
{
if (row["codice"] is { } code)
{
natures.TryAdd(code, Choice(row["natura"], NatureWords) is { } n ? (AccountNature)n : null);
}
}
var parents = natures.Keys.Select(ParentOf).Where(p => p is not null).ToHashSet(StringComparer.OrdinalIgnoreCase);
var seen = new HashSet(StringComparer.OrdinalIgnoreCase);
var results = new List(rows.Count);
var accounts = new List();
foreach (var row in rows)
{
var messages = new List();
var cells = new CellReader(row, messages);
var code = row["codice"];
messages.AddRange(Fields.Where(f => f.Required && !cells.Has(f.Key)).Select(f => new ImportMessage(f.Key, ImportErrors.Required)));
if (code is null)
{
results.Add(new(row.Line, row["descrizione"] ?? string.Empty, ImportAction.Skip, messages));
continue;
}
if (!seen.Add(code))
{
results.Add(new(row.Line, code, ImportAction.Skip, [new("codice", ImportErrors.CodeRepeated, Value: code)]));
continue;
}
var parts = code.Split('.');
var level = parts.Length;
if (level > MaxLevel || parts.Any(p => p.Length == 0 || !p.All(char.IsAsciiLetterOrDigit)))
{
messages.Add(new("codice", ImportErrors.AccountLevel, Value: code));
}
else if (cells.Number("livello") is { } written && written != level)
{
messages.Add(new("livello", ImportErrors.AccountLevel, Value: level.ToString(System.Globalization.CultureInfo.InvariantCulture)));
}
var parent = ParentOf(code);
if (row["padre"] is { } named && !string.Equals(named, parent, StringComparison.OrdinalIgnoreCase))
{
messages.Add(new("padre", ImportErrors.AccountParent, Value: parent ?? string.Empty));
}
else if (parent is not null && !natures.ContainsKey(parent))
{
messages.Add(new("padre", ImportErrors.AccountParent, Value: parent));
}
var nature = NatureOf(code, natures);
if (nature is null)
{
messages.Add(new("natura", cells.Has("natura") ? ImportErrors.Choice : ImportErrors.Required, Value: cells.Has("natura") ? string.Join(", ", NatureWords) : null));
}
else if (parent is not null && natures.ContainsKey(parent) && NatureOf(parent, natures) is { } parentNature && parentNature != nature)
{
messages.Add(new("natura", ImportErrors.AccountNature, Value: NatureWords[(int)parentNature]));
}
var type = cells.Choice(Fields[5]) is { } t ? (AccountType)t : AccountType.Generic;
var flags = (row["flag"] ?? string.Empty).ToUpperInvariant().Where(c => !char.IsWhiteSpace(c) && c is not ',' and not ';').ToList();
if (flags.FirstOrDefault(c => !FlagLetters.Contains(c, StringComparison.Ordinal)) is var bad && bad != default)
{
messages.Add(new("flag", ImportErrors.AccountFlag, Value: bad.ToString()));
}
var postable = flags.Contains('M');
var leaf = !parents.Contains(code);
if (postable && !leaf)
{
messages.Add(new("flag", ImportErrors.AccountPostable));
}
else if (!postable && leaf && level > 1)
{
messages.Add(new("flag", ImportErrors.AccountLeaf, IsWarning: true));
}
if (messages.All(m => m.IsWarning) && nature is { } valid)
{
accounts.Add(new(code, row["descrizione"] ?? string.Empty, level, parent, valid, type, postable, flags.Contains('I'), flags.Contains('P'), flags.Contains('C'),
flags.Contains('X'), row["voce_cee"], row["riclassifica"]));
}
results.Add(new(row.Line, code, messages.Any(m => !m.IsWarning) ? ImportAction.Skip : ImportAction.Create, messages));
}
return (results, accounts);
}
/// The code without its last part, or for a first level account.
/// The code.
/// The parent code.
public static string? ParentOf(string code)
{
ArgumentNullException.ThrowIfNull(code);
var point = code.LastIndexOf('.');
return point <= 0 ? null : code[..point];
}
// The nature written on the account, else the one of the nearest ancestor that has one.
private static AccountNature? NatureOf(string code, Dictionary natures)
{
for (var current = code; current is not null; current = ParentOf(current))
{
if (natures.TryGetValue(current, out var nature) && nature is not null)
{
return nature;
}
}
return null;
}
private static int? Choice(string? text, IReadOnlyList words) => text is null ? null : ImportValues.Choice(text, words) is var i and >= 0 ? i : null;
}
///
/// The chart of accounts (piano-dei-conti): CSV, XLSX or khaemhat-coa.json. The accounts the check
/// accepts are added; those that exist are updated when the options say so (M7, issue #62).
///
public sealed class ChartOfAccountsImportTarget : IImportTarget
{
/// The permission to change the chart of accounts.
public const string WritePermission = "ledger.account.write";
private readonly PermissionService _permissions;
private readonly IUnitOfWorkFactory? _factory;
/// Creates the target.
/// Checks the permission.
/// The units of work, to write the accounts.
public ChartOfAccountsImportTarget(PermissionService permissions, IUnitOfWorkFactory? factory = null)
{
_permissions = permissions;
_factory = factory;
}
///
public string Key => "piano-dei-conti";
///
public string ModuleCode => ModuleCodes.Accounting;
///
public string Permission => WritePermission;
///
public string ExportPermission => "ledger.account.read";
///
public bool CanApply => _factory is not null;
///
public bool CanExport => _factory is not null;
///
public IReadOnlyList Fields => ChartOfAccountsImportValidator.Fields;
///
public async Task> CheckAsync(ImportContext context, IReadOnlyList rows, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
await CompanyGuard.DemandAsync(_permissions, context.Actor, context.CompanyCode, Permission, cancellationToken).ConfigureAwait(false);
return ChartOfAccountsImportValidator.Check(rows).Results;
}
///
public async Task> ApplyAsync(ImportContext context, IReadOnlyList rows, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
var factory = _factory ?? throw new InvalidOperationException(ImportErrors.CheckOnly);
var company = await CompanyGuard.DemandAsync(_permissions, context.Actor, context.CompanyCode, Permission, cancellationToken).ConfigureAwait(false);
var (results, accounts) = ChartOfAccountsImportValidator.Check(rows);
var update = context.Options.Existing == ExistingCodeAction.Update;
Dictionary written;
await using (var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
written = await Ledger.LedgerService.ImportAsync(uow, accounts, update, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
return [.. results.Select(r => r.Action == ImportAction.Skip
? r
: r with { Action = written.TryGetValue(r.Key, out var created) ? (created ? ImportAction.Create : ImportAction.Update) : ImportAction.Skip })];
}
///
public async Task>> ExportAsync(ImportContext context, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
var factory = _factory ?? throw new InvalidOperationException(ImportErrors.CheckOnly);
var company = await CompanyGuard.DemandAsync(_permissions, context.Actor, context.CompanyCode, ExportPermission, cancellationToken).ConfigureAwait(false);
await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var accounts = (await uow.Repository().ListAsync(Data.Querying.Query.For(), cancellationToken).ConfigureAwait(false)).Items
.OrderBy(a => a.Code, StringComparer.Ordinal);
return [.. accounts.Select(a => (IReadOnlyList