Files
Khaemhat/tests/Khaemhat.Web.Tests/Tables/TableScreensTests.cs
T
Alby96andClaude Opus 5.5 3401271483 feat: parties with radar, record, checks, VIES and demo data (#41)
Customers, suppliers, prospects and leads live in one parties archive
with a kind and a subject type (ADR 0029). A customer that also supplies
carries is_also_supplier, so it shows in both radars with one code.

- Three radars (/anagrafiche/clienti, /fornitori, /contatti) with search,
  quick filters and bulk disable/enable; the record has eight tabs
  (main data, addresses, contacts, terms, fiscal and SDI, banks, notes and
  attachments, history) on the MasterDataPage base.
- PartyService saves the whole record in one transaction, checks it with
  the fiscal pack (VAT number, tax code, recipient code, country), treats
  a duplicate VAT number or a consumer without tax code as warnings, fills
  the default recipient code, runs VIES after commit for EU companies, and
  converts prospects/leads (new customer code, old one kept as
  previous_code) and suppliers (become customers that also supply).
- Delete falls back to disable when the party is referenced.
- DemoPartiesSeeder adds 3 salespeople and 21 parties with fictitious but
  formally valid identifiers; SeedAsync now runs demo seeders when asked.
- Test host accepts service overrides so VIES can be stubbed.

Docs: ADR 0029, wiki Anagrafiche and demo data pages, regenerated data
model, CHANGELOG and STATUS.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 10:06:33 +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), typeof(Khaemhat.Application.Parties.PartyService) }
.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) || (c.StartsWith("parties.", StringComparison.Ordinal) && !c.StartsWith("parties.party", 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();
}