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:
1 parent
9bcf8c1082
commit
07555de700
27 files changed
+1627
-40
No files matched your search
@@ -0,0 +1,289 @@
|
||||
using Khaemhat.Application.Instance;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
using Khaemhat.Infrastructure.Http;
|
||||
|
||||
namespace Khaemhat.Application.Tables;
|
||||
|
||||
/// <summary>A municipality proposed for an address.</summary>
|
||||
/// <param name="MunicipalityCode">The code of the municipality (Italy: cadastral code).</param>
|
||||
/// <param name="Name">The name.</param>
|
||||
/// <param name="ProvinceCode">The province.</param>
|
||||
/// <param name="Region">The region.</param>
|
||||
/// <param name="PostalCode">The postal code: the one typed, or the only one of the municipality.</param>
|
||||
public sealed record PlaceSuggestion(string MunicipalityCode, string Name, string ProvinceCode, string? Region, string? PostalCode);
|
||||
|
||||
/// <summary>An option of the automatic filling (mockup 074).</summary>
|
||||
/// <param name="Key">The key, also the setting <c>autofill.<key></c>.</param>
|
||||
/// <param name="Default">Whether it is on in a new company.</param>
|
||||
public sealed record AutoFillOption(string Key, bool Default = true);
|
||||
|
||||
/// <summary>
|
||||
/// The automatic filling of SPEC §11.12: municipality, province and region from the postal code, the personal tax code
|
||||
/// from the personal data, the VIES check of EU VAT numbers, bank and BIC from the IBAN, delivery dates from the lead
|
||||
/// time. Each option can be switched off in the company preferences; the forms ask <see cref="IsOnAsync"/> before
|
||||
/// filling. The defaults that documents take from the customer and the document type come with the documents (M5).
|
||||
/// </summary>
|
||||
/// <param name="tables">The company tables.</param>
|
||||
/// <param name="fiscal">The fiscal pack of the company.</param>
|
||||
/// <param name="settings">The company settings.</param>
|
||||
/// <param name="permissions">The permissions.</param>
|
||||
/// <param name="vies">The VIES client.</param>
|
||||
public sealed class AutoFillService(TableService tables, CompanyFiscalContext fiscal, CompanySettingsService settings, PermissionService permissions, ViesClient vies)
|
||||
{
|
||||
/// <summary>The start of the setting keys.</summary>
|
||||
public const string SettingPrefix = "autofill.";
|
||||
|
||||
/// <summary>Municipality, province and region from the postal code.</summary>
|
||||
public const string PostalCode = "postal-code";
|
||||
|
||||
/// <summary>Personal tax code from the personal data.</summary>
|
||||
public const string TaxCode = "tax-code";
|
||||
|
||||
/// <summary>VIES check of EU VAT numbers when saving.</summary>
|
||||
public const string Vies = "vies";
|
||||
|
||||
/// <summary>Bank and BIC from the IBAN.</summary>
|
||||
public const string BankFromIban = "bank-from-iban";
|
||||
|
||||
/// <summary>Daily ECB exchange rates.</summary>
|
||||
public const string EcbRates = "ecb-rates";
|
||||
|
||||
/// <summary>Item description copied into document lines.</summary>
|
||||
public const string ItemDescription = "item-description";
|
||||
|
||||
/// <summary>Last price charged to the customer shown as reference.</summary>
|
||||
public const string LastPrice = "last-price";
|
||||
|
||||
/// <summary>Start from the last similar document of the customer.</summary>
|
||||
public const string LastDocument = "last-document";
|
||||
|
||||
/// <summary>Delivery date = document date + lead time.</summary>
|
||||
public const string DeliveryDate = "delivery-date";
|
||||
|
||||
/// <summary>Revenue and cost accounts from item, category and reason.</summary>
|
||||
public const string Accounts = "accounts";
|
||||
|
||||
private const int MaxSuggestions = 20;
|
||||
|
||||
/// <summary>The options, in the order of the preferences page.</summary>
|
||||
public static readonly IReadOnlyList<AutoFillOption> Options =
|
||||
[
|
||||
new(PostalCode), new(TaxCode), new(Vies), new(BankFromIban), new(EcbRates),
|
||||
new(ItemDescription), new(LastPrice), new(LastDocument, Default: false), new(DeliveryDate), new(Accounts),
|
||||
];
|
||||
|
||||
/// <summary>The options of a company.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>Whether each option is on, by key.</returns>
|
||||
public async Task<IReadOnlyDictionary<string, bool>> OptionsAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(permissions, actor, companyCode, TableService.ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||
return await ReadAsync(company, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Whether an option is on, for the forms and services that fill fields (no permission check).</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="key">The option.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns><see langword="true"/> when on.</returns>
|
||||
public async Task<bool> IsOnAsync(string companyCode, string key, CancellationToken cancellationToken = default) =>
|
||||
(await ReadAsync(companyCode, cancellationToken).ConfigureAwait(false)).GetValueOrDefault(key);
|
||||
|
||||
/// <summary>Saves the options of a company.</summary>
|
||||
/// <param name="actor">Who saves.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="values">The options to change, by key.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The options now in force.</returns>
|
||||
public async Task<IReadOnlyDictionary<string, bool>> SaveOptionsAsync(Actor actor, string companyCode, IReadOnlyDictionary<string, bool> values,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(values);
|
||||
var company = await CompanyGuard.DemandAsync(permissions, actor, companyCode, TableService.WritePermission, cancellationToken).ConfigureAwait(false);
|
||||
var known = Options.Select(o => o.Key).ToHashSet(StringComparer.Ordinal);
|
||||
await settings.SetManyAsync(
|
||||
actor,
|
||||
company,
|
||||
values.Where(v => known.Contains(v.Key)).ToDictionary(v => SettingPrefix + v.Key, v => (string?)(v.Value ? "true" : "false"), StringComparer.Ordinal),
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
return await ReadAsync(company, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The municipalities with a postal code.</summary>
|
||||
/// <param name="actor">Who asks.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="postalCode">The postal code.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The municipalities, by name; empty when none or when the code is not complete.</returns>
|
||||
public async Task<IReadOnlyList<PlaceSuggestion>> PlacesByPostalCodeAsync(Actor actor, string companyCode, string? postalCode, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var code = postalCode?.Trim() ?? string.Empty;
|
||||
if (code.Length < 4 || !code.All(char.IsAsciiDigit))
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
return
|
||||
[
|
||||
.. (await MunicipalitiesAsync(actor, companyCode, cancellationToken).ConfigureAwait(false))
|
||||
.Where(m => PostalCodeMatches(m.PostalCodes, code))
|
||||
.OrderBy(m => m.Description, StringComparer.CurrentCulture)
|
||||
.Take(MaxSuggestions)
|
||||
.Select(m => Suggest(m, code)),
|
||||
];
|
||||
}
|
||||
|
||||
/// <summary>The municipalities whose name starts with some text.</summary>
|
||||
/// <param name="actor">Who asks.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="name">The start of the name.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The municipalities, exact name first.</returns>
|
||||
public async Task<IReadOnlyList<PlaceSuggestion>> PlacesByNameAsync(Actor actor, string companyCode, string? name, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var text = name?.Trim() ?? string.Empty;
|
||||
if (text.Length < 2)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
return
|
||||
[
|
||||
.. (await MunicipalitiesAsync(actor, companyCode, cancellationToken).ConfigureAwait(false))
|
||||
.Where(m => m.Description.StartsWith(text, StringComparison.CurrentCultureIgnoreCase))
|
||||
.OrderBy(m => m.Description.Length == text.Length ? 0 : 1)
|
||||
.ThenBy(m => m.Description, StringComparer.CurrentCulture)
|
||||
.Take(MaxSuggestions)
|
||||
.Select(m => Suggest(m, null)),
|
||||
];
|
||||
}
|
||||
|
||||
/// <summary>Whether a postal code is in a list such as <c>10121,10122</c> or <c>00118-00199</c>.</summary>
|
||||
/// <param name="list">The postal codes of a municipality.</param>
|
||||
/// <param name="code">The postal code.</param>
|
||||
/// <returns><see langword="true"/> when it is one of them.</returns>
|
||||
public static bool PostalCodeMatches(string? list, string code)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(code);
|
||||
foreach (var item in (list ?? string.Empty).Split([',', ';', ' '], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
|
||||
{
|
||||
var dash = item.IndexOf('-', StringComparison.Ordinal);
|
||||
if (dash < 0)
|
||||
{
|
||||
if (string.Equals(item, code, StringComparison.Ordinal))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
var from = item[..dash].Trim();
|
||||
var to = item[(dash + 1)..].Trim();
|
||||
if (from.Length == code.Length && to.Length == code.Length
|
||||
&& string.CompareOrdinal(code, from) >= 0 && string.CompareOrdinal(code, to) <= 0)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>The personal tax code of a person, computed by the fiscal pack of the company.</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="data">The personal data.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The code, or <see langword="null"/> when the country has no such code or the data are incomplete.</returns>
|
||||
public async Task<string?> PersonalTaxCodeAsync(string companyCode, PersonalTaxCodeData data, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(data);
|
||||
var pack = await fiscal.PackOfAsync(companyCode, cancellationToken).ConfigureAwait(false);
|
||||
if (pack.GetFeature<ITaxIdentifierRules>() is not { } rules
|
||||
|| string.IsNullOrWhiteSpace(data.Surname) || string.IsNullOrWhiteSpace(data.GivenName) || string.IsNullOrWhiteSpace(data.BirthPlaceCode))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return rules.ComputePersonalTaxCode(data);
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Checks an EU VAT number with VIES.</summary>
|
||||
/// <param name="countryCode">The ISO country code.</param>
|
||||
/// <param name="vatNumber">The number.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The outcome; a service that does not answer gives <see cref="ViesStatus.Unavailable"/>.</returns>
|
||||
public Task<ViesResult> CheckVatAsync(string countryCode, string vatNumber, CancellationToken cancellationToken = default) =>
|
||||
vies.CheckAsync(countryCode, vatNumber, cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// The bank of an IBAN: name and BIC from the directory of the fiscal pack or, when the directory does not know the
|
||||
/// bank, from an account of the company at the same bank.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who asks.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="iban">The IBAN.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The bank, or <see langword="null"/> when the IBAN is not a domestic one.</returns>
|
||||
public async Task<BankInfo?> BankFromIbanAsync(Actor actor, string companyCode, string? iban, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var pack = await fiscal.PackOfAsync(companyCode, cancellationToken).ConfigureAwait(false);
|
||||
if (pack.GetFeature<IBankDirectory>() is not { } directory || directory.ReadIban(iban) is not { } bank)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (bank.Name is not null)
|
||||
{
|
||||
return bank;
|
||||
}
|
||||
|
||||
var known = (await tables.ActiveAsync<BankAccount>(actor, companyCode, cancellationToken).ConfigureAwait(false))
|
||||
.Select(a => (Account: a, Bank: directory.ReadIban(a.Iban)))
|
||||
.FirstOrDefault(a => a.Bank?.BankCode == bank.BankCode && !string.IsNullOrWhiteSpace(a.Account.BankName));
|
||||
return known.Account is { } account ? bank with { Name = account.BankName, Bic = account.Bic } : bank;
|
||||
}
|
||||
|
||||
/// <summary>The delivery date of a record: its date plus the lead time, moved to the next working day.</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="date">The date of the document.</param>
|
||||
/// <param name="leadTimeDays">The lead time in calendar days.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The date.</returns>
|
||||
public async Task<DateOnly> DeliveryDateAsync(string companyCode, DateOnly date, int leadTimeDays, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var pack = await fiscal.PackOfAsync(companyCode, cancellationToken).ConfigureAwait(false);
|
||||
return pack.Calendar.NextWorkingDay(date.AddDays(Math.Max(0, leadTimeDays)));
|
||||
}
|
||||
|
||||
private async Task<IReadOnlyList<Municipality>> MunicipalitiesAsync(Actor actor, string companyCode, CancellationToken cancellationToken) =>
|
||||
await tables.ActiveAsync<Municipality>(actor, companyCode, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
private static PlaceSuggestion Suggest(Municipality municipality, string? postalCode)
|
||||
{
|
||||
var single = municipality.PostalCodes is { } codes && !codes.Contains(',', StringComparison.Ordinal) && !codes.Contains('-', StringComparison.Ordinal)
|
||||
? codes.Trim()
|
||||
: null;
|
||||
return new PlaceSuggestion(municipality.Code, municipality.Description, municipality.ProvinceCode, municipality.Region, postalCode ?? single);
|
||||
}
|
||||
|
||||
private async Task<IReadOnlyDictionary<string, bool>> ReadAsync(string company, CancellationToken cancellationToken)
|
||||
{
|
||||
var values = await settings.GetAllAsync(company, SettingPrefix, cancellationToken).ConfigureAwait(false);
|
||||
return Options.ToDictionary(
|
||||
o => o.Key,
|
||||
o => values.TryGetValue(SettingPrefix + o.Key, out var value) && bool.TryParse(value, out var on) ? on : o.Default,
|
||||
StringComparer.Ordinal);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
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.<table>.mask</c>, <c>codes.<table>.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><key>.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><key>.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;
|
||||
}
|
||||
|
||||
@@ -176,11 +176,15 @@ public sealed class ExchangeRateService
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Loads the ECB reference rates into every active company (SPEC §11.12 "cambi BCE"), on working days.</summary>
|
||||
/// <summary>
|
||||
/// Loads the ECB reference rates into every active company (SPEC §11.12 "cambi BCE"), on working days; a company that
|
||||
/// switched the option off in its preferences is skipped.
|
||||
/// </summary>
|
||||
/// <param name="client">The ECB client.</param>
|
||||
/// <param name="rates">The exchange rates.</param>
|
||||
/// <param name="companies">The companies.</param>
|
||||
public sealed class EcbRatesJob(EcbRatesClient client, ExchangeRateService rates, ICompanyRegistry companies) : IScheduledJob
|
||||
/// <param name="autoFill">The automatic filling options.</param>
|
||||
public sealed class EcbRatesJob(EcbRatesClient client, ExchangeRateService rates, ICompanyRegistry companies, AutoFillService autoFill) : IScheduledJob
|
||||
{
|
||||
/// <summary>The job type.</summary>
|
||||
public const string JobType = "tables.ecb-rates";
|
||||
@@ -196,7 +200,7 @@ public sealed class EcbRatesJob(EcbRatesClient client, ExchangeRateService rates
|
||||
var changed = 0;
|
||||
foreach (var company in await companies.ListAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
if (company.Status is CompanyStatus.Active)
|
||||
if (company.Status is CompanyStatus.Active && await autoFill.IsOnAsync(company.Code, AutoFillService.EcbRates, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
changed += await rates.StoreEcbAsync(company.Code, downloaded, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user