@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; } } }