diff --git a/src/Khaemhat.Application/Treasury/ScheduleService.cs b/src/Khaemhat.Application/Treasury/ScheduleService.cs index 713798f..8205af5 100644 --- a/src/Khaemhat.Application/Treasury/ScheduleService.cs +++ b/src/Khaemhat.Application/Treasury/ScheduleService.cs @@ -13,6 +13,11 @@ using Khaemhat.Infrastructure.Files; namespace Khaemhat.Application.Treasury; +/// The payment methods and the bank accounts of the company. +/// The payment methods in use. +/// The bank accounts in use. +public sealed record TreasuryChoices(IReadOnlyList Methods, IReadOnlyList Banks); + /// Which items the schedule shows. public enum ScheduleView { @@ -258,6 +263,20 @@ public sealed class ScheduleService return await RowsAsync(uow, items, today, cancellationToken).ConfigureAwait(false); } + /// The payment methods and the bank accounts in use, for the choices of the treasury screens. + /// Who reads. + /// The company. + /// Cancellation. + /// The choices, by code. + public async Task ChoicesAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.ScheduleRead, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var methods = (await uow.Repository().ListAsync(Query.For().Where(m => !m.Disabled).OrderBy(m => m.Code), cancellationToken).ConfigureAwait(false)).Items; + var banks = (await uow.Repository().ListAsync(Query.For().Where(b => !b.Disabled).OrderBy(b => b.Code), cancellationToken).ConfigureAwait(false)).Items; + return new TreasuryChoices(methods, banks); + } + internal static async Task LoadAsync(IUnitOfWork uow, ScheduleFilter filter, DateOnly today, CancellationToken cancellationToken) { var direction = filter.Direction; diff --git a/src/Khaemhat.Application/Treasury/TreasuryFeedSource.cs b/src/Khaemhat.Application/Treasury/TreasuryFeedSource.cs new file mode 100644 index 0000000..2c4b377 --- /dev/null +++ b/src/Khaemhat.Application/Treasury/TreasuryFeedSource.cs @@ -0,0 +1,79 @@ +using System.Globalization; +using Khaemhat.Application.Dashboard; +using Khaemhat.Application.Localization; +using Khaemhat.Application.Security; +using Khaemhat.Core.Accounting; +using Khaemhat.Core.Treasury; + +namespace Khaemhat.Application.Treasury; + +/// +/// The schedule on the dashboard (SPEC §10.3): the collections and payments due in the next days among the deadlines, +/// and the customers' items past due among the things to do. Only for who may see the schedule of the company. +/// +/// The schedule. +/// The permissions, licence included. +/// The texts. +public sealed class TreasuryFeedSource(ScheduleService schedule, PermissionService permissions, ITexts texts) : IDeadlineSource, ITodoSource +{ + /// The text key of the area. + public const string Area = "Dashboard.Areas.Treasury"; + + /// The most deadlines of the schedule on the dashboard. + public const int MaxDeadlines = 12; + + private const string Href = "/scadenzario/scadenze"; + + /// + public async Task> GetAsync(FeedContext context, DateOnly until, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(context); + if (!await AllowedAsync(context, cancellationToken).ConfigureAwait(false)) + { + return []; + } + + var days = Math.Max(0, until.DayNumber - context.Today.DayNumber); + var rows = await schedule.DueSoonAsync(context.Actor, context.Actor.CompanyCode!, days, MaxDeadlines * 2, cancellationToken).ConfigureAwait(false); + return [.. rows.Where(r => r.Item.DueDate >= context.Today && r.Item.Status != OpenItemStatus.InRemittance).Take(MaxDeadlines).Select(r => + { + var receivable = r.Item.Direction == OpenItemDirection.Receivable; + return new FeedItem( + "openitem-" + r.Item.Id.ToString(CultureInfo.InvariantCulture), + texts.Format(receivable ? "Dashboard.Feed.DueReceivable" : "Dashboard.Feed.DuePayable", r.PartyName, texts.Money(r.Item.Residual)), + Area, + receivable ? FeedTone.Info : FeedTone.Warning) + { + Detail = r.Item.DocumentNumber, + When = new DateTimeOffset(r.Item.DueDate.ToDateTime(TimeOnly.MinValue), context.Now.Offset), + Href = Href + (receivable ? string.Empty : "?vista=fornitori"), + }; + })]; + } + + /// + public async Task> GetAsync(FeedContext context, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(context); + if (!await AllowedAsync(context, cancellationToken).ConfigureAwait(false)) + { + return []; + } + + var overdue = await schedule.ItemsAsync(context.Actor, context.Actor.CompanyCode!, new ScheduleFilter(OpenItemDirection.Receivable, ScheduleView.Overdue), cancellationToken) + .ConfigureAwait(false); + return overdue.Rows.Count == 0 + ? [] + : + [ + new FeedItem("openitems-overdue", texts.Format("Dashboard.Feed.Overdue", overdue.Rows.Count, texts.Money(overdue.Overdue)), Area, FeedTone.Error) + { + Priority = 40, + Href = "/scadenzario/solleciti", + }, + ]; + } + + private async Task AllowedAsync(FeedContext context, CancellationToken cancellationToken) => + context.Actor.CompanyCode is not null && (await permissions.CheckAsync(context.Actor, TreasuryPermissions.ScheduleRead, cancellationToken).ConfigureAwait(false)).Allowed; +} diff --git a/src/Khaemhat.Web/Components/Pages/Treasury/CashFlowPage.razor b/src/Khaemhat.Web/Components/Pages/Treasury/CashFlowPage.razor new file mode 100644 index 0000000..17af04b --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Treasury/CashFlowPage.razor @@ -0,0 +1,193 @@ +@page "/scadenzario/flusso-di-cassa" +@attribute [Authorize] +@using Khaemhat.Application.Treasury +@using Khaemhat.Core.Treasury +@using Khaemhat.Web.Treasury +@inject ShellSession Session +@inject CashFlowService CashFlow + +@* The cash flow forecast (SPEC §11.8, report "flusso di cassa 90 gg"): the money of the banks and the cash today and, + week by week or month by month, what comes in and goes out from the open items, the remittances presented, the + orders not yet invoiced, the recurring entries and the taxes still to pay. Overdue items fall in the first period. *@ + + + +
+
+
@T["Shell.Menu.Finance"] / @T["Treasury.CashFlow.Title"]
+

@T["Treasury.CashFlow.Heading"]

