using Khaemhat.Application.Modules; using Khaemhat.Application.Security; using Khaemhat.Application.Tables; using Khaemhat.Core.Accounting; using Khaemhat.Core.Items; using Khaemhat.Core.Tables; using Khaemhat.Data; using Khaemhat.Data.Querying; 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. 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); /// /// 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'))); } 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. Until the ledger exists (M7) /// the file is only checked; M7 writes the accounts this check accepts. /// /// Checks the permission. public sealed class ChartOfAccountsImportTarget(PermissionService permissions) : IImportTarget { /// The permission to change the chart of accounts. public const string WritePermission = "ledger.account.write"; /// public string Key => "piano-dei-conti"; /// public string ModuleCode => ModuleCodes.Accounting; /// public string Permission => WritePermission; /// public string ExportPermission => "ledger.account.read"; /// public bool CanApply => false; /// public bool CanExport => false; /// 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 Task> ApplyAsync(ImportContext context, IReadOnlyList rows, CancellationToken cancellationToken) => throw new InvalidOperationException(ImportErrors.CheckOnly); /// public Task>> ExportAsync(ImportContext context, CancellationToken cancellationToken) => Task.FromResult>>([]); } /// /// The opening stock (giacenze-iniziali): item, warehouse, quantity and unit cost. Until the stock entries exist /// (M6) the file is only checked; M6 writes the opening entry from the rows this check accepts. /// /// Opens the company databases. /// Checks the permission. public sealed class OpeningStockImportTarget(IUnitOfWorkFactory factory, PermissionService permissions) : IImportTarget { private static readonly ImportField[] StockFields = [ new("articolo", ImportFieldKind.Code, Required: true, Aliases: ["codice_articolo", "codice", "cod_articolo", "sku"]), new("deposito", ImportFieldKind.Code, Aliases: ["magazzino", "codice_magazzino"]), new("quantita", ImportFieldKind.Number, Required: true, Aliases: ["qta", "qty", "giacenza", "esistenza"]), new("costo_unitario", ImportFieldKind.Number, Aliases: ["costo", "valore_unitario", "prezzo_acquisto"]), ]; /// public string Key => "giacenze-iniziali"; /// public string ModuleCode => ModuleCodes.Core; /// public string Permission => "inventory.entry.write"; /// public string ExportPermission => "inventory.stock.read"; /// public bool CanApply => false; /// public bool CanExport => false; /// public IReadOnlyList Fields => StockFields; /// public async Task> CheckAsync(ImportContext context, IReadOnlyList rows, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(rows); var company = await CompanyGuard.DemandAsync(permissions, context.Actor, context.CompanyCode, Permission, cancellationToken).ConfigureAwait(false); await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); var items = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items; var codes = new CodeIndex(items.Select(i => (i.Code, i.Id))); var byId = items.ToDictionary(i => i.Id); var warehouses = await CodeIndex.LoadAsync(uow, cancellationToken).ConfigureAwait(false); var seen = new HashSet<(long, long)>(); var results = new List(rows.Count); foreach (var row in rows) { var messages = new List(); var cells = new CellReader(row, messages); messages.AddRange(StockFields.Where(f => f.Required && !cells.Has(f.Key)).Select(f => new ImportMessage(f.Key, ImportErrors.Required))); var item = cells.Code("articolo", codes) is { } id ? byId[id] : null; var warehouse = cells.Code("deposito", warehouses) ?? (cells.Has("deposito") ? null : item?.WarehouseId); if (item is not null && (item.Kind != ItemKind.Goods || !item.Stocked)) { messages.Add(new("articolo", ImportErrors.NotStocked, Value: item.Code)); } if (item is not null && warehouse is null && !cells.Has("deposito")) { messages.Add(new("deposito", ImportErrors.Required)); } if (cells.Number("quantita") is <= 0) { messages.Add(new("quantita", ImportErrors.Positive)); } if (cells.Number("costo_unitario") is < 0) { messages.Add(new("costo_unitario", Items.ItemService.NotNegative)); } var label = row["articolo"] ?? string.Empty; if (item is not null && warehouse is { } w && !seen.Add((item.Id, w))) { messages.Add(new("articolo", ImportErrors.CodeRepeated, Value: label)); } results.Add(new(row.Line, label, messages.Any(m => !m.IsWarning) ? ImportAction.Skip : ImportAction.Create, messages)); } return results; } /// public Task> ApplyAsync(ImportContext context, IReadOnlyList rows, CancellationToken cancellationToken) => throw new InvalidOperationException(ImportErrors.CheckOnly); /// public Task>> ExportAsync(ImportContext context, CancellationToken cancellationToken) => Task.FromResult>>([]); }