Files
Khaemhat/src/Khaemhat.Application/ImportExport/CheckOnlyImportTargets.cs
T
Alby96andClaude Opus 5.5 9e3ba92993 feat: general ledger, automatic posting, VAT settlement, withholdings and F24 (#62 #63 #64 #65 #66 #67 #68)
M7 adds the double-entry ledger so that the documents of M5 and M6 reach the
accounts without retyping, and the Italian VAT obligations can be prepared from
the same data.

- Chart of accounts on three levels with the Italian "PMI standard" model in the
  fiscal pack, journal templates with proposed lines, VAT registers; the chart
  import now writes the accounts and exports them (#62, ADR 0036).
- Journal entries: draft, posted, final with the libro giornale number,
  reversal; recurring entries with the nightly ledger.recurring job (#63).
- Documents post their entry inside the document transaction (PostingEngine,
  LedgerPoster) with VAT lines, open items and withholdings; a change rewrites
  the same entry, a cancellation removes or reverses it (#64, ADR 0037).
- VAT registers with final print, monthly or quarterly settlement with pro rata,
  interest, minimum and advance, confirmation with the LIQ entry, period lock
  and F24 line, LIPE file and F24 data (#65).
- Operated and suffered withholdings, CU data, stamp duty by quarter with the
  5,000 euro threshold, F24 summary with its payment entry (#66).
- Party ledgers, account ledgers, trial balance and libro giornale (#67).
- Demo accounting with the settlements of the past months confirmed and checked
  by hand in a test; wiki Contabilita, IVA, Fiscalita italiana completed with
  screenshots; CHANGELOG 0.7.0, STATUS, ADR 0036-0037 (#68).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 01:41:58 +01:00

276 lines
14 KiB
C#

using Khaemhat.Application.Modules;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Accounting;
using Khaemhat.Data;
namespace Khaemhat.Application.ImportExport;
/// <summary>An account of the chart read from a file.</summary>
/// <param name="Code">The code, parts separated by points (<c>01.02.003</c>).</param>
/// <param name="Description">The description.</param>
/// <param name="Level">The level, 1 to 3: the number of parts of the code.</param>
/// <param name="ParentCode">The code without its last part.</param>
/// <param name="Nature">The nature.</param>
/// <param name="Type">The use.</param>
/// <param name="Postable">Postings go on it (only leaves).</param>
/// <param name="VatRelevant">Relevant for VAT.</param>
/// <param name="SubLedger">With a sub-ledger of customers or suppliers.</param>
/// <param name="ClosesAutomatically">Closed by the year end.</param>
/// <param name="Disabled">Not used any more.</param>
/// <param name="StatementLine">The line of the legal statements (voce CEE).</param>
/// <param name="Reclassification">The line of the reclassified statements.</param>
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);
/// <summary>
/// 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.
/// </summary>
public static class ChartOfAccountsImportValidator
{
/// <summary>The words of <c>natura</c>, in the order of <see cref="AccountNature"/>.</summary>
public static readonly IReadOnlyList<string> NatureWords = ["attivo", "passivo", "costo", "ricavo", "ordine"];
/// <summary>The words of <c>tipo</c>, in the order of <see cref="AccountType"/>.</summary>
public static readonly IReadOnlyList<string> TypeWords = ["generico", "clienti", "fornitori", "banca", "cassa", "iva", "erario"];
/// <summary>The flag letters: postable, VAT relevant, sub-ledger, automatic closing, disabled.</summary>
public const string FlagLetters = "MIPCX";
/// <summary>The deepest level.</summary>
public const int MaxLevel = 3;
/// <summary>The columns of the chart.</summary>
public static IReadOnlyList<ImportField> 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"]),
];
/// <summary>Checks the rows of a chart.</summary>
/// <param name="rows">The rows.</param>
/// <returns>A result per row, and the accounts without errors.</returns>
public static (IReadOnlyList<ImportRowResult> Results, IReadOnlyList<ImportedAccount> Accounts) Check(IReadOnlyList<ImportRow> 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<string, AccountNature?>(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<string>(StringComparer.OrdinalIgnoreCase);
var results = new List<ImportRowResult>(rows.Count);
var accounts = new List<ImportedAccount>();
foreach (var row in rows)
{
var messages = new List<ImportMessage>();
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);
}
/// <summary>The code without its last part, or <see langword="null"/> for a first level account.</summary>
/// <param name="code">The code.</param>
/// <returns>The parent code.</returns>
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<string, AccountNature?> 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<string> words) => text is null ? null : ImportValues.Choice(text, words) is var i and >= 0 ? i : null;
}
/// <summary>
/// The chart of accounts (<c>piano-dei-conti</c>): CSV, XLSX or <c>khaemhat-coa.json</c>. The accounts the check
/// accepts are added; those that exist are updated when the options say so (M7, issue #62).
/// </summary>
public sealed class ChartOfAccountsImportTarget : IImportTarget
{
/// <summary>The permission to change the chart of accounts.</summary>
public const string WritePermission = "ledger.account.write";
private readonly PermissionService _permissions;
private readonly IUnitOfWorkFactory? _factory;
/// <summary>Creates the target.</summary>
/// <param name="permissions">Checks the permission.</param>
/// <param name="factory">The units of work, to write the accounts.</param>
public ChartOfAccountsImportTarget(PermissionService permissions, IUnitOfWorkFactory? factory = null)
{
_permissions = permissions;
_factory = factory;
}
/// <inheritdoc />
public string Key => "piano-dei-conti";
/// <inheritdoc />
public string ModuleCode => ModuleCodes.Accounting;
/// <inheritdoc />
public string Permission => WritePermission;
/// <inheritdoc />
public string ExportPermission => "ledger.account.read";
/// <inheritdoc />
public bool CanApply => _factory is not null;
/// <inheritdoc />
public bool CanExport => _factory is not null;
/// <inheritdoc />
public IReadOnlyList<ImportField> Fields => ChartOfAccountsImportValidator.Fields;
/// <inheritdoc />
public async Task<IReadOnlyList<ImportRowResult>> CheckAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
await CompanyGuard.DemandAsync(_permissions, context.Actor, context.CompanyCode, Permission, cancellationToken).ConfigureAwait(false);
return ChartOfAccountsImportValidator.Check(rows).Results;
}
/// <inheritdoc />
public async Task<IReadOnlyList<ImportRowResult>> ApplyAsync(ImportContext context, IReadOnlyList<ImportRow> 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<string, bool> 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 })];
}
/// <inheritdoc />
public async Task<IReadOnlyList<IReadOnlyList<object?>>> 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<GlAccount, long>().ListAsync(Data.Querying.Query.For<GlAccount>(), cancellationToken).ConfigureAwait(false)).Items
.OrderBy(a => a.Code, StringComparer.Ordinal);
return [.. accounts.Select(a => (IReadOnlyList<object?>)
[
a.Code, a.Description, a.Level, ChartOfAccountsImportValidator.ParentOf(a.Code), ChartOfAccountsImportValidator.NatureWords[(int)a.Nature],
ChartOfAccountsImportValidator.TypeWords[(int)a.Type], a.StatementLine, a.Reclassification,
(a.Postable ? "M" : string.Empty) + (a.VatRelevant ? "I" : string.Empty) + (a.SubLedger ? "P" : string.Empty)
+ (a.ClosesAutomatically ? "C" : string.Empty) + (a.Disabled ? "X" : string.Empty),
])];
}
}