+
@T["Treasury.CashFlow.Hint"]
+
+
+ + +
+ + + @foreach (var source in Enum.GetValues()) + { + + } +
+
+ + @if (_forecast is { } f) + { + var lowest = f.Periods.Count == 0 ? f.Opening : Math.Min(f.Opening, f.Periods.Min(p => p.Balance)); + + +
+ + + + + + + + + + + + + @{ var scale = Math.Max(1m, f.Periods.Select(p => Math.Abs(p.Balance)).DefaultIfEmpty(0m).Max()); } + @foreach (var p in f.Periods) + { + var width = (int)Math.Round(Math.Abs(p.Balance) / scale * 100m); + + + + + + + + } + +
@T["Treasury.CashFlow.Period"]@T["Treasury.Reconciliation.In"]@T["Treasury.Reconciliation.Out"]@T["Treasury.CashFlow.Balance"]@T["Treasury.CashFlow.Chart"]
@T.Date(p.From) – @T.Date(p.To)@(p.In != 0m ? T.Money(p.In) : null)@(p.Out != 0m ? T.Money(p.Out) : null)@T.Money(p.Balance)
+
+ + + + @foreach (var a in f.Accounts) + { + + + + + } + + + + + + + +
@a.Name@T.Money(a.Balance)
@T["Treasury.Fields.Total"]@T.Money(f.Opening)
+
+
+ + + @if (f.Movements.Count == 0) + { +

@T["Treasury.CashFlow.NoMovements"]

+ } + else + { +
+ + + + + + + + + + + @foreach (var m in f.Movements) + { + + + + + + + } + +
@T["Treasury.Fields.Date"]@T["Treasury.CashFlow.Source"]@T["Treasury.Reconciliation.Description"]@T["Treasury.Fields.Amount"]
@T.Date(m.Date)@T[TreasuryScreens.EnumKey(m.Source)]@m.Label@T.Money(m.Amount)
+
+ } +
+ } +
+ +@code { + private int _days = 90; + private int _period = 7; + private readonly HashSet _sources = [.. Enum.GetValues()]; + private CashFlowForecast? _forecast; + + private IReadOnlyList> DayChoices => + [.. new[] { 30, 60, 90, 180, 365 }.Select(d => new KhOption(d, T.Format("Treasury.CashFlow.DaysText", d)))]; + + private IReadOnlyList> PeriodChoices => + [ + new(7, T["Treasury.CashFlow.Weeks"]), + new(30, T["Treasury.CashFlow.Months"]), + ]; + + /// + protected override async Task OnInitializedAsync() + { + await Session.EnsureLoadedAsync(); + if (FinanceGuard.Allowed(Session, TreasuryPermissions.ScheduleRead)) + { + await LoadAsync(); + } + } + + private IReadOnlyList Stats(CashFlowForecast f, decimal lowest) => + [ + new(T["Treasury.CashFlow.Today"], T.Money(f.Opening)), + new(T["Treasury.CashFlow.TotalIn"], T.Money(f.Periods.Sum(p => p.In)), KhTone.Ok), + new(T["Treasury.CashFlow.TotalOut"], T.Money(f.Periods.Sum(p => p.Out)), KhTone.Warning), + new(T["Treasury.CashFlow.End"], T.Money(f.Periods.Count == 0 ? f.Opening : f.Periods[^1].Balance)), + new(T["Treasury.CashFlow.Lowest"], T.Money(lowest), lowest < 0m ? KhTone.Error : KhTone.Neutral), + ]; + + private async Task LoadAsync() + { + if (Session.Actor is { } actor && Session.Company?.Code is { } company) + { + _forecast = await CashFlow.ForecastAsync(actor, company, _days, _sources, _period); + } + } + + private async Task SetDaysAsync(int days) + { + _days = days; + await LoadAsync(); + } + + private async Task SetPeriodAsync(int period) + { + _period = period; + await LoadAsync(); + } + + private async Task ToggleAsync(CashFlowSource source, bool on) + { + if (on) + { + _sources.Add(source); + } + else + { + _sources.Remove(source); + } + + await LoadAsync(); + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Treasury/DunningPage.razor b/src/Khaemhat.Web/Components/Pages/Treasury/DunningPage.razor new file mode 100644 index 0000000..ba5fd34 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Treasury/DunningPage.razor @@ -0,0 +1,369 @@ +@page "/scadenzario/solleciti" +@attribute [Authorize] +@using Khaemhat.Application.Security +@using Khaemhat.Application.Treasury +@using Khaemhat.Core.Treasury +@using Khaemhat.Web.Ledger +@using Khaemhat.Web.Treasury +@inject ShellSession Session +@inject DunningService Dunning +@inject ToastService Toasts +@inject DialogService Dialogs +@inject IJSRuntime JS + +@* The reminders (SPEC §11.8, mockup 056): the customers with items past due by more days than the next level asks, + public administrations and disputed items left out; the level, the channel and the late interest of D.Lgs. + 231/2002; the letters sent by e-mail or PEC with the PDF attached, the third level that blocks the customer, the + history of what was sent. The scheduled task "Solleciti automatici" sends the levels marked automatic. *@ + + + +
+
+
@T["Shell.Menu.Finance"] / @T["Treasury.Dunning.Title"]
+

@T["Treasury.Dunning.Heading"]

+
+
+ @if (CanWrite) + { +
+ + +
+ } +
+ + + + + + @if (_tab == "proposal") + { + + @T["Treasury.Dunning.Rule"] + + @if (_proposal.Count == 0) + { +

@T["Treasury.Dunning.Nothing"]

+ } + else + { +
+ + + + + + + + + + + + + + + + @foreach (var p in _proposal) + { + + + + + + + + + + + + } + +
@T["Treasury.Fields.Customer"]@T["Treasury.Dunning.Items"]@T["Treasury.Schedule.Overdue"]@T["Treasury.Dunning.MaxDays"]@T["Treasury.Dunning.LastSent"]@T["Treasury.Dunning.NextLevel"]@T["Treasury.Dunning.Channel"]@T["Treasury.Statement.Interest"]@T["Treasury.Dunning.Include"]
@p.PartyName @(p.Blocked ? T["Treasury.Dunning.Blocked"] : null)@p.Items.Count@T.Money(p.Overdue)@p.MaxDays@(p.LastSent is { } last ? p.CurrentLevel + " · " + T.Date(last) : "—") + @if (p.Level is { } level) + { + @T.Format("Treasury.Dunning.Level", level.Level) + } + else + { + @T["Treasury.Dunning.Waiting"] + } + @(p.Level is { } l ? T[TreasuryScreens.EnumKey(l.Channel)] : "—") @(p.Pec ?? p.Email)@T.Money(p.Interest) + @if (p.Level is not null) + { + var on = _included.Contains(p.PartyId); + + } +
+
+ } +
+
+ + + + + + + + + + + + + + + + + @foreach (var level in _levels) + { + + + + + + + + + + + } + +
@T["Treasury.Dunning.LevelColumn"]@T["Treasury.Dunning.After"]@T["Treasury.Dunning.Template"]@T["Treasury.Dunning.Channel"]@T["Treasury.Statement.Interest"]@T["Treasury.Dunning.Action"]@T["Treasury.Dunning.Automatic"]
@level.Level@level.DaysAfterDue@level.Name@T[TreasuryScreens.EnumKey(level.Channel)]@T[level.ChargeInterest ? "Treasury.Dunning.InterestYes" : "Treasury.Dunning.InterestNo"]@T[TreasuryScreens.EnumKey(level.Action)]@T[level.Automatic ? "Common.Yes" : "Common.No"] + @if (CanWrite) + { + + } +
+
@T["Treasury.Dunning.Placeholders"]
+
+ } + else + { + + @if (_history.Count == 0) + { +

@T["Treasury.Dunning.NoHistory"]

+ } + else + { + + + + + + + + + + + + + + + + + @foreach (var row in _history) + { + var l = row.Letter; + + + + + + + + + + + + + } + +
@T["Treasury.Fields.Date"]@T["Treasury.Fields.Customer"]@T["Treasury.Dunning.LevelColumn"]@T["Treasury.Dunning.Channel"]@T["Treasury.Dunning.Recipients"]@T["Treasury.Dunning.Items"]@T["Treasury.Schedule.Overdue"]@T["Treasury.Statement.Interest"]@T["Treasury.Fields.Status"]@T["Treasury.Dunning.SentBy"]
@T.Date(l.SentOn)@row.PartyName@l.Level@T[TreasuryScreens.EnumKey(l.Channel)]@l.Recipients@l.ItemCount@T.Money(l.OverdueAmount)@LedgerScreens.AmountText(T, l.Interest)@T[TreasuryScreens.EnumKey(l.Status)]@l.SentBy
+ } +
+ } + + + + @if (_level is { } level) + { +
+ + + + + + + + +
+

@T["Treasury.Dunning.Placeholders"]

+ } +
+
+ + +
+
+
+ +@code { + private string _tab = "proposal"; + private IReadOnlyList _proposal = []; + private IReadOnlyList _levels = []; + private IReadOnlyList _history = []; + private readonly HashSet _included = []; + private DunningLevel? _level; + private bool _busy; + + private bool CanWrite => Session.Permissions.Allows(TreasuryPermissions.ScheduleWrite); + + private IReadOnlyList Tabs => + [ + new("proposal", "send", T["Treasury.Dunning.Proposal"], _proposal.Count(p => p.Level is not null)), + new("history", "clock", T["Treasury.Dunning.History"]), + ]; + + private IReadOnlyList> Channels => TreasuryScreens.Choices(T); + + private IReadOnlyList> Actions => TreasuryScreens.Choices(T); + + private IReadOnlyList Stats + { + get + { + var last = _history.Count == 0 ? null : _history[0].Letter; + return + [ + new(T["Treasury.Dunning.Customers"], _proposal.Count.ToString(T.Culture)), + new(T["Treasury.Dunning.OverdueTotal"], T.Money(_proposal.Sum(p => p.Overdue)), KhTone.Error), + new(T["Treasury.Dunning.Today"], _proposal.Count(p => p.Level is not null).ToString(T.Culture), KhTone.Warning), + new(T["Treasury.Dunning.LastRun"], last is null ? "—" : T.Date(last.SentOn) + " · " + _history.Count(h => h.Letter.SentOn == last.SentOn)), + new(T["Treasury.Dunning.Schedule"], T["Treasury.Dunning.ScheduleText"]), + ]; + } + } + + /// + protected override async Task OnInitializedAsync() + { + await Session.EnsureLoadedAsync(); + if (FinanceGuard.Allowed(Session, TreasuryPermissions.ScheduleRead)) + { + await LoadAsync(); + } + } + + private async Task LoadAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _levels = await Dunning.LevelsAsync(actor, company); + _proposal = await Dunning.ProposalAsync(actor, company); + _history = await Dunning.HistoryAsync(actor, company); + _included.Clear(); + _included.UnionWith(_proposal.Where(p => p.Level is not null).Select(p => p.PartyId)); + } + + private async Task SetTabAsync(string tab) + { + _tab = tab; + await LoadAsync(); + } + + private void Toggle(long partyId, bool on) + { + if (on) + { + _included.Add(partyId); + } + else + { + _included.Remove(partyId); + } + } + + private async Task PreviewAsync() => await RunAsync(async (actor, company) => + { + if (_proposal.FirstOrDefault(p => _included.Contains(p.PartyId)) is { } first) + { + await LedgerScreens.DownloadAsync(JS, await Dunning.PreviewAsync(actor, company, first.PartyId)); + } + }); + + private async Task SendAsync() + { + if (!await Dialogs.ConfirmAsync(new ConfirmRequest(T["Treasury.Dunning.SendTitle"], T.Format("Treasury.Dunning.SendText", _included.Count), T["Treasury.Dunning.SendTitle"], T["Common.Cancel"]))) + { + return; + } + + await RunAsync(async (actor, company) => + { + var run = await Dunning.SendAsync(actor, company, [.. _included]); + Toasts.Show(run.Skipped.Count == 0 ? ToastKind.Success : ToastKind.Warning, T.Format("Treasury.Dunning.Sent", run.Sent, run.Letters), + run.Skipped.Count == 0 ? null : string.Join("; ", run.Skipped.Select(s => s.Party + ": " + (T.Contains(s.Reason) ? T[s.Reason] : s.Reason)))); + if (run.Pdf is { } pdf) + { + await LedgerScreens.DownloadAsync(JS, pdf); + } + + await LoadAsync(); + }); + } + + private void OpenLevel(DunningLevel level) => _level = new DunningLevel + { + Id = level.Id, + Level = level.Level, + DaysAfterDue = level.DaysAfterDue, + Name = level.Name, + Subject = level.Subject, + Body = level.Body, + Channel = level.Channel, + ChargeInterest = level.ChargeInterest, + Action = level.Action, + Automatic = level.Automatic, + }; + + private async Task SaveLevelAsync() => await RunAsync(async (actor, company) => + { + if (_level is { } level) + { + await Dunning.SaveLevelAsync(actor, company, level); + _level = null; + Toasts.Show(ToastKind.Success, T["Treasury.Saved"], null); + await LoadAsync(); + } + }); + + private async Task RunAsync(Func action) + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _busy = true; + try + { + await action(actor, company); + } + catch (ValidationFailedException ex) + { + Toasts.Show(ToastKind.Error, T["Treasury.NotDone"], TreasuryScreens.Errors(T, ex)); + } + finally + { + _busy = false; + } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Treasury/FinanceGuard.razor b/src/Khaemhat.Web/Components/Pages/Treasury/FinanceGuard.razor new file mode 100644 index 0000000..8ccd736 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Treasury/FinanceGuard.razor @@ -0,0 +1,62 @@ +@using Khaemhat.Application.Modules +@inject ShellSession Session + +@* What every page of the schedule checks first: an open company, the module FIN in the licence and the permission. *@ +@if (!_loaded) +{ +

@T["Common.Loading"]

+} +else if (Session.Company is null) +{ +
+ +

@T["Treasury.NoCompany"]

+
+} +else if (!Session.Licenses.IsModuleActive(ModuleCodes.Finance)) +{ +
+ +

@T["Treasury.NoModule.Title"]

+

@T["Treasury.NoModule.Lead"]

+
+} +else if (!Session.Permissions.Allows(Permission)) +{ +
+ +

@T["Pages.AccessDenied.Title"]

+

@T["Pages.AccessDenied.Lead"]

+ @T["Common.BackHome"] +
+} +else +{ + @ChildContent +} + +@code { + private bool _loaded; + + /// The permission the page needs. + [Parameter, EditorRequired] + public string Permission { get; set; } = string.Empty; + + /// The page. + [Parameter] + public RenderFragment? ChildContent { get; set; } + + /// Whether the page may load its data: company, licence and permission. + /// The session. + /// The permission. + /// True when it may. + public static bool Allowed(ShellSession session, string permission) => + session is { Actor: not null, Company: not null } && session.Licenses.IsModuleActive(ModuleCodes.Finance) && session.Permissions.Allows(permission); + + /// + protected override async Task OnInitializedAsync() + { + await Session.EnsureLoadedAsync(); + _loaded = true; + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Treasury/MandatesPage.razor b/src/Khaemhat.Web/Components/Pages/Treasury/MandatesPage.razor new file mode 100644 index 0000000..1338146 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Treasury/MandatesPage.razor @@ -0,0 +1,217 @@ +@page "/scadenzario/mandati" +@attribute [Authorize] +@using Khaemhat.Application.Parties +@using Khaemhat.Application.Security +@using Khaemhat.Application.Treasury +@using Khaemhat.Core.Parties +@using Khaemhat.Core.Treasury +@using Khaemhat.Web.Treasury +@inject ShellSession Session +@inject MandateService Mandates +@inject PartyService Parties +@inject ToastService Toasts +@inject DialogService Dialogs +@inject TimeProvider Clock + +@* The SEPA direct debit mandates of the customers (SPEC §11.8, mockup 055): the unique reference, the signature, the + scheme Core or B2B, the account of the debtor; a direct debit remittance takes only the items of customers with a + valid mandate, and the first collection of each mandate goes out as FRST, the next ones as RCUR. *@ + + + +
+
+
@T["Shell.Menu.Finance"] / @T["Treasury.Mandates.Title"]
+

@T["Treasury.Mandates.Heading"]

+
@T["Treasury.Mandates.Hint"]
+
+
+ @if (CanWrite) + { +
+ +
+ } +
+ + + @if (_rows.Count == 0) + { +

@T["Treasury.Mandates.None"]

+ } + else + { +
+ + + + + + + + + + + + + + + @foreach (var row in _rows) + { + var m = row.Mandate; + + + + + + + + + + + } + +
@T["Treasury.Fields.Customer"]@T["Treasury.Mandates.Reference"]@T["Treasury.Mandates.Signed"]@T["Treasury.Mandates.Scheme"]@T["Treasury.Fields.Iban"]@T["Treasury.Mandates.LastCollection"]@T["Treasury.Fields.Status"]
@row.PartyName @row.PartyCode@m.Reference@T.Date(m.SignatureDate)@T[TreasuryScreens.EnumKey(m.Scheme)] @(m.OneOff ? "· " + T["Treasury.Mandates.OneOff"] : null)@m.Iban@(m.LastCollectionDate is { } last ? T.Date(last) : T["Treasury.Mandates.First"])@T[m.Revoked ? "Treasury.Mandates.Revoked" : "Treasury.Mandates.Active"] + @if (CanWrite) + { + + + + } +
+
+ } +
+ + + +
+ + + + + + + + +
+
+
+ + +
+
+
+ +@code { + private IReadOnlyList _rows = []; + private bool _busy; + private bool _editOpen; + private long? _editId; + private PartyRow? _party; + private string? _reference; + private DateOnly? _signed; + private SddScheme _scheme; + private bool _oneOff; + private string? _iban; + private string? _bic; + private string? _notes; + + private bool CanWrite => Session.Permissions.Allows(TreasuryPermissions.ScheduleWrite); + + private IReadOnlyList> Schemes => TreasuryScreens.Choices(T); + + /// + protected override async Task OnInitializedAsync() + { + await Session.EnsureLoadedAsync(); + if (FinanceGuard.Allowed(Session, TreasuryPermissions.ScheduleRead)) + { + await LoadAsync(); + } + } + + private async Task LoadAsync() + { + if (Session.Actor is { } actor && Session.Company?.Code is { } company) + { + _rows = await Mandates.ListAsync(actor, company); + } + } + + private async Task> SearchPartiesAsync(string text, CancellationToken cancellationToken) => + Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(PartyService.ReadPermission) + ? await Parties.SearchAsync(actor, company, PartyArchive.Customers, text, cancellationToken) + : []; + + private async Task OpenEdit(MandateRow? row) + { + var m = row?.Mandate; + _editId = m?.Id; + _party = m is not null && Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(PartyService.ReadPermission) + ? (await Parties.RowsAsync(actor, company, [m.PartyId])).FirstOrDefault() + : null; + _reference = m?.Reference; + _signed = m?.SignatureDate ?? DateOnly.FromDateTime(Clock.GetLocalNow().DateTime); + _scheme = m?.Scheme ?? SddScheme.Core; + _oneOff = m?.OneOff ?? false; + _iban = m?.Iban; + _bic = m?.Bic; + _notes = m?.Notes; + _editOpen = true; + } + + private async Task SaveAsync() => await RunAsync(async (actor, company) => + { + if (_party is { } party && _signed is { } signed) + { + await Mandates.SaveAsync(actor, company, new MandateInput(_editId, party.Id, _reference ?? string.Empty, signed, _scheme, _iban ?? string.Empty, _bic, _oneOff, _notes)); + _editOpen = false; + Toasts.Show(ToastKind.Success, T["Treasury.Saved"], null); + await LoadAsync(); + } + }); + + private async Task RevokeAsync(MandateRow row) => await RunAsync(async (actor, company) => + { + await Mandates.RevokeAsync(actor, company, row.Mandate.Id, !row.Mandate.Revoked); + await LoadAsync(); + }); + + private async Task DeleteAsync(MandateRow row) + { + if (!await Dialogs.ConfirmAsync(new ConfirmRequest(T["Treasury.Mandates.Delete"], T.Format("Treasury.Mandates.DeleteText", row.Mandate.Reference), T["Treasury.Mandates.Delete"], T["Common.Cancel"], Danger: true))) + { + return; + } + + await RunAsync(async (actor, company) => + { + await Mandates.DeleteAsync(actor, company, row.Mandate.Id); + await LoadAsync(); + }); + } + + private async Task RunAsync(Func action) + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _busy = true; + try + { + await action(actor, company); + } + catch (ValidationFailedException ex) + { + Toasts.Show(ToastKind.Error, T["Treasury.NotDone"], TreasuryScreens.Errors(T, ex)); + } + finally + { + _busy = false; + } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Treasury/PaymentDialog.razor b/src/Khaemhat.Web/Components/Pages/Treasury/PaymentDialog.razor new file mode 100644 index 0000000..1d5c271 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Treasury/PaymentDialog.razor @@ -0,0 +1,180 @@ +@using Khaemhat.Application.Security +@using Khaemhat.Application.Treasury +@using Khaemhat.Core.Accounting +@using Khaemhat.Core.Treasury +@using Khaemhat.Web.Ledger +@using Khaemhat.Web.Treasury +@inject ShellSession Session +@inject PaymentService Payments +@inject ToastService Toasts +@inject TimeProvider Clock + +@* Record a collection or a payment on the items chosen in the schedule (SPEC §11.8, mockup 054): the amount of each + item, an allowance that closes it for less, the fees of the bank; the entry is written by the treasury with the + template of collections or payments and the items are settled. *@ + + +
+ + + + + + + + +
+

@T["Treasury.Payment.Items"]

+
+ + + + + + + + + + + + + + @foreach (var line in _lines) + { + var item = line.Row.Item; + + + + + + + + + + } + + + + + + + + + + +
@T["Treasury.Fields.Document"]@T["Treasury.Fields.Installment"]@T["Treasury.Fields.DueDate"]@T["Treasury.Fields.Residual"]@T[Receipt ? "Treasury.Payment.Collected" : "Treasury.Payment.Paid"]@T["Treasury.Fields.Allowance"]@T["Treasury.Payment.ResidualAfter"]
@item.DocumentNumber@item.Installment@T.Date(item.DueDate)@T.Money(item.Residual)@T.Money(item.Residual - line.Amount - line.Allowance)
@T["Treasury.Fields.Total"]@T.Money(_lines.Sum(l => l.Row.Item.Residual))@T.Money(Total)@T.Money(_lines.Sum(l => l.Allowance))@T.Money(_lines.Sum(l => l.Row.Item.Residual - l.Amount - l.Allowance))
+
+
+ + @T.Format(Receipt ? "Treasury.Payment.EntryReceipt" : "Treasury.Payment.EntryPayment", T.Money(Total), T.Money(_lines.Sum(l => l.Allowance))) +
+
+
+ + +
+
+ +@code { + private List _lines = []; + private DateOnly? _date; + private long? _methodId; + private long? _bankId; + private string? _reference; + private decimal? _fees; + private string? _notes; + private bool _busy; + private IReadOnlyList? _shown; + + /// Whether the dialog is open. + [Parameter] + public bool Open { get; set; } + + /// The items to settle, all of one party and one direction. + [Parameter] + public IReadOnlyList Rows { get; set; } = []; + + /// The payment methods and the banks. + [Parameter] + public TreasuryChoices? Choices { get; set; } + + /// Closed without saving. + [Parameter] + public EventCallback OnClose { get; set; } + + /// Saved. + [Parameter] + public EventCallback OnSaved { get; set; } + + private bool Receipt => Rows.Count == 0 || Rows[0].Item.Direction == OpenItemDirection.Receivable; + + private string PartyName => Rows.Count == 0 ? string.Empty : (Rows[0].PartyCode is { } code ? code + " · " : string.Empty) + Rows[0].PartyName; + + private decimal Total => _lines.Sum(l => l.Amount); + + private IReadOnlyList> Methods => TreasuryScreens.MethodChoices(Choices?.Methods ?? []); + + private IReadOnlyList> Banks => TreasuryScreens.BankChoices(Choices?.Banks ?? []); + + /// + protected override void OnParametersSet() + { + if (!Open || ReferenceEquals(_shown, Rows)) + { + return; + } + + // A new set of items: the whole residual of each, the method of the first and the bank it names or the default. + _shown = Rows; + _lines = [.. Rows.Select(r => new Line(r) { Amount = r.Item.Residual })]; + _date = DateOnly.FromDateTime(Clock.GetLocalNow().DateTime); + _methodId = Rows.Select(r => r.Item.PaymentMethodId).FirstOrDefault(m => m is not null); + _bankId = Rows.Select(r => r.Item.BankAccountId).FirstOrDefault(b => b is not null) + ?? Choices?.Banks.FirstOrDefault(b => b.IsDefault)?.Id ?? Choices?.Banks.FirstOrDefault()?.Id; + _reference = null; + _fees = null; + _notes = null; + } + + private async Task CloseAsync() + { + _shown = null; + await OnClose.InvokeAsync(); + } + + private async Task SaveAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _date is not { } date || Rows.Count == 0) + { + return; + } + + _busy = true; + try + { + var payment = await Payments.RegisterAsync(actor, company, new PaymentInput( + Receipt ? PaymentDirection.Receipt : PaymentDirection.Disbursement, Rows[0].Item.PartyId, date, _methodId, _bankId, _fees ?? 0m, _reference, _notes, + [.. _lines.Where(l => l.Amount != 0m || l.Allowance != 0m).Select(l => new PaymentLineInput(l.Row.Item.Id, l.Amount, l.Allowance))])); + Toasts.Show(ToastKind.Success, T[Receipt ? "Treasury.Payment.ReceiptSaved" : "Treasury.Payment.PaymentSaved"], T.Money(payment.Amount)); + _shown = null; + await OnSaved.InvokeAsync(payment); + } + catch (ValidationFailedException ex) + { + Toasts.Show(ToastKind.Error, T["Treasury.NotDone"], TreasuryScreens.Errors(T, ex)); + } + finally + { + _busy = false; + } + } + + private sealed class Line(ScheduleRow row) + { + public ScheduleRow Row { get; } = row; + + public decimal Amount { get; set; } + + public decimal Allowance { get; set; } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Treasury/PaymentsPage.razor b/src/Khaemhat.Web/Components/Pages/Treasury/PaymentsPage.razor new file mode 100644 index 0000000..3002d91 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Treasury/PaymentsPage.razor @@ -0,0 +1,172 @@ +@page "/scadenzario/incassi" +@page "/scadenzario/pagamenti" +@attribute [Authorize] +@using Khaemhat.Application.Security +@using Khaemhat.Application.Treasury +@using Khaemhat.Core.Treasury +@using Khaemhat.Web.Ledger +@using Khaemhat.Web.Treasury +@inject ShellSession Session +@inject PaymentService Payments +@inject ToastService Toasts +@inject DialogService Dialogs +@inject NavigationManager Navigation +@inject TimeProvider Clock + +@* The collections or the payments of a period (SPEC §11.8): who, when, how much, on which bank, the documents they + settled and their entry; cancelling one gives the items back and takes the entry away. Those born from a + remittance are cancelled from the remittance. *@ + + + +
+
+ +

@T[Title]

+
@T[Receipts ? "Treasury.Payments.ReceiptsHint" : "Treasury.Payments.PaymentsHint"]
+
+
+ +
+ + +
+ + + + @T.Format("Treasury.Payments.Total", _rows.Count, T.Money(_rows.Sum(r => r.Payment.Amount))) +
+ @if (_rows.Count == 0) + { +

@T["Treasury.Payments.None"]

+ } + else + { +
+ + + + + + + + + + + + + + + + + + @foreach (var row in _rows) + { + var p = row.Payment; + + + + + + + + + + + + + + } + +
@T["Treasury.Fields.Date"]@T[Receipts ? "Treasury.Fields.Customer" : "Treasury.Fields.Supplier"]@T["Treasury.Payments.Documents"]@T["Treasury.Fields.Reference"]@T["Treasury.Fields.Bank"]@T["Treasury.Payments.Origin"]@T["Treasury.Fields.Amount"]@T["Treasury.Fields.Allowance"]@T["Treasury.Fields.Fees"]@T["Treasury.Payments.Entry"]
@T.Date(p.PaymentDate)@row.PartyName@row.Documents@p.Reference@(row.Bank ?? T["Treasury.Payment.Cash"])@T[TreasuryScreens.EnumKey(p.Origin)]@T.Money(p.Amount)@LedgerScreens.AmountText(T, p.AllowanceAmount)@LedgerScreens.AmountText(T, p.Fees) + @if (p.GlEntryId is { } entry) + { + @row.EntryNumber + } + + @if (CanWrite && p.Origin != PaymentOrigin.Remittance) + { + + } +
+
+ } +
+
+ +@code { + private IReadOnlyList _rows = []; + private DateOnly? _from; + private DateOnly? _to; + private bool _busy; + + private bool Receipts => !Navigation.Uri.Contains("/pagamenti", StringComparison.OrdinalIgnoreCase); + + private string Title => Receipts ? "Treasury.Payments.Receipts" : "Treasury.Payments.Payments"; + + private bool CanWrite => Session.Permissions.Allows(TreasuryPermissions.PaymentWrite); + + /// + protected override async Task OnParametersSetAsync() + { + await Session.EnsureLoadedAsync(); + var today = DateOnly.FromDateTime(Clock.GetLocalNow().DateTime); + _from ??= new DateOnly(today.Year, 1, 1); + _to ??= today.AddDays(30); + if (FinanceGuard.Allowed(Session, TreasuryPermissions.PaymentRead)) + { + await LoadAsync(); + } + } + + private async Task LoadAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _from is not { } from || _to is not { } to) + { + return; + } + + _rows = await Payments.ListAsync(actor, company, Receipts ? PaymentDirection.Receipt : PaymentDirection.Disbursement, from, to); + } + + private async Task SetFromAsync(DateOnly? date) + { + _from = date; + await LoadAsync(); + } + + private async Task SetToAsync(DateOnly? date) + { + _to = date; + await LoadAsync(); + } + + private async Task CancelAsync(PaymentRow row) + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company + || !await Dialogs.ConfirmAsync(new ConfirmRequest(T["Treasury.Payments.Cancel"], T.Format("Treasury.Payments.CancelText", T.Money(row.Payment.Amount), row.PartyName), T["Treasury.Payments.Cancel"], T["Common.Cancel"]))) + { + return; + } + + _busy = true; + try + { + await Payments.CancelAsync(actor, company, row.Payment.Id); + Toasts.Show(ToastKind.Success, T["Treasury.Payments.Cancelled"], null); + await LoadAsync(); + } + catch (ValidationFailedException ex) + { + Toasts.Show(ToastKind.Error, T["Treasury.NotDone"], TreasuryScreens.Errors(T, ex)); + } + finally + { + _busy = false; + } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Treasury/ReconciliationPage.razor b/src/Khaemhat.Web/Components/Pages/Treasury/ReconciliationPage.razor new file mode 100644 index 0000000..17d0e58 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Treasury/ReconciliationPage.razor @@ -0,0 +1,604 @@ +@page "/scadenzario/riconciliazione" +@attribute [Authorize] +@using Khaemhat.Application.Ledger +@using Khaemhat.Application.Security +@using Khaemhat.Application.Treasury +@using Khaemhat.Core.Accounting +@using Khaemhat.Core.Treasury +@using Khaemhat.Web.Ledger +@using Khaemhat.Web.Treasury +@inject ShellSession Session +@inject BankReconciliationService Reconciliation +@inject ScheduleService Schedule +@inject PaymentService Payments +@inject LedgerService Ledger +@inject ToastService Toasts +@inject TimeProvider Clock + +@* Bank reconciliation (SPEC §11.8, mockup 057): the statement imported from CAMT.053, CBI or CSV, the movements + matched by amount, date, reference and name with open items, recorded payments, F24, remittance credits and unpaid + effects, or by the saved rules for the recurring ones; the proposals confirmed one by one or all those above 90%, + the rest matched by hand, posted to an account or ignored. The difference between the bank and the books is what is + still to reconcile. *@ + + + +
+
+
@T["Shell.Menu.Finance"] / @T["Treasury.Reconciliation.Title"]
+

@T["Treasury.Reconciliation.Title"]

+
+
+ + + +
+ + + + + + +
+ + + + @if (_tab == "lines") + { + + @if (_lines.Count == 0) + { +

@T["Treasury.Reconciliation.None"]

+ } + else + { +
+ + + + + + + + + + + + + + + @foreach (var row in _lines) + { + var l = row.Line; + + + + + + + + + + + } + +
@T["Treasury.Fields.Date"]@T["Treasury.Reconciliation.Description"]@T["Treasury.Reconciliation.In"]@T["Treasury.Reconciliation.Out"]@T["Treasury.Fields.Status"]@T["Treasury.Reconciliation.Proposal"]@T["Treasury.Reconciliation.Confidence"]
@T.Date(l.BookingDate)@l.Description @row.PartyName@(l.Amount > 0m ? T.Money(l.Amount) : null)@(l.Amount < 0m ? T.Money(-l.Amount) : null)@T[TreasuryScreens.EnumKey(l.Status)] + @if (l.MatchKind != StatementMatchKind.None) + { + @T[TreasuryScreens.EnumKey(l.MatchKind)] · + } + @l.Proposal + @if (l.GlEntryId is { } entry) + { + @T["Treasury.Payments.Entry"] + } + @(l.Confidence > 0 ? l.Confidence + "%" : "—") + @if (l.Status == StatementLineStatus.Suggested) + { + + } + @if (l.Status is StatementLineStatus.ToMatch or StatementLineStatus.Suggested) + { + + + + + } + else + { + + } +
+
+ } +
@T["Treasury.Reconciliation.Footer"]
+
+ } + else if (_tab == "rules") + { + + + + + + @if (_rules.Count == 0) + { +

@T["Treasury.Rules.None"]

+ } + else + { + + + + + + + + + + + + + @foreach (var rule in _rules) + { + + + + + + + + + } + +
@T["Treasury.Rules.Name"]@T["Treasury.Rules.Pattern"]@T["Treasury.Rules.Direction"]@T["Treasury.Rules.Account"]@T["Treasury.Rules.Uses"]
@rule.Name@rule.Pattern@T[TreasuryScreens.EnumKey(rule.Direction)]@AccountText(rule.AccountId)@rule.Uses + + +
+ } +
+
+ } + else + { + + @if (_statements.Count == 0) + { +

@T["Treasury.Reconciliation.NoStatements"]

+ } + else + { + + + + + + + + + + + + + @foreach (var st in _statements) + { + + + + + + + + + } + +
@T["Treasury.Reconciliation.File"]@T["Treasury.Reconciliation.Format"]@T["Treasury.Fields.From"]@T["Treasury.Fields.To"]@T["Treasury.Reconciliation.Movements"]@T["Treasury.Reconciliation.Closing"]
@st.FileName@T[TreasuryScreens.EnumKey(st.Format)]@T.Date(st.FromDate)@T.Date(st.ToDate)@st.MovementCount@(st.ClosingBalance is { } c ? T.Money(c) : "—")
+ } +
+ } + + + + @if (_itemsFor is { } target) + { +

@target.Line.Description · @T.Money(target.Line.Amount)

+ + + + @foreach (var row in _items) + { + + + + + + + + } + +
@row.PartyName@row.Item.DocumentNumber@T.Date(row.Item.DueDate)@T.Money(row.Item.Residual)
+

@T.Format("Treasury.Reconciliation.Chosen", T.Money(_items.Where(r => _chosen.Contains(r.Item.Id)).Sum(r => r.Item.Residual)))

+ } +
+
+ + +
+
+ + + + @if (_paymentsFor is { } target) + { +

@target.Line.Description · @T.Money(target.Line.Amount)

+ @if (_payments.Count == 0) + { +

@T["Treasury.Payments.None"]

+ } + + + @foreach (var p in _payments) + { + + + + + + + + } + +
@T.Date(p.Payment.PaymentDate)@p.PartyName@p.Payment.Reference@T.Money(p.Payment.Amount + p.Payment.Fees)
+ } +
+
+ +
+
+ + + + @if (_postFor is { } target) + { +

@target.Line.Description · @T.Money(target.Line.Amount)

+
+ + + +
+ } +
+
+ + +
+
+ + + +
+ + + + + + +
+
+
+ + +
+
+
+ +@code { + private string _tab = "lines"; + private string _show = "open"; + private long? _bankId; + private TreasuryChoices? _choices; + private BankPosition? _position; + private IReadOnlyList _lines = []; + private IReadOnlyList _statements = []; + private IReadOnlyList _rules = []; + private IReadOnlyList _accounts = []; + private bool _busy; + + private StatementLineRow? _itemsFor; + private IReadOnlyList _items = []; + private readonly HashSet _chosen = []; + private StatementLineRow? _paymentsFor; + private IReadOnlyList _payments = []; + private StatementLineRow? _postFor; + private long? _postAccount; + private string? _postDescription; + private string? _postRule; + + private bool _ruleOpen; + private long? _ruleId; + private string? _ruleName; + private string? _rulePattern; + private BankRuleDirection _ruleDirection; + private long? _ruleAccount; + private string? _ruleDescription; + private bool _ruleDisabled; + + private IReadOnlyList> Banks => TreasuryScreens.BankChoices(_choices?.Banks ?? []); + + private IReadOnlyList> Shows => + [ + new("open", T["Treasury.Reconciliation.ShowOpen"]), + new("all", T["Treasury.All"]), + ]; + + private IReadOnlyList> Directions => TreasuryScreens.Choices(T); + + private IReadOnlyList> Accounts => [.. _accounts.Where(a => a.Postable && !a.Disabled).Select(a => new KhOption(a.Id, a.Code + " " + a.Description))]; + + private IReadOnlyList Tabs => + [ + new("lines", "list", T["Treasury.Reconciliation.Lines"], _position?.ToMatch), + new("rules", "zap", T["Treasury.Rules.Title"], _rules.Count), + new("statements", "file", T["Treasury.Reconciliation.Statements"]), + ]; + + private IReadOnlyList Stats + { + get + { + var bank = _choices?.Banks.FirstOrDefault(b => b.Id == _bankId); + var p = _position; + var difference = p?.BankBalance is { } balance ? balance - p.BookBalance : (decimal?)null; + return + [ + new(T["Treasury.Reconciliation.Account"], bank is null ? "—" : bank.BankName ?? bank.Description), + new(T["Treasury.Reconciliation.BankBalance"], p?.BankBalance is { } b ? T.Money(b) + (p.BankBalanceDate is { } d ? " · " + T.Date(d) : null) : "—"), + new(T["Treasury.Reconciliation.BookBalance"], p is null ? "—" : T.Money(p.BookBalance)), + new(T["Treasury.Reconciliation.Difference"], difference is { } diff ? T.Money(diff) : "—", difference is { } x && x != 0m ? KhTone.Warning : KhTone.Ok), + new(T["Treasury.Reconciliation.ToMatch"], p is null ? "—" : T.Format("Treasury.Reconciliation.ToMatchText", p.ToMatch, T.Money(p.ToMatchAmount))), + ]; + } + } + + /// + protected override async Task OnInitializedAsync() + { + await Session.EnsureLoadedAsync(); + if (!FinanceGuard.Allowed(Session, TreasuryPermissions.BankReconcile)) + { + return; + } + + _choices = await Schedule.ChoicesAsync(Session.Actor!, Session.Company!.Code); + _bankId = _choices.Banks.FirstOrDefault(b => b.IsDefault)?.Id ?? _choices.Banks.FirstOrDefault()?.Id; + if (Session.Permissions.Allows(LedgerPermissions.EntryRead)) + { + _accounts = await Ledger.AccountsAsync(Session.Actor!, Session.Company.Code); + } + + _rules = await Reconciliation.RulesAsync(Session.Actor!, Session.Company.Code); + await LoadAsync(); + } + + private async Task LoadAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _bankId is not { } bank) + { + return; + } + + _lines = await Reconciliation.LinesAsync(actor, company, bank, _show == "open"); + _position = await Reconciliation.PositionAsync(actor, company, bank); + _statements = await Reconciliation.StatementsAsync(actor, company, bank); + } + + private string AccountText(long id) => _accounts.FirstOrDefault(a => a.Id == id) is { } a ? a.Code + " " + a.Description : id.ToString(T.Culture); + + private async Task SetBankAsync(long? bank) + { + _bankId = bank; + await LoadAsync(); + } + + private async Task SetShowAsync(string show) + { + _show = show; + await LoadAsync(); + } + + private async Task ImportAsync(InputFileChangeEventArgs e) => await RunAsync(async (actor, company) => + { + if (_bankId is not { } bank) + { + return; + } + + using var buffer = new MemoryStream(); + await using (var stream = e.File.OpenReadStream(10 * 1024 * 1024)) + { + await stream.CopyToAsync(buffer); + } + + var result = await Reconciliation.ImportAsync(actor, company, bank, e.File.Name, buffer.ToArray()); + Toasts.Show(ToastKind.Success, T.Format("Treasury.Reconciliation.Imported", result.Added, result.Duplicates, result.Suggested), null); + await LoadAsync(); + }); + + private async Task RefreshAsync() => await RunAsync(async (actor, company) => + { + if (_bankId is { } bank) + { + var found = await Reconciliation.RefreshAsync(actor, company, bank); + Toasts.Show(ToastKind.Info, T.Format("Treasury.Reconciliation.Refreshed", found), null); + await LoadAsync(); + } + }); + + private async Task ConfirmAllAsync() => await RunAsync(async (actor, company) => + { + if (_bankId is { } bank) + { + var done = await Reconciliation.ConfirmAllAsync(actor, company, bank); + Toasts.Show(ToastKind.Success, T.Format("Treasury.Reconciliation.Confirmed", done), null); + await LoadAsync(); + } + }); + + private async Task ConfirmAsync(BankStatementLine line) => await RunAsync(async (actor, company) => + { + await Reconciliation.ConfirmAsync(actor, company, line.Id); + await LoadAsync(); + }); + + private async Task IgnoreAsync(BankStatementLine line) => await RunAsync(async (actor, company) => + { + await Reconciliation.IgnoreAsync(actor, company, line.Id); + await LoadAsync(); + }); + + private async Task ResetAsync(BankStatementLine line) => await RunAsync(async (actor, company) => + { + await Reconciliation.ResetAsync(actor, company, line.Id); + await LoadAsync(); + }); + + private async Task OpenItemsAsync(StatementLineRow row) + { + _itemsFor = row; + _chosen.Clear(); + await LoadItemsAsync(row.PartyName); + } + + private async Task LoadItemsAsync(string? search) + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _itemsFor is not { } target) + { + return; + } + + var direction = target.Line.Amount > 0m ? OpenItemDirection.Receivable : OpenItemDirection.Payable; + _items = [.. (await Schedule.ItemsAsync(actor, company, new ScheduleFilter(direction, ScheduleView.Open, Search: string.IsNullOrWhiteSpace(search) ? null : search))).Rows + .Where(r => r.Item.Status != OpenItemStatus.InRemittance).Take(50)]; + } + + private async Task SearchItemsAsync(ChangeEventArgs e) => await LoadItemsAsync(e.Value?.ToString()); + + private void ToggleItem(long id, bool on) + { + if (on) + { + _chosen.Add(id); + } + else + { + _chosen.Remove(id); + } + } + + private async Task MatchItemsAsync() => await RunAsync(async (actor, company) => + { + if (_itemsFor is { } target) + { + await Reconciliation.MatchItemsAsync(actor, company, target.Line.Id, [.. _items.Where(r => _chosen.Contains(r.Item.Id)).OrderBy(r => r.Item.DueDate).Select(r => r.Item.Id)]); + _itemsFor = null; + await LoadAsync(); + } + }); + + private async Task OpenPaymentsAsync(StatementLineRow row) + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _paymentsFor = row; + var day = row.Line.BookingDate; + var direction = row.Line.Amount > 0m ? PaymentDirection.Receipt : PaymentDirection.Disbursement; + _payments = [.. (await Payments.ListAsync(actor, company, direction, day.AddDays(-45), day.AddDays(15))).Where(p => p.Payment.StatementLineId is null)]; + } + + private async Task MatchPaymentAsync(long paymentId) => await RunAsync(async (actor, company) => + { + if (_paymentsFor is { } target) + { + await Reconciliation.MatchPaymentAsync(actor, company, target.Line.Id, paymentId); + _paymentsFor = null; + await LoadAsync(); + } + }); + + private Task OpenPostAsync(StatementLineRow row) + { + _postFor = row; + _postAccount = null; + _postDescription = row.Line.Description; + _postRule = null; + return Task.CompletedTask; + } + + private async Task PostAsync() => await RunAsync(async (actor, company) => + { + if (_postFor is { } target && _postAccount is { } account) + { + await Reconciliation.PostAsync(actor, company, target.Line.Id, account, _postDescription, string.IsNullOrWhiteSpace(_postRule) ? null : _postRule.Trim()); + _postFor = null; + _rules = await Reconciliation.RulesAsync(actor, company); + await LoadAsync(); + } + }); + + private Task OpenRuleAsync(BankMatchRule? rule) + { + _ruleId = rule?.Id; + _ruleName = rule?.Name; + _rulePattern = rule?.Pattern; + _ruleDirection = rule?.Direction ?? BankRuleDirection.Out; + _ruleAccount = rule?.AccountId; + _ruleDescription = rule?.EntryDescription; + _ruleDisabled = rule?.Disabled ?? false; + _ruleOpen = true; + return Task.CompletedTask; + } + + private async Task SaveRuleAsync() => await RunAsync(async (actor, company) => + { + if (_ruleAccount is { } account) + { + await Reconciliation.SaveRuleAsync(actor, company, new BankRuleInput(_ruleId, _ruleName ?? string.Empty, _rulePattern ?? string.Empty, _ruleDirection, account, _ruleDescription, _ruleDisabled)); + _ruleOpen = false; + _rules = await Reconciliation.RulesAsync(actor, company); + } + }); + + private async Task DeleteRuleAsync(BankMatchRule rule) => await RunAsync(async (actor, company) => + { + await Reconciliation.DeleteRuleAsync(actor, company, rule.Id); + _rules = await Reconciliation.RulesAsync(actor, company); + }); + + private async Task RunAsync(Func action) + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _busy = true; + try + { + await action(actor, company); + } + catch (ValidationFailedException ex) + { + Toasts.Show(ToastKind.Error, T["Treasury.NotDone"], TreasuryScreens.Errors(T, ex)); + } + finally + { + _busy = false; + } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Treasury/RemittancesPage.razor b/src/Khaemhat.Web/Components/Pages/Treasury/RemittancesPage.razor new file mode 100644 index 0000000..71c1945 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Treasury/RemittancesPage.razor @@ -0,0 +1,528 @@ +@page "/scadenzario/distinte" +@attribute [Authorize] +@using Khaemhat.Application.Security +@using Khaemhat.Application.Treasury +@using Khaemhat.Core.Treasury +@using Khaemhat.Web.Ledger +@using Khaemhat.Web.Treasury +@inject ShellSession Session +@inject RemittanceService Remittances +@inject ScheduleService Schedule +@inject ToastService Toasts +@inject DialogService Dialogs +@inject IJSRuntime JS +@inject TimeProvider Clock + +@* The remittances (SPEC §11.8, mockup 055): RiBa in the CBI file, SEPA direct debits (pain.008) and SEPA credit + transfers to the suppliers (pain.001). A new remittance gathers the items due by a date with the method of its kind, + checks the bank coordinates and the mandates; then the file, the presentation with its entry, the credit of the + bank and the effects that come back unpaid, which reopen the item with the fees. *@ + + + +
+
+
@T["Shell.Menu.Finance"] / @T["Treasury.Remittances.Title"]
+

@T["Treasury.Remittances.Heading"]

+
@T["Treasury.Remittances.Hint"]
+
+
+ + + + @if (_tab == "new") + { +
+ +
+ + + + + + + @if (_kind != RemittanceKind.SepaCreditTransfer) + { + + } + +
+ + @if (CanWrite) + { + + } +
+ + @if (_candidates.Count == 0) + { +

@T["Treasury.Remittances.NoCandidates"]

+ } + else + { +
+ + + + + + + + + + + + + + + @foreach (var c in _candidates) + { + var item = c.Row.Item; + var late = item.DueDate < Today; + + + + + + + + + + + } + +
@T["Treasury.Select"]@T[_kind == RemittanceKind.SepaCreditTransfer ? "Treasury.Fields.Supplier" : "Treasury.Fields.Customer"]@T["Treasury.Fields.Document"]@T["Treasury.Fields.Installment"]@T["Treasury.Fields.DueDate"]@T["Treasury.Fields.Amount"]@T["Treasury.Remittances.PartyBank"]@T["Treasury.Remittances.Check"]
+ + @c.Row.PartyName@item.DocumentNumber@item.Installment@T.Date(item.DueDate)@T.Money(item.Residual)@TreasuryScreens.ShortIban(c.Iban) @(c.Mandate is { } m ? "· " + m.Reference : null) + @if (!c.Ready) + { + @string.Join(", ", c.Problems.Select(p => T[p])) + } + else if (late) + { + @T["Treasury.Remittances.Late"] + } + else + { + @T["Treasury.Remittances.Ok"] + } +
+
+ } +
@T["Treasury.Remittances.Footer"]
+
+
+ } + else + { + +
+ +
+ @if (_list.Count == 0) + { +

@T["Treasury.Remittances.None"]

+ } + else + { + + + + + + + + + + + + + + @foreach (var row in _list) + { + var r = row.Remittance; + + + + + + + + + + } + +
@T["Treasury.Fields.Number"]@T["Treasury.Remittances.Kind"]@T["Treasury.Fields.Bank"]@T["Treasury.Remittances.PresentationDate"]@T["Treasury.Remittances.Effects"]@T["Treasury.Fields.Total"]@T["Treasury.Fields.Status"]
@TreasuryScreens.Number(r)@T[TreasuryScreens.EnumKey(r.Kind)] @(r.Advance ? "· " + T["Treasury.Remittances.AdvanceShort"] : null)@row.Bank@T.Date(r.PresentationDate)@r.ItemCount@T.Money(r.TotalAmount)@T[TreasuryScreens.EnumKey(r.Status)]
+ } +
+ + @if (_open is { } open) + { + var rem = open.Row.Remittance; + + + @if (CanWrite) + { + @if (rem.Status is RemittanceStatus.Draft or RemittanceStatus.Generated) + { + + + + } + @if (rem.Status == RemittanceStatus.Presented) + { + + } + } + + + + + + + + + + + + + + + + + @foreach (var line in open.Lines) + { + var l = line.Line; + + + + + + + + + + + } + +
@T["Treasury.Fields.Party"]@T["Treasury.Fields.Document"]@T["Treasury.Fields.DueDate"]@T["Treasury.Fields.Iban"]@T["Treasury.Remittances.EndToEnd"]@T["Treasury.Fields.Amount"]@T["Treasury.Fields.Status"]
@line.PartyName@line.Item?.DocumentNumber@T.Date(l.DueDate)@TreasuryScreens.ShortIban(l.Iban) @(line.Mandate is { } m ? "· " + m : null)@l.EndToEndId@T.Money(l.Amount) + @T[TreasuryScreens.EnumKey(l.Status)] + @if (l.UnpaidOn is { } u) + { + @T.Date(u) · @T.Money(l.UnpaidFees) + } + + @if (CanWrite && rem.Status is RemittanceStatus.Draft or RemittanceStatus.Generated) + { + + } + else if (CanWrite && rem.Kind != RemittanceKind.SepaCreditTransfer && rem.Status is RemittanceStatus.Presented or RemittanceStatus.Closed && l.Status != RemittanceLineStatus.Unpaid) + { + + } +
+
+ + @(rem.FileName is { } file ? T.Format("Treasury.Remittances.FileName", file) : null) + @(rem.CreditedOn is { } credited ? " · " + T.Format("Treasury.Remittances.CreditedOn", T.Date(credited)) : null) + + @if (rem.GlEntryId is { } entry) + { + @T["Treasury.Remittances.Entry"] + } + @if (rem.CreditEntryId is { } credit) + { + @T["Treasury.Remittances.CreditEntry"] + } +
+
+
+ } + } + + + +

@T["Treasury.Remittances.CreditText"]

+
+ +
+
+
+ + +
+
+ + + +

@T["Treasury.Remittances.UnpaidText"]

+
+ + +
+
+
+ + +
+
+
+ +@code { + private string _tab = "new"; + private RemittanceKind _kind = RemittanceKind.Riba; + private long? _bankId; + private DateOnly? _presentation; + private DateOnly? _dueUntil; + private bool _advance; + private string? _notes; + private IReadOnlyList _candidates = []; + private readonly HashSet _chosen = []; + private TreasuryChoices? _choices; + private int _year; + private IReadOnlyList _list = []; + private (RemittanceRow Row, IReadOnlyList Lines)? _open; + private bool _busy; + private bool _creditOpen; + private DateOnly? _creditOn; + private RemittanceLine? _unpaid; + private DateOnly? _unpaidOn; + private decimal? _unpaidFees; + + private DateOnly Today => DateOnly.FromDateTime(Clock.GetLocalNow().DateTime); + + private bool CanWrite => Session.Permissions.Allows(TreasuryPermissions.ScheduleWrite); + + private decimal SelectedTotal => _candidates.Where(c => _chosen.Contains(c.Row.Item.Id)).Sum(c => c.Row.Item.Residual); + + private IReadOnlyList Tabs => + [ + new("new", "plus", T["Treasury.Remittances.New"]), + new("history", "list", T["Treasury.Remittances.History"]), + ]; + + private IReadOnlyList> Kinds => TreasuryScreens.Choices(T); + + private IReadOnlyList> Banks => TreasuryScreens.BankChoices(_choices?.Banks ?? []); + + private IReadOnlyList> Years => [.. Enumerable.Range(Today.Year - 3, 5).Select(y => new KhOption(y, y.ToString(System.Globalization.CultureInfo.InvariantCulture)))]; + + private IReadOnlyList Steps => + [ + new(T["Treasury.Remittances.Step.Select"], T.Format("Treasury.Remittances.Step.SelectText", _chosen.Count, _candidates.Count(c => !c.Ready))), + new(T["Treasury.Remittances.Step.Check"], T["Treasury.Remittances.Step.CheckText"]), + new(T["Treasury.Remittances.Step.File"], T[_kind == RemittanceKind.Riba ? "Treasury.Remittances.Step.FileCbi" : "Treasury.Remittances.Step.FileXml"]), + new(T["Treasury.Remittances.Step.Post"], T["Treasury.Remittances.Step.PostText"]), + new(T["Treasury.Remittances.Step.Credit"], T["Treasury.Remittances.Step.CreditText"]), + ]; + + /// + protected override async Task OnInitializedAsync() + { + await Session.EnsureLoadedAsync(); + _year = Today.Year; + _presentation = Today; + _dueUntil = Today.AddDays(30); + if (FinanceGuard.Allowed(Session, TreasuryPermissions.ScheduleRead)) + { + _choices = await Schedule.ChoicesAsync(Session.Actor!, Session.Company!.Code); + _bankId = _choices.Banks.FirstOrDefault(b => b.IsDefault)?.Id ?? _choices.Banks.FirstOrDefault()?.Id; + await LoadCandidatesAsync(); + } + } + + private async Task LoadCandidatesAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _dueUntil is not { } until) + { + return; + } + + _candidates = await Remittances.CandidatesAsync(actor, company, _kind, until); + _chosen.Clear(); + _chosen.UnionWith(_candidates.Where(c => c.Ready && c.Row.Item.DueDate >= Today).Select(c => c.Row.Item.Id)); + } + + private async Task LoadListAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _list = await Remittances.ListAsync(actor, company, _year); + } + + private async Task SetTabAsync(string tab) + { + _tab = tab; + if (tab == "history") + { + await LoadListAsync(); + } + else + { + await LoadCandidatesAsync(); + } + } + + private async Task SetKindAsync(RemittanceKind kind) + { + _kind = kind; + await LoadCandidatesAsync(); + } + + private async Task SetDueUntilAsync(DateOnly? date) + { + _dueUntil = date; + await LoadCandidatesAsync(); + } + + private async Task SetYearAsync(int year) + { + _year = year; + _open = null; + await LoadListAsync(); + } + + private void Toggle(long id, bool on) + { + if (on) + { + _chosen.Add(id); + } + else + { + _chosen.Remove(id); + } + } + + private async Task OpenAsync(long id) => await RunAsync(async (actor, company) => _open = await Remittances.GetAsync(actor, company, id)); + + private async Task ReloadOpenAsync(long id) + { + await LoadListAsync(); + await OpenAsync(id); + } + + private async Task CreateAsync() => await RunAsync(async (actor, company) => + { + if (_bankId is { } bank && _presentation is { } presented && _dueUntil is { } until) + { + var remittance = await Remittances.CreateAsync(actor, company, new RemittanceInput(_kind, bank, presented, until, _advance, _notes, [.. _chosen])); + Toasts.Show(ToastKind.Success, T["Treasury.Remittances.Created"], TreasuryScreens.Number(remittance)); + _tab = "history"; + _year = remittance.Year; + await ReloadOpenAsync(remittance.Id); + } + }); + + private async Task FileAsync() => await RunAsync(async (actor, company) => + { + if (_open is { } open) + { + await LedgerScreens.DownloadAsync(JS, await Remittances.FileAsync(actor, company, open.Row.Remittance.Id)); + await ReloadOpenAsync(open.Row.Remittance.Id); + } + }); + + private async Task PresentAsync() + { + if (_open is not { } open + || !await Dialogs.ConfirmAsync(new ConfirmRequest(T["Treasury.Remittances.Present"], T["Treasury.Remittances.PresentText"], T["Treasury.Remittances.Present"], T["Common.Cancel"]))) + { + return; + } + + await RunAsync(async (actor, company) => + { + await Remittances.PresentAsync(actor, company, open.Row.Remittance.Id); + Toasts.Show(ToastKind.Success, T["Treasury.Remittances.Presented"], null); + await ReloadOpenAsync(open.Row.Remittance.Id); + }); + } + + private void OpenCredit(Remittance remittance) + { + _creditOn = remittance.DueUntil <= Today ? remittance.DueUntil : Today; + _creditOpen = true; + } + + private async Task CreditAsync() => await RunAsync(async (actor, company) => + { + if (_open is { } open && _creditOn is { } date) + { + await Remittances.CreditAsync(actor, company, open.Row.Remittance.Id, date); + _creditOpen = false; + await ReloadOpenAsync(open.Row.Remittance.Id); + } + }); + + private void OpenUnpaid(RemittanceLine line) + { + _unpaid = line; + _unpaidOn = Today; + _unpaidFees = null; + } + + private async Task UnpaidAsync() => await RunAsync(async (actor, company) => + { + if (_open is { } open && _unpaid is { } line && _unpaidOn is { } date) + { + await Remittances.UnpaidAsync(actor, company, line.Id, date, _unpaidFees ?? 0m); + _unpaid = null; + Toasts.Show(ToastKind.Warning, T["Treasury.Remittances.UnpaidDone"], null); + await ReloadOpenAsync(open.Row.Remittance.Id); + } + }); + + private async Task RemoveLineAsync(RemittanceLine line) => await RunAsync(async (actor, company) => + { + if (_open is { } open) + { + await Remittances.RemoveLineAsync(actor, company, line.Id); + await ReloadOpenAsync(open.Row.Remittance.Id); + } + }); + + private async Task DeleteAsync() + { + if (_open is not { } open + || !await Dialogs.ConfirmAsync(new ConfirmRequest(T["Treasury.Remittances.Delete"], T["Treasury.Remittances.DeleteText"], T["Treasury.Remittances.Delete"], T["Common.Cancel"]) { Danger = true })) + { + return; + } + + await RunAsync(async (actor, company) => + { + await Remittances.DeleteAsync(actor, company, open.Row.Remittance.Id); + _open = null; + await LoadListAsync(); + }); + } + + private async Task RunAsync(Func action) + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _busy = true; + try + { + await action(actor, company); + } + catch (ValidationFailedException ex) + { + Toasts.Show(ToastKind.Error, T["Treasury.NotDone"], TreasuryScreens.Errors(T, ex)); + } + finally + { + _busy = false; + } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Treasury/SchedulePage.razor b/src/Khaemhat.Web/Components/Pages/Treasury/SchedulePage.razor new file mode 100644 index 0000000..f893a8e --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Treasury/SchedulePage.razor @@ -0,0 +1,397 @@ +@page "/scadenzario" +@page "/scadenzario/scadenze" +@attribute [Authorize] +@using Khaemhat.Application.Security +@using Khaemhat.Application.Treasury +@using Khaemhat.Core.Accounting +@using Khaemhat.Core.Treasury +@using Khaemhat.Web.Ledger +@using Khaemhat.Web.Treasury +@inject ShellSession Session +@inject ScheduleService Schedule +@inject ToastService Toasts +@inject IJSRuntime JS +@inject TimeProvider Clock + +@* The schedule (SPEC §11.8, mockups 053 and 054): the open items of customers and suppliers with the aging of what is + past due, the filters by state and party, the collection or payment of the items chosen, the change of due date, + method or dispute of one item, the statement of a party and the export of the grid. *@ + + + +
+
+
@T["Shell.Menu.Finance"] / @T["Treasury.Schedule.Title"]
+

@T["Treasury.Schedule.Heading"]

+
@T["Treasury.Schedule.Hint"]
+
+
+ @if (_result is { } r) + { + @T.Format("Treasury.Schedule.OpenTotal", T.Money(r.Residual)) + @T.Format("Treasury.Schedule.OverdueTotal", T.Money(r.Overdue)) + } +
+ + @if (_result is { } result) + { +
+ @T.Format("Treasury.Aging.Count", result.Aging.CountNotDue) + @T.Format("Treasury.Aging.Count", result.Aging.Count1To30) + @T.Format("Treasury.Aging.Count", result.Aging.Count31To60) + @T.Format("Treasury.Aging.Count", result.Aging.Count61To90) + @T.Format("Treasury.Aging.Count", result.Aging.CountOver90) +
+ } + + +
+ + + + +
+ + +
+ +
+
+ @if (CanPay) + { + + } + + @T["Treasury.Schedule.SelectHint"] +
+ @if (_result is not { Rows.Count: > 0 } rows) + { +

@T["Treasury.Schedule.None"]

+ } + else + { +
+ + + + + + + + + + + + + + + + + + + @foreach (var row in rows.Rows) + { + var item = row.Item; + var selectable = !item.Closed && item.Status != OpenItemStatus.InRemittance; + + + + + + + + + + + + + + + } + +
@T["Treasury.Select"]@T[_direction == OpenItemDirection.Receivable ? "Treasury.Fields.Customer" : "Treasury.Fields.Supplier"]@T["Treasury.Fields.Document"]@T["Treasury.Fields.Installment"]@T["Treasury.Fields.DueDate"]@T["Treasury.Fields.Days"]@T["Treasury.Fields.Method"]@T["Treasury.Fields.Amount"]@T[_direction == OpenItemDirection.Receivable ? "Treasury.Payment.Collected" : "Treasury.Payment.Paid"]@T["Treasury.Fields.Residual"]@T["Treasury.Fields.Status"]
+ @if (selectable) + { + + } + @row.PartyName + @if (item.EntryId > 0) + { + @item.DocumentNumber + } + else + { + @item.DocumentNumber + } + @item.Installment@T.Date(item.DueDate)@(item.Closed ? null : row.DaysOverdue.ToString(T.Culture))@(row.MethodDescription ?? row.Method)@T.Money(item.Amount)@T.Money(item.PaidAmount)@T.Money(item.Residual) + @TreasuryScreens.StatusText(T, item, Today) + @if (row.Remittance is { } remittance) + { + @remittance + } + + @if (CanWrite && !item.Closed) + { + + } +
+
+
+ @T.Format("Treasury.Schedule.Footer", rows.Rows.Count, _selected.Count, T.Money(SelectedRows.Sum(r => r.Item.Residual))) +
+ } +
+ + + + + + @if (_edit is { } edit) + { +

@T.Format("Treasury.Schedule.EditText", edit.Item.DocumentNumber ?? string.Empty, edit.Item.Installment, edit.PartyName)

+
+ + + + + +
+ } +
+
+ + +
+
+ + + + @if (_statement is { } st) + { +

@st.Party.Name · @T.Format("Treasury.Statement.At", T.Date(st.Day))

+
+ + + +
+ + + + + + + + + + + + @foreach (var row in st.Items) + { + + + + + + + + } + +
@T["Treasury.Fields.Document"]@T["Treasury.Fields.DueDate"]@T["Treasury.Fields.Amount"]@T["Treasury.Fields.Residual"]@T["Treasury.Fields.Status"]
@row.Item.DocumentNumber @(row.Item.Installment > 1 ? "· " + row.Item.Installment : null)@T.Date(row.Item.DueDate)@T.Money(row.Item.Amount)@T.Money(row.Item.Residual)@TreasuryScreens.StatusText(T, row.Item, st.Day)
+ @if (st.Payments.Count > 0) + { +

@T["Treasury.Statement.Payments"]

+ + + @foreach (var p in st.Payments) + { + + + + + + } + +
@T.Date(p.PaymentDate)@p.Reference@T.Money(p.Amount)
+ } + } +
+
+ +
+
+
+ +@code { + private OpenItemDirection _direction = OpenItemDirection.Receivable; + private ScheduleView _view = ScheduleView.Open; + private long? _methodId; + private string? _search; + private ScheduleResult? _result; + private TreasuryChoices? _choices; + private readonly HashSet _selected = []; + private bool _busy; + private bool _paymentOpen; + private IReadOnlyList _paymentRows = []; + private ScheduleRow? _edit; + private DateOnly? _editDue; + private long? _editMethod; + private long? _editBank; + private bool _editDisputed; + private string? _editNotes; + private PartyStatement? _statement; + + /// The direction asked by the address (?fornitori). + [SupplyParameterFromQuery(Name = "vista")] + public string? Side { get; set; } + + private DateOnly Today => DateOnly.FromDateTime(Clock.GetLocalNow().DateTime); + + private bool CanWrite => Session.Permissions.Allows(TreasuryPermissions.ScheduleWrite); + + private bool CanPay => Session.Permissions.Allows(TreasuryPermissions.PaymentWrite); + + private IEnumerable SelectedRows => _result?.Rows.Where(r => _selected.Contains(r.Item.Id)) ?? []; + + private bool OnePartySelected => _selected.Count > 0 && SelectedRows.Select(r => r.Item.PartyId).Distinct().Count() == 1; + + private IReadOnlyList> Views => TreasuryScreens.Choices(T); + + private IReadOnlyList> Methods => TreasuryScreens.MethodChoices(_choices?.Methods ?? []); + + private IReadOnlyList> Banks => TreasuryScreens.BankChoices(_choices?.Banks ?? []); + + /// + protected override async Task OnInitializedAsync() + { + await Session.EnsureLoadedAsync(); + if (string.Equals(Side, "fornitori", StringComparison.Ordinal)) + { + _direction = OpenItemDirection.Payable; + } + + if (FinanceGuard.Allowed(Session, TreasuryPermissions.ScheduleRead)) + { + _choices = await Schedule.ChoicesAsync(Session.Actor!, Session.Company!.Code); + await LoadAsync(); + } + } + + private ScheduleFilter Filter => new(_direction, _view, null, null, null, _methodId, string.IsNullOrWhiteSpace(_search) ? null : _search.Trim()); + + private async Task LoadAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _result = await Schedule.ItemsAsync(actor, company, Filter); + _selected.IntersectWith(_result.Rows.Select(r => r.Item.Id)); + } + + private async Task SetDirectionAsync(OpenItemDirection direction) + { + _direction = direction; + _selected.Clear(); + await LoadAsync(); + } + + private async Task SetViewAsync(ScheduleView view) + { + _view = view; + await LoadAsync(); + } + + private async Task SetMethodAsync(long? method) + { + _methodId = method; + await LoadAsync(); + } + + private async Task SearchAsync(ChangeEventArgs e) + { + _search = e.Value?.ToString(); + await LoadAsync(); + } + + private void Toggle(long id, bool on) + { + if (on) + { + _selected.Add(id); + } + else + { + _selected.Remove(id); + } + } + + private void OpenPayment() + { + _paymentRows = [.. SelectedRows.OrderBy(r => r.Item.DueDate)]; + _paymentOpen = true; + } + + private async Task PaidAsync(Payment payment) + { + _paymentOpen = false; + _selected.Clear(); + await LoadAsync(); + } + + private void OpenEdit(ScheduleRow row) + { + _edit = row; + _editDue = row.Item.DueDate; + _editMethod = row.Item.PaymentMethodId; + _editBank = row.Item.BankAccountId; + _editDisputed = row.Item.Disputed; + _editNotes = row.Item.Notes; + } + + private async Task SaveEditAsync() => await RunAsync(async (actor, company) => + { + if (_edit is { } edit && _editDue is { } due) + { + await Schedule.UpdateAsync(actor, company, edit.Item.Id, new OpenItemChange(due, _editMethod, _editBank, _editDisputed, _editNotes)); + _edit = null; + Toasts.Show(ToastKind.Success, T["Treasury.Saved"], null); + await LoadAsync(); + } + }); + + private async Task StatementAsync() => await RunAsync(async (actor, company) => + { + if (SelectedRows.FirstOrDefault() is { } row) + { + _statement = await Schedule.StatementAsync(actor, company, row.Item.PartyId, _direction); + } + }); + + private async Task ExportAsync() => await RunAsync(async (actor, company) => await LedgerScreens.DownloadAsync(JS, await Schedule.ExportAsync(actor, company, Filter))); + + private async Task RunAsync(Func action) + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _busy = true; + try + { + await action(actor, company); + } + catch (ValidationFailedException ex) + { + Toasts.Show(ToastKind.Error, T["Treasury.NotDone"], TreasuryScreens.Errors(T, ex)); + } + finally + { + _busy = false; + } + } +} diff --git a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs index c8d74a9..0f30e22 100644 --- a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs +++ b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs @@ -244,6 +244,9 @@ internal static class KhaemhatServices services.AddSingleton(); services.AddSingleton(sp => sp.GetRequiredService()); services.AddSingleton(sp => sp.GetRequiredService()); + services.AddSingleton(); + services.AddSingleton(sp => sp.GetRequiredService()); + services.AddSingleton(sp => sp.GetRequiredService()); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); diff --git a/src/Khaemhat.Web/Resources/it-IT/Dashboard.json b/src/Khaemhat.Web/Resources/it-IT/Dashboard.json index b09b36b..0f7cc77 100644 --- a/src/Khaemhat.Web/Resources/it-IT/Dashboard.json +++ b/src/Khaemhat.Web/Resources/it-IT/Dashboard.json @@ -50,7 +50,8 @@ }, "Areas": { "System": "Sistema", - "Notifications": "Avvisi" + "Notifications": "Avvisi", + "Treasury": "Tesoreria" }, "Coming": { "Text": "Questo widget si riempie con i dati di {0}, in arrivo con la milestone {1}. Intanto puoi già metterlo dove ti serve.", @@ -71,7 +72,10 @@ "TrialEnds": "Fine del periodo di prova", "JobRanOnce": "Attività programmata", "JobRanTimes": "Eseguita {0} volte oggi", - "JobFailed": "Attività «{0}» non riuscita" + "JobFailed": "Attività «{0}» non riuscita", + "DueReceivable": "Incasso da {0}: {1}", + "DuePayable": "Pagamento a {0}: {1}", + "Overdue": "{0} partite di clienti scadute da incassare ({1})" }, "Widgets": { "Kpi": { diff --git a/src/Khaemhat.Web/Resources/it-IT/Ledger.json b/src/Khaemhat.Web/Resources/it-IT/Ledger.json index 7522976..b521206 100644 --- a/src/Khaemhat.Web/Resources/it-IT/Ledger.json +++ b/src/Khaemhat.Web/Resources/it-IT/Ledger.json @@ -413,7 +413,14 @@ "StampDuty": "Bollo", "Rounding": "Arrotondamenti", "VatSettlement": "Erario c/IVA", - "SplitPaymentVat": "IVA split payment" + "SplitPaymentVat": "IVA split payment", + "AllowanceIncome": "Abbuoni attivi", + "BankCharges": "Spese bancarie", + "BillsForCollection": "Effetti all'incasso", + "BankAdvances": "Anticipi su effetti", + "ExchangeGain": "Utili su cambi", + "ExchangeLoss": "Perdite su cambi", + "LateInterest": "Interessi di mora attivi" }, "AccountSide": { "Debit": "Dare", diff --git a/src/Khaemhat.Web/Resources/it-IT/Shell.json b/src/Khaemhat.Web/Resources/it-IT/Shell.json index 90c9ed4..11b5622 100644 --- a/src/Khaemhat.Web/Resources/it-IT/Shell.json +++ b/src/Khaemhat.Web/Resources/it-IT/Shell.json @@ -99,10 +99,14 @@ }, "Finance": { "_": "Scadenzario", - "OpenItems": "Scadenze", - "Remittances": "Distinte RiBa e SEPA", + "OpenItems": "Partite aperte", + "Receipts": "Incassi", + "Payments": "Pagamenti", "Dunning": "Solleciti", - "Reconciliation": "Riconciliazione bancaria" + "Remittances": "Distinte RiBa/SDD", + "Mandates": "Mandati SDD", + "Reconciliation": "Riconciliazione bancaria", + "CashFlow": "Flusso di cassa" }, "EInvoicing": { "_": "Fatt. elettronica", diff --git a/src/Khaemhat.Web/Resources/it-IT/Treasury.json b/src/Khaemhat.Web/Resources/it-IT/Treasury.json new file mode 100644 index 0000000..9041e41 --- /dev/null +++ b/src/Khaemhat.Web/Resources/it-IT/Treasury.json @@ -0,0 +1,444 @@ +{ + "Treasury": { + "NoCompany": "Scegli un'azienda per lavorare sullo scadenzario", + "NoModule": { + "Title": "Tesoreria non attiva", + "Lead": "La licenza di questa azienda non comprende il modulo Scadenzario e tesoreria (FIN). Attivalo da Amministrazione, Licenze." + }, + "NotDone": "Operazione non eseguita", + "Saved": "Salvato", + "All": "Tutti", + "Select": "Seleziona", + "Export": "Esporta", + "Fields": { + "Allowance": "Abbuono", + "Amount": "Importo", + "Bank": "Banca", + "Customer": "Cliente", + "Supplier": "Fornitore", + "Party": "Cliente o fornitore", + "Date": "Data", + "Days": "Gg", + "Document": "Documento", + "DueDate": "Scadenza", + "Fees": "Spese", + "From": "Dal", + "To": "Al", + "Iban": "IBAN", + "Installment": "Rata", + "Method": "Metodo", + "Notes": "Note", + "Number": "Numero", + "Reference": "Riferimento", + "Residual": "Residuo", + "Status": "Stato", + "Total": "Totale", + "Year": "Anno", + "Bic": "BIC" + }, + "Aging": { + "NotDue": "Non scaduto", + "Days1To30": "Scaduto 1-30 gg", + "Days31To60": "31-60 gg", + "Days61To90": "61-90 gg", + "Over90": "Oltre 90 gg", + "Count": "{0} partite" + }, + "Schedule": { + "Title": "Partite aperte", + "Heading": "Partite aperte", + "Hint": "Scadenze di clienti e fornitori con anzianità dello scaduto. Seleziona le partite di una controparte per registrare l'incasso o il pagamento.", + "OpenTotal": "Aperto {0}", + "OverdueTotal": "Scaduto {0}", + "Search": "Cerca controparte o documento", + "View": "Mostra", + "Direction": "Clienti o fornitori", + "Customers": "Clienti", + "Suppliers": "Fornitori", + "SelectHint": "Le partite scelte devono essere della stessa controparte.", + "None": "Nessuna partita con questi filtri.", + "Overdue": "Scaduta", + "DueSoon": "In scadenza", + "Disputed": "Contestata", + "Edit": "Modifica partita", + "EditText": "Partita {0} rata {1} di {2}: scadenza, metodo, banca e contestazione.", + "Footer": "{0} partite · {1} selezionate · residuo selezionato {2}" + }, + "Statement": { + "Open": "Estratto conto", + "Title": "Estratto conto", + "At": "situazione al {0}", + "Interest": "Interessi di mora", + "Payments": "Incassi e pagamenti registrati" + }, + "Payment": { + "NewReceipt": "Registra incasso", + "NewPayment": "Registra pagamento", + "Cash": "Cassa", + "Items": "Partite da chiudere", + "Collected": "Incassato", + "Paid": "Pagato", + "ResidualAfter": "Residuo dopo", + "Save": "Registra e chiudi partite", + "EntryReceipt": "Verrà generata la prima nota Banca (D) / Clienti (A) per {0}, con abbuoni per {1}.", + "EntryPayment": "Verrà generata la prima nota Fornitori (D) / Banca (A) per {0}, con abbuoni per {1}.", + "ReceiptSaved": "Incasso registrato", + "PaymentSaved": "Pagamento registrato" + }, + "Payments": { + "Receipts": "Incassi", + "Payments": "Pagamenti", + "ReceiptsHint": "Gli incassi dai clienti del periodo con i documenti saldati e la registrazione contabile.", + "PaymentsHint": "I pagamenti ai fornitori del periodo con i documenti saldati e la registrazione contabile.", + "Documents": "Documenti", + "Origin": "Origine", + "Entry": "Registrazione", + "Total": "{0} movimenti · {1}", + "None": "Nessun movimento nel periodo.", + "Cancel": "Annulla movimento", + "CancelText": "Annullare il movimento di {0} di {1}? Le partite tornano aperte e la registrazione viene eliminata o stornata.", + "Cancelled": "Movimento annullato" + }, + "Remittances": { + "Title": "Distinte", + "Heading": "Distinte RiBa / SDD / bonifici", + "Hint": "Raccogli gli effetti in scadenza, genera il file per l'home banking, contabilizza la presentazione, l'accredito e gli insoluti.", + "New": "Nuova distinta", + "History": "Storico distinte", + "Kind": "Tipo", + "Bank": "Banca di presentazione", + "PresentationDate": "Data presentazione", + "DueUntil": "Scadenze fino al", + "Effects": "Effetti", + "Advance": "Salvo buon fine (anticipo)", + "AdvanceShort": "s.b.f.", + "Create": "Crea distinta", + "Candidates": "Effetti proponibili", + "PartyBank": "Banca controparte", + "Check": "Controllo", + "Late": "Scaduta: escludere?", + "Ok": "OK", + "NoCandidates": "Nessuna partita con questo metodo entro la data scelta.", + "Footer": "Formati: RiBa (CBI), SDD core/B2B (pain.008), bonifici SEPA (pain.001) · gli insoluti tornano come partite riaperte con spese", + "None": "Nessuna distinta nell'anno.", + "Detail": "Distinta {0} n. {1}", + "Lines": "Effetti della distinta", + "FileCbi": "Genera file CBI", + "FileXml": "Genera file XML", + "Present": "Contabilizza presentazione", + "PresentText": "La distinta viene contabilizzata: gli effetti passano dai clienti alla banca (o i bonifici ai fornitori vengono registrati). Continuare?", + "Presented": "Distinta contabilizzata", + "Delete": "Elimina distinta", + "DeleteText": "Eliminare la distinta? Le partite tornano disponibili.", + "Created": "Distinta creata", + "Credit": "Registra accredito", + "CreditText": "La banca ha accreditato gli effetti: le partite si chiudono e l'anticipo, se c'è, viene estinto.", + "CreditedOnLabel": "Data accredito", + "CreditedOn": "accreditata il {0}", + "CreditEntry": "Registrazione accredito", + "Entry": "Registrazione presentazione", + "EndToEnd": "Riferimento", + "FileName": "file {0}", + "RemoveLine": "Togli dalla distinta", + "Unpaid": "Insoluto", + "UnpaidText": "L'effetto è tornato insoluto: la partita si riapre e le spese della banca vengono addebitate al cliente.", + "UnpaidDone": "Insoluto registrato", + "Step": { + "Select": "Selezione effetti", + "SelectText": "{0} selezionati · {1} esclusi", + "Check": "Controlli", + "CheckText": "IBAN, ABI/CAB, mandati, scadenze", + "File": "Generazione file", + "FileCbi": "tracciato CBI RiBa standard", + "FileXml": "XML SEPA pain.008 o pain.001", + "Post": "Contabilizzazione", + "PostText": "effetti attivi / clienti", + "Credit": "Accredito e insoluti", + "CreditText": "chiusura delle partite o riapertura con spese" + } + }, + "Mandates": { + "Title": "Mandati SDD", + "Heading": "Mandati SEPA Direct Debit", + "Hint": "Ogni cliente che paga con addebito diretto ha bisogno di un mandato firmato. Il primo incasso esce come FRST, i successivi come RCUR.", + "New": "Nuovo mandato", + "Edit": "Modifica mandato", + "None": "Nessun mandato registrato.", + "Reference": "Riferimento mandato (UMR)", + "Signed": "Firmato il", + "Scheme": "Schema", + "OneOff": "Una tantum", + "LastCollection": "Ultimo incasso", + "First": "Mai usato (FRST)", + "Active": "Valido", + "Revoked": "Revocato", + "Revoke": "Revoca", + "Restore": "Annulla revoca", + "Delete": "Elimina mandato", + "DeleteText": "Eliminare il mandato {0}?" + }, + "Dunning": { + "Title": "Solleciti", + "Heading": "Solleciti di pagamento", + "Preview": "Anteprima", + "Send": "Invia {0} solleciti", + "SendTitle": "Invia solleciti", + "SendText": "Inviare {0} solleciti per e-mail o PEC? Le lettere senza indirizzo vengono preparate in PDF.", + "Sent": "{0} inviati, {1} lettere", + "Proposal": "Proposta di invio", + "Rule": "regola: scaduto oltre i giorni del livello · escluse PA e partite contestate", + "Nothing": "Nessun cliente da sollecitare.", + "Items": "Partite", + "MaxDays": "Gg max", + "LastSent": "Ultimo sollecito", + "NextLevel": "Prossimo livello", + "Level": "Livello {0}", + "Waiting": "In attesa", + "Channel": "Canale", + "Include": "Includi", + "Blocked": "· bloccato", + "Levels": "Livelli e modelli", + "LevelColumn": "Livello", + "After": "Dopo (gg)", + "Template": "Modello", + "Action": "Azione", + "Automatic": "Automatico", + "InterestYes": "sì (D.Lgs. 231/2002)", + "InterestNo": "no", + "EditLevel": "Modifica livello", + "ChargeInterest": "Calcola interessi di mora", + "Subject": "Oggetto", + "Body": "Testo", + "Placeholders": "Segnaposti: {cliente} {azienda} {elenco} {totale} {interessi} {riferimento} {giorni}", + "History": "Registro invii", + "NoHistory": "Nessun sollecito inviato.", + "Recipients": "Destinatari", + "SentBy": "Inviato da", + "Customers": "Clienti con scaduto", + "OverdueTotal": "Scaduto totale", + "Today": "Da sollecitare oggi", + "LastRun": "Ultimo invio", + "Schedule": "Esecuzione automatica", + "ScheduleText": "giorni feriali alle 7:00" + }, + "Reconciliation": { + "Title": "Riconciliazione bancaria", + "Import": "Importa estratto conto", + "Auto": "Abbina automatico", + "ConfirmAll": "Conferma suggeriti ≥ 90%", + "ShowOpen": "Da riconciliare", + "Lines": "Movimenti", + "Statements": "Estratti importati", + "None": "Nessun movimento da riconciliare.", + "Description": "Descrizione", + "In": "Entrate", + "Out": "Uscite", + "Proposal": "Abbinamento proposto", + "Confidence": "Conf.", + "Confirm": "Conferma", + "MatchItems": "Abbina a partite", + "MatchPayment": "Abbina a incasso o pagamento registrato", + "Post": "Registra su conto", + "Ignore": "Ignora", + "Reset": "Annulla abbinamento", + "Match": "Abbina", + "Chosen": "Totale partite scelte {0}", + "EntryDescription": "Descrizione registrazione", + "SaveRule": "Salva come regola (testo da cercare)", + "SaveRuleHint": "Se scrivi un testo, i movimenti futuri che lo contengono verranno proposti su questo conto.", + "Footer": "Abbinamento per importo, data, CRO/riferimento e nome; regole salvate per i ricorrenti", + "NoStatements": "Nessun estratto conto importato.", + "File": "File", + "Format": "Formato", + "Movements": "Movimenti", + "Closing": "Saldo finale", + "Account": "Conto", + "BankBalance": "Saldo banca", + "BookBalance": "Saldo contabile", + "Difference": "Differenza", + "ToMatch": "Movimenti", + "ToMatchText": "{0} da riconciliare · {1}", + "Imported": "{0} movimenti importati, {1} già presenti, {2} con proposta", + "Refreshed": "{0} proposte trovate", + "Confirmed": "{0} movimenti riconciliati" + }, + "Rules": { + "Title": "Regole", + "New": "Nuova regola", + "Edit": "Regola di abbinamento", + "None": "Nessuna regola salvata.", + "Name": "Nome", + "Pattern": "Testo da cercare", + "PatternHint": "Senza distinzione tra maiuscole e minuscole.", + "Direction": "Movimenti", + "Account": "Conto", + "Uses": "Usi", + "Disabled": "Disattivata", + "Delete": "Elimina regola" + }, + "CashFlow": { + "Title": "Flusso di cassa", + "Heading": "Flusso di cassa previsto", + "Hint": "Disponibilità di oggi e movimenti attesi da scadenze, distinte, ordini, registrazioni ricorrenti e imposte. Lo scaduto cade nel primo periodo.", + "Days": "Orizzonte", + "DaysText": "{0} giorni", + "Period": "Periodo", + "Weeks": "Settimane", + "Months": "Mesi", + "Periods": "Andamento", + "Balance": "Saldo", + "Chart": "Grafico", + "Accounts": "Banche e cassa oggi", + "Movements": "Movimenti previsti", + "NoMovements": "Nessun movimento previsto.", + "Source": "Origine", + "Today": "Disponibilità oggi", + "TotalIn": "Entrate previste", + "TotalOut": "Uscite previste", + "End": "Saldo finale", + "Lowest": "Punto più basso" + }, + "Enums": { + "OpenItemStatus": { + "Open": "Aperta", + "Partial": "Parziale", + "Closed": "Chiusa", + "Unpaid": "Insoluta", + "InRemittance": "In distinta" + }, + "ScheduleView": { + "Open": "Aperte", + "Overdue": "Scadute", + "Unpaid": "Insolute", + "InRemittance": "In distinta", + "Disputed": "Contestate", + "Closed": "Chiuse", + "All": "Tutte" + }, + "PaymentOrigin": { + "Manual": "Manuale", + "Remittance": "Distinta", + "BankStatement": "Estratto conto" + }, + "RemittanceKind": { + "Riba": "RiBa (CBI)", + "SddCore": "SDD Core", + "SddB2b": "SDD B2B", + "SepaCreditTransfer": "Bonifici SEPA" + }, + "RemittanceStatus": { + "Draft": "Bozza", + "Generated": "File generato", + "Presented": "Presentata", + "Closed": "Chiusa" + }, + "RemittanceLineStatus": { + "Included": "In distinta", + "Paid": "Pagato", + "Unpaid": "Insoluto" + }, + "SddScheme": { + "Core": "Core (privati)", + "B2b": "B2B (imprese)" + }, + "StatementLineStatus": { + "ToMatch": "Da abbinare", + "Suggested": "Suggerito", + "Matched": "Abbinato", + "Ignored": "Ignorato" + }, + "StatementMatchKind": { + "None": "Nessuno", + "OpenItems": "Partite", + "Payment": "Movimento registrato", + "TaxPayment": "F24", + "Rule": "Regola", + "RemittanceCredit": "Accredito distinta", + "Unpaid": "Insoluto", + "Entry": "Registrazione" + }, + "StatementFormat": { + "Csv": "CSV", + "Camt053": "CAMT.053", + "Cbi": "CBI" + }, + "BankRuleDirection": { + "Any": "Entrate e uscite", + "In": "Entrate", + "Out": "Uscite" + }, + "DunningChannel": { + "None": "Nessuno", + "Email": "e-mail", + "Pec": "PEC", + "Letter": "Lettera PDF" + }, + "DunningAction": { + "None": "—", + "NotifyAgent": "Avvisa l'agente", + "BlockCustomer": "Blocca il cliente" + }, + "DunningLetterStatus": { + "Queued": "In coda", + "Sent": "Inviato", + "Failed": "Non inviato" + }, + "CashFlowSource": { + "Receivables": "Incassi da clienti", + "Payables": "Pagamenti a fornitori", + "SaleOrders": "Ordini clienti", + "PurchaseOrders": "Ordini fornitori", + "Recurring": "Ricorrenti", + "Taxes": "Imposte" + } + } + }, + "treasury": { + "not-found": "L'elemento non esiste più.", + "account-missing": "Manca il conto contabile: controlla il piano dei conti e le causali.", + "money-account-missing": "Manca il conto della banca o della cassa: indica il conto contabile della banca.", + "iban-invalid": "L'IBAN non è valido.", + "payment": { + "party-required": "Indica il cliente o il fornitore.", + "items-required": "Scegli almeno una partita.", + "amount-required": "Indica un importo diverso da zero.", + "item-party": "Le partite devono essere della stessa controparte.", + "over-settled": "L'importo supera il residuo della partita.", + "unbalanced": "Il movimento non quadra con le partite.", + "from-remittance": "Il movimento nasce da una distinta: annullalo dalla distinta." + }, + "item": { + "in-remittance": "La partita è in una distinta." + }, + "remittance": { + "empty": "La distinta non ha effetti.", + "status": "La distinta non è nello stato giusto per questa operazione.", + "bank": "La banca di presentazione non ha i dati richiesti (IBAN, SIA, CUC o identificativo creditore).", + "iban": "IBAN o ABI/CAB mancanti", + "mandate": "Mandato SDD mancante o revocato", + "item": "La partita non è disponibile.", + "format": "Il pacchetto fiscale non sa scrivere questo formato." + }, + "mandate": { + "duplicate": "Esiste già un mandato con questo riferimento.", + "reference": "Il riferimento del mandato è obbligatorio (massimo 35 caratteri).", + "used": "Il mandato è già stato usato in una distinta: revocalo invece di eliminarlo." + }, + "statement": { + "format": "Formato dell'estratto conto non riconosciuto (CAMT.053, CBI o CSV).", + "empty": "L'estratto conto non contiene movimenti.", + "account": "L'estratto conto è di un altro conto." + }, + "match": { + "done": "Il movimento è già riconciliato.", + "amount": "L'importo non corrisponde." + }, + "rule": { + "pattern": "Scrivi il testo da cercare." + }, + "dunning": { + "recipient": "Nessun indirizzo e-mail o PEC: preparata la lettera PDF.", + "level": "Livello di sollecito non valido." + } + } +} diff --git a/src/Khaemhat.Web/Shell/MenuCatalog.cs b/src/Khaemhat.Web/Shell/MenuCatalog.cs index 097ecda..28153da 100644 --- a/src/Khaemhat.Web/Shell/MenuCatalog.cs +++ b/src/Khaemhat.Web/Shell/MenuCatalog.cs @@ -74,10 +74,11 @@ public static class MenuCatalog ("Shell.Menu.Ledger.Parties", "partitari"), ("Shell.Menu.Ledger.VatRegisters", "registri-iva"), ("Shell.Menu.Ledger.VatSettlement", "liquidazione-iva"), ("Shell.Menu.Ledger.Withholdings", "ritenute"), ("Shell.Menu.Ledger.StampDuty", "bollo"), ("Shell.Menu.Ledger.Statements", "bilancio")), - Area("Shell.Menu.Finance", "coins", "/scadenzario", ModuleCodes.Finance, "finance.schedule.read", "M9", - ("Shell.Menu.Finance.OpenItems", "scadenze"), ("Shell.Menu.Finance.Remittances", "distinte"), ("Shell.Menu.Finance.Dunning", "solleciti"), - ("Shell.Menu.Finance.Reconciliation", "riconciliazione")), - Area("Shell.Menu.EInvoicing", "file-check", "/fatturazione-elettronica", ModuleCodes.EInvoicing, "einvoice.document.read", "M8", + Area("Shell.Menu.Finance", "coins", "/scadenzario", ModuleCodes.Finance, "finance.schedule.read", null, + ("Shell.Menu.Finance.OpenItems", "scadenze"), ("Shell.Menu.Finance.Receipts", "incassi"), ("Shell.Menu.Finance.Payments", "pagamenti"), + ("Shell.Menu.Finance.Dunning", "solleciti"), ("Shell.Menu.Finance.Remittances", "distinte"), ("Shell.Menu.Finance.Mandates", "mandati"), + ("Shell.Menu.Finance.Reconciliation", "riconciliazione"), ("Shell.Menu.Finance.CashFlow", "flusso-di-cassa")), + Area("Shell.Menu.EInvoicing", "file-check", "/fatturazione-elettronica", ModuleCodes.EInvoicing, "einvoice.document.read", "M9", ("Shell.Menu.EInvoicing.Dashboard", "cruscotto"), ("Shell.Menu.EInvoicing.Channels", "canali"), ("Shell.Menu.EInvoicing.IntentDeclarations", "dichiarazioni-intento")), Area("Shell.Menu.Assets", "building", "/cespiti", ModuleCodes.Assets, "assets.asset.read", "M10", diff --git a/src/Khaemhat.Web/Treasury/TreasuryScreens.cs b/src/Khaemhat.Web/Treasury/TreasuryScreens.cs new file mode 100644 index 0000000..8e5cb0c --- /dev/null +++ b/src/Khaemhat.Web/Treasury/TreasuryScreens.cs @@ -0,0 +1,126 @@ +using System.Globalization; +using Khaemhat.Application.Localization; +using Khaemhat.Application.Security; +using Khaemhat.Core.Accounting; +using Khaemhat.Core.Tables; +using Khaemhat.Core.Treasury; +using Khaemhat.Web.Ledger; +using Khaemhat.Web.Ui; + +namespace Khaemhat.Web.Treasury; + +/// What the screens of the schedule and the treasury share (SPEC §11.8, mockups 053-057): addresses, texts and tones. +public static class TreasuryScreens +{ + /// The address of the area. + public const string BasePath = "/scadenzario"; + + /// The key of the text of an enum value. + /// The value. + /// The key. + public static string EnumKey(Enum value) + { + ArgumentNullException.ThrowIfNull(value); + return "Treasury.Enums." + value.GetType().Name + "." + value; + } + + /// The choices of an enum. + /// The enum. + /// The texts. + /// The choices in declaration order. + public static IReadOnlyList> Choices(ITexts texts) + where TEnum : struct, Enum + { + ArgumentNullException.ThrowIfNull(texts); + return [.. Enum.GetValues().Select(v => new KhOption(v, texts[EnumKey(v)]))]; + } + + /// The text of the errors of a refused operation. + /// The texts. + /// The refusal. + /// The messages. + public static string Errors(ITexts texts, ValidationFailedException exception) => LedgerScreens.Errors(texts, exception); + + /// The tone of the state of an item; an open item past due is an error. + /// The item. + /// Today. + /// The tone. + public static KhTone ToneOf(OpenItem item, DateOnly today) + { + ArgumentNullException.ThrowIfNull(item); + return item.Status switch + { + OpenItemStatus.Closed => KhTone.Ok, + OpenItemStatus.Unpaid => KhTone.Error, + OpenItemStatus.InRemittance => KhTone.Info, + OpenItemStatus.Partial => KhTone.Warning, + _ when item.DueDate < today => KhTone.Error, + _ when item.DueDate <= today.AddDays(7) => KhTone.Warning, + _ => KhTone.Neutral, + }; + } + + /// The text of the state of an item: overdue and due soon are told apart from open. + /// The texts. + /// The item. + /// Today. + /// The text. + public static string StatusText(ITexts texts, OpenItem item, DateOnly today) + { + ArgumentNullException.ThrowIfNull(texts); + ArgumentNullException.ThrowIfNull(item); + var text = item.Status == OpenItemStatus.Open && item.DueDate < today ? texts["Treasury.Schedule.Overdue"] + : item.Status == OpenItemStatus.Open && item.DueDate <= today.AddDays(7) ? texts["Treasury.Schedule.DueSoon"] + : texts[EnumKey(item.Status)]; + return item.Disputed ? text + " · " + texts["Treasury.Schedule.Disputed"] : text; + } + + /// The tone of the state of a remittance. + /// The state. + /// The tone. + public static KhTone ToneOf(RemittanceStatus status) => status switch + { + RemittanceStatus.Draft => KhTone.Warning, + RemittanceStatus.Generated => KhTone.Info, + RemittanceStatus.Presented => KhTone.Accent, + _ => KhTone.Ok, + }; + + /// The tone of the state of a movement of the bank. + /// The state. + /// The tone. + public static KhTone ToneOf(StatementLineStatus status) => status switch + { + StatementLineStatus.Matched => KhTone.Ok, + StatementLineStatus.Suggested => KhTone.Info, + StatementLineStatus.Ignored => KhTone.Neutral, + _ => KhTone.Warning, + }; + + /// A number of a remittance as the screens show it. + /// The remittance. + /// The text, year/number. + public static string Number(Remittance remittance) + { + ArgumentNullException.ThrowIfNull(remittance); + return remittance.Year.ToString(CultureInfo.InvariantCulture) + "/" + remittance.Number.ToString("000", CultureInfo.InvariantCulture); + } + + /// An IBAN shortened for a grid: country, check digits and the last four characters. + /// The IBAN. + /// The short text. + public static string ShortIban(string? iban) => + string.IsNullOrEmpty(iban) || iban.Length < 10 ? iban ?? string.Empty : iban[..4] + "…" + iban[^4..]; + + /// The choices of the bank accounts. + /// The bank accounts. + /// The choices, code and name. + public static IReadOnlyList> BankChoices(IEnumerable banks) => + [.. (banks ?? []).Select(b => new KhOption(b.Id, b.Code + " · " + (b.BankName ?? b.Description)))]; + + /// The choices of the payment methods. + /// The payment methods. + /// The choices, description and code of the e-invoice. + public static IReadOnlyList> MethodChoices(IEnumerable methods) => + [.. (methods ?? []).Select(m => new KhOption(m.Id, m.Description + " (" + m.EInvoiceCode + ")"))]; +} diff --git a/src/Khaemhat.Web/wwwroot/app.css b/src/Khaemhat.Web/wwwroot/app.css index 53c7d36..54e5234 100644 --- a/src/Khaemhat.Web/wwwroot/app.css +++ b/src/Khaemhat.Web/wwwroot/app.css @@ -436,3 +436,19 @@ h1[tabindex="-1"]:focus { outline: none; box-shadow: none; } .grid tr.err td { background: var(--kh-err-soft); } .grid tfoot td { border-top: 1px solid var(--kh-border); } @media (max-width: 1100px) { .kh-ledger-split, .kh-ledger-two { grid-template-columns: minmax(0, 1fr); } } + +/* Schedule and treasury (M8): aging tiles, the remittance form beside its effects, the bars of the cash flow. */ +.kh-aging { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 12px; margin: 10px 0 12px; } +.kh-remit { display: grid; grid-template-columns: minmax(280px, 1fr) minmax(0, 3fr); gap: 12px; align-items: start; } +.kh-remit .kh-panel .btn.primary, .kh-remit .panel .btn.primary { margin-top: 12px; width: 100%; justify-content: center; } +.kh-subhead { margin: 14px 0 6px; font-size: 12px; font-weight: 600; text-transform: uppercase; letter-spacing: .04em; color: var(--kh-text-2); } +.grid .chkcol { width: 32px; text-align: center; } +.grid tr.warn td { background: var(--kh-warn-soft); } +.grid tr.clickable { cursor: pointer; } +.grid td.neg, .grid td .neg { color: var(--kh-err); } +.grid td.pos { color: var(--kh-ok); } +.btn.ok { color: var(--kh-ok); border-color: var(--kh-ok); } +.kh-cfbarcol { width: 28%; } +.kh-cfbar { display: block; height: 8px; border-radius: 4px; background: var(--kh-accent); min-width: 2px; } +.kh-cfbar.neg { background: var(--kh-err); } +@media (max-width: 1100px) { .kh-remit { grid-template-columns: minmax(0, 1fr); } } diff --git a/tests/Khaemhat.Web.Tests/Shell/LocalizationRulesTests.cs b/tests/Khaemhat.Web.Tests/Shell/LocalizationRulesTests.cs index ff40898..e090f77 100644 --- a/tests/Khaemhat.Web.Tests/Shell/LocalizationRulesTests.cs +++ b/tests/Khaemhat.Web.Tests/Shell/LocalizationRulesTests.cs @@ -95,7 +95,7 @@ public sealed partial class LocalizationRulesTests 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()); + Assert.IsEmpty(keys.Where(k => !ShellTests.Texts.Contains(k)).ToList(), string.Join(", ", keys.Where(k => !ShellTests.Texts.Contains(k)))); } [TestMethod] @@ -115,7 +115,7 @@ public sealed partial class LocalizationRulesTests keys.AddRange(typeof(LedgerErrors).GetFields(BindingFlags.Public | BindingFlags.Static) .Where(f => f.IsLiteral).Select(f => (string)f.GetRawConstantValue()!)); - Assert.IsEmpty(keys.Where(k => !ShellTests.Texts.Contains(k)).ToList()); + Assert.IsEmpty(keys.Where(k => !ShellTests.Texts.Contains(k)).ToList(), string.Join(", ", keys.Where(k => !ShellTests.Texts.Contains(k)))); } [TestMethod]