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; /// The screens of the company tables (mockups 052, 075, 076): every table has one, every field and text exists. [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(); 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().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()).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), typeof(Khaemhat.Application.Items.ItemService), typeof(Khaemhat.Application.Items.PriceListService) } .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)) || (c.StartsWith("items.", StringComparison.Ordinal) && !c.StartsWith("items.item", StringComparison.Ordinal) && !c.StartsWith("items.cost", StringComparison.Ordinal))) .Where(c => !c.EndsWith('.')) .Concat(Enum.GetValues().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.AreEqual(new SeedOptions(false, 1, null), all, "Base data of every active company."); Assert.IsTrue(SeedCommand.TryParse(["seed", "--company", "demo", "--base"], out var one, out _)); Assert.AreEqual("DEMO", one!.Company); Assert.IsTrue(SeedCommand.TryParse(["seed", "--demo", "--scale", "3", "--company", "demo"], out var demo, out _)); Assert.AreEqual(new SeedOptions(true, 3, "DEMO"), demo); Assert.IsFalse(SeedCommand.TryParse(["seed"], out _, out var usage)); Assert.IsNotNull(usage); Assert.IsFalse(SeedCommand.TryParse(["seed", "--base", "--scale", "2"], out _, out _), "The scale is for the demo data."); Assert.IsFalse(SeedCommand.TryParse(["seed", "--demo", "--scale", "0"], out _, out _)); Assert.IsFalse(SeedCommand.TryParse(["seed", "--demo", "--scale", "101"], out _, out _)); 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(); }