The municipalities now come with their postal codes, so the lookup from postal code works on a new company without loading anything. GeoNames (CC BY 4.0) lists places rather than municipalities: a postal code goes to a municipality only when the name and the province abbreviation match exactly one of them (the name alone within Sardinia, whose abbreviations changed), which covers 7,750 of 7,894 municipalities; the rest are mostly renamed or merged ones that users complete by hand. tools/Khaemhat.PlacesTool rebuilds both lists from the ISTAT sheet and the GeoNames file, framework only, so the yearly update is repeatable. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
179 lines
10 KiB
C#
179 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 with the GeoNames postal codes; the few missing
|
|
// ones are written by the users.
|
|
var municipalities = await tables.ActiveAsync<Municipality>(Root, company);
|
|
Assert.HasCount(7894, municipalities);
|
|
Assert.IsEmpty(await autoFill.PlacesByPostalCodeAsync(Root, company, "18038"));
|
|
var sanremo = municipalities.Single(m => m.Code == "I138");
|
|
sanremo.PostalCodes = "18038";
|
|
await tables.SaveAsync(Root, company, sanremo);
|
|
Assert.AreEqual("Sanremo", (await autoFill.PlacesByPostalCodeAsync(Root, company, "18038")).Single().Name);
|
|
|
|
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));
|
|
}
|
|
}
|