From d958e7372d06e6292aa88c42a105e065ecde1858 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Wed, 11 Nov 2026 18:11:16 +0100 Subject: [PATCH] feat: Kh component library, record pages and profile security (M3, part 2) Adds the building blocks every later screen uses, so modules are built from one set of components instead of ad hoc markup: - Form components (KhForm, KhTextBox, KhNumberBox, KhDateBox, KhSelect, KhCheck, KhSwitch, KhHotlink) with Italian number and date input, inline calculation (=10*3), field messages plus a summary that focuses the field, and service errors added by field name. - Display and window components (panels, tiles, badges, chips, money, tabs with Alt+1..9, steps, dialog, side drawer and DrawerService). - KhIconToolbar that keeps one line and moves less used commands into the "..." menu, KhDocHead, and the RecordPage/DocumentPage/MasterDataPage bases with standard commands, shortcuts and save/cancel/delete flow (#27, #29). - Development-only component catalog and sample document page. - Profile: personal data, password change that ends other sessions, TOTP enable/disable and recovery codes through ProfileService (#31). Refs #27 #29 #31 Co-Authored-By: Claude Opus 5.5 --- .../Security/AccountSecurity.cs | 29 ++ .../Security/ProfileService.cs | 270 +++++++++++ .../Components/Layout/MainLayout.razor | 1 + .../Pages/Dev/ComponentCatalog.razor | 315 +++++++++++++ .../Pages/Dev/SampleDocumentPage.razor | 194 ++++++++ .../Components/Pages/Profile.razor | 28 +- .../Pages/ProfileTabs/ProfileAccount.razor | 140 ++++++ .../Pages/ProfileTabs/ProfileSecurity.razor | 258 +++++++++++ src/Khaemhat.Web/Components/Ui/KhBadge.razor | 22 + src/Khaemhat.Web/Components/Ui/KhCheck.razor | 17 + src/Khaemhat.Web/Components/Ui/KhChip.razor | 57 +++ .../Components/Ui/KhContextAction.razor | 47 ++ .../Components/Ui/KhDateBox.razor | 114 +++++ src/Khaemhat.Web/Components/Ui/KhDialog.razor | 82 ++++ .../Components/Ui/KhDocHead.razor | 131 ++++++ src/Khaemhat.Web/Components/Ui/KhDrawer.razor | 78 ++++ .../Components/Ui/KhDrawerHost.razor | 20 + src/Khaemhat.Web/Components/Ui/KhField.razor | 57 +++ .../Components/Ui/KhFieldGroup.razor | 37 ++ src/Khaemhat.Web/Components/Ui/KhForm.razor | 146 ++++++ .../Components/Ui/KhHotlink.razor | 300 +++++++++++++ .../Components/Ui/KhIconButton.razor | 73 +++ .../Components/Ui/KhIconToolbar.razor | 203 +++++++++ src/Khaemhat.Web/Components/Ui/KhMoney.razor | 20 + .../Components/Ui/KhNumberBox.razor | 81 ++++ src/Khaemhat.Web/Components/Ui/KhPanel.razor | 53 +++ .../Components/Ui/KhRecordLayout.razor | 24 + src/Khaemhat.Web/Components/Ui/KhSelect.razor | 49 ++ src/Khaemhat.Web/Components/Ui/KhSteps.razor | 62 +++ src/Khaemhat.Web/Components/Ui/KhStrip.razor | 32 ++ src/Khaemhat.Web/Components/Ui/KhSwitch.razor | 25 ++ src/Khaemhat.Web/Components/Ui/KhTabs.razor | 108 +++++ .../Components/Ui/KhTextArea.razor | 24 + .../Components/Ui/KhTextBox.razor | 28 ++ src/Khaemhat.Web/Components/Ui/KhTile.razor | 60 +++ src/Khaemhat.Web/Components/Ui/KhVSteps.razor | 16 + src/Khaemhat.Web/Components/_Imports.razor | 3 +- src/Khaemhat.Web/Hosting/KhaemhatServices.cs | 2 + src/Khaemhat.Web/Resources/it-IT/Auth.json | 3 + src/Khaemhat.Web/Resources/it-IT/Pages.json | 181 +++++++- src/Khaemhat.Web/Resources/it-IT/Shell.json | 3 +- src/Khaemhat.Web/Resources/it-IT/Ui.json | 67 +++ src/Khaemhat.Web/Shell/Feedback.cs | 50 +++ src/Khaemhat.Web/Shell/KeyboardShortcuts.cs | 39 +- src/Khaemhat.Web/Shell/ShellSession.cs | 11 + src/Khaemhat.Web/Shell/TabService.cs | 3 + src/Khaemhat.Web/Ui/CatalogSamples.cs | 96 ++++ src/Khaemhat.Web/Ui/ItalianInput.cs | 293 ++++++++++++ src/Khaemhat.Web/Ui/KhForms.cs | 311 +++++++++++++ src/Khaemhat.Web/Ui/KhModels.cs | 104 +++++ src/Khaemhat.Web/Ui/RecordPages.cs | 419 ++++++++++++++++++ src/Khaemhat.Web/wwwroot/app.css | 6 + src/Khaemhat.Web/wwwroot/css/interactive.css | 78 ++++ src/Khaemhat.Web/wwwroot/js/khaemhat.js | 105 ++++- .../Shell/LocalizationRulesTests.cs | 3 +- .../Shell/ProfileServiceTests.cs | 97 ++++ .../Ui/ItalianInputTests.cs | 186 ++++++++ 57 files changed, 5249 insertions(+), 12 deletions(-) create mode 100644 src/Khaemhat.Application/Security/ProfileService.cs create mode 100644 src/Khaemhat.Web/Components/Pages/Dev/ComponentCatalog.razor create mode 100644 src/Khaemhat.Web/Components/Pages/Dev/SampleDocumentPage.razor create mode 100644 src/Khaemhat.Web/Components/Pages/ProfileTabs/ProfileAccount.razor create mode 100644 src/Khaemhat.Web/Components/Pages/ProfileTabs/ProfileSecurity.razor create mode 100644 src/Khaemhat.Web/Components/Ui/KhBadge.razor create mode 100644 src/Khaemhat.Web/Components/Ui/KhCheck.razor create mode 100644 src/Khaemhat.Web/Components/Ui/KhChip.razor create mode 100644 src/Khaemhat.Web/Components/Ui/KhContextAction.razor create mode 100644 src/Khaemhat.Web/Components/Ui/KhDateBox.razor create mode 100644 src/Khaemhat.Web/Components/Ui/KhDialog.razor create mode 100644 src/Khaemhat.Web/Components/Ui/KhDocHead.razor create mode 100644 src/Khaemhat.Web/Components/Ui/KhDrawer.razor create mode 100644 src/Khaemhat.Web/Components/Ui/KhDrawerHost.razor create mode 100644 src/Khaemhat.Web/Components/Ui/KhField.razor create mode 100644 src/Khaemhat.Web/Components/Ui/KhFieldGroup.razor create mode 100644 src/Khaemhat.Web/Components/Ui/KhForm.razor create mode 100644 src/Khaemhat.Web/Components/Ui/KhHotlink.razor create mode 100644 src/Khaemhat.Web/Components/Ui/KhIconButton.razor create mode 100644 src/Khaemhat.Web/Components/Ui/KhIconToolbar.razor create mode 100644 src/Khaemhat.Web/Components/Ui/KhMoney.razor create mode 100644 src/Khaemhat.Web/Components/Ui/KhNumberBox.razor create mode 100644 src/Khaemhat.Web/Components/Ui/KhPanel.razor create mode 100644 src/Khaemhat.Web/Components/Ui/KhRecordLayout.razor create mode 100644 src/Khaemhat.Web/Components/Ui/KhSelect.razor create mode 100644 src/Khaemhat.Web/Components/Ui/KhSteps.razor create mode 100644 src/Khaemhat.Web/Components/Ui/KhStrip.razor create mode 100644 src/Khaemhat.Web/Components/Ui/KhSwitch.razor create mode 100644 src/Khaemhat.Web/Components/Ui/KhTabs.razor create mode 100644 src/Khaemhat.Web/Components/Ui/KhTextArea.razor create mode 100644 src/Khaemhat.Web/Components/Ui/KhTextBox.razor create mode 100644 src/Khaemhat.Web/Components/Ui/KhTile.razor create mode 100644 src/Khaemhat.Web/Components/Ui/KhVSteps.razor create mode 100644 src/Khaemhat.Web/Resources/it-IT/Ui.json create mode 100644 src/Khaemhat.Web/Ui/CatalogSamples.cs create mode 100644 src/Khaemhat.Web/Ui/ItalianInput.cs create mode 100644 src/Khaemhat.Web/Ui/KhForms.cs create mode 100644 src/Khaemhat.Web/Ui/KhModels.cs create mode 100644 src/Khaemhat.Web/Ui/RecordPages.cs create mode 100644 tests/Khaemhat.Web.Tests/Shell/ProfileServiceTests.cs create mode 100644 tests/Khaemhat.Web.Tests/Ui/ItalianInputTests.cs diff --git a/src/Khaemhat.Application/Security/AccountSecurity.cs b/src/Khaemhat.Application/Security/AccountSecurity.cs index 3274c80..23fb2bf 100644 --- a/src/Khaemhat.Application/Security/AccountSecurity.cs +++ b/src/Khaemhat.Application/Security/AccountSecurity.cs @@ -237,11 +237,40 @@ public sealed class AccountSecurity } account.TotpEnabled = true; + return NewRecoveryCodes(account); + } + + /// Replaces the recovery codes with ten new ones; the old ones stop working. + /// The account. + /// The new codes, to show once. + public static IReadOnlyList NewRecoveryCodes(IAccount account) + { + ArgumentNullException.ThrowIfNull(account); var codes = Enumerable.Range(0, 10).Select(_ => SecureTokenGenerator.CreateReadableCode(2)).ToList(); account.TotpRecoveryCodes = JsonSerializer.Serialize(codes.Select(c => SecureTokenGenerator.Hash(c)).ToList()); return codes; } + /// How many recovery codes are still unused. + /// The account. + /// The number of codes left. + public static int RecoveryCodesLeft(IAccount account) + { + ArgumentNullException.ThrowIfNull(account); + return account.TotpEnabled ? Deserialize(account.TotpRecoveryCodes).Count : 0; + } + + /// Checks the current password without counting failures (profile changes that ask for it again). + /// The account. + /// The password typed. + /// Whether it is right. + public static bool IsCurrentPassword(IAccount account, string password) + { + ArgumentNullException.ThrowIfNull(account); + ArgumentNullException.ThrowIfNull(password); + return account.PasswordHash is not null && PasswordHasher.Verify(account.PasswordHash, password) != PasswordVerification.Failed; + } + /// Checks a TOTP code at sign-in. A code is never accepted twice. /// The account. /// The code. diff --git a/src/Khaemhat.Application/Security/ProfileService.cs b/src/Khaemhat.Application/Security/ProfileService.cs new file mode 100644 index 0000000..234fc50 --- /dev/null +++ b/src/Khaemhat.Application/Security/ProfileService.cs @@ -0,0 +1,270 @@ +using System.Net.Mail; +using Khaemhat.Application.Audit; +using Khaemhat.Core.Security; +using Khaemhat.Infrastructure.Security; + +namespace Khaemhat.Application.Security; + +/// What the profile page shows about the signed-in account (SPEC §12, mockup 008). +/// The sign-in name. +/// The name shown in the interface. +/// The e-mail address. +/// Whether it is an instance account (super user or administrator). +/// Whether the two-step verification is active. +/// Whether the two-step verification is mandatory, so it cannot be turned off. +/// Unused recovery codes. +/// Whether the account signs in with a password (technical users do not). +/// When the password was last set (UTC). +/// The last successful sign-in (UTC). +public sealed record ProfileInfo( + string UserName, + string DisplayName, + string? Email, + bool IsInstanceAccount, + bool TotpEnabled, + bool TotpRequired, + int RecoveryCodesLeft, + bool HasPassword, + DateTime? PasswordChangedAt, + DateTime? LastLoginAt); + +/// +/// The changes users make to their own account from the profile (SPEC §12, issue #31): name and e-mail, password, +/// two-step verification and recovery codes. Unlike it works from the session owner, not +/// from the cookie, because the profile runs in the interactive circuit where the cookie cannot be read. Every change is +/// recorded in sys_security_audit; a password change closes the other sessions of the account. +/// +/// Instance accounts. +/// Company users. +/// Credential rules. +/// Sessions. +/// The security audit. +public sealed class ProfileService( + SystemUserService systemUsers, + UserService companyUsers, + AccountSecurity security, + SessionStore sessions, + ISecurityAuditLog audit) +{ + /// The longest display name accepted. + public const int DisplayNameMaxLength = 100; + + /// The display name is empty or too long. + public const string DisplayNameInvalid = "display_name_invalid"; + + /// The e-mail address is not valid. + public const string EmailInvalid = "email_invalid"; + + /// The two-step verification is mandatory for the account and cannot be turned off. + public const string TotpRequiredError = "totp_required"; + + /// Reads the account of a session owner. + /// The session owner. + /// Cancellation. + /// The profile, or when the account no longer exists or is disabled. + public async Task GetAsync(SessionOwner owner, CancellationToken cancellationToken = default) + { + var account = await LoadAsync(owner, cancellationToken).ConfigureAwait(false); + return account is null ? null : InfoOf(account, owner); + } + + /// Changes name and e-mail. + /// The session owner. + /// The new name. + /// The new e-mail, or empty to remove it. + /// Cancellation. + /// The error codes; empty when saved. + public async Task> UpdateAsync(SessionOwner owner, string? displayName, string? email, CancellationToken cancellationToken = default) + { + var name = displayName?.Trim() ?? string.Empty; + var mail = string.IsNullOrWhiteSpace(email) ? null : email.Trim(); + var errors = new List(); + if (name.Length is 0 or > DisplayNameMaxLength) + { + errors.Add(DisplayNameInvalid); + } + + if (mail is not null && !IsEmail(mail)) + { + errors.Add(EmailInvalid); + } + + if (errors.Count > 0) + { + return errors; + } + + var account = await RequireAsync(owner, cancellationToken).ConfigureAwait(false); + account.DisplayName = name; + account.Email = mail; + await SaveAsync(account, owner, cancellationToken).ConfigureAwait(false); + await AuditAsync("user.profile-updated", account, owner, cancellationToken).ConfigureAwait(false); + return []; + } + + /// Changes the password, checking the current one, and closes every other session of the account. + /// The session owner. + /// The session that stays open. + /// The current password. + /// The new password. + /// Cancellation. + /// The error codes (); empty when changed. + public async Task> ChangePasswordAsync( + SessionOwner owner, long? currentSessionId, string currentPassword, string newPassword, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(currentPassword); + ArgumentNullException.ThrowIfNull(newPassword); + var account = await RequireAsync(owner, cancellationToken).ConfigureAwait(false); + if (!AccountSecurity.IsCurrentPassword(account, currentPassword)) + { + await AuditAsync("user.password-change-refused", account, owner, cancellationToken).ConfigureAwait(false); + return [SecurityErrors.CurrentPasswordWrong]; + } + + var errors = security.ChangePassword(account, newPassword); + if (errors.Count > 0) + { + return errors; + } + + await SaveAsync(account, owner, cancellationToken).ConfigureAwait(false); + await sessions.RevokeAllAsync(owner, "password_changed", currentSessionId, cancellationToken).ConfigureAwait(false); + await AuditAsync("user.password-changed", account, owner, cancellationToken).ConfigureAwait(false); + return []; + } + + /// Starts turning on the two-step verification; reloading the page shows the same secret. + /// The session owner. + /// The company of the session, shown in the label of the authenticator app. + /// Cancellation. + /// The secret to show, or when the verification is already active. + public async Task BeginTotpSetupAsync(SessionOwner owner, string? companyCode, CancellationToken cancellationToken = default) + { + var account = await RequireAsync(owner, cancellationToken).ConfigureAwait(false); + if (account.TotpEnabled) + { + return null; + } + + var secret = security.PendingTotpSecret(account); + if (secret is null) + { + secret = security.BeginTotpSetup(account); + await SaveAsync(account, owner, cancellationToken).ConfigureAwait(false); + } + + var label = companyCode is null ? account.UserName : account.UserName + "@" + companyCode; + return new TotpSetup(secret, TotpGenerator.ProvisioningUri(secret, label)); + } + + /// Completes turning on the two-step verification with the first code from the app. + /// The session owner. + /// The code. + /// Cancellation. + /// The ten recovery codes to show once, or when the code is wrong. + public async Task?> ConfirmTotpSetupAsync(SessionOwner owner, string code, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(code); + var account = await RequireAsync(owner, cancellationToken).ConfigureAwait(false); + if (account.TotpEnabled) + { + return null; + } + + var codes = security.ConfirmTotpSetup(account, code.Trim()); + if (codes is null) + { + return null; + } + + await SaveAsync(account, owner, cancellationToken).ConfigureAwait(false); + await AuditAsync("user.totp-enabled", account, owner, cancellationToken).ConfigureAwait(false); + return codes; + } + + /// Replaces the recovery codes, asking the password again. + /// The session owner. + /// The current password. + /// Cancellation. + /// The new codes, or when the password is wrong or the verification is off. + public async Task?> RenewRecoveryCodesAsync(SessionOwner owner, string password, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(password); + var account = await RequireAsync(owner, cancellationToken).ConfigureAwait(false); + if (!account.TotpEnabled || !AccountSecurity.IsCurrentPassword(account, password)) + { + return null; + } + + var codes = AccountSecurity.NewRecoveryCodes(account); + await SaveAsync(account, owner, cancellationToken).ConfigureAwait(false); + await AuditAsync("user.recovery-codes-renewed", account, owner, cancellationToken).ConfigureAwait(false); + return codes; + } + + /// Turns the two-step verification off, asking the password again; refused when it is mandatory. + /// The session owner. + /// The current password. + /// Cancellation. + /// The error codes; empty when turned off. + public async Task> DisableTotpAsync(SessionOwner owner, string password, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(password); + var account = await RequireAsync(owner, cancellationToken).ConfigureAwait(false); + if (IsTotpRequired(account, owner)) + { + return [TotpRequiredError]; + } + + if (!AccountSecurity.IsCurrentPassword(account, password)) + { + return [SecurityErrors.CurrentPasswordWrong]; + } + + AccountSecurity.ResetTotp(account); + await SaveAsync(account, owner, cancellationToken).ConfigureAwait(false); + await AuditAsync("user.totp-disabled", account, owner, cancellationToken).ConfigureAwait(false); + return []; + } + + private static bool IsEmail(string value) => + value.Length <= 254 && MailAddress.TryCreate(value, out var address) && address.Address == value && value.Contains('.', StringComparison.Ordinal); + + private bool IsTotpRequired(IAccount account, SessionOwner owner) => + owner.IsInstanceAccount || account is CompanyUser { TotpRequired: true } || security.Options.TotpRequiredForUsers; + + private ProfileInfo InfoOf(IAccount account, SessionOwner owner) => new( + account.UserName, + account.DisplayName, + account.Email, + owner.IsInstanceAccount, + account.TotpEnabled, + IsTotpRequired(account, owner), + AccountSecurity.RecoveryCodesLeft(account), + account.PasswordHash is not null, + account.PasswordChangedAt, + account.LastLoginAt); + + private async Task LoadAsync(SessionOwner owner, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(owner); + IAccount? account = owner.IsInstanceAccount + ? await systemUsers.GetAsync(owner.UserId, cancellationToken).ConfigureAwait(false) + : await companyUsers.GetAsync(owner.CompanyDatabase!, owner.UserId, cancellationToken).ConfigureAwait(false); + return account is { IsActive: true } ? account : null; + } + + private async Task RequireAsync(SessionOwner owner, CancellationToken cancellationToken) => + await LoadAsync(owner, cancellationToken).ConfigureAwait(false) + ?? throw new AccessDeniedException(SecurityErrors.InvalidCredentials, "The account no longer exists or is disabled."); + + private Task SaveAsync(IAccount account, SessionOwner owner, CancellationToken cancellationToken) => account switch + { + SystemUser system => systemUsers.SaveAsync(system, cancellationToken), + CompanyUser user => companyUsers.SaveAsync(owner.CompanyDatabase!, user, cancellationToken), + _ => throw new InvalidOperationException("Unknown account type."), + }; + + private Task AuditAsync(string action, IAccount account, SessionOwner owner, CancellationToken cancellationToken) => + audit.WriteAsync(new SecurityEvent(action, account.UserName, owner.CompanyDatabase), cancellationToken); +} diff --git a/src/Khaemhat.Web/Components/Layout/MainLayout.razor b/src/Khaemhat.Web/Components/Layout/MainLayout.razor index 68b4d53..3e8a836 100644 --- a/src/Khaemhat.Web/Components/Layout/MainLayout.razor +++ b/src/Khaemhat.Web/Components/Layout/MainLayout.razor @@ -56,6 +56,7 @@ +
@T["Shell.Error.Unexpected"] diff --git a/src/Khaemhat.Web/Components/Pages/Dev/ComponentCatalog.razor b/src/Khaemhat.Web/Components/Pages/Dev/ComponentCatalog.razor new file mode 100644 index 0000000..500424e --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Dev/ComponentCatalog.razor @@ -0,0 +1,315 @@ +@page "/sviluppo/componenti" +@attribute [Authorize] +@inject IWebHostEnvironment Environment +@inject ToastService Toasts +@inject DialogService Dialogs +@inject DrawerService Drawers +@inject TimeProvider Clock + +@* The catalog of the Kh components with all their states (issue #27): development only. *@ + + +@if (!Environment.IsDevelopment()) +{ +
+

@T["Pages.Catalog.DevOnly"]

+ @T["Common.BackHome"] +
+} +else +{ +
+
+

@T["Pages.Catalog.Title"]

+
@T["Pages.Catalog.Subtitle"]
+
+
+ @T["Pages.Catalog.OpenDocument"] +
+ + + + @switch (_section) + { + case "campi": + + + + + + + + + + + + + + + + +
+
@T["Pages.Catalog.Fields.States"]
+
+ + + + +
+
+
+ break; + + case "pannelli": +
+
+ + @T["Pages.Catalog.Panels.RevenueDetail"] + + + + +
+ + +
+ @T["Pages.Catalog.Panels.Draft"] + @T["Pages.Catalog.Panels.Sent"] + @T["Pages.Catalog.Panels.Paid"] + @T["Pages.Catalog.Panels.Expiring"] + @T["Pages.Catalog.Panels.Overdue"] + @T["Pages.Catalog.Panels.Issued"] +
+
+ + + + + @if (_filter) + { + + } +
+
+ +
+
+
+ break; + + case "navigazione": +
+ + +
@T.Format("Pages.Catalog.Navigation.TabShown", DemoTabs.First(t => t.Id == _demoTab).Text)
+
+ + +
+ +
+ + +
+
+
+
+ break; + + case "finestre": +
+ +
+ + + + +
+
+ @foreach (var kind in Enum.GetValues()) + { + + } +
+
+
+ + +

@T["Pages.Catalog.Windows.DialogText"]

+ + + +
+
+ + +
+
+ +

@T["Pages.Catalog.Windows.DrawerText"]

+ +
+ break; + + case "toolbar": +
+

@T["Pages.Catalog.Toolbar.Intro"]

+
+ +
+ + + @T["Pages.Catalog.Fields.Date"] @(_document.Date is { } d ? T.Date(d) : null) + @T["Pages.Catalog.Head.Section"] A + + @T["Pages.Catalog.Panels.Draft"] + + + + + + +
+ break; + } +} + +@code { + private readonly KhValidation _validation = new(); + private SampleDocument _document = default!; + private KhForm? _form; + private string _section = "campi"; + private string _demoTab = "righe"; + private string? _kind; + private string? _email; + private string? _dialogText; + private decimal? _amount; + private bool _split; + private bool _stamp = true; + private bool _readOnly; + private bool _filter = true; + private bool _dialog; + private bool _drawer; + private int _step = 1; + + private IReadOnlyList Sections => + [ + new("campi", "edit", T["Pages.Catalog.Sections.Fields"]), + new("pannelli", "layers", T["Pages.Catalog.Sections.Panels"]), + new("navigazione", "columns", T["Pages.Catalog.Sections.Navigation"]), + new("finestre", "layout", T["Pages.Catalog.Sections.Windows"]), + new("toolbar", "settings", T["Pages.Catalog.Sections.Toolbar"]), + ]; + + private IReadOnlyList> Kinds => + [ + new("TD01", T["Pages.Catalog.Fields.KindInvoice"]), + new("TD04", T["Pages.Catalog.Fields.KindCredit"]), + new("TD24", T["Pages.Catalog.Fields.KindDeferred"]), + ]; + + private IReadOnlyList Stats => + [ + new(T["Pages.Catalog.Panels.Documents"], "128"), + new(T["Pages.Catalog.Panels.Taxable"], T.Money(104_000m)), + new(T["Pages.Catalog.Panels.Collected"], T.Money(96_120m), KhTone.Ok), + new(T["Pages.Catalog.Panels.Overdue"], T.Money(4_870.55m), KhTone.Error), + ]; + + private IReadOnlyList DemoTabs => + [ + new("righe", "list", T["Ui.Record.Tabs.Lines"], 3), + new("testata", "file", T["Ui.Record.Tabs.Header"]), + new("allegati", "paperclip", T["Ui.Record.Tabs.Attachments"], 2), + new("storico", "history", T["Ui.Record.Tabs.History"]), + ]; + + private IReadOnlyList Steps => + [ + new(T["Pages.Catalog.Navigation.Step1"], T["Pages.Catalog.Navigation.Step1Detail"]), + new(T["Pages.Catalog.Navigation.Step2"], T["Pages.Catalog.Navigation.Step2Detail"]), + new(T["Pages.Catalog.Navigation.Step3"], T["Pages.Catalog.Navigation.Step3Detail"]), + ]; + + private IReadOnlyList PartyLines => [T["Pages.Catalog.Head.Address"], T["Pages.Catalog.Head.Vat"]]; + + private IReadOnlyList SubValues => + [ + new(T["Pages.Catalog.Panels.Taxable"], T.Money(_document.Taxable)), + new(T["Pages.Catalog.Head.VatAmount"], T.Money(_document.Vat)), + new(T["Pages.Catalog.Head.Stamp"], T.Money(2m)), + ]; + + private IReadOnlyList DemoToolbar => + [ + Item("new", "plus", "Ui.Toolbar.New", "Ctrl+N") with { Priority = 0 }, + Item("save", "save", "Ui.Toolbar.Save", "Ctrl+S") with { Primary = true, Priority = 0 }, + Item("cancel", "undo", "Ui.Toolbar.Cancel", null) with { Priority = 2 }, + Item("delete", "trash", "Ui.Toolbar.Delete", "Ctrl+Delete") with { Danger = true, Priority = 3 }, + Item("copy", "copy", "Ui.Toolbar.Duplicate", null) with { Group = 1, Priority = 4 }, + Item("print", "printer", "Ui.Toolbar.Print", "Ctrl+P") with { Group = 1, Priority = 4 }, + Item("mail", "mail", "Ui.Toolbar.Email", null) with { Group = 1, Priority = 5 }, + Item("export", "download", "Ui.Toolbar.Export", null) with { Group = 1, Priority = 5 }, + Item("attachments", "paperclip", "Ui.Toolbar.Attachments", null) with { Group = 2, Count = 2, Priority = 5 }, + Item("history", "history", "Ui.Toolbar.History", null) with { Group = 2, Priority = 6 }, + Item("links", "link", "Ui.Toolbar.Links", null) with { Group = 2, Count = 1, Priority = 6 }, + Item("issue", "send", "Pages.Catalog.Toolbar.Issue", null) with { Kind = ToolbarKind.Action, Primary = true, Priority = 1 }, + Item("xml", "file-check", "Pages.Catalog.Toolbar.Xml", null) with { Kind = ToolbarKind.Action, Priority = 3 }, + Item("post", "book", "Pages.Catalog.Toolbar.Post", null) with { Kind = ToolbarKind.Action, Tone = KhTone.Ok, Priority = 3 }, + Item("ddt", "truck", "Pages.Catalog.Toolbar.Ddt", null) with { Kind = ToolbarKind.Action, Priority = 4 }, + Item("final", "lock", "Pages.Catalog.Toolbar.Final", null) with { Kind = ToolbarKind.Action, Priority = 4 }, + Item("radar", "radar", "Ui.Toolbar.Radar", "F9") with { End = true, Priority = 6 }, + Item("previous", "chevron-up", "Ui.Toolbar.Previous", "Ctrl+ArrowUp") with { End = true, Priority = 7 }, + Item("next", "chevron-down", "Ui.Toolbar.Next", "Ctrl+ArrowDown") with { End = true, Priority = 7 }, + Item("settings", "settings", "Pages.Catalog.Toolbar.Settings", null) with { Kind = ToolbarKind.Menu }, + ]; + + /// + protected override void OnInitialized() => + _document = CatalogSamples.Document(DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(Clock.GetUtcNow(), TimeZoneInfo.Local).DateTime)); + + private ToolbarItem Item(string id, string icon, string key, string? shortcut) => + new(id, icon, T[key]) { Shortcut = shortcut, OnClick = () => Clicked(key) }; + + private Task Clicked(string key) + { + Toasts.Show(ToastKind.Info, T.Format("Pages.Catalog.Toolbar.Clicked", T[key])); + return Task.CompletedTask; + } + + private string? EmailRule(string? value) => + string.IsNullOrEmpty(value) || value.Contains('@', StringComparison.Ordinal) ? null : T["Auth.Errors.email_invalid"]; + + private void OnValid() => Toasts.Show(ToastKind.Success, T["Pages.Catalog.Fields.Valid"]); + + private void ServerError() => _validation.Add("number", T["Pages.Catalog.Fields.NumberTaken"]); + + private void Radar(string text) => Toasts.Show(ToastKind.Info, T.Format("Pages.Catalog.Fields.RadarOpened", text)); + + private void OpenParty(SampleParty party) => Toasts.Show(ToastKind.Info, T.Format("Pages.Catalog.Fields.PartyOpened", party.Name)); + + private void CreateParty(string text) + { + _document.Party = new SampleParty("C9999", text); + Toasts.Show(ToastKind.Success, T.Format("Pages.Catalog.Fields.PartyCreated", text)); + } + + private Task ServiceDrawerAsync() => Drawers.ShowAsync(new DrawerRequest( + T["Pages.Catalog.Windows.DrawerService"], "sidebar", + @

@T["Pages.Catalog.Windows.DrawerServiceText"]

, + @)); + + private async Task ConfirmAsync() + { + var yes = await Dialogs.ConfirmAsync(new(T["Ui.Record.DeleteTitle"], T["Ui.Record.DeleteText"], T["Ui.Toolbar.Delete"], T["Common.Cancel"], Danger: true)); + Toasts.Show(yes ? ToastKind.Warning : ToastKind.Info, T[yes ? "Pages.Catalog.Windows.Confirmed" : "Pages.Catalog.Windows.Cancelled"]); + } + + private static string KindKey(ToastKind kind) => "Pages.Catalog.Windows.Toast." + kind; + + private void ShowToast(ToastKind kind) => Toasts.Show(kind, T[KindKey(kind)], T["Pages.Catalog.Windows.ToastText"]); +} diff --git a/src/Khaemhat.Web/Components/Pages/Dev/SampleDocumentPage.razor b/src/Khaemhat.Web/Components/Pages/Dev/SampleDocumentPage.razor new file mode 100644 index 0000000..84259a3 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Dev/SampleDocumentPage.razor @@ -0,0 +1,194 @@ +@page "/sviluppo/documento" +@attribute [Authorize] +@inherits DocumentPage +@inject IWebHostEnvironment Environment +@inject TimeProvider Clock + +@* A document page built on DocumentPage (issue #29): toolbar, header, tabs with Righe first, shortcuts. Fake data, + development only. *@ + + +@if (!Environment.IsDevelopment() || Record is null) +{ +

@T["Pages.Catalog.DevOnly"]

+} +else +{ + + + + + @T["Pages.Catalog.Fields.Date"] @(Record.Date is { } d ? T.Date(d) : null) + + + @if (Record.Issued) + { + @T["Pages.Catalog.Panels.Issued"] + } + else + { + @T["Pages.Catalog.Panels.Draft"] + } + @if (IsModified) + { + @T["Pages.Catalog.Modified"] + } + + + + + + + + @switch (ActiveTab) + { + case TabIds.Lines: + + + + + + + + + + + + @foreach (var line in Record.Lines) + { + + + + + + + + } + +
@T["Pages.Catalog.Lines.Code"]@T["Pages.Catalog.Lines.Description"]@T["Pages.Catalog.Lines.Quantity"]@T["Pages.Catalog.Lines.Price"]@T["Pages.Catalog.Lines.Amount"]
@line.Code@line.Description@T.Number(line.Quantity ?? 0, 2)
+ break; + + case TabIds.Header: + + + + + + + + + + + + break; + + default: +

@T["Pages.Catalog.TabPlaceholder"]

+ break; + } +
+
+} + +@code { + private int _saved; + + /// + public override IReadOnlyList Tabs => Record is null ? [] : StandardTabs(attachments: 2, links: 1); + + /// + public override bool IsReadOnly => Record?.Issued == true; + + /// + protected override IList Lines => Record?.Lines ?? []; + + /// + protected override string? NewUrl => "sviluppo/documento"; + + /// + protected override int? AttachmentCount => 2; + + /// + protected override bool CanMove => true; + + private IReadOnlyList PartyLines => [T["Pages.Catalog.Head.Address"], T["Pages.Catalog.Head.Vat"]]; + + private IReadOnlyList SubValues => Record is null ? [] : + [ + new(T["Pages.Catalog.Panels.Taxable"], T.Money(Record.Taxable)), + new(T["Pages.Catalog.Head.VatAmount"], T.Money(Record.Vat)), + ]; + + /// + protected override void OnInitialized() + { + base.OnInitialized(); + Record = CatalogSamples.Document(Today); + } + + /// + protected override IEnumerable ContextActions() + { + yield return new ToolbarItem("issue", "send", T["Pages.Catalog.Toolbar.Issue"]) + { + Kind = ToolbarKind.Action, Primary = true, Disabled = IsReadOnly || IsModified, OnClick = IssueAsync, + }; + } + + /// + protected override Task SaveCoreAsync() + { + // A pretend rule of the service: the number must keep the year prefix. + if (Record is null || !Record.Number.StartsWith("2026/", StringComparison.Ordinal)) + { + Validation.Add("number", T["Pages.Catalog.Fields.NumberTaken"]); + return Task.FromResult(false); + } + + _saved++; + return Task.FromResult(true); + } + + /// + protected override Task ReloadAsync() + { + Record = CatalogSamples.Document(Today); + return Task.CompletedTask; + } + + /// + protected override Task MoveAsync(int direction) + { + Toasts.Show(ToastKind.Info, T[direction < 0 ? "Ui.Toolbar.Previous" : "Ui.Toolbar.Next"]); + return Task.CompletedTask; + } + + /// + protected override Task RadarAsync() + { + Toasts.Show(ToastKind.Info, T["Ui.Toolbar.Radar"]); + return Task.CompletedTask; + } + + private DateOnly Today => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(Clock.GetUtcNow(), TimeZoneInfo.Local).DateTime); + + private void Change(Action change) + { + change(); + MarkModified(); + } + + private Task IssueAsync() + { + if (Record is not null) + { + Record.Issued = true; + Toasts.Show(ToastKind.Success, T["Pages.Catalog.Panels.Issued"]); + } + + return Task.CompletedTask; + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Profile.razor b/src/Khaemhat.Web/Components/Pages/Profile.razor index 212fcd7..33a19cb 100644 --- a/src/Khaemhat.Web/Components/Pages/Profile.razor +++ b/src/Khaemhat.Web/Components/Pages/Profile.razor @@ -4,6 +4,7 @@ @using Khaemhat.Application.Preferences @using Khaemhat.Application.Security @using Khaemhat.Web.Security +@using Khaemhat.Web.Components.Pages.ProfileTabs @implements IAsyncDisposable @inject ShellSession Session @inject ThemeService Theme @@ -176,6 +177,14 @@
break; + case AccountSection: + + break; + + case SecuritySection: + + break; + case SessionsSection:

@T["Pages.Profile.Sessions.Intro"]

@@ -238,9 +247,16 @@ { - @foreach (var keys in shortcut.Keys) + @if (shortcut.Display is { } display) { - @keys + @display + } + else + { + @foreach (var keys in shortcut.Keys) + { + @KeyboardShortcuts.Pretty(keys) + } } @T[shortcut.TextKey] @@ -260,11 +276,15 @@ private const string StartSection = "pagina-iniziale"; private const string ShortcutsSection = "scorciatoie"; private const string SessionsSection = "sessioni"; + private const string AccountSection = "dati"; + private const string SecuritySection = "sicurezza"; private static readonly (string Id, string Icon, string Key)[] Sections = [ (AppearanceSection, "palette", "Pages.Profile.Tabs.Appearance"), (StartSection, "home", "Pages.Profile.Tabs.Start"), + (AccountSection, "user", "Pages.Profile.Tabs.Account"), + (SecuritySection, "lock", "Pages.Profile.Tabs.Security"), (SessionsSection, "monitor", "Pages.Profile.Tabs.Sessions"), (ShortcutsSection, "keyboard", "Pages.Profile.Tabs.Shortcuts"), ]; @@ -281,7 +301,7 @@ private SessionOwner? _owner; private long _currentSessionId; - /// The section: aspetto, pagina-iniziale, sessioni, scorciatoie. + /// The section: aspetto, pagina-iniziale, dati, sicurezza, sessioni, scorciatoie. [SupplyParameterFromQuery(Name = "scheda")] public string? Section { get; set; } @@ -293,6 +313,8 @@ private bool IsModified => Draft != Session.Preferences; + private long? CurrentSession => _currentSessionId == 0 ? null : _currentSessionId; + private IEnumerable StartChoices => MenuCatalog.All.Where(i => i.Milestone is null && Session.CanSee(i)); /// diff --git a/src/Khaemhat.Web/Components/Pages/ProfileTabs/ProfileAccount.razor b/src/Khaemhat.Web/Components/Pages/ProfileTabs/ProfileAccount.razor new file mode 100644 index 0000000..7f25209 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/ProfileTabs/ProfileAccount.razor @@ -0,0 +1,140 @@ +@using Khaemhat.Application.Security +@using Khaemhat.Web.Security +@inject ProfileService Profiles +@inject ShellSession Session +@inject ToastService Toasts +@inject SecurityPolicyOptions Policy + +@* "Dati personali" of the profile (SPEC §12, issue #31): the name and e-mail the user may change alone. *@ +@if (_info is null) +{ +

@T["Common.Loading"]

+} +else +{ +
+
+ @T["Pages.Profile.Account.Data"] +
+
+ + +
+
+ + +
+
+ + + @T["Pages.Profile.Account.EmailHint"] +
+ @foreach (var message in _messages) + { + + } +
+ +
+
+
+ +
+ @T["Pages.Profile.Account.About"] +
+
@T["Pages.Profile.Account.Kind"]
+
@T[Session.LevelKey]
+
@T["Pages.Profile.Account.Company"]
+
@(Session.Company?.Name ?? T["Pages.Profile.Sessions.InstanceAccount"])
+
@T["Pages.Profile.Account.LastLogin"]
+
@(_info.LastLoginAt is { } last ? T.DateTime(last, TimeZoneInfo.Local) : T["Pages.Profile.Account.Never"])
+
@T["Pages.Profile.Account.PasswordChanged"]
+
@(_info.PasswordChangedAt is { } changed ? T.DateTime(changed, TimeZoneInfo.Local) : T["Pages.Profile.Account.Never"])
+
@T["Pages.Profile.Account.TwoStep"]
+
+ @if (_info.TotpEnabled) + { + @T["Pages.Profile.Security.TotpOn"] + } + else + { + @T["Pages.Profile.Security.TotpOff"] + } +
+
+
+
+} + +@code { + private ProfileInfo? _info; + private string? _displayName; + private string? _email; + private IReadOnlyList _errors = []; + private IReadOnlyList _messages = []; + private bool _busy; + private bool _reported; + + /// The account of the session. + [Parameter, EditorRequired] + public SessionOwner? Owner { get; set; } + + /// The tab of the page, to show the modified mark. + [CascadingParameter] + public KhTab? Tab { get; set; } + + private bool IsModified => _info is not null && (_displayName != _info.DisplayName || (_email ?? string.Empty) != (_info.Email ?? string.Empty)); + + /// + protected override async Task OnInitializedAsync() + { + if (Owner is not null) + { + _info = await Profiles.GetAsync(Owner); + _displayName = _info?.DisplayName; + _email = _info?.Email; + } + } + + /// + protected override void OnAfterRender(bool firstRender) + { + // Only a change of state is reported, so the mark set by another section of the page is left alone. + if (IsModified != _reported) + { + _reported = IsModified; + Tab?.SetModified(_reported); + } + } + + private bool HasError(string code) => _errors.Contains(code); + + private async Task SaveAsync() + { + if (Owner is null || !IsModified || _busy) + { + return; + } + + _busy = true; + try + { + _errors = await Profiles.UpdateAsync(Owner, _displayName, _email); + _messages = LoginFlow.Messages(T, Policy, string.Join(',', _errors)); + if (_errors.Count == 0) + { + _info = await Profiles.GetAsync(Owner); + _displayName = _info?.DisplayName; + _email = _info?.Email; + Session.SetDisplayName(_displayName); + Toasts.Show(ToastKind.Success, T["Pages.Profile.Account.Saved"]); + } + } + finally + { + _busy = false; + } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/ProfileTabs/ProfileSecurity.razor b/src/Khaemhat.Web/Components/Pages/ProfileTabs/ProfileSecurity.razor new file mode 100644 index 0000000..20bc5b8 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/ProfileTabs/ProfileSecurity.razor @@ -0,0 +1,258 @@ +@using Khaemhat.Application.Security +@using Khaemhat.Web.Security +@inject ProfileService Profiles +@inject ShellSession Session +@inject ToastService Toasts +@inject DialogService Dialogs +@inject SecurityPolicyOptions Policy + +@* "Password e verifica in due passaggi" of the profile (SPEC §7.3, §12, issue #31). A password change closes the other + sessions; turning the verification off and renewing the recovery codes ask for the password again. *@ +@if (_info is null) +{ +

@T["Common.Loading"]

+} +else +{ +
+ @if (_info.HasPassword) + { +
+
@T["Pages.Profile.Security.Password"]
+
+
+ + +
+
+ + + @T.Format("Pages.Profile.Security.Rules", Policy.MinimumLength, Policy.HistorySize) +
+
+ + + @if (Mismatch) + { + @T["Pages.Profile.Security.Mismatch"] + } +
+ @foreach (var message in _passwordMessages) + { + + } +
+ +
+

@T["Pages.Profile.Security.ChangeNote"]

+
+
+ } + +
+
@T["Pages.Profile.Security.TwoStep"]
+
+

+ @if (_info.TotpEnabled) + { + @T["Pages.Profile.Security.TotpOn"] + } + else + { + @T["Pages.Profile.Security.TotpOff"] + } + @if (_info.TotpRequired) + { + @T["Pages.Profile.Security.TotpRequired"] + } +

+ + @if (_recoveryCodes is not null) + { +
@T["Pages.Profile.Security.CodesOnce"]
+
    + @foreach (var recovery in _recoveryCodes) + { +
  • @recovery
  • + } +
+ + } + else if (!_info.TotpEnabled && _setup is null) + { +

@T["Pages.Profile.Security.TotpIntro"]

+ + } + else if (!_info.TotpEnabled && _setup is not null) + { +

@T["Pages.Profile.Security.SetupText"]

+
+
@T["Auth.TotpSetup.Secret"]
+
@Grouped(_setup.Secret)
+
@T["Auth.TotpSetup.Phone"]
+
@T["Auth.TotpSetup.OpenInApp"]
+
+
+
+ + +
+ @if (_codeWrong) + { + + } +
+ + +
+
+ } + else + { +

@T.Format("Pages.Profile.Security.CodesLeft", _info.RecoveryCodesLeft)

+
+
+ + +
+ @foreach (var message in _totpMessages) + { + + } +
+ + @if (!_info.TotpRequired) + { + + } +
+
+ } +
+
+
+} + +@code { + private ProfileInfo? _info; + private string? _current; + private string? _new; + private string? _repeat; + private string? _code; + private string? _confirm; + private bool _codeWrong; + private bool _busy; + private TotpSetup? _setup; + private IReadOnlyList? _recoveryCodes; + private IReadOnlyList _passwordMessages = []; + private IReadOnlyList _totpMessages = []; + + /// The account of the session. + [Parameter, EditorRequired] + public SessionOwner? Owner { get; set; } + + /// The session that stays open after a password change. + [Parameter] + public long? CurrentSessionId { get; set; } + + private bool Mismatch => !string.IsNullOrEmpty(_repeat) && _repeat != _new; + + private bool CanChangePassword => !_busy && !string.IsNullOrEmpty(_current) && !string.IsNullOrEmpty(_new) && _new == _repeat; + + /// + protected override Task OnInitializedAsync() => ReloadAsync(); + + private async Task ReloadAsync() => _info = Owner is null ? null : await Profiles.GetAsync(Owner); + + private async Task ChangePasswordAsync() + { + if (Owner is null || !CanChangePassword) + { + return; + } + + _busy = true; + try + { + var errors = await Profiles.ChangePasswordAsync(Owner, CurrentSessionId, _current!, _new!); + _passwordMessages = LoginFlow.Messages(T, Policy, string.Join(',', errors)); + if (errors.Count == 0) + { + _current = _new = _repeat = null; + await ReloadAsync(); + Toasts.Show(ToastKind.Success, T["Pages.Profile.Security.Changed"], T["Pages.Profile.Security.ChangedText"]); + } + } + finally + { + _busy = false; + } + } + + private async Task BeginSetupAsync() + { + if (Owner is not null) + { + _codeWrong = false; + _setup = await Profiles.BeginTotpSetupAsync(Owner, Session.Company?.Code); + } + } + + private async Task ConfirmSetupAsync() + { + if (Owner is null || string.IsNullOrWhiteSpace(_code)) + { + return; + } + + var codes = await Profiles.ConfirmTotpSetupAsync(Owner, _code); + _code = null; + _codeWrong = codes is null; + if (codes is not null) + { + _setup = null; + _recoveryCodes = codes; + await ReloadAsync(); + Toasts.Show(ToastKind.Success, T["Pages.Profile.Security.Enabled"]); + } + } + + private async Task RenewCodesAsync() + { + if (Owner is null || string.IsNullOrEmpty(_confirm)) + { + return; + } + + var codes = await Profiles.RenewRecoveryCodesAsync(Owner, _confirm); + _confirm = null; + _totpMessages = codes is null ? LoginFlow.Messages(T, Policy, SecurityErrors.CurrentPasswordWrong) : []; + if (codes is not null) + { + _recoveryCodes = codes; + await ReloadAsync(); + } + } + + private async Task DisableAsync() + { + if (Owner is null || string.IsNullOrEmpty(_confirm) + || !await Dialogs.ConfirmAsync(new(T["Pages.Profile.Security.DisableTitle"], T["Pages.Profile.Security.DisableText"], + T["Pages.Profile.Security.Disable"], T["Common.Cancel"], Danger: true))) + { + return; + } + + var errors = await Profiles.DisableTotpAsync(Owner, _confirm); + _confirm = null; + _totpMessages = LoginFlow.Messages(T, Policy, string.Join(',', errors)); + if (errors.Count == 0) + { + await ReloadAsync(); + Toasts.Show(ToastKind.Warning, T["Pages.Profile.Security.Disabled"]); + } + } + + private static string Grouped(string secret) => + string.Join(' ', Enumerable.Range(0, (secret.Length + 3) / 4).Select(i => secret.Substring(i * 4, Math.Min(4, secret.Length - (i * 4))))); +} diff --git a/src/Khaemhat.Web/Components/Ui/KhBadge.razor b/src/Khaemhat.Web/Components/Ui/KhBadge.razor new file mode 100644 index 0000000..2e474e5 --- /dev/null +++ b/src/Khaemhat.Web/Components/Ui/KhBadge.razor @@ -0,0 +1,22 @@ +@* A state badge with its dot (SPEC §10.7): Emessa, Pagata, Scaduta... *@ +@ChildContent + +@code { + /// The tone. + [Parameter] + public KhTone Tone { get; set; } + + /// The text. + [Parameter] + public RenderFragment? ChildContent { get; set; } + + private string ToneClass => Tone switch + { + KhTone.Accent => "accent", + KhTone.Info => "blue", + KhTone.Ok => "green", + KhTone.Warning => "amber", + KhTone.Error => "red", + _ => "gray", + }; +} diff --git a/src/Khaemhat.Web/Components/Ui/KhCheck.razor b/src/Khaemhat.Web/Components/Ui/KhCheck.razor new file mode 100644 index 0000000..eca4cf4 --- /dev/null +++ b/src/Khaemhat.Web/Components/Ui/KhCheck.razor @@ -0,0 +1,17 @@ +@inherits KhInputBase + +@* A check box with its text on the right (SPEC §10.7). In the grid it lines up with the other fields. *@ + + + + +@code { + /// + protected override bool IsEmpty(bool value) => !value; + + private Task OnChangeAsync(ChangeEventArgs e) => SetValueAsync(e.Value is true); +} diff --git a/src/Khaemhat.Web/Components/Ui/KhChip.razor b/src/Khaemhat.Web/Components/Ui/KhChip.razor new file mode 100644 index 0000000..aa9aa58 --- /dev/null +++ b/src/Khaemhat.Web/Components/Ui/KhChip.razor @@ -0,0 +1,57 @@ +@* A chip (SPEC §10.5.2, §10.7). Info chips summarise a condition: icon, a short label and a bold value ("Pagamento + RB 60 gg"). With OnRemove it becomes a filter chip with a remove button. *@ +@if (OnRemove.HasDelegate) +{ + + @Text @Value + + +} +else +{ + + @if (Icon is not null) + { + + } + @Text + @if (Value is not null) + { + @Value + } + +} + +@code { + /// The icon. + [Parameter] + public string? Icon { get; set; } + + /// The label. + [Parameter] + public string? Text { get; set; } + + /// The value, in bold. + [Parameter] + public string? Value { get; set; } + + /// A tooltip with the details. + [Parameter] + public string? Title { get; set; } + + /// The tone: accent, warning, error. + [Parameter] + public KhTone Tone { get; set; } + + /// Makes it a removable filter chip. + [Parameter] + public EventCallback OnRemove { get; set; } + + private string? ToneClass => Tone switch + { + KhTone.Accent => "acc", + KhTone.Warning => "warn", + KhTone.Error => "err", + _ => null, + }; +} diff --git a/src/Khaemhat.Web/Components/Ui/KhContextAction.razor b/src/Khaemhat.Web/Components/Ui/KhContextAction.razor new file mode 100644 index 0000000..a752c48 --- /dev/null +++ b/src/Khaemhat.Web/Components/Ui/KhContextAction.razor @@ -0,0 +1,47 @@ +@* A contextual action of a document (SPEC §10.4): icon and a short label (three words at most), the main one filled. + Labels never wrap. *@ + + +@code { + /// The icon. + [Parameter, EditorRequired] + public string Icon { get; set; } = string.Empty; + + /// The label. + [Parameter, EditorRequired] + public string Text { get; set; } = string.Empty; + + /// The main action of the document. + [Parameter] + public bool Primary { get; set; } + + /// The colour. + [Parameter] + public KhTone Tone { get; set; } + + /// Not usable now. + [Parameter] + public bool Disabled { get; set; } + + /// The shortcut, in the tooltip. + [Parameter] + public string? Shortcut { get; set; } + + /// What it does. + [Parameter] + public EventCallback OnClick { get; set; } + + /// Other attributes. + [Parameter(CaptureUnmatchedValues = true)] + public IReadOnlyDictionary? Attributes { get; set; } + + private string? ToneClass => Primary ? "primary" : Tone switch + { + KhTone.Ok => "ok", + KhTone.Warning => "warn", + KhTone.Error => "danger", + _ => null, + }; +} diff --git a/src/Khaemhat.Web/Components/Ui/KhDateBox.razor b/src/Khaemhat.Web/Components/Ui/KhDateBox.razor new file mode 100644 index 0000000..0912b55 --- /dev/null +++ b/src/Khaemhat.Web/Components/Ui/KhDateBox.razor @@ -0,0 +1,114 @@ +@inherits KhInputBase +@inject TimeProvider Clock + +@* A date as gg/mm/aaaa (SPEC §10.7): short forms (5, 5/3, 050326), T today, F end of month, I start of month, + and - + one day (typed as text, or a key press when the field holds a whole date), arrows up and down one day. *@ + + + + + + + +@code { + private string _text = string.Empty; + private DateOnly? _shown; + private bool _first = true; + private ElementReference _input; + + /// The first date accepted. + [Parameter] + public DateOnly? Min { get; set; } + + /// The last date accepted. + [Parameter] + public DateOnly? Max { get; set; } + + [Inject] + private IJSRuntime JS { get; set; } = default!; + + private DateOnly Today => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(Clock.GetUtcNow(), TimeZoneInfo.Local).DateTime); + + /// + protected override void OnParametersSet() + { + base.OnParametersSet(); + if (_first || (ParseError is null && Value != _shown)) + { + _first = false; + _shown = Value; + _text = Value is { } date ? T.Date(date) : string.Empty; + } + } + + /// + protected override async Task OnAfterRenderAsync(bool firstRender) + { + if (firstRender) + { + await JS.InvokeVoidAsync("khaemhat.preventKeys", _input); + } + } + + /// + public override IEnumerable Validate() + { + foreach (var message in base.Validate()) + { + yield return message; + yield break; + } + + if (Value is { } v && Min is { } min && v < min) + { + yield return T.Format("Ui.Validation.DateMin", T.Date(min)); + } + else if (Value is { } w && Max is { } max && w > max) + { + yield return T.Format("Ui.Validation.DateMax", T.Date(max)); + } + } + + private async Task OnChangeAsync(ChangeEventArgs e) + { + _text = e.Value as string ?? string.Empty; + StateHasChanged(); + await Task.Yield(); + await ApplyAsync(_text); + } + + private async Task OnKeyDownAsync(KeyboardEventArgs e) + { + if (IsReadOnly || e.CtrlKey || e.AltKey) + { + return; + } + + var step = e.Key switch + { + "ArrowUp" => "+", + "ArrowDown" => "-", + _ => null, + }; + if (step is not null) + { + await ApplyAsync(step); + } + } + + private async Task ApplyAsync(string text) + { + if (!ItalianDate.TryParse(text, Today, Value, out var date)) + { + ParseError = T["Ui.Validation.Date"]; + return; + } + + _shown = date; + _text = date is { } d ? T.Date(d) : string.Empty; + await SetValueAsync(date); + } +} diff --git a/src/Khaemhat.Web/Components/Ui/KhDialog.razor b/src/Khaemhat.Web/Components/Ui/KhDialog.razor new file mode 100644 index 0000000..65086b4 --- /dev/null +++ b/src/Khaemhat.Web/Components/Ui/KhDialog.razor @@ -0,0 +1,82 @@ +@inject IJSRuntime JS + +@* A modal dialog (SPEC §10.7): title with icon, content, buttons at the bottom right. Escape and the close button + call OnClose; the focus moves into the dialog when it opens. *@ +@if (Open) +{ +
+ +
+} + +@code { + private static int _next; + private readonly string _id = "kh-dlg" + Interlocked.Increment(ref _next).ToString(System.Globalization.CultureInfo.InvariantCulture); + private ElementReference _dialog; + private bool _wasOpen; + + /// Whether the dialog is shown. + [Parameter] + public bool Open { get; set; } + + /// The title. + [Parameter] + public string? Title { get; set; } + + /// The icon before the title. + [Parameter] + public string? Icon { get; set; } + + /// The width: sm (420 px), md (640 px), lg (860 px). + [Parameter] + public string Size { get; set; } = "md"; + + /// Called by Escape and the close button. + [Parameter] + public EventCallback OnClose { get; set; } + + /// The content. + [Parameter] + public RenderFragment? ChildContent { get; set; } + + /// The buttons. + [Parameter] + public RenderFragment? Footer { get; set; } + + private string SizeClass => "kh-" + Size; + + /// + protected override async Task OnAfterRenderAsync(bool firstRender) + { + if (Open && !_wasOpen) + { + await JS.InvokeVoidAsync("khaemhat.focusFirst", _dialog); + } + + _wasOpen = Open; + } + + private async Task OnKeyDownAsync(KeyboardEventArgs e) + { + if (e.Key == "Escape") + { + await CloseAsync(); + } + } + + private Task CloseAsync() => OnClose.InvokeAsync(); +} diff --git a/src/Khaemhat.Web/Components/Ui/KhDocHead.razor b/src/Khaemhat.Web/Components/Ui/KhDocHead.razor new file mode 100644 index 0000000..e747d0b --- /dev/null +++ b/src/Khaemhat.Web/Components/Ui/KhDocHead.razor @@ -0,0 +1,131 @@ +@* The header of a document or master record (SPEC §10.5.2, mockups 020, 021, 014) in three blocks: on the left the + kind (icon, label, big number, meta line, state badges); in the middle the counterpart (initials, name with code, + detail lines, condition chips); on the right the total with three sub-values, or the KPIs of a master record. *@ +
+
+
+ +
+
@KindLabel
+
@Number
+
+
+ @if (Facts is not null || State is not null) + { +
@Facts @State
+ } +
+
+ @if (Party is not null) + { + @Party + } + else if (PartyName is not null) + { +
+ +
+
+ @PartyName + @if (PartyCode is not null) + { + @PartyCode + } +
+ @foreach (var line in PartyLines ?? []) + { +
@line
+ } +
+
+ } + @if (Chips is not null) + { +
@Chips
+ } +
+
+ @if (Totals is not null) + { + @Totals + } + else + { + @TotalLabel + @TotalValue + @if (SubValues is { Count: > 0 }) + { + + @foreach (var sub in SubValues) + { + @sub.Label @sub.Value + } + + } + } +
+
+ +@code { + /// The icon of the kind. + [Parameter] + public string KindIcon { get; set; } = "file"; + + /// The kind: "Fattura immediata · TD01", "Cliente". + [Parameter] + public string? KindLabel { get; set; } + + /// The number or code, big. + [Parameter] + public string? Number { get; set; } + + /// The meta line: date, section, register. + [Parameter] + public RenderFragment? Facts { get; set; } + + /// The state badges. + [Parameter] + public RenderFragment? State { get; set; } + + /// The counterpart name. + [Parameter] + public string? PartyName { get; set; } + + /// The counterpart code. + [Parameter] + public string? PartyCode { get; set; } + + /// The lines under the name: address, VAT number, PEC. + [Parameter] + public IReadOnlyList? PartyLines { get; set; } + + /// The whole middle block, in place of the counterpart parameters. + [Parameter] + public RenderFragment? Party { get; set; } + + /// The condition chips (KhChip). + [Parameter] + public RenderFragment? Chips { get; set; } + + /// The label of the total. + [Parameter] + public string? TotalLabel { get; set; } + + /// The total, formatted. + [Parameter] + public string? TotalValue { get; set; } + + /// The three values under the total (taxable, VAT, stamp...). + [Parameter] + public IReadOnlyList? SubValues { get; set; } + + /// The whole right block, in place of the total parameters (KPIs of a master record). + [Parameter] + public RenderFragment? Totals { get; set; } + + /// Extra classes. + [Parameter] + public string? Class { get; set; } + + private string Initials => ShellSession.InitialsOf(PartyName ?? string.Empty); +} diff --git a/src/Khaemhat.Web/Components/Ui/KhDrawer.razor b/src/Khaemhat.Web/Components/Ui/KhDrawer.razor new file mode 100644 index 0000000..c8c6cd8 --- /dev/null +++ b/src/Khaemhat.Web/Components/Ui/KhDrawer.razor @@ -0,0 +1,78 @@ +@inject IJSRuntime JS + +@* A side panel from the right (SPEC §10.7): details, attachments, the dashboard "Personalizza". Not modal: the page + stays usable; Escape and the close button call OnClose. *@ +@if (Open) +{ + +} + +@code { + private static int _next; + private readonly string _id = "kh-drw" + Interlocked.Increment(ref _next).ToString(System.Globalization.CultureInfo.InvariantCulture); + private ElementReference _drawer; + private bool _wasOpen; + + /// Whether the panel is shown. + [Parameter] + public bool Open { get; set; } + + /// The title. + [Parameter] + public string? Title { get; set; } + + /// The icon before the title. + [Parameter] + public string? Icon { get; set; } + + /// A wider panel (560 px). + [Parameter] + public bool Wide { get; set; } + + /// Called by Escape and the close button. + [Parameter] + public EventCallback OnClose { get; set; } + + /// The content. + [Parameter] + public RenderFragment? ChildContent { get; set; } + + /// The buttons. + [Parameter] + public RenderFragment? Footer { get; set; } + + /// + protected override async Task OnAfterRenderAsync(bool firstRender) + { + if (Open && !_wasOpen) + { + await JS.InvokeVoidAsync("khaemhat.focusFirst", _drawer); + } + + _wasOpen = Open; + } + + private async Task OnKeyDownAsync(KeyboardEventArgs e) + { + if (e.Key == "Escape") + { + await CloseAsync(); + } + } + + private Task CloseAsync() => OnClose.InvokeAsync(); +} diff --git a/src/Khaemhat.Web/Components/Ui/KhDrawerHost.razor b/src/Khaemhat.Web/Components/Ui/KhDrawerHost.razor new file mode 100644 index 0000000..786bac5 --- /dev/null +++ b/src/Khaemhat.Web/Components/Ui/KhDrawerHost.razor @@ -0,0 +1,20 @@ +@implements IDisposable +@inject DrawerService Drawers + +@* Shows the side panel opened with DrawerService (SPEC §10.7). *@ +@if (Drawers.Current is { } request) +{ + + @request.Content + +} + +@code { + /// + protected override void OnInitialized() => Drawers.Changed += OnChanged; + + /// + public void Dispose() => Drawers.Changed -= OnChanged; + + private void OnChanged() => _ = InvokeAsync(StateHasChanged); +} diff --git a/src/Khaemhat.Web/Components/Ui/KhField.razor b/src/Khaemhat.Web/Components/Ui/KhField.razor new file mode 100644 index 0000000..3eff76b --- /dev/null +++ b/src/Khaemhat.Web/Components/Ui/KhField.razor @@ -0,0 +1,57 @@ +@* A field of the 12-column form grid (SPEC §10.5.4): label above, asterisk when required, the input, the hint and the + messages under it. The input components use it; a page can wrap any custom input with it. *@ +
+ @if (Label is not null) + { + + } + @ChildContent + @if (Messages is { Count: > 0 }) + { + @string.Join(" ", Messages) + } + else if (Hint is not null) + { + @Hint + } +
+ +@code { + /// The label. + [Parameter] + public string? Label { get; set; } + + /// The id of the input the label belongs to. + [Parameter] + public string? For { get; set; } + + /// Shows the required mark. + [Parameter] + public bool Required { get; set; } + + /// A suggestion under the field. + [Parameter] + public string? Hint { get; set; } + + /// The messages of the field. + [Parameter] + public IReadOnlyList? Messages { get; set; } + + /// The columns taken (1-12); 0 leaves the width to the container. + [Parameter] + public int Span { get; set; } = 6; + + /// The input. + [Parameter] + public RenderFragment? ChildContent { get; set; } + + private string? SpanClass => Span is > 0 and <= 12 ? "c" + Span.ToString(System.Globalization.CultureInfo.InvariantCulture) : null; + + private string? DescribedBy => For is null ? null : For + "-d"; +} diff --git a/src/Khaemhat.Web/Components/Ui/KhFieldGroup.razor b/src/Khaemhat.Web/Components/Ui/KhFieldGroup.razor new file mode 100644 index 0000000..7e80e20 --- /dev/null +++ b/src/Khaemhat.Web/Components/Ui/KhFieldGroup.razor @@ -0,0 +1,37 @@ +@* A group of fields (SPEC §10.5.4): a titled box with its own 12-column grid. Inside a KhForm with Layout Groups the + groups stand side by side; Wide takes the whole row. *@ +
+
+ @if (Icon is not null) + { + + } + @Title +
+
@ChildContent
+
+ +@code { + private static int _next; + private readonly string _id = "kh-fg" + Interlocked.Increment(ref _next).ToString(System.Globalization.CultureInfo.InvariantCulture); + + /// The title. + [Parameter, EditorRequired] + public string Title { get; set; } = string.Empty; + + /// The icon. + [Parameter] + public string? Icon { get; set; } + + /// Takes the whole row. + [Parameter] + public bool Wide { get; set; } + + /// Extra classes. + [Parameter] + public string? Class { get; set; } + + /// The fields. + [Parameter] + public RenderFragment? ChildContent { get; set; } +} diff --git a/src/Khaemhat.Web/Components/Ui/KhForm.razor b/src/Khaemhat.Web/Components/Ui/KhForm.razor new file mode 100644 index 0000000..7740262 --- /dev/null +++ b/src/Khaemhat.Web/Components/Ui/KhForm.razor @@ -0,0 +1,146 @@ +@implements IDisposable +@inject IJSRuntime JS + +@* A form (SPEC §10.5.4, §10.5.6): the fields check themselves on submit, the messages appear next to each field and + in a summary at the top whose entries move the focus to the field. Read-only applies to every field inside. *@ +
+ + @if (ShowSummary && Summary.Count > 0) + { + + } + @ChildContent + +
+ +@code { + private KhFormContext _context = default!; + private KhValidation? _subscribed; + private ElementReference _summary; + private bool _focusSummary; + + /// The messages; give one to add the messages the services return. A new one is made otherwise. + [Parameter] + public KhValidation? Validation { get; set; } + + /// Every field is read-only. + [Parameter] + public bool ReadOnly { get; set; } + + /// The arrangement of the children. + [Parameter] + public KhFormLayout Layout { get; set; } = KhFormLayout.Grid; + + /// Shows the summary of the messages. + [Parameter] + public bool ShowSummary { get; set; } = true; + + /// Extra classes. + [Parameter] + public string? Class { get; set; } + + /// Called when the fields are valid. + [Parameter] + public EventCallback OnValidSubmit { get; set; } + + /// The fields. + [Parameter] + public RenderFragment? ChildContent { get; set; } + + /// The context given to the fields. + public KhFormContext Context => _context; + + private string FormClass => Layout switch + { + KhFormLayout.Groups => "fgroups " + Class, + KhFormLayout.Plain => "form plain " + Class, + _ => "form " + Class, + }; + + // The messages with the label and input of their field, also those the page added by name. + private IReadOnlyList Summary => + [.. _context.Validation.Messages.Select(m => m.InputId is null && _context.Find(m.Field) is { } f ? m with { Label = f.Label, InputId = f.InputId } : m)]; + + /// + protected override void OnParametersSet() + { + var validation = Validation ?? _subscribed ?? new KhValidation(); + if (!ReferenceEquals(validation, _subscribed)) + { + if (_subscribed is not null) + { + _subscribed.Changed -= OnChanged; + } + + validation.Changed += OnChanged; + _subscribed = validation; + _context = new KhFormContext(validation); + } + + _context.ReadOnly = ReadOnly; + } + + /// Checks the fields as on submit, without calling . + /// Whether the form is valid. + public bool Validate() + { + var valid = _context.Validate(); + _focusSummary = !valid; + StateHasChanged(); + return valid; + } + + /// + protected override async Task OnAfterRenderAsync(bool firstRender) + { + if (_focusSummary && Summary.Count > 0) + { + _focusSummary = false; + await _summary.FocusAsync(); + } + } + + private async Task SubmitAsync() + { + if (ReadOnly || !Validate()) + { + return; + } + + await OnValidSubmit.InvokeAsync(); + _focusSummary = !_context.Validation.IsValid; + } + + private async Task FocusAsync(string inputId) => await JS.InvokeVoidAsync("khaemhat.focus", "#" + inputId); + + private void OnChanged() => _ = InvokeAsync(StateHasChanged); + + /// + public void Dispose() + { + if (_subscribed is not null) + { + _subscribed.Changed -= OnChanged; + } + } +} diff --git a/src/Khaemhat.Web/Components/Ui/KhHotlink.razor b/src/Khaemhat.Web/Components/Ui/KhHotlink.razor new file mode 100644 index 0000000..1722007 --- /dev/null +++ b/src/Khaemhat.Web/Components/Ui/KhHotlink.razor @@ -0,0 +1,300 @@ +@typeparam TItem +@inherits KhInputBase +@implements IAsyncDisposable +@inject IJSRuntime JS + +@* A link to another record (SPEC §10.5.4, §10.7): the code in evidence, the description beside it, incremental search + while typing, F4 or the magnifier opens the radar, Ctrl+Enter or the arrow opens the record, and "Crea" adds a new + one from the text typed. Leaving the field with a code resolves it; an unknown code is an error. *@ + + + + +@code { + private string _text = string.Empty; + private TItem? _shown; + private bool _first = true; + private bool _open; + private bool _typing; + private bool _searching; + private int _active; + private IReadOnlyList _hits = []; + private CancellationTokenSource? _search; + private ElementReference _input; + + /// Finds the records matching a text (code or description), a few at most. + [Parameter, EditorRequired] + public Func>> Search { get; set; } = default!; + + /// The code of a record. + [Parameter, EditorRequired] + public Func CodeOf { get; set; } = default!; + + /// The description of a record. + [Parameter, EditorRequired] + public Func DescriptionOf { get; set; } = default!; + + /// Opens the radar to choose (F4), with the text typed. + [Parameter] + public EventCallback OnRadar { get; set; } + + /// Opens the chosen record (Ctrl+Enter). + [Parameter] + public EventCallback OnOpen { get; set; } + + /// Creates a record from the text typed; the page then sets the value. + [Parameter] + public EventCallback OnCreate { get; set; } + + /// The text shown while empty. + [Parameter] + public string? Placeholder { get; set; } + + /// The wait after the last key before searching. + [Parameter] + public int DelayMilliseconds { get; set; } = 200; + + private string ListId => InputId + "-l"; + + private string? ActiveId => !_open ? null : _active < _hits.Count ? ListId + "-" + _active : CanCreate ? ListId + "-new" : null; + + private bool CanCreate => OnCreate.HasDelegate && _typing && !string.IsNullOrWhiteSpace(_text); + + private string? PreventedKeys => IsReadOnly ? null : _open ? "ArrowUp ArrowDown Enter Ctrl+Enter F4" : "ArrowDown Ctrl+Enter F4"; + + /// + protected override void OnParametersSet() + { + base.OnParametersSet(); + if (_first || (!_typing && !EqualityComparer.Default.Equals(Value!, _shown!))) + { + _first = false; + _shown = Value; + _text = Value is { } item ? CodeOf(item) : string.Empty; + } + } + + /// + protected override async Task OnAfterRenderAsync(bool firstRender) + { + if (firstRender) + { + await JS.InvokeVoidAsync("khaemhat.preventKeys", _input); + } + } + + private void OnInput(ChangeEventArgs e) + { + _text = e.Value as string ?? string.Empty; + _typing = true; + ParseError = null; + _ = SearchAsync(_text); + } + + private async Task SearchAsync(string text) + { + if (_search is not null) + { + await _search.CancelAsync(); + _search.Dispose(); + } + + var cancel = new CancellationTokenSource(); + _search = cancel; + if (string.IsNullOrWhiteSpace(text)) + { + _open = false; + return; + } + + try + { + await Task.Delay(DelayMilliseconds, cancel.Token); + _searching = true; + var hits = await Search(text.Trim(), cancel.Token); + if (cancel.IsCancellationRequested) + { + return; + } + + _hits = hits; + _active = 0; + _open = true; + _searching = false; + await InvokeAsync(StateHasChanged); + } + catch (OperationCanceledException) + { + // A newer search took over. + } + } + + private async Task OnKeyDownAsync(KeyboardEventArgs e) + { + if (IsReadOnly) + { + return; + } + + var count = _hits.Count + (CanCreate ? 1 : 0); + switch (e.Key) + { + case "ArrowDown" when !_open: + await SearchNowAsync(); + break; + case "ArrowDown" when count > 0: + _active = (_active + 1) % count; + break; + case "ArrowUp" when _open && count > 0: + _active = (_active - 1 + count) % count; + break; + case "Enter" when e.CtrlKey: + await OpenAsync(); + break; + case "Enter" when _open && _active < _hits.Count: + await SelectAsync(_hits[_active]); + break; + case "Enter" when _open && CanCreate: + await CreateAsync(); + break; + case "Escape" when _open || _typing: + Restore(); + break; + case "F4": + await RadarAsync(); + break; + } + } + + private async Task SearchNowAsync() + { + _searching = true; + _hits = await Search(_text.Trim(), CancellationToken.None); + _searching = false; + _active = 0; + _open = true; + } + + // Leaving the field after typing: the exact code, or the only match, is taken; an empty text clears the value. + private async Task OnChangeAsync(ChangeEventArgs e) + { + if (!_typing) + { + return; + } + + var text = (e.Value as string ?? string.Empty).Trim(); + if (text.Length == 0) + { + await SelectAsync(default); + return; + } + + var hits = await Search(text, CancellationToken.None); + var match = hits.FirstOrDefault(h => string.Equals(CodeOf(h), text, StringComparison.OrdinalIgnoreCase)); + if (match is not null || hits.Count == 1) + { + await SelectAsync(match ?? hits[0]); + } + else + { + ParseError = T.Format("Ui.Hotlink.NotFound", text); + } + } + + private async Task SelectAsync(TItem? item) + { + _typing = false; + _open = false; + _shown = item; + _text = item is { } chosen ? CodeOf(chosen) : string.Empty; + await SetValueAsync(item); + } + + private void Restore() + { + _typing = false; + _open = false; + ParseError = null; + _text = Value is { } item ? CodeOf(item) : string.Empty; + } + + private void Close() => _open = false; + + private async Task RadarAsync() + { + _open = false; + await OnRadar.InvokeAsync(_typing ? _text : string.Empty); + } + + private async Task OpenAsync() + { + if (Value is { } item) + { + await OnOpen.InvokeAsync(item); + } + } + + private async Task CreateAsync() + { + var text = _text.Trim(); + Restore(); + await OnCreate.InvokeAsync(text); + } + + /// + public async ValueTask DisposeAsync() + { + if (_search is not null) + { + await _search.CancelAsync(); + _search.Dispose(); + } + + Dispose(); + } +} diff --git a/src/Khaemhat.Web/Components/Ui/KhIconButton.razor b/src/Khaemhat.Web/Components/Ui/KhIconButton.razor new file mode 100644 index 0000000..3173984 --- /dev/null +++ b/src/Khaemhat.Web/Components/Ui/KhIconButton.razor @@ -0,0 +1,73 @@ +@* A 32x32 icon command (SPEC §10.4): no label, a tooltip with the name and the shortcut, an optional counter. *@ +@if (Href is not null && !Disabled) +{ + @Inner +} +else +{ + +} + +@code { + /// The icon. + [Parameter, EditorRequired] + public string Icon { get; set; } = string.Empty; + + /// The name: tooltip and accessible name. + [Parameter, EditorRequired] + public string Text { get; set; } = string.Empty; + + /// The shortcut shown in the tooltip. + [Parameter] + public string? Shortcut { get; set; } + + /// A counter badge. + [Parameter] + public int? Count { get; set; } + + /// Filled with the accent (Save). + [Parameter] + public bool Primary { get; set; } + + /// Destructive. + [Parameter] + public bool Danger { get; set; } + + /// Toggled on. + [Parameter] + public bool Active { get; set; } + + /// Not usable now. + [Parameter] + public bool Disabled { get; set; } + + /// What it does. + [Parameter] + public EventCallback OnClick { get; set; } + + /// Makes it a link. + [Parameter] + public string? Href { get; set; } + + /// Other attributes. + [Parameter(CaptureUnmatchedValues = true)] + public IReadOnlyDictionary? Attributes { get; set; } + + private string Classes => string.Join(' ', new[] { Primary ? "primary" : null, Danger ? "danger" : null, Active ? "on" : null, Disabled ? "disabled" : null }.Where(c => c is not null)); + + private RenderFragment Inner => @ + + @if (Count is > 0) + { + + } + + @Text + @if (Shortcut is not null) + { + @KeyboardShortcuts.Pretty(Shortcut) + } + + ; +} diff --git a/src/Khaemhat.Web/Components/Ui/KhIconToolbar.razor b/src/Khaemhat.Web/Components/Ui/KhIconToolbar.razor new file mode 100644 index 0000000..0c2479f --- /dev/null +++ b/src/Khaemhat.Web/Components/Ui/KhIconToolbar.razor @@ -0,0 +1,203 @@ +@implements IAsyncDisposable +@inject IJSRuntime JS +@inject NavigationManager Navigation + +@* The command bar of a page (SPEC §10.4, mockup 020): icon groups on the left, at most four contextual actions, the + right group (radar, previous, next) and the "⋯" menu with the rest. The bar always stays on one line: when it is too + narrow the commands with the highest priority move into the menu (measured in the browser, khaemhat.watchToolbar). *@ + + +@code { + private ElementReference _bar; + private ElementReference _menuRef; + private bool _placeMenu; + private DotNetObjectReference? _self; + private HashSet _overflow = new(StringComparer.Ordinal); + private bool _menu; + private bool _watching; + + /// The most contextual actions shown on the bar (SPEC §10.4). + public const int MaxActions = 4; + + /// The commands. + [Parameter, EditorRequired] + public IReadOnlyList Items { get; set; } = []; + + /// The accessible name of the bar. + [Parameter] + public string? Label { get; set; } + + /// Extra classes. + [Parameter] + public string? Class { get; set; } + + private IEnumerable Start => Items.Where(i => i.Kind == ToolbarKind.Icon && !i.End); + + private IEnumerable End => Items.Where(i => i.Kind == ToolbarKind.Icon && i.End); + + private List Actions => [.. Items.Where(i => i.Kind == ToolbarKind.Action)]; + + // The menu: what does not fit, the fifth action onwards, and the commands that live only there. + private List MenuItems => + [ + .. Items.Where(i => i.Kind != ToolbarKind.Menu && _overflow.Contains(i.Id)), + .. Actions.Skip(MaxActions), + .. Items.Where(i => i.Kind == ToolbarKind.Menu), + ]; + + /// The ids of the commands moved into the menu, for the tests. + public IReadOnlyCollection Overflow => _overflow; + + private static string? PriorityOf(ToolbarItem item) => + item.Priority > 0 ? item.Priority.ToString(System.Globalization.CultureInfo.InvariantCulture) : null; + + private RenderFragment Icon(ToolbarItem item) => + @; + + /// + protected override async Task OnAfterRenderAsync(bool firstRender) + { + if (!_watching) + { + _watching = true; + _self = DotNetObjectReference.Create(this); + await JS.InvokeVoidAsync("khaemhat.watchToolbar", _bar, _self); + } + else + { + await JS.InvokeVoidAsync("khaemhat.fitToolbar", _bar); + } + + // The menu is placed against the window, so a container that clips its content cannot cut it. + if (_placeMenu && _menu) + { + _placeMenu = false; + await JS.InvokeVoidAsync("khaemhat.placeMenu", _menuRef); + } + } + + /// Called by the browser with the commands that do not fit. + /// The ids moved into the menu. + [JSInvokable] + public void SetOverflow(string[] ids) + { + var next = new HashSet(ids ?? [], StringComparer.Ordinal); + if (!next.SetEquals(_overflow)) + { + _overflow = next; + StateHasChanged(); + } + } + + private void ToggleMenu() + { + _menu = !_menu; + _placeMenu = _menu; + } + + private void CloseMenu() => _menu = false; + + private void OnMenuKey(KeyboardEventArgs e) + { + if (e.Key == "Escape") + { + _menu = false; + } + } + + private async Task RunAsync(ToolbarItem item) + { + _menu = false; + if (item.Disabled) + { + return; + } + + if (item.Href is not null) + { + Navigation.NavigateTo(item.Href); + } + else if (item.OnClick is not null) + { + await item.OnClick(); + } + } + + /// + public async ValueTask DisposeAsync() + { + if (_self is null) + { + return; + } + + try + { + await JS.InvokeVoidAsync("khaemhat.unwatchToolbar", _bar); + } + catch (JSDisconnectedException) + { + // The page is gone with the circuit. + } + + _self.Dispose(); + } +} diff --git a/src/Khaemhat.Web/Components/Ui/KhMoney.razor b/src/Khaemhat.Web/Components/Ui/KhMoney.razor new file mode 100644 index 0000000..ef9d3fd --- /dev/null +++ b/src/Khaemhat.Web/Components/Ui/KhMoney.razor @@ -0,0 +1,20 @@ +@* An amount in euro in the Italian format with tabular figures (SPEC §10.7); negative amounts in red when asked. *@ +@(Value is { } v ? T.Money(v) : Empty) + +@code { + /// The amount. + [Parameter] + public decimal? Value { get; set; } + + /// Shows negative amounts in red. + [Parameter] + public bool RedWhenNegative { get; set; } + + /// The text when there is no amount. + [Parameter] + public string? Empty { get; set; } + + /// Extra classes. + [Parameter] + public string? Class { get; set; } +} diff --git a/src/Khaemhat.Web/Components/Ui/KhNumberBox.razor b/src/Khaemhat.Web/Components/Ui/KhNumberBox.razor new file mode 100644 index 0000000..2dab646 --- /dev/null +++ b/src/Khaemhat.Web/Components/Ui/KhNumberBox.razor @@ -0,0 +1,81 @@ +@inherits KhInputBase + +@* A number in the Italian format (SPEC §10.7): comma for decimals, point for thousands, and the inline calculation + when the text starts with "=" (=10*3 gives 30). The value is rounded to the decimals of the field. *@ + + + + +@code { + private string _text = string.Empty; + private decimal? _shown; + private bool _first = true; + + /// The decimals kept and shown. + [Parameter] + public int Decimals { get; set; } = 2; + + /// The smallest value accepted. + [Parameter] + public decimal? Min { get; set; } + + /// The largest value accepted. + [Parameter] + public decimal? Max { get; set; } + + /// The text shown while empty. + [Parameter] + public string? Placeholder { get; set; } + + /// + protected override void OnParametersSet() + { + base.OnParametersSet(); + if (_first || (ParseError is null && Value != _shown)) + { + _first = false; + _shown = Value; + _text = ItalianNumber.Format(Value, Decimals, T.Culture); + } + } + + /// + public override IEnumerable Validate() + { + foreach (var message in base.Validate()) + { + yield return message; + yield break; + } + + if (Value is { } v && Min is { } min && v < min) + { + yield return T.Format("Ui.Validation.Min", T.Number(min, Decimals)); + } + else if (Value is { } w && Max is { } max && w > max) + { + yield return T.Format("Ui.Validation.Max", T.Number(max, Decimals)); + } + } + + private async Task OnChangeAsync(ChangeEventArgs e) + { + // Render the typed text first: the browser holds it already, so the formatted text below differs from the last + // render and reaches the page even when the value does not change (=1+1 over 2,00). + _text = e.Value as string ?? string.Empty; + StateHasChanged(); + await Task.Yield(); + if (!ItalianNumber.TryParse(_text, out var value)) + { + ParseError = T["Ui.Validation.Number"]; + return; + } + + value = value is { } v ? Math.Round(v, Decimals, MidpointRounding.AwayFromZero) : null; + _shown = value; + _text = ItalianNumber.Format(value, Decimals, T.Culture); + await SetValueAsync(value); + } +} diff --git a/src/Khaemhat.Web/Components/Ui/KhPanel.razor b/src/Khaemhat.Web/Components/Ui/KhPanel.razor new file mode 100644 index 0000000..5466fc4 --- /dev/null +++ b/src/Khaemhat.Web/Components/Ui/KhPanel.razor @@ -0,0 +1,53 @@ +@* A panel with a header (SPEC §10.7): icon, title, actions on the right, an optional link. *@ +
+ @if (Title is not null || Actions is not null) + { +
+ @if (Icon is not null) + { + + } + @Title + @Actions + @if (LinkHref is not null) + { + @LinkText + } +
+ } +
@ChildContent
+
+ +@code { + /// The title. + [Parameter] + public string? Title { get; set; } + + /// The icon before the title. + [Parameter] + public string? Icon { get; set; } + + /// Buttons on the right of the header. + [Parameter] + public RenderFragment? Actions { get; set; } + + /// A link on the right of the header ("Vedi tutti"). + [Parameter] + public string? LinkHref { get; set; } + + /// The text of the link. + [Parameter] + public string? LinkText { get; set; } + + /// No padding around the content (a grid, a list). + [Parameter] + public bool Tight { get; set; } + + /// Extra classes. + [Parameter] + public string? Class { get; set; } + + /// The content. + [Parameter] + public RenderFragment? ChildContent { get; set; } +} diff --git a/src/Khaemhat.Web/Components/Ui/KhRecordLayout.razor b/src/Khaemhat.Web/Components/Ui/KhRecordLayout.razor new file mode 100644 index 0000000..93ef4d3 --- /dev/null +++ b/src/Khaemhat.Web/Components/Ui/KhRecordLayout.razor @@ -0,0 +1,24 @@ +@* The frame of a record page (SPEC §10.5, mockups 020, 021): toolbar, header, tabs and the content of the active tab. + The page derives from DocumentPage or MasterDataPage and passes itself as Page. *@ +
+ + @Heading +
+ +
@ChildContent
+
+
+ +@code { + /// The page. + [Parameter, EditorRequired] + public IRecordPage Page { get; set; } = default!; + + /// The header (KhDocHead). + [Parameter] + public RenderFragment? Heading { get; set; } + + /// The content of the active tab. + [Parameter] + public RenderFragment? ChildContent { get; set; } +} diff --git a/src/Khaemhat.Web/Components/Ui/KhSelect.razor b/src/Khaemhat.Web/Components/Ui/KhSelect.razor new file mode 100644 index 0000000..9b6438a --- /dev/null +++ b/src/Khaemhat.Web/Components/Ui/KhSelect.razor @@ -0,0 +1,49 @@ +@using System.Globalization +@typeparam TValue +@inherits KhInputBase + +@* A choice from a short list (SPEC §10.7). Long lists of records use KhHotlink. *@ + + + + +@code { + /// The choices. + [Parameter, EditorRequired] + public IReadOnlyList> Options { get; set; } = []; + + /// The text of the empty choice; shows none when a value is chosen. + [Parameter] + public string? Empty { get; set; } + + private int Selected + { + get + { + for (var i = 0; i < Options.Count; i++) + { + if (EqualityComparer.Default.Equals(Options[i].Value, Value!)) + { + return i; + } + } + + return -1; + } + } + + private Task OnChangeAsync(ChangeEventArgs e) => + int.TryParse(e.Value as string, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var index) && index >= 0 && index < Options.Count + ? SetValueAsync(Options[index].Value) + : SetValueAsync(default); +} diff --git a/src/Khaemhat.Web/Components/Ui/KhSteps.razor b/src/Khaemhat.Web/Components/Ui/KhSteps.razor new file mode 100644 index 0000000..82d60c8 --- /dev/null +++ b/src/Khaemhat.Web/Components/Ui/KhSteps.razor @@ -0,0 +1,62 @@ +@* The steps of a procedure (SPEC §10.7): horizontal over a wizard, or vertical (KhVSteps style) beside it. Steps + before Current are done. *@ +@if (Vertical) +{ +
    + @for (var i = 0; i < Items.Count; i++) + { + var step = Items[i]; +
  1. + @NumberOf(i) + + @step.Title + @if (step.Detail is not null) + { + @step.Detail + } + +
  2. + } +
+} +else +{ +
    + @for (var i = 0; i < Items.Count; i++) + { + var step = Items[i]; +
  1. + @NumberOf(i) + @step.Title + @if (i < Items.Count - 1) + { + + } +
  2. + } +
+} + +@code { + private RenderFragment NumberOf(int index) => index < Current + ? builder => { builder.OpenComponent(0); builder.AddAttribute(1, nameof(KhIcon.Name), "check"); builder.AddAttribute(2, nameof(KhIcon.Class), "sm"); builder.CloseComponent(); } + : builder => builder.AddContent(0, index + 1); + + /// The steps. + [Parameter, EditorRequired] + public IReadOnlyList Items { get; set; } = []; + + /// The index of the current step. + [Parameter] + public int Current { get; set; } + + /// Vertical layout. + [Parameter] + public bool Vertical { get; set; } + + /// The accessible name. + [Parameter] + public string? Label { get; set; } + + private string? StateOf(int index) => index < Current ? "done" : index == Current ? "on" : null; +} diff --git a/src/Khaemhat.Web/Components/Ui/KhStrip.razor b/src/Khaemhat.Web/Components/Ui/KhStrip.razor new file mode 100644 index 0000000..1f6c2bc --- /dev/null +++ b/src/Khaemhat.Web/Components/Ui/KhStrip.razor @@ -0,0 +1,32 @@ +@* A strip of figures side by side (SPEC §10.7): totals over a list, the state of a procedure. *@ +
+ @foreach (var stat in Items) + { +
+ @stat.Label + @stat.Value +
+ } +
+ +@code { + /// The figures. + [Parameter, EditorRequired] + public IReadOnlyList Items { get; set; } = []; + + /// The accessible name of the strip. + [Parameter] + public string? Label { get; set; } + + /// Extra classes. + [Parameter] + public string? Class { get; set; } + + private static string? ToneClass(KhTone tone) => tone switch + { + KhTone.Ok => "ok", + KhTone.Warning => "warn", + KhTone.Error => "err", + _ => null, + }; +} diff --git a/src/Khaemhat.Web/Components/Ui/KhSwitch.razor b/src/Khaemhat.Web/Components/Ui/KhSwitch.razor new file mode 100644 index 0000000..3a1815f --- /dev/null +++ b/src/Khaemhat.Web/Components/Ui/KhSwitch.razor @@ -0,0 +1,25 @@ +@inherits KhInputBase + +@* An on/off switch (SPEC §10.7): a button with role switch, operable with Space and Enter. *@ + + + + +@code { + /// The text when on; defaults to "Attivo". + [Parameter] + public string? OnText { get; set; } + + /// The text when off; defaults to "Disattivo". + [Parameter] + public string? OffText { get; set; } + + /// + protected override bool IsEmpty(bool value) => !value; + + private Task ToggleAsync() => SetValueAsync(!Value); +} diff --git a/src/Khaemhat.Web/Components/Ui/KhTabs.razor b/src/Khaemhat.Web/Components/Ui/KhTabs.razor new file mode 100644 index 0000000..58405ae --- /dev/null +++ b/src/Khaemhat.Web/Components/Ui/KhTabs.razor @@ -0,0 +1,108 @@ +@implements IDisposable +@inject KeyboardShortcutService Keys + +@* The tabs of a page (SPEC §10.5.3): icon, text, counter; Alt+1..9 picks the tab by position while the page is the + active one. With HrefOf the tabs are links (the address keeps the tab), otherwise buttons. *@ +
+ @for (var i = 0; i < Items.Count; i++) + { + var item = Items[i]; + var active = item.Id == Active; + var key = i < 9 ? "Alt+" + (i + 1).ToString(System.Globalization.CultureInfo.InvariantCulture) : null; + if (HrefOf is not null) + { + + @item.Text + @if (item.Count is { } n) + { + @n + } + + } + else + { + + } + } +
+ +@code { + /// The tabs. + [Parameter, EditorRequired] + public IReadOnlyList Items { get; set; } = []; + + /// The id of the active tab. + [Parameter] + public string? Active { get; set; } + + /// Called when the user picks a tab. + [Parameter] + public EventCallback ActiveChanged { get; set; } + + /// Makes the tabs links: the address of each tab. + [Parameter] + public Func? HrefOf { get; set; } + + /// Alt+1..9 picks the tabs (one tab bar per page should have it). + [Parameter] + public bool Shortcuts { get; set; } = true; + + /// The accessible name of the tab bar. + [Parameter] + public string? Label { get; set; } + + /// Extra classes. + [Parameter] + public string? Class { get; set; } + + /// The tab of the shell holding the page: the shortcuts work only while it is active. + [CascadingParameter] + public KhTab? Tab { get; set; } + + [Inject] + private NavigationManager Navigation { get; set; } = default!; + + /// + protected override void OnInitialized() => Keys.PagePressed += OnShortcutAsync; + + private async Task SelectAsync(KhTabItem item) + { + if (item.Id != Active) + { + Active = item.Id; + await ActiveChanged.InvokeAsync(item.Id); + } + } + + private async Task OnShortcutAsync(string command) + { + if (!Shortcuts || (Tab is not null && !Tab.IsActive) || !KeyboardShortcuts.TryGetTabNumber(command, out var number) || number > Items.Count) + { + return; + } + + var item = Items[number - 1]; + await InvokeAsync(async () => + { + if (HrefOf is not null) + { + Navigation.NavigateTo(HrefOf(item)); + } + else + { + await SelectAsync(item); + StateHasChanged(); + } + }); + } + + /// + public void Dispose() => Keys.PagePressed -= OnShortcutAsync; +} diff --git a/src/Khaemhat.Web/Components/Ui/KhTextArea.razor b/src/Khaemhat.Web/Components/Ui/KhTextArea.razor new file mode 100644 index 0000000..b66737f --- /dev/null +++ b/src/Khaemhat.Web/Components/Ui/KhTextArea.razor @@ -0,0 +1,24 @@ +@inherits KhInputBase + +@* A text on several lines (SPEC §10.7). *@ + + + + +@code { + /// The visible lines. + [Parameter] + public int Rows { get; set; } = 3; + + /// The text shown while empty. + [Parameter] + public string? Placeholder { get; set; } + + /// The longest text. + [Parameter] + public int? MaxLength { get; set; } + + private Task OnChangeAsync(ChangeEventArgs e) => SetValueAsync(e.Value as string); +} diff --git a/src/Khaemhat.Web/Components/Ui/KhTextBox.razor b/src/Khaemhat.Web/Components/Ui/KhTextBox.razor new file mode 100644 index 0000000..2dbb95b --- /dev/null +++ b/src/Khaemhat.Web/Components/Ui/KhTextBox.razor @@ -0,0 +1,28 @@ +@inherits KhInputBase + +@* A text field (SPEC §10.7). Mono shows codes in the code font. *@ + + + + +@code { + /// The input type: text, email, tel, url, password. + [Parameter] + public string Type { get; set; } = "text"; + + /// The text shown while empty. + [Parameter] + public string? Placeholder { get; set; } + + /// The longest text. + [Parameter] + public int? MaxLength { get; set; } + + /// Shows the value in the code font. + [Parameter] + public bool Mono { get; set; } + + private Task OnChangeAsync(ChangeEventArgs e) => SetValueAsync(e.Value as string); +} diff --git a/src/Khaemhat.Web/Components/Ui/KhTile.razor b/src/Khaemhat.Web/Components/Ui/KhTile.razor new file mode 100644 index 0000000..e769963 --- /dev/null +++ b/src/Khaemhat.Web/Components/Ui/KhTile.razor @@ -0,0 +1,60 @@ +@* A KPI tile (SPEC §10.7): title with icon, big value, a detail line, a coloured edge for the tone. With Href the + whole tile is a link. *@ +@if (Href is not null) +{ + @Body +} +else +{ +
@Body
+} + +@code { + /// The title. + [Parameter, EditorRequired] + public string Title { get; set; } = string.Empty; + + /// The icon. + [Parameter] + public string? Icon { get; set; } + + /// The value. + [Parameter] + public string? Value { get; set; } + + /// The line under the value. + [Parameter] + public RenderFragment? Detail { get; set; } + + /// The tone of the edge. + [Parameter] + public KhTone Tone { get; set; } + + /// Makes the tile a link. + [Parameter] + public string? Href { get; set; } + + private string? ToneClass => Tone switch + { + KhTone.Ok => "ok", + KhTone.Warning => "warn", + KhTone.Error => "err", + KhTone.Accent => "acc", + _ => null, + }; + + private RenderFragment Body => @ + + @if (Icon is not null) + { + + } + @Title + + @Value + @if (Detail is not null) + { + @Detail + } + ; +} diff --git a/src/Khaemhat.Web/Components/Ui/KhVSteps.razor b/src/Khaemhat.Web/Components/Ui/KhVSteps.razor new file mode 100644 index 0000000..e5dd7bc --- /dev/null +++ b/src/Khaemhat.Web/Components/Ui/KhVSteps.razor @@ -0,0 +1,16 @@ +@* The vertical steps of a wizard (SPEC §10.7): KhSteps laid out in a column, with a line under each title. *@ + + +@code { + /// The steps. + [Parameter, EditorRequired] + public IReadOnlyList Items { get; set; } = []; + + /// The index of the current step. + [Parameter] + public int Current { get; set; } + + /// The accessible name. + [Parameter] + public string? Label { get; set; } +} diff --git a/src/Khaemhat.Web/Components/_Imports.razor b/src/Khaemhat.Web/Components/_Imports.razor index 384ed7c..208fa06 100644 --- a/src/Khaemhat.Web/Components/_Imports.razor +++ b/src/Khaemhat.Web/Components/_Imports.razor @@ -1,4 +1,4 @@ -@using System.Net.Http +@using System.Net.Http @using System.Net.Http.Json @using Microsoft.AspNetCore.Authorization @using Microsoft.AspNetCore.Components.Authorization @@ -18,4 +18,5 @@ @using Khaemhat.Web.Shell @using Khaemhat.Web.Components.Shell @using Khaemhat.Web.Components.Ui +@using Khaemhat.Web.Ui @inject ITexts T diff --git a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs index 98e017a..158ec93 100644 --- a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs +++ b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs @@ -114,6 +114,7 @@ internal static class KhaemhatServices services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); // Companies and start. services.AddSingleton(); @@ -144,6 +145,7 @@ internal static class KhaemhatServices services.AddScoped(); services.AddScoped(); services.AddScoped(); + services.AddScoped(); return services; } } diff --git a/src/Khaemhat.Web/Resources/it-IT/Auth.json b/src/Khaemhat.Web/Resources/it-IT/Auth.json index f0cef50..e6bac8d 100644 --- a/src/Khaemhat.Web/Resources/it-IT/Auth.json +++ b/src/Khaemhat.Web/Resources/it-IT/Auth.json @@ -78,6 +78,9 @@ "level_too_low": "Il tuo livello di accesso non consente questa operazione.", "permission_denied": "Il tuo profilo non ha il permesso per questa operazione.", "module_not_licensed": "Il modulo non è compreso nella licenza.", + "display_name_invalid": "Il nome è obbligatorio e non può superare 100 caratteri.", + "email_invalid": "L'indirizzo e-mail non è valido.", + "totp_required": "La verifica in due passaggi è obbligatoria per il tuo account e non si può disattivare.", "Other": "Accesso non riuscito." } } diff --git a/src/Khaemhat.Web/Resources/it-IT/Pages.json b/src/Khaemhat.Web/Resources/it-IT/Pages.json index 21400fc..c908b22 100644 --- a/src/Khaemhat.Web/Resources/it-IT/Pages.json +++ b/src/Khaemhat.Web/Resources/it-IT/Pages.json @@ -50,12 +50,14 @@ }, "Profile": { "Title": "Il mio profilo", - "Subtitle": "Aspetto, pagina iniziale e scorciatoie da tastiera. Le scelte valgono solo per il tuo account.", + "Subtitle": "Dati personali, sicurezza, aspetto, pagina iniziale e scorciatoie da tastiera. Le scelte valgono solo per il tuo account.", "Tabs": { "Appearance": "Aspetto", "Start": "Pagina iniziale", - "Shortcuts": "Scorciatoie", - "Sessions": "Sessioni" + "Account": "Dati personali", + "Security": "Password e 2FA", + "Sessions": "Sessioni", + "Shortcuts": "Scorciatoie" }, "Theme": { "_": "Tema", @@ -141,6 +143,179 @@ "Revoked": "Sessione chiusa", "RevokedMany": "Sessioni chiuse: {0}", "None": "Nessuna altra sessione attiva." + }, + "Account": { + "Data": "Dati personali", + "UserName": "Nome utente", + "DisplayName": "Nome visualizzato", + "Email": "E-mail", + "EmailHint": "Serve per il recupero della password e per le notifiche.", + "About": "Account", + "Kind": "Tipo di account", + "Company": "Azienda", + "LastLogin": "Ultimo accesso", + "PasswordChanged": "Password cambiata il", + "TwoStep": "Verifica in due passaggi", + "Never": "Mai", + "Saved": "Dati personali salvati" + }, + "Security": { + "Password": "Password", + "Current": "Password attuale", + "New": "Nuova password", + "Repeat": "Ripeti la nuova password", + "Rules": "Almeno {0} caratteri e tre tipi tra minuscole, maiuscole, cifre e simboli; diversa dalle ultime {1}.", + "Mismatch": "Le due password non coincidono.", + "Change": "Cambia password", + "ChangeNote": "Dopo il cambio le altre sessioni aperte con il tuo account vengono chiuse.", + "Changed": "Password cambiata", + "ChangedText": "Le altre sessioni sono state chiuse.", + "TwoStep": "Verifica in due passaggi", + "TotpOn": "Attiva", + "TotpOff": "Non attiva", + "TotpRequired": "Obbligatoria", + "TotpIntro": "Oltre alla password, all'accesso viene chiesto un codice generato da un'app sul telefono (Google Authenticator, Microsoft Authenticator, Aegis...).", + "Enable": "Attiva la verifica", + "SetupText": "Aggiungi l'account nell'app con il codice segreto o con il collegamento, poi scrivi il primo codice che l'app mostra.", + "Enabled": "Verifica in due passaggi attivata", + "CodesOnce": "Conserva questi codici di recupero in un posto sicuro: ognuno sostituisce una volta il codice dell'app e non verranno mostrati di nuovo.", + "CodesDone": "Li ho conservati", + "CodesLeft": "Codici di recupero ancora utilizzabili: {0}.", + "ConfirmPassword": "Password attuale, per confermare", + "Renew": "Nuovi codici di recupero", + "Disable": "Disattiva la verifica", + "DisableTitle": "Disattivare la verifica in due passaggi?", + "DisableText": "All'accesso basterà la password. I codici di recupero non varranno più.", + "Disabled": "Verifica in due passaggi disattivata" + } + }, + "Catalog": { + "Title": "Catalogo componenti", + "Subtitle": "I componenti Kh con tutti gli stati. Pagina di sviluppo: i dati sono finti.", + "DevOnly": "Questa pagina esiste solo nell'ambiente di sviluppo.", + "OpenDocument": "Documento di prova", + "Document": "Documento di prova", + "Modified": "Modificato", + "TabPlaceholder": "Il contenuto di questa scheda arriva con i documenti veri.", + "Sections": { + "Fields": "Campi", + "Panels": "Pannelli", + "Navigation": "Navigazione", + "Windows": "Finestre", + "Toolbar": "Toolbar e intestazione" + }, + "Fields": { + "Document": "Documento", + "Conditions": "Condizioni", + "States": "Stati e verifica", + "Number": "Numero", + "NumberTaken": "Il numero è già usato da un altro documento (messaggio dal servizio).", + "Date": "Data", + "DateHint": "T oggi, F fine mese, + e - un giorno", + "Kind": "Tipo documento", + "KindInvoice": "TD01 · Fattura", + "KindCredit": "TD04 · Nota di credito", + "KindDeferred": "TD24 · Fattura differita", + "Party": "Cliente", + "PartyHint": "Scrivi codice o nome; F4 radar, Ctrl+Invio apre", + "Discount": "Sconto %", + "DiscountHint": "Da 0 a 100", + "Amount": "Importo", + "AmountHint": "Prova un calcolo: =10*3", + "Email": "E-mail", + "Split": "Scissione dei pagamenti", + "Stamp": "Bollo virtuale", + "Notes": "Note", + "Disabled": "Campo disattivato", + "DisabledValue": "Non modificabile", + "Validate": "Verifica", + "ServerError": "Errore dal servizio", + "ClearMessages": "Togli i messaggi", + "ReadOnly": "Sola lettura", + "Valid": "Tutti i campi sono validi", + "RadarOpened": "Qui si apre il radar dei clienti con il testo: {0}", + "PartyOpened": "Qui si apre la scheda di {0}", + "PartyCreated": "Creato il cliente {0}" + }, + "Panels": { + "Revenue": "Fatturato dell'anno", + "RevenueDetail": "Rispetto all'anno scorso: +8%", + "Collected": "Incassato", + "Expiring": "In scadenza", + "Overdue": "Scaduto", + "Strip": "Riepilogo", + "Documents": "Documenti", + "Taxable": "Imponibile", + "Panel": "Pannello", + "Link": "Vedi tutti", + "Draft": "Bozza", + "Sent": "Inviata", + "Paid": "Pagata", + "Issued": "Emessa", + "Payment": "Pagamento", + "PaymentValue": "RB 60 gg", + "PriceList": "Listino", + "PriceListValue": "Rivenditori", + "Credit": "Fido superato", + "Blocked": "Cliente bloccato", + "Filter": "Stato:", + "FilterValue": "Da pagare" + }, + "Navigation": { + "Tabs": "Schede", + "TabShown": "Scheda mostrata: {0}", + "Steps": "Passi", + "Step1": "Scegli i dati", + "Step1Detail": "Periodo e registri", + "Step2": "Controlla", + "Step2Detail": "Anteprima dei totali", + "Step3": "Conferma", + "Step3Detail": "Registrazione definitiva" + }, + "Windows": { + "Title": "Dialoghi, pannelli, conferme e avvisi", + "Dialog": "Dialogo", + "DialogText": "Un dialogo modale: Esc chiude, il fuoco entra nel primo campo.", + "Drawer": "Pannello laterale", + "DrawerText": "Un pannello laterale non modale: la pagina resta usabile.", + "DrawerService": "Pannello da codice", + "DrawerServiceText": "Aperto con DrawerService da qualunque punto del codice.", + "Confirm": "Conferma", + "Confirmed": "Confermato", + "Cancelled": "Annullato", + "ToastText": "Un avviso breve in basso a destra.", + "Toast": { + "Info": "Informazione", + "Success": "Fatto", + "Warning": "Attenzione", + "Error": "Errore" + } + }, + "Toolbar": { + "Intro": "Trascina il bordo destro del riquadro per stringere la toolbar: i comandi meno usati passano nel menu ⋯ senza andare a capo.", + "Issue": "Conferma ed emetti", + "Xml": "XML SDI", + "Post": "Contabilizza", + "Ddt": "Genera DDT", + "Final": "Rendi definitiva", + "Settings": "Impostazioni del documento", + "Clicked": "Comando: {0}" + }, + "Head": { + "Kind": "Fattura immediata · TD01", + "Section": "Sezionale", + "Total": "Totale documento", + "VatAmount": "IVA", + "Stamp": "Bollo", + "Address": "Via di Prova 1, 00100 Roma (RM)", + "Vat": "P.IVA 00000000000" + }, + "Lines": { + "Code": "Articolo", + "Description": "Descrizione", + "Quantity": "Quantità", + "Price": "Prezzo", + "Amount": "Importo" } } } diff --git a/src/Khaemhat.Web/Resources/it-IT/Shell.json b/src/Khaemhat.Web/Resources/it-IT/Shell.json index 622eaed..090554f 100644 --- a/src/Khaemhat.Web/Resources/it-IT/Shell.json +++ b/src/Khaemhat.Web/Resources/it-IT/Shell.json @@ -197,7 +197,8 @@ "Radar": "Radar", "PreviousRecord": "Record precedente", "NextRecord": "Record successivo", - "Balance": "Quadra la registrazione" + "Balance": "Quadra la registrazione", + "PageTab": "Scheda della pagina per posizione" }, "Error": { "Unexpected": "Si è verificato un errore imprevisto.", diff --git a/src/Khaemhat.Web/Resources/it-IT/Ui.json b/src/Khaemhat.Web/Resources/it-IT/Ui.json new file mode 100644 index 0000000..43557aa --- /dev/null +++ b/src/Khaemhat.Web/Resources/it-IT/Ui.json @@ -0,0 +1,67 @@ +{ + "Ui": { + "Validation": { + "Required": "Campo obbligatorio.", + "Number": "Non è un numero valido: usa la virgola per i decimali oppure un calcolo come =10*3.", + "Date": "Non è una data valida: scrivi gg/mm/aaaa, oppure T per oggi, F per fine mese.", + "Min": "Il valore minimo è {0}.", + "Max": "Il valore massimo è {0}.", + "DateMin": "La data non può essere prima del {0}.", + "DateMax": "La data non può essere dopo il {0}.", + "Summary": "Da correggere prima di salvare: {0}" + }, + "Date": { + "Placeholder": "gg/mm/aaaa" + }, + "Hotlink": { + "Search": "Cerca nel radar (F4)", + "Open": "Apri la scheda (Ctrl+Invio)", + "None": "Nessun risultato", + "Create": "Crea «{0}»", + "NotFound": "Il codice «{0}» non esiste." + }, + "Chip": { + "Remove": "Togli il filtro {0}" + }, + "Toolbar": { + "Label": "Comandi", + "More": "Altri comandi", + "Empty": "Nessun altro comando", + "New": "Nuovo", + "Save": "Salva", + "Cancel": "Annulla le modifiche", + "Delete": "Elimina", + "Duplicate": "Duplica", + "Print": "Stampa", + "Email": "Invia per e-mail", + "Export": "Genera file", + "Attachments": "Allegati", + "History": "Storico", + "Links": "Collegamenti", + "Radar": "Radar", + "Previous": "Precedente", + "Next": "Successivo" + }, + "Record": { + "TabsLabel": "Sezioni", + "Invalid": "Ci sono dati da correggere: vedi i messaggi accanto ai campi.", + "Saved": "Salvato", + "Deleted": "Eliminato", + "DiscardTitle": "Annullare le modifiche?", + "DiscardText": "Le modifiche non salvate andranno perse e verranno ricaricati i dati salvati.", + "Discard": "Annulla le modifiche", + "DeleteTitle": "Eliminare?", + "DeleteText": "L'eliminazione non si può annullare.", + "Tabs": { + "Lines": "Righe", + "Header": "Testata", + "Totals": "Totali", + "DueDates": "Scadenze", + "Notes": "Note", + "Attachments": "Allegati", + "Links": "Collegamenti", + "History": "Storico" + } + } + } +} diff --git a/src/Khaemhat.Web/Shell/Feedback.cs b/src/Khaemhat.Web/Shell/Feedback.cs index 8ca32a4..029853c 100644 --- a/src/Khaemhat.Web/Shell/Feedback.cs +++ b/src/Khaemhat.Web/Shell/Feedback.cs @@ -106,3 +106,53 @@ public sealed class DialogService pending?.TrySetResult(confirmed); } } + +/// A side panel opened from code (SPEC §10.7 DrawerService). +/// The title. +/// The icon. +/// The content. +/// The buttons, or . +/// A wider panel. +public sealed record DrawerRequest(string Title, string? Icon, Microsoft.AspNetCore.Components.RenderFragment Content, + Microsoft.AspNetCore.Components.RenderFragment? Footer = null, bool Wide = false); + +/// +/// Opens one side panel at a time from code; KhDrawerHost in the layout shows it. A page that owns its panel +/// can also write <KhDrawer Open="..."> directly. +/// +public sealed class DrawerService +{ + private TaskCompletionSource? _closed; + + /// Raised when the panel opens, closes or must be drawn again. + public event Action? Changed; + + /// The panel shown, or . + public DrawerRequest? Current { get; private set; } + + /// Shows a panel, closing the previous one. + /// The panel. + /// A task that ends when the panel is closed. + public Task ShowAsync(DrawerRequest request) + { + ArgumentNullException.ThrowIfNull(request); + _closed?.TrySetResult(); + _closed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + Current = request; + Changed?.Invoke(); + return _closed.Task; + } + + /// Closes the panel. + public void Close() + { + var closed = _closed; + _closed = null; + Current = null; + Changed?.Invoke(); + closed?.TrySetResult(); + } + + /// Draws the panel again after its data changed. + public void Refresh() => Changed?.Invoke(); +} diff --git a/src/Khaemhat.Web/Shell/KeyboardShortcuts.cs b/src/Khaemhat.Web/Shell/KeyboardShortcuts.cs index 37924c6..0f56b53 100644 --- a/src/Khaemhat.Web/Shell/KeyboardShortcuts.cs +++ b/src/Khaemhat.Web/Shell/KeyboardShortcuts.cs @@ -17,7 +17,11 @@ public enum ShortcutScope /// The combinations, as the browser script writes them (Ctrl+S, F9, Alt+W). /// The text key of the description. /// Who handles it. -public sealed record Shortcut(string Id, IReadOnlyList Keys, string TextKey, ShortcutScope Scope); +public sealed record Shortcut(string Id, IReadOnlyList Keys, string TextKey, ShortcutScope Scope) +{ + /// How the keys are shown when they are a series (Alt+1...9); shows . + public string? Display { get; init; } +} /// /// The shortcut table of SPEC §10.5.7. Browsers keep some combinations for themselves (Ctrl+W, Ctrl+Tab, Ctrl+N @@ -75,6 +79,9 @@ public static class KeyboardShortcuts /// Delete. public const string Delete = "page.delete"; + + /// Alt+1..9: the tab of the page by position; the page receives page.tab.N. + public const string PageTab = "page.tab"; } /// The table. @@ -95,6 +102,10 @@ public static class KeyboardShortcuts new(Commands.PreviousRecord, ["Ctrl+ArrowUp"], "Shell.Shortcuts.PreviousRecord", ShortcutScope.Page), new(Commands.NextRecord, ["Ctrl+ArrowDown"], "Shell.Shortcuts.NextRecord", ShortcutScope.Page), new(Commands.Balance, ["Ctrl+D"], "Shell.Shortcuts.Balance", ShortcutScope.Page), + new(Commands.PageTab, [.. Enumerable.Range(1, 9).Select(n => "Alt+" + n.ToString(System.Globalization.CultureInfo.InvariantCulture))], "Shell.Shortcuts.PageTab", ShortcutScope.Page) + { + Display = "Alt+1...9", + }, ]; /// The shortcut of a command. @@ -102,10 +113,32 @@ public static class KeyboardShortcuts /// The shortcut, or . public static Shortcut? Find(string id) => All.FirstOrDefault(s => s.Id == id); + /// Reads the tab number of a page.tab.N command. + /// The command received. + /// The tab number, 1 to 9. + /// Whether the command picks a tab. + public static bool TryGetTabNumber(string command, out int number) + { + number = 0; + return command is not null && command.StartsWith(Commands.PageTab + ".", StringComparison.Ordinal) + && int.TryParse(command.AsSpan(Commands.PageTab.Length + 1), System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out number) + && number is >= 1 and <= 9; + } + /// The first combination of a command, for tooltips (Ctrl+S). /// The command. /// The combination, or an empty string. public static string KeysOf(string id) => Find(id)?.Keys[0] ?? string.Empty; + + /// A combination as shown to people: arrows as symbols, Escape as Esc. + /// The combination, as in . + /// The text to show. + public static string Pretty(string? combo) => combo is null ? string.Empty : combo + .Replace("ArrowUp", "↑", StringComparison.Ordinal) + .Replace("ArrowDown", "↓", StringComparison.Ordinal) + .Replace("ArrowLeft", "←", StringComparison.Ordinal) + .Replace("ArrowRight", "→", StringComparison.Ordinal) + .Replace("Escape", "Esc", StringComparison.Ordinal); } /// @@ -147,7 +180,9 @@ public sealed class KeyboardShortcutService(IJSRuntime js) : IAsyncDisposable var handler = shortcut.Scope == ShortcutScope.Shell ? ShellPressed : PagePressed; if (handler is not null) { - await handler(shortcut.Id).ConfigureAwait(false); + // The tab shortcuts tell the page which tab: page.tab.3 for Alt+3. + var command = shortcut.Id == KeyboardShortcuts.Commands.PageTab ? shortcut.Id + "." + combo[^1] : shortcut.Id; + await handler(command).ConfigureAwait(false); } } diff --git a/src/Khaemhat.Web/Shell/ShellSession.cs b/src/Khaemhat.Web/Shell/ShellSession.cs index 47a7e35..4ea496b 100644 --- a/src/Khaemhat.Web/Shell/ShellSession.cs +++ b/src/Khaemhat.Web/Shell/ShellSession.cs @@ -129,6 +129,17 @@ public sealed class ShellSession( Changed?.Invoke(); } + /// Shows a new name in the shell after the user changed it from the profile. + /// The new name. + public void SetDisplayName(string? displayName) + { + if (!string.IsNullOrWhiteSpace(displayName) && displayName != DisplayName) + { + DisplayName = displayName; + Changed?.Invoke(); + } + } + /// Saves one setting of the user (open tabs, layouts...). /// The key. /// The value, or to remove it. diff --git a/src/Khaemhat.Web/Shell/TabService.cs b/src/Khaemhat.Web/Shell/TabService.cs index 420287b..fbd19a7 100644 --- a/src/Khaemhat.Web/Shell/TabService.cs +++ b/src/Khaemhat.Web/Shell/TabService.cs @@ -33,6 +33,9 @@ public sealed class KhTab /// The icon set by the page; uses the menu icon. public string? Icon { get; private set; } + /// Whether the tab is the one shown: page shortcuts act only there. + public bool IsActive => ReferenceEquals(_owner.Active, this); + /// Whether the page has unsaved changes (orange dot, warning on close). public bool IsModified { get; private set; } diff --git a/src/Khaemhat.Web/Ui/CatalogSamples.cs b/src/Khaemhat.Web/Ui/CatalogSamples.cs new file mode 100644 index 0000000..a3be00f --- /dev/null +++ b/src/Khaemhat.Web/Ui/CatalogSamples.cs @@ -0,0 +1,96 @@ +namespace Khaemhat.Web.Ui; + +/// A customer of the component catalog: fake data for the development page only. +/// The code. +/// The name. +public sealed record SampleParty(string Code, string Name); + +/// A line of the sample document of the component catalog. +public sealed class SampleLine +{ + /// The item code. + public string Code { get; set; } = string.Empty; + + /// The description. + public string Description { get; set; } = string.Empty; + + /// The quantity. + public decimal? Quantity { get; set; } + + /// The unit price. + public decimal? Price { get; set; } + + /// The amount. + public decimal Amount => Math.Round((Quantity ?? 0) * (Price ?? 0), 2, MidpointRounding.AwayFromZero); +} + +/// The sample document of the component catalog. +public sealed class SampleDocument +{ + /// The number. + public string Number { get; set; } = string.Empty; + + /// The date. + public DateOnly? Date { get; set; } + + /// The customer. + public SampleParty? Party { get; set; } + + /// The discount in percent. + public decimal? Discount { get; set; } + + /// The notes. + public string? Notes { get; set; } + + /// Whether it is issued (read-only). + public bool Issued { get; set; } + + /// The lines. + public List Lines { get; } = []; + + /// The taxable amount. + public decimal Taxable => Math.Round(Lines.Sum(l => l.Amount) * (1 - ((Discount ?? 0) / 100)), 2, MidpointRounding.AwayFromZero); + + /// The VAT at 22%. + public decimal Vat => Math.Round(Taxable * 0.22m, 2, MidpointRounding.AwayFromZero); + + /// The total. + public decimal Total => Taxable + Vat; +} + +/// Fake data for the component catalog (development only): no real company or person. +public static class CatalogSamples +{ + /// The customers. + public static IReadOnlyList Parties { get; } = + [ + new("C0001", "Esempio Uno Srl"), + new("C0002", "Esempio Due Spa"), + new("C0003", "Prova Tre Snc"), + new("C0010", "Cliente Dimostrativo"), + new("C0011", "Officine di Prova"), + new("C0020", "Studio Fittizio Associato"), + ]; + + /// Finds customers by code or name, like a hotlink search. + /// The text. + /// Cancellation. + /// At most eight customers. + public static Task> SearchAsync(string text, CancellationToken cancellationToken) + { + IReadOnlyList hits = [.. Parties.Where(p => p.Code.Contains(text, StringComparison.OrdinalIgnoreCase) || p.Name.Contains(text, StringComparison.OrdinalIgnoreCase)).Take(8)]; + return Task.FromResult(hits); + } + + /// A new sample document. + /// Today. + /// The document. + public static SampleDocument Document(DateOnly today) + { + var document = new SampleDocument { Number = "2026/000123", Date = today, Party = Parties[0], Discount = 0 }; + document.Lines.Add(new SampleLine { Code = "ART-001", Description = "Articolo di prova", Quantity = 10, Price = 12.5m }); + document.Lines.Add(new SampleLine { Code = "ART-002", Description = "Servizio dimostrativo", Quantity = 1, Price = 340m }); + document.Lines.Add(new SampleLine { Code = "ART-003", Description = "Materiale fittizio", Quantity = 4.5m, Price = 8.9m }); + return document; + } +} diff --git a/src/Khaemhat.Web/Ui/ItalianInput.cs b/src/Khaemhat.Web/Ui/ItalianInput.cs new file mode 100644 index 0000000..4bc557f --- /dev/null +++ b/src/Khaemhat.Web/Ui/ItalianInput.cs @@ -0,0 +1,293 @@ +using System.Globalization; + +namespace Khaemhat.Web.Ui; + +/// +/// Reads numbers typed the Italian way (SPEC §10.7 KhNumberBox): comma for decimals, point for thousands, and +/// an inline calculation when the text starts with = (=10*3, =(120+80)/4). A single point +/// followed by other than three digits is taken as a decimal point, because the numeric keypad types it. +/// +public static class ItalianNumber +{ + /// Reads a number or an inline calculation. + /// The text typed. + /// The value. + /// when the text is a number, a valid calculation, or empty (value ). + public static bool TryParse(string? text, out decimal? value) + { + value = null; + var trimmed = text?.Trim() ?? string.Empty; + if (trimmed.Length == 0) + { + return true; + } + + if (trimmed[0] == '=') + { + if (InlineCalculator.TryEvaluate(trimmed[1..], out var result)) + { + value = result; + return true; + } + + return false; + } + + if (TryParseNumber(trimmed.Replace(" ", string.Empty, StringComparison.Ordinal).Replace("€", string.Empty, StringComparison.Ordinal), out var number)) + { + value = number; + return true; + } + + return false; + } + + /// Formats a value for the field: thousands separator and exactly decimals. + /// The value. + /// The decimals shown. + /// The culture. + /// The text. + public static string Format(decimal? value, int decimals, CultureInfo culture) => + value is { } v ? v.ToString("N" + decimals.ToString(CultureInfo.InvariantCulture), culture) : string.Empty; + + /// Reads one number written with Italian separators. + /// The text, without spaces. + /// The value. + /// Whether it is a number. + internal static bool TryParseNumber(string text, out decimal value) + { + value = 0; + if (text.Length == 0 || text.Any(c => !(char.IsAsciiDigit(c) || c is '.' or ',' or '-' or '+'))) + { + return false; + } + + string normalized; + var points = text.Count(c => c == '.'); + if (text.Contains(',', StringComparison.Ordinal)) + { + // 1.234,56: points are thousands, the comma is the decimal separator. + if (text.Count(c => c == ',') > 1) + { + return false; + } + + normalized = text.Replace(".", string.Empty, StringComparison.Ordinal).Replace(',', '.'); + } + else if (points == 1 && !IsThousands(text)) + { + normalized = text; // 10.5 from the numeric keypad. + } + else + { + normalized = text.Replace(".", string.Empty, StringComparison.Ordinal); + } + + return decimal.TryParse(normalized, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out value); + } + + // "1.234" and "12.345": exactly three digits after the only point. + private static bool IsThousands(string text) + { + var index = text.IndexOf('.', StringComparison.Ordinal); + var after = text.Length - index - 1; + return after == 3 && index > 0 && text[..index].TrimStart('-', '+').Length is > 0 and <= 3; + } +} + +/// +/// The four operations with parentheses and unary minus, for the inline calculation of number fields. Numbers follow +/// . No variables, no functions: a small recursive-descent parser over decimals. +/// +public static class InlineCalculator +{ + /// Evaluates an expression. + /// The expression, without the leading =. + /// The result. + /// Whether the expression is valid (division by zero is not). + public static bool TryEvaluate(string expression, out decimal value) + { + ArgumentNullException.ThrowIfNull(expression); + var parser = new Parser(expression.Replace(" ", string.Empty, StringComparison.Ordinal).Replace('x', '*').Replace('X', '*').Replace(':', '/')); + try + { + value = parser.Expression(); + return parser.AtEnd; + } + catch (Exception ex) when (ex is FormatException or DivideByZeroException or OverflowException) + { + value = 0; + return false; + } + } + + private sealed class Parser(string text) + { + private int _position; + + public bool AtEnd => _position == text.Length; + + public decimal Expression() + { + var value = Term(); + while (!AtEnd && text[_position] is '+' or '-') + { + var op = text[_position++]; + var right = Term(); + value = op == '+' ? value + right : value - right; + } + + return value; + } + + private decimal Term() + { + var value = Factor(); + while (!AtEnd && text[_position] is '*' or '/') + { + var op = text[_position++]; + var right = Factor(); + value = op == '*' ? value * right : value / right; + } + + return value; + } + + private decimal Factor() + { + if (AtEnd) + { + throw new FormatException("Unexpected end."); + } + + switch (text[_position]) + { + case '-': + _position++; + return -Factor(); + case '+': + _position++; + return Factor(); + case '(': + _position++; + var inner = Expression(); + if (AtEnd || text[_position] != ')') + { + throw new FormatException("Missing parenthesis."); + } + + _position++; + return inner; + } + + var start = _position; + while (!AtEnd && (char.IsAsciiDigit(text[_position]) || text[_position] is '.' or ',')) + { + _position++; + } + + return start < _position && ItalianNumber.TryParseNumber(text[start.._position], out var number) + ? number + : throw new FormatException("Number expected."); + } + } +} + +/// +/// Reads dates typed the Italian way (SPEC §10.7 KhDateBox): gg/mm/aaaa and its short forms (5, +/// 5/3, 050326, 5-3-26), T today, F end of month, +/- one day, +/// +7/-30 days from the current value (or today). +/// +public static class ItalianDate +{ + private static readonly char[] Separators = ['/', '-', '.', ' ']; + + /// Reads a date. + /// The text typed. + /// Today. + /// The value before the change, the base of F and of relative days. + /// The date; when the text is empty. + /// Whether the text is a date or empty. + public static bool TryParse(string? text, DateOnly today, DateOnly? current, out DateOnly? value) + { + value = null; + var trimmed = text?.Trim().ToUpperInvariant() ?? string.Empty; + if (trimmed.Length == 0) + { + return true; + } + + var baseDate = current ?? today; + switch (trimmed) + { + case "T" or "O": + value = today; + return true; + case "F": + value = new DateOnly(baseDate.Year, baseDate.Month, DateTime.DaysInMonth(baseDate.Year, baseDate.Month)); + return true; + case "I": + value = new DateOnly(baseDate.Year, baseDate.Month, 1); + return true; + case "+": + value = baseDate.AddDays(1); + return true; + case "-": + value = baseDate.AddDays(-1); + return true; + } + + if (trimmed[0] is '+' or '-' && int.TryParse(trimmed, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var days) && Math.Abs(days) <= 36_500) + { + value = baseDate.AddDays(days); + return true; + } + + var parts = trimmed.Split(Separators, StringSplitOptions.RemoveEmptyEntries); + if (parts.Any(p => !p.All(char.IsAsciiDigit))) + { + return false; + } + + if (parts.Length == 1) + { + parts = parts[0].Length switch + { + <= 2 => [parts[0]], + 4 => [parts[0][..2], parts[0][2..]], + 6 => [parts[0][..2], parts[0][2..4], parts[0][4..]], + 8 => [parts[0][..2], parts[0][2..4], parts[0][4..]], + _ => [], + }; + } + + if (parts.Length is 0 or > 3 || parts.Any(p => p.Length > 4)) + { + return false; + } + + var day = int.Parse(parts[0], CultureInfo.InvariantCulture); + var month = parts.Length > 1 ? int.Parse(parts[1], CultureInfo.InvariantCulture) : today.Month; + var year = parts.Length > 2 ? YearOf(parts[2], today) : today.Year; + if (year is < 1900 or > 2999 || month is < 1 or > 12 || day < 1 || day > DateTime.DaysInMonth(year, month)) + { + return false; + } + + value = new DateOnly(year, month, day); + return true; + } + + // Two digits: this century, unless that is more than twenty years ahead (birth dates, old documents). + private static int YearOf(string text, DateOnly today) + { + var year = int.Parse(text, CultureInfo.InvariantCulture); + if (text.Length > 2) + { + return year; + } + + var century = today.Year / 100 * 100; + return century + year > today.Year + 20 ? century - 100 + year : century + year; + } +} diff --git a/src/Khaemhat.Web/Ui/KhForms.cs b/src/Khaemhat.Web/Ui/KhForms.cs new file mode 100644 index 0000000..9ef19da --- /dev/null +++ b/src/Khaemhat.Web/Ui/KhForms.cs @@ -0,0 +1,311 @@ +using System.Globalization; +using Khaemhat.Application.Localization; +using Microsoft.AspNetCore.Components; + +namespace Khaemhat.Web.Ui; + +/// One message of the validation: the field it belongs to (or none for the whole form) and the text. +/// The field name, or . +/// The label of the field, shown in the summary. +/// The element to focus from the summary. +/// The message. +public sealed record KhValidationMessage(string? Field, string? Label, string? InputId, string Message); + +/// +/// The messages of a form (SPEC §10.5.6: next to the field and in a summary). The fields add theirs when the form is +/// submitted; the page adds the ones the services return (), then the form shows them. +/// +public sealed class KhValidation +{ + private readonly List _messages = []; + + /// Raised when the messages change. + public event Action? Changed; + + /// Every message, in the order added. + public IReadOnlyList Messages => _messages; + + /// Whether there are no messages. + public bool IsValid => _messages.Count == 0; + + /// Adds a message. + /// The field name, or for the whole form. + /// The message. + public void Add(string? field, string message) + { + ArgumentException.ThrowIfNullOrWhiteSpace(message); + _messages.Add(new KhValidationMessage(field, null, null, message)); + Changed?.Invoke(); + } + + /// The messages of a field. + /// The field name. + /// The messages. + public IReadOnlyList For(string field) => [.. _messages.Where(m => m.Field == field).Select(m => m.Message)]; + + /// Removes the messages of a field, when the user changes it. + /// The field name. + public void ClearField(string field) + { + if (_messages.RemoveAll(m => m.Field == field) > 0) + { + Changed?.Invoke(); + } + } + + /// Removes every message. + public void Clear() + { + if (_messages.Count > 0) + { + _messages.Clear(); + Changed?.Invoke(); + } + } + + internal void AddResolved(KhValidationMessage message) => _messages.Add(message); + + internal void Notify() => Changed?.Invoke(); +} + +/// A field that takes part in the validation of a KhForm. +public interface IKhField +{ + /// The name of the field: the key of its messages. + string FieldName { get; } + + /// The label, shown in the summary. + string? Label { get; } + + /// The id of the input element. + string InputId { get; } + + /// Checks the value: required, readable, field rule. + /// The messages; empty when valid. + IEnumerable Validate(); +} + +/// What a KhForm gives its fields: the messages, read-only state and the list of fields. +public sealed class KhFormContext +{ + private readonly List _fields = []; + + /// Creates the context. + /// The messages of the form. + public KhFormContext(KhValidation validation) => Validation = validation; + + /// The messages. + public KhValidation Validation { get; } + + /// Every field is read-only (an issued invoice, SPEC §10.5.6). + public bool ReadOnly { get; internal set; } + + /// Adds a field. + /// The field. + public void Register(IKhField field) => _fields.Add(field); + + /// Removes a field. + /// The field. + public void Unregister(IKhField field) => _fields.Remove(field); + + /// Checks every field and puts the messages in . + /// Whether the form is valid. + public bool Validate() + { + Validation.Clear(); + foreach (var field in _fields) + { + foreach (var message in field.Validate()) + { + Validation.AddResolved(new KhValidationMessage(field.FieldName, field.Label, field.InputId, message)); + } + } + + Validation.Notify(); + return Validation.IsValid; + } + + /// The label and input of a field, to complete the messages the page added. + /// The field name. + /// The field, or . + public IKhField? Find(string? name) => name is null ? null : _fields.FirstOrDefault(f => f.FieldName == name); +} + +/// +/// The base of the input components (KhTextBox, KhNumberBox, KhDateBox...): value binding, label, +/// hint, required mark, read-only state from the form, messages next to the field and validation. +/// +/// The type of the value. +public abstract class KhInputBase : ComponentBase, IKhField, IDisposable +{ + private static int _next; + private KhFormContext? _registered; + + /// The texts (components also get them as T from _Imports.razor). + [Inject] + protected ITexts Texts { get; set; } = default!; + + /// The value. + [Parameter] + public TValue? Value { get; set; } + + /// Called when the user changes the value. + [Parameter] + public EventCallback ValueChanged { get; set; } + + /// The label above the field. + [Parameter] + public string? Label { get; set; } + + /// The name of the field for the messages; defaults to the label. + [Parameter] + public string? Name { get; set; } + + /// A suggestion under the field. + [Parameter] + public string? Hint { get; set; } + + /// The value is mandatory: asterisk and check. + [Parameter] + public bool Required { get; set; } + + /// The field cannot be changed. + [Parameter] + public bool ReadOnly { get; set; } + + /// The field is disabled. + [Parameter] + public bool Disabled { get; set; } + + /// The columns of the 12-column grid the field takes (SPEC §10.5.4). + [Parameter] + public int Span { get; set; } = 6; + + /// An extra rule: returns a message, or when the value is good. + [Parameter] + public Func? Rule { get; set; } + + /// The id of the input; generated when not given. + [Parameter] + public string? Id { get; set; } + + /// Other attributes for the input element. + [Parameter(CaptureUnmatchedValues = true)] + public IReadOnlyDictionary? Attributes { get; set; } + + /// The form the field is in. + [CascadingParameter] + public KhFormContext? Form { get; set; } + + /// + public string FieldName => Name ?? Label ?? InputId; + + /// + public string InputId { get; private set; } = string.Empty; + + /// Whether the user may change the value. + protected bool IsReadOnly => ReadOnly || Form?.ReadOnly == true; + + /// The message of a text that could not be read (a date such as 31/02), until the user fixes it. + protected string? ParseError { get; set; } + + /// The messages shown next to the field. + protected IReadOnlyList Messages => + ParseError is not null ? [ParseError] : Form?.Validation.For(FieldName) ?? []; + + /// The id of the hint and messages, for aria-describedby. + protected string DescribedBy => InputId + "-d"; + + /// The aria-invalid value: "true" with messages, absent otherwise (a bare attribute is not "true"). + protected string? AriaInvalid => Messages.Count > 0 ? "true" : null; + + /// The aria-required value. + protected string? AriaRequired => Required ? "true" : null; + + /// The CSS classes of the input: error state. + protected string InputClass => Messages.Count > 0 ? "in err" : "in"; + + /// + protected override void OnParametersSet() + { + if (InputId.Length == 0) + { + InputId = Id ?? "kh-i" + Interlocked.Increment(ref _next).ToString(CultureInfo.InvariantCulture); + } + + if (!ReferenceEquals(_registered, Form)) + { + _registered?.Unregister(this); + Form?.Register(this); + _registered = Form; + } + } + + /// Whether the value counts as empty for . + /// The value. + /// when empty. + protected virtual bool IsEmpty(TValue? value) => value is null || (value is string s && string.IsNullOrWhiteSpace(s)); + + /// + public virtual IEnumerable Validate() + { + if (ParseError is not null) + { + yield return ParseError; + yield break; + } + + if (Required && IsEmpty(Value)) + { + yield return Texts["Ui.Validation.Required"]; + yield break; + } + + if (Rule?.Invoke(Value) is { } message) + { + yield return message; + } + } + + /// Changes the value, tells the parent and clears the messages of the field. + /// The new value. + /// A task. + protected async Task SetValueAsync(TValue? value) + { + ParseError = null; + Form?.Validation.ClearField(FieldName); + if (EqualityComparer.Default.Equals(Value!, value!)) + { + return; + } + + Value = value; + await ValueChanged.InvokeAsync(value); + } + + /// + public void Dispose() + { + _registered?.Unregister(this); + GC.SuppressFinalize(this); + } +} + +/// How a KhForm arranges its children. +public enum KhFormLayout +{ + /// The 12-column grid of fields (.form). + Grid = 0, + + /// Groups of fields side by side (.fgroups), each a KhFieldGroup. + Groups = 1, + + /// The grid without padding, inside a panel that already has it. + Plain = 2, +} + +/// A choice of a KhSelect. +/// The type of the value. +/// The value. +/// The text shown. +public sealed record KhOption(TValue Value, string Text); diff --git a/src/Khaemhat.Web/Ui/KhModels.cs b/src/Khaemhat.Web/Ui/KhModels.cs new file mode 100644 index 0000000..deda85b --- /dev/null +++ b/src/Khaemhat.Web/Ui/KhModels.cs @@ -0,0 +1,104 @@ +namespace Khaemhat.Web.Ui; + +/// The colour of a tile, badge, chip or value: the meaning, not the hue (the theme picks the hue). +public enum KhTone +{ + /// Neutral. + Neutral = 0, + + /// The accent of the user. + Accent = 1, + + /// Information. + Info = 2, + + /// Good: paid, sent, done. + Ok = 3, + + /// Attention: expiring, to check. + Warning = 4, + + /// Problem: overdue, rejected. + Error = 5, +} + +/// One value of a KhStrip. +/// The label above. +/// The value. +/// The colour of the value. +public sealed record KhStat(string Label, string Value, KhTone Tone = KhTone.Neutral); + +/// One tab of a KhTabs. +/// The identifier (also the query value when the tabs are links). +/// The icon. +/// The text. +/// A counter after the text: attachments (3), links (2). +public sealed record KhTabItem(string Id, string Icon, string Text, int? Count = null); + +/// One step of a KhSteps or KhVSteps. +/// The title. +/// The line under the title (vertical steps only). +public sealed record KhStep(string Title, string? Detail = null); + +/// Where a toolbar command sits. +public enum ToolbarKind +{ + /// An icon button (32x32, tooltip with name and shortcut). + Icon = 0, + + /// A contextual action of the document: icon and a short label, at most four on the bar. + Action = 1, + + /// Only in the "⋯" menu. + Menu = 2, +} + +/// +/// A command of a KhIconToolbar (SPEC §10.4). Commands of the same stand together with a +/// separator between groups; puts them on the right (radar, previous, next). When the bar is too +/// narrow, the commands with the highest move to the "⋯" menu first. +/// +/// The identifier. +/// The icon. +/// The name: tooltip and accessible name of icons, label of actions and menu entries. +public sealed record ToolbarItem(string Id, string Icon, string Text) +{ + /// The kind. + public ToolbarKind Kind { get; init; } + + /// The shortcut shown in the tooltip, such as Ctrl+S. + public string? Shortcut { get; init; } + + /// What the command does. + public Func? OnClick { get; init; } + + /// An address to open instead of . + public string? Href { get; init; } + + /// The main command (Save, the main action): filled with the accent. + public bool Primary { get; init; } + + /// A destructive command. + public bool Danger { get; init; } + + /// The command cannot be used now. + public bool Disabled { get; init; } + + /// A toggled command (the radar is open). + public bool Active { get; init; } + + /// A counter badge (attachments, links). + public int? Count { get; init; } + + /// The group; a separator stands between groups. + public int Group { get; init; } + + /// On the right side of the bar. + public bool End { get; init; } + + /// Who leaves first when space is short: higher first; 0 never leaves. + public int Priority { get; init; } = 1; + + /// The colour of a contextual action. + public KhTone Tone { get; init; } +} diff --git a/src/Khaemhat.Web/Ui/RecordPages.cs b/src/Khaemhat.Web/Ui/RecordPages.cs new file mode 100644 index 0000000..661d22a --- /dev/null +++ b/src/Khaemhat.Web/Ui/RecordPages.cs @@ -0,0 +1,419 @@ +using Khaemhat.Application.Localization; +using Khaemhat.Web.Components.Ui; +using Khaemhat.Web.Shell; +using Microsoft.AspNetCore.Components; + +namespace Khaemhat.Web.Ui; + +/// What KhRecordLayout needs from a record page. +public interface IRecordPage +{ + /// The commands of the toolbar. + IReadOnlyList Toolbar { get; } + + /// The tabs. + IReadOnlyList Tabs { get; } + + /// The tab shown. + string ActiveTab { get; } + + /// Every field is read-only. + bool IsReadOnly { get; } + + /// The messages of the form. + KhValidation Validation { get; } + + /// Shows another tab. + /// The tab id. + /// A task. + Task ShowTabAsync(string id); +} + +/// +/// The base of the pages that edit one record (SPEC §10.5): toolbar with the standard commands, tabs, modified state +/// shown on the shell tab, validation, confirmation before discarding or deleting, and the page shortcuts of §10.5.7 +/// (Ctrl+S, Ctrl+N, Ctrl+P, Ctrl+Canc, F9, Ctrl+Up/Down), active only while the page is the shown tab. +/// +/// The record. +public abstract class RecordPage : ComponentBase, IRecordPage, IDisposable + where TRecord : class +{ + private string? _activeTab; + + /// The texts. + [Inject] + protected ITexts Texts { get; set; } = default!; + + /// The page shortcuts. + [Inject] + protected KeyboardShortcutService Keys { get; set; } = default!; + + /// Confirmations. + [Inject] + protected DialogService Dialogs { get; set; } = default!; + + /// Short messages. + [Inject] + protected ToastService Toasts { get; set; } = default!; + + /// Navigation. + [Inject] + protected NavigationManager Navigation { get; set; } = default!; + + /// The shell tab that holds the page. + [CascadingParameter] + public KhTab? Tab { get; set; } + + /// The record shown. + protected TRecord? Record { get; set; } + + /// + public KhValidation Validation { get; } = new(); + + /// The form of the page, to check the fields before saving (@ref it). + protected KhForm? Form { get; set; } + + /// Whether there are unsaved changes. + protected bool IsModified { get; private set; } + + /// + public virtual bool IsReadOnly => false; + + /// Whether the record is new (Delete is not offered). + protected virtual bool IsNew => false; + + /// + public abstract IReadOnlyList Tabs { get; } + + /// + public string ActiveTab => _activeTab ?? (Tabs.Count > 0 ? Tabs[0].Id : string.Empty); + + /// + public IReadOnlyList Toolbar => [.. StandardCommands(), .. ContextActions(), .. MenuCommands()]; + + /// The address of a new record; hides "Nuovo". + protected virtual string? NewUrl => null; + + /// Whether the record may be deleted. + protected virtual bool CanDelete => !IsNew && !IsReadOnly; + + /// The number of attachments, shown on the toolbar; hides the command. + protected virtual int? AttachmentCount => null; + + /// Whether there is a previous and next record (navigation with Ctrl+Up/Down). + protected virtual bool CanMove => false; + + /// Marks the record as changed: the shell tab shows the orange dot. + protected void MarkModified() + { + if (!IsModified) + { + IsModified = true; + Tab?.SetModified(true); + } + } + + /// Marks the record as saved. + protected void MarkSaved() + { + IsModified = false; + Tab?.SetModified(false); + } + + /// + public Task ShowTabAsync(string id) + { + _activeTab = id; + StateHasChanged(); + return Task.CompletedTask; + } + + /// Saves: checks the form, calls , reports the outcome. + /// Whether it was saved. + public async Task SaveAsync() + { + if (IsReadOnly) + { + return false; + } + + if (Form is not null && !Form.Validate()) + { + Toasts.Show(ToastKind.Error, Texts["Ui.Record.Invalid"]); + return false; + } + + if (!await SaveCoreAsync()) + { + Toasts.Show(ToastKind.Error, Texts["Ui.Record.Invalid"]); + StateHasChanged(); + return false; + } + + MarkSaved(); + Toasts.Show(ToastKind.Success, Texts["Ui.Record.Saved"]); + StateHasChanged(); + return true; + } + + /// Discards the changes after a confirmation and reloads the record. + /// A task. + public async Task CancelAsync() + { + if (IsModified && !await Dialogs.ConfirmAsync(new(Texts["Ui.Record.DiscardTitle"], Texts["Ui.Record.DiscardText"], + Texts["Ui.Record.Discard"], Texts["Common.Cancel"], Danger: true))) + { + return; + } + + Validation.Clear(); + await ReloadAsync(); + MarkSaved(); + StateHasChanged(); + } + + /// Deletes the record after a confirmation. + /// A task. + public async Task DeleteAsync() + { + if (!CanDelete || !await Dialogs.ConfirmAsync(new(Texts["Ui.Record.DeleteTitle"], Texts["Ui.Record.DeleteText"], + Texts["Ui.Toolbar.Delete"], Texts["Common.Cancel"], Danger: true))) + { + return; + } + + await DeleteCoreAsync(); + MarkSaved(); + Toasts.Show(ToastKind.Success, Texts["Ui.Record.Deleted"]); + } + + /// Opens a new record. + /// A task. + public Task NewAsync() + { + if (NewUrl is not null) + { + Navigation.NavigateTo(NewUrl); + } + + return Task.CompletedTask; + } + + /// Writes the record; adds messages to and returns when refused. + /// Whether it was saved. + protected abstract Task SaveCoreAsync(); + + /// Reads the record again, dropping the changes. + /// A task. + protected abstract Task ReloadAsync(); + + /// Deletes the record. + /// A task. + protected virtual Task DeleteCoreAsync() => Task.CompletedTask; + + /// Prints (Ctrl+P): by default the print preview of the browser. + /// A task. + protected virtual Task PrintAsync() => Task.CompletedTask; + + /// Opens the radar of the records of this kind (F9). + /// A task. + protected virtual Task RadarAsync() => Task.CompletedTask; + + /// Shows the previous (-1) or next (+1) record. + /// The direction. + /// A task. + protected virtual Task MoveAsync(int direction) => Task.CompletedTask; + + /// Opens the attachments. + /// A task. + protected virtual Task AttachmentsAsync() => Task.CompletedTask; + + /// The contextual actions of the record (Conferma ed emetti, Contabilizza...). + /// The actions. + protected virtual IEnumerable ContextActions() => []; + + /// The commands that live only in the "⋯" menu. + /// The commands. + protected virtual IEnumerable MenuCommands() => []; + + /// The standard commands of SPEC §10.4. + /// The commands. + protected virtual IEnumerable StandardCommands() + { + if (NewUrl is not null) + { + yield return Command("new", "plus", "Ui.Toolbar.New", KeyboardShortcuts.Commands.New, NewAsync) with { Group = 0, Priority = 0 }; + } + + yield return Command("save", "save", "Ui.Toolbar.Save", KeyboardShortcuts.Commands.Save, SaveAsync) with + { + Group = 0, Priority = 0, Primary = IsModified, Disabled = IsReadOnly, + }; + yield return Command("cancel", "undo", "Ui.Toolbar.Cancel", null, CancelAsync) with { Group = 0, Disabled = !IsModified, Priority = 2 }; + yield return Command("delete", "trash", "Ui.Toolbar.Delete", KeyboardShortcuts.Commands.Delete, DeleteAsync) with + { + Group = 0, Danger = true, Disabled = !CanDelete, Priority = 3, + }; + yield return Command("print", "printer", "Ui.Toolbar.Print", KeyboardShortcuts.Commands.Print, PrintAsync) with { Group = 1, Priority = 4 }; + if (AttachmentCount is { } attachments) + { + yield return Command("attachments", "paperclip", "Ui.Toolbar.Attachments", null, AttachmentsAsync) with { Group = 2, Count = attachments, Priority = 5 }; + } + + yield return Command("radar", "radar", "Ui.Toolbar.Radar", KeyboardShortcuts.Commands.Radar, RadarAsync) with { End = true, Priority = 6 }; + if (CanMove) + { + yield return Command("previous", "chevron-up", "Ui.Toolbar.Previous", KeyboardShortcuts.Commands.PreviousRecord, () => MoveAsync(-1)) with { End = true, Priority = 7 }; + yield return Command("next", "chevron-down", "Ui.Toolbar.Next", KeyboardShortcuts.Commands.NextRecord, () => MoveAsync(1)) with { End = true, Priority = 7 }; + } + } + + /// A command with its text and the keys of a shortcut. + /// The id. + /// The icon. + /// The text key. + /// The shortcut command, or . + /// What it does. + /// The command. + protected ToolbarItem Command(string id, string icon, string textKey, string? shortcut, Func onClick) => + new(id, icon, Texts[textKey]) { Shortcut = shortcut is null ? null : KeyboardShortcuts.KeysOf(shortcut), OnClick = onClick }; + + /// + protected override void OnInitialized() => Keys.PagePressed += OnShortcutAsync; + + private async Task OnShortcutAsync(string command) + { + if (Tab is not null && !Tab.IsActive) + { + return; + } + + Func? action = command switch + { + KeyboardShortcuts.Commands.Save => SaveAsync, + KeyboardShortcuts.Commands.New when NewUrl is not null => NewAsync, + KeyboardShortcuts.Commands.Print => PrintAsync, + KeyboardShortcuts.Commands.Delete when CanDelete => DeleteAsync, + KeyboardShortcuts.Commands.Radar => RadarAsync, + KeyboardShortcuts.Commands.PreviousRecord when CanMove => () => MoveAsync(-1), + KeyboardShortcuts.Commands.NextRecord when CanMove => () => MoveAsync(1), + _ => null, + }; + if (action is not null) + { + await InvokeAsync(async () => + { + await action(); + StateHasChanged(); + }); + } + } + + /// + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + /// Releases the shortcut subscription. + /// Called from . + protected virtual void Dispose(bool disposing) + { + if (disposing) + { + Keys.PagePressed -= OnShortcutAsync; + } + } +} + +/// +/// The base of document pages (SPEC §10.5.3): the first tab is Righe and the page opens there; then Testata, +/// Totali, Scadenze, Note, Allegati, Collegamenti, Storico as the document needs. +/// +/// The document. +/// A line of the document. +public abstract class DocumentPage : RecordPage + where TDocument : class +{ + /// The standard tab ids of a document. + public static class TabIds + { + /// Lines (first). + public const string Lines = "righe"; + + /// Header fields. + public const string Header = "testata"; + + /// Totals. + public const string Totals = "totali"; + + /// Due dates. + public const string DueDates = "scadenze"; + + /// Notes. + public const string Notes = "note"; + + /// Attachments. + public const string Attachments = "allegati"; + + /// Links to other documents. + public const string Links = "collegamenti"; + + /// History. + public const string History = "storico"; + } + + /// The lines of the document. + protected abstract IList Lines { get; } + + /// The standard tabs, Righe first, with the counters given. + /// The attachments, or to leave the tab out. + /// The linked documents, or to leave the tab out. + /// The tabs. + protected IReadOnlyList StandardTabs(int? attachments = null, int? links = null) + { + var tabs = new List + { + new(TabIds.Lines, "list", Texts["Ui.Record.Tabs.Lines"], Lines.Count), + new(TabIds.Header, "file", Texts["Ui.Record.Tabs.Header"]), + new(TabIds.Totals, "euro", Texts["Ui.Record.Tabs.Totals"]), + new(TabIds.DueDates, "calendar", Texts["Ui.Record.Tabs.DueDates"]), + new(TabIds.Notes, "edit", Texts["Ui.Record.Tabs.Notes"]), + }; + if (attachments is { } a) + { + tabs.Add(new(TabIds.Attachments, "paperclip", Texts["Ui.Record.Tabs.Attachments"], a)); + } + + if (links is { } l) + { + tabs.Add(new(TabIds.Links, "link", Texts["Ui.Record.Tabs.Links"], l)); + } + + tabs.Add(new(TabIds.History, "history", Texts["Ui.Record.Tabs.History"])); + return tabs; + } +} + +/// +/// The base of master data pages (SPEC §10.5.3): customers, suppliers, items. The first tab is the main data; the +/// header shows identity, contacts, condition chips and KPIs. +/// +/// The record. +public abstract class MasterDataPage : RecordPage + where TRecord : class +{ + /// The standard tab ids of a master record. + public static class TabIds + { + /// Main data (first). + public const string Main = "dati"; + + /// Notes and attachments. + public const string Notes = "note"; + + /// History. + public const string History = "storico"; + } +} diff --git a/src/Khaemhat.Web/wwwroot/app.css b/src/Khaemhat.Web/wwwroot/app.css index 40c138f..1edff91 100644 --- a/src/Khaemhat.Web/wwwroot/app.css +++ b/src/Khaemhat.Web/wwwroot/app.css @@ -74,6 +74,12 @@ button.sw { text-align: left; color: var(--kh-text); } padding: 0 8px; font: inherit; } .kh-inset { margin: 0 14px 14px; } .kh-h2 { font-size: var(--kh-fs-lg); font-weight: 600; margin: 6px 0 0; } +/* Profile forms (issue #31): actions at the end of a form, read-only facts. */ +.form .kh-formactions, .kh-formactions { display: flex; gap: 8px; justify-content: flex-end; flex-wrap: wrap; } +.kh-facts { display: grid; grid-template-columns: max-content 1fr; gap: 6px 14px; margin: 0; padding: 12px 14px; font-size: 12.5px; } +.kh-facts dt { color: var(--kh-text-2); } +.kh-facts dd { margin: 0; } +.fgroup .pb > p:first-child { margin-top: 0; } .kh-table { width: 100%; border-collapse: collapse; font-size: 12.5px; } .kh-table th { text-align: left; font-weight: 600; color: var(--kh-text-2); font-size: var(--kh-fs-sm); padding: 6px 10px; border-bottom: 1px solid var(--kh-border-strong); } .kh-table td { padding: 7px 10px; border-bottom: 1px solid var(--kh-border); vertical-align: middle; } diff --git a/src/Khaemhat.Web/wwwroot/css/interactive.css b/src/Khaemhat.Web/wwwroot/css/interactive.css index 7d2c61b..39def1d 100644 --- a/src/Khaemhat.Web/wwwroot/css/interactive.css +++ b/src/Khaemhat.Web/wwwroot/css/interactive.css @@ -140,3 +140,81 @@ a.tab { text-decoration: none; } @media (max-width: 899px) { .gsearch .ph { display: none; } } + +/* ---- Kh components (issues #27, #29) ---- */ +/* Form fields */ +input.in.num, .f .in input.num { text-align: right; font-variant-numeric: tabular-nums; } +input.in.mono { font-family: var(--kh-mono); font-size: 12px; font-weight: 600; color: var(--kh-accent-text); } +.kh-datebox svg.i { color: var(--kh-text-3); flex: none; } +.kh-check { height: auto; min-height: 30px; cursor: pointer; } +.kh-check input { accent-color: var(--kh-accent); width: 15px; height: 15px; margin: 0; } +.kh-switch { display: inline-flex; align-items: center; gap: 8px; height: 30px; border: 0; background: none; padding: 0; font: inherit; color: var(--kh-text); cursor: pointer; } +.kh-switch:disabled { opacity: .55; cursor: default; } +.kh-vsum { display: flex; gap: 10px; align-items: flex-start; padding: 10px 12px; border-radius: var(--kh-radius-lg); background: var(--kh-err-soft); color: var(--kh-err-text); font-size: 12.5px; } +.kh-vsum.wide { grid-column: 1 / -1; } +.kh-vsum ul { margin: 4px 0 0; padding-left: 18px; } +.kh-vsum:focus { outline: 2px solid var(--kh-err); outline-offset: 2px; } +.kh-link { border: 0; background: none; padding: 0; font: inherit; color: inherit; text-decoration: underline; cursor: pointer; text-align: left; } + +/* Hotlink */ +.kh-hotlink { position: relative; } +.kh-hotlink .in input.code { flex: none; width: 10ch; } +.kh-lk { border: 0; background: none; padding: 2px; color: var(--kh-text-3); cursor: pointer; border-radius: 4px; display: grid; place-items: center; } +.kh-lk:hover { color: var(--kh-accent-text); background: var(--kh-surface-3); } +.kh-hits { position: absolute; top: calc(100% + 3px); left: 0; right: 0; z-index: 15; list-style: none; margin: 0; padding: 4px; max-height: 260px; overflow: auto; + background: var(--kh-surface); border: 1px solid var(--kh-border); border-radius: 8px; box-shadow: var(--kh-shadow-lg); } +.kh-hits li { display: flex; gap: 10px; align-items: center; padding: 6px 8px; border-radius: 6px; font-size: 12.5px; cursor: pointer; white-space: nowrap; overflow: hidden; } +.kh-hits li .code { font: 600 12px var(--kh-mono); color: var(--kh-accent-text); min-width: 8ch; } +.kh-hits li .desc { overflow: hidden; text-overflow: ellipsis; color: var(--kh-text-2); } +.kh-hits li.on, .kh-hits li:hover { background: var(--kh-accent-soft); } +.kh-hits li.none { color: var(--kh-text-3); cursor: default; background: none; } +.kh-hits li.new { color: var(--kh-accent-text); border-top: 1px solid var(--kh-border); margin-top: 3px; } + +/* Display */ +.kh-money { font-variant-numeric: tabular-nums; white-space: nowrap; } +.kh-money.neg { color: var(--kh-err); } +a.kh-tilelink { color: inherit; text-decoration: none; } +a.kh-tilelink:hover { border-color: var(--kh-accent); } +.kh-chipx { border: 0; background: none; padding: 0; color: inherit; display: grid; place-items: center; cursor: pointer; } +.kh-steps { list-style: none; margin: 0; } +.steps.kh-steps { padding: 4px 0; } +.vsteps.kh-steps { padding: 6px 0; } +button.tab { border: 0; border-bottom: 2px solid transparent; background: none; font: inherit; cursor: pointer; } +button.tab.active { border-bottom-color: var(--kh-accent); } + +/* Dialog and drawer */ +.dialog.kh-sm { width: 420px; } .dialog.kh-md { width: 640px; } .dialog.kh-lg { width: 860px; } +.dialog .db { max-height: calc(100vh - 220px); overflow: auto; } +.drawer.wide { width: 560px; } +.kh-close { width: 28px; height: 28px; background: none; cursor: pointer; } +@media (max-width: 700px) { .drawer, .drawer.wide { width: 100vw; } } + +/* Toolbar */ +.kh-toolbar { flex-wrap: nowrap; min-width: 0; } +.kh-toolbar .grp { flex: none; } +.kh-toolbar [data-ovf-hidden] { display: none !important; } +button.ib { background: none; padding: 0; cursor: pointer; font: inherit; } +button.ib.primary { background: var(--kh-accent); } +.ib:disabled, .ib.disabled { opacity: .35; cursor: default; pointer-events: none; } +button.ctx { cursor: pointer; } +.ctx:disabled { opacity: .45; cursor: default; } +.kh-morewrap { position: relative; flex: none; } +.kh-catch { position: fixed; inset: 0; z-index: 19; } +.kh-moremenu { min-width: 240px; } +.popmenu .mi.danger, .popmenu .mi.danger svg.i { color: var(--kh-err); } +.popmenu .mi:disabled { opacity: .45; } + +/* Document header and record pages */ +.kh-min0 { min-width: 0; } +.kh-ellipsis { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.kh-record { display: flex; flex-direction: column; gap: var(--kh-gap); min-width: 0; } +.kh-recordbody { overflow: visible; } +.kh-recordtab { min-width: 0; overflow-x: auto; } +@media (max-width: 1200px) { .dochead { grid-template-columns: 1fr 1fr; } .dochead > div:last-child { grid-column: 1 / -1; border-left: 0; border-top: 1px solid var(--kh-border); align-items: flex-start; text-align: left; } } +@media (max-width: 800px) { .dochead { grid-template-columns: 1fr; } .dochead > div + div { border-left: 0; border-top: 1px solid var(--kh-border); } } + +/* Component catalog (development) */ +.kh-catalog { display: flex; flex-direction: column; gap: var(--kh-gap); padding-top: var(--kh-gap); } +.kh-catalogrow { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; } +.kh-catalogbar { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; padding: 10px 11px; } +.kh-resizable { resize: horizontal; overflow: hidden; min-width: 240px; max-width: 100%; padding: 2px 6px 12px 2px; border: 1px dashed var(--kh-border); border-radius: var(--kh-radius-lg); } diff --git a/src/Khaemhat.Web/wwwroot/js/khaemhat.js b/src/Khaemhat.Web/wwwroot/js/khaemhat.js index f7c9e19..7c7546c 100644 --- a/src/Khaemhat.Web/wwwroot/js/khaemhat.js +++ b/src/Khaemhat.Web/wwwroot/js/khaemhat.js @@ -22,10 +22,16 @@ return combo + key; } + // The keys an element handles itself (data-kh-prevent="ArrowDown F4"): the page shortcuts leave them alone. + function preventedBy(element, combo) { + const list = element && element.getAttribute ? element.getAttribute("data-kh-prevent") : null; + return !!list && list.split(" ").indexOf(combo) >= 0; + } + function onKeyDown(e) { if (!shortcutTarget || e.isComposing) return; const combo = comboOf(e); - if (!combo || !shortcutCombos.has(combo)) return; + if (!combo || !shortcutCombos.has(combo) || preventedBy(e.target, combo)) return; e.preventDefault(); e.stopPropagation(); shortcutTarget.invokeMethodAsync("OnShortcut", combo).catch(function () { /* circuit gone */ }); @@ -87,6 +93,103 @@ } }, + // Stops the browser default of the keys listed in data-kh-prevent (read at each key, so Blazor can change it): + // arrows and Enter in an open hotlink list, + and - in a date field. + preventKeys: function (element) { + if (!element || element.khPrevent) return; + element.khPrevent = true; + element.addEventListener("keydown", function (e) { + // Date fields: + and - move one day when the field holds a whole date, and are typed otherwise (5-3-26, +30). + if ((e.key === "+" || e.key === "-") && !e.ctrlKey && !e.altKey && element.hasAttribute("data-kh-datestep") + && /^\d{1,2}\/\d{1,2}\/\d{4}$/.test(element.value)) { + e.preventDefault(); + e.stopPropagation(); + element.dispatchEvent(new KeyboardEvent("keydown", { key: e.key === "+" ? "ArrowUp" : "ArrowDown", bubbles: true })); + return; + } + const combo = comboOf(e); + if (combo && preventedBy(element, combo)) e.preventDefault(); + }); + }, + + // Places a drop-down menu under its button with fixed coordinates, aligned right, shorter when the window is. + placeMenu: function (menu) { + const anchor = menu && menu.parentElement; + if (!anchor) return; + const r = anchor.getBoundingClientRect(); + const below = window.innerHeight - r.bottom - 12; + const above = r.top - 12; + menu.style.position = "fixed"; + menu.style.right = Math.max(8, window.innerWidth - r.right) + "px"; + menu.style.left = "auto"; + if (below >= 200 || below >= above) { + menu.style.top = (r.bottom + 6) + "px"; + menu.style.bottom = "auto"; + menu.style.maxHeight = below + "px"; + } else { + menu.style.bottom = (window.innerHeight - r.top + 6) + "px"; + menu.style.top = "auto"; + menu.style.maxHeight = above + "px"; + } + menu.style.overflowY = "auto"; + }, + + // Moves the focus to the first field or button inside an element (dialogs, side panels). + focusFirst: function (element) { + if (!element) return; + const target = element.querySelector("[autofocus], input:not([type=hidden]):not([disabled]):not([readonly]), select:not([disabled]), textarea:not([disabled]):not([readonly]), .db button:not([disabled]), .df button:not([disabled])") + || element.querySelector("button:not([disabled])"); + if (target) target.focus(); + }, + + // Keeps a toolbar on one line: the commands with the highest data-ovf move out (data-ovf-hidden) until the bar + // fits, then .NET is told which ones, to list them in the "..." menu. + watchToolbar: function (element, target) { + if (!element) return; + element.khToolbar = target; + element.khObserver = new ResizeObserver(function () { window.khaemhat.fitToolbar(element); }); + element.khObserver.observe(element); + window.khaemhat.fitToolbar(element); + }, + + fitToolbar: function (element) { + if (!element || !element.khToolbar || element.clientWidth === 0) return; + const items = Array.prototype.slice.call(element.querySelectorAll("[data-ovf]")); + const groups = element.querySelectorAll("[data-ovf-group]"); + items.forEach(function (item) { item.removeAttribute("data-ovf-hidden"); }); + groups.forEach(function (group) { group.removeAttribute("data-ovf-hidden"); }); + const order = items.map(function (item, index) { return { item: item, index: index, priority: Number(item.getAttribute("data-ovf")) || 0 }; }) + .sort(function (a, b) { return b.priority - a.priority || b.index - a.index; }); + const hidden = []; + for (let i = 0; i < order.length && element.scrollWidth > element.clientWidth; i++) { + order[i].item.setAttribute("data-ovf-hidden", ""); + hidden.push(order[i].item.getAttribute("data-id")); + } + groups.forEach(function (group) { + const children = group.querySelectorAll("[data-ovf]"); + if (children.length > 0 && Array.prototype.every.call(children, function (c) { return c.hasAttribute("data-ovf-hidden"); })) { + group.setAttribute("data-ovf-hidden", ""); + } + }); + element.querySelectorAll(".sep").forEach(function (sep) { + const next = sep.nextElementSibling; + if (next && next.hasAttribute("data-ovf-hidden")) sep.setAttribute("data-ovf-hidden", ""); + else sep.removeAttribute("data-ovf-hidden"); + }); + const key = hidden.join(","); + if (element.khOverflow !== key) { + element.khOverflow = key; + element.khToolbar.invokeMethodAsync("SetOverflow", hidden).catch(function () { /* circuit gone */ }); + } + }, + + unwatchToolbar: function (element) { + if (!element) return; + if (element.khObserver) element.khObserver.disconnect(); + element.khObserver = null; + element.khToolbar = null; + }, + print: function () { window.print(); }, diff --git a/tests/Khaemhat.Web.Tests/Shell/LocalizationRulesTests.cs b/tests/Khaemhat.Web.Tests/Shell/LocalizationRulesTests.cs index 8260dc1..17c947d 100644 --- a/tests/Khaemhat.Web.Tests/Shell/LocalizationRulesTests.cs +++ b/tests/Khaemhat.Web.Tests/Shell/LocalizationRulesTests.cs @@ -87,6 +87,7 @@ public sealed partial class LocalizationRulesTests keys.AddRange(Enum.GetValues().Select(v => "Pages.Profile.Start." + v)); keys.AddRange(Enum.GetValues().Select(v => "Pages.Profile.Shortcuts." + v)); keys.AddRange(UserPreferences.Accents.Select(a => "Pages.Profile.Accent." + a)); + keys.AddRange(Enum.GetValues().Select(v => "Pages.Catalog.Windows.Toast." + v)); Assert.IsEmpty(keys.Where(k => !ShellTests.Texts.Contains(k)).ToList()); } @@ -268,6 +269,6 @@ public sealed partial class LocalizationRulesTests [GeneratedRegex(@"&[a-zA-Z]+;|&#\d+;")] private static partial Regex EntityPattern(); - [GeneratedRegex("\"((?:Shell|Pages|Auth|Common)\\.[A-Za-z0-9_.]+)\"")] + [GeneratedRegex("\"((?:Shell|Pages|Auth|Common|Ui)\\.[A-Za-z0-9_.]+)\"")] private static partial Regex KeyPattern(); } diff --git a/tests/Khaemhat.Web.Tests/Shell/ProfileServiceTests.cs b/tests/Khaemhat.Web.Tests/Shell/ProfileServiceTests.cs new file mode 100644 index 0000000..7a65590 --- /dev/null +++ b/tests/Khaemhat.Web.Tests/Shell/ProfileServiceTests.cs @@ -0,0 +1,97 @@ +using Khaemhat.Application.Security; +using Khaemhat.Core.Security; +using Khaemhat.Infrastructure.Security; +using Khaemhat.Web.Tests.Hosting; +using Microsoft.Extensions.DependencyInjection; + +namespace Khaemhat.Web.Tests.Shell; + +/// "Il mio profilo": the user changes name, e-mail, password and two-step verification alone (issue #31). +[TestClass] +public sealed class ProfileServiceTests +{ + private const string NewPassword = "Altra-Password-2026"; + + [TestMethod] + public async Task InstanceAccount_ChangesData_Password_AndTurnsOnTheVerification() + { + var (app, _, _) = await TestInstance.StartAsync(CancellationToken.None); + await using (app) + { + var profiles = app.Services.GetRequiredService(); + var sessions = app.Services.GetRequiredService(); + var owner = new SessionOwner(null, 1); + + var info = await profiles.GetAsync(owner); + Assert.IsNotNull(info); + Assert.AreEqual(TestInstance.SuperUser, info.UserName); + Assert.IsTrue(info.TotpRequired, "Instance accounts always need the two-step verification."); + + // Name and e-mail are checked, then saved. + CollectionAssert.AreEquivalent( + new[] { ProfileService.DisplayNameInvalid, ProfileService.EmailInvalid }, (await profiles.UpdateAsync(owner, " ", "not-an-address")).ToList()); + Assert.IsEmpty(await profiles.UpdateAsync(owner, " Amministratore Prova ", "admin@example.com")); + info = await profiles.GetAsync(owner); + Assert.AreEqual("Amministratore Prova", info!.DisplayName); + Assert.AreEqual("admin@example.com", info.Email); + + // The password: the current one is checked, the policy applies, the other sessions are closed. + await sessions.CreateAsync(owner, SessionState.Active, null, "10.0.0.1", "test-a", persistent: false); + await sessions.CreateAsync(owner, SessionState.Active, null, "10.0.0.2", "test-b", persistent: false); + var kept = (await sessions.ListAsync(owner))[0].Id; + CollectionAssert.AreEqual(new[] { SecurityErrors.CurrentPasswordWrong }, (await profiles.ChangePasswordAsync(owner, kept, "wrong", NewPassword)).ToList()); + CollectionAssert.Contains((await profiles.ChangePasswordAsync(owner, kept, TestInstance.SuperUserPassword, "short")).ToList(), SecurityErrors.PasswordTooShort); + Assert.IsEmpty(await profiles.ChangePasswordAsync(owner, kept, TestInstance.SuperUserPassword, NewPassword)); + Assert.AreEqual(kept, (await sessions.ListAsync(owner)).Single().Id, "Only the session that changed the password stays open."); + CollectionAssert.AreEqual(new[] { SecurityErrors.CurrentPasswordWrong }, (await profiles.ChangePasswordAsync(owner, kept, TestInstance.SuperUserPassword, "Terza-Password-2026")).ToList()); + + // The two-step verification: the same secret until confirmed, ten recovery codes, cannot be turned off. + var setup = await profiles.BeginTotpSetupAsync(owner, null); + Assert.IsNotNull(setup); + Assert.AreEqual(setup.Secret, (await profiles.BeginTotpSetupAsync(owner, null))!.Secret); + Assert.IsNull(await profiles.ConfirmTotpSetupAsync(owner, "abc")); + var codes = await profiles.ConfirmTotpSetupAsync(owner, CodeOf(setup.Secret)); + Assert.HasCount(10, codes!); + info = await profiles.GetAsync(owner); + Assert.IsTrue(info!.TotpEnabled); + Assert.AreEqual(10, info.RecoveryCodesLeft); + Assert.IsNull(await profiles.BeginTotpSetupAsync(owner, null), "Already active."); + CollectionAssert.AreEqual(new[] { ProfileService.TotpRequiredError }, (await profiles.DisableTotpAsync(owner, NewPassword)).ToList()); + + // New recovery codes need the password and replace the old ones. + Assert.IsNull(await profiles.RenewRecoveryCodesAsync(owner, "wrong")); + var renewed = await profiles.RenewRecoveryCodesAsync(owner, NewPassword); + Assert.HasCount(10, renewed!); + Assert.IsEmpty(renewed!.Intersect(codes!).ToList()); + await app.StopAsync(); + } + } + + [TestMethod] + public async Task CompanyUser_MayTurnTheVerificationOff_WithThePassword() + { + var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None); + await using (app) + { + var profiles = app.Services.GetRequiredService(); + var users = app.Services.GetRequiredService(); + var root = new Actor(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null); + var (user, password) = await users.CreateAsync(root, company, new NewCompanyUser("lucia", "Lucia Bianchi", null, UserKind.Human, [], new UserFlags(false, false, false, false))); + var owner = new SessionOwner(company, user.Id); + + var setup = await profiles.BeginTotpSetupAsync(owner, company); + Assert.Contains("lucia%40", setup!.ProvisioningUri, "The app shows user and company."); + Assert.IsNotNull(await profiles.ConfirmTotpSetupAsync(owner, CodeOf(setup.Secret))); + Assert.IsFalse((await profiles.GetAsync(owner))!.TotpRequired); + + CollectionAssert.AreEqual(new[] { SecurityErrors.CurrentPasswordWrong }, (await profiles.DisableTotpAsync(owner, "wrong")).ToList()); + Assert.IsEmpty(await profiles.DisableTotpAsync(owner, password!)); + var info = await profiles.GetAsync(owner); + Assert.IsFalse(info!.TotpEnabled); + Assert.AreEqual(0, info.RecoveryCodesLeft); + await app.StopAsync(); + } + } + + private static string CodeOf(string secret) => TotpGenerator.Compute(Base32.Decode(secret), TotpGenerator.StepOf(DateTimeOffset.UtcNow)); +} diff --git a/tests/Khaemhat.Web.Tests/Ui/ItalianInputTests.cs b/tests/Khaemhat.Web.Tests/Ui/ItalianInputTests.cs new file mode 100644 index 0000000..9c7ae56 --- /dev/null +++ b/tests/Khaemhat.Web.Tests/Ui/ItalianInputTests.cs @@ -0,0 +1,186 @@ +using System.Globalization; +using Khaemhat.Web.Shell; +using Khaemhat.Web.Ui; + +namespace Khaemhat.Web.Tests.Ui; + +/// Numbers, inline calculations and dates typed the Italian way (SPEC §10.7, issue #27). +[TestClass] +public sealed class ItalianInputTests +{ + private static readonly DateOnly Today = new(2026, 11, 11); + + [TestMethod] + [DataRow("1234,5", "1234.5")] + [DataRow("1.234,56", "1234.56")] + [DataRow("1.234.567", "1234567")] + [DataRow("-12,5", "-12.5")] + [DataRow("12.5", "12.5")] + [DataRow("1.234", "1234")] + [DataRow(" 42 ", "42")] + [DataRow("=10*3", "30")] + [DataRow("=100/3", "33.333333333333333333333333333")] + [DataRow("=(2+3)x4", "20")] + [DataRow("=12:4", "3")] + [DataRow("=10,5+0,5", "11")] + [DataRow("=-2*-3", "6")] + public void Number_ReadsItalianFormsAndCalculations(string text, string expected) + { + Assert.IsTrue(ItalianNumber.TryParse(text, out var value), text); + Assert.AreEqual(decimal.Parse(expected, CultureInfo.InvariantCulture), value, text); + } + + [TestMethod] + [DataRow("abc")] + [DataRow("12,3,4")] + [DataRow("=10/0")] + [DataRow("=(1+2")] + [DataRow("=1+")] + [DataRow("=")] + public void Number_RefusesWhatIsNotANumber(string text) => Assert.IsFalse(ItalianNumber.TryParse(text, out _), text); + + [TestMethod] + public void Number_EmptyIsNull() + { + Assert.IsTrue(ItalianNumber.TryParse(" ", out var value)); + Assert.IsNull(value); + } + + [TestMethod] + public void Number_FormatsWithTheCulture() + { + var italian = CultureInfo.GetCultureInfo("it-IT"); + Assert.AreEqual("1.234,50", ItalianNumber.Format(1234.5m, 2, italian)); + Assert.AreEqual(string.Empty, ItalianNumber.Format(null, 2, italian)); + } + + [TestMethod] + [DataRow("T", 2026, 11, 11)] + [DataRow("o", 2026, 11, 11)] + [DataRow("F", 2026, 11, 30)] + [DataRow("I", 2026, 11, 1)] + [DataRow("+", 2026, 11, 12)] + [DataRow("-", 2026, 11, 10)] + [DataRow("+30", 2026, 12, 11)] + [DataRow("-11", 2026, 10, 31)] + [DataRow("5", 2026, 11, 5)] + [DataRow("5/3", 2026, 3, 5)] + [DataRow("05/03/2027", 2027, 3, 5)] + [DataRow("5-3-26", 2026, 3, 5)] + [DataRow("5.3.26", 2026, 3, 5)] + [DataRow("0503", 2026, 3, 5)] + [DataRow("050326", 2026, 3, 5)] + [DataRow("05032026", 2026, 3, 5)] + [DataRow("1/1/60", 1960, 1, 1)] + [DataRow("1/1/46", 2046, 1, 1)] + [DataRow("29/2/28", 2028, 2, 29)] + public void Date_ReadsShortFormsAndLetters(string text, int year, int month, int day) + { + Assert.IsTrue(ItalianDate.TryParse(text, Today, null, out var value), text); + Assert.AreEqual(new DateOnly(year, month, day), value, text); + } + + [TestMethod] + public void Date_RelativeFormsStartFromTheCurrentValue() + { + var current = new DateOnly(2026, 2, 10); + Assert.IsTrue(ItalianDate.TryParse("F", Today, current, out var end)); + Assert.AreEqual(new DateOnly(2026, 2, 28), end); + Assert.IsTrue(ItalianDate.TryParse("+7", Today, current, out var week)); + Assert.AreEqual(new DateOnly(2026, 2, 17), week); + Assert.IsTrue(ItalianDate.TryParse("T", Today, current, out var today)); + Assert.AreEqual(Today, today); + } + + [TestMethod] + [DataRow("31/11/2026")] + [DataRow("29/2/2027")] + [DataRow("0/1")] + [DataRow("1/13")] + [DataRow("123")] + [DataRow("ieri")] + [DataRow("1/2/3/4")] + public void Date_RefusesWhatIsNotADate(string text) => Assert.IsFalse(ItalianDate.TryParse(text, Today, null, out _), text); + + [TestMethod] + public void Date_EmptyIsNull() + { + Assert.IsTrue(ItalianDate.TryParse(string.Empty, Today, Today, out var value)); + Assert.IsNull(value); + } + + [TestMethod] + public void Validation_CollectsFieldMessagesAndRaisesChanged() + { + var validation = new KhValidation(); + var changes = 0; + validation.Changed += () => changes++; + + validation.Add("number", "taken"); + validation.Add(null, "whole form"); + Assert.IsFalse(validation.IsValid); + CollectionAssert.AreEqual(new[] { "taken" }, validation.For("number").ToArray()); + + validation.ClearField("number"); + validation.ClearField("number"); + Assert.HasCount(1, validation.Messages); + validation.Clear(); + Assert.IsTrue(validation.IsValid); + Assert.AreEqual(4, changes); + } + + [TestMethod] + public void FormContext_ValidatesEveryRegisteredField() + { + var context = new KhFormContext(new KhValidation()); + var empty = new FakeField("name", "Nome", "Campo obbligatorio."); + var good = new FakeField("code", "Codice"); + context.Register(empty); + context.Register(good); + + Assert.IsFalse(context.Validate()); + var message = context.Validation.Messages.Single(); + Assert.AreEqual("name", message.Field); + Assert.AreEqual("Nome", message.Label); + Assert.AreEqual("in-name", message.InputId); + Assert.AreSame(good, context.Find("code")); + + context.Unregister(empty); + Assert.IsTrue(context.Validate()); + } + + [TestMethod] + [DataRow("page.tab.1", 1)] + [DataRow("page.tab.9", 9)] + public void PageTab_ReadsTheNumber(string command, int expected) + { + Assert.IsTrue(KeyboardShortcuts.TryGetTabNumber(command, out var number)); + Assert.AreEqual(expected, number); + } + + [TestMethod] + [DataRow("page.tab.0")] + [DataRow("page.tab.10")] + [DataRow("page.tab.")] + [DataRow("page.save")] + public void PageTab_RefusesOtherCommands(string command) => Assert.IsFalse(KeyboardShortcuts.TryGetTabNumber(command, out _)); + + [TestMethod] + public void Pretty_ShowsArrowsAsSymbols() + { + Assert.AreEqual("Ctrl+↑", KeyboardShortcuts.Pretty("Ctrl+ArrowUp")); + Assert.AreEqual("Esc", KeyboardShortcuts.Pretty("Escape")); + Assert.AreEqual(string.Empty, KeyboardShortcuts.Pretty(null)); + } + + private sealed class FakeField(string name, string label, params string[] messages) : IKhField + { + public string FieldName => name; + + public string? Label => label; + + public string InputId => "in-" + name; + + public IEnumerable Validate() => messages; + } +}