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>
333 lines
15 KiB
C#
333 lines
15 KiB
C#
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;
|
|
|
|
/// <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>
|
|
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);
|
|
|
|
/// <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')));
|
|
}
|
|
|
|
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>. Until the ledger exists (M7)
|
|
/// the file is only checked; M7 writes the accounts this check accepts.
|
|
/// </summary>
|
|
/// <param name="permissions">Checks the permission.</param>
|
|
public sealed class ChartOfAccountsImportTarget(PermissionService permissions) : IImportTarget
|
|
{
|
|
/// <summary>The permission to change the chart of accounts.</summary>
|
|
public const string WritePermission = "ledger.account.write";
|
|
|
|
/// <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 => false;
|
|
|
|
/// <inheritdoc />
|
|
public bool CanExport => false;
|
|
|
|
/// <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 Task<IReadOnlyList<ImportRowResult>> ApplyAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken) =>
|
|
throw new InvalidOperationException(ImportErrors.CheckOnly);
|
|
|
|
/// <inheritdoc />
|
|
public Task<IReadOnlyList<IReadOnlyList<object?>>> ExportAsync(ImportContext context, CancellationToken cancellationToken) =>
|
|
Task.FromResult<IReadOnlyList<IReadOnlyList<object?>>>([]);
|
|
}
|
|
|
|
/// <summary>
|
|
/// The opening stock (<c>giacenze-iniziali</c>): 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.
|
|
/// </summary>
|
|
/// <param name="factory">Opens the company databases.</param>
|
|
/// <param name="permissions">Checks the permission.</param>
|
|
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"]),
|
|
];
|
|
|
|
/// <inheritdoc />
|
|
public string Key => "giacenze-iniziali";
|
|
|
|
/// <inheritdoc />
|
|
public string ModuleCode => ModuleCodes.Core;
|
|
|
|
/// <inheritdoc />
|
|
public string Permission => "inventory.entry.write";
|
|
|
|
/// <inheritdoc />
|
|
public string ExportPermission => "inventory.stock.read";
|
|
|
|
/// <inheritdoc />
|
|
public bool CanApply => false;
|
|
|
|
/// <inheritdoc />
|
|
public bool CanExport => false;
|
|
|
|
/// <inheritdoc />
|
|
public IReadOnlyList<ImportField> Fields => StockFields;
|
|
|
|
/// <inheritdoc />
|
|
public async Task<IReadOnlyList<ImportRowResult>> CheckAsync(ImportContext context, IReadOnlyList<ImportRow> 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<Item, long>().ListAsync(Query.For<Item>(), 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<Warehouse>(uow, cancellationToken).ConfigureAwait(false);
|
|
var seen = new HashSet<(long, long)>();
|
|
var results = new List<ImportRowResult>(rows.Count);
|
|
foreach (var row in rows)
|
|
{
|
|
var messages = new List<ImportMessage>();
|
|
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;
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public Task<IReadOnlyList<ImportRowResult>> ApplyAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken) =>
|
|
throw new InvalidOperationException(ImportErrors.CheckOnly);
|
|
|
|
/// <inheritdoc />
|
|
public Task<IReadOnlyList<IReadOnlyList<object?>>> ExportAsync(ImportContext context, CancellationToken cancellationToken) =>
|
|
Task.FromResult<IReadOnlyList<IReadOnlyList<object?>>>([]);
|
|
}
|