Files
Khaemhat/src/Khaemhat.Application/Tables/CodeRuleService.cs
T
Alby96andClaude Opus 5.5 07555de700 feat: automatic codes and automatic filling (#43)
Parties, items and the CRM archives need codes given by the system without
duplicates, and the address and bank fields should fill themselves; this adds
both before the party and item screens that use them.

- CodeMask ({seq:0000}, {anno}, {categoria}) and code_sequences (migration
  015): one sequence per rule, year and category, taken under a lock in the
  transaction that saves the record, skipping codes written by hand
- CodeRuleService: rules in company settings with the masks of SPEC 11.12,
  validation, preview of the next code, manual code allowed or not
- AutoFillService: municipality from postal code and back, personal tax code,
  VIES, bank and BIC from the IBAN, delivery date on working days, options
  that can be switched off (the ECB job honours its option)
- IBankDirectory.ReadIban gives ABI and CAB even without the ABI list; the
  Italian pack now registers the directory
- Company preferences page (mockup 074) at /tabelle/preferenze, in the menu
- aria-checked now renders true/false on switch rows and profile radios
- ADR 0027, wiki, CHANGELOG, STATUS, DATA-MODEL

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 23:33:02 +01:00

287 lines
14 KiB
C#

using Khaemhat.Application.Instance;
using Khaemhat.Application.Modules;
using Khaemhat.Application.Security;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Tables;
/// <summary>A table whose codes can be given automatically (SPEC §11.12, mockup 074).</summary>
/// <param name="Key">The rule key, also the start of the sequence keys, such as <c>customers</c>.</param>
/// <param name="Group">The box of the preferences page: <c>parties</c>, <c>items</c> or <c>crm</c>.</param>
/// <param name="DefaultMask">The mask of a new company.</param>
/// <param name="Module">The licence module the table belongs to.</param>
/// <param name="CategoriesAllowed">Whether the mask may use the category.</param>
/// <param name="MaxLength">The longest code the table accepts.</param>
public sealed record CodeRuleDefinition(string Key, string Group, string DefaultMask, string Module, bool CategoriesAllowed = false, int MaxLength = 20);
/// <summary>The automatic code of a table as the company set it.</summary>
/// <param name="Key">The rule key.</param>
/// <param name="Mask">The mask.</param>
/// <param name="AllowManual">Whether a user may write a code instead of the automatic one.</param>
/// <param name="UniqueBarcode">Items only: refuse two items with the same EAN.</param>
public sealed record CodeRule(string Key, string Mask, bool AllowManual, bool UniqueBarcode = false);
/// <summary>
/// The automatic codes of a company (SPEC §11.12): the mask of each table in the company settings
/// (<c>codes.&lt;table&gt;.mask</c>, <c>codes.&lt;table&gt;.manual</c>) and the numbers in <c>code_sequences</c>, given
/// under a lock inside the transaction that saves the record, so two saves at the same time never get the same code. A
/// number whose code is already taken (a code written by hand) is skipped.
/// </summary>
/// <param name="factory">The units of work.</param>
/// <param name="permissions">The permissions.</param>
/// <param name="settings">The company settings.</param>
public sealed class CodeRuleService(IUnitOfWorkFactory factory, PermissionService permissions, CompanySettingsService settings)
{
/// <summary>The start of the setting keys.</summary>
public const string SettingPrefix = "codes.";
/// <summary>Error: the code was written by hand where only automatic codes are allowed.</summary>
public const string ManualNotAllowed = "codes.manual";
/// <summary>Error: the mask uses the category and the record has none.</summary>
public const string CategoryRequired = "codes.category-required";
/// <summary>Error: the code is longer than the table accepts.</summary>
public const string CodeTooLong = "codes.too-long";
/// <summary>Error: no free code was found (too many codes taken by hand).</summary>
public const string Exhausted = "codes.exhausted";
/// <summary>The field the errors of a record's code are reported on.</summary>
public const string CodeField = "Code";
/// <summary>The field the errors of a mask are reported on.</summary>
public const string MaskField = "Mask";
private const int MaxSkips = 1000;
/// <summary>The tables with automatic codes and their masks of SPEC §11.12.</summary>
public static readonly IReadOnlyList<CodeRuleDefinition> Definitions =
[
new("customers", "parties", "C{seq:000000}", ModuleCodes.Core),
new("suppliers", "parties", "F{seq:000000}", ModuleCodes.Core),
new("leads", "parties", "L{anno}-{seq:0000}", ModuleCodes.Crm),
new("items", "items", "{categoria}-{seq:0000}", ModuleCodes.Core, CategoriesAllowed: true, MaxLength: 30),
new("assets", "items", "CESP-{seq:0000}", ModuleCodes.Assets),
new("opportunities", "crm", "OPP-{anno}-{seq:0000}", ModuleCodes.Crm),
new("tickets", "crm", "TK-{anno}-{seq:0000}", ModuleCodes.Services),
new("service-contracts", "crm", "SVC-{seq:0000}", ModuleCodes.Services),
new("interventions", "crm", "MAN-{anno}-{seq:0000}", ModuleCodes.Services),
];
/// <summary>The definition of a rule.</summary>
/// <param name="key">The rule key.</param>
/// <returns>The definition.</returns>
/// <exception cref="KeyNotFoundException">The key is not a rule.</exception>
public static CodeRuleDefinition Definition(string key) =>
Definitions.FirstOrDefault(d => d.Key == key) ?? throw new KeyNotFoundException("Unknown code rule " + key + ".");
/// <summary>The rule of a new company.</summary>
/// <param name="definition">The table.</param>
/// <returns>The rule.</returns>
public static CodeRule DefaultRule(CodeRuleDefinition definition)
{
ArgumentNullException.ThrowIfNull(definition);
return new CodeRule(definition.Key, definition.DefaultMask, AllowManual: true, UniqueBarcode: definition.Key == "items");
}
/// <summary>Checks a set of rules.</summary>
/// <param name="rules">The rules.</param>
/// <returns>The errors, on <c>&lt;key&gt;.Mask</c>.</returns>
public static IReadOnlyList<TableProblem> Validate(IEnumerable<CodeRule> rules)
{
ArgumentNullException.ThrowIfNull(rules);
var problems = new List<TableProblem>();
foreach (var rule in rules)
{
var definition = Definition(rule.Key);
if (CodeMask.Check(rule.Mask, definition.MaxLength, definition.CategoriesAllowed) is { } error)
{
problems.Add(new(rule.Key + "." + MaskField, error));
}
}
return problems;
}
/// <summary>The rules of a company, every table included (the default where the company set nothing).</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The rules, in the order of <see cref="Definitions"/>.</returns>
public async Task<IReadOnlyList<CodeRule>> RulesAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(permissions, actor, companyCode, TableService.ReadPermission, cancellationToken).ConfigureAwait(false);
return await ReadRulesAsync(company, cancellationToken).ConfigureAwait(false);
}
/// <summary>The rule of one table, for the services that save its records (no permission check).</summary>
/// <param name="companyCode">The company.</param>
/// <param name="key">The rule key.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The rule.</returns>
public async Task<CodeRule> RuleAsync(string companyCode, string key, CancellationToken cancellationToken = default)
{
_ = Definition(key);
return (await ReadRulesAsync(CompanyCodes.Normalize(companyCode), cancellationToken).ConfigureAwait(false)).First(r => r.Key == key);
}
/// <summary>Saves the rules of a company.</summary>
/// <param name="actor">Who saves.</param>
/// <param name="companyCode">The company.</param>
/// <param name="rules">The rules (tables left out keep their rule).</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The rules now in force.</returns>
/// <exception cref="ValidationFailedException">A mask is not valid (<c>&lt;key&gt;.Mask:code</c>).</exception>
public async Task<IReadOnlyList<CodeRule>> SaveAsync(Actor actor, string companyCode, IReadOnlyList<CodeRule> rules, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(rules);
var company = await CompanyGuard.DemandAsync(permissions, actor, companyCode, TableService.WritePermission, cancellationToken).ConfigureAwait(false);
var problems = Validate(rules);
if (problems.Count > 0)
{
throw new ValidationFailedException([.. problems.Select(p => p.Field + ":" + p.Code)]);
}
var values = new Dictionary<string, string?>(StringComparer.Ordinal);
foreach (var rule in rules)
{
values[SettingPrefix + rule.Key + ".mask"] = CodeMask.Parse(rule.Mask).Text;
values[SettingPrefix + rule.Key + ".manual"] = rule.AllowManual ? "true" : "false";
if (rule.Key == "items")
{
values[SettingPrefix + "items.unique-barcode"] = rule.UniqueBarcode ? "true" : "false";
}
}
await settings.SetManyAsync(actor, company, values, cancellationToken).ConfigureAwait(false);
return await ReadRulesAsync(company, cancellationToken).ConfigureAwait(false);
}
/// <summary>The code the next record would get, without taking it.</summary>
/// <param name="actor">Who asks.</param>
/// <param name="companyCode">The company.</param>
/// <param name="rule">The rule, possibly not saved yet.</param>
/// <param name="date">The date of the record (for masks with the year).</param>
/// <param name="category">The category (for masks with the category).</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The code, or <see langword="null"/> when the mask is not valid.</returns>
public async Task<string?> PreviewAsync(Actor actor, string companyCode, CodeRule rule, DateOnly date, string? category, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(rule);
var company = await CompanyGuard.DemandAsync(permissions, actor, companyCode, TableService.ReadPermission, cancellationToken).ConfigureAwait(false);
if (!CodeMask.TryParse(rule.Mask, out var mask, out _) || (mask!.UsesCategory && string.IsNullOrWhiteSpace(category)))
{
return null;
}
await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var key = mask.SequenceKey(rule.Key, date.Year, category);
var last = await uow.Repository<CodeSequence, long>().FindAsync(Query.For<CodeSequence>().Where(s => s.Key == key), cancellationToken).ConfigureAwait(false);
return mask.Format((last?.LastValue ?? 0) + 1, date.Year, category);
}
/// <summary>
/// Takes the next free code inside the caller's transaction; the number is used up only if the transaction commits.
/// </summary>
/// <param name="unitOfWork">The unit of work of the save, with a transaction open.</param>
/// <param name="rule">The rule.</param>
/// <param name="date">The date of the record.</param>
/// <param name="category">The category, for masks with the category.</param>
/// <param name="taken">Whether a code is already used in the table.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The code.</returns>
/// <exception cref="ValidationFailedException">No category, code too long, or no free code (<c>Code:code</c>).</exception>
public static async Task<string> AssignAsync(IUnitOfWork unitOfWork, CodeRule rule, DateOnly date, string? category,
Func<string, CancellationToken, Task<bool>> taken, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(unitOfWork);
ArgumentNullException.ThrowIfNull(rule);
ArgumentNullException.ThrowIfNull(taken);
var definition = Definition(rule.Key);
var mask = CodeMask.Parse(rule.Mask);
if (mask.UsesCategory && string.IsNullOrWhiteSpace(category))
{
throw new ValidationFailedException([CodeField + ":" + CategoryRequired]);
}
var key = mask.SequenceKey(rule.Key, date.Year, category);
await unitOfWork.AcquireLockAsync("code:" + key, cancellationToken).ConfigureAwait(false);
var repository = unitOfWork.Repository<CodeSequence, long>();
var sequence = await repository.FindAsync(Query.For<CodeSequence>().Where(s => s.Key == key), cancellationToken).ConfigureAwait(false)
?? new CodeSequence { Key = key };
for (var skip = 0; skip < MaxSkips; skip++)
{
sequence.LastValue++;
var code = mask.Format(sequence.LastValue, date.Year, category);
if (code.Length > definition.MaxLength)
{
throw new ValidationFailedException([CodeField + ":" + CodeTooLong]);
}
if (await taken(code, cancellationToken).ConfigureAwait(false))
{
continue;
}
if (sequence.Id == 0)
{
await repository.InsertAsync(sequence, cancellationToken).ConfigureAwait(false);
}
else
{
await repository.UpdateAsync(sequence, cancellationToken).ConfigureAwait(false);
}
return code;
}
throw new ValidationFailedException([CodeField + ":" + Exhausted]);
}
/// <summary>Checks a code written by hand against the rule.</summary>
/// <param name="rule">The rule.</param>
/// <param name="code">The code, empty to get the automatic one.</param>
/// <returns>The error code, or <see langword="null"/>.</returns>
public static string? CheckManual(CodeRule rule, string? code)
{
ArgumentNullException.ThrowIfNull(rule);
if (string.IsNullOrWhiteSpace(code))
{
return null;
}
if (!rule.AllowManual)
{
return ManualNotAllowed;
}
return code.Trim().Length > Definition(rule.Key).MaxLength ? CodeTooLong : null;
}
private async Task<IReadOnlyList<CodeRule>> ReadRulesAsync(string company, CancellationToken cancellationToken)
{
var values = await settings.GetAllAsync(company, SettingPrefix, cancellationToken).ConfigureAwait(false);
return
[
.. Definitions.Select(d =>
{
var rule = DefaultRule(d);
var mask = values.GetValueOrDefault(SettingPrefix + d.Key + ".mask");
return rule with
{
Mask = mask is { Length: > 0 } && CodeMask.Check(mask, d.MaxLength, d.CategoriesAllowed) is null ? mask : rule.Mask,
AllowManual = ReadFlag(values, SettingPrefix + d.Key + ".manual", rule.AllowManual),
UniqueBarcode = d.Key == "items" && ReadFlag(values, SettingPrefix + "items.unique-barcode", rule.UniqueBarcode),
};
}),
];
}
private static bool ReadFlag(IReadOnlyDictionary<string, string?> values, string key, bool fallback) =>
values.TryGetValue(key, out var value) && bool.TryParse(value, out var flag) ? flag : fallback;
}