feat: general ledger, automatic posting, VAT settlement, withholdings and F24 (#62 #63 #64 #65 #66 #67 #68)

M7 adds the double-entry ledger so that the documents of M5 and M6 reach the
accounts without retyping, and the Italian VAT obligations can be prepared from
the same data.

- Chart of accounts on three levels with the Italian "PMI standard" model in the
  fiscal pack, journal templates with proposed lines, VAT registers; the chart
  import now writes the accounts and exports them (#62, ADR 0036).
- Journal entries: draft, posted, final with the libro giornale number,
  reversal; recurring entries with the nightly ledger.recurring job (#63).
- Documents post their entry inside the document transaction (PostingEngine,
  LedgerPoster) with VAT lines, open items and withholdings; a change rewrites
  the same entry, a cancellation removes or reverses it (#64, ADR 0037).
- VAT registers with final print, monthly or quarterly settlement with pro rata,
  interest, minimum and advance, confirmation with the LIQ entry, period lock
  and F24 line, LIPE file and F24 data (#65).
- Operated and suffered withholdings, CU data, stamp duty by quarter with the
  5,000 euro threshold, F24 summary with its payment entry (#66).
- Party ledgers, account ledgers, trial balance and libro giornale (#67).
- Demo accounting with the settlements of the past months confirmed and checked
  by hand in a test; wiki Contabilita, IVA, Fiscalita italiana completed with
  screenshots; CHANGELOG 0.7.0, STATUS, ADR 0036-0037 (#68).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-13 01:41:58 +01:00
1 parent 838362bfe1
commit 9e3ba92993
83 files changed
+13838 -497

No files matched your search

@@ -40,7 +40,7 @@ else
<KhSelect TValue="MissingCodeAction" Label="@T["ImportExport.Missing"]" Name="missing" Options="MissingChoices" Value="_options.Missing"
ValueChanged="SetMissing" Span="6" Disabled="_busy" />
}
else if (IsPrices)
else if (OnlyExistingOption)
{
<KhSelect TValue="ExistingCodeAction" Label="@T["ImportExport.Existing"]" Name="existing" Options="ExistingChoices" Value="_options.Existing"
ValueChanged="SetExisting" Span="12" Disabled="_busy" />
@@ -40,7 +40,7 @@ public partial class ImportExportPage
private bool IsRecordTarget => Target is PartiesImportTarget or ItemsImportTarget;
private bool IsPrices => Target is PricesImportTarget;
private bool OnlyExistingOption => Target is PricesImportTarget or ChartOfAccountsImportTarget;
private bool CanExport => Target.CanExport && Session.Permissions.Flags.CanExport && Session.Permissions.Allows(Target.ExportPermission);
@@ -0,0 +1,316 @@
@page "/contabilita/piano-dei-conti"
@attribute [Authorize]
@using Khaemhat.Application.Ledger
@using Khaemhat.Application.Security
@using Khaemhat.Core.Accounting
@using Khaemhat.Web.Ledger
@inject ShellSession Session
@inject LedgerService Ledger
@inject LedgerQueryService Queries
@inject ToastService Toasts
@inject DialogService Dialogs
@inject IJSRuntime JS
@inject TimeProvider Clock
@* The chart of accounts and the account ledger (SPEC §11.7, mockup 042): mastri, conti and sottoconti in three levels
with the line of the legal statements, the account chosen with its data and its movements in a period, each with
the way to its entry. Accounts with movements or children cannot be deleted, only disabled. *@
<KhPageTitle Text="@T["Ledger.Accounts.Title"]" Icon="layers" />
<LedgerGuard Permission="@LedgerPermissions.AccountRead">
<div class="phead">
<div>
<div class="crumbs"><a href="@LedgerScreens.BasePath">@T["Shell.Menu.Ledger"]</a> / @T["Ledger.Accounts.Title"]</div>
<h1>@T["Ledger.Accounts.Heading"]</h1>
<div class="sub">@T["Ledger.Accounts.Hint"]</div>
</div>
<div class="grow"></div>
<div class="toolbar">
@if (CanWrite)
{
<button type="button" class="btn primary" disabled="@_busy" @onclick="() => Edit(null)"><KhIcon Name="plus" /> @T["Ledger.Accounts.New"]</button>
}
</div>
</div>
<div class="kh-ledger-split">
<KhPanel Title="@T["Ledger.Accounts.Chart"]" Icon="list" Tight="true">
<div class="filters">
<input type="search" class="in" placeholder="@T["Ledger.Accounts.Search"]" aria-label="@T["Ledger.Accounts.Search"]" value="@_search"
@oninput="e => _search = e.Value?.ToString()" />
<span class="grow"></span>
<span class="muted sm">@T.Format("Ledger.Accounts.Count", T.Number(_accounts.Count))</span>
</div>
<div class="kh-ledger-tree">
<table class="grid" aria-label="@T["Ledger.Accounts.Chart"]">
<thead>
<tr>
<th scope="col">@T["Ledger.Fields.Code"]</th>
<th scope="col">@T["Ledger.Fields.Description"]</th>
<th scope="col">@T["Ledger.Fields.Nature"]</th>
<th scope="col">@T["Ledger.Fields.StatementLine"]</th>
</tr>
</thead>
<tbody>
@foreach (var a in Visible)
{
<tr class="@(a.Id == _selected?.Id ? "sel" : null) @(a.Disabled ? "muted" : null)" style="cursor:pointer" @onclick="() => SelectAsync(a)">
<td class="code lvl@(a.Level)" style="padding-left:@((a.Level - 1) * 14 + 8)px">@a.Code</td>
<td class="lvl@(a.Level)">@a.Description</td>
<td>@T[LedgerScreens.EnumKey(a.Nature)]</td>
<td class="code">@a.StatementLine</td>
</tr>
}
</tbody>
</table>
</div>
</KhPanel>
<div class="kh-ledger-side">
@if (_editing)
{
<KhPanel Title="@T[_id is null ? "Ledger.Accounts.New" : "Ledger.Accounts.Edit"]" Icon="edit">
<div class="form plain">
<KhTextBox Label="@T["Ledger.Fields.Code"]" Name="code" @bind-Value="_code" Span="4" Required="true" Mono="true" MaxLength="20" Hint="@T["Ledger.Accounts.CodeHint"]" Disabled="@(_id is not null)" />
<KhTextBox Label="@T["Ledger.Fields.Description"]" Name="description" @bind-Value="_description" Span="8" Required="true" MaxLength="100" />
<KhSelect TValue="AccountNature" Label="@T["Ledger.Fields.Nature"]" Name="nature" Options="LedgerScreens.Choices<AccountNature>(T)" @bind-Value="_nature" Span="6" />
<KhSelect TValue="AccountType" Label="@T["Ledger.Fields.Type"]" Name="type" Options="LedgerScreens.Choices<AccountType>(T)" @bind-Value="_type" Span="6" />
<KhTextBox Label="@T["Ledger.Fields.StatementLine"]" Name="cee" @bind-Value="_statementLine" Span="6" MaxLength="20" Mono="true" Hint="@T["Ledger.Accounts.CeeHint"]" />
<KhTextBox Label="@T["Ledger.Fields.Reclassification"]" Name="reclass" @bind-Value="_reclassification" Span="6" MaxLength="20" Mono="true" />
<KhCheck Label="@T["Ledger.Fields.SubLedger"]" Name="subledger" @bind-Value="_subLedger" Span="6" />
<KhCheck Label="@T["Ledger.Fields.VatRelevant"]" Name="vat" @bind-Value="_vatRelevant" Span="6" />
<KhCheck Label="@T["Ledger.Fields.ClosesAutomatically"]" Name="closes" @bind-Value="_closes" Span="6" />
<KhCheck Label="@T["Ledger.Fields.Disabled"]" Name="disabled" @bind-Value="_disabled" Span="6" />
</div>
<div class="kh-formactions">
@if (_id is { } id)
{
<button type="button" class="btn" disabled="@_busy" @onclick="() => DeleteAsync(id)"><KhIcon Name="trash" /> @T["Common.Delete"]</button>
}
<button type="button" class="btn" @onclick="() => _editing = false">@T["Common.Cancel"]</button>
<button type="button" class="btn primary" disabled="@_busy" @onclick="SaveAsync"><KhIcon Name="check" /> @T["Common.Save"]</button>
</div>
</KhPanel>
}
else if (_selected is { } account)
{
<KhPanel Title="@(account.Code + " · " + account.Description)" Icon="book">
<Actions>
@if (CanWrite)
{
<button type="button" class="btn sm" @onclick="() => Edit(account)"><KhIcon Name="edit" /> @T["Common.Edit"]</button>
}
</Actions>
<ChildContent>
<dl class="kv">
<dt>@T["Ledger.Fields.Level"]</dt><dd>@T[$"Ledger.Accounts.Level{account.Level}"]</dd>
<dt>@T["Ledger.Fields.Nature"]</dt><dd>@T[LedgerScreens.EnumKey(account.Nature)]</dd>
<dt>@T["Ledger.Fields.Type"]</dt><dd>@T[LedgerScreens.EnumKey(account.Type)]</dd>
<dt>@T["Ledger.Fields.StatementLine"]</dt><dd class="code">@(account.StatementLine ?? "-")</dd>
<dt>@T["Ledger.Fields.SubLedger"]</dt><dd>@T[account.SubLedger ? "Common.Yes" : "Common.No"]</dd>
</dl>
</ChildContent>
</KhPanel>
@if (account.Postable && Session.Permissions.Allows(LedgerPermissions.EntryRead))
{
<KhPanel Title="@T["Ledger.Accounts.Ledger"]" Icon="list" Tight="true">
<Actions>
<button type="button" class="btn sm" disabled="@_busy" @onclick="PrintAsync"><KhIcon Name="printer" /> @T["Ledger.Print"]</button>
</Actions>
<ChildContent>
<MovementsTable Page="_page" From="_from" To="_to" FromChanged="SetFromAsync" ToChanged="SetToAsync" OnPage="PageAsync" Offset="_offset" PageSize="PageSize" ShowAccount="false" />
</ChildContent>
</KhPanel>
}
}
else
{
<p class="kh-wempty">@T["Ledger.Accounts.Choose"]</p>
}
</div>
</div>
</LedgerGuard>
@code {
private const int PageSize = 30;
private IReadOnlyList<GlAccount> _accounts = [];
private GlAccount? _selected;
private string? _search;
private bool _busy;
private LedgerPage? _page;
private int _offset;
private DateOnly? _from;
private DateOnly? _to;
private bool _editing;
private long? _id;
private string? _code;
private string? _description;
private AccountNature _nature;
private AccountType _type;
private string? _statementLine;
private string? _reclassification;
private bool _subLedger;
private bool _vatRelevant;
private bool _closes = true;
private bool _disabled;
private bool CanWrite => Session.Permissions.Allows(LedgerPermissions.AccountWrite);
private IEnumerable<GlAccount> Visible => string.IsNullOrWhiteSpace(_search)
? _accounts
: _accounts.Where(a => a.Code.StartsWith(_search.Trim(), StringComparison.OrdinalIgnoreCase) || a.Description.Contains(_search.Trim(), StringComparison.OrdinalIgnoreCase));
/// <inheritdoc />
protected override async Task OnInitializedAsync()
{
await Session.EnsureLoadedAsync();
var today = DateOnly.FromDateTime(Clock.GetLocalNow().DateTime);
_from = new DateOnly(today.Year, 1, 1);
_to = new DateOnly(today.Year, 12, 31);
if (Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(LedgerPermissions.AccountRead)
&& Session.Licenses.IsModuleActive(Khaemhat.Application.Modules.ModuleCodes.Accounting))
{
_accounts = await Ledger.AccountsAsync(actor, company);
}
}
private async Task SelectAsync(GlAccount account)
{
_selected = account;
_editing = false;
_offset = 0;
await LoadMovementsAsync();
}
private async Task LoadMovementsAsync()
{
_page = null;
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _selected is not { Postable: true } account
|| _from is not { } from || _to is not { } to || !Session.Permissions.Allows(LedgerPermissions.EntryRead))
{
return;
}
_page = await Queries.MovementsAsync(actor, company, new LedgerFilter(account.Id, null, from, to, false, _offset, PageSize));
}
private async Task SetFromAsync(DateOnly? date)
{
_from = date;
_offset = 0;
await LoadMovementsAsync();
}
private async Task SetToAsync(DateOnly? date)
{
_to = date;
_offset = 0;
await LoadMovementsAsync();
}
private async Task PageAsync(int offset)
{
_offset = offset;
await LoadMovementsAsync();
}
private async Task PrintAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _selected is not { } account || _from is not { } from || _to is not { } to)
{
return;
}
_busy = true;
try
{
await LedgerScreens.DownloadAsync(JS, await Queries.PrintMovementsAsync(actor, company, new LedgerFilter(account.Id, null, from, to)));
}
finally
{
_busy = false;
}
}
private void Edit(GlAccount? account)
{
_id = account?.Id;
_code = account?.Code ?? (_selected is { Level: < 3 } parent ? parent.Code + "." : null);
_description = account?.Description;
_nature = account?.Nature ?? _selected?.Nature ?? AccountNature.Asset;
_type = account?.Type ?? (account is null ? _selected?.Type ?? AccountType.Generic : AccountType.Generic);
_statementLine = account?.StatementLine ?? (account is null ? _selected?.StatementLine : null);
_reclassification = account?.Reclassification;
_subLedger = account?.SubLedger ?? false;
_vatRelevant = account?.VatRelevant ?? false;
_closes = account?.ClosesAutomatically ?? true;
_disabled = account?.Disabled ?? false;
_editing = true;
}
private async Task SaveAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
_busy = true;
try
{
var saved = await Ledger.SaveAccountAsync(actor, company, new AccountInput(_id, _code ?? string.Empty, _description ?? string.Empty, _nature, _type)
{
StatementLine = _statementLine,
Reclassification = _reclassification,
SubLedger = _subLedger,
VatRelevant = _vatRelevant,
ClosesAutomatically = _closes,
Disabled = _disabled,
});
_accounts = await Ledger.AccountsAsync(actor, company);
_selected = _accounts.FirstOrDefault(a => a.Id == saved.Id);
_editing = false;
Toasts.Show(ToastKind.Success, T["Ledger.Saved"], saved.Code);
await LoadMovementsAsync();
}
catch (ValidationFailedException ex)
{
Toasts.Show(ToastKind.Error, T["Ledger.NotSaved"], LedgerScreens.Errors(T, ex));
}
finally
{
_busy = false;
}
}
private async Task DeleteAsync(long id)
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
if (!await Dialogs.ConfirmAsync(new ConfirmRequest(T["Ledger.Accounts.Delete"], T.Format("Ledger.Accounts.DeleteText", _code ?? string.Empty), T["Common.Delete"], T["Common.Cancel"])))
{
return;
}
_busy = true;
try
{
await Ledger.DeleteAccountAsync(actor, company, id);
_accounts = await Ledger.AccountsAsync(actor, company);
_selected = null;
_editing = false;
}
catch (ValidationFailedException ex)
{
Toasts.Show(ToastKind.Error, T["Ledger.NotDone"], LedgerScreens.Errors(T, ex));
}
finally
{
_busy = false;
}
}
}
@@ -0,0 +1,207 @@
@page "/contabilita/bilancio"
@attribute [Authorize]
@using Khaemhat.Application.Ledger
@using Khaemhat.Application.Security
@using Khaemhat.Application.Tables
@using Khaemhat.Core.Accounting
@using Khaemhat.Core.Tables
@using Khaemhat.Web.Ledger
@inject ShellSession Session
@inject LedgerQueryService Queries
@inject TableService Tables
@inject ToastService Toasts
@inject IJSRuntime JS
@inject TimeProvider Clock
@* The trial balance and the general journal (SPEC §11.7, issue #67): the balances of every account in a period, with
the totals of conti and mastri, by cost center too, debits and credits that must match and the result of the
period; the print of the trial balance and of the general journal, provisional or of the final entries. *@
<KhPageTitle Text="@T["Ledger.Balance.Title"]" Icon="chart" />
<LedgerGuard Permission="@LedgerPermissions.EntryRead">
<div class="phead">
<div>
<div class="crumbs"><a href="@LedgerScreens.BasePath">@T["Shell.Menu.Ledger"]</a> / @T["Ledger.Balance.Title"]</div>
<h1>@T["Ledger.Balance.Heading"]</h1>
<div class="sub">@T["Ledger.Balance.Hint"]</div>
</div>
<div class="grow"></div>
<div class="toolbar">
<button type="button" class="btn" disabled="@(_busy || _from is null || _to is null)" @onclick="PrintAsync"><KhIcon Name="printer" /> @T["Ledger.Balance.Print"]</button>
<button type="button" class="btn" disabled="@(_busy || _from is null || _to is null)" @onclick="() => JournalAsync(final: false)"><KhIcon Name="book" /> @T["Ledger.Balance.JournalProvisional"]</button>
<button type="button" class="btn" disabled="@(_busy || _from is null || _to is null)" @onclick="() => JournalAsync(final: true)"><KhIcon Name="lock" /> @T["Ledger.Balance.JournalFinal"]</button>
</div>
</div>
<KhPanel Tight="true">
<div class="filters kh-ledger-filters">
<KhDateBox Label="@T["Ledger.Fields.From"]" Name="from" Value="_from" ValueChanged="SetFromAsync" />
<KhDateBox Label="@T["Ledger.Fields.To"]" Name="to" Value="_to" ValueChanged="SetToAsync" />
<KhSelect TValue="long?" Label="@T["Ledger.Fields.CostCenter"]" Name="center" Options="CenterChoices" Value="_center" ValueChanged="SetCenterAsync" Empty="@T["Ledger.Balance.AllCenters"]" />
<KhSelect TValue="int" Label="@T["Ledger.Balance.Detail"]" Name="level" Options="LevelChoices" @bind-Value="_level" />
<KhCheck Label="@T["Ledger.Balance.Drafts"]" Name="drafts" Value="_drafts" ValueChanged="SetDraftsAsync" />
</div>
@if (_balance is { } balance)
{
<KhStrip Items="Stats(balance)" Label="@T["Ledger.Balance.Title"]" />
@if (balance.Lines.Count == 0)
{
<p class="kh-wempty">@T["Ledger.Balance.None"]</p>
}
else
{
<div class="gridwrap kh-scrollx">
<table class="grid kh-ledger-tree" aria-label="@T["Ledger.Balance.Title"]">
<thead>
<tr>
<th scope="col">@T["Ledger.Fields.Account"]</th>
<th scope="col">@T["Ledger.Fields.Description"]</th>
<th scope="col" class="num">@T["Ledger.Balance.Opening"]</th>
<th scope="col" class="num">@T["Ledger.Side.Dare"]</th>
<th scope="col" class="num">@T["Ledger.Side.Avere"]</th>
<th scope="col" class="num">@T["Ledger.Balance.Debit"]</th>
<th scope="col" class="num">@T["Ledger.Balance.Credit"]</th>
</tr>
</thead>
<tbody>
@foreach (var line in balance.Lines.Where(l => l.Level <= _level))
{
<tr>
<td class="code lvl@(line.Level)" style="padding-left:@((line.Level - 1) * 14 + 8)px">@line.Code</td>
<td class="lvl@(line.Level)">@line.Description</td>
<td class="num">@(line.Opening == 0m ? null : LedgerScreens.Balance(T, line.Opening))</td>
<td class="num">@LedgerScreens.AmountText(T, line.Debit)</td>
<td class="num">@LedgerScreens.AmountText(T, line.Credit)</td>
<td class="num">@(line.Closing > 0m ? T.Money(line.Closing) : null)</td>
<td class="num">@(line.Closing < 0m ? T.Money(-line.Closing) : null)</td>
</tr>
}
</tbody>
<tfoot>
<tr>
<td colspan="3"><b>@T["Ledger.Balance.Totals"]</b></td>
<td class="num"><b>@T.Money(balance.TotalDebit)</b></td>
<td class="num"><b>@T.Money(balance.TotalCredit)</b></td>
<td colspan="2" class="num"><b>@T[balance.Result >= 0m ? "Ledger.Balance.Profit" : "Ledger.Balance.Loss"] @T.Money(Math.Abs(balance.Result))</b></td>
</tr>
</tfoot>
</table>
</div>
}
}
</KhPanel>
</LedgerGuard>
@code {
private DateOnly? _from;
private DateOnly? _to;
private long? _center;
private int _level = 3;
private bool _drafts;
private bool _busy;
private TrialBalance? _balance;
private IReadOnlyList<CostCenter> _centers = [];
private DateOnly Today => DateOnly.FromDateTime(Clock.GetLocalNow().DateTime);
private IReadOnlyList<KhOption<long?>> CenterChoices => [.. _centers.Select(c => new KhOption<long?>(c.Id, c.Code + " · " + c.Description))];
private IReadOnlyList<KhOption<int>> LevelChoices =>
[
new(1, T["Ledger.Accounts.Level1"]),
new(2, T["Ledger.Accounts.Level2"]),
new(3, T["Ledger.Accounts.Level3"]),
];
private IReadOnlyList<KhStat> Stats(TrialBalance balance) =>
[
new(T["Ledger.Side.Dare"], T.Money(balance.TotalDebit)),
new(T["Ledger.Side.Avere"], T.Money(balance.TotalCredit)),
new(T["Ledger.Balance.Check"], T[balance.Balanced ? "Ledger.Balance.Balanced" : "Ledger.Balance.NotBalanced"], balance.Balanced ? KhTone.Ok : KhTone.Error),
new(T["Ledger.Balance.Result"], T.Money(balance.Result), balance.Result >= 0m ? KhTone.Ok : KhTone.Warning),
];
/// <inheritdoc />
protected override async Task OnInitializedAsync()
{
await Session.EnsureLoadedAsync();
_from = new DateOnly(Today.Year, 1, 1);
_to = Today;
if (Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(LedgerPermissions.EntryRead)
&& Session.Licenses.IsModuleActive(Khaemhat.Application.Modules.ModuleCodes.Accounting))
{
try
{
_centers = await Tables.ActiveAsync<CostCenter>(actor, company);
}
catch (AccessDeniedException)
{
_centers = [];
}
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;
}
_balance = await Queries.TrialBalanceAsync(actor, company, from, to, _center, _drafts);
}
private async Task SetFromAsync(DateOnly? date)
{
_from = date;
await LoadAsync();
}
private async Task SetToAsync(DateOnly? date)
{
_to = date;
await LoadAsync();
}
private async Task SetCenterAsync(long? center)
{
_center = center;
await LoadAsync();
}
private async Task SetDraftsAsync(bool drafts)
{
_drafts = drafts;
await LoadAsync();
}
private async Task PrintAsync() => await RunAsync(async (actor, company, from, to) =>
await LedgerScreens.DownloadAsync(JS, await Queries.PrintTrialBalanceAsync(actor, company, from, to, _center)));
private async Task JournalAsync(bool final) => await RunAsync(async (actor, company, from, to) =>
await LedgerScreens.DownloadAsync(JS, await Queries.PrintJournalAsync(actor, company, from, to, final)));
private async Task RunAsync(Func<Actor, string, DateOnly, DateOnly, Task> action)
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _from is not { } from || _to is not { } to)
{
return;
}
_busy = true;
try
{
await action(actor, company, from, to);
}
catch (ValidationFailedException ex)
{
Toasts.Show(ToastKind.Error, T["Ledger.NotDone"], LedgerScreens.Errors(T, ex));
}
finally
{
_busy = false;
}
}
}
@@ -0,0 +1,655 @@
@page "/contabilita/prima-nota/nuova"
@page "/contabilita/prima-nota/{Id:long}"
@attribute [Authorize]
@using Khaemhat.Application.Ledger
@using Khaemhat.Application.Parties
@using Khaemhat.Application.Security
@using Khaemhat.Application.Tables
@using Khaemhat.Core.Accounting
@using Khaemhat.Core.Tables
@using Khaemhat.Web.Ledger
@inject ShellSession Session
@inject JournalEntryService Journal
@inject LedgerService Ledger
@inject PartyService Parties
@inject TableService Tables
@inject ToastService Toasts
@inject DialogService Dialogs
@inject NavigationManager Navigation
@inject TimeProvider Clock
@* An entry of the journal (SPEC §11.7, mockups 040-041): guided by a journal template, which proposes the accounts
and the sides, or typed by hand; the totals and the imbalance are always in view and an entry is posted only when it
balances; the VAT lines feed the VAT register of the entry. Entries of documents and final entries are read only:
they are changed by the document, or reversed. *@
<KhPageTitle Text="@Title" Icon="book" />
<LedgerGuard Permission="@LedgerPermissions.EntryRead">
@if (!_loaded)
{
<p class="muted kh-pad">@T["Common.Loading"]</p>
}
else
{
<div class="phead">
<div>
<div class="crumbs"><a href="@LedgerScreens.BasePath">@T["Shell.Menu.Ledger"]</a> / <a href="@(LedgerScreens.BasePath + "/prima-nota")">@T["Ledger.Journal.Title"]</a> / @Title</div>
<h1>@Title</h1>
<div class="sub">
@if (_entry is { } e)
{
<KhBadge Tone="LedgerScreens.ToneOf(e.Status)">@T[LedgerScreens.EnumKey(e.Status)]</KhBadge>
<span> @T[LedgerScreens.EnumKey(e.Source)]</span>
@if (e.JournalNumber is { } j)
{
<span> · @T.Format("Ledger.Entry.JournalNumber", j)</span>
}
@if (e.ReversalOfId is { } of)
{
<span> · <a href="@LedgerScreens.EntryUrl(of)">@T["Ledger.Entry.ReversalOf"]</a></span>
}
@if (e.ReversedById is { } by)
{
<span> · <a href="@LedgerScreens.EntryUrl(by)">@T["Ledger.Entry.ReversedBy"]</a></span>
}
}
else
{
@T["Ledger.Entry.NewHint"]
}
</div>
</div>
<div class="grow"></div>
<div class="toolbar">
@if (Editable && CanWrite)
{
<button type="button" class="btn" disabled="@_busy" @onclick="() => SaveAsync(post: false)"><KhIcon Name="save" /> @T["Ledger.Entry.SaveDraft"]</button>
<button type="button" class="btn primary" disabled="@(_busy || !Balanced)" @onclick="() => SaveAsync(post: true)"><KhIcon Name="check" /> @T["Ledger.Entry.Post"]</button>
}
@if (_entry is { } current && CanWrite)
{
@if (current.Status != GlEntryStatus.Draft && current.ReversedById is null && current.ReversalOfId is null)
{
<button type="button" class="btn" disabled="@_busy" @onclick="ReverseAsync"><KhIcon Name="undo" /> @T["Ledger.Entry.Reverse"]</button>
}
@if (current.Status != GlEntryStatus.Final && current.Source != GlEntrySource.Document)
{
<button type="button" class="btn" disabled="@_busy" @onclick="DeleteAsync"><KhIcon Name="trash" /> @T["Common.Delete"]</button>
}
}
</div>
</div>
<KhStrip Items="Stats" Label="@T["Ledger.Entry.Totals"]" />
@if (!Balanced && _lines.Any(l => l.Debit != 0m || l.Credit != 0m))
{
<div class="callout err kh-pad" role="alert">
<KhIcon Name="alert" />
<span>@T.Format("Ledger.Entry.Unbalanced", T.Money(Math.Abs(Difference)), T[Difference > 0m ? "Ledger.Side.Avere" : "Ledger.Side.Dare"])</span>
</div>
}
<KhPanel Title="@T["Ledger.Entry.Header"]" Icon="file">
<div class="form plain">
<KhDateBox Label="@T["Ledger.Fields.Date"]" Name="date" @bind-Value="_date" Span="3" Required="true" Disabled="!Editable" />
<KhSelect TValue="long?" Label="@T["Ledger.Fields.Template"]" Name="template" Options="TemplateChoices" Value="_templateId" ValueChanged="SetTemplate"
Empty="@T["Ledger.Entry.NoTemplate"]" Span="5" Disabled="!Editable" />
<KhSelect TValue="long?" Label="@T["Ledger.Fields.VatRegister"]" Name="register" Options="RegisterChoices" @bind-Value="_registerId"
Empty="@T["Ledger.Entry.NoRegister"]" Span="4" Disabled="!Editable" />
<KhTextBox Label="@T["Ledger.Fields.Description"]" Name="description" @bind-Value="_description" Span="6" Required="true" MaxLength="200" Disabled="!Editable" />
<KhTextBox Label="@T["Ledger.Fields.DocumentNumber"]" Name="docnumber" @bind-Value="_documentNumber" Span="3" MaxLength="30" Disabled="!Editable" />
<KhDateBox Label="@T["Ledger.Fields.DocumentDate"]" Name="docdate" @bind-Value="_documentDate" Span="3" Disabled="!Editable" />
</div>
</KhPanel>
<KhPanel Title="@T["Ledger.Entry.Lines"]" Icon="list" Tight="true">
<Actions>
@if (Editable)
{
<button type="button" class="btn sm" @onclick="AddLine"><KhIcon Name="plus" /> @T["Ledger.Entry.AddLine"]</button>
<button type="button" class="btn sm" disabled="@(Balanced || _lines.Count == 0)" @onclick="CloseDifference"><KhIcon Name="check" /> @T["Ledger.Entry.CloseDifference"]</button>
}
</Actions>
<ChildContent>
<datalist id="kh-accounts">
@foreach (var a in _accounts.Where(a => a.Postable && !a.Disabled))
{
<option value="@(a.Code + " · " + a.Description)"></option>
}
</datalist>
<div class="gridwrap kh-scrollx">
<table class="grid" aria-label="@T["Ledger.Entry.Lines"]">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">@T["Ledger.Fields.Account"]</th>
<th scope="col">@T["Ledger.Fields.Party"]</th>
<th scope="col">@T["Ledger.Fields.LineDescription"]</th>
<th scope="col">@T["Ledger.Fields.CostCenter"]</th>
<th scope="col" class="num">@T["Ledger.Side.Dare"]</th>
<th scope="col" class="num">@T["Ledger.Side.Avere"]</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
@for (var i = 0; i < _lines.Count; i++)
{
var line = _lines[i];
var n = i + 1;
var account = AccountOf(line.AccountId);
<tr class="@(line.AccountId is null && (line.Debit != 0m || line.Credit != 0m) ? "err" : null)">
<td class="muted">@n</td>
@if (Editable)
{
<td><input class="in" list="kh-accounts" aria-label="@(T["Ledger.Fields.Account"] + " " + n)" value="@AccountText(account)" @onchange="e => SetAccount(line, e.Value?.ToString())" style="min-width:260px" /></td>
<td class="kh-cellpick">
@if (account?.SubLedger == true)
{
<KhHotlink TItem="PartyRow" Name="@("party" + n)" Value="line.Party" ValueChanged="v => line.Party = v" Span="12"
Search="(t, c) => SearchPartiesAsync(account, t, c)" CodeOf="r => r.Code" DescriptionOf="r => r.Name" Placeholder="@T["Ledger.Entry.ChooseParty"]" />
}
</td>
<td><input class="in" maxlength="200" aria-label="@(T["Ledger.Fields.LineDescription"] + " " + n)" value="@line.Description" @onchange="e => line.Description = e.Value?.ToString()" /></td>
<td>
<select class="in" aria-label="@(T["Ledger.Fields.CostCenter"] + " " + n)" @onchange="e => line.CostCenterId = long.TryParse(e.Value?.ToString(), out var c) && c > 0 ? c : null">
<option value="0"></option>
@foreach (var center in _centers)
{
<option value="@center.Id" selected="@(center.Id == line.CostCenterId)">@center.Code</option>
}
</select>
</td>
<td class="num"><input class="in num" inputmode="decimal" aria-label="@(T["Ledger.Side.Dare"] + " " + n)" value="@LedgerScreens.AmountText(T, line.Debit)" @onchange="e => SetAmount(line, e.Value?.ToString(), debit: true)" /></td>
<td class="num"><input class="in num" inputmode="decimal" aria-label="@(T["Ledger.Side.Avere"] + " " + n)" value="@LedgerScreens.AmountText(T, line.Credit)" @onchange="e => SetAmount(line, e.Value?.ToString(), debit: false)" /></td>
<td><button type="button" class="btn sm" aria-label="@T["Ledger.Entry.RemoveLine"]" @onclick="() => _lines.Remove(line)"><KhIcon Name="trash" /></button></td>
}
else
{
<td><span class="code">@account?.Code</span> @account?.Description</td>
<td>@line.Party?.Name</td>
<td>@line.Description</td>
<td>@_centers.FirstOrDefault(c => c.Id == line.CostCenterId)?.Code</td>
<td class="num">@LedgerScreens.AmountText(T, line.Debit)</td>
<td class="num">@LedgerScreens.AmountText(T, line.Credit)</td>
<td></td>
}
</tr>
}
</tbody>
<tfoot>
<tr>
<td colspan="5" class="num"><b>@T["Ledger.Entry.Totals"]</b></td>
<td class="num"><b>@T.Money(TotalDebit)</b></td>
<td class="num"><b>@T.Money(TotalCredit)</b></td>
<td></td>
</tr>
</tfoot>
</table>
</div>
</ChildContent>
</KhPanel>
@if (_registerId is not null || _vat.Count > 0)
{
<KhPanel Title="@T["Ledger.Entry.Vat"]" Icon="euro" Tight="true">
<Actions>
@if (Editable)
{
<button type="button" class="btn sm" @onclick="() => _vat.Add(new VatLine())"><KhIcon Name="plus" /> @T["Ledger.Entry.AddVat"]</button>
}
</Actions>
<ChildContent>
<table class="grid" aria-label="@T["Ledger.Entry.Vat"]">
<thead>
<tr>
<th scope="col">@T["Ledger.Fields.TaxCode"]</th>
<th scope="col" class="num">@T["Ledger.Fields.Rate"]</th>
<th scope="col" class="num">@T["Ledger.Fields.Taxable"]</th>
<th scope="col" class="num">@T["Ledger.Fields.Tax"]</th>
<th scope="col" class="num">@T["Ledger.Fields.NonDeductible"]</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
@foreach (var v in _vat)
{
<tr>
@if (Editable)
{
<td>
<select class="in" aria-label="@T["Ledger.Fields.TaxCode"]" @onchange="e => SetTaxCode(v, e.Value?.ToString())">
<option value="0"></option>
@foreach (var taxCode in _taxCodes)
{
<option value="@taxCode.Id" selected="@(taxCode.Id == v.TaxCodeId)">@(taxCode.Code + " · " + taxCode.Description)</option>
}
</select>
</td>
<td class="num">@(v.Nature ?? v.Rate.ToString("0.##", T.Culture) + "%")</td>
<td class="num"><input class="in num" inputmode="decimal" aria-label="@T["Ledger.Fields.Taxable"]" value="@LedgerScreens.AmountText(T, v.Taxable)" @onchange="e => SetTaxable(v, e.Value?.ToString())" /></td>
<td class="num"><input class="in num" inputmode="decimal" aria-label="@T["Ledger.Fields.Tax"]" value="@LedgerScreens.AmountText(T, v.Tax)" @onchange="e => v.Tax = LedgerScreens.ParseAmount(T, e.Value?.ToString())" /></td>
<td class="num"><input class="in num" inputmode="decimal" aria-label="@T["Ledger.Fields.NonDeductible"]" value="@LedgerScreens.AmountText(T, v.NonDeductible)" @onchange="e => v.NonDeductible = LedgerScreens.ParseAmount(T, e.Value?.ToString())" /></td>
<td><button type="button" class="btn sm" aria-label="@T["Ledger.Entry.RemoveLine"]" @onclick="() => _vat.Remove(v)"><KhIcon Name="trash" /></button></td>
}
else
{
<td>@_taxCodes.FirstOrDefault(c => c.Id == v.TaxCodeId)?.Code</td>
<td class="num">@(v.Nature ?? v.Rate.ToString("0.##", T.Culture) + "%")</td>
<td class="num">@T.Money(v.Taxable)</td>
<td class="num">@T.Money(v.Tax)</td>
<td class="num">@LedgerScreens.AmountText(T, v.NonDeductible)</td>
<td></td>
}
</tr>
}
</tbody>
</table>
</ChildContent>
</KhPanel>
}
<KhDialog Open="_reverseOpen" Title="@T["Ledger.Entry.Reverse"]" Icon="undo" OnClose="() => _reverseOpen = false">
<ChildContent>
<p>@T["Ledger.Entry.ReverseText"]</p>
<div class="form plain">
<KhDateBox Label="@T["Ledger.Entry.ReverseDate"]" Name="reversedate" @bind-Value="_reverseDate" Span="6" Required="true" />
</div>
</ChildContent>
<Footer>
<button type="button" class="btn" @onclick="() => _reverseOpen = false">@T["Common.Cancel"]</button>
<button type="button" class="btn primary" disabled="@(_busy || _reverseDate is null)" @onclick="ConfirmReverseAsync"><KhIcon Name="undo" /> @T["Ledger.Entry.Reverse"]</button>
</Footer>
</KhDialog>
}
</LedgerGuard>
@code {
private bool _loaded;
private bool _busy;
private GlEntry? _entry;
private IReadOnlyList<GlAccount> _accounts = [];
private IReadOnlyList<TemplateView> _templates = [];
private IReadOnlyList<VatRegister> _registers = [];
private IReadOnlyList<TaxCode> _taxCodes = [];
private IReadOnlyList<CostCenter> _centers = [];
private DateOnly? _date;
private long? _templateId;
private long? _registerId;
private string? _description;
private string? _documentNumber;
private DateOnly? _documentDate;
private List<Line> _lines = [];
private List<VatLine> _vat = [];
private bool _reverseOpen;
private DateOnly? _reverseDate;
/// <summary>The entry, or <see langword="null"/> for a new one.</summary>
[Parameter]
public long? Id { get; set; }
private string Title => _entry is { } e ? T.Format("Ledger.Entry.Title", e.EntryNumber ?? T["Ledger.Journal.NoNumber"]) : T["Ledger.Entry.New"];
private bool CanWrite => Session.Permissions.Allows(LedgerPermissions.EntryWrite);
private bool Editable => CanWrite && (_entry is null || (_entry.Status != GlEntryStatus.Final && _entry.Source != GlEntrySource.Document));
private decimal TotalDebit => _lines.Sum(l => l.Debit);
private decimal TotalCredit => _lines.Sum(l => l.Credit);
private decimal Difference => TotalDebit - TotalCredit;
private bool Balanced => Difference == 0m && TotalDebit != 0m;
private IReadOnlyList<KhStat> Stats =>
[
new(T["Ledger.Side.Dare"], T.Money(TotalDebit)),
new(T["Ledger.Side.Avere"], T.Money(TotalCredit)),
new(T["Ledger.Entry.Difference"], T.Money(Math.Abs(Difference)), Difference == 0m ? KhTone.Ok : KhTone.Error),
new(T["Ledger.Entry.LinesCount"], T.Number(_lines.Count)),
];
private IReadOnlyList<KhOption<long?>> TemplateChoices =>
[.. _templates.Where(t => !t.Template.Disabled).Select(t => new KhOption<long?>(t.Template.Id, t.Template.Code + " · " + t.Template.Description))];
private IReadOnlyList<KhOption<long?>> RegisterChoices =>
[.. _registers.Where(r => !r.Disabled).Select(r => new KhOption<long?>(r.Id, r.Code + " · " + r.Description))];
/// <inheritdoc />
protected override async Task OnParametersSetAsync()
{
await Session.EnsureLoadedAsync();
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || !Session.Permissions.Allows(LedgerPermissions.EntryRead)
|| !Session.Licenses.IsModuleActive(Khaemhat.Application.Modules.ModuleCodes.Accounting))
{
_loaded = true;
return;
}
if (_accounts.Count == 0)
{
_accounts = await Ledger.AccountsAsync(actor, company);
_templates = await Journal.TemplatesAsync(actor, company);
_registers = await Ledger.RegistersAsync(actor, company);
_taxCodes = await ActiveAsync<TaxCode>(actor, company);
_centers = await ActiveAsync<CostCenter>(actor, company);
}
await LoadAsync(actor, company);
_loaded = true;
}
private async Task<IReadOnlyList<TItem>> ActiveAsync<TItem>(Actor actor, string company)
where TItem : CodedEntity, new()
{
try
{
return await Tables.ActiveAsync<TItem>(actor, company);
}
catch (AccessDeniedException)
{
return [];
}
}
private async Task LoadAsync(Actor actor, string company)
{
if (Id is not { } id)
{
_entry = null;
_date = DateOnly.FromDateTime(Clock.GetLocalNow().DateTime);
_lines = [new Line(), new Line()];
_vat = [];
return;
}
var view = await Journal.GetAsync(actor, company, id);
if (view is null)
{
Navigation.NavigateTo(LedgerScreens.BasePath + "/prima-nota");
return;
}
var e = view.Entry;
_entry = e;
_date = e.EntryDate;
_templateId = e.JournalTemplateId;
_registerId = e.VatRegisterId;
_description = e.Description;
_documentNumber = e.DocumentNumber;
_documentDate = e.DocumentDate;
var partyIds = view.Lines.Where(l => l.PartyId is not null).Select(l => l.PartyId!.Value).Distinct().ToList();
var parties = partyIds.Count == 0 || !Session.Permissions.Allows(PartyService.ReadPermission)
? new Dictionary<long, PartyRow>()
: (await Parties.RowsAsync(actor, company, partyIds)).ToDictionary(p => p.Id);
_lines = [.. view.Lines.Select(l => new Line
{
AccountId = l.AccountId,
Party = l.PartyId is { } p ? parties.GetValueOrDefault(p) : null,
Description = l.Description,
Debit = l.Debit,
Credit = l.Credit,
CostCenterId = l.CostCenterId,
JobId = l.JobId,
})];
_vat = [.. view.Vat.Select(v => new VatLine
{
TaxCodeId = v.TaxCodeId,
Rate = v.Rate,
Nature = v.Nature,
Taxable = v.Taxable,
Tax = v.Tax,
NonDeductible = v.NonDeductibleTax,
Exigibility = v.Exigibility,
RegisterId = v.VatRegisterId == e.VatRegisterId ? null : v.VatRegisterId,
})];
}
private GlAccount? AccountOf(long? id) => id is { } value ? _accounts.FirstOrDefault(a => a.Id == value) : null;
private static string AccountText(GlAccount? account) => account is null ? string.Empty : account.Code + " · " + account.Description;
private void SetAccount(Line line, string? text)
{
var code = (text ?? string.Empty).Split('·')[0].Trim();
var account = _accounts.FirstOrDefault(a => string.Equals(a.Code, code, StringComparison.OrdinalIgnoreCase))
?? _accounts.FirstOrDefault(a => a.Postable && a.Description.Contains(code, StringComparison.OrdinalIgnoreCase));
line.AccountId = account?.Id;
if (account?.SubLedger != true)
{
line.Party = null;
}
}
private void SetAmount(Line line, string? text, bool debit)
{
var amount = LedgerScreens.ParseAmount(T, text);
if (debit)
{
line.Debit = amount;
if (amount != 0m)
{
line.Credit = 0m;
}
}
else
{
line.Credit = amount;
if (amount != 0m)
{
line.Debit = 0m;
}
}
}
private void AddLine() => _lines.Add(new Line { Description = _description });
// The last line without an amount (or a new one) takes the difference on the side that balances.
private void CloseDifference()
{
var target = _lines.LastOrDefault(l => l.Debit == 0m && l.Credit == 0m);
if (target is null)
{
target = new Line { Description = _description };
_lines.Add(target);
}
if (Difference > 0m)
{
target.Credit = Difference;
}
else
{
target.Debit = -Difference;
}
}
// A template proposes its lines with their accounts and sides, and its VAT register.
private void SetTemplate(long? id)
{
_templateId = id;
if (_templates.FirstOrDefault(t => t.Template.Id == id) is not { } view)
{
return;
}
_description ??= view.Template.Description;
if (view.Template.VatRegisterCode is { } code)
{
_registerId = _registers.FirstOrDefault(r => r.Code == code)?.Id ?? _registerId;
}
if (_lines.All(l => l.Debit == 0m && l.Credit == 0m))
{
_lines = [.. view.Lines.Select(l => new Line { AccountId = l.AccountId, Description = l.Description ?? _description })];
}
}
private async Task<IReadOnlyList<PartyRow>> SearchPartiesAsync(GlAccount? account, string text, CancellationToken cancellationToken) =>
Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(PartyService.ReadPermission)
? await Parties.SearchAsync(actor, company, account?.Type == AccountType.Suppliers ? PartyArchive.Suppliers : PartyArchive.Customers, text, cancellationToken)
: [];
private void SetTaxCode(VatLine line, string? value)
{
line.TaxCodeId = long.TryParse(value, out var id) && id > 0 ? id : null;
var code = _taxCodes.FirstOrDefault(c => c.Id == line.TaxCodeId);
line.Rate = code?.Rate ?? 0m;
line.Nature = code?.Nature;
line.Exigibility = code?.Exigibility ?? Khaemhat.Core.Tax.TaxExigibility.Immediate;
line.Tax = Math.Round(line.Taxable * line.Rate / 100m, 2, MidpointRounding.AwayFromZero);
line.NonDeductible = Math.Round(line.Tax * (code?.NonDeductiblePercent ?? 0m) / 100m, 2, MidpointRounding.AwayFromZero);
}
private void SetTaxable(VatLine line, string? text)
{
line.Taxable = LedgerScreens.ParseAmount(T, text);
line.Tax = Math.Round(line.Taxable * line.Rate / 100m, 2, MidpointRounding.AwayFromZero);
var code = _taxCodes.FirstOrDefault(c => c.Id == line.TaxCodeId);
line.NonDeductible = Math.Round(line.Tax * (code?.NonDeductiblePercent ?? 0m) / 100m, 2, MidpointRounding.AwayFromZero);
}
private async Task SaveAsync(bool post)
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
_busy = true;
try
{
var input = new EntryInput(
_entry?.Id,
_date ?? default,
_description ?? string.Empty,
[.. _lines.Select(l => new EntryLineDraft(l.AccountId, l.Party?.Id, l.Description, l.Debit, l.Credit, l.CostCenterId, l.JobId))])
{
JournalTemplateId = _templateId,
DocumentNumber = _documentNumber,
DocumentDate = _documentDate,
PartyId = _lines.Select(l => l.Party?.Id).FirstOrDefault(p => p is not null),
VatRegisterId = _registerId,
VatDate = _date,
Vat = [.. _vat.Where(v => v.Taxable != 0m || v.Tax != 0m).Select(v => new EntryVatDraft(v.TaxCodeId, v.Rate, v.Nature, v.Taxable, v.Tax, v.NonDeductible, v.Exigibility, v.RegisterId))],
Notes = _entry?.Notes,
Post = post,
};
var saved = await Journal.SaveAsync(actor, company, input);
Toasts.Show(ToastKind.Success, T[post ? "Ledger.Entry.Posted" : "Ledger.Saved"], saved.Entry.EntryNumber);
if (Id != saved.Entry.Id)
{
Navigation.NavigateTo(LedgerScreens.EntryUrl(saved.Entry.Id));
}
else
{
await LoadAsync(actor, company);
}
}
catch (ValidationFailedException ex)
{
Toasts.Show(ToastKind.Error, T["Ledger.NotSaved"], LedgerScreens.Errors(T, ex));
}
finally
{
_busy = false;
}
}
private void ReverseAsync()
{
_reverseDate = DateOnly.FromDateTime(Clock.GetLocalNow().DateTime);
_reverseOpen = true;
}
private async Task ConfirmReverseAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _entry is null || _reverseDate is not { } date)
{
return;
}
_busy = true;
try
{
var reversal = await Journal.ReverseAsync(actor, company, _entry.Id, date);
_reverseOpen = false;
Toasts.Show(ToastKind.Success, T["Ledger.Entry.Reversed"], reversal.Entry.EntryNumber);
Navigation.NavigateTo(LedgerScreens.EntryUrl(reversal.Entry.Id));
}
catch (ValidationFailedException ex)
{
Toasts.Show(ToastKind.Error, T["Ledger.NotDone"], LedgerScreens.Errors(T, ex));
}
finally
{
_busy = false;
}
}
private async Task DeleteAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _entry is null)
{
return;
}
if (!await Dialogs.ConfirmAsync(new ConfirmRequest(T["Ledger.Entry.Delete"], T.Format("Ledger.Entry.DeleteText", _entry.EntryNumber ?? _entry.Description), T["Common.Delete"], T["Common.Cancel"])))
{
return;
}
_busy = true;
try
{
await Journal.DeleteAsync(actor, company, _entry.Id);
Toasts.Show(ToastKind.Success, T["Ledger.Entry.Deleted"]);
Navigation.NavigateTo(LedgerScreens.BasePath + "/prima-nota");
}
catch (ValidationFailedException ex)
{
Toasts.Show(ToastKind.Error, T["Ledger.NotDone"], LedgerScreens.Errors(T, ex));
}
finally
{
_busy = false;
}
}
private sealed class Line
{
public long? AccountId { get; set; }
public PartyRow? Party { get; set; }
public string? Description { get; set; }
public decimal Debit { get; set; }
public decimal Credit { get; set; }
public long? CostCenterId { get; set; }
public long? JobId { get; set; }
}
private sealed class VatLine
{
public long? TaxCodeId { get; set; }
public decimal Rate { get; set; }
public string? Nature { get; set; }
public decimal Taxable { get; set; }
public decimal Tax { get; set; }
public decimal NonDeductible { get; set; }
public Khaemhat.Core.Tax.TaxExigibility Exigibility { get; set; }
public long? RegisterId { get; set; }
}
}
@@ -0,0 +1,473 @@
@page "/contabilita"
@page "/contabilita/prima-nota"
@attribute [Authorize]
@using Khaemhat.Application.Ledger
@using Khaemhat.Application.Security
@using Khaemhat.Core.Accounting
@using Khaemhat.Web.Ledger
@inject ShellSession Session
@inject JournalEntryService Journal
@inject LedgerService Ledger
@inject RecurringEntryService Recurring
@inject ToastService Toasts
@inject DialogService Dialogs
@inject NavigationManager Navigation
@inject TimeProvider Clock
@* The journal (SPEC §11.7, mockup 040): the entries of a period, paged, with their state (draft, posted, final), the
way to each entry, the posting of the documents not yet in the ledger, the final numbering of the general journal
and the recurring entries. *@
<KhPageTitle Text="@T["Ledger.Journal.Title"]" Icon="book" />
<LedgerGuard Permission="@LedgerPermissions.EntryRead">
<div class="phead">
<div>
<div class="crumbs"><a href="@LedgerScreens.BasePath">@T["Shell.Menu.Ledger"]</a> / @T["Ledger.Journal.Title"]</div>
<h1>@T["Ledger.Journal.Heading"]</h1>
<div class="sub">@T["Ledger.Journal.Hint"]</div>
</div>
<div class="grow"></div>
<div class="toolbar">
@if (CanWrite)
{
<a class="btn primary" href="@(LedgerScreens.BasePath + "/prima-nota/nuova")"><KhIcon Name="plus" /> @T["Ledger.Journal.New"]</a>
<button type="button" class="btn" disabled="@_busy" @onclick="PostDocumentsAsync"><KhIcon Name="refresh" /> @T["Ledger.Journal.PostDocuments"]</button>
}
@if (CanFinalize)
{
<button type="button" class="btn" disabled="@_busy" @onclick="FinalizeAsync"><KhIcon Name="lock" /> @T["Ledger.Journal.Finalize"]</button>
}
</div>
</div>
<KhTabs Items="Tabs" Active="@_tab" ActiveChanged="t => _tab = t" Label="@T["Ledger.Journal.Title"]" />
@if (_tab == "recurring")
{
<KhPanel Title="@T["Ledger.Recurring.Title"]" Icon="history" Tight="true">
<Actions>
@if (CanWrite)
{
<button type="button" class="btn" disabled="@_busy" @onclick="GenerateAsync"><KhIcon Name="zap" /> @T["Ledger.Recurring.Generate"]</button>
<button type="button" class="btn primary" disabled="@_busy" @onclick="() => EditRecurring(null)"><KhIcon Name="plus" /> @T["Ledger.Recurring.New"]</button>
}
</Actions>
<ChildContent>
@if (_recurring.Count == 0)
{
<p class="kh-wempty">@T["Ledger.Recurring.None"]</p>
}
else
{
<table class="grid" aria-label="@T["Ledger.Recurring.Title"]">
<thead>
<tr>
<th scope="col">@T["Ledger.Fields.Description"]</th>
<th scope="col">@T["Ledger.Recurring.Frequency"]</th>
<th scope="col">@T["Ledger.Recurring.NextDate"]</th>
<th scope="col">@T["Ledger.Recurring.EndDate"]</th>
<th scope="col">@T["Ledger.Recurring.Model"]</th>
<th scope="col">@T["Ledger.Fields.Status"]</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
@foreach (var r in _recurring)
{
<tr>
<td>@r.Description</td>
<td>@T[LedgerScreens.EnumKey(r.Frequency)]</td>
<td>@T.Date(r.NextDate)</td>
<td>@(r.EndDate is { } end ? T.Date(end) : "-")</td>
<td><a href="@LedgerScreens.EntryUrl(r.ModelEntryId)">@T["Ledger.Recurring.OpenModel"]</a></td>
<td><KhBadge Tone="@(r.Disabled ? KhTone.Neutral : KhTone.Ok)">@T[r.Disabled ? "Ledger.Recurring.Suspended" : "Ledger.Recurring.Active"]</KhBadge></td>
<td class="num">
@if (CanWrite)
{
<button type="button" class="btn sm" @onclick="() => EditRecurring(r)"><KhIcon Name="edit" /> @T["Common.Edit"]</button>
<button type="button" class="btn sm" @onclick="() => DeleteRecurringAsync(r)"><KhIcon Name="trash" /></button>
}
</td>
</tr>
}
</tbody>
</table>
}
</ChildContent>
</KhPanel>
<p class="muted sm kh-pad">@T["Ledger.Recurring.Hint"]</p>
}
else
{
<KhPanel Tight="true">
<div class="filters">
<input type="search" class="in" placeholder="@T["Ledger.Journal.Search"]" aria-label="@T["Ledger.Journal.Search"]" value="@_text"
@onchange="e => SetTextAsync(e.Value?.ToString())" />
<KhDateBox Label="@T["Ledger.Fields.From"]" Name="from" Value="_from" ValueChanged="d => SetFromAsync(d)" />
<KhDateBox Label="@T["Ledger.Fields.To"]" Name="to" Value="_to" ValueChanged="d => SetToAsync(d)" />
<KhSelect TValue="GlEntryStatus?" Label="@T["Ledger.Fields.Status"]" Name="status" Options="StatusChoices" Value="_status" ValueChanged="SetStatusAsync" Empty="@T["Ledger.Journal.AllStates"]" />
<span class="grow"></span>
<span class="muted sm">@T.Format("Ledger.Journal.Count", T.Number(_total))</span>
</div>
@if (_rows.Count == 0)
{
<p class="kh-wempty">@T["Ledger.Journal.None"]</p>
}
else
{
<div class="gridwrap kh-scrollx">
<table class="grid" aria-label="@T["Ledger.Journal.Title"]">
<thead>
<tr>
<th scope="col">@T["Ledger.Fields.Number"]</th>
<th scope="col">@T["Ledger.Fields.Date"]</th>
<th scope="col">@T["Ledger.Fields.Template"]</th>
<th scope="col">@T["Ledger.Fields.Description"]</th>
<th scope="col">@T["Ledger.Fields.Document"]</th>
<th scope="col">@T["Ledger.Fields.Party"]</th>
<th scope="col" class="num">@T["Ledger.Fields.Amount"]</th>
<th scope="col">@T["Ledger.Fields.Status"]</th>
</tr>
</thead>
<tbody>
@foreach (var row in _rows)
{
var e = row.Entry;
<tr style="cursor:pointer" @onclick="() => Navigation.NavigateTo(LedgerScreens.EntryUrl(e.Id))">
<td class="code"><a href="@LedgerScreens.EntryUrl(e.Id)">@(e.EntryNumber ?? T["Ledger.Journal.NoNumber"])</a></td>
<td>@T.Date(e.EntryDate)</td>
<td class="code">@e.TemplateCode</td>
<td>@e.Description</td>
<td>@e.DocumentNumber</td>
<td>@row.PartyName</td>
<td class="num">@T.Money(e.TotalDebit)</td>
<td>
<KhBadge Tone="LedgerScreens.ToneOf(e.Status)">@T[LedgerScreens.EnumKey(e.Status)]</KhBadge>
@if (e.ReversedById is not null)
{
<KhBadge Tone="KhTone.Neutral">@T["Ledger.Journal.Reversed"]</KhBadge>
}
</td>
</tr>
}
</tbody>
</table>
</div>
<div class="filters">
<span class="muted sm">@T.Format("Ledger.Pager", _offset + 1, Math.Min(_offset + PageSize, _total), _total)</span>
<span class="grow"></span>
<button type="button" class="btn sm" disabled="@(_offset == 0)" @onclick="() => PageAsync(-1)"><KhIcon Name="chevron-left" /> @T["Ledger.Previous"]</button>
<button type="button" class="btn sm" disabled="@(_offset + PageSize >= _total)" @onclick="() => PageAsync(1)">@T["Ledger.Next"] <KhIcon Name="chevron-right" /></button>
</div>
}
</KhPanel>
}
<KhDialog Open="_finalizeOpen" Title="@T["Ledger.Journal.Finalize"]" Icon="lock" OnClose="() => _finalizeOpen = false">
<ChildContent>
<p>@T["Ledger.Journal.FinalizeText"]</p>
<div class="form plain">
<KhDateBox Label="@T["Ledger.Journal.FinalizeUpTo"]" Name="upto" @bind-Value="_upTo" Span="6" Required="true" />
</div>
</ChildContent>
<Footer>
<button type="button" class="btn" @onclick="() => _finalizeOpen = false">@T["Common.Cancel"]</button>
<button type="button" class="btn primary" disabled="@(_busy || _upTo is null)" @onclick="ConfirmFinalizeAsync"><KhIcon Name="lock" /> @T["Ledger.Journal.Finalize"]</button>
</Footer>
</KhDialog>
<KhDialog Open="_postOpen" Title="@T["Ledger.Journal.PostDocuments"]" Icon="refresh" OnClose="() => _postOpen = false">
<ChildContent>
<p>@T["Ledger.Journal.PostText"]</p>
<div class="form plain">
<KhDateBox Label="@T["Ledger.Fields.From"]" Name="postfrom" @bind-Value="_postFrom" Span="6" Required="true" />
<KhDateBox Label="@T["Ledger.Fields.To"]" Name="postto" @bind-Value="_postTo" Span="6" Required="true" />
<KhCheck Label="@T["Ledger.Journal.PostAgain"]" Name="again" @bind-Value="_postAgain" Span="12" />
</div>
@if (_report is { } report)
{
<div class="callout @(report.Failed.Count == 0 ? "ok" : "warn")" role="status">
<KhIcon Name="info" />
<div>
@T.Format("Ledger.Journal.Posted", report.Posted)
@foreach (var failure in report.Failed)
{
<div class="sm">@failure</div>
}
</div>
</div>
}
</ChildContent>
<Footer>
<button type="button" class="btn" @onclick="() => _postOpen = false">@T["Common.Close"]</button>
<button type="button" class="btn primary" disabled="@(_busy || _postFrom is null || _postTo is null)" @onclick="ConfirmPostAsync"><KhIcon Name="zap" /> @T["Ledger.Journal.PostRun"]</button>
</Footer>
</KhDialog>
<KhDialog Open="_recurringOpen" Title="@T["Ledger.Recurring.Title"]" Icon="history" OnClose="() => _recurringOpen = false">
<ChildContent>
<div class="form plain">
<KhTextBox Label="@T["Ledger.Fields.Description"]" Name="rdesc" @bind-Value="_rDescription" Span="12" Required="true" MaxLength="200" />
<KhTextBox Label="@T["Ledger.Recurring.ModelNumber"]" Name="rmodel" @bind-Value="_rModel" Span="6" Required="true" Mono="true" Hint="@T["Ledger.Recurring.ModelHint"]" />
<KhSelect TValue="RecurrenceFrequency" Label="@T["Ledger.Recurring.Frequency"]" Name="rfreq" Options="LedgerScreens.Choices<RecurrenceFrequency>(T)" @bind-Value="_rFrequency" Span="6" />
<KhDateBox Label="@T["Ledger.Recurring.NextDate"]" Name="rnext" @bind-Value="_rNext" Span="6" Required="true" />
<KhDateBox Label="@T["Ledger.Recurring.EndDate"]" Name="rend" @bind-Value="_rEnd" Span="6" />
<KhCheck Label="@T["Ledger.Recurring.Suspended"]" Name="rdisabled" @bind-Value="_rDisabled" Span="12" />
</div>
</ChildContent>
<Footer>
<button type="button" class="btn" @onclick="() => _recurringOpen = false">@T["Common.Cancel"]</button>
<button type="button" class="btn primary" disabled="@_busy" @onclick="SaveRecurringAsync"><KhIcon Name="check" /> @T["Common.Save"]</button>
</Footer>
</KhDialog>
</LedgerGuard>
@code {
private const int PageSize = 50;
private IReadOnlyList<EntryRow> _rows = [];
private IReadOnlyList<RecurringEntry> _recurring = [];
private int _total;
private int _offset;
private string? _text;
private DateOnly? _from;
private DateOnly? _to;
private GlEntryStatus? _status;
private string _tab = "entries";
private bool _busy;
private bool _finalizeOpen;
private DateOnly? _upTo;
private bool _postOpen;
private DateOnly? _postFrom;
private DateOnly? _postTo;
private bool _postAgain;
private PostingReport? _report;
private bool _recurringOpen;
private long? _rId;
private string? _rDescription;
private string? _rModel;
private RecurrenceFrequency _rFrequency;
private DateOnly? _rNext;
private DateOnly? _rEnd;
private bool _rDisabled;
private bool CanWrite => Session.Permissions.Allows(LedgerPermissions.EntryWrite);
private bool CanFinalize => Session.Permissions.Allows(LedgerPermissions.EntryFinalize);
private DateOnly Today => DateOnly.FromDateTime(Clock.GetLocalNow().DateTime);
private IReadOnlyList<KhTabItem> Tabs =>
[
new("entries", "book", T["Ledger.Journal.Entries"], _total),
new("recurring", "history", T["Ledger.Recurring.Title"], _recurring.Count),
];
private IReadOnlyList<KhOption<GlEntryStatus?>> StatusChoices =>
[.. Enum.GetValues<GlEntryStatus>().Select(s => new KhOption<GlEntryStatus?>(s, T[LedgerScreens.EnumKey(s)]))];
/// <inheritdoc />
protected override async Task OnInitializedAsync()
{
await Session.EnsureLoadedAsync();
_from = new DateOnly(Today.Year, 1, 1);
_to = new DateOnly(Today.Year, 12, 31);
if (Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(LedgerPermissions.EntryRead)
&& Session.Licenses.IsModuleActive(Khaemhat.Application.Modules.ModuleCodes.Accounting))
{
await LoadAsync();
_recurring = await Recurring.ListAsync(actor, company);
}
}
private async Task LoadAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
(_rows, _total) = await Journal.ListAsync(actor, company, new EntryFilter(_from, _to, _status, null, _text, _offset, PageSize));
}
private async Task SetTextAsync(string? text)
{
_text = string.IsNullOrWhiteSpace(text) ? null : text.Trim();
_offset = 0;
await LoadAsync();
}
private async Task SetFromAsync(DateOnly? date)
{
_from = date;
_offset = 0;
await LoadAsync();
}
private async Task SetToAsync(DateOnly? date)
{
_to = date;
_offset = 0;
await LoadAsync();
}
private async Task SetStatusAsync(GlEntryStatus? status)
{
_status = status;
_offset = 0;
await LoadAsync();
}
private async Task PageAsync(int step)
{
_offset = Math.Max(0, _offset + (step * PageSize));
await LoadAsync();
}
private void FinalizeAsync()
{
_upTo ??= Today.AddDays(-Today.Day);
_finalizeOpen = true;
}
private async Task ConfirmFinalizeAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _upTo is not { } upTo)
{
return;
}
if (!await Dialogs.ConfirmAsync(new ConfirmRequest(T["Ledger.Journal.Finalize"], T.Format("Ledger.Journal.FinalizeConfirm", T.Date(upTo)), T["Ledger.Journal.Finalize"], T["Common.Cancel"])))
{
return;
}
await RunAsync(async () =>
{
var count = await Journal.FinalizeAsync(actor, company, upTo);
Toasts.Show(ToastKind.Success, T.Format("Ledger.Journal.Finalized", count));
_finalizeOpen = false;
await LoadAsync();
});
}
private void PostDocumentsAsync()
{
_postFrom ??= new DateOnly(Today.Year, 1, 1);
_postTo ??= Today;
_report = null;
_postOpen = true;
}
private async Task ConfirmPostAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _postFrom is not { } from || _postTo is not { } to)
{
return;
}
await RunAsync(async () =>
{
_report = await Ledger.PostPendingAsync(actor, company, from, to, _postAgain);
await LoadAsync();
});
}
private void EditRecurring(RecurringEntry? r)
{
_rId = r?.Id;
_rDescription = r?.Description;
_rModel = r?.ModelEntryId.ToString(System.Globalization.CultureInfo.InvariantCulture);
_rFrequency = r?.Frequency ?? RecurrenceFrequency.Monthly;
_rNext = r?.NextDate ?? Today;
_rEnd = r?.EndDate;
_rDisabled = r?.Disabled ?? false;
_recurringOpen = true;
}
private async Task SaveRecurringAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
var model = await ModelIdAsync(actor, company, _rModel);
await RunAsync(async () =>
{
await Recurring.SaveAsync(actor, company, new RecurringEntryInput(_rId, _rDescription ?? string.Empty, model, _rFrequency, _rNext ?? default, _rEnd, _rDisabled));
_recurring = await Recurring.ListAsync(actor, company);
_recurringOpen = false;
Toasts.Show(ToastKind.Success, T["Ledger.Saved"]);
});
}
// The model is chosen by the number of the entry as shown (2026/00012) or by its id.
private async Task<long> ModelIdAsync(Actor actor, string company, string? text)
{
text = text?.Trim();
if (string.IsNullOrEmpty(text))
{
return 0;
}
if (!text.Contains('/', StringComparison.Ordinal) && long.TryParse(text, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var id))
{
return id;
}
var (rows, _) = await Journal.ListAsync(actor, company, new EntryFilter(Text: text, Limit: 20));
return rows.FirstOrDefault(r => r.Entry.EntryNumber == text)?.Entry.Id ?? 0;
}
private async Task DeleteRecurringAsync(RecurringEntry r)
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
if (!await Dialogs.ConfirmAsync(new ConfirmRequest(T["Ledger.Recurring.Delete"], T.Format("Ledger.Recurring.DeleteText", r.Description), T["Common.Delete"], T["Common.Cancel"])))
{
return;
}
await RunAsync(async () =>
{
await Recurring.DeleteAsync(actor, company, r.Id);
_recurring = await Recurring.ListAsync(actor, company);
});
}
private async Task GenerateAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
await RunAsync(async () =>
{
var (written, problems) = await Recurring.GenerateAsync(actor, company, Today);
Toasts.Show(problems.Count == 0 ? ToastKind.Success : ToastKind.Warning, T.Format("Ledger.Recurring.Generated", written), string.Join(" ", problems));
_recurring = await Recurring.ListAsync(actor, company);
await LoadAsync();
});
}
private async Task RunAsync(Func<Task> action)
{
_busy = true;
try
{
await action();
}
catch (ValidationFailedException ex)
{
Toasts.Show(ToastKind.Error, T["Ledger.NotDone"], LedgerScreens.Errors(T, ex));
}
finally
{
_busy = false;
}
}
}
@@ -0,0 +1,55 @@
@using Khaemhat.Application.Modules
@inject ShellSession Session
@* What every page of the ledger checks first: an open company, the module ACCT in the licence and the permission. *@
@if (!_loaded)
{
<p class="muted kh-pad">@T["Common.Loading"]</p>
}
else if (Session.Company is null)
{
<div class="kh-message">
<KhIcon Name="building" Class="lg" />
<h1>@T["Ledger.NoCompany"]</h1>
</div>
}
else if (!Session.Licenses.IsModuleActive(ModuleCodes.Accounting))
{
<div class="kh-message">
<KhIcon Name="key" Class="lg" />
<h1>@T["Ledger.NoModule.Title"]</h1>
<p class="lead">@T["Ledger.NoModule.Lead"]</p>
</div>
}
else if (!Session.Permissions.Allows(Permission))
{
<div class="kh-message">
<KhIcon Name="lock" Class="lg" />
<h1>@T["Pages.AccessDenied.Title"]</h1>
<p class="lead">@T["Pages.AccessDenied.Lead"]</p>
<a class="btn" href="./">@T["Common.BackHome"]</a>
</div>
}
else
{
@ChildContent
}
@code {
private bool _loaded;
/// <summary>The permission the page needs.</summary>
[Parameter, EditorRequired]
public string Permission { get; set; } = string.Empty;
/// <summary>The page.</summary>
[Parameter]
public RenderFragment? ChildContent { get; set; }
/// <inheritdoc />
protected override async Task OnInitializedAsync()
{
await Session.EnsureLoadedAsync();
_loaded = true;
}
}
@@ -0,0 +1,114 @@
@using Khaemhat.Application.Ledger
@using Khaemhat.Web.Ledger
@* The movements of an account or a party (mastrino, estratto conto, mockups 042 and 044): the period, the opening
balance, the movements of the page with the running balance and the way to each entry, the totals and the pager. *@
<div class="filters kh-ledger-filters">
<KhDateBox Label="@T["Ledger.Fields.From"]" Name="mfrom" Value="From" ValueChanged="FromChanged" />
<KhDateBox Label="@T["Ledger.Fields.To"]" Name="mto" Value="To" ValueChanged="ToChanged" />
<span class="grow"></span>
@if (Page is { } p)
{
<span class="muted sm">@T["Ledger.Movements.Opening"]: <b>@LedgerScreens.Balance(T, p.Opening)</b></span>
}
</div>
@if (Page is not { } page)
{
<p class="muted kh-pad">@T["Common.Loading"]</p>
}
else if (page.TotalCount == 0)
{
<p class="kh-wempty">@T["Ledger.Movements.None"]</p>
}
else
{
<div class="gridwrap kh-scrollx">
<table class="grid" aria-label="@T["Ledger.Movements.Title"]">
<thead>
<tr>
<th scope="col">@T["Ledger.Fields.Date"]</th>
<th scope="col">@T["Ledger.Fields.Number"]</th>
@if (ShowAccount)
{
<th scope="col">@T["Ledger.Fields.Account"]</th>
}
<th scope="col">@T["Ledger.Fields.Document"]</th>
<th scope="col">@T["Ledger.Fields.Description"]</th>
<th scope="col" class="num">@T["Ledger.Side.Dare"]</th>
<th scope="col" class="num">@T["Ledger.Side.Avere"]</th>
<th scope="col" class="num">@T["Ledger.Movements.Balance"]</th>
</tr>
</thead>
<tbody>
@foreach (var m in page.Movements)
{
<tr>
<td>@T.Date(m.EntryDate)</td>
<td class="code"><a href="@LedgerScreens.EntryUrl(m.EntryId)">@(m.EntryNumber ?? T["Ledger.Journal.NoNumber"])</a></td>
@if (ShowAccount)
{
<td class="code">@m.AccountCode</td>
}
<td>@m.DocumentNumber</td>
<td>@m.Description</td>
<td class="num">@LedgerScreens.AmountText(T, m.Debit)</td>
<td class="num">@LedgerScreens.AmountText(T, m.Credit)</td>
<td class="num">@LedgerScreens.Balance(T, m.Balance)</td>
</tr>
}
</tbody>
<tfoot>
<tr>
<td colspan="@(ShowAccount ? 5 : 4)" class="num"><b>@T["Ledger.Movements.Totals"]</b></td>
<td class="num"><b>@T.Money(page.TotalDebit)</b></td>
<td class="num"><b>@T.Money(page.TotalCredit)</b></td>
<td class="num"><b>@LedgerScreens.Balance(T, page.Closing)</b></td>
</tr>
</tfoot>
</table>
</div>
<div class="filters">
<span class="muted sm">@T.Format("Ledger.Pager", Offset + 1, Math.Min(Offset + PageSize, page.TotalCount), page.TotalCount)</span>
<span class="grow"></span>
<button type="button" class="btn sm" disabled="@(Offset == 0)" @onclick="() => OnPage.InvokeAsync(Math.Max(0, Offset - PageSize))"><KhIcon Name="chevron-left" /> @T["Ledger.Previous"]</button>
<button type="button" class="btn sm" disabled="@(Offset + PageSize >= page.TotalCount)" @onclick="() => OnPage.InvokeAsync(Offset + PageSize)">@T["Ledger.Next"] <KhIcon Name="chevron-right" /></button>
</div>
}
@code {
/// <summary>The page of movements, or <see langword="null"/> while loading.</summary>
[Parameter]
public LedgerPage? Page { get; set; }
/// <summary>From this day.</summary>
[Parameter]
public DateOnly? From { get; set; }
/// <summary>Up to this day.</summary>
[Parameter]
public DateOnly? To { get; set; }
/// <summary>The start of the period changed.</summary>
[Parameter]
public EventCallback<DateOnly?> FromChanged { get; set; }
/// <summary>The end of the period changed.</summary>
[Parameter]
public EventCallback<DateOnly?> ToChanged { get; set; }
/// <summary>Another page is asked, by its first movement.</summary>
[Parameter]
public EventCallback<int> OnPage { get; set; }
/// <summary>The first movement of the page.</summary>
[Parameter]
public int Offset { get; set; }
/// <summary>The size of a page.</summary>
[Parameter]
public int PageSize { get; set; } = 30;
/// <summary>Show the account of each movement (statements of a party).</summary>
[Parameter]
public bool ShowAccount { get; set; }
}
@@ -0,0 +1,246 @@
@page "/contabilita/partitari"
@attribute [Authorize]
@using Khaemhat.Application.Ledger
@using Khaemhat.Core.Accounting
@using Khaemhat.Web.Ledger
@inject ShellSession Session
@inject LedgerQueryService Queries
@inject IJSRuntime JS
@inject TimeProvider Clock
@* The sub-ledgers of customers and suppliers (partitario, estratto conto, SPEC §11.7, mockup 044): each party with
its balance and its open items; the party chosen with its movements in a period on every account, the running
balance and the way to each entry, its open items and the print of the statement. *@
<KhPageTitle Text="@T["Ledger.Parties.Title"]" Icon="users" />
<LedgerGuard Permission="@LedgerPermissions.EntryRead">
<div class="phead">
<div>
<div class="crumbs"><a href="@LedgerScreens.BasePath">@T["Shell.Menu.Ledger"]</a> / @T["Ledger.Parties.Title"]</div>
<h1>@T["Ledger.Parties.Heading"]</h1>
<div class="sub">@T["Ledger.Parties.Hint"]</div>
</div>
</div>
<KhTabs Items="Tabs" Active="@(_type == AccountType.Suppliers ? "suppliers" : "customers")" ActiveChanged="SetTypeAsync" Label="@T["Ledger.Parties.Title"]" />
<div class="kh-ledger-split">
<KhPanel Title="@T[_type == AccountType.Suppliers ? "Ledger.Parties.Suppliers" : "Ledger.Parties.Customers"]" Icon="users" Tight="true">
<div class="filters">
<input type="search" class="in" placeholder="@T["Ledger.Parties.Search"]" aria-label="@T["Ledger.Parties.Search"]" value="@_search"
@onchange="e => SearchAsync(e.Value?.ToString())" />
<span class="grow"></span>
<span class="muted sm">@T.Format("Ledger.Parties.Total", LedgerScreens.Balance(T, _balances.Sum(b => b.Balance)))</span>
</div>
@if (_balances.Count == 0)
{
<p class="kh-wempty">@T["Ledger.Parties.None"]</p>
}
else
{
<div class="kh-ledger-tree">
<table class="grid" aria-label="@T["Ledger.Parties.Title"]">
<thead>
<tr>
<th scope="col">@T["Ledger.Fields.Party"]</th>
<th scope="col" class="num">@T["Ledger.Side.Dare"]</th>
<th scope="col" class="num">@T["Ledger.Side.Avere"]</th>
<th scope="col" class="num">@T["Ledger.Movements.Balance"]</th>
<th scope="col" class="num">@T["Ledger.Parties.OpenItems"]</th>
</tr>
</thead>
<tbody>
@foreach (var b in _balances)
{
<tr class="@(b.PartyId == _selected?.PartyId ? "sel" : null)" style="cursor:pointer" @onclick="() => SelectAsync(b)">
<td>@b.Name</td>
<td class="num">@T.Money(b.Debit)</td>
<td class="num">@T.Money(b.Credit)</td>
<td class="num"><b>@LedgerScreens.Balance(T, b.Balance)</b></td>
<td class="num">@(b.OpenItems > 0 ? T.Number(b.OpenItems) : null)</td>
</tr>
}
</tbody>
</table>
</div>
}
</KhPanel>
<div class="kh-ledger-side">
@if (_selected is { } party)
{
<KhPanel Title="@T.Format("Ledger.Parties.Statement", party.Name)" Icon="file" Tight="true">
<Actions>
<button type="button" class="btn sm" disabled="@_busy" @onclick="PrintAsync"><KhIcon Name="printer" /> @T["Ledger.Print"]</button>
</Actions>
<ChildContent>
<MovementsTable Page="_page" From="_from" To="_to" FromChanged="SetFromAsync" ToChanged="SetToAsync" OnPage="PageAsync" Offset="_offset" PageSize="PageSize" />
</ChildContent>
</KhPanel>
<KhPanel Title="@T["Ledger.Parties.OpenItemsTitle"]" Icon="clock" Tight="true">
<Actions>
<KhCheck Label="@T["Ledger.Parties.ShowClosed"]" Name="closed" Value="_closed" ValueChanged="SetClosedAsync" />
</Actions>
<ChildContent>
@if (_items.Count == 0)
{
<p class="kh-wempty">@T["Ledger.Parties.NoOpenItems"]</p>
}
else
{
<table class="grid" aria-label="@T["Ledger.Parties.OpenItemsTitle"]">
<thead>
<tr>
<th scope="col">@T["Ledger.Fields.Document"]</th>
<th scope="col">@T["Ledger.Fields.DocumentDate"]</th>
<th scope="col">@T["Ledger.Parties.Installment"]</th>
<th scope="col">@T["Ledger.Parties.DueDate"]</th>
<th scope="col" class="num">@T["Ledger.Fields.Amount"]</th>
<th scope="col" class="num">@T["Ledger.Parties.Paid"]</th>
<th scope="col" class="num">@T["Ledger.Parties.Residual"]</th>
</tr>
</thead>
<tbody>
@foreach (var item in _items)
{
var overdue = !item.Closed && item.DueDate < Today;
<tr class="@(item.Closed ? "muted" : null)">
<td><a href="@LedgerScreens.EntryUrl(item.EntryId)">@item.DocumentNumber</a></td>
<td>@T.Date(item.DocumentDate)</td>
<td>@item.Installment</td>
<td class="@(overdue ? "err" : null)">@T.Date(item.DueDate)</td>
<td class="num">@T.Money(item.Amount)</td>
<td class="num">@LedgerScreens.AmountText(T, item.PaidAmount)</td>
<td class="num"><b>@T.Money(item.Amount - item.PaidAmount)</b></td>
</tr>
}
</tbody>
</table>
}
</ChildContent>
</KhPanel>
}
else
{
<p class="kh-wempty">@T["Ledger.Parties.Choose"]</p>
}
</div>
</div>
</LedgerGuard>
@code {
private const int PageSize = 30;
private AccountType _type = AccountType.Customers;
private IReadOnlyList<PartyBalance> _balances = [];
private PartyBalance? _selected;
private string? _search;
private LedgerPage? _page;
private IReadOnlyList<OpenItem> _items = [];
private int _offset;
private DateOnly? _from;
private DateOnly? _to;
private bool _closed;
private bool _busy;
private DateOnly Today => DateOnly.FromDateTime(Clock.GetLocalNow().DateTime);
private IReadOnlyList<KhTabItem> Tabs =>
[
new("customers", "users", T["Ledger.Parties.Customers"]),
new("suppliers", "truck", T["Ledger.Parties.Suppliers"]),
];
/// <inheritdoc />
protected override async Task OnInitializedAsync()
{
await Session.EnsureLoadedAsync();
_from = new DateOnly(Today.Year, 1, 1);
_to = Today;
await LoadAsync();
}
private async Task LoadAsync()
{
if (Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(LedgerPermissions.EntryRead)
&& Session.Licenses.IsModuleActive(Khaemhat.Application.Modules.ModuleCodes.Accounting))
{
_balances = await Queries.PartyBalancesAsync(actor, company, _type, _to ?? Today, _search);
}
}
private async Task SetTypeAsync(string tab)
{
_type = tab == "suppliers" ? AccountType.Suppliers : AccountType.Customers;
_selected = null;
await LoadAsync();
}
private async Task SearchAsync(string? text)
{
_search = text;
await LoadAsync();
}
private async Task SelectAsync(PartyBalance party)
{
_selected = party;
_offset = 0;
await LoadPartyAsync();
}
private async Task LoadPartyAsync()
{
_page = null;
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _selected is not { } party || _from is not { } from || _to is not { } to)
{
return;
}
_page = await Queries.MovementsAsync(actor, company, new LedgerFilter(null, party.PartyId, from, to, false, _offset, PageSize));
_items = await Queries.OpenItemsAsync(actor, company, party.PartyId, _type == AccountType.Suppliers ? OpenItemDirection.Payable : OpenItemDirection.Receivable, _closed);
}
private async Task SetFromAsync(DateOnly? date)
{
_from = date;
_offset = 0;
await LoadPartyAsync();
}
private async Task SetToAsync(DateOnly? date)
{
_to = date;
_offset = 0;
await LoadPartyAsync();
}
private async Task PageAsync(int offset)
{
_offset = offset;
await LoadPartyAsync();
}
private async Task SetClosedAsync(bool closed)
{
_closed = closed;
await LoadPartyAsync();
}
private async Task PrintAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _selected is not { } party || _from is not { } from || _to is not { } to)
{
return;
}
_busy = true;
try
{
await LedgerScreens.DownloadAsync(JS, await Queries.PrintMovementsAsync(actor, company, new LedgerFilter(null, party.PartyId, from, to)));
}
finally
{
_busy = false;
}
}
}
@@ -0,0 +1,227 @@
@page "/contabilita/bollo"
@attribute [Authorize]
@using Khaemhat.Application.Ledger
@using Khaemhat.Application.Security
@using Khaemhat.Web.Ledger
@inject ShellSession Session
@inject TaxService Taxes
@inject ToastService Toasts
@inject IJSRuntime JS
@inject TimeProvider Clock
@* The virtual stamp duty on e-invoices (SPEC §11.7, mockup 060): the invoices of a quarter with the duty, the amount,
the payment code and the due date (a small first quarter goes with the second, the first two with the third), the
F24 line, its data file and its payment. *@
<KhPageTitle Text="@T["Ledger.StampDuty.Title"]" Icon="file-check" />
<LedgerGuard Permission="@LedgerPermissions.SettlementRead">
<div class="phead">
<div>
<div class="crumbs"><a href="@LedgerScreens.BasePath">@T["Shell.Menu.Ledger"]</a> / @T["Ledger.StampDuty.Title"]</div>
<h1>@T["Ledger.StampDuty.Heading"]</h1>
<div class="sub">@T["Ledger.StampDuty.Hint"]</div>
</div>
<div class="grow"></div>
<div class="toolbar">
@if (Current is { } q)
{
<KhBadge Tone="KhTone.Info">@T.Format("Ledger.StampDuty.QuarterBadge", q.Quarter, q.Year)</KhBadge>
}
@if (CanConfirm)
{
<button type="button" class="btn primary" disabled="@(_busy || Current is null || Current.Amount == 0m || Current.Payment?.PaidOn is not null)" @onclick="RecordAsync"><KhIcon Name="check" /> @T["Ledger.StampDuty.Record"]</button>
}
<button type="button" class="btn" disabled="@(_busy || Current?.Payment is null)" @onclick="ExportAsync"><KhIcon Name="download" /> @T["Ledger.StampDuty.Export"]</button>
</div>
</div>
<div class="filters kh-ledger-filters">
<KhSelect TValue="int" Label="@T["Ledger.Settlement.Year"]" Name="year" Options="YearChoices" Value="_year" ValueChanged="SetYearAsync" />
<KhSelect TValue="int" Label="@T["Ledger.StampDuty.Quarter"]" Name="quarter" Options="QuarterChoices" Value="_quarter" ValueChanged="SetQuarterAsync" />
</div>
@if (Current is { } current)
{
<KhStrip Items="Stats(current)" Label="@T["Ledger.StampDuty.Title"]" />
}
<KhPanel Tight="true">
@if (_documents.Count == 0)
{
<p class="kh-wempty">@T["Ledger.StampDuty.None"]</p>
}
else
{
<table class="grid" aria-label="@T["Ledger.StampDuty.Title"]">
<thead>
<tr>
<th scope="col">@T["Ledger.Fields.Document"]</th>
<th scope="col">@T["Ledger.Fields.DocumentDate"]</th>
<th scope="col">@T["Ledger.Fields.Party"]</th>
<th scope="col" class="num">@T["Ledger.Fields.Taxable"]</th>
<th scope="col" class="num">@T["Ledger.StampDuty.Duty"]</th>
<th scope="col">@T["Ledger.StampDuty.Charge"]</th>
</tr>
</thead>
<tbody>
@foreach (var d in _documents)
{
<tr>
<td class="code"><a href="@Khaemhat.Web.Documents.SalesScreens.RecordUrl(d.Kind, d.DocumentId)">@d.DocumentNumber</a></td>
<td>@T.Date(d.DocumentDate)</td>
<td>@d.PartyName</td>
<td class="num">@T.Money(d.Taxable)</td>
<td class="num">@T.Money(d.StampDuty)</td>
<td><KhBadge Tone="@(d.Charged ? KhTone.Info : KhTone.Neutral)">@T[d.Charged ? "Ledger.StampDuty.Charged" : "Ledger.StampDuty.Borne"]</KhBadge></td>
</tr>
}
</tbody>
</table>
}
<div class="filters"><span class="muted sm">@T["Ledger.StampDuty.Footer"]</span></div>
</KhPanel>
<KhPanel Title="@T.Format("Ledger.StampDuty.Year", _year)" Icon="calendar" Tight="true">
<table class="grid" aria-label="@T.Format("Ledger.StampDuty.Year", _year)">
<thead>
<tr>
<th scope="col">@T["Ledger.StampDuty.Quarter"]</th>
<th scope="col" class="num">@T["Ledger.StampDuty.Invoices"]</th>
<th scope="col" class="num">@T["Ledger.Fields.Amount"]</th>
<th scope="col">@T["Ledger.Settlement.DueDate"]</th>
<th scope="col">@T["Ledger.Fields.Status"]</th>
</tr>
</thead>
<tbody>
@foreach (var q in _quarters)
{
<tr class="@(q.Quarter == _quarter ? "sel" : null)" style="cursor:pointer" @onclick="() => SetQuarterAsync(q.Quarter)">
<td>@T.Format("Ledger.StampDuty.QuarterBadge", q.Quarter, q.Year)</td>
<td class="num">@q.Documents</td>
<td class="num">@T.Money(q.Amount)</td>
<td>@T.Date(q.DueDate)</td>
<td>
@if (q.Payment is { PaidOn: { } paid })
{
<KhBadge Tone="KhTone.Ok">@T.Format("Ledger.StampDuty.PaidOn", T.Date(paid))</KhBadge>
}
else if (q.Payment is not null)
{
<KhBadge Tone="KhTone.Warning">@T["Ledger.StampDuty.InF24"]</KhBadge>
}
else if (q.Amount > 0m)
{
<KhBadge Tone="KhTone.Neutral">@T["Ledger.StampDuty.ToRecord"]</KhBadge>
}
</td>
</tr>
}
</tbody>
</table>
</KhPanel>
</LedgerGuard>
@code {
private int _year;
private int _quarter;
private IReadOnlyList<StampDutyQuarter> _quarters = [];
private IReadOnlyList<StampDutyDocument> _documents = [];
private bool _busy;
private DateOnly Today => DateOnly.FromDateTime(Clock.GetLocalNow().DateTime);
private bool CanConfirm => Session.Permissions.Allows(LedgerPermissions.SettlementConfirm);
private StampDutyQuarter? Current => _quarters.FirstOrDefault(q => q.Quarter == _quarter);
private IReadOnlyList<KhOption<int>> YearChoices => [.. Enumerable.Range(Today.Year - 3, 5).Select(y => new KhOption<int>(y, y.ToString(System.Globalization.CultureInfo.InvariantCulture)))];
private IReadOnlyList<KhOption<int>> QuarterChoices => [.. Enumerable.Range(1, 4).Select(q => new KhOption<int>(q, T.Format("Ledger.StampDuty.QuarterBadge", q, _year)))];
private IReadOnlyList<KhStat> Stats(StampDutyQuarter q)
{
var previous = q.Quarter > 1 ? _quarters.FirstOrDefault(p => p.Quarter == q.Quarter - 1) : null;
return
[
new(T["Ledger.StampDuty.Invoices"], T.Number(q.Documents)),
new(T["Ledger.Fields.Amount"], T.Money(q.Amount)),
new(T["Ledger.Settlement.PaymentCode"], q.Payment?.PaymentCode ?? "-"),
new(T["Ledger.Settlement.DueDate"], T.Date(q.DueDate)),
new(T["Ledger.StampDuty.Previous"], previous is null ? "-" : T.Money(previous.Amount) + (previous.Payment?.PaidOn is { } paid ? " · " + T.Format("Ledger.StampDuty.PaidOn", T.Date(paid)) : string.Empty),
previous?.Payment?.PaidOn is not null ? KhTone.Ok : KhTone.Neutral),
];
}
/// <inheritdoc />
protected override async Task OnInitializedAsync()
{
await Session.EnsureLoadedAsync();
_year = Today.Year;
_quarter = ((Today.Month - 1) / 3) + 1;
if (Session.Actor is { } && Session.Company is { } && Session.Permissions.Allows(LedgerPermissions.SettlementRead)
&& Session.Licenses.IsModuleActive(Khaemhat.Application.Modules.ModuleCodes.Accounting))
{
await LoadAsync();
}
}
private async Task LoadAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
_quarters = await Taxes.StampDutyAsync(actor, company, _year);
_documents = await Taxes.StampDutyDocumentsAsync(actor, company, _year, _quarter);
}
private async Task SetYearAsync(int year)
{
_year = year;
await LoadAsync();
}
private async Task SetQuarterAsync(int quarter)
{
_quarter = quarter;
await LoadAsync();
}
private async Task RecordAsync() => await RunAsync(async (actor, company) =>
{
var payment = await Taxes.StampDutyPaymentAsync(actor, company, _year, _quarter);
Toasts.Show(ToastKind.Success, payment is null ? T["Ledger.StampDuty.NoneDue"] : T.Format("Ledger.StampDuty.Recorded", T.Money(payment.Amount), T.Date(payment.DueDate)));
await LoadAsync();
});
private async Task ExportAsync() => await RunAsync(async (actor, company) =>
{
if (Current?.Payment is { } payment)
{
await LedgerScreens.DownloadAsync(JS, await Taxes.ExportFormAsync(actor, company, payment.DueDate));
}
});
private async Task RunAsync(Func<Actor, string, Task> 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["Ledger.NotDone"], LedgerScreens.Errors(T, ex));
}
finally
{
_busy = false;
}
}
}
@@ -0,0 +1,283 @@
@page "/contabilita/causali"
@attribute [Authorize]
@using Khaemhat.Application.Ledger
@using Khaemhat.Application.Security
@using Khaemhat.Core.Accounting
@using Khaemhat.Web.Ledger
@inject ShellSession Session
@inject LedgerService Ledger
@inject ToastService Toasts
@inject DialogService Dialogs
@* The journal templates (causali contabili, SPEC §11.7, mockup 043): each template is a model of entry, with the
lines in order, the role of each line (customer, revenue, VAT on sales...), its side and its usual account, the VAT
register and whether it opens items. The documents post through the template of their type. *@
<KhPageTitle Text="@T["Ledger.Templates.Title"]" Icon="layers" />
<LedgerGuard Permission="@LedgerPermissions.AccountRead">
<div class="phead">
<div>
<div class="crumbs"><a href="@LedgerScreens.BasePath">@T["Shell.Menu.Ledger"]</a> / @T["Ledger.Templates.Title"]</div>
<h1>@T["Ledger.Templates.Heading"]</h1>
<div class="sub">@T["Ledger.Templates.Hint"]</div>
</div>
<div class="grow"></div>
<div class="toolbar">
@if (CanWrite)
{
<button type="button" class="btn primary" disabled="@_busy" @onclick="() => Edit(null)"><KhIcon Name="plus" /> @T["Ledger.Templates.New"]</button>
}
</div>
</div>
<div class="kh-ledger-split">
<KhPanel Title="@T["Ledger.Templates.List"]" Icon="list" Tight="true">
<table class="grid" aria-label="@T["Ledger.Templates.List"]">
<thead>
<tr>
<th scope="col">@T["Ledger.Fields.Code"]</th>
<th scope="col">@T["Ledger.Fields.Description"]</th>
<th scope="col">@T["Ledger.Fields.VatRegister"]</th>
</tr>
</thead>
<tbody>
@foreach (var view in _templates)
{
var t = view.Template;
<tr class="@(t.Id == _id ? "sel" : null) @(t.Disabled ? "muted" : null)" style="cursor:pointer" @onclick="() => Edit(view)">
<td class="code">@t.Code</td>
<td>@t.Description</td>
<td class="code">@t.VatRegisterCode</td>
</tr>
}
</tbody>
</table>
</KhPanel>
<div class="kh-ledger-side">
@if (_editing)
{
<datalist id="kh-template-accounts">
@foreach (var a in _accounts.Where(a => a.Postable && !a.Disabled))
{
<option value="@(a.Code + " · " + a.Description)"></option>
}
</datalist>
<KhPanel Title="@T[_id is null ? "Ledger.Templates.New" : "Ledger.Templates.Edit"]" Icon="edit">
<div class="form plain">
<KhTextBox Label="@T["Ledger.Fields.Code"]" Name="code" @bind-Value="_code" Span="3" Required="true" Mono="true" MaxLength="10" Disabled="!CanWrite" />
<KhTextBox Label="@T["Ledger.Fields.Description"]" Name="description" @bind-Value="_description" Span="9" Required="true" MaxLength="100" Disabled="!CanWrite" />
<KhSelect TValue="JournalArea" Label="@T["Ledger.Fields.Area"]" Name="area" Options="LedgerScreens.Choices<JournalArea>(T)" @bind-Value="_area" Span="4" Disabled="!CanWrite" />
<KhSelect TValue="string" Label="@T["Ledger.Fields.VatRegister"]" Name="register" Options="RegisterChoices" @bind-Value="_register" Empty="@T["Ledger.Entry.NoRegister"]" Span="4" Disabled="!CanWrite" />
<KhCheck Label="@T["Ledger.Fields.OpensItems"]" Name="opens" @bind-Value="_opensItems" Span="4" Disabled="!CanWrite" />
<KhCheck Label="@T["Ledger.Fields.Reverses"]" Name="reverses" @bind-Value="_reverses" Span="4" Disabled="!CanWrite" />
<KhCheck Label="@T["Ledger.Fields.Disabled"]" Name="disabled" @bind-Value="_disabled" Span="4" Disabled="!CanWrite" />
</div>
</KhPanel>
<KhPanel Title="@T["Ledger.Templates.Lines"]" Icon="list" Tight="true">
<Actions>
@if (CanWrite)
{
<button type="button" class="btn sm" @onclick="() => _lines.Add(new Line())"><KhIcon Name="plus" /> @T["Ledger.Entry.AddLine"]</button>
}
</Actions>
<ChildContent>
<table class="grid" aria-label="@T["Ledger.Templates.Lines"]">
<thead>
<tr>
<th scope="col">@T["Ledger.Fields.Role"]</th>
<th scope="col">@T["Ledger.Fields.Side"]</th>
<th scope="col">@T["Ledger.Fields.Account"]</th>
<th scope="col">@T["Ledger.Fields.LineDescription"]</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
@foreach (var line in _lines)
{
<tr>
<td>
<select class="in" aria-label="@T["Ledger.Fields.Role"]" disabled="@(!CanWrite)" @onchange="e => SetRole(line, e.Value)">
@foreach (var role in Enum.GetValues<PostingRole>())
{
<option value="@role" selected="@(role == line.Role)">@T[LedgerScreens.EnumKey(role)]</option>
}
</select>
</td>
<td>
<select class="in" aria-label="@T["Ledger.Fields.Side"]" disabled="@(!CanWrite)" @onchange="e => SetSide(line, e.Value)">
@foreach (var side in Enum.GetValues<AccountSide>())
{
<option value="@side" selected="@(side == line.Side)">@T[LedgerScreens.EnumKey(side)]</option>
}
</select>
</td>
<td><input class="in" list="kh-template-accounts" aria-label="@T["Ledger.Fields.Account"]" disabled="@(!CanWrite)" value="@AccountText(line.AccountId)" @onchange="e => SetAccount(line, e.Value?.ToString())" style="min-width:220px" /></td>
<td><input class="in" maxlength="100" aria-label="@T["Ledger.Fields.LineDescription"]" disabled="@(!CanWrite)" value="@line.Description" @onchange="e => line.Description = e.Value?.ToString()" /></td>
<td>
@if (CanWrite)
{
<button type="button" class="btn sm" aria-label="@T["Ledger.Entry.RemoveLine"]" @onclick="() => _lines.Remove(line)"><KhIcon Name="trash" /></button>
}
</td>
</tr>
}
</tbody>
</table>
</ChildContent>
</KhPanel>
@if (CanWrite)
{
<div class="kh-formactions">
@if (_id is { } id)
{
<button type="button" class="btn" disabled="@_busy" @onclick="() => DeleteAsync(id)"><KhIcon Name="trash" /> @T["Common.Delete"]</button>
}
<button type="button" class="btn" @onclick="() => _editing = false">@T["Common.Cancel"]</button>
<button type="button" class="btn primary" disabled="@_busy" @onclick="SaveAsync"><KhIcon Name="check" /> @T["Common.Save"]</button>
</div>
}
}
else
{
<p class="kh-wempty">@T["Ledger.Templates.Choose"]</p>
}
</div>
</div>
</LedgerGuard>
@code {
private IReadOnlyList<TemplateView> _templates = [];
private IReadOnlyList<GlAccount> _accounts = [];
private IReadOnlyList<VatRegister> _registers = [];
private bool _busy;
private bool _editing;
private long? _id;
private string? _code;
private string? _description;
private JournalArea _area;
private string? _register;
private bool _opensItems;
private bool _reverses;
private bool _disabled;
private List<Line> _lines = [];
private bool CanWrite => Session.Permissions.Allows(LedgerPermissions.AccountWrite);
private IReadOnlyList<KhOption<string>> RegisterChoices => [.. _registers.Select(r => new KhOption<string>(r.Code, r.Code + " · " + r.Description))];
/// <inheritdoc />
protected override async Task OnInitializedAsync()
{
await Session.EnsureLoadedAsync();
if (Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(LedgerPermissions.AccountRead)
&& Session.Licenses.IsModuleActive(Khaemhat.Application.Modules.ModuleCodes.Accounting))
{
_templates = await Ledger.TemplatesAsync(actor, company);
_accounts = await Ledger.AccountsAsync(actor, company);
_registers = await Ledger.RegistersAsync(actor, company);
}
}
private string AccountText(long? id) => _accounts.FirstOrDefault(a => a.Id == id) is { } a ? a.Code + " · " + a.Description : string.Empty;
private void SetAccount(Line line, string? text)
{
var code = (text ?? string.Empty).Split('·')[0].Trim();
line.AccountId = code.Length == 0 ? null : _accounts.FirstOrDefault(a => string.Equals(a.Code, code, StringComparison.OrdinalIgnoreCase))?.Id;
}
private void Edit(TemplateView? view)
{
var t = view?.Template;
_id = t?.Id;
_code = t?.Code;
_description = t?.Description;
_area = t?.Area ?? JournalArea.General;
_register = t?.VatRegisterCode;
_opensItems = t?.OpensItems ?? false;
_reverses = t?.Reverses ?? false;
_disabled = t?.Disabled ?? false;
_lines = view is null
? [new Line { Side = AccountSide.Debit }, new Line { Side = AccountSide.Credit }]
: [.. view.Lines.Select(l => new Line { Role = l.Role, Side = l.Side, AccountId = l.AccountId, Description = l.Description })];
_editing = true;
}
private async Task SaveAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
_busy = true;
try
{
var saved = await Ledger.SaveTemplateAsync(actor, company, new TemplateInput(
_id, _code ?? string.Empty, _description ?? string.Empty, _area, [.. _lines.Select(l => new TemplateLineInput(l.Role, l.Side, l.AccountId, l.Description))])
{
VatRegisterCode = _register,
OpensItems = _opensItems,
Reverses = _reverses,
Disabled = _disabled,
});
_templates = await Ledger.TemplatesAsync(actor, company);
Edit(_templates.FirstOrDefault(t => t.Template.Id == saved.Template.Id));
Toasts.Show(ToastKind.Success, T["Ledger.Saved"], saved.Template.Code);
}
catch (ValidationFailedException ex)
{
Toasts.Show(ToastKind.Error, T["Ledger.NotSaved"], LedgerScreens.Errors(T, ex));
}
finally
{
_busy = false;
}
}
private async Task DeleteAsync(long id)
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
if (!await Dialogs.ConfirmAsync(new ConfirmRequest(T["Ledger.Templates.Delete"], T.Format("Ledger.Templates.DeleteText", _code ?? string.Empty), T["Common.Delete"], T["Common.Cancel"])))
{
return;
}
_busy = true;
try
{
await Ledger.DeleteTemplateAsync(actor, company, id);
_templates = await Ledger.TemplatesAsync(actor, company);
_editing = false;
_id = null;
}
catch (ValidationFailedException ex)
{
Toasts.Show(ToastKind.Error, T["Ledger.NotDone"], LedgerScreens.Errors(T, ex));
}
finally
{
_busy = false;
}
}
private sealed class Line
{
public PostingRole Role { get; set; }
public AccountSide Side { get; set; }
public long? AccountId { get; set; }
public string? Description { get; set; }
}
private static void SetRole(Line line, object? value) => line.Role = Enum.Parse<PostingRole>(value?.ToString() ?? nameof(PostingRole.Account));
private static void SetSide(Line line, object? value) => line.Side = Enum.Parse<AccountSide>(value?.ToString() ?? nameof(AccountSide.Debit));
}
@@ -0,0 +1,263 @@
@page "/contabilita/registri-iva"
@attribute [Authorize]
@using Khaemhat.Application.Ledger
@using Khaemhat.Application.Security
@using Khaemhat.Core.Accounting
@using Khaemhat.Web.Ledger
@inject ShellSession Session
@inject VatService Vat
@inject LedgerService Ledger
@inject ToastService Toasts
@inject DialogService Dialogs
@inject IJSRuntime JS
@inject TimeProvider Clock
@* The VAT registers (SPEC §11.7, mockup 045): the lines of a register in a period with protocol, document, party,
rate, taxable and VAT, the totals by rate; the provisional print of any period and the final print, which goes on
from the day after the last one and numbers the pages of the year after the last page printed. *@
<KhPageTitle Text="@T["Ledger.VatRegisters.Title"]" Icon="file-check" />
<LedgerGuard Permission="@LedgerPermissions.VatRegisterRead">
<div class="phead">
<div>
<div class="crumbs"><a href="@LedgerScreens.BasePath">@T["Shell.Menu.Ledger"]</a> / @T["Ledger.VatRegisters.Title"]</div>
<h1>@T["Ledger.VatRegisters.Heading"]</h1>
<div class="sub">@T["Ledger.VatRegisters.Hint"]</div>
</div>
<div class="grow"></div>
<div class="toolbar">
<button type="button" class="btn" disabled="@(_busy || _view is null)" @onclick="() => PrintAsync(final: false)"><KhIcon Name="printer" /> @T["Ledger.VatRegisters.PrintProvisional"]</button>
@if (Session.Permissions.Allows(LedgerPermissions.SettlementConfirm))
{
<button type="button" class="btn primary" disabled="@(_busy || _view is null)" @onclick="OpenFinal"><KhIcon Name="lock" /> @T["Ledger.VatRegisters.PrintFinal"]</button>
}
</div>
</div>
@if (_registers.Count > 0)
{
<KhTabs Items="Tabs" Active="@_registerId.ToString(System.Globalization.CultureInfo.InvariantCulture)" ActiveChanged="SetRegisterAsync" Label="@T["Ledger.VatRegisters.Title"]" />
}
@if (_view is { } view)
{
<KhStrip Items="Stats(view)" Label="@view.Register.Description" />
<KhPanel Tight="true">
<div class="filters kh-ledger-filters">
<KhDateBox Label="@T["Ledger.Fields.From"]" Name="from" Value="_from" ValueChanged="SetFromAsync" />
<KhDateBox Label="@T["Ledger.Fields.To"]" Name="to" Value="_to" ValueChanged="SetToAsync" />
<span class="grow"></span>
<span class="muted sm">@T.Format("Ledger.VatRegisters.Lines", T.Number(view.Rows.Count))</span>
</div>
@if (view.Rows.Count == 0)
{
<p class="kh-wempty">@T["Ledger.VatRegisters.None"]</p>
}
else
{
<div class="gridwrap kh-scrollx">
<table class="grid" aria-label="@view.Register.Description">
<thead>
<tr>
<th scope="col">@T["Ledger.Fields.Protocol"]</th>
<th scope="col">@T["Ledger.Fields.VatDate"]</th>
<th scope="col">@T["Ledger.Fields.Document"]</th>
<th scope="col">@T["Ledger.Fields.DocumentDate"]</th>
<th scope="col">@T["Ledger.Fields.Party"]</th>
<th scope="col">@T["Ledger.Fields.Rate"]</th>
<th scope="col" class="num">@T["Ledger.Fields.Taxable"]</th>
<th scope="col" class="num">@T["Ledger.Fields.Tax"]</th>
<th scope="col" class="num">@T["Ledger.Fields.NonDeductible"]</th>
<th scope="col">@T["Ledger.Fields.Exigibility"]</th>
</tr>
</thead>
<tbody>
@foreach (var r in view.Rows)
{
<tr>
<td class="code"><a href="@LedgerScreens.EntryUrl(r.EntryId)">@r.VatProtocol</a></td>
<td>@T.Date(r.VatDate)</td>
<td>@r.DocumentNumber</td>
<td>@(r.DocumentDate is { } d ? T.Date(d) : null)</td>
<td>@r.PartyName</td>
<td>@RateText(r.Rate, r.Nature)</td>
<td class="num">@T.Money(r.Taxable)</td>
<td class="num">@T.Money(r.Tax)</td>
<td class="num">@LedgerScreens.AmountText(T, r.NonDeductibleTax)</td>
<td>@(r.Exigibility == Khaemhat.Core.Tax.TaxExigibility.Immediate ? null : T["Ledger.Enums.TaxExigibility." + r.Exigibility])</td>
</tr>
}
</tbody>
</table>
</div>
}
</KhPanel>
<KhPanel Title="@T["Ledger.VatRegisters.Totals"]" Icon="euro" Tight="true">
<table class="grid" aria-label="@T["Ledger.VatRegisters.Totals"]">
<thead>
<tr>
<th scope="col">@T["Ledger.Fields.Rate"]</th>
<th scope="col" class="num">@T["Ledger.Fields.Taxable"]</th>
<th scope="col" class="num">@T["Ledger.Fields.Tax"]</th>
<th scope="col" class="num">@T["Ledger.Fields.NonDeductible"]</th>
</tr>
</thead>
<tbody>
@foreach (var t in view.Totals)
{
<tr>
<td>@RateText(t.Rate, t.Nature)</td>
<td class="num">@T.Money(t.Taxable)</td>
<td class="num">@T.Money(t.Tax)</td>
<td class="num">@LedgerScreens.AmountText(T, t.NonDeductibleTax)</td>
</tr>
}
</tbody>
<tfoot>
<tr>
<td><b>@T["Ledger.VatRegisters.RegisterTotal"]</b></td>
<td class="num"><b>@T.Money(view.Totals.Sum(t => t.Taxable))</b></td>
<td class="num"><b>@T.Money(view.Totals.Sum(t => t.Tax))</b></td>
<td class="num"><b>@LedgerScreens.AmountText(T, view.Totals.Sum(t => t.NonDeductibleTax))</b></td>
</tr>
</tfoot>
</table>
</KhPanel>
}
else if (_registers.Count == 0)
{
<p class="kh-wempty">@T["Ledger.VatRegisters.NoRegisters"]</p>
}
<KhDialog Open="_finalOpen" Title="@T["Ledger.VatRegisters.PrintFinal"]" Icon="lock" OnClose="() => _finalOpen = false">
<ChildContent>
<p>@T.Format("Ledger.VatRegisters.FinalText", _finalFrom is { } ff ? T.Date(ff) : "-", _view?.Register.PrintYear == _finalTo?.Year ? (_view?.Register.LastPage ?? 0) + 1 : 1)</p>
<div class="form plain">
<KhDateBox Label="@T["Ledger.VatRegisters.FinalUpTo"]" Name="finalto" @bind-Value="_finalTo" Span="6" Required="true" />
</div>
</ChildContent>
<Footer>
<button type="button" class="btn" @onclick="() => _finalOpen = false">@T["Common.Cancel"]</button>
<button type="button" class="btn primary" disabled="@(_busy || _finalTo is null)" @onclick="() => PrintAsync(final: true)"><KhIcon Name="printer" /> @T["Ledger.VatRegisters.PrintFinal"]</button>
</Footer>
</KhDialog>
</LedgerGuard>
@code {
private IReadOnlyList<VatRegister> _registers = [];
private long _registerId;
private VatRegisterView? _view;
private DateOnly? _from;
private DateOnly? _to;
private bool _busy;
private bool _finalOpen;
private DateOnly? _finalFrom;
private DateOnly? _finalTo;
private DateOnly Today => DateOnly.FromDateTime(Clock.GetLocalNow().DateTime);
private IReadOnlyList<KhTabItem> Tabs =>
[.. _registers.Where(r => !r.Disabled).Select(r => new KhTabItem(r.Id.ToString(System.Globalization.CultureInfo.InvariantCulture), "file", r.Code + " · " + r.Description))];
private IReadOnlyList<KhStat> Stats(VatRegisterView view) =>
[
new(T["Ledger.Fields.Kind"], T[LedgerScreens.EnumKey(view.Register.Kind)] + (view.Register.ReverseCharge ? " · RC" : string.Empty)),
new(T["Ledger.Fields.Taxable"], T.Money(view.Totals.Sum(t => t.Taxable))),
new(T["Ledger.Fields.Tax"], T.Money(view.Totals.Sum(t => t.Tax))),
new(T["Ledger.VatRegisters.LastPrint"], view.Register.LastPrintedDate is { } d ? T.Date(d) : T["Ledger.VatRegisters.NeverPrinted"],
view.Register.LastPrintedDate is null ? KhTone.Warning : KhTone.Ok),
new(T["Ledger.VatRegisters.LastPage"], view.Register.PrintYear is { } y ? y.ToString(System.Globalization.CultureInfo.InvariantCulture) + "/" + view.Register.LastPage.ToString(System.Globalization.CultureInfo.InvariantCulture) : "-"),
];
/// <inheritdoc />
protected override async Task OnInitializedAsync()
{
await Session.EnsureLoadedAsync();
_from = new DateOnly(Today.Year, Today.Month, 1).AddMonths(-1);
_to = new DateOnly(Today.Year, Today.Month, 1).AddDays(-1);
if (Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(LedgerPermissions.VatRegisterRead)
&& Session.Licenses.IsModuleActive(Khaemhat.Application.Modules.ModuleCodes.Accounting))
{
_registers = await Ledger.RegistersAsync(actor, company);
_registerId = _registers.FirstOrDefault(r => !r.Disabled)?.Id ?? 0;
await LoadAsync();
}
}
private async Task LoadAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _registerId == 0 || _from is not { } from || _to is not { } to)
{
return;
}
_view = await Vat.RegisterAsync(actor, company, _registerId, from, to);
}
private async Task SetRegisterAsync(string id)
{
_registerId = long.Parse(id, System.Globalization.CultureInfo.InvariantCulture);
await LoadAsync();
}
private async Task SetFromAsync(DateOnly? date)
{
_from = date;
await LoadAsync();
}
private async Task SetToAsync(DateOnly? date)
{
_to = date;
await LoadAsync();
}
private string RateText(decimal rate, string? nature) => nature ?? rate.ToString("0.##", T.Culture) + "%";
private void OpenFinal()
{
var register = _view?.Register;
_finalFrom = register?.LastPrintedDate is { } last ? last.AddDays(1) : new DateOnly(Today.Year, 1, 1);
_finalTo = _to;
_finalOpen = true;
}
private async Task PrintAsync(bool final)
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _from is not { } from || _to is not { } to)
{
return;
}
if (final && !await Dialogs.ConfirmAsync(new ConfirmRequest(T["Ledger.VatRegisters.PrintFinal"], T["Ledger.VatRegisters.FinalConfirm"], T["Ledger.VatRegisters.PrintFinal"], T["Common.Cancel"])))
{
return;
}
_busy = true;
try
{
var file = final
? await Vat.PrintRegisterAsync(actor, company, _registerId, _finalFrom ?? from, _finalTo ?? to, final: true)
: await Vat.PrintRegisterAsync(actor, company, _registerId, from, to, final: false);
await LedgerScreens.DownloadAsync(JS, file);
if (final)
{
_finalOpen = false;
_registers = await Ledger.RegistersAsync(actor, company);
Toasts.Show(ToastKind.Success, T["Ledger.VatRegisters.Printed"]);
await LoadAsync();
}
}
catch (ValidationFailedException ex)
{
Toasts.Show(ToastKind.Error, T["Ledger.NotDone"], LedgerScreens.Errors(T, ex));
}
finally
{
_busy = false;
}
}
}
@@ -0,0 +1,411 @@
@page "/contabilita/liquidazione-iva"
@attribute [Authorize]
@using Khaemhat.Application.Ledger
@using Khaemhat.Application.Security
@using Khaemhat.Application.Tables
@using Khaemhat.Core.Accounting
@using Khaemhat.Core.Tax
@using Khaemhat.Web.Ledger
@inject ShellSession Session
@inject VatService Vat
@inject TaxService Taxes
@inject CompanyProfileService Profiles
@inject ToastService Toasts
@inject DialogService Dialogs
@inject IJSRuntime JS
@inject TimeProvider Clock
@* The periodic VAT settlement (SPEC §11.7, mockup 046): the registers of the period, the VAT due and deductible, the
credit carried, the advance and the interest of quarterly payers; the confirmation settles the months (no more VAT
documents there), posts the entry and writes the F24 line; the LIPE of the quarter and the F24 data for the
intermediary or the home banking. In December, the advance. *@
<KhPageTitle Text="@T["Ledger.Settlement.Title"]" Icon="coins" />
<LedgerGuard Permission="@LedgerPermissions.SettlementRead">
<div class="phead">
<div>
<div class="crumbs"><a href="@LedgerScreens.BasePath">@T["Shell.Menu.Ledger"]</a> / @T["Ledger.Settlement.Title"]</div>
<h1>@T["Ledger.Settlement.Heading"]</h1>
<div class="sub">@T["Ledger.Settlement.Hint"]</div>
</div>
<div class="grow"></div>
<div class="toolbar">
<KhBadge Tone="KhTone.Info">@PeriodName(_year, _number)</KhBadge>
@if (_view is { } v)
{
<KhBadge Tone="@(v.Settlement.Status == VatSettlementStatus.Confirmed ? KhTone.Ok : KhTone.Warning)">@T[LedgerScreens.EnumKey(v.Settlement.Status)]</KhBadge>
}
</div>
</div>
<div class="toolbar kh-pad">
<button type="button" class="btn primary" disabled="@(_busy || Confirmed)" @onclick="ComputeAsync"><KhIcon Name="zap" /> @T["Ledger.Settlement.Compute"]</button>
@if (CanConfirm)
{
@if (Confirmed)
{
<button type="button" class="btn" disabled="@_busy" @onclick="ReopenAsync"><KhIcon Name="undo" /> @T["Ledger.Settlement.Reopen"]</button>
}
else
{
<button type="button" class="btn" disabled="@(_busy || _view is null)" @onclick="ConfirmAsync"><KhIcon Name="lock" /> @T["Ledger.Settlement.Confirm"]</button>
}
}
<button type="button" class="btn" disabled="@(_busy || !QuarterClosed)" @onclick="LipeAsync"><KhIcon Name="file" /> @T["Ledger.Settlement.Lipe"]</button>
<button type="button" class="btn" disabled="@(_busy || _view?.Settlement.DueDate is null || _view.Settlement.AmountDue == 0m)" @onclick="F24Async"><KhIcon Name="download" /> @T["Ledger.Settlement.F24Data"]</button>
</div>
<KhPanel>
<div class="form plain">
<KhField Label="@T["Ledger.Settlement.Periodicity"]" Span="3"><span class="in ro">@T["Ledger.Enums.VatPeriodicity." + _periodicity]</span></KhField>
<KhSelect TValue="int" Label="@T["Ledger.Settlement.Year"]" Name="year" Options="YearChoices" Value="_year" ValueChanged="SetYearAsync" Span="2" />
<KhSelect TValue="int" Label="@T["Ledger.Settlement.Period"]" Name="period" Options="PeriodChoices" Value="_number" ValueChanged="SetPeriodAsync" Span="3" />
<KhField Label="@T["Ledger.Settlement.PreviousCredit"]" Span="2"><span class="in ro">@T.Money(_view?.Settlement.PreviousCredit ?? 0m)</span></KhField>
<KhField Label="@T["Ledger.Settlement.ProRata"]" Span="2"><span class="in ro">@T.Format("Ledger.Settlement.ProRataValue", (_view?.Settlement.ProRataPercent ?? 100m).ToString("0.##", T.Culture))</span></KhField>
</div>
</KhPanel>
@if (_view is { } view)
{
var s = view.Settlement;
<KhPanel Title="@T["Ledger.Settlement.Registers"]" Icon="file-check" Tight="true">
<table class="grid" aria-label="@T["Ledger.Settlement.Registers"]">
<thead>
<tr>
<th scope="col">@T["Ledger.Fields.VatRegister"]</th>
<th scope="col">@T["Ledger.Fields.Kind"]</th>
<th scope="col" class="num">@T["Ledger.Settlement.Documents"]</th>
<th scope="col" class="num">@T["Ledger.Fields.Taxable"]</th>
<th scope="col" class="num">@T["Ledger.Fields.Tax"]</th>
<th scope="col" class="num">@T["Ledger.Fields.NonDeductible"]</th>
<th scope="col" class="num">@T["Ledger.Settlement.Deferred"]</th>
</tr>
</thead>
<tbody>
@foreach (var line in view.Lines)
{
var register = view.Registers.GetValueOrDefault(line.VatRegisterId);
<tr>
<td class="code">@register?.Code</td>
<td>@register?.Description</td>
<td class="num">@line.Documents</td>
<td class="num">@T.Money(line.Taxable)</td>
<td class="num">@T.Money(line.Tax)</td>
<td class="num">@LedgerScreens.AmountText(T, line.NonDeductibleTax)</td>
<td class="num">@LedgerScreens.AmountText(T, line.DeferredTax)</td>
</tr>
}
</tbody>
</table>
</KhPanel>
<div class="kh-ledger-two">
<KhPanel Title="@T["Ledger.Settlement.Calculation"]" Icon="chart">
<div class="totals">
<span>@T["Ledger.Settlement.SalesTax"]</span><span>@T.Money(s.SalesTax)</span>
<span>@T["Ledger.Settlement.PurchaseTax"]</span><span>@T.Money(s.PurchaseTax)</span>
<span>@T["Ledger.Settlement.NonDeductibleTax"]</span><span>@T.Money(s.NonDeductibleTax)</span>
<span>@T["Ledger.Settlement.DeferredTax"]</span><span>@T.Money(s.DeferredTax)</span>
<span>@T["Ledger.Settlement.PreviousCredit"]</span><span>@T.Money(s.PreviousCredit)</span>
<span>@T["Ledger.Settlement.PreviousDebit"]</span><span>@T.Money(s.PreviousDebit)</span>
<span>@T["Ledger.Settlement.AdvancePaid"]</span><span>@T.Money(s.AdvancePaid)</span>
<span>@T.Format("Ledger.Settlement.Interest", s.InterestPercent.ToString("0.##", T.Culture))</span><span>@T.Money(s.Interest)</span>
@if (s.AmountDue > 0m)
{
<span class="big">@T["Ledger.Settlement.AmountDue"]</span><span>@T.Money(s.AmountDue)</span>
}
else if (s.DebitCarried > 0m)
{
<span class="big">@T["Ledger.Settlement.DebitCarried"]</span><span>@T.Money(s.DebitCarried)</span>
}
else
{
<span class="big">@T["Ledger.Settlement.CreditCarried"]</span><span>@T.Money(s.CreditCarried)</span>
}
</div>
</KhPanel>
<KhPanel Title="@T["Ledger.Settlement.Payment"]" Icon="euro">
<dl class="kv">
<dt>@T["Ledger.Settlement.PaymentCode"]</dt><dd class="code">@s.PaymentCode</dd>
<dt>@T["Ledger.Settlement.Year"]</dt><dd>@s.Year</dd>
<dt>@T["Ledger.Fields.Amount"]</dt><dd>@T.Money(s.AmountDue)</dd>
<dt>@T["Ledger.Settlement.DueDate"]</dt><dd>@(s.DueDate is { } due ? T.Date(due) : "-")</dd>
<dt>@T["Ledger.Settlement.Entry"]</dt><dd>
@if (s.GlEntryId is { } entry)
{
<a href="@LedgerScreens.EntryUrl(entry)">@T["Ledger.Settlement.OpenEntry"]</a>
}
else
{
<span>-</span>
}
</dd>
<dt>@T["Ledger.Settlement.LipeQuarter"]</dt><dd>@T.Format("Ledger.Settlement.QuarterName", QuarterOf(s), s.Year)</dd>
</dl>
<div class="callout info kh-pad">
<KhIcon Name="info" />
<span>@T["Ledger.Settlement.Telematic"]</span>
</div>
</KhPanel>
</div>
}
else
{
<p class="kh-wempty">@T["Ledger.Settlement.NotComputed"]</p>
}
<KhPanel Title="@T.Format("Ledger.Settlement.YearList", _year)" Icon="list" Tight="true">
@if (_settlements.Count == 0)
{
<p class="kh-wempty">@T["Ledger.Settlement.NoneYet"]</p>
}
else
{
<table class="grid" aria-label="@T.Format("Ledger.Settlement.YearList", _year)">
<thead>
<tr>
<th scope="col">@T["Ledger.Settlement.Period"]</th>
<th scope="col" class="num">@T["Ledger.Settlement.SalesTax"]</th>
<th scope="col" class="num">@T["Ledger.Settlement.PurchaseTax"]</th>
<th scope="col" class="num">@T["Ledger.Settlement.AmountDue"]</th>
<th scope="col" class="num">@T["Ledger.Settlement.CreditCarried"]</th>
<th scope="col">@T["Ledger.Settlement.DueDate"]</th>
<th scope="col">@T["Ledger.Fields.Status"]</th>
</tr>
</thead>
<tbody>
@foreach (var item in _settlements)
{
<tr class="@(item.Number == _number ? "sel" : null)" style="cursor:pointer" @onclick="() => SetPeriodAsync(item.Number)">
<td>@PeriodName(item.Year, item.Number)</td>
<td class="num">@T.Money(item.SalesTax)</td>
<td class="num">@T.Money(item.PurchaseTax)</td>
<td class="num">@(item.AmountDue == 0m ? null : T.Money(item.AmountDue))</td>
<td class="num">@(item.CreditCarried == 0m ? null : T.Money(item.CreditCarried))</td>
<td>@(item.DueDate is { } due ? T.Date(due) : null)</td>
<td><KhBadge Tone="@(item.Status == VatSettlementStatus.Confirmed ? KhTone.Ok : KhTone.Warning)">@T[LedgerScreens.EnumKey(item.Status)]</KhBadge></td>
</tr>
}
</tbody>
</table>
}
</KhPanel>
@if (CanConfirm)
{
<KhPanel Title="@T.Format("Ledger.Advance.Title", _year)" Icon="calendar">
<p class="muted sm">@T["Ledger.Advance.Hint"]</p>
<div class="form plain">
<KhSelect TValue="VatAdvanceMethod" Label="@T["Ledger.Advance.Method"]" Name="method" Options="LedgerScreens.Choices<VatAdvanceMethod>(T)" Value="_method" ValueChanged="SetMethod" Span="4" />
<KhNumberBox Label="@T["Ledger.Advance.Basis"]" Name="basis" @bind-Value="_basis" Span="4" Hint="@T["Ledger.Advance.BasisHint"]" />
<KhField Label="@T["Ledger.Advance.Bases"]" Span="4">
<span class="in ro">@T.Format("Ledger.Advance.BasesValue", T.Money(_bases.Historical), T.Money(_bases.Actual))</span>
</KhField>
</div>
<div class="kh-formactions">
<button type="button" class="btn" disabled="@_busy" @onclick="LoadBasesAsync"><KhIcon Name="refresh" /> @T["Ledger.Advance.Refresh"]</button>
<button type="button" class="btn primary" disabled="@(_busy || (_basis ?? 0m) <= 0m)" @onclick="AdvanceAsync"><KhIcon Name="check" /> @T["Ledger.Advance.Record"]</button>
</div>
</KhPanel>
}
</LedgerGuard>
@code {
private VatPeriodicity _periodicity = VatPeriodicity.Monthly;
private int _year;
private int _number;
private VatSettlementView? _view;
private IReadOnlyList<VatSettlement> _settlements = [];
private bool _busy;
private VatAdvanceMethod _method = VatAdvanceMethod.Historical;
private decimal? _basis;
private (decimal Historical, decimal Actual) _bases;
private DateOnly Today => DateOnly.FromDateTime(Clock.GetLocalNow().DateTime);
private bool CanConfirm => Session.Permissions.Allows(LedgerPermissions.SettlementConfirm);
private bool Confirmed => _view?.Settlement.Status == VatSettlementStatus.Confirmed;
private int LastNumber => _periodicity == VatPeriodicity.Monthly ? 12 : 4;
// The LIPE of a quarter needs its settlements confirmed: the last month of the quarter (or the quarter itself).
private bool QuarterClosed => _view?.Settlement is { Status: VatSettlementStatus.Confirmed } s
&& (s.Periodicity == VatPeriodicity.Quarterly || s.Number % 3 == 0);
private IReadOnlyList<KhOption<int>> YearChoices => [.. Enumerable.Range(Today.Year - 3, 5).Select(y => new KhOption<int>(y, y.ToString(System.Globalization.CultureInfo.InvariantCulture)))];
private IReadOnlyList<KhOption<int>> PeriodChoices => [.. Enumerable.Range(1, LastNumber).Select(n => new KhOption<int>(n, PeriodName(_year, n)))];
/// <inheritdoc />
protected override async Task OnInitializedAsync()
{
await Session.EnsureLoadedAsync();
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || !Session.Permissions.Allows(LedgerPermissions.SettlementRead)
|| !Session.Licenses.IsModuleActive(Khaemhat.Application.Modules.ModuleCodes.Accounting))
{
return;
}
try
{
_periodicity = (await Profiles.GetAsync(actor, company)).VatPeriodicity;
}
catch (AccessDeniedException)
{
_periodicity = VatPeriodicity.Monthly;
}
var previous = Today.AddMonths(-1);
_year = previous.Year;
_number = _periodicity == VatPeriodicity.Monthly ? previous.Month : ((previous.Month - 1) / 3) + 1;
await LoadAsync();
await LoadBasesAsync();
}
private async Task LoadAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
_settlements = await Vat.SettlementsAsync(actor, company, _year);
var current = _settlements.FirstOrDefault(s => s.Number == _number && s.Periodicity == _periodicity);
_view = current is null ? null : await Vat.SettlementAsync(actor, company, current.Id);
}
private async Task LoadBasesAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
_bases = await Vat.AdvanceBasisAsync(actor, company, _year);
SetMethod(_method);
}
private void SetMethod(VatAdvanceMethod method)
{
_method = method;
_basis = method switch
{
VatAdvanceMethod.Historical => _bases.Historical,
VatAdvanceMethod.Actual => _bases.Actual,
_ => _basis,
};
}
private async Task SetYearAsync(int year)
{
_year = year;
await LoadAsync();
await LoadBasesAsync();
}
private async Task SetPeriodAsync(int number)
{
_number = number;
await LoadAsync();
}
private string PeriodName(int year, int number)
{
if (year == 0)
{
return string.Empty;
}
if (_periodicity == VatPeriodicity.Quarterly)
{
return T.Format("Ledger.Settlement.QuarterName", number, year);
}
var text = new DateOnly(year, number, 1).ToString("MMMM yyyy", T.Culture);
return char.ToUpper(text[0], T.Culture) + text[1..];
}
private static int QuarterOf(VatSettlement s) => s.Periodicity == VatPeriodicity.Quarterly ? s.Number : ((s.Number - 1) / 3) + 1;
private async Task ComputeAsync() => await RunAsync(async (actor, company) =>
{
_view = await Vat.ComputeAsync(actor, company, _year, _number);
_settlements = await Vat.SettlementsAsync(actor, company, _year);
});
private async Task ConfirmAsync()
{
if (_view is not { } view || !await Dialogs.ConfirmAsync(new ConfirmRequest(
T["Ledger.Settlement.Confirm"], T.Format("Ledger.Settlement.ConfirmText", PeriodName(_year, _number), T.Money(view.Settlement.AmountDue)), T["Ledger.Settlement.Confirm"], T["Common.Cancel"])))
{
return;
}
await RunAsync(async (actor, company) =>
{
_view = await Vat.ConfirmAsync(actor, company, view.Settlement.Id);
_settlements = await Vat.SettlementsAsync(actor, company, _year);
Toasts.Show(ToastKind.Success, T["Ledger.Settlement.Confirmed"], PeriodName(_year, _number));
});
}
private async Task ReopenAsync()
{
if (_view is not { } view || !await Dialogs.ConfirmAsync(new ConfirmRequest(
T["Ledger.Settlement.Reopen"], T["Ledger.Settlement.ReopenText"], T["Ledger.Settlement.Reopen"], T["Common.Cancel"])))
{
return;
}
await RunAsync(async (actor, company) =>
{
_view = await Vat.ReopenAsync(actor, company, view.Settlement.Id);
_settlements = await Vat.SettlementsAsync(actor, company, _year);
});
}
private async Task LipeAsync() => await RunAsync(async (actor, company) =>
{
if (_view?.Settlement is { } s)
{
await LedgerScreens.DownloadAsync(JS, await Vat.PeriodicReturnAsync(actor, company, s.Year, QuarterOf(s)));
}
});
private async Task F24Async() => await RunAsync(async (actor, company) =>
{
if (_view?.Settlement.DueDate is { } due)
{
await LedgerScreens.DownloadAsync(JS, await Taxes.ExportFormAsync(actor, company, due));
}
});
private async Task AdvanceAsync() => await RunAsync(async (actor, company) =>
{
var payment = await Vat.AdvanceAsync(actor, company, _year, _method, _basis ?? 0m);
Toasts.Show(ToastKind.Success, payment is null ? T["Ledger.Advance.NoneDue"] : T.Format("Ledger.Advance.Recorded", T.Money(payment.Amount), T.Date(payment.DueDate)));
});
private async Task RunAsync(Func<Actor, string, Task> 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["Ledger.NotDone"], LedgerScreens.Errors(T, ex));
}
finally
{
_busy = false;
}
}
}
@@ -0,0 +1,420 @@
@page "/contabilita/ritenute"
@attribute [Authorize]
@using Khaemhat.Application.Ledger
@using Khaemhat.Application.Security
@using Khaemhat.Core.Accounting
@using Khaemhat.Web.Ledger
@inject ShellSession Session
@inject TaxService Taxes
@inject ToastService Toasts
@inject DialogService Dialogs
@inject IJSRuntime JS
@inject TimeProvider Clock
@* Withholdings and the F24 (SPEC §11.7, mockup 047): the withholdings operated on the fees received, which become due
when the invoice is paid and join the F24 of the 16th of the next month, and those suffered on the fees issued, a
credit for the tax return; the CU data of a year; the F24 of a due date with every tax in it (VAT, withholdings,
stamp duty), its data file and the record of its payment. *@
<KhPageTitle Text="@T["Ledger.Withholdings.Title"]" Icon="shield-check" />
<LedgerGuard Permission="@LedgerPermissions.SettlementRead">
<div class="phead">
<div>
<div class="crumbs"><a href="@LedgerScreens.BasePath">@T["Shell.Menu.Ledger"]</a> / @T["Ledger.Withholdings.Title"]</div>
<h1>@T["Ledger.Withholdings.Heading"]</h1>
<div class="sub">@T["Ledger.Withholdings.Hint"]</div>
</div>
<div class="grow"></div>
<div class="toolbar">
<button type="button" class="btn" disabled="@_busy" @onclick="CertificationsAsync"><KhIcon Name="file" /> @T["Ledger.Withholdings.Cu"]</button>
</div>
</div>
<KhTabs Items="Tabs" Active="@_tab" ActiveChanged="SetTabAsync" Label="@T["Ledger.Withholdings.Title"]" />
<KhPanel Tight="true">
<div class="filters kh-ledger-filters">
<KhSelect TValue="int" Label="@T["Ledger.Settlement.Year"]" Name="year" Options="YearChoices" Value="_year" ValueChanged="SetYearAsync" />
<span class="grow"></span>
<span class="muted sm">@T.Format("Ledger.Withholdings.Total", T.Money(_rows.Sum(r => r.Withholding.Amount)))</span>
</div>
@if (_rows.Count == 0)
{
<p class="kh-wempty">@T["Ledger.Withholdings.None"]</p>
}
else
{
<div class="gridwrap kh-scrollx">
<table class="grid" aria-label="@T["Ledger.Withholdings.Title"]">
<thead>
<tr>
<th scope="col">@T["Ledger.Fields.Document"]</th>
<th scope="col">@T["Ledger.Fields.DocumentDate"]</th>
<th scope="col">@T["Ledger.Fields.Party"]</th>
<th scope="col">@T["Ledger.Withholdings.Type"]</th>
<th scope="col" class="num">@T["Ledger.Fields.Taxable"]</th>
<th scope="col">@T["Ledger.Withholdings.Fund"]</th>
<th scope="col" class="num">@T["Ledger.Withholdings.FundAmount"]</th>
<th scope="col">@T["Ledger.Withholdings.Rate"]</th>
<th scope="col" class="num">@T["Ledger.Fields.Amount"]</th>
<th scope="col">@T["Ledger.Withholdings.PaidOn"]</th>
<th scope="col">@T["Ledger.Fields.Status"]</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
@foreach (var row in _rows)
{
var w = row.Withholding;
<tr>
<td class="code">
@if (w.GlEntryId is { } entry)
{
<a href="@LedgerScreens.EntryUrl(entry)">@w.DocumentNumber</a>
}
else
{
@w.DocumentNumber
}
</td>
<td>@T.Date(w.DocumentDate)</td>
<td>@row.PartyName</td>
<td>@w.WithholdingType @(w.Reason is { } reason ? "· " + reason : null)</td>
<td class="num">@T.Money(w.Taxable)</td>
<td>@w.SocialSecurityFund</td>
<td class="num">@LedgerScreens.AmountText(T, w.SocialSecurityAmount)</td>
<td>@(w.Rate.ToString("0.##", T.Culture))% @(w.BasePercent != 100m ? T.Format("Ledger.Withholdings.On", w.BasePercent.ToString("0.##", T.Culture)) : null)</td>
<td class="num"><b>@T.Money(w.Amount)</b></td>
<td>@(w.InvoicePaidOn is { } paid ? T.Date(paid) : null)</td>
<td><KhBadge Tone="ToneOf(w.Status)">@T[LedgerScreens.EnumKey(w.Status)]</KhBadge></td>
<td class="num">
@if (CanConfirm)
{
@if (w.InvoicePaidOn is null)
{
<button type="button" class="btn sm" disabled="@_busy" @onclick="() => OpenPaid(row)"><KhIcon Name="check" /> @T["Ledger.Withholdings.InvoicePaid"]</button>
}
else if (w.Status != WithholdingStatus.Paid)
{
<button type="button" class="btn sm" disabled="@_busy" @onclick="() => UndoAsync(row)"><KhIcon Name="undo" /></button>
}
}
</td>
</tr>
}
</tbody>
</table>
</div>
}
<div class="filters"><span class="muted sm">@T["Ledger.Withholdings.Footer"]</span></div>
</KhPanel>
<div class="kh-ledger-two">
<KhPanel Title="@T["Ledger.F24.Title"]" Icon="euro" Tight="true">
<Actions>
<select class="in" style="width:auto" aria-label="@T["Ledger.F24.DueDate"]" @onchange="e => SetDueAsync(e.Value?.ToString())">
@foreach (var date in _dueDates)
{
<option value="@date.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture)" selected="@(date == _due)">@T.Date(date)</option>
}
</select>
<button type="button" class="btn sm" disabled="@(_busy || _due is null)" @onclick="ExportAsync"><KhIcon Name="download" /> @T["Ledger.Settlement.F24Data"]</button>
@if (CanConfirm)
{
@if (_formPaid)
{
<button type="button" class="btn sm" disabled="@_busy" @onclick="UnpayAsync"><KhIcon Name="undo" /> @T["Ledger.F24.Unpay"]</button>
}
else
{
<button type="button" class="btn sm primary" disabled="@(_busy || _form is null || _form.Lines.Count == 0)" @onclick="OpenPay"><KhIcon Name="check" /> @T["Ledger.F24.Pay"]</button>
}
}
</Actions>
<ChildContent>
@if (_form is not { Lines.Count: > 0 } form)
{
<p class="kh-wempty">@T[_formPaid ? "Ledger.F24.AllPaid" : "Ledger.F24.None"]</p>
}
else
{
<table class="grid" aria-label="@T["Ledger.F24.Lines"]">
<thead>
<tr>
<th scope="col">@T["Ledger.Settlement.PaymentCode"]</th>
<th scope="col">@T["Ledger.Fields.Description"]</th>
<th scope="col">@T["Ledger.Settlement.Period"]</th>
<th scope="col" class="num">@T["Ledger.Side.Dare"]</th>
<th scope="col" class="num">@T["Ledger.F24.Credit"]</th>
</tr>
</thead>
<tbody>
@foreach (var line in form.Lines)
{
<tr>
<td class="code">@line.Code</td>
<td>@line.Description</td>
<td>@(line.Period is { } p ? p + "/" + line.Year : line.Year.ToString(System.Globalization.CultureInfo.InvariantCulture))</td>
<td class="num">@LedgerScreens.AmountText(T, line.Debit)</td>
<td class="num">@LedgerScreens.AmountText(T, line.Credit)</td>
</tr>
}
</tbody>
<tfoot>
<tr>
<td colspan="3"><b>@T.Format("Ledger.F24.Total", _due is { } td ? T.Date(td) : string.Empty)</b></td>
<td class="num" colspan="2"><b>@T.Money(form.Balance)</b></td>
</tr>
</tfoot>
</table>
}
</ChildContent>
</KhPanel>
<div class="callout info">
<KhIcon Name="info" />
<span>@T["Ledger.Withholdings.Note"]</span>
</div>
</div>
<KhDialog Open="_paidOpen" Title="@T["Ledger.Withholdings.InvoicePaid"]" Icon="check" OnClose="() => _paidOpen = false">
<ChildContent>
<p>@T.Format("Ledger.Withholdings.InvoicePaidText", _paidRow?.Withholding.DocumentNumber ?? string.Empty, _paidRow?.PartyName ?? string.Empty)</p>
<div class="form plain">
<KhDateBox Label="@T["Ledger.Withholdings.PaidOn"]" Name="paidon" @bind-Value="_paidOn" Span="6" Required="true" />
</div>
</ChildContent>
<Footer>
<button type="button" class="btn" @onclick="() => _paidOpen = false">@T["Common.Cancel"]</button>
<button type="button" class="btn primary" disabled="@(_busy || _paidOn is null)" @onclick="ConfirmPaidAsync"><KhIcon Name="check" /> @T["Common.Save"]</button>
</Footer>
</KhDialog>
<KhDialog Open="_payOpen" Title="@T["Ledger.F24.Pay"]" Icon="euro" OnClose="() => _payOpen = false">
<ChildContent>
<p>@T.Format("Ledger.F24.PayText", _due is { } pd ? T.Date(pd) : string.Empty, T.Money(_form?.Balance ?? 0m))</p>
<div class="form plain">
<KhDateBox Label="@T["Ledger.F24.PaidOn"]" Name="f24paid" @bind-Value="_payOn" Span="6" Required="true" />
</div>
</ChildContent>
<Footer>
<button type="button" class="btn" @onclick="() => _payOpen = false">@T["Common.Cancel"]</button>
<button type="button" class="btn primary" disabled="@(_busy || _payOn is null)" @onclick="PayAsync"><KhIcon Name="check" /> @T["Ledger.F24.Pay"]</button>
</Footer>
</KhDialog>
</LedgerGuard>
@code {
private string _tab = "operated";
private int _year;
private IReadOnlyList<WithholdingRow> _rows = [];
private IReadOnlyList<DateOnly> _dueDates = [];
private DateOnly? _due;
private Khaemhat.Fiscal.Abstractions.TaxPaymentForm? _form;
private bool _formPaid;
private bool _busy;
private bool _paidOpen;
private WithholdingRow? _paidRow;
private DateOnly? _paidOn;
private bool _payOpen;
private DateOnly? _payOn;
private DateOnly Today => DateOnly.FromDateTime(Clock.GetLocalNow().DateTime);
private bool CanConfirm => Session.Permissions.Allows(LedgerPermissions.SettlementConfirm);
private IReadOnlyList<KhTabItem> Tabs =>
[
new("operated", "users", T["Ledger.Withholdings.Operated"]),
new("suffered", "user", T["Ledger.Withholdings.Suffered"]),
new("all", "list", T["Ledger.Withholdings.All"]),
];
private IReadOnlyList<KhOption<int>> YearChoices => [.. Enumerable.Range(Today.Year - 3, 5).Select(y => new KhOption<int>(y, y.ToString(System.Globalization.CultureInfo.InvariantCulture)))];
/// <inheritdoc />
protected override async Task OnInitializedAsync()
{
await Session.EnsureLoadedAsync();
_year = Today.Year;
if (Session.Actor is { } && Session.Company is { } && Session.Permissions.Allows(LedgerPermissions.SettlementRead)
&& Session.Licenses.IsModuleActive(Khaemhat.Application.Modules.ModuleCodes.Accounting))
{
await LoadAsync();
await LoadDueDatesAsync(null);
}
}
private async Task LoadAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
WithholdingDirection? direction = _tab switch
{
"operated" => WithholdingDirection.Operated,
"suffered" => WithholdingDirection.Suffered,
_ => null,
};
_rows = await Taxes.WithholdingsAsync(actor, company, _year, direction);
}
// The due dates of the year with something on them; the first one still unpaid from today on is chosen.
private async Task LoadDueDatesAsync(DateOnly? keep)
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
var payments = (await Taxes.PaymentsAsync(actor, company, _year)).Concat(await Taxes.PaymentsAsync(actor, company, _year + 1)).ToList();
_dueDates = [.. payments.Select(p => p.DueDate).Distinct().Order()];
DateOnly? firstUnpaid = payments.Where(p => p.PaidOn is null).OrderBy(p => p.DueDate).Select(p => (DateOnly?)p.DueDate).FirstOrDefault();
DateOnly? lastDue = _dueDates.Count > 0 ? _dueDates[^1] : null;
_due = keep is { } k && _dueDates.Contains(k) ? k : firstUnpaid ?? lastDue;
_formPaid = _due is { } due && payments.Where(p => p.DueDate == due).All(p => p.PaidOn is not null);
await LoadFormAsync();
}
private async Task LoadFormAsync()
{
_form = null;
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _due is not { } due)
{
return;
}
_form = await Taxes.FormAsync(actor, company, due);
}
private async Task SetTabAsync(string tab)
{
_tab = tab;
await LoadAsync();
}
private async Task SetYearAsync(int year)
{
_year = year;
await LoadAsync();
await LoadDueDatesAsync(null);
}
private async Task SetDueAsync(string? text)
{
if (DateOnly.TryParseExact(text, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out var date))
{
await LoadDueDatesAsync(date);
}
}
private void OpenPaid(WithholdingRow row)
{
_paidRow = row;
_paidOn = Today;
_paidOpen = true;
}
private async Task ConfirmPaidAsync() => await RunAsync(async (actor, company) =>
{
if (_paidRow is { } row && _paidOn is { } date)
{
await Taxes.InvoicePaidAsync(actor, company, row.Withholding.Id, date);
_paidOpen = false;
await LoadAsync();
await LoadDueDatesAsync(_due);
}
});
private async Task UndoAsync(WithholdingRow row)
{
if (!await Dialogs.ConfirmAsync(new ConfirmRequest(T["Ledger.Withholdings.Undo"], T.Format("Ledger.Withholdings.UndoText", row.Withholding.DocumentNumber ?? string.Empty), T["Ledger.Withholdings.Undo"], T["Common.Cancel"])))
{
return;
}
await RunAsync(async (actor, company) =>
{
await Taxes.UndoInvoicePaidAsync(actor, company, row.Withholding.Id);
await LoadAsync();
await LoadDueDatesAsync(_due);
});
}
private async Task CertificationsAsync() => await RunAsync(async (actor, company) => await LedgerScreens.DownloadAsync(JS, await Taxes.CertificationsAsync(actor, company, _year)));
private async Task ExportAsync() => await RunAsync(async (actor, company) =>
{
if (_due is { } due)
{
await LedgerScreens.DownloadAsync(JS, await Taxes.ExportFormAsync(actor, company, due));
}
});
private void OpenPay()
{
_payOn = _due is { } due && due <= Today ? due : Today;
_payOpen = true;
}
private async Task PayAsync() => await RunAsync(async (actor, company) =>
{
if (_due is { } due && _payOn is { } paidOn)
{
var entry = await Taxes.PayAsync(actor, company, due, paidOn);
_payOpen = false;
Toasts.Show(ToastKind.Success, T["Ledger.F24.Paid"], entry?.EntryNumber);
await LoadAsync();
await LoadDueDatesAsync(due);
}
});
private async Task UnpayAsync()
{
if (!await Dialogs.ConfirmAsync(new ConfirmRequest(T["Ledger.F24.Unpay"], T["Ledger.F24.UnpayText"], T["Ledger.F24.Unpay"], T["Common.Cancel"])))
{
return;
}
await RunAsync(async (actor, company) =>
{
if (_due is { } due)
{
await Taxes.UnpayAsync(actor, company, due);
await LoadAsync();
await LoadDueDatesAsync(due);
}
});
}
private static KhTone ToneOf(WithholdingStatus status) => status switch
{
WithholdingStatus.Due => KhTone.Warning,
WithholdingStatus.Paid => KhTone.Ok,
WithholdingStatus.Suffered => KhTone.Neutral,
_ => KhTone.Info,
};
private async Task RunAsync(Func<Actor, string, Task> 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["Ledger.NotDone"], LedgerScreens.Errors(T, ex));
}
finally
{
_busy = false;
}
}
}
@@ -154,6 +154,16 @@ internal static class KhaemhatServices
services.AddSingleton<IScheduledJob, Khaemhat.Application.Inventory.InventoryRebuildJob>();
services.AddSingleton<Khaemhat.Application.Items.PriceListService>();
// The ledger (ADR 0036, ADR 0037): the documents post through LedgerPoster inside the transaction of the engine.
services.AddSingleton<Khaemhat.Application.Ledger.LedgerPoster>();
services.AddSingleton<Khaemhat.Application.Ledger.JournalEntryService>();
services.AddSingleton<Khaemhat.Application.Ledger.LedgerService>();
services.AddSingleton<Khaemhat.Application.Ledger.VatService>();
services.AddSingleton<Khaemhat.Application.Ledger.TaxService>();
services.AddSingleton<Khaemhat.Application.Ledger.LedgerQueryService>();
services.AddSingleton<Khaemhat.Application.Ledger.RecurringEntryService>();
services.AddSingleton<IScheduledJob, Khaemhat.Application.Ledger.RecurringEntriesJob>();
// The document engine (ADR 0032): one engine, the copies, a typed service per family.
services.AddSingleton<Khaemhat.Application.Documents.DocumentEngine>();
services.AddSingleton<Khaemhat.Application.Documents.DocumentCopyService>();
@@ -177,6 +187,7 @@ internal static class KhaemhatServices
services.AddSingleton<ISeeder, BaseTablesSeeder>();
services.AddSingleton<ISeeder, DemoPartiesSeeder>();
services.AddSingleton<ISeeder, DemoItemsSeeder>();
services.AddSingleton<ISeeder, LedgerSeeder>();
services.AddSingleton<SeedRunner>();
// Companies and start.
@@ -186,6 +197,8 @@ internal static class KhaemhatServices
services.AddSingleton<ICompanySeeder>(sp => sp.GetRequiredService<DemoSalesSeeder>());
services.AddSingleton<DemoPurchasesSeeder>();
services.AddSingleton<ICompanySeeder>(sp => sp.GetRequiredService<DemoPurchasesSeeder>());
services.AddSingleton<DemoLedgerSeeder>();
services.AddSingleton<ICompanySeeder>(sp => sp.GetRequiredService<DemoLedgerSeeder>());
services.AddSingleton<CompanyService>();
services.AddSingleton<CompanyContextResolver>();
services.AddScoped<ICompanyContext, WebCompanyContext>();
+1
View File
@@ -133,6 +133,7 @@ public static class SeedCommand
// The demo documents go through the document engine, after the masters they use.
await services.GetRequiredService<DemoSalesSeeder>().SeedAsync(code, new CompanySeedContext(IsNew: false, Base: false, Demo: true)).ConfigureAwait(false);
await services.GetRequiredService<DemoPurchasesSeeder>().SeedAsync(code, new CompanySeedContext(IsNew: false, Base: false, Demo: true)).ConfigureAwait(false);
await services.GetRequiredService<DemoLedgerSeeder>().SeedAsync(code, new CompanySeedContext(IsNew: false, Base: false, Demo: true)).ConfigureAwait(false);
}
}
+106
View File
@@ -0,0 +1,106 @@
using Khaemhat.Application.Ledger;
using Khaemhat.Application.Localization;
using Khaemhat.Application.Security;
using Khaemhat.Core.Accounting;
using Khaemhat.Web.Tables;
using Khaemhat.Web.Ui;
using Microsoft.JSInterop;
namespace Khaemhat.Web.Ledger;
/// <summary>What the screens of the ledger share (SPEC §11.7, mockups 040-047 and 060): addresses, texts of enums and errors, downloads.</summary>
public static class LedgerScreens
{
/// <summary>The address of the area.</summary>
public const string BasePath = "/contabilita";
/// <summary>The address of an entry.</summary>
/// <param name="id">The entry.</param>
/// <returns>The address.</returns>
public static string EntryUrl(long id) => BasePath + "/prima-nota/" + id.ToString(System.Globalization.CultureInfo.InvariantCulture);
/// <summary>The key of the text of an enum value.</summary>
/// <param name="value">The value.</param>
/// <returns>The key.</returns>
public static string EnumKey(Enum value)
{
ArgumentNullException.ThrowIfNull(value);
return "Ledger.Enums." + value.GetType().Name + "." + value;
}
/// <summary>The choices of an enum.</summary>
/// <typeparam name="TEnum">The enum.</typeparam>
/// <param name="texts">The texts.</param>
/// <returns>The choices in declaration order.</returns>
public static IReadOnlyList<KhOption<TEnum>> Choices<TEnum>(ITexts texts)
where TEnum : struct, Enum
{
ArgumentNullException.ThrowIfNull(texts);
return [.. Enum.GetValues<TEnum>().Select(v => new KhOption<TEnum>(v, texts[EnumKey(v)]))];
}
/// <summary>The text of the errors of a refused operation.</summary>
/// <param name="texts">The texts.</param>
/// <param name="exception">The refusal.</param>
/// <returns>The messages, one sentence each.</returns>
public static string Errors(ITexts texts, ValidationFailedException exception)
{
ArgumentNullException.ThrowIfNull(texts);
ArgumentNullException.ThrowIfNull(exception);
return string.Join(" ", exception.Errors.Select(e => TableValues.SplitError(e).Code).Distinct(StringComparer.Ordinal).Select(c => texts.Contains(c) ? texts[c] : c));
}
/// <summary>The tone of the state of an entry.</summary>
/// <param name="status">The state.</param>
/// <returns>The tone.</returns>
public static KhTone ToneOf(GlEntryStatus status) => status switch
{
GlEntryStatus.Draft => KhTone.Warning,
GlEntryStatus.Final => KhTone.Ok,
_ => KhTone.Info,
};
/// <summary>A balance as the screens show it: amount and side (D or A).</summary>
/// <param name="texts">The texts.</param>
/// <param name="amount">The balance, debit positive.</param>
/// <returns>The text.</returns>
public static string Balance(ITexts texts, decimal amount)
{
ArgumentNullException.ThrowIfNull(texts);
return amount == 0m ? texts.Money(0m) : texts.Money(Math.Abs(amount)) + " " + texts[amount > 0m ? "Ledger.Side.D" : "Ledger.Side.A"];
}
/// <summary>Gives the browser a file made by the ledger.</summary>
/// <param name="js">The interop.</param>
/// <param name="file">The file.</param>
/// <returns>A task.</returns>
public static async Task DownloadAsync(IJSRuntime js, LedgerFile file)
{
ArgumentNullException.ThrowIfNull(js);
ArgumentNullException.ThrowIfNull(file);
using var buffer = new MemoryStream(file.Content);
using var stream = new DotNetStreamReference(buffer, leaveOpen: true);
await js.InvokeVoidAsync("khaemhat.download", file.FileName, file.MediaType, stream).ConfigureAwait(false);
}
/// <summary>Reads an amount typed with the Italian separators.</summary>
/// <param name="texts">The texts (for the culture).</param>
/// <param name="text">The text.</param>
/// <returns>The amount, or zero.</returns>
public static decimal ParseAmount(ITexts texts, string? text)
{
ArgumentNullException.ThrowIfNull(texts);
var clean = (text ?? string.Empty).Replace("€", string.Empty, StringComparison.Ordinal).Replace(".", string.Empty, StringComparison.Ordinal).Trim();
return decimal.TryParse(clean, System.Globalization.NumberStyles.Number, texts.Culture, out var value) ? Math.Round(value, 2, MidpointRounding.AwayFromZero) : 0m;
}
/// <summary>An amount for an input box: empty for zero.</summary>
/// <param name="texts">The texts.</param>
/// <param name="amount">The amount.</param>
/// <returns>The text.</returns>
public static string AmountText(ITexts texts, decimal amount)
{
ArgumentNullException.ThrowIfNull(texts);
return amount == 0m ? string.Empty : amount.ToString("#,##0.00", texts.Culture);
}
}
@@ -4,6 +4,8 @@
"Close": "Chiudi",
"Cancel": "Annulla",
"Save": "Salva",
"Edit": "Modifica",
"Delete": "Elimina",
"Reset": "Ripristina",
"Yes": "Sì",
"No": "No",
@@ -0,0 +1,520 @@
{
"Ledger": {
"Saved": "Salvato",
"NotSaved": "Non salvato",
"NotDone": "Operazione non eseguita",
"NoCompany": "Scegli un'azienda per lavorare sulla contabilità",
"NoModule": {
"Title": "Contabilità non attiva",
"Lead": "La licenza di questa azienda non comprende il modulo Contabilità generale e IVA (ACCT). Attivalo da Amministrazione, Licenze."
},
"Print": "Stampa",
"Pager": "{0}-{1} di {2}",
"Previous": "Precedenti",
"Next": "Successivi",
"Side": {
"Dare": "Dare",
"Avere": "Avere",
"D": "D",
"A": "A"
},
"Fields": {
"Account": "Conto",
"Amount": "Importo",
"Area": "Area",
"ClosesAutomatically": "Chiuso in automatico a fine esercizio",
"Code": "Codice",
"CostCenter": "Centro di costo",
"Date": "Data",
"Description": "Descrizione",
"Disabled": "Disattivato",
"Document": "Documento",
"DocumentDate": "Data documento",
"DocumentNumber": "Numero documento",
"Exigibility": "Esigibilità",
"From": "Dal",
"To": "Al",
"Kind": "Tipo",
"Level": "Livello",
"LineDescription": "Descrizione riga",
"Nature": "Natura",
"NonDeductible": "Indetraibile",
"Number": "Numero",
"OpensItems": "Apre partite",
"Party": "Cliente o fornitore",
"Protocol": "Protocollo",
"Rate": "Aliquota",
"Reclassification": "Riclassificazione",
"Reverses": "Causale di storno",
"Role": "Ruolo",
"Side": "Segno",
"StatementLine": "Voce di bilancio CEE",
"Status": "Stato",
"SubLedger": "Partitario",
"Tax": "Imposta",
"TaxCode": "Codice IVA",
"Taxable": "Imponibile",
"Template": "Causale",
"Type": "Tipo",
"VatDate": "Data registrazione IVA",
"VatRegister": "Registro IVA",
"VatRelevant": "Rilevante IVA"
},
"Journal": {
"Title": "Prima nota",
"Heading": "Prima nota",
"Hint": "Le registrazioni contabili dell'esercizio: manuali, dai documenti, dalle liquidazioni e dai versamenti.",
"Entries": "Registrazioni",
"Count": "{0} registrazioni",
"None": "Nessuna registrazione con questi filtri.",
"Search": "Cerca per descrizione, numero o documento",
"AllStates": "Tutti gli stati",
"New": "Nuova registrazione",
"NoNumber": "Bozza",
"Reversed": "Stornata",
"PostDocuments": "Contabilizza documenti",
"PostText": "Registra in prima nota i documenti di vendita e acquisto confermati del periodo che non sono ancora contabilizzati.",
"PostAgain": "Ricontabilizza anche i documenti già registrati (solo se le registrazioni non sono definitive)",
"PostRun": "Contabilizza",
"Posted": "Documenti contabilizzati: {0}.",
"Finalize": "Rendi definitive",
"FinalizeText": "Le registrazioni rese definitive ricevono il numero di libro giornale e non si possono più modificare né eliminare: si correggono solo con uno storno.",
"FinalizeUpTo": "Fino al giorno",
"FinalizeConfirm": "Rendere definitive tutte le registrazioni fino al {0}? L'operazione non si può annullare.",
"Finalized": "Registrazioni rese definitive: {0}."
},
"Entry": {
"Title": "Registrazione {0}",
"New": "Nuova registrazione",
"NewHint": "Scegli una causale per proporre le righe, poi completa conti e importi: Dare e Avere devono quadrare.",
"Header": "Testata",
"Lines": "Righe",
"LinesCount": "Righe",
"Vat": "Castelletto IVA",
"Totals": "Totali",
"Difference": "Sbilancio",
"Unbalanced": "La registrazione non quadra: mancano {0} in {1}.",
"CloseDifference": "Chiudi lo sbilancio",
"AddLine": "Aggiungi riga",
"RemoveLine": "Togli riga",
"AddVat": "Aggiungi aliquota",
"ChooseParty": "Cerca cliente o fornitore",
"NoTemplate": "Nessuna causale",
"NoRegister": "Nessun registro IVA",
"JournalNumber": "Libro giornale n. {0}",
"SaveDraft": "Salva bozza",
"Post": "Registra",
"Posted": "Registrazione salvata",
"Reverse": "Storna",
"ReverseDate": "Data dello storno",
"ReverseText": "Lo storno crea una nuova registrazione con Dare e Avere invertiti che annulla questa.",
"Reversed": "Storno registrato",
"ReversalOf": "storno di un'altra registrazione",
"ReversedBy": "stornata da un'altra registrazione",
"Delete": "Elimina registrazione",
"DeleteText": "Eliminare la registrazione {0}? Solo le registrazioni non definitive si possono eliminare.",
"Deleted": "Registrazione eliminata"
},
"Recurring": {
"Title": "Ricorrenti",
"Hint": "Le registrazioni che si ripetono (affitti, canoni, ratei): ogni notte Khaemhat copia la registrazione modello alle date previste.",
"None": "Nessuna registrazione ricorrente.",
"New": "Nuova ricorrente",
"Model": "Registrazione modello",
"ModelNumber": "Numero della registrazione modello",
"ModelHint": "Il numero di prima nota della registrazione da copiare.",
"OpenModel": "Apri il modello",
"Frequency": "Frequenza",
"NextDate": "Prossima data",
"EndDate": "Fino al",
"Active": "Attiva",
"Suspended": "Sospesa",
"Generate": "Genera ora",
"Generated": "Registrazioni ricorrenti generate: {0}.",
"Delete": "Elimina ricorrente",
"DeleteText": "Eliminare la ricorrente \"{0}\"? Le registrazioni già generate restano."
},
"Accounts": {
"Title": "Piano dei conti",
"Heading": "Piano dei conti",
"Hint": "Mastri, conti e sottoconti dell'azienda, con natura, voce di bilancio CEE e mastrino dei movimenti.",
"Chart": "Conti",
"Count": "{0} conti",
"Search": "Cerca per codice o descrizione",
"Choose": "Scegli un conto per vederne i dati e il mastrino.",
"New": "Nuovo conto",
"Edit": "Modifica conto",
"Delete": "Elimina conto",
"DeleteText": "Eliminare il conto {0}? Si possono eliminare solo i conti senza movimenti e senza sottoconti.",
"CodeHint": "Mastro, conto e sottoconto separati da punti, ad esempio 05.01.001.",
"CeeHint": "La voce dello schema di bilancio civilistico (art. 2424 e 2425 c.c.), ad esempio CII1.",
"Ledger": "Mastrino",
"Level1": "Mastri",
"Level2": "Conti",
"Level3": "Sottoconti"
},
"Templates": {
"Title": "Causali contabili",
"Heading": "Causali contabili",
"Hint": "Le causali guidano la prima nota: propongono conti, segni e registro IVA delle righe.",
"List": "Causali",
"Choose": "Scegli una causale per modificarla.",
"New": "Nuova causale",
"Edit": "Modifica causale",
"Lines": "Righe proposte",
"Delete": "Elimina causale",
"DeleteText": "Eliminare la causale {0}? Le causali usate da una registrazione non si possono eliminare."
},
"Parties": {
"Title": "Partitari",
"Heading": "Partitari clienti e fornitori",
"Hint": "Saldo contabile, estratto conto e partite aperte di ogni cliente e fornitore.",
"Customers": "Clienti",
"Suppliers": "Fornitori",
"Search": "Cerca per nome o codice",
"None": "Nessun movimento per questi soggetti.",
"Total": "Saldo complessivo {0}",
"OpenItems": "Aperte",
"Choose": "Scegli un cliente o un fornitore per vederne l'estratto conto.",
"Statement": "Estratto conto di {0}",
"OpenItemsTitle": "Partite",
"ShowClosed": "Mostra anche le partite chiuse",
"NoOpenItems": "Nessuna partita aperta.",
"Installment": "Rata",
"DueDate": "Scadenza",
"Paid": "Pagato",
"Residual": "Residuo"
},
"Movements": {
"Title": "Movimenti",
"None": "Nessun movimento nel periodo.",
"Opening": "Saldo iniziale",
"Totals": "Totali del periodo",
"Balance": "Saldo"
},
"Balance": {
"Title": "Bilancio di verifica",
"Heading": "Bilancio di verifica e libro giornale",
"Hint": "I saldi di tutti i conti nel periodo, con i totali di conti e mastri; la stampa del bilancio e del libro giornale.",
"AllCenters": "Tutti i centri di costo",
"Detail": "Dettaglio",
"Drafts": "Comprendi le bozze",
"Print": "Stampa bilancio",
"JournalProvisional": "Libro giornale di prova",
"JournalFinal": "Libro giornale definitivo",
"None": "Nessun saldo nel periodo.",
"Opening": "Saldo iniziale",
"Debit": "Saldo Dare",
"Credit": "Saldo Avere",
"Totals": "Totali",
"Check": "Quadratura",
"Balanced": "Dare e Avere quadrano",
"NotBalanced": "Dare e Avere non quadrano",
"Result": "Risultato del periodo",
"Profit": "Utile",
"Loss": "Perdita"
},
"VatRegisters": {
"Title": "Registri IVA",
"Heading": "Registri IVA",
"Hint": "Vendite, acquisti e corrispettivi del periodo con protocollo, imponibile e imposta per aliquota; stampa di prova e definitiva.",
"NoRegisters": "Non ci sono registri IVA: aggiorna le tabelle di base dell'azienda.",
"None": "Nessuna registrazione nel periodo.",
"Lines": "{0} registrazioni",
"Totals": "Riepilogo per aliquota",
"RegisterTotal": "Totale registro",
"LastPrint": "Ultima stampa definitiva",
"LastPage": "Ultima pagina",
"NeverPrinted": "Mai stampato",
"PrintProvisional": "Stampa di prova",
"PrintFinal": "Stampa definitiva",
"FinalUpTo": "Fino al giorno",
"FinalText": "La stampa definitiva parte dal {0} e numera le pagine dalla {1}; dopo la stampa le registrazioni del periodo non si possono più modificare.",
"FinalConfirm": "Stampare in definitivo il registro? L'operazione non si può annullare.",
"Printed": "Registro stampato"
},
"Settlement": {
"Title": "Liquidazione IVA",
"Heading": "Liquidazione IVA periodica",
"Hint": "Calcolo dell'IVA a debito e a credito del periodo, credito o debito riportato, interessi trimestrali, registrazione e dati per F24 e LIPE.",
"Periodicity": "Periodicità",
"Year": "Anno",
"Period": "Periodo",
"QuarterName": "{0}° trimestre {1}",
"PreviousCredit": "Credito periodo precedente",
"PreviousDebit": "Debito periodo precedente",
"Compute": "Calcola",
"Confirm": "Conferma liquidazione",
"ConfirmText": "Confermare la liquidazione di {0}? Viene registrata in prima nota e l'importo di {1} va nei versamenti F24.",
"Confirmed": "Liquidazione confermata",
"Reopen": "Riapri",
"ReopenText": "Riaprire la liquidazione? La registrazione viene eliminata o stornata e il versamento F24 tolto, se non è già pagato.",
"NotComputed": "Liquidazione non ancora calcolata: premi Calcola.",
"Calculation": "Calcolo",
"Registers": "Registri del periodo",
"Documents": "Documenti",
"Deferred": "Esigibilità differita",
"SalesTax": "IVA a debito sulle vendite",
"PurchaseTax": "IVA a credito sugli acquisti",
"NonDeductibleTax": "IVA indetraibile",
"DeferredTax": "IVA a esigibilità differita",
"ProRata": "Pro rata",
"ProRataValue": "Detraibilità {0}%",
"CreditCarried": "Credito da riportare",
"DebitCarried": "Debito sotto la soglia di versamento, riportato",
"AdvancePaid": "Acconto versato",
"Interest": "Interessi trimestrali {0}%",
"AmountDue": "Da versare",
"Payment": "Versamento",
"PaymentCode": "Codice tributo",
"DueDate": "Scadenza",
"Entry": "Registrazione",
"OpenEntry": "Apri la registrazione",
"LipeQuarter": "Trimestre LIPE",
"Lipe": "Comunicazione LIPE",
"F24Data": "Dati F24",
"Telematic": "Khaemhat prepara i file della comunicazione LIPE e i dati del modello F24: l'invio telematico si fa con i servizi dell'Agenzia delle Entrate o dell'intermediario.",
"YearList": "Liquidazioni {0}",
"NoneYet": "Nessuna liquidazione nell'anno."
},
"Advance": {
"Title": "Acconto IVA {0}",
"Hint": "L'acconto di dicembre si versa entro il 27/12 con il codice 6013 (mensili) o 6035 (trimestrali); non è dovuto sotto 103,29 euro.",
"Bases": "Basi di calcolo",
"BasesValue": "Storico {0} · Effettivo {1}",
"Method": "Metodo",
"Basis": "Base di calcolo",
"BasisHint": "Per il metodo previsionale, l'IVA che prevedi di dover versare per dicembre o il quarto trimestre.",
"Refresh": "Ricalcola le basi",
"Record": "Registra acconto",
"Recorded": "Acconto di {0} da versare entro il {1}",
"NoneDue": "Nessun acconto dovuto"
},
"Withholdings": {
"Title": "Ritenute d'acconto",
"Heading": "Ritenute d'acconto e F24",
"Hint": "Le ritenute operate sui compensi ai professionisti e quelle subite sulle tue fatture; prospetto F24, versamento e dati per la Certificazione Unica.",
"Operated": "Operate",
"Suffered": "Subite",
"All": "Tutte",
"None": "Nessuna ritenuta nell'anno.",
"Type": "Tipo",
"Rate": "Aliquota",
"On": "su {0}% dell'imponibile",
"Fund": "Cassa",
"FundAmount": "Contributo cassa",
"PaidOn": "Pagata il",
"Total": "Totale ritenute {0}",
"Footer": "La ritenuta operata diventa dovuta quando paghi la fattura del professionista e si versa entro il 16 del mese successivo.",
"Note": "La Certificazione Unica si invia con i servizi dell'Agenzia delle Entrate: Khaemhat prepara i dati dei percipienti.",
"Cu": "Dati Certificazione Unica",
"InvoicePaid": "Fattura pagata",
"InvoicePaidText": "Registra il pagamento della fattura {0} di {1}: la ritenuta diventa da versare con l'F24 del mese successivo.",
"Undo": "Annulla pagamento",
"UndoText": "Annullare il pagamento della fattura {0}? La registrazione della ritenuta viene tolta."
},
"F24": {
"Title": "Prospetto F24",
"DueDate": "Scadenza",
"Lines": "Righe del modello F24",
"None": "Nessun tributo in scadenza.",
"AllPaid": "Tutti i tributi della scadenza sono pagati.",
"Credit": "Credito",
"Total": "Saldo F24 del {0}",
"Pay": "Registra pagamento",
"PayText": "Registra il pagamento dell'F24 del {0} per {1}: Khaemhat scrive la registrazione in prima nota.",
"PaidOn": "Pagato il",
"Paid": "Pagamento F24 registrato",
"Unpay": "Annulla pagamento",
"UnpayText": "Annullare il pagamento dell'F24? La registrazione del pagamento viene tolta o stornata."
},
"StampDuty": {
"Title": "Imposta di bollo",
"Heading": "Imposta di bollo sulle fatture elettroniche",
"Hint": "Il bollo virtuale da 2 euro sulle fatture esenti sopra 77,47 euro, per trimestre, con codice tributo e scadenza.",
"Year": "Bollo {0}",
"Quarter": "Trimestre",
"QuarterBadge": "{0}° trim. {1}",
"Invoices": "Fatture",
"Duty": "Bollo",
"Charge": "Addebito",
"Charged": "Addebitato al cliente",
"Borne": "A carico dell'azienda",
"None": "Nessuna fattura con bollo nel trimestre.",
"Footer": "Sotto 5.000 euro il bollo del primo trimestre si versa con il secondo (30/9) e quello dei primi due con il terzo (30/11).",
"Previous": "Trimestre precedente",
"Record": "Metti in F24",
"Recorded": "Bollo di {0} da versare entro il {1}",
"NoneDue": "Nessun bollo da versare",
"Export": "Dati F24",
"PaidOn": "pagato il {0}",
"InF24": "In F24",
"ToRecord": "Da mettere in F24"
},
"Enums": {
"GlEntryStatus": {
"Draft": "Bozza",
"Posted": "Registrata",
"Final": "Definitiva"
},
"GlEntrySource": {
"Manual": "Manuale",
"Document": "Da documento",
"VatSettlement": "Liquidazione IVA",
"TaxPayment": "Versamento F24",
"Recurring": "Ricorrente",
"Reversal": "Storno",
"Withholding": "Ritenuta"
},
"RecurrenceFrequency": {
"Monthly": "Mensile",
"Quarterly": "Trimestrale",
"HalfYearly": "Semestrale",
"Yearly": "Annuale"
},
"AccountNature": {
"Asset": "Attività",
"Liability": "Passività",
"Cost": "Costo",
"Revenue": "Ricavo",
"Memorandum": "Conto d'ordine"
},
"AccountType": {
"Generic": "Generico",
"Customers": "Clienti",
"Suppliers": "Fornitori",
"Bank": "Banca",
"Cash": "Cassa",
"Vat": "IVA",
"Tax": "Tributi"
},
"JournalArea": {
"General": "Generale",
"Sales": "Vendite",
"Purchases": "Acquisti",
"Treasury": "Tesoreria",
"Taxes": "Imposte",
"YearEnd": "Chiusura esercizio"
},
"PostingRole": {
"Account": "Conto indicato",
"Customer": "Cliente",
"Supplier": "Fornitore",
"Revenue": "Ricavo",
"Cost": "Costo",
"SalesVat": "IVA vendite",
"PurchaseVat": "IVA acquisti",
"Bank": "Banca",
"Cash": "Cassa",
"WithholdingPayable": "Ritenute da versare",
"WithholdingCredit": "Ritenute subite",
"SocialSecurity": "Contributo cassa",
"StampDuty": "Bollo",
"Rounding": "Arrotondamenti",
"VatSettlement": "Erario c/IVA",
"SplitPaymentVat": "IVA split payment"
},
"AccountSide": {
"Debit": "Dare",
"Credit": "Avere"
},
"VatRegisterKind": {
"Sales": "Vendite",
"Purchases": "Acquisti",
"Receipts": "Corrispettivi"
},
"VatSettlementStatus": {
"Draft": "Da confermare",
"Confirmed": "Confermata"
},
"WithholdingStatus": {
"Waiting": "In attesa del pagamento",
"Due": "Da versare",
"Paid": "Versata",
"Suffered": "Subita"
},
"VatAdvanceMethod": {
"Historical": "Storico",
"Forecast": "Previsionale",
"Actual": "Effettivo"
},
"VatPeriodicity": {
"Monthly": "Mensile",
"Quarterly": "Trimestrale"
},
"TaxExigibility": {
"Immediate": "Immediata",
"Deferred": "Differita",
"SplitPayment": "Scissione dei pagamenti"
}
}
},
"ledger": {
"entry": {
"not-found": "La registrazione non esiste più.",
"description-required": "Scrivi la descrizione della registrazione.",
"date-required": "Indica la data di registrazione.",
"lines-required": "Una registrazione ha almeno due righe.",
"unbalanced": "Il totale Dare e il totale Avere non coincidono.",
"vat-register-required": "Con righe IVA serve un registro IVA.",
"final": "La registrazione è definitiva: si corregge solo con uno storno.",
"from-document": "La registrazione viene da un documento: correggi il documento e ricontabilizzalo.",
"already-reversed": "La registrazione è già stata stornata.",
"not-posted": "Si possono stornare solo le registrazioni registrate.",
"final-order": "Le date devono seguire l'ordine del libro giornale: c'è già una registrazione definitiva successiva.",
"recurring-model": "La registrazione è il modello di una ricorrente: togli prima la ricorrente.",
"drafts-before-final": "Ci sono bozze nel periodo: registrale o eliminale prima di renderlo definitivo.",
"no-fiscal-year": "Non c'è un esercizio aperto per questa data."
},
"line": {
"account-required": "Ogni riga ha un conto.",
"account-missing": "Un conto delle righe non esiste più.",
"account-not-postable": "Si registra solo sui sottoconti, non su mastri e conti.",
"account-disabled": "Un conto delle righe è disattivato.",
"party-required": "Le righe su clienti e fornitori indicano il soggetto.",
"amount-required": "Ogni riga ha un importo in Dare o in Avere.",
"both-sides": "Una riga ha l'importo in Dare oppure in Avere, non in entrambi.",
"negative": "Gli importi non possono essere negativi."
},
"vat": {
"code-required": "Ogni riga IVA ha un codice IVA."
},
"posting": {
"account-missing": "Manca un conto per contabilizzare il documento: controlla causali e piano dei conti."
},
"template": {
"missing": "Manca la causale contabile per questo documento: aggiorna le tabelle di base.",
"code": "Il codice della causale non è valido.",
"duplicate": "Esiste già una causale con questo codice.",
"used": "La causale è usata da registrazioni: disattivala invece di eliminarla."
},
"account": {
"used": "Il conto ha movimenti: disattivalo invece di eliminarlo.",
"has-children": "Il conto ha sottoconti: elimina prima quelli.",
"parent": "Il conto padre non esiste: crea prima il mastro o il conto.",
"duplicate": "Esiste già un conto con questo codice.",
"code": "Il codice del conto non è valido: usa mastro, conto e sottoconto separati da punti."
},
"bank": {
"account-missing": "Il conto bancario non ha un conto contabile e manca il conto banca predefinito."
}
},
"vat": {
"settlement": {
"confirmed": "La liquidazione è confermata: riaprila per ricalcolarla.",
"previous": "Conferma prima la liquidazione del periodo precedente.",
"later": "C'è una liquidazione successiva confermata: riapri prima quella."
},
"register": {
"print-order": "La stampa definitiva riprende dal giorno dopo l'ultima stampata."
}
},
"tax": {
"payment": {
"paid": "Il versamento è già pagato: annulla prima il pagamento."
}
},
"withholding": {
"not-due": "La ritenuta non è ancora da versare: registra prima il pagamento della fattura."
}
}
+4 -1
View File
@@ -89,8 +89,12 @@
"_": "Contabilità",
"Journal": "Prima nota",
"Accounts": "Piano dei conti",
"Templates": "Causali",
"Parties": "Partitari",
"VatRegisters": "Registri IVA",
"VatSettlement": "Liquidazione IVA",
"Withholdings": "Ritenute e F24",
"StampDuty": "Bollo virtuale",
"Statements": "Bilancio"
},
"Finance": {
@@ -104,7 +108,6 @@
"_": "Fatt. elettronica",
"Dashboard": "Cruscotto SDI",
"Channels": "Canali di trasmissione",
"StampDuty": "Bollo virtuale",
"IntentDeclarations": "Dichiarazioni d'intento"
},
"Assets": {
+6 -4
View File
@@ -69,14 +69,16 @@ public static class MenuCatalog
Area("Shell.Menu.Inventory", "box", "/magazzino", ModuleCodes.Core, "inventory.stock.read", null,
("Shell.Menu.Inventory.Stock", "giacenze"), ("Shell.Menu.Inventory.Entries", "movimenti"), ("Shell.Menu.Inventory.StockTake", "inventario"),
("Shell.Menu.Inventory.Reorder", "riordino")),
Area("Shell.Menu.Ledger", "book", "/contabilita", ModuleCodes.Accounting, "ledger.entry.read", "M7",
("Shell.Menu.Ledger.Journal", "prima-nota"), ("Shell.Menu.Ledger.Accounts", "piano-dei-conti"), ("Shell.Menu.Ledger.VatRegisters", "registri-iva"),
("Shell.Menu.Ledger.VatSettlement", "liquidazione-iva"), ("Shell.Menu.Ledger.Statements", "bilancio")),
Area("Shell.Menu.Ledger", "book", "/contabilita", ModuleCodes.Accounting, "ledger.entry.read", null,
("Shell.Menu.Ledger.Journal", "prima-nota"), ("Shell.Menu.Ledger.Accounts", "piano-dei-conti"), ("Shell.Menu.Ledger.Templates", "causali"),
("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",
("Shell.Menu.EInvoicing.Dashboard", "cruscotto"), ("Shell.Menu.EInvoicing.Channels", "canali"), ("Shell.Menu.EInvoicing.StampDuty", "bollo"),
("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",
("Shell.Menu.Assets.Register", "registro"), ("Shell.Menu.Assets.Depreciation", "ammortamenti")),
+14
View File
@@ -422,3 +422,17 @@ h1[tabindex="-1"]:focus { outline: none; box-shadow: none; }
.kh-cellpick .f > label:empty { display: none; }
.kh-plainlist { margin: 4px 0 0; padding-left: 18px; }
.kh-pendingself { margin-bottom: 12px; }
/* Ledger (M7): chart and detail side by side, levels of the chart, the summary of a settlement, grids of amounts. */
.kh-ledger-split { display: grid; grid-template-columns: minmax(0, 4fr) minmax(0, 7fr); gap: 12px; align-items: start; }
.kh-ledger-side { display: flex; flex-direction: column; gap: 12px; min-width: 0; }
.kh-ledger-tree { max-height: 68vh; overflow: auto; }
.kh-ledger-tree .lvl1, .kh-ledger-tree .lvl2 { font-weight: 600; }
.kh-ledger-tree .lvl1 { color: var(--kh-accent); }
.kh-ledger-two { display: grid; grid-template-columns: minmax(0, 3fr) minmax(0, 2fr); gap: 12px; align-items: start; }
.kh-ledger-checks { display: flex; flex-wrap: wrap; gap: 4px 10px; font-size: 12px; color: var(--kh-ok); }
.kh-ledger-checks .no { color: var(--kh-warn); }
.kh-ledger-filters .f { margin: 0; }
.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); } }