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;
/// A table whose codes can be given automatically (SPEC §11.12, mockup 074).
/// The rule key, also the start of the sequence keys, such as customers.
/// The box of the preferences page: parties, items or crm.
/// The mask of a new company.
/// The licence module the table belongs to.
/// Whether the mask may use the category.
/// The longest code the table accepts.
public sealed record CodeRuleDefinition(string Key, string Group, string DefaultMask, string Module, bool CategoriesAllowed = false, int MaxLength = 20);
/// The automatic code of a table as the company set it.
/// The rule key.
/// The mask.
/// Whether a user may write a code instead of the automatic one.
/// Items only: refuse two items with the same EAN.
public sealed record CodeRule(string Key, string Mask, bool AllowManual, bool UniqueBarcode = false);
///
/// The automatic codes of a company (SPEC §11.12): the mask of each table in the company settings
/// (codes.<table>.mask, codes.<table>.manual) and the numbers in code_sequences, 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.
///
/// The units of work.
/// The permissions.
/// The company settings.
public sealed class CodeRuleService(IUnitOfWorkFactory factory, PermissionService permissions, CompanySettingsService settings)
{
/// The start of the setting keys.
public const string SettingPrefix = "codes.";
/// Error: the code was written by hand where only automatic codes are allowed.
public const string ManualNotAllowed = "codes.manual";
/// Error: the mask uses the category and the record has none.
public const string CategoryRequired = "codes.category-required";
/// Error: the code is longer than the table accepts.
public const string CodeTooLong = "codes.too-long";
/// Error: no free code was found (too many codes taken by hand).
public const string Exhausted = "codes.exhausted";
/// The field the errors of a record's code are reported on.
public const string CodeField = "Code";
/// The field the errors of a mask are reported on.
public const string MaskField = "Mask";
private const int MaxSkips = 1000;
/// The tables with automatic codes and their masks of SPEC §11.12.
public static readonly IReadOnlyList 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),
];
/// The definition of a rule.
/// The rule key.
/// The definition.
/// The key is not a rule.
public static CodeRuleDefinition Definition(string key) =>
Definitions.FirstOrDefault(d => d.Key == key) ?? throw new KeyNotFoundException("Unknown code rule " + key + ".");
/// The rule of a new company.
/// The table.
/// The rule.
public static CodeRule DefaultRule(CodeRuleDefinition definition)
{
ArgumentNullException.ThrowIfNull(definition);
return new CodeRule(definition.Key, definition.DefaultMask, AllowManual: true, UniqueBarcode: definition.Key == "items");
}
/// Checks a set of rules.
/// The rules.
/// The errors, on <key>.Mask.
public static IReadOnlyList Validate(IEnumerable rules)
{
ArgumentNullException.ThrowIfNull(rules);
var problems = new List();
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;
}
/// The rules of a company, every table included (the default where the company set nothing).
/// Who reads.
/// The company.
/// Cancellation.
/// The rules, in the order of .
public async Task> 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);
}
/// The rule of one table, for the services that save its records (no permission check).
/// The company.
/// The rule key.
/// Cancellation.
/// The rule.
public async Task RuleAsync(string companyCode, string key, CancellationToken cancellationToken = default)
{
_ = Definition(key);
return (await ReadRulesAsync(CompanyCodes.Normalize(companyCode), cancellationToken).ConfigureAwait(false)).First(r => r.Key == key);
}
/// Saves the rules of a company.
/// Who saves.
/// The company.
/// The rules (tables left out keep their rule).
/// Cancellation.
/// The rules now in force.
/// A mask is not valid (<key>.Mask:code).
public async Task> SaveAsync(Actor actor, string companyCode, IReadOnlyList 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(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);
}
/// The code the next record would get, without taking it.
/// Who asks.
/// The company.
/// The rule, possibly not saved yet.
/// The date of the record (for masks with the year).
/// The category (for masks with the category).
/// Cancellation.
/// The code, or when the mask is not valid.
public async Task 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().FindAsync(Query.For().Where(s => s.Key == key), cancellationToken).ConfigureAwait(false);
return mask.Format((last?.LastValue ?? 0) + 1, date.Year, category);
}
///
/// Takes the next free code inside the caller's transaction; the number is used up only if the transaction commits.
///
/// The unit of work of the save, with a transaction open.
/// The rule.
/// The date of the record.
/// The category, for masks with the category.
/// Whether a code is already used in the table.
/// Cancellation.
/// The code.
/// No category, code too long, or no free code (Code:code).
public static async Task AssignAsync(IUnitOfWork unitOfWork, CodeRule rule, DateOnly date, string? category,
Func> 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();
var sequence = await repository.FindAsync(Query.For().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]);
}
/// Checks a code written by hand against the rule.
/// The rule.
/// The code, empty to get the automatic one.
/// The error code, or .
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> 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 values, string key, bool fallback) =>
values.TryGetValue(key, out var value) && bool.TryParse(value, out var flag) ? flag : fallback;
}