Files
Khaemhat/tests/Khaemhat.Web.Tests/Tables/TableScreensTests.cs
T
Alby96andClaude Opus 5.5 07555de700 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>
2026-11-11 23:33:02 +01:00

208 lines
11 KiB
C#

using System.Reflection;
using System.Text.RegularExpressions;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Tables;
using Khaemhat.Core.Tax;
using Khaemhat.Web.Components.Pages.Tables;
using Khaemhat.Web.Hosting;
using Khaemhat.Web.Tables;
using Khaemhat.Web.Tests.Shell;
namespace Khaemhat.Web.Tests.Tables;
/// <summary>The screens of the company tables (mockups 052, 075, 076): every table has one, every field and text exists.</summary>
[TestClass]
public sealed partial class TableScreensTests
{
[TestMethod]
public void EveryTableOfTheCatalog_HasOneScreen_WithItsEntity()
{
var catalog = new TableCatalog();
CollectionAssert.AreEquivalent(catalog.All.Select(t => t.Key).ToList(), TableScreens.All.Select(s => s.Key).ToList());
Assert.HasCount(TableScreens.All.Count, TableScreens.All.Select(s => s.Slug).Distinct().ToList(), "Unique addresses.");
foreach (var screen in TableScreens.All)
{
Assert.AreEqual(catalog.Find(screen.Key)!.EntityType, screen.Entity, screen.Key);
Assert.AreSame(screen, TableScreens.Find(screen.Slug.ToUpperInvariant()));
Assert.DoesNotContain(screen.Slug, TablesIndex.Pages.Select(p => p.Href).ToList(), "The special pages have their own address.");
}
}
[TestMethod]
public void EveryField_IsAWritablePropertyOfTheRightKind()
{
foreach (var (entity, field) in TableScreens.All.SelectMany(s => s.Fields.Select(f => (s.Entity, f)))
.Concat(ProfileLayout.Fields.Select(f => (typeof(CompanyProfile), f))))
{
var property = TableValues.PropertyOf(entity, field);
var type = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
var name = entity.Name + "." + field.Property;
Assert.IsTrue(property.CanWrite, name);
switch (field.Kind)
{
case TableFieldKind.Number:
Assert.IsTrue(type == typeof(decimal) || type == typeof(int) || type == typeof(long), name);
break;
case TableFieldKind.Bool:
Assert.AreEqual(typeof(bool), type, name);
break;
case TableFieldKind.Date:
Assert.AreEqual(typeof(DateOnly), type, name);
break;
case TableFieldKind.Choice:
Assert.IsTrue(type.IsEnum || (type == typeof(string) && field.Values is { Count: > 0 }), name);
break;
case TableFieldKind.Lookup:
Assert.IsTrue(field.Lookup is not null && typeof(CodedEntity).IsAssignableFrom(field.Lookup), name);
Assert.AreEqual(field.ByCode ? typeof(string) : typeof(long), type, name);
break;
case TableFieldKind.CodeList:
Assert.IsNotNull(field.CodeList, name);
Assert.AreEqual(typeof(string), type, name);
break;
default:
Assert.AreEqual(typeof(string), type, name);
break;
}
}
}
[TestMethod]
public void CodeLists_ComeFromTheItalianPack()
{
var pack = new Fiscal.Italy.ItalyFiscalPack();
foreach (var field in TableScreens.All.SelectMany(s => s.Fields).Concat(ProfileLayout.Fields).Where(f => f.Kind == TableFieldKind.CodeList))
{
Assert.IsNotEmpty(field.CodeList!(pack)!.Entries, field.Property);
}
}
[TestMethod]
public void EveryTextTheScreensBuild_Exists()
{
var keys = new List<string>();
keys.AddRange(TableScreens.All.SelectMany(s => new[] { s.TitleKey, s.HintKey }));
keys.AddRange(TableScreens.All.SelectMany(s => s.Fields).Concat(ProfileLayout.Fields).Select(f => f.LabelKey));
keys.AddRange(new[] { "Code", "Description", "Disabled", "CurrencyCode", "RateDate", "Rate", "Source" }.Select(p => "CompanyTables.Fields." + p));
keys.AddRange(Enum.GetValues<TableGroup>().Select(g => "CompanyTables.Groups." + g));
keys.AddRange(ProfileLayout.Tabs.Select(t => "CompanyTables.Profile.Tabs." + t.Id));
keys.AddRange(ProfileLayout.Tabs.SelectMany(t => t.Groups).Select(g => "CompanyTables.Profile.Groups." + g.Key));
keys.AddRange(TablesIndex.Pages.SelectMany(p => new[] { p.Title, p.Hint }));
foreach (var field in TableScreens.All.SelectMany(s => s.Fields).Concat(ProfileLayout.Fields))
{
keys.AddRange((field.Values ?? []).Select(v => TableOptions.ValueKey(field, v)));
}
var enums = TableScreens.All.SelectMany(s => s.Fields.Where(f => f.Kind == TableFieldKind.Choice).Select(f => TableValues.PropertyOf(s.Entity, f)))
.Concat(ProfileLayout.Fields.Where(f => f is { Kind: TableFieldKind.Choice, Values: null }).Select(f => TableValues.PropertyOf(typeof(CompanyProfile), f)))
.Select(p => Nullable.GetUnderlyingType(p.PropertyType) ?? p.PropertyType)
.Concat([typeof(FiscalYearStatus), typeof(FiscalPeriodStatus), typeof(VatPeriodicity)])
.Distinct();
keys.AddRange(enums.SelectMany(e => Enum.GetValues(e).Cast<Enum>()).Select(TableScreens.EnumKey));
keys.AddRange(new[] { ExchangeRateService.EcbSource, ExchangeRateService.ManualSource }.Select(s => "CompanyTables.Values.Source." + s));
Assert.IsEmpty(keys.Where(k => !ShellTests.Texts.Contains(k)).Distinct().ToList());
}
[TestMethod]
public void EveryErrorCode_HasAText()
{
var codes = new[] { typeof(TableService), typeof(TableCatalog), typeof(CompanyProfileService), typeof(FiscalYearService), typeof(PaymentTermService), typeof(ExchangeRateService), typeof(CodeRuleService), typeof(CodeMask) }
.SelectMany(t => t.GetFields(BindingFlags.Public | BindingFlags.Static).Where(f => f.IsLiteral && f.FieldType == typeof(string)))
.Select(f => (string)f.GetRawConstantValue()!)
.Where(c => c.StartsWith("tables.", StringComparison.Ordinal) || c.StartsWith("profile.", StringComparison.Ordinal) || c.StartsWith("fiscal.", StringComparison.Ordinal)
|| c.StartsWith("codes.", StringComparison.Ordinal))
.Where(c => !c.EndsWith('.'))
.Concat(Enum.GetValues<PeriodState>().Select(FiscalYearService.ErrorOf))
.ToList();
// The problems of the Italian pack are literals in its sources.
foreach (var file in Directory.EnumerateFiles(Path.Combine(Repository.Root, "src", "Khaemhat.Fiscal.Italy"), "*.cs", SearchOption.AllDirectories)
.Where(f => !Repository.IsBuildOutput(f)))
{
codes.AddRange(FiscalCode().Matches(File.ReadAllText(file)).Select(m => m.Groups[1].Value));
}
Assert.IsGreaterThan(40, codes.Count);
Assert.IsEmpty(codes.Where(c => !ShellTests.Texts.Contains(c)).Distinct().ToList());
}
[TestMethod]
public void Values_AreConvertedBetweenEditorsAndProperties()
{
var term = new PaymentTerm();
var method = TableValues.PropertyOf(typeof(PaymentTerm), new TableField(nameof(PaymentTerm.PaymentMethodId)));
TableValues.SetText(term, method, "42");
Assert.AreEqual(42L, term.PaymentMethodId);
Assert.AreEqual("42", TableValues.GetText(term, method));
TableValues.SetText(term, method, string.Empty);
Assert.IsNull(term.PaymentMethodId);
var numerator = new DocumentNumerator();
var kind = TableValues.PropertyOf(typeof(DocumentNumerator), new TableField(nameof(DocumentNumerator.Kind)));
TableValues.SetText(numerator, kind, "SalesInvoice");
Assert.AreEqual(NumeratorKind.SalesInvoice, numerator.Kind);
var year = TableValues.PropertyOf(typeof(DocumentNumerator), new TableField(nameof(DocumentNumerator.Year)));
TableValues.SetNumber(numerator, year, 2026.4m);
Assert.AreEqual(2026, numerator.Year);
TableValues.SetNumber(numerator, year, null);
Assert.AreEqual(0, numerator.Year);
var section = TableValues.PropertyOf(typeof(DocumentNumerator), new TableField(nameof(DocumentNumerator.Section)));
TableValues.SetText(numerator, section, " ");
Assert.IsNull(numerator.Section, "An empty optional text is null.");
var format = TableValues.PropertyOf(typeof(DocumentNumerator), new TableField(nameof(DocumentNumerator.Format)));
TableValues.SetText(numerator, format, null);
Assert.AreEqual(string.Empty, numerator.Format, "A required text is never null.");
Assert.AreEqual(("Iban", "tables.iban.invalid"), TableValues.SplitError("Iban:tables.iban.invalid"));
Assert.AreEqual(((string?)null, "fiscal.year.closed"), TableValues.SplitError("fiscal.year.closed"));
}
[TestMethod]
public void PaymentTermLines_MustAddUpToTheWhole()
{
Assert.IsEmpty(PaymentTermService.Validate([Line(30, 50m), Line(60, 50m)]));
Assert.AreEqual(PaymentTermService.LinesRequired, PaymentTermService.Validate([]).Single().Code);
Assert.AreEqual(PaymentTermService.PercentTotal, PaymentTermService.Validate([Line(30, 50m), Line(60, 40m)]).Single().Code);
Assert.AreEqual(PaymentTermService.DaysRange, PaymentTermService.Validate([Line(-1, 100m)]).Single().Code);
Assert.AreEqual(PaymentTermService.FixedDayRange, PaymentTermService.Validate([new PaymentTermLine { Days = 30, Percent = 100m, FixedDay = 32 }]).Single().Code);
static PaymentTermLine Line(int days, decimal percent) => new() { Days = days, Percent = percent };
}
[TestMethod]
public void Menu_LeadsToRealPages()
{
var area = Khaemhat.Web.Shell.MenuCatalog.FindArea("/tabelle")!;
Assert.IsNull(area.Milestone, "Delivered in M4.");
foreach (var child in area.Children)
{
var slug = child.Href[(TableScreens.BasePath.Length + 1)..];
Assert.IsTrue(TableScreens.Find(slug) is not null || TablesIndex.Pages.Any(p => p.Href == child.Href), child.Href);
Assert.IsTrue(ShellTests.Texts.Contains(child.Key), child.Key);
}
}
[TestMethod]
public void SeedCommand_ReadsItsArguments()
{
Assert.IsTrue(SeedCommand.Matches(["seed", "--base"]));
Assert.IsFalse(SeedCommand.Matches(["--urls", "http://localhost:5080"]));
Assert.IsTrue(SeedCommand.TryParse(["seed", "--base"], out var all, out _));
Assert.IsNull(all, "Every active company.");
Assert.IsTrue(SeedCommand.TryParse(["seed", "--company", "demo", "--base"], out var one, out _));
Assert.AreEqual("DEMO", one);
Assert.IsFalse(SeedCommand.TryParse(["seed"], out _, out var usage));
Assert.IsNotNull(usage);
Assert.IsFalse(SeedCommand.TryParse(["seed", "--demo"], out _, out _), "Demo data arrive with parties and items.");
Assert.IsFalse(SeedCommand.TryParse(["seed", "--base", "--company"], out _, out _));
Assert.IsFalse(SeedCommand.TryParse(["seed", "--base", "--other"], out _, out _));
}
[GeneratedRegex("\"(fiscal\\.[a-z][a-z.\\-]*[a-z])\"")]
private static partial Regex FiscalCode();
}