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>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-11 23:33:02 +01:00
1 parent 9bcf8c1082
commit 07555de700
27 files changed
+1627 -40

No files matched your search

+268
View File
@@ -0,0 +1,268 @@
using System.Globalization;
using System.Text;
using Khaemhat.Core.Entities;
namespace Khaemhat.Core.Tables;
/// <summary>
/// The last number given by an automatic code sequence (<c>code_sequences</c>, SPEC §11.12). One row per rule and,
/// when the mask asks for it, per year and per category: the key is <c>items:VALV</c> or <c>leads:2026</c>.
/// </summary>
public sealed class CodeSequence : Entity<long>
{
/// <summary>The key of the sequence, see <see cref="CodeMask.SequenceKey"/>.</summary>
public string Key { get; set; } = string.Empty;
/// <summary>The last number given; the next code uses this plus one.</summary>
public long LastValue { get; set; }
}
/// <summary>
/// A mask of automatic codes (SPEC §11.12, mockup 074), such as <c>C{seq:000000}</c> or <c>{categoria}-{seq:0000}</c>:
/// letters, digits and <c>- _ / .</c> written as they are, plus the placeholders <c>{seq:000}</c> (the progressive
/// number with as many digits as zeros; <c>{seq}</c> without zeros in front), <c>{anno}</c> (the year, four digits; also
/// <c>{year}</c>) and <c>{categoria}</c> (the code of the category; also <c>{category}</c>). The number restarts every
/// year when the mask has the year, and runs separately per category when it has the category.
/// </summary>
public sealed record CodeMask
{
/// <summary>Error: the mask needs exactly one <c>{seq}</c>.</summary>
public const string SequenceRequired = "codes.mask.sequence";
/// <summary>Error: a placeholder is not known.</summary>
public const string UnknownPlaceholder = "codes.mask.placeholder";
/// <summary>Error: the mask has characters not allowed in a code.</summary>
public const string InvalidCharacter = "codes.mask.character";
/// <summary>Error: the codes of the mask are longer than the code column.</summary>
public const string TooLong = "codes.mask.too-long";
/// <summary>Error: the mask uses the category for a table without categories.</summary>
public const string CategoryNotAllowed = "codes.mask.category";
private const string AllowedLiterals = "-_/.";
private readonly IReadOnlyList<Part> _parts;
private CodeMask(string text, IReadOnlyList<Part> parts)
{
Text = text;
_parts = parts;
Digits = parts.First(p => p.Kind == PartKind.Sequence).Digits;
UsesYear = parts.Any(p => p.Kind == PartKind.Year);
UsesCategory = parts.Any(p => p.Kind == PartKind.Category);
FixedLength = parts.Sum(p => p.Kind switch
{
PartKind.Literal => p.Text.Length,
PartKind.Year => 4,
PartKind.Sequence => Math.Max(1, p.Digits),
_ => 0,
});
}
private enum PartKind
{
Literal,
Sequence,
Year,
Category,
}
/// <summary>The mask, with the written characters in upper case.</summary>
public string Text { get; }
/// <summary>The digits of the number (0: as many as needed).</summary>
public int Digits { get; }
/// <summary>Whether the number restarts every year.</summary>
public bool UsesYear { get; }
/// <summary>Whether the code contains the category and the number runs per category.</summary>
public bool UsesCategory { get; }
/// <summary>The length of a code without the category, with the number at its minimum width.</summary>
public int FixedLength { get; }
/// <summary>Reads a mask.</summary>
/// <param name="text">The mask as typed.</param>
/// <param name="mask">The mask, when valid.</param>
/// <param name="error">The error code, when not.</param>
/// <returns><see langword="true"/> when valid.</returns>
public static bool TryParse(string? text, out CodeMask? mask, out string? error)
{
mask = null;
error = null;
var value = text?.Trim() ?? string.Empty;
var parts = new List<Part>();
var literal = new StringBuilder();
var i = 0;
while (i < value.Length)
{
var c = value[i];
if (c == '{')
{
var end = value.IndexOf('}', i);
if (end < 0)
{
error = UnknownPlaceholder;
return false;
}
if (literal.Length > 0)
{
parts.Add(new Part(PartKind.Literal, literal.ToString(), 0));
literal.Clear();
}
if (!TryReadPlaceholder(value[(i + 1)..end], out var part))
{
error = UnknownPlaceholder;
return false;
}
parts.Add(part);
i = end + 1;
continue;
}
var upper = char.ToUpperInvariant(c);
if (!(upper is >= 'A' and <= 'Z' or >= '0' and <= '9') && !AllowedLiterals.Contains(upper, StringComparison.Ordinal))
{
error = InvalidCharacter;
return false;
}
literal.Append(upper);
i++;
}
if (literal.Length > 0)
{
parts.Add(new Part(PartKind.Literal, literal.ToString(), 0));
}
if (parts.Count(p => p.Kind == PartKind.Sequence) != 1)
{
error = SequenceRequired;
return false;
}
mask = new CodeMask(string.Concat(parts.Select(p => p.ToMask())), parts);
return true;
}
/// <summary>Reads a mask that is known to be valid.</summary>
/// <param name="text">The mask.</param>
/// <returns>The mask.</returns>
/// <exception cref="FormatException">The mask is not valid.</exception>
public static CodeMask Parse(string text) =>
TryParse(text, out var mask, out var error) ? mask! : throw new FormatException(error);
/// <summary>The checks of a mask for a table.</summary>
/// <param name="text">The mask as typed.</param>
/// <param name="maxLength">The longest code the table accepts.</param>
/// <param name="categoriesAllowed">Whether the table has categories.</param>
/// <returns>The error code, or <see langword="null"/> when the mask can be used.</returns>
public static string? Check(string? text, int maxLength, bool categoriesAllowed)
{
if (!TryParse(text, out var mask, out var error))
{
return error;
}
if (mask!.UsesCategory && !categoriesAllowed)
{
return CategoryNotAllowed;
}
// A category adds at least one character.
return mask.FixedLength + (mask.UsesCategory ? 1 : 0) > maxLength ? TooLong : null;
}
/// <summary>The key of the sequence a code of this mask takes its number from.</summary>
/// <param name="rule">The rule, such as <c>customers</c>.</param>
/// <param name="year">The year of the record.</param>
/// <param name="category">The category code, for masks with the category.</param>
/// <returns>The key, such as <c>items:VALV</c> or <c>leads:2026</c>.</returns>
public string SequenceKey(string rule, int year, string? category)
{
ArgumentException.ThrowIfNullOrWhiteSpace(rule);
var key = new StringBuilder(rule);
if (UsesYear)
{
key.Append(':').Append(year.ToString("D4", CultureInfo.InvariantCulture));
}
if (UsesCategory)
{
key.Append(':').Append(Normalize(category));
}
return key.ToString();
}
/// <summary>Writes a code.</summary>
/// <param name="number">The progressive number.</param>
/// <param name="year">The year.</param>
/// <param name="category">The category code, for masks with the category.</param>
/// <returns>The code.</returns>
public string Format(long number, int year, string? category)
{
ArgumentOutOfRangeException.ThrowIfNegative(number);
var code = new StringBuilder();
foreach (var part in _parts)
{
code.Append(part.Kind switch
{
PartKind.Sequence => number.ToString(part.Digits > 0 ? "D" + part.Digits.ToString(CultureInfo.InvariantCulture) : "D", CultureInfo.InvariantCulture),
PartKind.Year => year.ToString("D4", CultureInfo.InvariantCulture),
PartKind.Category => Normalize(category),
_ => part.Text,
});
}
return code.ToString();
}
/// <inheritdoc />
public override string ToString() => Text;
private static string Normalize(string? category) => (category ?? string.Empty).Trim().ToUpperInvariant();
private static bool TryReadPlaceholder(string body, out Part part)
{
var colon = body.IndexOf(':', StringComparison.Ordinal);
var name = (colon < 0 ? body : body[..colon]).Trim().ToUpperInvariant();
var format = colon < 0 ? null : body[(colon + 1)..].Trim();
part = default;
switch (name)
{
case "SEQ" when format is null:
part = new Part(PartKind.Sequence, string.Empty, 0);
return true;
case "SEQ" when format.Length is > 0 and <= 12 && format.All(c => c == '0'):
part = new Part(PartKind.Sequence, string.Empty, format.Length);
return true;
case "ANNO" or "YEAR" when format is null:
part = new Part(PartKind.Year, string.Empty, 0);
return true;
case "CATEGORIA" or "CATEGORY" when format is null:
part = new Part(PartKind.Category, string.Empty, 0);
return true;
default:
return false;
}
}
private readonly record struct Part(PartKind Kind, string Text, int Digits)
{
public string ToMask() => Kind switch
{
PartKind.Sequence => Digits > 0 ? "{seq:" + new string('0', Digits) + "}" : "{seq}",
PartKind.Year => "{anno}",
PartKind.Category => "{categoria}",
_ => Text,
};
}
}