Files
Khaemhat/tests/Khaemhat.Web.Tests/Tables/CodeRulesTests.cs
T
Alby96andClaude Opus 5.5 321aae7e81 feat: provinces and municipalities from the ISTAT list in the base data (#45)
New companies now get the 110 provinces and 7,894 municipalities in force
(ISTAT list of 26/02/2026, CC BY 4.0), so the tax code calculation and the
municipality lookups work without loading anything. The list lives in the
Italian pack behind a new IPlaceDirectory feature and is added by the base
seeder like the rest of the base data: missing codes only, never touching
existing rows. The pack data version moves to IT 2026.3 so existing
companies receive the lists at the next start.

Postal codes are left out: the only candidate source (comuni-json) has no
licence for them and stops at 2020 (ADR 0028).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 09:07:12 +01:00

180 lines
10 KiB
C#

using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Security;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Fiscal.Abstractions;
using Khaemhat.Web.Tests.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace Khaemhat.Web.Tests.Tables;
/// <summary>Automatic codes and automatic filling on a real instance (issue #43).</summary>
[TestClass]
public sealed class CodeRulesTests
{
private static readonly Actor Root = new(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null);
private static readonly DateOnly Day = new(2026, 11, 11);
[TestMethod]
public async Task Rules_StartFromTheSpecification_AndAreSavedInTheCompanySettings()
{
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
await using (app)
{
var codes = app.Services.GetRequiredService<CodeRuleService>();
var rules = await codes.RulesAsync(Root, company);
Assert.HasCount(CodeRuleService.Definitions.Count, rules);
Assert.AreEqual("C{seq:000000}", rules.Single(r => r.Key == "customers").Mask);
Assert.IsTrue(rules.Single(r => r.Key == "items").UniqueBarcode);
var refused = await Assert.ThrowsExactlyAsync<ValidationFailedException>(() =>
codes.SaveAsync(Root, company, [new CodeRule("customers", "CLI", true), new CodeRule("suppliers", "{categoria}{seq:000}", true)]));
CollectionAssert.AreEquivalent(new[] { "customers.Mask:" + CodeMask.SequenceRequired, "suppliers.Mask:" + CodeMask.CategoryNotAllowed }, refused.Errors.ToArray());
var saved = await codes.SaveAsync(Root, company, [new CodeRule("customers", "cl{seq:0000}", AllowManual: false)]);
Assert.AreEqual(new CodeRule("customers", "CL{seq:0000}", false), saved.Single(r => r.Key == "customers"));
Assert.AreEqual("F{seq:000000}", saved.Single(r => r.Key == "suppliers").Mask, "Tables left out keep their rule.");
Assert.AreEqual(CodeRuleService.ManualNotAllowed, CodeRuleService.CheckManual(saved[0], "MIO"));
Assert.IsNull(CodeRuleService.CheckManual(saved[0], " "));
await app.StopAsync();
}
}
[TestMethod]
public async Task Assign_GivesNumbersInOrder_SkipsCodesTaken_AndKeepsYearsAndCategoriesApart()
{
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
await using (app)
{
var codes = app.Services.GetRequiredService<CodeRuleService>();
var factory = app.Services.GetRequiredService<IUnitOfWorkFactory>();
var customers = await codes.RuleAsync(company, "customers");
var items = await codes.RuleAsync(company, "items");
var leads = await codes.RuleAsync(company, "leads");
var taken = new HashSet<string>(StringComparer.Ordinal) { "C000002" };
async Task<string> AssignAsync(CodeRule rule, DateOnly date, string? category = null, bool commit = true)
{
await using var uow = await factory.CreateAsync(DatabaseScope.Company(company));
await uow.BeginAsync();
var code = await CodeRuleService.AssignAsync(uow, rule, date, category, (c, _) => Task.FromResult(taken.Contains(c)));
if (commit)
{
await uow.CommitAsync();
}
return code;
}
Assert.AreEqual("C000001", await codes.PreviewAsync(Root, company, customers, Day, null));
Assert.AreEqual("C000001", await AssignAsync(customers, Day));
Assert.AreEqual("C000003", await AssignAsync(customers, Day), "C000002 was written by hand.");
Assert.AreEqual("C000004", await AssignAsync(customers, Day, commit: false));
Assert.AreEqual("C000004", await codes.PreviewAsync(Root, company, customers, Day, null), "A rolled back save gives its number back.");
Assert.AreEqual("VALV-0001", await AssignAsync(items, Day, "valv"));
Assert.AreEqual("PUMP-0001", await AssignAsync(items, Day, "PUMP"));
Assert.AreEqual("VALV-0002", await AssignAsync(items, Day, "VALV"));
var noCategory = await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => AssignAsync(items, Day));
Assert.AreEqual("Code:" + CodeRuleService.CategoryRequired, noCategory.Errors.Single());
Assert.AreEqual("L2026-0001", await AssignAsync(leads, Day));
Assert.AreEqual("L2027-0001", await AssignAsync(leads, Day.AddYears(1)));
Assert.AreEqual("L2026-0002", await AssignAsync(leads, Day));
// A mask changed later continues the same sequence: codes already given are never rewritten.
Assert.AreEqual("CL0004", await AssignAsync(customers with { Mask = "CL{seq:0000}" }, Day));
await app.StopAsync();
}
}
[TestMethod]
public async Task Assign_NeverGivesTheSameCodeToTwoSavesAtTheSameTime()
{
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
await using (app)
{
var factory = app.Services.GetRequiredService<IUnitOfWorkFactory>();
var rule = await app.Services.GetRequiredService<CodeRuleService>().RuleAsync(company, "suppliers");
var assigned = await Task.WhenAll(Enumerable.Range(0, 8).Select(async _ =>
{
await using var uow = await factory.CreateAsync(DatabaseScope.Company(company));
await uow.BeginAsync();
var code = await CodeRuleService.AssignAsync(uow, rule, Day, null, (_, _) => Task.FromResult(false));
await uow.CommitAsync();
return code;
}));
CollectionAssert.AreEquivalent(Enumerable.Range(1, 8).Select(n => "F" + n.ToString("D6", System.Globalization.CultureInfo.InvariantCulture)).ToArray(), assigned);
await app.StopAsync();
}
}
[TestMethod]
public async Task AutoFill_FindsPlacesBanksAndDates_AndRespectsTheOptions()
{
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
await using (app)
{
var services = app.Services;
var tables = services.GetRequiredService<TableService>();
var autoFill = services.GetRequiredService<AutoFillService>();
// The base data brings every municipality of the ISTAT list, without postal codes: the users add them.
var municipalities = await tables.ActiveAsync<Municipality>(Root, company);
Assert.HasCount(7894, municipalities);
Assert.IsEmpty(await autoFill.PlacesByPostalCodeAsync(Root, company, "10128"));
var turinRow = municipalities.Single(m => m.Code == "L219");
turinRow.PostalCodes = "10121-10156";
await tables.SaveAsync(Root, company, turinRow);
var pinerolo = municipalities.Single(m => m.Code == "G674");
pinerolo.PostalCodes = "10064";
await tables.SaveAsync(Root, company, pinerolo);
var turin = (await autoFill.PlacesByPostalCodeAsync(Root, company, "10128")).Single();
Assert.AreEqual(new PlaceSuggestion("L219", "Torino", "TO", "Piemonte", "10128"), turin);
Assert.AreEqual("10064", (await autoFill.PlacesByNameAsync(Root, company, "pinerolo")).Single().PostalCode);
Assert.IsTrue((await autoFill.PlacesByNameAsync(Root, company, "pin")).Count > 1);
Assert.IsEmpty(await autoFill.PlacesByPostalCodeAsync(Root, company, "1012"));
Assert.IsEmpty(await autoFill.PlacesByPostalCodeAsync(Root, company, "10157"));
var code = await autoFill.PersonalTaxCodeAsync(company, new PersonalTaxCodeData("Rossi", "Mario", new DateOnly(1980, 1, 1), PersonSex.Male, "L219"));
Assert.AreEqual("RSSMRA80A01L219", code![..15]);
// The bank is not in the directory yet: name and BIC come from an account of the company at the same bank.
var iban = "IT60X0542811101000000123456";
Assert.AreEqual(new BankInfo("05428", null, null, "11101"), await autoFill.BankFromIbanAsync(Root, company, iban));
await tables.SaveAsync(Root, company, new BankAccount { Code = "BPR", Description = "Conto ordinario", BankName = "Banca di prova", Bic = "BPROITMMXXX", Iban = "IT42L1234512345123456789012" });
await tables.SaveAsync(Root, company, new BankAccount { Code = "BP2", Description = "Altro conto", BankName = "Banca di prova", Bic = "BPROITMMXXX", Iban = "IT84S0542811101000000654321" });
Assert.AreEqual(new BankInfo("05428", "Banca di prova", "BPROITMMXXX", "11101"), await autoFill.BankFromIbanAsync(Root, company, iban));
Assert.IsNull(await autoFill.BankFromIbanAsync(Root, company, "DE89370400440532013000"));
// Friday 14 August 2026 + 1 day is Saturday 15th (also a holiday), then Sunday: the delivery moves to Monday 17th.
Assert.AreEqual(new DateOnly(2026, 8, 17), await autoFill.DeliveryDateAsync(company, new DateOnly(2026, 8, 14), 1));
Assert.IsTrue(await autoFill.IsOnAsync(company, AutoFillService.PostalCode));
Assert.IsFalse(await autoFill.IsOnAsync(company, AutoFillService.LastDocument));
var options = await autoFill.SaveOptionsAsync(Root, company, new Dictionary<string, bool> { [AutoFillService.PostalCode] = false, ["unknown"] = true });
Assert.IsFalse(options[AutoFillService.PostalCode]);
Assert.IsFalse(options.ContainsKey("unknown"));
Assert.IsFalse(await autoFill.IsOnAsync(company, AutoFillService.PostalCode));
await app.StopAsync();
}
}
[TestMethod]
[DataRow("10121-10156", "10128", true)]
[DataRow("10121-10156", "10157", false)]
[DataRow("10064", "10064", true)]
[DataRow("00118-00199, 00010", "00010", true)]
[DataRow(null, "00010", false)]
[DataRow("1012-1015", "10128", false)]
public void PostalCodeMatches_ReadsListsAndRanges(string? list, string code, bool expected)
{
Assert.AreEqual(expected, AutoFillService.PostalCodeMatches(list, code));
}
}