The pages of the Scadenzario area follow mockups 053-057: open items with aging, the collection and payment dialog, collections and payments of a period, remittances (new, file, presentation, credit, unpaid), SDD mandates, reminders with levels and history, bank reconciliation with rules, and the cash flow forecast. The dashboard shows the items due among the deadlines and the overdue receivables among the things to do. Texts are in Treasury.json; the menu lists the new pages and no longer marks the area as coming. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
301 lines
11 KiB
C#
301 lines
11 KiB
C#
using System.Text;
|
||
using System.Text.RegularExpressions;
|
||
using System.Reflection;
|
||
using Khaemhat.Application.Preferences;
|
||
using Khaemhat.Core.Accounting;
|
||
using Khaemhat.Core.Tax;
|
||
using Khaemhat.Web.Ledger;
|
||
using Khaemhat.Web.Shell;
|
||
|
||
namespace Khaemhat.Web.Tests.Shell;
|
||
|
||
/// <summary>
|
||
/// The rule of SPEC §1.9 and issue #33: components contain no literal interface texts, every text comes from
|
||
/// <c>Resources/it-IT/*.json</c>, and every key the code asks for exists.
|
||
/// </summary>
|
||
[TestClass]
|
||
public sealed partial class LocalizationRulesTests
|
||
{
|
||
// Words allowed as they are: the product name and the names of things that are not translated.
|
||
private static readonly HashSet<string> Allowed = new(StringComparer.Ordinal) { "Khaemhat" };
|
||
|
||
[TestMethod]
|
||
public void Components_ContainNoLiteralTexts()
|
||
{
|
||
var problems = new List<string>();
|
||
foreach (var file in ComponentFiles())
|
||
{
|
||
foreach (var text in LiteralTexts(File.ReadAllText(file)))
|
||
{
|
||
problems.Add(Path.GetRelativePath(Repository.Root, file) + ": " + text);
|
||
}
|
||
}
|
||
|
||
Assert.IsEmpty(problems, "Texts belong in Resources/it-IT/*.json:\n" + string.Join('\n', problems));
|
||
}
|
||
|
||
[TestMethod]
|
||
public void TheCheck_FindsLiteralTexts_AndLetsTheRestThrough()
|
||
{
|
||
const string page = """
|
||
@page "/x"
|
||
@inject Foo Bar
|
||
@* A comment with words is fine. *@
|
||
<h1>@T["Pages.X.Title"]</h1>
|
||
<p class="lead">Testo scritto a mano</p>
|
||
<button title="Chiudi" aria-label="@T["Common.Close"]">@T.Format("Pages.X.Count", items.Count(i => i > 0))</button>
|
||
<img alt="" src="x.svg" />
|
||
<span>@(a ? T["A"] : T["B"]) · @Model.Name</span>
|
||
<input placeholder="Cerca" />
|
||
@foreach (var item in Items.Where(i => i.Level > 2))
|
||
{
|
||
<li>@item.Name</li>
|
||
}
|
||
<span>× ● Khaemhat @Session.Company?.Code @if (n.Body is not null) {<br />}</span>
|
||
@code {
|
||
private string Text => "Un testo nel codice";
|
||
}
|
||
""";
|
||
|
||
var found = LiteralTexts(page).ToList();
|
||
|
||
CollectionAssert.AreEquivalent(new[] { "Testo scritto a mano", "title=\"Chiudi\"", "placeholder=\"Cerca\"" }, found);
|
||
}
|
||
|
||
[TestMethod]
|
||
public void EveryTextKeyInTheCode_Exists()
|
||
{
|
||
var missing = new List<string>();
|
||
// The web project, and the application one where the dashboard catalog and sources name their texts.
|
||
foreach (var file in new[] { "Khaemhat.Web", "Khaemhat.Application" }
|
||
.SelectMany(project => Directory.EnumerateFiles(Path.Combine(Repository.Root, "src", project), "*.*", SearchOption.AllDirectories))
|
||
.Where(f => (f.EndsWith(".razor", StringComparison.Ordinal) || f.EndsWith(".cs", StringComparison.Ordinal)) && !Repository.IsBuildOutput(f)))
|
||
{
|
||
foreach (Match match in KeyPattern().Matches(File.ReadAllText(file)))
|
||
{
|
||
var key = match.Groups[1].Value;
|
||
if (!key.EndsWith('.') && !ShellTests.Texts.Contains(key))
|
||
{
|
||
missing.Add(Path.GetFileName(file) + ": " + key);
|
||
}
|
||
}
|
||
}
|
||
|
||
Assert.IsEmpty(missing, string.Join('\n', missing));
|
||
}
|
||
|
||
[TestMethod]
|
||
public void KeysBuiltFromValues_Exist()
|
||
{
|
||
var keys = new List<string>();
|
||
keys.AddRange(Enum.GetValues<ThemeMode>().Select(v => "Pages.Profile.Theme." + v));
|
||
keys.AddRange(Enum.GetValues<Density>().Select(v => "Pages.Profile.Density." + v));
|
||
keys.AddRange(Enum.GetValues<StartPage>().Select(v => "Pages.Profile.Start." + v));
|
||
keys.AddRange(Enum.GetValues<ShortcutScope>().Select(v => "Pages.Profile.Shortcuts." + v));
|
||
keys.AddRange(UserPreferences.Accents.Select(a => "Pages.Profile.Accent." + a));
|
||
keys.AddRange(Enum.GetValues<ToastKind>().Select(v => "Pages.Catalog.Windows.Toast." + v));
|
||
|
||
Assert.IsEmpty(keys.Where(k => !ShellTests.Texts.Contains(k)).ToList(), string.Join(", ", keys.Where(k => !ShellTests.Texts.Contains(k))));
|
||
}
|
||
|
||
[TestMethod]
|
||
public void LedgerEnumsAndErrors_HaveTexts()
|
||
{
|
||
var keys = new List<string>();
|
||
foreach (var type in new[]
|
||
{
|
||
typeof(GlEntryStatus), typeof(GlEntrySource), typeof(RecurrenceFrequency), typeof(AccountNature), typeof(AccountType),
|
||
typeof(JournalArea), typeof(PostingRole), typeof(AccountSide), typeof(VatRegisterKind), typeof(VatSettlementStatus),
|
||
typeof(WithholdingStatus), typeof(VatAdvanceMethod), typeof(VatPeriodicity), typeof(TaxExigibility),
|
||
})
|
||
{
|
||
keys.AddRange(Enum.GetValues(type).Cast<Enum>().Select(LedgerScreens.EnumKey));
|
||
}
|
||
|
||
keys.AddRange(typeof(LedgerErrors).GetFields(BindingFlags.Public | BindingFlags.Static)
|
||
.Where(f => f.IsLiteral).Select(f => (string)f.GetRawConstantValue()!));
|
||
|
||
Assert.IsEmpty(keys.Where(k => !ShellTests.Texts.Contains(k)).ToList(), string.Join(", ", keys.Where(k => !ShellTests.Texts.Contains(k))));
|
||
}
|
||
|
||
[TestMethod]
|
||
public void TextFiles_AvoidCharactersGiteaFlagsAsAmbiguous()
|
||
{
|
||
var folder = Path.Combine(Repository.Root, "src", "Khaemhat.Web", "Resources");
|
||
foreach (var file in Directory.EnumerateFiles(folder, "*.json", SearchOption.AllDirectories))
|
||
{
|
||
var text = File.ReadAllText(file);
|
||
foreach (var c in new[] { '–', '×', '−', '›' })
|
||
{
|
||
Assert.DoesNotContain(c.ToString(), text, Path.GetFileName(file) + " contains U+" + ((int)c).ToString("X4", System.Globalization.CultureInfo.InvariantCulture));
|
||
}
|
||
}
|
||
}
|
||
|
||
internal static IEnumerable<string> ComponentFiles() =>
|
||
Directory.EnumerateFiles(Path.Combine(Repository.Root, "src", "Khaemhat.Web", "Components"), "*.razor", SearchOption.AllDirectories)
|
||
.Where(f => !Repository.IsBuildOutput(f));
|
||
|
||
/// <summary>The literal texts of a component: text between tags and text attributes, once code and expressions are removed.</summary>
|
||
/// <param name="razor">The component source.</param>
|
||
/// <returns>The texts found.</returns>
|
||
internal static IEnumerable<string> LiteralTexts(string razor)
|
||
{
|
||
var markup = CommentPattern().Replace(razor, string.Empty);
|
||
var code = markup.IndexOf("@code", StringComparison.Ordinal);
|
||
if (code >= 0)
|
||
{
|
||
markup = markup[..code];
|
||
}
|
||
|
||
var lines = markup.Split('\n').Select(l => CodeLinePattern().IsMatch(l) ? string.Empty : l);
|
||
markup = StripExpressions(string.Join('\n', lines));
|
||
|
||
foreach (Match attribute in AttributePattern().Matches(markup))
|
||
{
|
||
if (HasWords(attribute.Groups[2].Value))
|
||
{
|
||
yield return attribute.Groups[1].Value + "=\"" + attribute.Groups[2].Value + "\"";
|
||
}
|
||
}
|
||
|
||
foreach (Match node in TextNodePattern().Matches(markup))
|
||
{
|
||
var text = node.Groups[1].Value.Trim();
|
||
if (HasWords(text))
|
||
{
|
||
yield return text;
|
||
}
|
||
}
|
||
}
|
||
|
||
private static bool HasWords(string text)
|
||
{
|
||
var words = WordPattern().Matches(EntityPattern().Replace(text, " ")).Select(m => m.Value).Where(w => !Allowed.Contains(w));
|
||
return words.Any();
|
||
}
|
||
|
||
// Removes Razor expressions: @T["..."], @T.Format(...), @(...), @item.Name, @Model.Items[0].Text...
|
||
private static string StripExpressions(string text)
|
||
{
|
||
var result = new StringBuilder(text.Length);
|
||
var i = 0;
|
||
while (i < text.Length)
|
||
{
|
||
if (text[i] != '@' || i + 1 >= text.Length)
|
||
{
|
||
result.Append(text[i++]);
|
||
continue;
|
||
}
|
||
|
||
i++;
|
||
if (text[i] == '(')
|
||
{
|
||
i = SkipBalanced(text, i);
|
||
continue;
|
||
}
|
||
|
||
var start = i;
|
||
while (i < text.Length && (char.IsLetterOrDigit(text[i]) || text[i] == '_'))
|
||
{
|
||
i++;
|
||
while (i < text.Length && text[i] is '[' or '(')
|
||
{
|
||
i = SkipBalanced(text, i);
|
||
}
|
||
|
||
// Member access, also null-conditional (?.) and null-forgiving (!.).
|
||
if (i + 2 < text.Length && text[i] is '?' or '!' && text[i + 1] == '.' && char.IsLetter(text[i + 2]))
|
||
{
|
||
i += 2;
|
||
}
|
||
else if (i + 1 < text.Length && text[i] == '.' && char.IsLetter(text[i + 1]))
|
||
{
|
||
i++;
|
||
}
|
||
}
|
||
|
||
// @if (...) { ... } written inside a line of markup: the condition is code.
|
||
if (text.AsSpan(start, i - start) is "if" or "foreach" or "for" or "while" or "switch")
|
||
{
|
||
while (i < text.Length && text[i] == ' ')
|
||
{
|
||
i++;
|
||
}
|
||
|
||
if (i < text.Length && text[i] == '(')
|
||
{
|
||
i = SkipBalanced(text, i);
|
||
}
|
||
}
|
||
}
|
||
|
||
return result.ToString();
|
||
}
|
||
|
||
private static int SkipBalanced(string text, int start)
|
||
{
|
||
var depth = 0;
|
||
var quote = '\0';
|
||
for (var i = start; i < text.Length; i++)
|
||
{
|
||
var c = text[i];
|
||
if (quote != '\0')
|
||
{
|
||
if (c == '\\')
|
||
{
|
||
i++;
|
||
}
|
||
else if (c == quote)
|
||
{
|
||
quote = '\0';
|
||
}
|
||
|
||
continue;
|
||
}
|
||
|
||
switch (c)
|
||
{
|
||
case '"' or '\'':
|
||
quote = c;
|
||
break;
|
||
case '(' or '[' or '{':
|
||
depth++;
|
||
break;
|
||
case ')' or ']' or '}':
|
||
depth--;
|
||
if (depth == 0)
|
||
{
|
||
return i + 1;
|
||
}
|
||
|
||
break;
|
||
}
|
||
}
|
||
|
||
return text.Length;
|
||
}
|
||
|
||
[GeneratedRegex(@"@\*.*?\*@", RegexOptions.Singleline)]
|
||
private static partial Regex CommentPattern();
|
||
|
||
// Lines of C#: directives, control flow, braces, local declarations and assignments inside code blocks.
|
||
[GeneratedRegex(@"^\s*(@(page|inject|using|attribute|layout|implements|inherits|namespace|rendermode|typeparam|foreach|for|if|switch|while|else)\b|@\{|\{|\}|(else|case|default|break|var|if|foreach|return)\b|[a-z_][A-Za-z0-9_.]*\s*(=[^=>]|\+\+|--)|(string|int|bool|long)\??\s)")]
|
||
private static partial Regex CodeLinePattern();
|
||
|
||
[GeneratedRegex("\\b(title|placeholder|alt|aria-label|label)=\"([^\"]*)\"")]
|
||
private static partial Regex AttributePattern();
|
||
|
||
[GeneratedRegex(@">([^<>]+)<")]
|
||
private static partial Regex TextNodePattern();
|
||
|
||
[GeneratedRegex(@"\p{L}{2,}")]
|
||
private static partial Regex WordPattern();
|
||
|
||
[GeneratedRegex(@"&[a-zA-Z]+;|&#\d+;")]
|
||
private static partial Regex EntityPattern();
|
||
|
||
[GeneratedRegex("\"((?:Shell|Pages|Auth|Common|Ui|Dashboard|Parties|Items|ImportExport|Ledger)\\.[A-Za-z0-9_.]+)\"")]
|
||
private static partial Regex KeyPattern();
|
||
}
|