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

@@ -115,6 +115,7 @@ public sealed partial class DocumentEngine
private readonly CompanyFiscalContext _packs;
private readonly TimeProvider _clock;
private readonly ILogger<DocumentEngine> _logger;
private readonly Ledger.LedgerPoster _ledger;
/// <summary>Creates the engine.</summary>
/// <param name="factory">The units of work.</param>
@@ -124,10 +125,13 @@ public sealed partial class DocumentEngine
/// <param name="packs">The fiscal pack of each company (tax rounding, stamp duty).</param>
/// <param name="clock">The clock.</param>
/// <param name="logger">The log (section Documenti): confirmations, changes of state, deletions.</param>
/// <param name="ledger">Posts the documents to the ledger (module ACCT).</param>
public DocumentEngine(
IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit, FiscalYearService fiscal, CompanyFiscalContext packs, TimeProvider clock,
ILogger<DocumentEngine> logger)
ILogger<DocumentEngine> logger, Ledger.LedgerPoster ledger)
{
ArgumentNullException.ThrowIfNull(ledger);
_ledger = ledger;
ArgumentNullException.ThrowIfNull(logger);
_logger = logger;
ArgumentNullException.ThrowIfNull(packs);
@@ -269,6 +273,7 @@ public sealed partial class DocumentEngine
{
await RefreshFulfillmentAsync(uow, record.Family, id, actor.UserName, cancellationToken).ConfigureAwait(false);
await InventoryPoster.SyncAsync(uow, record.Family, id, cancellationToken).ConfigureAwait(false);
await _ledger.SyncAsync(uow, record.Family, id, cancellationToken).ConfigureAwait(false);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
@@ -357,6 +362,7 @@ public sealed partial class DocumentEngine
await store.RecordAsync(_audit, uow, AuditAction.Update, id, before, header, actor.UserName, cancellationToken).ConfigureAwait(false);
await LinkAsync(uow, definition, record, actor.UserName, cancellationToken).ConfigureAwait(false);
await InventoryPoster.SyncAsync(uow, family, id, cancellationToken).ConfigureAwait(false);
await _ledger.SyncAsync(uow, family, id, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
LogConfirmed(_logger, header.Kind, header.DocumentNumber ?? id.ToString(System.Globalization.CultureInfo.InvariantCulture), header.Status, company, actor.UserName);
}
@@ -703,6 +709,7 @@ public sealed partial class DocumentEngine
// A cancelled delivery note gives its stock back; a closed or reopened order its open quantities.
await InventoryPoster.SyncAsync(uow, family, id, cancellationToken).ConfigureAwait(false);
await _ledger.SyncAsync(uow, family, id, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
LogChanged(_logger, record.Header.Kind, record.Header.DocumentNumber ?? id.ToString(System.Globalization.CultureInfo.InvariantCulture), action, next, company, actor.UserName);
}
@@ -2,6 +2,7 @@ using Khaemhat.Application.Modules;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Accounting;
using Khaemhat.Data;
namespace Khaemhat.Application.ImportExport;
@@ -17,9 +18,11 @@ namespace Khaemhat.Application.ImportExport;
/// <param name="SubLedger">With a sub-ledger of customers or suppliers.</param>
/// <param name="ClosesAutomatically">Closed by the year end.</param>
/// <param name="Disabled">Not used any more.</param>
/// <param name="StatementLine">The line of the legal statements (voce CEE).</param>
/// <param name="Reclassification">The line of the reclassified statements.</param>
public sealed record ImportedAccount(
string Code, string Description, int Level, string? ParentCode, AccountNature Nature, AccountType Type, bool Postable, bool VatRelevant, bool SubLedger,
bool ClosesAutomatically, bool Disabled);
bool ClosesAutomatically, bool Disabled, string? StatementLine = null, string? Reclassification = null);
/// <summary>
/// The checks of a chart of accounts from a file (SPEC §12.12, ADR 0031): codes of one to three parts separated by
@@ -145,7 +148,7 @@ public static class ChartOfAccountsImportValidator
if (messages.All(m => m.IsWarning) && nature is { } valid)
{
accounts.Add(new(code, row["descrizione"] ?? string.Empty, level, parent, valid, type, postable, flags.Contains('I'), flags.Contains('P'), flags.Contains('C'),
flags.Contains('X')));
flags.Contains('X'), row["voce_cee"], row["riclassifica"]));
}
results.Add(new(row.Line, code, messages.Any(m => !m.IsWarning) ? ImportAction.Skip : ImportAction.Create, messages));
@@ -182,15 +185,26 @@ public static class ChartOfAccountsImportValidator
}
/// <summary>
/// The chart of accounts (<c>piano-dei-conti</c>): CSV, XLSX or <c>khaemhat-coa.json</c>. Until the ledger exists (M7)
/// the file is only checked; M7 writes the accounts this check accepts.
/// The chart of accounts (<c>piano-dei-conti</c>): CSV, XLSX or <c>khaemhat-coa.json</c>. The accounts the check
/// accepts are added; those that exist are updated when the options say so (M7, issue #62).
/// </summary>
/// <param name="permissions">Checks the permission.</param>
public sealed class ChartOfAccountsImportTarget(PermissionService permissions) : IImportTarget
public sealed class ChartOfAccountsImportTarget : IImportTarget
{
/// <summary>The permission to change the chart of accounts.</summary>
public const string WritePermission = "ledger.account.write";
private readonly PermissionService _permissions;
private readonly IUnitOfWorkFactory? _factory;
/// <summary>Creates the target.</summary>
/// <param name="permissions">Checks the permission.</param>
/// <param name="factory">The units of work, to write the accounts.</param>
public ChartOfAccountsImportTarget(PermissionService permissions, IUnitOfWorkFactory? factory = null)
{
_permissions = permissions;
_factory = factory;
}
/// <inheritdoc />
public string Key => "piano-dei-conti";
@@ -204,10 +218,10 @@ public sealed class ChartOfAccountsImportTarget(PermissionService permissions) :
public string ExportPermission => "ledger.account.read";
/// <inheritdoc />
public bool CanApply => false;
public bool CanApply => _factory is not null;
/// <inheritdoc />
public bool CanExport => false;
public bool CanExport => _factory is not null;
/// <inheritdoc />
public IReadOnlyList<ImportField> Fields => ChartOfAccountsImportValidator.Fields;
@@ -216,15 +230,46 @@ public sealed class ChartOfAccountsImportTarget(PermissionService permissions) :
public async Task<IReadOnlyList<ImportRowResult>> CheckAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
await CompanyGuard.DemandAsync(permissions, context.Actor, context.CompanyCode, Permission, cancellationToken).ConfigureAwait(false);
await CompanyGuard.DemandAsync(_permissions, context.Actor, context.CompanyCode, Permission, cancellationToken).ConfigureAwait(false);
return ChartOfAccountsImportValidator.Check(rows).Results;
}
/// <inheritdoc />
public Task<IReadOnlyList<ImportRowResult>> ApplyAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken) =>
throw new InvalidOperationException(ImportErrors.CheckOnly);
public async Task<IReadOnlyList<ImportRowResult>> ApplyAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
var factory = _factory ?? throw new InvalidOperationException(ImportErrors.CheckOnly);
var company = await CompanyGuard.DemandAsync(_permissions, context.Actor, context.CompanyCode, Permission, cancellationToken).ConfigureAwait(false);
var (results, accounts) = ChartOfAccountsImportValidator.Check(rows);
var update = context.Options.Existing == ExistingCodeAction.Update;
Dictionary<string, bool> written;
await using (var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
written = await Ledger.LedgerService.ImportAsync(uow, accounts, update, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
return [.. results.Select(r => r.Action == ImportAction.Skip
? r
: r with { Action = written.TryGetValue(r.Key, out var created) ? (created ? ImportAction.Create : ImportAction.Update) : ImportAction.Skip })];
}
/// <inheritdoc />
public Task<IReadOnlyList<IReadOnlyList<object?>>> ExportAsync(ImportContext context, CancellationToken cancellationToken) =>
Task.FromResult<IReadOnlyList<IReadOnlyList<object?>>>([]);
public async Task<IReadOnlyList<IReadOnlyList<object?>>> ExportAsync(ImportContext context, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
var factory = _factory ?? throw new InvalidOperationException(ImportErrors.CheckOnly);
var company = await CompanyGuard.DemandAsync(_permissions, context.Actor, context.CompanyCode, ExportPermission, cancellationToken).ConfigureAwait(false);
await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var accounts = (await uow.Repository<GlAccount, long>().ListAsync(Data.Querying.Query.For<GlAccount>(), cancellationToken).ConfigureAwait(false)).Items
.OrderBy(a => a.Code, StringComparer.Ordinal);
return [.. accounts.Select(a => (IReadOnlyList<object?>)
[
a.Code, a.Description, a.Level, ChartOfAccountsImportValidator.ParentOf(a.Code), ChartOfAccountsImportValidator.NatureWords[(int)a.Nature],
ChartOfAccountsImportValidator.TypeWords[(int)a.Type], a.StatementLine, a.Reclassification,
(a.Postable ? "M" : string.Empty) + (a.VatRelevant ? "I" : string.Empty) + (a.SubLedger ? "P" : string.Empty)
+ (a.ClosesAutomatically ? "C" : string.Empty) + (a.Disabled ? "X" : string.Empty),
])];
}
}
@@ -59,6 +59,7 @@ public sealed class JobScheduler
new("system.attachments-trash", "Svuotamento cestino allegati", Files.AttachmentTrashPurgeJob.JobType, "45 3 * * *", 1800),
new("system.ecb-rates", "Cambi di riferimento BCE", Tables.EcbRatesJob.JobType, "30 16 * * 1-5", 300, UsesNetwork: true),
new("inventory.rebuild", "Ricostruzione del magazzino", Inventory.InventoryRebuildJob.JobType, "15 2 * * 0", 3600),
new("ledger.recurring", "Registrazioni ricorrenti", Ledger.RecurringEntriesJob.JobType, "0 5 * * *", 1800),
];
private readonly IUnitOfWorkFactory _factory;
@@ -0,0 +1,562 @@
using Khaemhat.Application.Audit;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Accounting;
using Khaemhat.Core.Parties;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Ledger;
/// <summary>An entry with its lines and VAT lines.</summary>
/// <param name="Entry">The entry.</param>
/// <param name="Lines">The lines.</param>
/// <param name="Vat">The VAT lines.</param>
/// <param name="PartyName">The name of the customer or supplier of the entry.</param>
public sealed record EntryView(GlEntry Entry, IReadOnlyList<GlEntryLine> Lines, IReadOnlyList<GlEntryVat> Vat, string? PartyName)
{
/// <summary>Debit minus credit.</summary>
public decimal Difference => Lines.Sum(l => l.Debit - l.Credit);
}
/// <summary>An entry as the journal lists it.</summary>
/// <param name="Entry">The entry.</param>
/// <param name="PartyName">The customer or supplier.</param>
public sealed record EntryRow(GlEntry Entry, string? PartyName);
/// <summary>What the journal list shows.</summary>
/// <param name="From">From this day.</param>
/// <param name="To">Up to this day.</param>
/// <param name="Status">Only this state.</param>
/// <param name="TemplateCode">Only this template.</param>
/// <param name="Text">Text in the description or the document number.</param>
/// <param name="Offset">The first row.</param>
/// <param name="Limit">How many rows.</param>
public sealed record EntryFilter(
DateOnly? From = null, DateOnly? To = null, GlEntryStatus? Status = null, string? TemplateCode = null, string? Text = null, int Offset = 0, int Limit = 50);
/// <summary>An entry typed in the journal.</summary>
/// <param name="Id">The entry, for a change.</param>
/// <param name="EntryDate">The date of registration.</param>
/// <param name="Description">The description.</param>
/// <param name="Lines">The lines.</param>
public sealed record EntryInput(long? Id, DateOnly EntryDate, string Description, IReadOnlyList<EntryLineDraft> Lines)
{
/// <summary>The template.</summary>
public long? JournalTemplateId { get; init; }
/// <summary>The date of competence.</summary>
public DateOnly? CompetenceDate { get; init; }
/// <summary>The number of the document.</summary>
public string? DocumentNumber { get; init; }
/// <summary>The date of the document.</summary>
public DateOnly? DocumentDate { get; init; }
/// <summary>The customer or supplier.</summary>
public long? PartyId { get; init; }
/// <summary>The VAT register.</summary>
public long? VatRegisterId { get; init; }
/// <summary>The VAT date.</summary>
public DateOnly? VatDate { get; init; }
/// <summary>The VAT lines.</summary>
public IReadOnlyList<EntryVatDraft> Vat { get; init; } = [];
/// <summary>Notes.</summary>
public string? Notes { get; init; }
/// <summary>Post it (it must balance) rather than keep it as a draft.</summary>
public bool Post { get; init; }
}
/// <summary>A journal template with its lines, for the guided entry.</summary>
/// <param name="Template">The template.</param>
/// <param name="Lines">Its lines.</param>
public sealed record TemplateView(JournalTemplate Template, IReadOnlyList<JournalTemplateLine> Lines);
/// <summary>
/// The journal (prima nota, SPEC §11.7, issue #63, mockups 040-041, ADR 0036): drafts that may not balance, posted
/// entries (provvisorie) numbered per year in the order of registration, final entries (definitive) numbered on the
/// general journal in date order and never changed again; a reversal corrects them. The guided entry starts from the
/// lines of a template; the manual one shows the imbalance while it is typed. The period must be open (for VAT too when
/// the entry has VAT lines). Entries of documents change only through their document.
/// </summary>
public sealed class JournalEntryService
{
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
private readonly FiscalYearService _fiscal;
private readonly AuditTrail _audit;
private readonly TimeProvider _clock;
/// <summary>Creates the service.</summary>
/// <param name="factory">The units of work.</param>
/// <param name="permissions">The permissions.</param>
/// <param name="fiscal">The fiscal calendar.</param>
/// <param name="audit">The history.</param>
/// <param name="clock">The clock.</param>
public JournalEntryService(IUnitOfWorkFactory factory, PermissionService permissions, FiscalYearService fiscal, AuditTrail audit, TimeProvider clock)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(fiscal);
ArgumentNullException.ThrowIfNull(audit);
ArgumentNullException.ThrowIfNull(clock);
_factory = factory;
_permissions = permissions;
_fiscal = fiscal;
_audit = audit;
_clock = clock;
}
/// <summary>The entries, the latest first.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="filter">The filter and the page.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The page and the total.</returns>
public async Task<(IReadOnlyList<EntryRow> Rows, int Total)> ListAsync(Actor actor, string companyCode, EntryFilter filter, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(filter);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var query = Query.For<GlEntry>();
if (filter.From is { } from)
{
query = query.Where(e => e.EntryDate >= from);
}
if (filter.To is { } to)
{
query = query.Where(e => e.EntryDate <= to);
}
if (filter.Status is { } status)
{
query = query.Where(e => e.Status == status);
}
if (!string.IsNullOrWhiteSpace(filter.TemplateCode))
{
var code = filter.TemplateCode;
query = query.Where(e => e.TemplateCode == code);
}
if (!string.IsNullOrWhiteSpace(filter.Text))
{
var text = filter.Text.Trim();
query = query.Where(e => e.Description.Contains(text) || e.DocumentNumber!.Contains(text) || e.EntryNumber!.Contains(text));
}
var repository = uow.Repository<GlEntry, long>();
var total = await repository.CountAsync(query, cancellationToken).ConfigureAwait(false);
var page = (await repository.ListAsync(
query.OrderByDescending(e => e.EntryDate).OrderByDescending(e => e.Id).Page(Math.Max(0, filter.Offset), Math.Clamp(filter.Limit, 1, 500)),
cancellationToken).ConfigureAwait(false)).Items;
var names = await PartyNamesAsync(uow, page.Select(e => e.PartyId), cancellationToken).ConfigureAwait(false);
return ([.. page.Select(e => new EntryRow(e, e.PartyId is { } p && names.TryGetValue(p, out var n) ? n : null))], total);
}
/// <summary>An entry with its lines.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The entry.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The entry, or none.</returns>
public async Task<EntryView?> GetAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return await ViewAsync(uow, id, cancellationToken).ConfigureAwait(false);
}
/// <summary>The journal templates with their lines, for the guided entry.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The active templates, by code.</returns>
public async Task<IReadOnlyList<TemplateView>> TemplatesAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var templates = (await uow.Repository<JournalTemplate, long>().ListAsync(Query.For<JournalTemplate>().Where(t => !t.Disabled).OrderBy(t => t.Code), cancellationToken)
.ConfigureAwait(false)).Items;
var lines = (await uow.Repository<JournalTemplateLine, long>().ListAsync(Query.For<JournalTemplateLine>().OrderBy(l => l.SortOrder), cancellationToken).ConfigureAwait(false)).Items;
return [.. templates.Select(t => new TemplateView(t, [.. lines.Where(l => l.JournalTemplateId == t.Id)]))];
}
/// <summary>
/// Saves an entry typed in the journal: a draft may not balance, a posted entry must and gets its number. Final
/// entries and entries of documents cannot change.
/// </summary>
/// <param name="actor">Who writes.</param>
/// <param name="companyCode">The company.</param>
/// <param name="input">The entry.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The entry as saved.</returns>
public async Task<EntryView> SaveAsync(Actor actor, string companyCode, EntryInput input, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(input);
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryWrite, cancellationToken).ConfigureAwait(false);
if (input.EntryDate == default)
{
throw new ValidationFailedException(["EntryDate:" + LedgerErrors.DateRequired]);
}
if (input.Post)
{
await _fiscal.DemandOpenAsync(company, input.EntryDate, input.Vat.Count > 0 ? PeriodUse.Vat : PeriodUse.NoVat, cancellationToken).ConfigureAwait(false);
}
long id;
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var entries = uow.Repository<GlEntry, long>();
GlEntry? before = null;
if (input.Id is { } existingId)
{
before = await entries.GetAsync(existingId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
if (before.Status == GlEntryStatus.Final)
{
throw new ValidationFailedException(["Status:" + LedgerErrors.Final]);
}
if (before.Source == GlEntrySource.Document)
{
throw new ValidationFailedException(["Source:" + LedgerErrors.FromDocument]);
}
}
var accounts = await LedgerStore.AccountsAsync(uow, cancellationToken).ConfigureAwait(false);
var lines = input.Lines.Where(l => l.AccountId is not null || l.Debit != 0m || l.Credit != 0m).ToList();
var errors = JournalEntryValidator.Check(
input.Description,
[.. lines.Select(l => new EntryLineCheck(l.AccountId, l.PartyId, l.Debit, l.Credit))],
input.Vat.Count,
input.VatRegisterId is not null,
LedgerStore.Rules(accounts),
input.Post).ToList();
if (input.Post)
{
await CheckFinalOrderAsync(uow, input.EntryDate, errors, cancellationToken).ConfigureAwait(false);
}
if (errors.Count > 0)
{
throw new ValidationFailedException(errors);
}
var template = input.JournalTemplateId is { } templateId
? await uow.Repository<JournalTemplate, long>().GetAsync(templateId, cancellationToken).ConfigureAwait(false)
: null;
var entry = before is null ? new GlEntry { Source = GlEntrySource.Manual } : Clone(before);
entry.EntryDate = input.EntryDate;
entry.CompetenceDate = input.CompetenceDate;
entry.JournalTemplateId = template?.Id;
entry.TemplateCode = template?.Code;
entry.Description = LedgerStore.Trim(input.Description.Trim(), 200)!;
entry.DocumentNumber = LedgerStore.Trim(input.DocumentNumber, 30);
entry.DocumentDate = input.DocumentDate;
entry.PartyId = input.PartyId;
entry.VatRegisterId = input.VatRegisterId;
entry.VatDate = input.VatRegisterId is null ? null : input.VatDate ?? input.EntryDate;
entry.Notes = LedgerStore.Trim(input.Notes, 500);
entry.Status = input.Post ? GlEntryStatus.Posted : before?.Status ?? GlEntryStatus.Draft;
if (before is not null && before.Number is not null && before.Year != input.EntryDate.Year)
{
entry.Number = null;
entry.EntryNumber = null;
}
if (before is null)
{
entry = await LedgerStore.InsertAsync(uow, entry, lines, input.Vat, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Insert, entry.Id, null, entry, actor.UserName, cancellationToken).ConfigureAwait(false);
}
else
{
await LedgerStore.UpdateAsync(uow, entry, lines, input.Vat, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, entry.Id, before, entry, actor.UserName, cancellationToken).ConfigureAwait(false);
}
id = entry.Id;
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
return await GetAsync(actor, company, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
}
/// <summary>Removes an entry that is not final and does not come from a document.</summary>
/// <param name="actor">Who removes it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The entry.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task DeleteAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryWrite, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var entry = await uow.Repository<GlEntry, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
if (entry.Status == GlEntryStatus.Final)
{
throw new ValidationFailedException(["Status:" + LedgerErrors.Final]);
}
if (entry.Source == GlEntrySource.Document)
{
throw new ValidationFailedException(["Source:" + LedgerErrors.FromDocument]);
}
await uow.ExecuteAsync(SqlFragment.Of($"UPDATE gl_recurring_entries SET last_entry_id = NULL WHERE last_entry_id = {id}"), cancellationToken).ConfigureAwait(false);
if (await uow.Repository<RecurringEntry, long>().CountAsync(Query.For<RecurringEntry>().Where(r => r.ModelEntryId == id), cancellationToken).ConfigureAwait(false) > 0)
{
throw new ValidationFailedException(["Id:" + LedgerErrors.RecurringModel]);
}
await LedgerStore.DeleteAsync(uow, id, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Delete, id, entry, (GlEntry?)null, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Reverses an entry (storno): a new posted entry with the same lines on the other side and the VAT with the
/// opposite sign; the open items of the entry not yet settled are removed.
/// </summary>
/// <param name="actor">Who reverses.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The entry.</param>
/// <param name="date">The date of the reversal.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The reversal.</returns>
public async Task<EntryView> ReverseAsync(Actor actor, string companyCode, long id, DateOnly date, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryWrite, cancellationToken).ConfigureAwait(false);
await _fiscal.DemandOpenAsync(company, date, PeriodUse.NoVat, cancellationToken).ConfigureAwait(false);
long reversalId;
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var entry = await uow.Repository<GlEntry, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
if (entry.Source == GlEntrySource.Document && entry.Status != GlEntryStatus.Final)
{
throw new ValidationFailedException(["Source:" + LedgerErrors.FromDocument]);
}
var reversal = await ReverseAsync(uow, entry, date, actor.UserName, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Insert, reversal.Id, null, reversal, actor.UserName, cancellationToken).ConfigureAwait(false);
reversalId = reversal.Id;
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
return await GetAsync(actor, company, reversalId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
}
/// <summary>
/// Makes final the posted entries up to a day (stampa definitiva del libro giornale): in date order each gets the
/// next number of the journal of its fiscal year, then never changes again.
/// </summary>
/// <param name="actor">Who does it: needs <c>ledger.entry.finalize</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="upTo">The last day.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>How many entries became final.</returns>
public async Task<int> FinalizeAsync(Actor actor, string companyCode, DateOnly upTo, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryFinalize, cancellationToken).ConfigureAwait(false);
var done = 0;
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var drafts = await uow.Repository<GlEntry, long>().CountAsync(
Query.For<GlEntry>().Where(e => e.Status == GlEntryStatus.Draft && e.EntryDate <= upTo), cancellationToken).ConfigureAwait(false);
if (drafts > 0)
{
throw new ValidationFailedException(["UpTo:" + LedgerErrors.DraftsBeforeFinal]);
}
var entries = (await uow.Repository<GlEntry, long>().ListAsync(
Query.For<GlEntry>().Where(e => e.Status == GlEntryStatus.Posted && e.EntryDate <= upTo).OrderBy(e => e.EntryDate).OrderBy(e => e.Number).OrderBy(e => e.Id),
cancellationToken).ConfigureAwait(false)).Items;
var years = (await uow.Repository<FiscalYear, long>().ListAsync(Query.For<FiscalYear>(), cancellationToken).ConfigureAwait(false)).Items;
var now = _clock.GetUtcNow().UtcDateTime;
foreach (var entry in entries)
{
var year = years.FirstOrDefault(y => y.StartDate <= entry.EntryDate && y.EndDate >= entry.EntryDate)
?? throw new ValidationFailedException(["UpTo:" + LedgerErrors.NoFiscalYear]);
year.LastFinalEntryNumber++;
year.LastFinalEntryDate = entry.EntryDate;
entry.JournalNumber = year.LastFinalEntryNumber;
entry.FinalizedAt = now;
entry.FinalizedBy = actor.UserName;
await LedgerStore.SetStatusAsync(uow, entry, GlEntryStatus.Final, cancellationToken).ConfigureAwait(false);
done++;
}
foreach (var year in years.Where(y => entries.Any(e => y.StartDate <= e.EntryDate && y.EndDate >= e.EntryDate)))
{
await uow.Repository<FiscalYear, long>().UpdateAsync(year, cancellationToken).ConfigureAwait(false);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
await _fiscal.InvalidateAsync(company, cancellationToken).ConfigureAwait(false);
return done;
}
/// <summary>Posts a draft: it must balance.</summary>
/// <param name="actor">Who posts.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The entry.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The entry as posted.</returns>
public async Task<EntryView> PostAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
var view = await GetAsync(actor, companyCode, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
var e = view.Entry;
return await SaveAsync(actor, companyCode, new EntryInput(e.Id, e.EntryDate, e.Description, [.. view.Lines.Select(Draft)])
{
JournalTemplateId = e.JournalTemplateId,
CompetenceDate = e.CompetenceDate,
DocumentNumber = e.DocumentNumber,
DocumentDate = e.DocumentDate,
PartyId = e.PartyId,
VatRegisterId = e.VatRegisterId,
VatDate = e.VatDate,
Vat = [.. view.Vat.Select(Draft)],
Notes = e.Notes,
Post = true,
}, cancellationToken).ConfigureAwait(false);
}
/// <summary>A line of an entry as a draft line.</summary>
/// <param name="line">The line.</param>
/// <returns>The draft.</returns>
public static EntryLineDraft Draft(GlEntryLine line)
{
ArgumentNullException.ThrowIfNull(line);
return new EntryLineDraft(line.AccountId, line.PartyId, line.Description, line.Debit, line.Credit, line.CostCenterId, line.JobId);
}
/// <summary>A VAT line of an entry as a draft line.</summary>
/// <param name="line">The line.</param>
/// <returns>The draft.</returns>
public static EntryVatDraft Draft(GlEntryVat line)
{
ArgumentNullException.ThrowIfNull(line);
return new EntryVatDraft(line.TaxCodeId, line.Rate, line.Nature, line.Taxable, line.Tax, line.NonDeductibleTax, line.Exigibility, line.VatRegisterId);
}
/// <summary>Writes the reversal of an entry in the open transaction.</summary>
internal static async Task<GlEntry> ReverseAsync(IUnitOfWork uow, GlEntry entry, DateOnly date, string? userName, CancellationToken cancellationToken)
{
if (entry.ReversedById is not null)
{
throw new ValidationFailedException(["Id:" + LedgerErrors.AlreadyReversed]);
}
if (entry.Status == GlEntryStatus.Draft)
{
throw new ValidationFailedException(["Status:" + LedgerErrors.NotPosted]);
}
var lines = await LedgerStore.LinesAsync(uow, entry.Id, cancellationToken).ConfigureAwait(false);
var vat = await LedgerStore.VatAsync(uow, entry.Id, cancellationToken).ConfigureAwait(false);
var reversal = new GlEntry
{
EntryDate = date < entry.EntryDate ? entry.EntryDate : date,
JournalTemplateId = entry.JournalTemplateId,
TemplateCode = entry.TemplateCode,
Description = LedgerStore.Trim("Storno " + (entry.EntryNumber ?? string.Empty) + " " + entry.Description, 200)!,
Status = GlEntryStatus.Posted,
Source = GlEntrySource.Reversal,
SourceFamily = entry.SourceFamily,
SourceDocumentId = entry.SourceDocumentId,
SourceKind = entry.SourceKind,
DocumentNumber = entry.DocumentNumber,
DocumentDate = entry.DocumentDate,
PartyId = entry.PartyId,
VatRegisterId = entry.VatRegisterId,
VatProtocol = entry.VatProtocol,
VatDate = date < entry.EntryDate ? entry.VatDate : date,
ReversalOfId = entry.Id,
IsDemo = entry.IsDemo,
Notes = userName is null ? null : "Storno di " + userName,
};
reversal = await LedgerStore.InsertAsync(
uow,
reversal,
[.. lines.Select(l => new EntryLineDraft(l.AccountId, l.PartyId, l.Description, l.Credit, l.Debit, l.CostCenterId, l.JobId))],
[.. vat.Select(v => new EntryVatDraft(v.TaxCodeId, v.Rate, v.Nature, -v.Taxable, -v.Tax, -v.NonDeductibleTax, v.Exigibility, v.VatRegisterId))],
cancellationToken).ConfigureAwait(false);
entry.ReversedById = reversal.Id;
await uow.Repository<GlEntry, long>().UpdateAsync(entry, cancellationToken).ConfigureAwait(false);
await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM gl_open_items WHERE entry_id = {entry.Id} AND paid_amount = 0"), cancellationToken).ConfigureAwait(false);
return reversal;
}
internal static async Task<EntryView?> ViewAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken)
{
if (await uow.Repository<GlEntry, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } entry)
{
return null;
}
var lines = await LedgerStore.LinesAsync(uow, id, cancellationToken).ConfigureAwait(false);
var vat = await LedgerStore.VatAsync(uow, id, cancellationToken).ConfigureAwait(false);
var names = await PartyNamesAsync(uow, [entry.PartyId], cancellationToken).ConfigureAwait(false);
return new EntryView(entry, lines, vat, entry.PartyId is { } p && names.TryGetValue(p, out var name) ? name : null);
}
internal static async Task<Dictionary<long, string>> PartyNamesAsync(IUnitOfWork uow, IEnumerable<long?> ids, CancellationToken cancellationToken)
{
var list = ids.Where(i => i is not null).Select(i => i!.Value).Distinct().ToList();
if (list.Count == 0)
{
return [];
}
return (await uow.Repository<Party, long>().ListAsync(Query.For<Party>().Where(p => list.Contains(p.Id)), cancellationToken).ConfigureAwait(false)).Items
.ToDictionary(p => p.Id, p => p.Name);
}
private static async Task CheckFinalOrderAsync(IUnitOfWork uow, DateOnly date, List<string> errors, CancellationToken cancellationToken)
{
var year = await uow.Repository<FiscalYear, long>().FindAsync(
Query.For<FiscalYear>().Where(y => y.StartDate <= date && y.EndDate >= date), cancellationToken).ConfigureAwait(false);
if (year?.LastFinalEntryDate is { } last && date < last)
{
errors.Add("EntryDate:" + LedgerErrors.FinalOrder);
}
}
private static GlEntry Clone(GlEntry entry) => new()
{
Id = entry.Id,
Year = entry.Year,
Number = entry.Number,
EntryNumber = entry.EntryNumber,
JournalNumber = entry.JournalNumber,
EntryDate = entry.EntryDate,
Description = entry.Description,
Status = entry.Status,
Source = entry.Source,
IsDemo = entry.IsDemo,
RowVersion = entry.RowVersion,
CreatedAt = entry.CreatedAt,
CreatedBy = entry.CreatedBy,
UpdatedAt = entry.UpdatedAt,
UpdatedBy = entry.UpdatedBy,
};
}
@@ -0,0 +1,448 @@
using Khaemhat.Application.Documents;
using Khaemhat.Application.Licensing;
using Khaemhat.Application.Modules;
using Khaemhat.Application.Security;
using Khaemhat.Core.Accounting;
using Khaemhat.Core.Documents;
using Khaemhat.Core.Items;
using Khaemhat.Core.Parties;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Ledger;
/// <summary>
/// Posts the documents to the ledger (SPEC §11.7, issue #64, ADR 0037) inside the transaction of the document engine,
/// like <see cref="Inventory.InventoryPoster"/> does with the warehouse: an invoice, credit note or self-invoice in
/// force writes its entry (with the VAT lines of its register, the open items of its installments and its
/// withholding); a change writes it again with the same number; a cancelled document loses it, or gets a reversal when
/// its entry is already final. Nothing is posted while the module ACCT is not licensed: the documents can be posted
/// later in bulk (<see cref="LedgerService.PostPendingAsync"/>).
/// </summary>
public sealed class LedgerPoster
{
private readonly ILicenseGate _licence;
/// <summary>Creates the poster.</summary>
/// <param name="licence">The licence (module ACCT).</param>
public LedgerPoster(ILicenseGate licence)
{
ArgumentNullException.ThrowIfNull(licence);
_licence = licence;
}
/// <summary>Whether the documents post to the ledger.</summary>
public bool Active => _licence.IsModuleActive(ModuleCodes.Accounting);
/// <summary>What a kind of document posts, if anything.</summary>
/// <param name="kind">The kind.</param>
/// <returns>The posting kind and whether the sides are reversed, or <see langword="null"/>.</returns>
public static (PostingKind Kind, bool Reverse)? PostingOf(DocumentKind kind) => kind switch
{
DocumentKind.ImmediateInvoice or DocumentKind.AccompanyingInvoice or DocumentKind.DeferredInvoice or DocumentKind.DownPaymentInvoice
or DocumentKind.DebitNote or DocumentKind.Fee => (PostingKind.Sale, false),
DocumentKind.CreditNote => (PostingKind.Sale, true),
DocumentKind.SelfInvoice => (PostingKind.SelfInvoice, false),
DocumentKind.PurchaseInvoice => (PostingKind.Purchase, false),
DocumentKind.PurchaseCreditNote => (PostingKind.Purchase, true),
_ => null,
};
/// <summary>Writes again the entry of a document from its current state.</summary>
/// <param name="uow">The unit of work of the company, in a transaction.</param>
/// <param name="family">The family.</param>
/// <param name="documentId">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The entry, or <see langword="null"/> when the document posts nothing.</returns>
public async Task<GlEntry?> SyncAsync(IUnitOfWork uow, DocumentFamily family, long documentId, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(uow);
if (!Active || family is not (DocumentFamily.SaleDocument or DocumentFamily.PurchaseDocument))
{
return null;
}
return await PostAsync(uow, family, documentId, cancellationToken).ConfigureAwait(false);
}
/// <summary>Posts or removes the entry of a document whatever the licence (bulk posting, tests).</summary>
/// <param name="uow">The unit of work of the company, in a transaction.</param>
/// <param name="family">The family.</param>
/// <param name="documentId">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The entry, or <see langword="null"/>.</returns>
internal static async Task<GlEntry?> PostAsync(IUnitOfWork uow, DocumentFamily family, long documentId, CancellationToken cancellationToken)
{
var store = DocumentStores.Of(family);
var header = await store.GetAsync(uow, documentId, cancellationToken).ConfigureAwait(false);
var existing = await CurrentEntryAsync(uow, family, documentId, cancellationToken).ConfigureAwait(false);
var posting = header is null ? null : PostingOf(header.Kind);
if (header is null || posting is null || !DocumentStateMachine.IsInForce(header.Status))
{
await RemoveAsync(uow, existing, cancellationToken).ConfigureAwait(false);
await RemoveWithholdingsAsync(uow, family, documentId, cancellationToken).ConfigureAwait(false);
if (header is not null && (header.Posted || header.GlEntryId is not null))
{
header.Posted = false;
header.GlEntryId = null;
await store.UpdateAsync(uow, header, cancellationToken).ConfigureAwait(false);
}
return null;
}
var built = await BuildAsync(uow, family, header, posting.Value, cancellationToken).ConfigureAwait(false);
if (built is null)
{
return null;
}
var (entry, lines, vat) = built.Value;
GlEntry result;
if (existing is null)
{
result = await LedgerStore.InsertAsync(uow, entry, lines, vat, cancellationToken).ConfigureAwait(false);
}
else if (existing.Status != GlEntryStatus.Final)
{
Copy(entry, existing);
await LedgerStore.UpdateAsync(uow, existing, lines, vat, cancellationToken).ConfigureAwait(false);
await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM gl_open_items WHERE entry_id = {existing.Id}"), cancellationToken).ConfigureAwait(false);
result = existing;
}
else if (await SameAsync(uow, existing, lines, cancellationToken).ConfigureAwait(false))
{
return existing;
}
else
{
// A final entry never changes: the reversal cancels it and a new entry posts the document as it is now.
await JournalEntryService.ReverseAsync(uow, existing, existing.EntryDate, null, cancellationToken).ConfigureAwait(false);
result = await LedgerStore.InsertAsync(uow, entry, lines, vat, cancellationToken).ConfigureAwait(false);
}
await OpenItemsAsync(uow, family, header, posting.Value, result, lines, cancellationToken).ConfigureAwait(false);
await WithholdingAsync(uow, family, header, result, cancellationToken).ConfigureAwait(false);
if (!header.Posted || header.GlEntryId != result.Id)
{
header.Posted = true;
header.GlEntryId = result.Id;
await store.UpdateAsync(uow, header, cancellationToken).ConfigureAwait(false);
}
return result;
}
/// <summary>The entry of a document that is not reversed, if any.</summary>
internal static async Task<GlEntry?> CurrentEntryAsync(IUnitOfWork uow, DocumentFamily family, long documentId, CancellationToken cancellationToken)
{
var entries = (await uow.Repository<GlEntry, long>().ListAsync(
Query.For<GlEntry>().Where(e => e.SourceFamily == family && e.SourceDocumentId == documentId && e.Source == GlEntrySource.Document)
.OrderByDescending(e => e.Id), cancellationToken).ConfigureAwait(false)).Items;
return entries.FirstOrDefault(e => e.ReversedById is null);
}
private static async Task RemoveAsync(IUnitOfWork uow, GlEntry? existing, CancellationToken cancellationToken)
{
if (existing is null)
{
return;
}
if (existing.Status == GlEntryStatus.Final)
{
await JournalEntryService.ReverseAsync(uow, existing, existing.EntryDate, null, cancellationToken).ConfigureAwait(false);
}
else
{
await LedgerStore.DeleteAsync(uow, existing.Id, cancellationToken).ConfigureAwait(false);
}
}
private static async Task RemoveWithholdingsAsync(IUnitOfWork uow, DocumentFamily family, long documentId, CancellationToken cancellationToken)
{
var waiting = nameof(WithholdingStatus.Waiting);
var suffered = nameof(WithholdingStatus.Suffered);
var text = family.ToString();
await uow.ExecuteAsync(
SqlFragment.Of($"DELETE FROM withholdings WHERE source_family = {text} AND source_document_id = {documentId} AND status IN ({waiting}, {suffered})"),
cancellationToken).ConfigureAwait(false);
}
private static void Copy(GlEntry from, GlEntry to)
{
to.EntryDate = from.EntryDate;
to.JournalTemplateId = from.JournalTemplateId;
to.TemplateCode = from.TemplateCode;
to.Description = from.Description;
to.SourceKind = from.SourceKind;
to.DocumentNumber = from.DocumentNumber;
to.DocumentDate = from.DocumentDate;
to.PartyId = from.PartyId;
to.VatRegisterId = from.VatRegisterId;
to.VatProtocol = from.VatProtocol;
to.VatDate = from.VatDate;
to.IsDemo = from.IsDemo;
if (to.Year != from.EntryDate.Year)
{
// A new year means a new number.
to.Number = null;
to.EntryNumber = null;
}
}
private static async Task<bool> SameAsync(IUnitOfWork uow, GlEntry existing, IReadOnlyList<EntryLineDraft> lines, CancellationToken cancellationToken)
{
var stored = await LedgerStore.LinesAsync(uow, existing.Id, cancellationToken).ConfigureAwait(false);
static string Key(long? account, long? party, decimal debit, decimal credit) => $"{account}|{party}|{debit:0.00}|{credit:0.00}";
var left = stored.Select(l => Key(l.AccountId, l.PartyId, l.Debit, l.Credit)).Order(StringComparer.Ordinal);
var right = lines.Select(l => Key(l.AccountId, l.PartyId, l.Debit, l.Credit)).Order(StringComparer.Ordinal);
return left.SequenceEqual(right, StringComparer.Ordinal);
}
private static async Task<(GlEntry Entry, List<EntryLineDraft> Lines, List<EntryVatDraft> Vat)?> BuildAsync(
IUnitOfWork uow, DocumentFamily family, DocumentHeader header, (PostingKind Kind, bool Reverse) posting, CancellationToken cancellationToken)
{
var type = await uow.Repository<DocumentType, long>().GetAsync(header.DocumentTypeId, cancellationToken).ConfigureAwait(false);
var templateCode = type?.JournalTemplateCode ?? DefaultTemplate(posting);
if (await LedgerStore.TemplateAsync(uow, templateCode, cancellationToken).ConfigureAwait(false) is not { } found)
{
return null;
}
var (template, templateLines) = found;
PartyPurchaseTerms? purchaseTerms = null;
if (posting.Kind == PostingKind.Purchase && header.PartyId is { } supplierId)
{
purchaseTerms = await uow.Repository<PartyPurchaseTerms, long>().FindAsync(
Query.For<PartyPurchaseTerms>().Where(t => t.PartyId == supplierId), cancellationToken).ConfigureAwait(false);
}
var registerCode = purchaseTerms?.VatRegisterCode ?? type?.VatRegisterCode ?? template.VatRegisterCode;
var register = await LedgerStore.RegisterAsync(uow, registerCode, cancellationToken).ConfigureAwait(false);
var accounts = (await uow.Repository<GlAccount, long>().ListAsync(Query.For<GlAccount>(), cancellationToken).ConfigureAwait(false)).Items;
var byCode = accounts.ToDictionary(a => a.Code, StringComparer.Ordinal);
long? Of(string? code) => code is not null && byCode.TryGetValue(code, out var account) && account.Postable ? account.Id : null;
long? Role(PostingRole role) => templateLines.FirstOrDefault(l => l.Role == role && l.AccountId is not null)?.AccountId;
var party = header.PartyId is { } partyId ? await uow.Repository<Party, long>().GetAsync(partyId, cancellationToken).ConfigureAwait(false) : null;
var record = await DocumentEngine.LoadAsync(uow, family, header.Id, cancellationToken).ConfigureAwait(false);
if (record is null)
{
return null;
}
var sale = posting.Kind == PostingKind.Sale;
var items = await ItemsAsync(uow, record.Lines, cancellationToken).ConfigureAwait(false);
var taxCodes = (await uow.Repository<TaxCode, long>().ListAsync(Query.For<TaxCode>(), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(t => t.Id);
var inputLines = new List<PostingLineInput>();
foreach (var line in record.Lines.Where(l => l.Kind != DocumentLineKind.Description && l.TaxableAmount != 0m))
{
var item = line.ItemId is { } itemId && items.TryGetValue(itemId, out var found2) ? found2 : null;
var tax = line.TaxCodeId is { } taxId && taxCodes.TryGetValue(taxId, out var code) ? code : null;
var account = Of(line.AccountCode)
?? Of(sale ? item?.RevenueAccountCode : item?.CostAccountCode)
?? Of(purchaseTerms?.CostAccountCode)
?? Of(sale ? tax?.SalesAccountCode : tax?.PurchaseAccountCode);
inputLines.Add(new PostingLineInput(account, line.TaxableAmount, line.TaxCodeId, line.CostCenterId, line.JobId));
}
var taxes = record.Figures.Summary
.Select(s => new PostingTaxInput(s.TaxCodeId, s.Rate, s.Nature, s.Exigibility, s.Taxable, s.Tax, s.NonDeductibleTax))
.ToList();
var stamp = header.StampDutyCharged ? header.StampDuty : 0m;
var total = taxes.Sum(t => t.Taxable) + taxes.Sum(t => t.Tax) + stamp;
var partyAccount = posting.Kind switch
{
PostingKind.Sale => Of(party?.CustomerAccountCode) ?? Role(PostingRole.Customer),
PostingKind.Purchase => Of(party?.SupplierAccountCode) ?? Role(PostingRole.Supplier),
_ => null,
};
var accountsOfPosting = new PostingAccounts(
partyAccount,
Role(sale ? PostingRole.Revenue : PostingRole.Cost),
Role(PostingRole.SalesVat),
Role(PostingRole.PurchaseVat),
Role(PostingRole.StampDuty),
Role(PostingRole.SocialSecurity));
PostingResult result;
try
{
result = PostingEngine.Post(
new PostingInput(posting.Kind, posting.Reverse, header.PartyId, inputLines, taxes, total, stamp, sale ? header.SocialSecurityAmount : 0m),
accountsOfPosting);
}
catch (PostingAccountMissingException exception)
{
throw new ValidationFailedException("Ledger:" + LedgerErrors.RoleAccountMissing, exception);
}
if (result.Vat.Count > 0 && register is null)
{
throw new ValidationFailedException(["VatRegisterId:" + LedgerErrors.VatRegisterRequired]);
}
// A self-invoice is annotated also in the purchase register of reverse charge (double annotation, §11.5).
VatRegister? purchaseRegister = null;
if (posting.Kind == PostingKind.SelfInvoice)
{
var registers = (await uow.Repository<VatRegister, long>().ListAsync(Query.For<VatRegister>(), cancellationToken).ConfigureAwait(false)).Items;
purchaseRegister = registers.FirstOrDefault(r => r.Kind == VatRegisterKind.Purchases && r.ReverseCharge && !r.Disabled)
?? registers.FirstOrDefault(r => r.Kind == VatRegisterKind.Purchases && !r.Disabled);
}
var purchase = family == DocumentFamily.PurchaseDocument;
var documentNumber = purchase ? header.ExternalReference ?? header.DocumentNumber : header.DocumentNumber;
var documentDate = purchase ? header.ExternalDate ?? header.DocumentDate : header.DocumentDate;
var entryDate = purchase ? header.VatDate ?? header.DocumentDate : header.DocumentDate;
var entry = new GlEntry
{
EntryDate = entryDate,
JournalTemplateId = template.Id,
TemplateCode = template.Code,
Description = LedgerStore.Trim(Describe(template.Description, documentNumber, documentDate, party), 200)!,
Status = GlEntryStatus.Posted,
Source = GlEntrySource.Document,
SourceFamily = family,
SourceDocumentId = header.Id,
SourceKind = header.Kind,
DocumentNumber = LedgerStore.Trim(documentNumber, 30),
DocumentDate = documentDate,
PartyId = header.PartyId,
VatRegisterId = result.Vat.Count > 0 ? register?.Id : null,
VatProtocol = purchase ? header.VatProtocol ?? header.Number : header.Number,
VatDate = header.VatDate ?? entryDate,
IsDemo = header.IsDemo,
};
var description = LedgerStore.Trim(documentNumber is null ? template.Description : template.Description + " " + documentNumber, 200);
var lines = result.Lines
.Select(l => new EntryLineDraft(l.AccountId, l.PartyId, description, l.Debit, l.Credit, l.CostCenterId, l.JobId))
.ToList();
var vat = result.Vat
.Select(v => new EntryVatDraft(
v.Tax.TaxCodeId, v.Tax.Rate, v.Tax.Nature, v.Tax.Taxable, v.Tax.Tax, v.Tax.NonDeductibleTax, v.Tax.Exigibility,
v.RegisterKind == VatRegisterKind.Purchases && purchaseRegister is not null ? purchaseRegister.Id : register?.Id))
.ToList();
return (entry, lines, vat);
}
private static string DefaultTemplate((PostingKind Kind, bool Reverse) posting) => posting switch
{
(PostingKind.Sale, false) => "FV",
(PostingKind.Sale, true) => "NCV",
(PostingKind.Purchase, false) => "FA",
(PostingKind.Purchase, true) => "NCA",
_ => "AFRC",
};
private static string Describe(string template, string? number, DateOnly date, Party? party)
{
var text = template;
if (number is not null)
{
text += " n. " + number;
}
text += " del " + date.ToString("dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
if (party is not null)
{
text += " - " + party.Name;
}
return text;
}
private static async Task<Dictionary<long, Item>> ItemsAsync(IUnitOfWork uow, IReadOnlyList<DocumentLine> lines, CancellationToken cancellationToken)
{
var ids = lines.Where(l => l.ItemId is not null).Select(l => l.ItemId!.Value).Distinct().ToList();
if (ids.Count == 0)
{
return [];
}
return (await uow.Repository<Item, long>().ListAsync(Query.For<Item>().Where(i => ids.Contains(i.Id)), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(i => i.Id);
}
private static async Task OpenItemsAsync(
IUnitOfWork uow, DocumentFamily family, DocumentHeader header, (PostingKind Kind, bool Reverse) posting, GlEntry entry,
IReadOnlyList<EntryLineDraft> lines, CancellationToken cancellationToken)
{
if (posting.Kind == PostingKind.SelfInvoice || header.PartyId is not { } partyId)
{
return;
}
var partyLine = lines.FirstOrDefault(l => l.PartyId == partyId);
if (partyLine?.AccountId is not { } accountId)
{
return;
}
var installments = (await uow.Repository<DocumentInstallment, long>().ListAsync(
Query.For<DocumentInstallment>().Where(i => i.Family == family && i.DocumentId == header.Id).OrderBy(i => i.Number), cancellationToken).ConfigureAwait(false)).Items;
var sign = posting.Reverse ? -1m : 1m;
var rows = installments.Count > 0
? installments.Select(i => (i.Number, i.DueDate, i.Amount, i.PaymentMethodId)).ToList()
: [(1, header.DocumentDate, header.NetAmount != 0m ? header.NetAmount : header.TotalAmount, header.PaymentMethodId)];
var repository = uow.Repository<OpenItem, long>();
foreach (var (number, due, amount, method) in rows)
{
await repository.InsertAsync(new OpenItem
{
Direction = posting.Kind == PostingKind.Sale ? OpenItemDirection.Receivable : OpenItemDirection.Payable,
PartyId = partyId,
AccountId = accountId,
EntryId = entry.Id,
SourceFamily = family,
SourceDocumentId = header.Id,
DocumentNumber = entry.DocumentNumber,
DocumentDate = entry.DocumentDate ?? header.DocumentDate,
Installment = number,
DueDate = due,
Amount = sign * amount,
PaymentMethodId = method,
IsDemo = header.IsDemo,
}, cancellationToken).ConfigureAwait(false);
}
}
private static async Task WithholdingAsync(IUnitOfWork uow, DocumentFamily family, DocumentHeader header, GlEntry entry, CancellationToken cancellationToken)
{
await RemoveWithholdingsAsync(uow, family, header.Id, cancellationToken).ConfigureAwait(false);
if (header.WithholdingAmount == 0m || header.PartyId is not { } partyId)
{
return;
}
var existing = await uow.Repository<Withholding, long>().CountAsync(
Query.For<Withholding>().Where(w => w.SourceFamily == family && w.SourceDocumentId == header.Id), cancellationToken).ConfigureAwait(false);
if (existing > 0)
{
// Already due or paid: the payment stays as it was.
return;
}
var operated = family == DocumentFamily.PurchaseDocument;
var sign = header.Kind is DocumentKind.CreditNote or DocumentKind.PurchaseCreditNote ? -1m : 1m;
await uow.Repository<Withholding, long>().InsertAsync(new Withholding
{
Direction = operated ? WithholdingDirection.Operated : WithholdingDirection.Suffered,
SourceFamily = family,
SourceDocumentId = header.Id,
DocumentNumber = entry.DocumentNumber,
DocumentDate = entry.DocumentDate ?? header.DocumentDate,
PartyId = partyId,
WithholdingType = header.WithholdingType,
Reason = header.WithholdingReason,
Taxable = sign * (header.TaxableAmount - header.SocialSecurityAmount),
SocialSecurityFund = header.SocialSecurityFund,
SocialSecurityAmount = sign * header.SocialSecurityAmount,
Rate = header.WithholdingRate ?? 0m,
BasePercent = header.WithholdingBasePercent,
Amount = sign * header.WithholdingAmount,
Status = operated ? WithholdingStatus.Waiting : WithholdingStatus.Suffered,
IsDemo = header.IsDemo,
}, cancellationToken).ConfigureAwait(false);
}
}
@@ -0,0 +1,436 @@
using System.Globalization;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Accounting;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Ledger;
/// <summary>A movement of an account (or of a party on an account), with the running balance.</summary>
/// <param name="EntryId">The entry, for the drill-down.</param>
/// <param name="EntryNumber">The number of the entry.</param>
/// <param name="EntryDate">The date.</param>
/// <param name="Description">The description of the line, or of the entry.</param>
/// <param name="DocumentNumber">The number of the document.</param>
/// <param name="DocumentDate">The date of the document.</param>
/// <param name="TemplateCode">The journal template.</param>
/// <param name="AccountCode">The account (when the view is of a party).</param>
/// <param name="Debit">The debit.</param>
/// <param name="Credit">The credit.</param>
/// <param name="Balance">The balance after the movement, debit positive.</param>
/// <param name="Status">The state of the entry.</param>
public sealed record LedgerMovement(
long EntryId, string? EntryNumber, DateOnly EntryDate, string? Description, string? DocumentNumber, DateOnly? DocumentDate, string? TemplateCode, string? AccountCode,
decimal Debit, decimal Credit, decimal Balance, GlEntryStatus Status);
/// <summary>A page of the movements of an account or a party.</summary>
/// <param name="Opening">The balance before the period.</param>
/// <param name="Movements">The movements of the page.</param>
/// <param name="TotalCount">How many movements the period has.</param>
/// <param name="TotalDebit">The debits of the period.</param>
/// <param name="TotalCredit">The credits of the period.</param>
/// <param name="Closing">The balance at the end of the period.</param>
public sealed record LedgerPage(decimal Opening, IReadOnlyList<LedgerMovement> Movements, long TotalCount, decimal TotalDebit, decimal TotalCredit, decimal Closing);
/// <summary>What the movements are asked for.</summary>
/// <param name="AccountId">The account; with <paramref name="PartyId"/>, its sub-ledger.</param>
/// <param name="PartyId">The customer or supplier (partitario, estratto conto).</param>
/// <param name="From">From this day.</param>
/// <param name="To">Up to this day.</param>
/// <param name="IncludeDrafts">Count the drafts too.</param>
/// <param name="Offset">The first movement of the page.</param>
/// <param name="Limit">The size of the page.</param>
public sealed record LedgerFilter(long? AccountId, long? PartyId, DateOnly From, DateOnly To, bool IncludeDrafts = false, int Offset = 0, int Limit = 50);
/// <summary>A line of the trial balance.</summary>
/// <param name="AccountId">The account.</param>
/// <param name="Code">The code.</param>
/// <param name="Description">The description.</param>
/// <param name="Level">The level (1 mastro, 2 conto, 3 sottoconto).</param>
/// <param name="Nature">The nature.</param>
/// <param name="Opening">The balance before the period.</param>
/// <param name="Debit">The debits of the period.</param>
/// <param name="Credit">The credits of the period.</param>
/// <param name="Closing">The balance at the end, debit positive.</param>
public sealed record TrialBalanceLine(long AccountId, string Code, string Description, int Level, AccountNature Nature, decimal Opening, decimal Debit, decimal Credit, decimal Closing);
/// <summary>The trial balance of a period.</summary>
/// <param name="Lines">The accounts with movements or a balance, with the totals of their parents.</param>
/// <param name="TotalDebit">The debits of the period.</param>
/// <param name="TotalCredit">The credits of the period.</param>
/// <param name="Result">The result of the period (revenues minus costs).</param>
public sealed record TrialBalance(IReadOnlyList<TrialBalanceLine> Lines, decimal TotalDebit, decimal TotalCredit, decimal Result)
{
/// <summary>Whether debits and credits match.</summary>
public bool Balanced => TotalDebit == TotalCredit;
}
/// <summary>A party with a balance on the customer or supplier accounts.</summary>
/// <param name="PartyId">The party.</param>
/// <param name="Name">The name.</param>
/// <param name="Debit">The debits.</param>
/// <param name="Credit">The credits.</param>
/// <param name="Balance">The balance, debit positive.</param>
/// <param name="OpenItems">The open items not closed.</param>
public sealed record PartyBalance(long PartyId, string Name, decimal Debit, decimal Credit, decimal Balance, int OpenItems);
/// <summary>
/// What the ledger tells (SPEC §11.7, issue #67, mockup 044): the movements of an account (mastrino) and of a customer
/// or supplier (partitario, estratto conto) with the running balance and the way to the entry; the open items; the
/// trial balance of a period, by cost center too, with the balances of the parents; the general journal (libro
/// giornale), provisional or as numbered. All the lists are paged in the database.
/// </summary>
public sealed class LedgerQueryService
{
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
/// <summary>Creates the service.</summary>
/// <param name="factory">The units of work.</param>
/// <param name="permissions">The permissions.</param>
public LedgerQueryService(IUnitOfWorkFactory factory, PermissionService permissions)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
_factory = factory;
_permissions = permissions;
}
/// <summary>The movements of an account or of a party in a period, with the running balance.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="filter">The account or party, the period, the page.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The page.</returns>
public async Task<LedgerPage> MovementsAsync(Actor actor, string companyCode, LedgerFilter filter, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(filter);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return await MovementsAsync(uow, filter, cancellationToken).ConfigureAwait(false);
}
/// <summary>The customers or suppliers with their balance on the sub-ledger accounts.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="type">Customers or suppliers.</param>
/// <param name="to">Up to this day.</param>
/// <param name="search">Part of the name.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The parties, by name.</returns>
public async Task<IReadOnlyList<PartyBalance>> PartyBalancesAsync(
Actor actor, string companyCode, AccountType type, DateOnly to, string? search = null, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var draft = nameof(GlEntryStatus.Draft);
var typeText = type.ToString();
var direction = (type == AccountType.Suppliers ? OpenItemDirection.Payable : OpenItemDirection.Receivable).ToString();
var like = "%" + (search ?? string.Empty).Trim().ToUpperInvariant() + "%";
var rows = await uow.QueryAsync<PartyRow>(SqlFragment.Of($"""
SELECT l.party_id AS party_id, p.name AS name, SUM(l.debit) AS debit, SUM(l.credit) AS credit,
(SELECT COUNT(*) FROM gl_open_items o WHERE o.party_id = l.party_id AND o.direction = {direction} AND o.closed = {false}) AS open_items
FROM gl_entry_lines l JOIN gl_accounts a ON a.id = l.account_id JOIN parties p ON p.id = l.party_id
WHERE a.type = {typeText} AND l.status <> {draft} AND l.entry_date <= {to} AND UPPER(p.name) LIKE {like}
GROUP BY l.party_id, p.name
ORDER BY p.name
"""), cancellationToken).ConfigureAwait(false);
return [.. rows.Select(r => new PartyBalance(r.PartyId, r.Name, r.Debit ?? 0m, r.Credit ?? 0m, (r.Debit ?? 0m) - (r.Credit ?? 0m), (int)r.OpenItems))];
}
/// <summary>The open items of a party (or of all), by due date.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="partyId">The party, or <see langword="null"/> for all.</param>
/// <param name="direction">Receivables or payables.</param>
/// <param name="includeClosed">Show the closed items too.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The items.</returns>
public async Task<IReadOnlyList<OpenItem>> OpenItemsAsync(
Actor actor, string companyCode, long? partyId, OpenItemDirection direction, bool includeClosed = false, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var query = Query.For<OpenItem>().Where(o => o.Direction == direction);
if (partyId is { } id)
{
query = query.Where(o => o.PartyId == id);
}
if (!includeClosed)
{
query = query.Where(o => !o.Closed);
}
return (await uow.Repository<OpenItem, long>().ListAsync(query.OrderBy(o => o.DueDate).OrderBy(o => o.Id), cancellationToken).ConfigureAwait(false)).Items;
}
/// <summary>The trial balance of a period (bilancio di verifica), optionally of one cost center.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="from">From this day.</param>
/// <param name="to">Up to this day.</param>
/// <param name="costCenterId">Only the lines of this cost center.</param>
/// <param name="includeDrafts">Count the drafts too.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The trial balance.</returns>
public async Task<TrialBalance> TrialBalanceAsync(
Actor actor, string companyCode, DateOnly from, DateOnly to, long? costCenterId = null, bool includeDrafts = false, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return await TrialBalanceAsync(uow, from, to, costCenterId, includeDrafts, cancellationToken).ConfigureAwait(false);
}
/// <summary>The trial balance as PDF.</summary>
/// <param name="actor">Who prints.</param>
/// <param name="companyCode">The company.</param>
/// <param name="from">From this day.</param>
/// <param name="to">Up to this day.</param>
/// <param name="costCenterId">Only the lines of this cost center.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The file.</returns>
public async Task<LedgerFile> PrintTrialBalanceAsync(Actor actor, string companyCode, DateOnly from, DateOnly to, long? costCenterId = null, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var balance = await TrialBalanceAsync(uow, from, to, costCenterId, includeDrafts: false, cancellationToken).ConfigureAwait(false);
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
var center = costCenterId is { } c ? await uow.Repository<CostCenter, long>().GetAsync(c, cancellationToken).ConfigureAwait(false) : null;
var rows = new List<IReadOnlyList<string?>>();
foreach (var line in balance.Lines)
{
var bold = line.Level < 3 ? "**" : string.Empty;
rows.Add([
bold + line.Code, new string(' ', (line.Level - 1) * 2) + line.Description, LedgerReport.Money(line.Opening), LedgerReport.Money(line.Debit),
LedgerReport.Money(line.Credit), line.Closing > 0m ? LedgerReport.Money(line.Closing) : null, line.Closing < 0m ? LedgerReport.Money(-line.Closing) : null,
]);
}
rows.Add(["**Totali", null, null, LedgerReport.Money(balance.TotalDebit), LedgerReport.Money(balance.TotalCredit), null, null]);
rows.Add(["**Risultato", balance.Result >= 0m ? "Utile del periodo" : "Perdita del periodo", null, null, null, null, LedgerReport.Money(Math.Abs(balance.Result))]);
var (file, _) = await LedgerReport.WriteAsync(
VatService.CompanyLine(profile),
"Bilancio di verifica" + (center is null ? string.Empty : " - centro di costo " + center.Code + " " + center.Description),
"Dal " + LedgerReport.Date(from) + " al " + LedgerReport.Date(to),
[new("Conto", 70), new("Descrizione", 260), new("Saldo iniziale", 85, true), new("Dare", 85, true), new("Avere", 85, true), new("Saldo dare", 85, true),
new("Saldo avere", 85, true)],
rows,
to.Year,
1,
cancellationToken).ConfigureAwait(false);
return new LedgerFile(string.Create(CultureInfo.InvariantCulture, $"bilancio_verifica_{from:yyyyMMdd}_{to:yyyyMMdd}.pdf"), Infrastructure.Files.PdfWriter.MediaType, file);
}
/// <summary>The movements of an account or party as PDF (mastrino, estratto conto).</summary>
/// <param name="actor">Who prints.</param>
/// <param name="companyCode">The company.</param>
/// <param name="filter">The account or party and the period (the page is ignored).</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The file.</returns>
public async Task<LedgerFile> PrintMovementsAsync(Actor actor, string companyCode, LedgerFilter filter, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(filter);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var page = await MovementsAsync(uow, filter with { Offset = 0, Limit = 100_000 }, cancellationToken).ConfigureAwait(false);
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
var account = filter.AccountId is { } a ? await uow.Repository<GlAccount, long>().GetAsync(a, cancellationToken).ConfigureAwait(false) : null;
var party = filter.PartyId is { } p ? await uow.Repository<Core.Parties.Party, long>().GetAsync(p, cancellationToken).ConfigureAwait(false) : null;
var title = party is not null ? "Estratto conto " + party.Name : "Mastrino " + account?.Code + " " + account?.Description;
var rows = new List<IReadOnlyList<string?>> { new[] { "**Saldo iniziale", null, null, null, null, null, Signed(page.Opening) } };
foreach (var m in page.Movements)
{
rows.Add([LedgerReport.Date(m.EntryDate), m.EntryNumber, m.DocumentNumber, m.Description, LedgerReport.Money(m.Debit), LedgerReport.Money(m.Credit), Signed(m.Balance)]);
}
rows.Add(["**Totali", null, null, null, LedgerReport.Money(page.TotalDebit), LedgerReport.Money(page.TotalCredit), Signed(page.Closing)]);
var (file, _) = await LedgerReport.WriteAsync(
VatService.CompanyLine(profile), title, "Dal " + LedgerReport.Date(filter.From) + " al " + LedgerReport.Date(filter.To),
[new("Data", 55), new("Registrazione", 70), new("Documento", 80), new("Descrizione", 300), new("Dare", 80, true), new("Avere", 80, true), new("Saldo", 90, true)],
rows, filter.To.Year, 1, cancellationToken).ConfigureAwait(false);
return new LedgerFile(
string.Create(CultureInfo.InvariantCulture, $"{(party is not null ? "estratto_conto_" + party.Code : "mastrino_" + account?.Code)}_{filter.To:yyyyMMdd}.pdf"),
Infrastructure.Files.PdfWriter.MediaType,
file);
}
/// <summary>
/// The general journal (libro giornale) of a period: every entry in date order with its lines. The provisional
/// print shows the posted entries too; the final one only the final entries, with their journal numbers and the
/// pages numbered from the first page of the year.
/// </summary>
/// <param name="actor">Who prints.</param>
/// <param name="companyCode">The company.</param>
/// <param name="from">From this day.</param>
/// <param name="to">Up to this day.</param>
/// <param name="final">Only the final entries.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The file.</returns>
public async Task<LedgerFile> PrintJournalAsync(Actor actor, string companyCode, DateOnly from, DateOnly to, bool final = false, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
var fiscalYear = await uow.Repository<FiscalYear, long>().FindAsync(Query.For<FiscalYear>().Where(y => y.StartDate <= to && y.EndDate >= to), cancellationToken).ConfigureAwait(false);
var draft = nameof(GlEntryStatus.Draft);
var finalText = nameof(GlEntryStatus.Final);
var condition = final ? SqlFragment.Of($"e.status = {finalText}") : SqlFragment.Of($"e.status <> {draft}");
var lines = await uow.QueryAsync<JournalRow>(SqlFragment.Of($"""
SELECT e.id AS entry_id, e.entry_number AS entry_number, e.journal_number AS journal_number, e.entry_date AS entry_date, e.description AS entry_description,
e.document_number AS document_number, a.code AS account_code, a.description AS account_description, p.name AS party_name,
l.description AS description, l.debit AS debit, l.credit AS credit
FROM gl_entries e JOIN gl_entry_lines l ON l.entry_id = e.id JOIN gl_accounts a ON a.id = l.account_id LEFT JOIN parties p ON p.id = l.party_id
WHERE e.entry_date >= {from} AND e.entry_date <= {to} AND {condition}
ORDER BY e.entry_date, e.journal_number, e.number, e.id, l.line_number
"""), cancellationToken).ConfigureAwait(false);
var rows = new List<IReadOnlyList<string?>>();
long? current = null;
foreach (var line in lines)
{
if (line.EntryId != current)
{
current = line.EntryId;
rows.Add([
"**" + LedgerReport.Date(line.EntryDate), line.JournalNumber?.ToString(CultureInfo.InvariantCulture) ?? line.EntryNumber, null,
line.EntryDescription + (line.DocumentNumber is { Length: > 0 } d ? " - doc. " + d : string.Empty), null, null,
]);
}
rows.Add([null, null, line.AccountCode, line.AccountDescription + (line.PartyName is { Length: > 0 } n ? " - " + n : string.Empty) + (line.Description is { Length: > 0 } t && t != line.EntryDescription ? " (" + t + ")" : string.Empty),
LedgerReport.Money(line.Debit), LedgerReport.Money(line.Credit)]);
}
rows.Add(["**Totali del periodo", null, null, null, LedgerReport.Money(lines.Sum(l => l.Debit)), LedgerReport.Money(lines.Sum(l => l.Credit))]);
var (file, _) = await LedgerReport.WriteAsync(
VatService.CompanyLine(profile),
"Libro giornale",
(final ? "Registrazioni definitive" : "Stampa provvisoria") + " dal " + LedgerReport.Date(from) + " al " + LedgerReport.Date(to),
[new("Data", 60), new("Numero", 65), new("Conto", 65), new("Descrizione", 400), new("Dare", 90, true), new("Avere", 90, true)],
rows,
to.Year,
final ? Math.Max(1, fiscalYear?.JournalFirstPage ?? 1) : 1,
cancellationToken).ConfigureAwait(false);
return new LedgerFile(
string.Create(CultureInfo.InvariantCulture, $"libro_giornale_{from:yyyyMMdd}_{to:yyyyMMdd}{(final ? "_definitivo" : "_provvisorio")}.pdf"),
Infrastructure.Files.PdfWriter.MediaType,
file);
}
/// <summary>The movements of an account or party, paged in the database, with the running balance.</summary>
internal static async Task<LedgerPage> MovementsAsync(IUnitOfWork uow, LedgerFilter filter, CancellationToken cancellationToken)
{
if (filter.AccountId is null && filter.PartyId is null)
{
throw new ValidationFailedException(["AccountId:" + LedgerErrors.AccountRequired]);
}
var where = Condition(filter);
var from = filter.From;
var to = filter.To;
var opening = await uow.QuerySingleAsync<decimal?>(SqlFragment.Of($"SELECT SUM(l.debit - l.credit) FROM gl_entry_lines l WHERE {where} AND l.entry_date < {from}"), cancellationToken)
.ConfigureAwait(false) ?? 0m;
var totals = (await uow.QueryAsync<TotalsRow>(SqlFragment.Of($"""
SELECT COUNT(*) AS lines, SUM(l.debit) AS debit, SUM(l.credit) AS credit FROM gl_entry_lines l
WHERE {where} AND l.entry_date >= {from} AND l.entry_date <= {to}
"""), cancellationToken).ConfigureAwait(false))[0];
var offset = Math.Max(0, filter.Offset);
var limit = Math.Clamp(filter.Limit, 1, 100_000);
var before = offset == 0
? 0m
: await uow.QuerySingleAsync<decimal?>(SqlFragment.Of($"""
SELECT SUM(x.amount) FROM (
SELECT l.debit - l.credit AS amount FROM gl_entry_lines l JOIN gl_entries e ON e.id = l.entry_id
WHERE {where} AND l.entry_date >= {from} AND l.entry_date <= {to}
ORDER BY l.entry_date, e.number, l.entry_id, l.line_number LIMIT {offset}) x
"""), cancellationToken).ConfigureAwait(false) ?? 0m;
var rows = await uow.QueryAsync<MovementRow>(SqlFragment.Of($"""
SELECT l.entry_id AS entry_id, e.entry_number AS entry_number, l.entry_date AS entry_date, COALESCE(l.description, e.description) AS description,
e.document_number AS document_number, e.document_date AS document_date, e.template_code AS template_code, a.code AS account_code,
l.debit AS debit, l.credit AS credit, l.status AS status
FROM gl_entry_lines l JOIN gl_entries e ON e.id = l.entry_id JOIN gl_accounts a ON a.id = l.account_id
WHERE {where} AND l.entry_date >= {from} AND l.entry_date <= {to}
ORDER BY l.entry_date, e.number, l.entry_id, l.line_number
LIMIT {limit} OFFSET {offset}
"""), cancellationToken).ConfigureAwait(false);
var balance = opening + before;
var movements = new List<LedgerMovement>(rows.Count);
foreach (var r in rows)
{
balance += r.Debit - r.Credit;
movements.Add(new LedgerMovement(r.EntryId, r.EntryNumber, r.EntryDate, r.Description, r.DocumentNumber, r.DocumentDate, r.TemplateCode, r.AccountCode, r.Debit, r.Credit, balance, r.Status));
}
var debit = totals.Debit ?? 0m;
var credit = totals.Credit ?? 0m;
return new LedgerPage(opening, movements, totals.Lines, debit, credit, opening + debit - credit);
}
/// <summary>The trial balance, with the totals of the parent accounts.</summary>
internal static async Task<TrialBalance> TrialBalanceAsync(IUnitOfWork uow, DateOnly from, DateOnly to, long? costCenterId, bool includeDrafts, CancellationToken cancellationToken)
{
var draft = nameof(GlEntryStatus.Draft);
var status = includeDrafts ? SqlFragment.Literal("1 = 1") : SqlFragment.Of($"l.status <> {draft}");
var center = costCenterId is { } c ? SqlFragment.Of($"l.cost_center_id = {c}") : SqlFragment.Literal("1 = 1");
var sums = await uow.QueryAsync<BalanceRow>(SqlFragment.Of($"""
SELECT l.account_id AS account_id,
SUM(CASE WHEN l.entry_date < {from} THEN l.debit - l.credit ELSE 0 END) AS opening,
SUM(CASE WHEN l.entry_date >= {from} THEN l.debit ELSE 0 END) AS debit,
SUM(CASE WHEN l.entry_date >= {from} THEN l.credit ELSE 0 END) AS credit
FROM gl_entry_lines l
WHERE l.entry_date <= {to} AND {status} AND {center}
GROUP BY l.account_id
"""), cancellationToken).ConfigureAwait(false);
var accounts = await LedgerStore.AccountsAsync(uow, cancellationToken).ConfigureAwait(false);
var totals = new Dictionary<long, (decimal Opening, decimal Debit, decimal Credit)>();
foreach (var s in sums)
{
var id = (long?)s.AccountId;
while (id is { } current && accounts.TryGetValue(current, out var account))
{
totals.TryGetValue(current, out var t);
totals[current] = (t.Opening + (s.Opening ?? 0m), t.Debit + (s.Debit ?? 0m), t.Credit + (s.Credit ?? 0m));
id = account.ParentId;
}
}
var lines = totals
.Select(kv => (Account: accounts[kv.Key], kv.Value))
.Where(x => x.Value.Opening != 0m || x.Value.Debit != 0m || x.Value.Credit != 0m)
.OrderBy(x => x.Account.Code, StringComparer.Ordinal)
.Select(x => new TrialBalanceLine(
x.Account.Id, x.Account.Code, x.Account.Description, x.Account.Level, x.Account.Nature, x.Value.Opening, x.Value.Debit, x.Value.Credit,
x.Value.Opening + x.Value.Debit - x.Value.Credit))
.ToList();
var leaves = lines.Where(l => accounts[l.AccountId].Postable).ToList();
var result = -leaves.Where(l => l.Nature is AccountNature.Revenue or AccountNature.Cost).Sum(l => l.Debit - l.Credit);
return new TrialBalance(lines, leaves.Sum(l => l.Debit), leaves.Sum(l => l.Credit), result);
}
private static SqlFragment Condition(LedgerFilter filter)
{
var draft = nameof(GlEntryStatus.Draft);
var status = filter.IncludeDrafts ? SqlFragment.Literal("1 = 1") : SqlFragment.Of($"l.status <> {draft}");
var account = filter.AccountId is { } a ? SqlFragment.Of($"l.account_id = {a}") : SqlFragment.Literal("1 = 1");
var party = filter.PartyId is { } p ? SqlFragment.Of($"l.party_id = {p}") : SqlFragment.Literal("1 = 1");
return SqlFragment.Of($"{status} AND {account} AND {party}");
}
private static string? Signed(decimal amount) => amount == 0m ? "0,00" : LedgerReport.Money(Math.Abs(amount)) + (amount > 0m ? " D" : " A");
private sealed record MovementRow(
long EntryId, string? EntryNumber, DateOnly EntryDate, string? Description, string? DocumentNumber, DateOnly? DocumentDate, string? TemplateCode, string? AccountCode,
decimal Debit, decimal Credit, GlEntryStatus Status);
private sealed record TotalsRow(long Lines, decimal? Debit, decimal? Credit);
private sealed record BalanceRow(long AccountId, decimal? Opening, decimal? Debit, decimal? Credit);
private sealed record PartyRow(long PartyId, string Name, decimal? Debit, decimal? Credit, long OpenItems);
private sealed record JournalRow(
long EntryId, string? EntryNumber, long? JournalNumber, DateOnly EntryDate, string EntryDescription, string? DocumentNumber, string AccountCode, string AccountDescription,
string? PartyName, string? Description, decimal Debit, decimal Credit);
}
@@ -0,0 +1,138 @@
using System.Globalization;
using Khaemhat.Infrastructure.Files;
namespace Khaemhat.Application.Ledger;
/// <summary>A column of a ledger print.</summary>
/// <param name="Title">The heading.</param>
/// <param name="Width">The width in points.</param>
/// <param name="Right">Aligned on the right (amounts).</param>
public sealed record ReportColumn(string Title, double Width, bool Right = false);
/// <summary>
/// The prints of the ledger (VAT registers, general journal, ledgers, trial balance, issue #65 and #67): A4 landscape,
/// the company and the title on every page, the headings repeated, the pages numbered from a first page in the form
/// <c>year/page</c> as the final prints of the books want (art. 2215-bis c.c., numbering by year).
/// </summary>
internal static class LedgerReport
{
private const double Margin = 28;
private const double LineHeight = 11;
private static readonly PdfColor Rule = PdfColor.Gray(180);
/// <summary>Writes a print.</summary>
/// <param name="company">The name, VAT number and address of the company.</param>
/// <param name="title">The title, such as <c>Registro IVA vendite</c>.</param>
/// <param name="subtitle">The period and the kind of print.</param>
/// <param name="columns">The columns.</param>
/// <param name="rows">The rows; a row whose first cell starts with <c>**</c> is a bold total.</param>
/// <param name="year">The year of the page numbers.</param>
/// <param name="firstPage">The number of the first page.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The file and the number of pages.</returns>
public static async Task<(byte[] File, int Pages)> WriteAsync(
string company, string title, string subtitle, IReadOnlyList<ReportColumn> columns, IReadOnlyList<IReadOnlyList<string?>> rows, int year, int firstPage,
CancellationToken cancellationToken)
{
using var buffer = new MemoryStream();
int pages;
await using (var pdf = new PdfWriter(buffer, new PdfDocumentInfo { Title = title }, leaveOpen: true))
{
var width = PdfWriter.A4Height;
var height = PdfWriter.A4Width;
var scale = Math.Min(1d, (width - (2 * Margin)) / Math.Max(1d, columns.Sum(c => c.Width)));
PdfPage? page = null;
var y = 0d;
var number = firstPage;
async Task NewPageAsync()
{
page = await pdf.AddPageAsync(width, height, cancellationToken).ConfigureAwait(false);
y = height - Margin;
page.DrawText(company, Margin, y, PdfFont.HelveticaBold, 9);
page.DrawTextRight(year.ToString(CultureInfo.InvariantCulture) + "/" + number.ToString(CultureInfo.InvariantCulture), width - Margin, y, PdfFont.Helvetica, 9);
y -= 14;
page.DrawText(title, Margin, y, PdfFont.HelveticaBold, 12);
y -= 12;
page.DrawText(subtitle, Margin, y, PdfFont.Helvetica, 8.5);
y -= 16;
var x = Margin;
foreach (var column in columns)
{
var w = column.Width * scale;
if (column.Right)
{
page.DrawTextRight(column.Title, x + w - 2, y, PdfFont.HelveticaBold, 7.5);
}
else
{
page.DrawText(column.Title, x + 2, y, PdfFont.HelveticaBold, 7.5);
}
x += w;
}
page.DrawLine(Margin, y - 3, width - Margin, y - 3, 0.6, Rule);
y -= LineHeight + 2;
number++;
}
await NewPageAsync().ConfigureAwait(false);
foreach (var row in rows)
{
if (y < Margin + LineHeight)
{
await NewPageAsync().ConfigureAwait(false);
}
var bold = row.Count > 0 && row[0] is { } first && first.StartsWith("**", StringComparison.Ordinal);
var font = bold ? PdfFont.HelveticaBold : PdfFont.Helvetica;
var x = Margin;
for (var i = 0; i < columns.Count; i++)
{
var w = columns[i].Width * scale;
var text = i < row.Count ? row[i] : null;
if (i == 0 && bold)
{
text = text![2..];
}
text = PdfTextLayout.Fit(text, font, 7.5, w - 4);
if (columns[i].Right)
{
page!.DrawTextRight(text, x + w - 2, y, font, 7.5);
}
else
{
page!.DrawText(text, x + 2, y, font, 7.5);
}
x += w;
}
if (bold)
{
page!.DrawLine(Margin, y + LineHeight - 2, width - Margin, y + LineHeight - 2, 0.4, Rule);
}
y -= LineHeight;
}
pages = pdf.PageCount;
await pdf.CloseAsync(cancellationToken).ConfigureAwait(false);
}
return (buffer.ToArray(), pages);
}
/// <summary>An amount as the prints show it, with the Italian separators.</summary>
/// <param name="amount">The amount.</param>
/// <returns>The text; empty for zero.</returns>
public static string Money(decimal amount) => amount == 0m ? string.Empty : amount.ToString("#,##0.00", Italian);
/// <summary>A date as the prints show it.</summary>
/// <param name="date">The date.</param>
/// <returns>The text.</returns>
public static string Date(DateOnly? date) => date?.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture) ?? string.Empty;
private static readonly CultureInfo Italian = CultureInfo.GetCultureInfo("it-IT");
}
@@ -0,0 +1,508 @@
using Khaemhat.Application.Audit;
using Khaemhat.Application.Documents;
using Khaemhat.Application.ImportExport;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Accounting;
using Khaemhat.Core.Documents;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Ledger;
/// <summary>An account typed in the chart.</summary>
/// <param name="Id">The account, for a change.</param>
/// <param name="Code">The code, such as <c>05.01.003</c>.</param>
/// <param name="Description">The description.</param>
/// <param name="Nature">The statement it ends up in (taken from the parent below the first level).</param>
/// <param name="Type">What the automatic postings look for.</param>
public sealed record AccountInput(long? Id, string Code, string Description, AccountNature Nature, AccountType Type = AccountType.Generic)
{
/// <summary>The line of the legal statements.</summary>
public string? StatementLine { get; init; }
/// <summary>The line of the reclassified statements.</summary>
public string? Reclassification { get; init; }
/// <summary>The lines carry a customer or supplier.</summary>
public bool SubLedger { get; init; }
/// <summary>Relevant for VAT.</summary>
public bool VatRelevant { get; init; }
/// <summary>Closed at the year end.</summary>
public bool ClosesAutomatically { get; init; } = true;
/// <summary>No longer used.</summary>
public bool Disabled { get; init; }
}
/// <summary>A line of a journal template typed on its screen.</summary>
/// <param name="Role">What it stands for.</param>
/// <param name="Side">Debit or credit.</param>
/// <param name="AccountId">The account.</param>
/// <param name="Description">The description proposed.</param>
public sealed record TemplateLineInput(PostingRole Role, AccountSide Side, long? AccountId, string? Description);
/// <summary>A journal template typed on its screen (mockup 043).</summary>
/// <param name="Id">The template, for a change.</param>
/// <param name="Code">The code.</param>
/// <param name="Description">The description.</param>
/// <param name="Area">The kind of operations.</param>
/// <param name="Lines">The model of the lines.</param>
public sealed record TemplateInput(long? Id, string Code, string Description, JournalArea Area, IReadOnlyList<TemplateLineInput> Lines)
{
/// <summary>The VAT register.</summary>
public string? VatRegisterCode { get; init; }
/// <summary>Opens items of customers or suppliers.</summary>
public bool OpensItems { get; init; }
/// <summary>Reverses the sides (credit notes).</summary>
public bool Reverses { get; init; }
/// <summary>No longer used.</summary>
public bool Disabled { get; init; }
}
/// <summary>What a bulk posting did.</summary>
/// <param name="Posted">Documents posted or posted again.</param>
/// <param name="Failed">Documents that could not be posted, with the reason.</param>
public sealed record PostingReport(int Posted, IReadOnlyList<string> Failed);
/// <summary>
/// The chart of accounts and the journal templates (SPEC §11.7, issue #62, mockups 042-043, ADR 0036): three levels
/// where only the leaves receive postings, the nature inherited from the mastro, no removal of accounts with postings or
/// children; the import of a chart (CSV, XLSX, JSON) through the guided import; the bulk posting of the documents not yet
/// posted and the posting again of a period (issue #64).
/// </summary>
public sealed class LedgerService
{
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
private readonly AuditTrail _audit;
/// <summary>Creates the service.</summary>
/// <param name="factory">The units of work.</param>
/// <param name="permissions">The permissions.</param>
/// <param name="audit">The history.</param>
public LedgerService(IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(audit);
_factory = factory;
_permissions = permissions;
_audit = audit;
}
/// <summary>The chart of accounts, by code.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>Every account.</returns>
public async Task<IReadOnlyList<GlAccount>> AccountsAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return [.. (await uow.Repository<GlAccount, long>().ListAsync(Query.For<GlAccount>(), cancellationToken).ConfigureAwait(false)).Items.OrderBy(a => a.Code, StringComparer.Ordinal)];
}
/// <summary>The VAT registers, by code.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>Every register.</returns>
public async Task<IReadOnlyList<VatRegister>> RegistersAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
// Sales first, then purchases and receipts; the ordinary register before the reverse charge one (enums are stored as text).
var registers = (await uow.Repository<VatRegister, long>().ListAsync(Query.For<VatRegister>(), cancellationToken).ConfigureAwait(false)).Items;
return [.. registers.OrderBy(r => r.Kind).ThenBy(r => r.ReverseCharge).ThenBy(r => r.Code, StringComparer.Ordinal)];
}
/// <summary>Saves an account: a new one under a leaf with postings is refused, the parent stops being postable.</summary>
/// <param name="actor">Who writes.</param>
/// <param name="companyCode">The company.</param>
/// <param name="input">The account.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The account as saved.</returns>
public async Task<GlAccount> SaveAccountAsync(Actor actor, string companyCode, AccountInput input, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(input);
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.AccountWrite, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var repository = uow.Repository<GlAccount, long>();
var code = (input.Code ?? string.Empty).Trim();
var errors = new List<string>();
var level = AccountCodes.LevelOf(code);
if (level == 0)
{
errors.Add("Code:" + LedgerErrors.AccountCode);
}
if (string.IsNullOrWhiteSpace(input.Description))
{
errors.Add("Description:" + LedgerErrors.DescriptionRequired);
}
GlAccount? before = null;
if (input.Id is { } id)
{
before = await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.AccountMissing);
if (!string.Equals(before.Code, code, StringComparison.Ordinal))
{
errors.Add("Code:" + LedgerErrors.AccountUsed);
}
}
else if (level > 0 && await repository.FindAsync(Query.For<GlAccount>().Where(a => a.Code == code), cancellationToken).ConfigureAwait(false) is not null)
{
errors.Add("Code:" + LedgerErrors.AccountDuplicate);
}
GlAccount? parent = null;
if (level > 1)
{
var parentCode = AccountCodes.ParentOf(code);
parent = await repository.FindAsync(Query.For<GlAccount>().Where(a => a.Code == parentCode), cancellationToken).ConfigureAwait(false);
if (parent is null)
{
errors.Add("Code:" + LedgerErrors.AccountParent);
}
else if (before is null && parent.Postable && await UsedAsync(uow, parent.Id, cancellationToken).ConfigureAwait(false))
{
errors.Add("Code:" + LedgerErrors.AccountUsed);
}
}
if (errors.Count > 0)
{
throw new ValidationFailedException(errors);
}
var account = before is null ? new GlAccount { Code = code, Level = level, ParentId = parent?.Id } : Clone(before);
account.Description = input.Description.Trim();
account.Nature = parent?.Nature ?? input.Nature;
account.Type = input.Type;
account.StatementLine = LedgerStore.Trim(input.StatementLine?.Trim(), 20);
account.Reclassification = LedgerStore.Trim(input.Reclassification?.Trim(), 20);
account.SubLedger = input.SubLedger;
account.VatRelevant = input.VatRelevant;
account.ClosesAutomatically = input.ClosesAutomatically;
account.Disabled = input.Disabled;
if (before is null)
{
account.Postable = level > 1;
account.Id = await repository.InsertAsync(account, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Insert, account.Id, null, account, actor.UserName, cancellationToken).ConfigureAwait(false);
if (parent is { Postable: true })
{
parent.Postable = false;
await repository.UpdateAsync(parent, cancellationToken).ConfigureAwait(false);
}
}
else
{
await repository.UpdateAsync(account, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, account.Id, before, account, actor.UserName, cancellationToken).ConfigureAwait(false);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return account;
}
/// <summary>Removes an account without children, postings or use in the templates.</summary>
/// <param name="actor">Who removes it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The account.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task DeleteAccountAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.AccountWrite, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var repository = uow.Repository<GlAccount, long>();
var account = await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.AccountMissing);
if (await repository.CountAsync(Query.For<GlAccount>().Where(a => a.ParentId == id), cancellationToken).ConfigureAwait(false) > 0)
{
throw new ValidationFailedException(["Id:" + LedgerErrors.AccountHasChildren]);
}
var inTemplates = await uow.Repository<JournalTemplateLine, long>().CountAsync(Query.For<JournalTemplateLine>().Where(l => l.AccountId == id), cancellationToken)
.ConfigureAwait(false);
if (inTemplates > 0 || await UsedAsync(uow, id, cancellationToken).ConfigureAwait(false))
{
throw new ValidationFailedException(["Id:" + LedgerErrors.AccountUsed]);
}
await repository.DeleteAsync(id, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Delete, id, account, (GlAccount?)null, actor.UserName, cancellationToken).ConfigureAwait(false);
if (account.ParentId is { } parentId
&& await repository.CountAsync(Query.For<GlAccount>().Where(a => a.ParentId == parentId), cancellationToken).ConfigureAwait(false) == 0
&& await repository.GetAsync(parentId, cancellationToken).ConfigureAwait(false) is { Level: > 1 } parent)
{
parent.Postable = true;
await repository.UpdateAsync(parent, cancellationToken).ConfigureAwait(false);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>The journal templates with their lines.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>Every template, by code.</returns>
public async Task<IReadOnlyList<TemplateView>> TemplatesAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var templates = (await uow.Repository<JournalTemplate, long>().ListAsync(Query.For<JournalTemplate>().OrderBy(t => t.Code), cancellationToken).ConfigureAwait(false)).Items;
var lines = (await uow.Repository<JournalTemplateLine, long>().ListAsync(Query.For<JournalTemplateLine>().OrderBy(l => l.SortOrder), cancellationToken).ConfigureAwait(false)).Items;
return [.. templates.Select(t => new TemplateView(t, [.. lines.Where(l => l.JournalTemplateId == t.Id)]))];
}
/// <summary>Saves a journal template with its lines.</summary>
/// <param name="actor">Who writes.</param>
/// <param name="companyCode">The company.</param>
/// <param name="input">The template.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The template as saved.</returns>
public async Task<TemplateView> SaveTemplateAsync(Actor actor, string companyCode, TemplateInput input, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(input);
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.AccountWrite, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var repository = uow.Repository<JournalTemplate, long>();
var code = (input.Code ?? string.Empty).Trim().ToUpperInvariant();
var errors = new List<string>();
if (code.Length is 0 or > 10)
{
errors.Add("Code:" + LedgerErrors.TemplateCode);
}
if (string.IsNullOrWhiteSpace(input.Description))
{
errors.Add("Description:" + LedgerErrors.DescriptionRequired);
}
var other = await repository.FindAsync(Query.For<JournalTemplate>().Where(t => t.Code == code), cancellationToken).ConfigureAwait(false);
if (other is not null && other.Id != input.Id)
{
errors.Add("Code:" + LedgerErrors.TemplateDuplicate);
}
if (input.VatRegisterCode is { Length: > 0 } registerCode && await LedgerStore.RegisterAsync(uow, registerCode, cancellationToken).ConfigureAwait(false) is null)
{
errors.Add("VatRegisterCode:" + LedgerErrors.VatRegisterRequired);
}
if (errors.Count > 0)
{
throw new ValidationFailedException(errors);
}
JournalTemplate? before = input.Id is { } id ? await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) : null;
var template = before is null ? new JournalTemplate() : new JournalTemplate { Id = before.Id, RowVersion = before.RowVersion, CreatedAt = before.CreatedAt, CreatedBy = before.CreatedBy, IsDemo = before.IsDemo };
template.Code = code;
template.Description = input.Description.Trim();
template.Area = input.Area;
template.VatRegisterCode = string.IsNullOrWhiteSpace(input.VatRegisterCode) ? null : input.VatRegisterCode.Trim();
template.OpensItems = input.OpensItems;
template.Reverses = input.Reverses;
template.Disabled = input.Disabled;
if (before is null)
{
template.Id = await repository.InsertAsync(template, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Insert, template.Id, null, template, actor.UserName, cancellationToken).ConfigureAwait(false);
}
else
{
await repository.UpdateAsync(template, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, template.Id, before, template, actor.UserName, cancellationToken).ConfigureAwait(false);
}
var templateId = template.Id;
await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM gl_journal_template_lines WHERE journal_template_id = {templateId}"), cancellationToken).ConfigureAwait(false);
var lines = new List<JournalTemplateLine>();
for (var i = 0; i < input.Lines.Count; i++)
{
var line = input.Lines[i];
var row = new JournalTemplateLine
{
JournalTemplateId = templateId,
SortOrder = (i + 1) * 10,
Role = line.Role,
Side = line.Side,
AccountId = line.AccountId,
Description = LedgerStore.Trim(line.Description, 100),
};
row.Id = await uow.Repository<JournalTemplateLine, long>().InsertAsync(row, cancellationToken).ConfigureAwait(false);
lines.Add(row);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return new TemplateView(template, lines);
}
/// <summary>Removes a template that no entry or document type uses.</summary>
/// <param name="actor">Who removes it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The template.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task DeleteTemplateAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.AccountWrite, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var template = await uow.Repository<JournalTemplate, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.TemplateMissing);
var code = template.Code;
var entries = await uow.Repository<GlEntry, long>().CountAsync(Query.For<GlEntry>().Where(e => e.JournalTemplateId == id), cancellationToken).ConfigureAwait(false);
var types = await uow.Repository<Core.Tables.DocumentType, long>().CountAsync(Query.For<Core.Tables.DocumentType>().Where(t => t.JournalTemplateCode == code), cancellationToken)
.ConfigureAwait(false);
if (entries > 0 || types > 0)
{
throw new ValidationFailedException(["Id:" + LedgerErrors.TemplateUsed]);
}
await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM gl_journal_template_lines WHERE journal_template_id = {id}"), cancellationToken).ConfigureAwait(false);
await uow.Repository<JournalTemplate, long>().DeleteAsync(id, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Delete, id, template, (JournalTemplate?)null, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Posts the documents in force of a period that have no entry (issue #64: posting in bulk, for instance after the
/// module is licensed), or with <paramref name="again"/> writes again the entries that are not final.
/// </summary>
/// <param name="actor">Who posts.</param>
/// <param name="companyCode">The company.</param>
/// <param name="from">From this day.</param>
/// <param name="to">Up to this day.</param>
/// <param name="again">Post again also the documents already posted.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>What was posted.</returns>
public async Task<PostingReport> PostPendingAsync(Actor actor, string companyCode, DateOnly from, DateOnly to, bool again = false, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryWrite, cancellationToken).ConfigureAwait(false);
var posted = 0;
var failed = new List<string>();
foreach (var family in new[] { DocumentFamily.SaleDocument, DocumentFamily.PurchaseDocument })
{
List<DocumentHeader> headers;
await using (var read = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
headers = [.. (await DocumentStores.Of(family).InForceAsync(read, cancellationToken).ConfigureAwait(false))
.Where(h => h.DocumentDate >= from && h.DocumentDate <= to && LedgerPoster.PostingOf(h.Kind) is not null && (again || !h.Posted))
.OrderBy(h => h.DocumentDate).ThenBy(h => h.Id)];
}
foreach (var header in headers)
{
// One transaction per document: one that cannot post does not stop the others.
try
{
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
if (await LedgerPoster.PostAsync(uow, family, header.Id, cancellationToken).ConfigureAwait(false) is not null)
{
posted++;
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
catch (ValidationFailedException exception)
{
failed.Add((header.DocumentNumber ?? header.Id.ToString(System.Globalization.CultureInfo.InvariantCulture)) + ": " + string.Join(", ", exception.Errors));
}
}
}
return new PostingReport(posted, failed);
}
/// <summary>Writes the accounts the import of a chart accepted: new codes are added, existing ones updated.</summary>
/// <param name="uow">The unit of work, in a transaction.</param>
/// <param name="accounts">The accounts, parents first or in any order.</param>
/// <param name="update">Update the accounts that exist.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>For each code, whether it was created (<see langword="true"/>) or updated.</returns>
internal static async Task<Dictionary<string, bool>> ImportAsync(IUnitOfWork uow, IReadOnlyList<ImportedAccount> accounts, bool update, CancellationToken cancellationToken)
{
var repository = uow.Repository<GlAccount, long>();
var existing = (await repository.ListAsync(Query.For<GlAccount>(), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(a => a.Code, StringComparer.OrdinalIgnoreCase);
var result = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
foreach (var imported in accounts.OrderBy(a => a.Level).ThenBy(a => a.Code, StringComparer.Ordinal))
{
if (existing.TryGetValue(imported.Code, out var account))
{
if (!update)
{
continue;
}
account.Description = LedgerStore.Trim(imported.Description, 100)!;
account.Nature = imported.Nature;
account.Type = imported.Type;
account.StatementLine = LedgerStore.Trim(imported.StatementLine, 20) ?? account.StatementLine;
account.Reclassification = LedgerStore.Trim(imported.Reclassification, 20) ?? account.Reclassification;
account.VatRelevant = imported.VatRelevant;
account.SubLedger = imported.SubLedger;
account.ClosesAutomatically = imported.ClosesAutomatically;
account.Disabled = imported.Disabled;
await repository.UpdateAsync(account, cancellationToken).ConfigureAwait(false);
result[imported.Code] = false;
continue;
}
account = new GlAccount
{
Code = imported.Code,
Description = LedgerStore.Trim(imported.Description, 100)!,
Level = imported.Level,
ParentId = imported.ParentCode is { } parent && existing.TryGetValue(parent, out var found) ? found.Id : null,
Nature = imported.Nature,
Type = imported.Type,
StatementLine = LedgerStore.Trim(imported.StatementLine, 20),
Reclassification = LedgerStore.Trim(imported.Reclassification, 20),
SubLedger = imported.SubLedger,
VatRelevant = imported.VatRelevant,
ClosesAutomatically = imported.ClosesAutomatically,
Disabled = imported.Disabled,
Postable = imported.Postable,
};
account.Id = await repository.InsertAsync(account, cancellationToken).ConfigureAwait(false);
existing[account.Code] = account;
result[imported.Code] = true;
}
return result;
}
internal static async Task<bool> UsedAsync(IUnitOfWork uow, long accountId, CancellationToken cancellationToken) =>
await uow.Repository<GlEntryLine, long>().CountAsync(Query.For<GlEntryLine>().Where(l => l.AccountId == accountId), cancellationToken).ConfigureAwait(false) > 0;
private static GlAccount Clone(GlAccount a) => new()
{
Id = a.Id,
Code = a.Code,
Level = a.Level,
ParentId = a.ParentId,
Postable = a.Postable,
IsDemo = a.IsDemo,
RowVersion = a.RowVersion,
CreatedAt = a.CreatedAt,
CreatedBy = a.CreatedBy,
UpdatedAt = a.UpdatedAt,
UpdatedBy = a.UpdatedBy,
};
}
@@ -0,0 +1,257 @@
using System.Globalization;
using Khaemhat.Core.Accounting;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Ledger;
/// <summary>The permissions of the ledger (module ACCT, <see cref="Modules.BuiltInModules"/>).</summary>
public static class LedgerPermissions
{
/// <summary>See the chart of accounts and the journal templates.</summary>
public const string AccountRead = "ledger.account.read";
/// <summary>Change the chart of accounts and the journal templates.</summary>
public const string AccountWrite = "ledger.account.write";
/// <summary>See the journal, the ledgers and the balances.</summary>
public const string EntryRead = "ledger.entry.read";
/// <summary>Write entries and post documents.</summary>
public const string EntryWrite = "ledger.entry.write";
/// <summary>Make entries final (libro giornale).</summary>
public const string EntryFinalize = "ledger.entry.finalize";
/// <summary>See the VAT registers.</summary>
public const string VatRegisterRead = "vat.register.read";
/// <summary>See the settlements, withholdings, stamp duty and F24.</summary>
public const string SettlementRead = "vat.settlement.read";
/// <summary>Confirm settlements and record tax payments.</summary>
public const string SettlementConfirm = "vat.settlement.confirm";
}
/// <summary>A line of an entry being written.</summary>
/// <param name="AccountId">The account.</param>
/// <param name="PartyId">The customer or supplier.</param>
/// <param name="Description">The description.</param>
/// <param name="Debit">The debit.</param>
/// <param name="Credit">The credit.</param>
/// <param name="CostCenterId">The cost center.</param>
/// <param name="JobId">The job.</param>
public sealed record EntryLineDraft(long? AccountId, long? PartyId, string? Description, decimal Debit, decimal Credit, long? CostCenterId = null, long? JobId = null);
/// <summary>A VAT line of an entry being written.</summary>
/// <param name="TaxCodeId">The VAT code.</param>
/// <param name="Rate">The rate.</param>
/// <param name="Nature">The nature.</param>
/// <param name="Taxable">The taxable amount, with sign.</param>
/// <param name="Tax">The VAT, with sign.</param>
/// <param name="NonDeductibleTax">The VAT not deductible.</param>
/// <param name="Exigibility">When the VAT is due.</param>
/// <param name="RegisterId">The register, when different from the one of the entry (self-invoices).</param>
public sealed record EntryVatDraft(
long? TaxCodeId, decimal Rate, string? Nature, decimal Taxable, decimal Tax, decimal NonDeductibleTax = 0m,
Core.Tax.TaxExigibility Exigibility = Core.Tax.TaxExigibility.Immediate, long? RegisterId = null);
/// <summary>
/// What every writer of the ledger shares (ADR 0036): the numbering of the entries in each year, the
/// writing of an entry with its lines and VAT lines (which keep its date and state), the removal of an entry and the
/// lookups of accounts, templates and registers.
/// </summary>
internal static class LedgerStore
{
/// <summary>Writes a new entry with its lines and VAT lines; posted entries get their number.</summary>
public static async Task<GlEntry> InsertAsync(
IUnitOfWork uow, GlEntry entry, IReadOnlyList<EntryLineDraft> lines, IReadOnlyList<EntryVatDraft> vat, CancellationToken cancellationToken)
{
entry.Year = entry.EntryDate.Year;
entry.TotalDebit = lines.Sum(l => l.Debit);
entry.TotalCredit = lines.Sum(l => l.Credit);
if (entry.Status != GlEntryStatus.Draft && entry.Number is null)
{
await NumberAsync(uow, entry, cancellationToken).ConfigureAwait(false);
}
entry.Id = await uow.Repository<GlEntry, long>().InsertAsync(entry, cancellationToken).ConfigureAwait(false);
await WriteLinesAsync(uow, entry, lines, vat, cancellationToken).ConfigureAwait(false);
return entry;
}
/// <summary>Replaces the lines of an entry and updates it.</summary>
public static async Task UpdateAsync(
IUnitOfWork uow, GlEntry entry, IReadOnlyList<EntryLineDraft> lines, IReadOnlyList<EntryVatDraft> vat, CancellationToken cancellationToken)
{
entry.Year = entry.Number is null ? entry.EntryDate.Year : entry.Year;
entry.TotalDebit = lines.Sum(l => l.Debit);
entry.TotalCredit = lines.Sum(l => l.Credit);
if (entry.Status != GlEntryStatus.Draft && entry.Number is null)
{
await NumberAsync(uow, entry, cancellationToken).ConfigureAwait(false);
}
await uow.Repository<GlEntry, long>().UpdateAsync(entry, cancellationToken).ConfigureAwait(false);
await RemoveLinesAsync(uow, entry.Id, cancellationToken).ConfigureAwait(false);
await WriteLinesAsync(uow, entry, lines, vat, cancellationToken).ConfigureAwait(false);
}
/// <summary>Changes the state of an entry and of its lines.</summary>
public static async Task SetStatusAsync(IUnitOfWork uow, GlEntry entry, GlEntryStatus status, CancellationToken cancellationToken)
{
entry.Status = status;
if (status != GlEntryStatus.Draft && entry.Number is null)
{
await NumberAsync(uow, entry, cancellationToken).ConfigureAwait(false);
}
await uow.Repository<GlEntry, long>().UpdateAsync(entry, cancellationToken).ConfigureAwait(false);
var text = status.ToString();
await uow.ExecuteAsync(SqlFragment.Of($"UPDATE gl_entry_lines SET status = {text} WHERE entry_id = {entry.Id}"), cancellationToken).ConfigureAwait(false);
await uow.ExecuteAsync(SqlFragment.Of($"UPDATE gl_entry_vat SET status = {text} WHERE entry_id = {entry.Id}"), cancellationToken).ConfigureAwait(false);
}
/// <summary>Removes an entry with its lines, VAT lines and open items.</summary>
public static async Task DeleteAsync(IUnitOfWork uow, long entryId, CancellationToken cancellationToken)
{
await RemoveLinesAsync(uow, entryId, cancellationToken).ConfigureAwait(false);
await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM gl_open_items WHERE entry_id = {entryId}"), cancellationToken).ConfigureAwait(false);
await uow.ExecuteAsync(SqlFragment.Of($"UPDATE gl_entries SET reversed_by_id = NULL WHERE reversed_by_id = {entryId}"), cancellationToken).ConfigureAwait(false);
await uow.Repository<GlEntry, long>().DeleteAsync(entryId, cancellationToken).ConfigureAwait(false);
}
/// <summary>The lines of an entry, in order.</summary>
public static async Task<IReadOnlyList<GlEntryLine>> LinesAsync(IUnitOfWork uow, long entryId, CancellationToken cancellationToken) =>
(await uow.Repository<GlEntryLine, long>().ListAsync(Query.For<GlEntryLine>().Where(l => l.EntryId == entryId).OrderBy(l => l.LineNumber), cancellationToken)
.ConfigureAwait(false)).Items;
/// <summary>The VAT lines of an entry, in order.</summary>
public static async Task<IReadOnlyList<GlEntryVat>> VatAsync(IUnitOfWork uow, long entryId, CancellationToken cancellationToken) =>
(await uow.Repository<GlEntryVat, long>().ListAsync(Query.For<GlEntryVat>().Where(l => l.EntryId == entryId).OrderBy(l => l.LineNumber), cancellationToken)
.ConfigureAwait(false)).Items;
/// <summary>Every account, by id.</summary>
public static async Task<Dictionary<long, GlAccount>> AccountsAsync(IUnitOfWork uow, CancellationToken cancellationToken) =>
(await uow.Repository<GlAccount, long>().ListAsync(Query.For<GlAccount>(), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(a => a.Id);
/// <summary>The rules the validator reads, by id.</summary>
public static Dictionary<long, AccountRule> Rules(IReadOnlyDictionary<long, GlAccount> accounts) =>
accounts.Values.ToDictionary(a => a.Id, a => new AccountRule(a.Id, a.Postable, a.Disabled, a.SubLedger));
/// <summary>A journal template with its lines, by code.</summary>
public static async Task<(JournalTemplate Template, IReadOnlyList<JournalTemplateLine> Lines)?> TemplateAsync(
IUnitOfWork uow, string? code, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(code))
{
return null;
}
var template = await uow.Repository<JournalTemplate, long>().FindAsync(Query.For<JournalTemplate>().Where(t => t.Code == code), cancellationToken).ConfigureAwait(false);
if (template is null)
{
return null;
}
var lines = (await uow.Repository<JournalTemplateLine, long>().ListAsync(
Query.For<JournalTemplateLine>().Where(l => l.JournalTemplateId == template.Id).OrderBy(l => l.SortOrder), cancellationToken).ConfigureAwait(false)).Items;
return (template, lines);
}
/// <summary>A VAT register by code.</summary>
public static Task<VatRegister?> RegisterAsync(IUnitOfWork uow, string? code, CancellationToken cancellationToken) =>
string.IsNullOrWhiteSpace(code)
? Task.FromResult<VatRegister?>(null)
: uow.Repository<VatRegister, long>().FindAsync(Query.For<VatRegister>().Where(r => r.Code == code), cancellationToken);
/// <summary>The account of a code, if any.</summary>
public static Task<GlAccount?> AccountAsync(IUnitOfWork uow, string? code, CancellationToken cancellationToken) =>
string.IsNullOrWhiteSpace(code)
? Task.FromResult<GlAccount?>(null)
: uow.Repository<GlAccount, long>().FindAsync(Query.For<GlAccount>().Where(a => a.Code == code), cancellationToken);
/// <summary>
/// Gives the entry the next number of its year (protocollo di prima nota). The numbers follow the order of
/// registration, not of the dates: the date order is the one of the journal, given when entries become final.
/// </summary>
public static async Task NumberAsync(IUnitOfWork uow, GlEntry entry, CancellationToken cancellationToken)
{
entry.Year = entry.EntryDate.Year;
var year = entry.Year;
var number = (await uow.QuerySingleAsync<long?>(SqlFragment.Of($"SELECT MAX(number) FROM gl_entries WHERE year = {year}"), cancellationToken).ConfigureAwait(false) ?? 0L) + 1L;
entry.Number = number;
entry.EntryNumber = Format(entry.Year, number);
}
/// <summary>The number of an entry as shown.</summary>
public static string Format(int year, long number) =>
year.ToString(CultureInfo.InvariantCulture) + "/" + number.ToString("D5", CultureInfo.InvariantCulture);
private static async Task RemoveLinesAsync(IUnitOfWork uow, long entryId, CancellationToken cancellationToken)
{
await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM gl_entry_lines WHERE entry_id = {entryId}"), cancellationToken).ConfigureAwait(false);
await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM gl_entry_vat WHERE entry_id = {entryId}"), cancellationToken).ConfigureAwait(false);
}
private static async Task WriteLinesAsync(
IUnitOfWork uow, GlEntry entry, IReadOnlyList<EntryLineDraft> lines, IReadOnlyList<EntryVatDraft> vat, CancellationToken cancellationToken)
{
var repository = uow.Repository<GlEntryLine, long>();
for (var i = 0; i < lines.Count; i++)
{
var line = lines[i];
await repository.InsertAsync(new GlEntryLine
{
EntryId = entry.Id,
LineNumber = i + 1,
EntryDate = entry.EntryDate,
Status = entry.Status,
AccountId = line.AccountId ?? 0,
PartyId = line.PartyId,
Description = Trim(line.Description, 200),
Debit = line.Debit,
Credit = line.Credit,
CostCenterId = line.CostCenterId,
JobId = line.JobId,
}, cancellationToken).ConfigureAwait(false);
}
if (vat.Count == 0)
{
return;
}
var registers = (await uow.Repository<VatRegister, long>().ListAsync(Query.For<VatRegister>(), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(r => r.Id);
var vatRepository = uow.Repository<GlEntryVat, long>();
for (var i = 0; i < vat.Count; i++)
{
var line = vat[i];
var registerId = line.RegisterId ?? entry.VatRegisterId ?? 0;
if (!registers.TryGetValue(registerId, out var register))
{
continue;
}
await vatRepository.InsertAsync(new GlEntryVat
{
EntryId = entry.Id,
LineNumber = i + 1,
VatRegisterId = register.Id,
RegisterKind = register.Kind,
VatDate = entry.VatDate ?? entry.EntryDate,
Status = entry.Status,
TaxCodeId = line.TaxCodeId,
Rate = line.Rate,
Nature = line.Nature,
Exigibility = line.Exigibility,
Taxable = line.Taxable,
Tax = line.Tax,
NonDeductibleTax = line.NonDeductibleTax,
}, cancellationToken).ConfigureAwait(false);
}
}
/// <summary>A text cut to a length.</summary>
public static string? Trim(string? text, int length) => text is null || text.Length <= length ? text : text[..length];
}
@@ -0,0 +1,288 @@
using System.Globalization;
using Khaemhat.Application.Audit;
using Khaemhat.Application.Jobs;
using Khaemhat.Application.Licensing;
using Khaemhat.Application.Modules;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Accounting;
using Khaemhat.Core.Instance;
using Khaemhat.Data;
using Khaemhat.Data.Companies;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Ledger;
/// <summary>A recurring entry being written.</summary>
/// <param name="Id">The recurring entry, or <see langword="null"/> for a new one.</param>
/// <param name="Description">What it is (rent, leasing, insurance).</param>
/// <param name="ModelEntryId">The entry copied each time (usually a draft kept as model).</param>
/// <param name="Frequency">How often.</param>
/// <param name="NextDate">The date of the next entry.</param>
/// <param name="EndDate">The last date, if any.</param>
/// <param name="Disabled">Suspended.</param>
public sealed record RecurringEntryInput(long? Id, string Description, long ModelEntryId, RecurrenceFrequency Frequency, DateOnly NextDate, DateOnly? EndDate, bool Disabled = false);
/// <summary>
/// The recurring entries (SPEC §11.7, issue #63): a model entry copied at each due date, posted with the date of the
/// due date; the job <c>ledger.recurring</c> writes those due every morning, and the screen can write them on demand.
/// An entry that cannot be posted (closed period, final journal after the date) stops its recurrence at that date
/// and is reported in the run.
/// </summary>
public sealed class RecurringEntryService
{
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
private readonly JournalEntryService _journal;
private readonly AuditTrail _audit;
/// <summary>Creates the service.</summary>
/// <param name="factory">The units of work.</param>
/// <param name="permissions">The permissions.</param>
/// <param name="journal">The journal.</param>
/// <param name="audit">The history.</param>
public RecurringEntryService(IUnitOfWorkFactory factory, PermissionService permissions, JournalEntryService journal, AuditTrail audit)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(journal);
ArgumentNullException.ThrowIfNull(audit);
_factory = factory;
_permissions = permissions;
_journal = journal;
_audit = audit;
}
/// <summary>The recurring entries, by next date.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The recurring entries.</returns>
public async Task<IReadOnlyList<RecurringEntry>> ListAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return (await uow.Repository<RecurringEntry, long>().ListAsync(Query.For<RecurringEntry>().OrderBy(r => r.NextDate), cancellationToken).ConfigureAwait(false)).Items;
}
/// <summary>Writes a recurring entry.</summary>
/// <param name="actor">Who writes.</param>
/// <param name="companyCode">The company.</param>
/// <param name="input">The recurring entry.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The recurring entry.</returns>
public async Task<RecurringEntry> SaveAsync(Actor actor, string companyCode, RecurringEntryInput input, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
ArgumentNullException.ThrowIfNull(input);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryWrite, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var errors = new List<string>();
if (string.IsNullOrWhiteSpace(input.Description))
{
errors.Add("Description:" + LedgerErrors.DescriptionRequired);
}
var model = await uow.Repository<GlEntry, long>().GetAsync(input.ModelEntryId, cancellationToken).ConfigureAwait(false);
if (model is null || model.Source == GlEntrySource.Document || model.VatRegisterId is not null)
{
errors.Add("ModelEntryId:" + LedgerErrors.RecurringModel);
}
if (input.NextDate == default)
{
errors.Add("NextDate:" + LedgerErrors.DateRequired);
}
if (errors.Count > 0)
{
throw new ValidationFailedException(errors);
}
var repository = uow.Repository<RecurringEntry, long>();
RecurringEntry? before = null;
RecurringEntry recurring;
if (input.Id is { } id)
{
recurring = await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
before = new RecurringEntry { Id = recurring.Id, Description = recurring.Description, NextDate = recurring.NextDate, Frequency = recurring.Frequency, Disabled = recurring.Disabled };
}
else
{
recurring = new RecurringEntry();
}
recurring.Description = LedgerStore.Trim(input.Description.Trim(), 200)!;
recurring.ModelEntryId = input.ModelEntryId;
recurring.Frequency = input.Frequency;
recurring.NextDate = input.NextDate;
recurring.EndDate = input.EndDate;
recurring.Disabled = input.Disabled;
if (before is null)
{
recurring.Id = await repository.InsertAsync(recurring, cancellationToken).ConfigureAwait(false);
}
else
{
await repository.UpdateAsync(recurring, cancellationToken).ConfigureAwait(false);
}
await _audit.RecordAsync(uow, before is null ? AuditAction.Insert : AuditAction.Update, recurring.Id, before, recurring, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return recurring;
}
/// <summary>Deletes a recurring entry (the entries already written stay).</summary>
/// <param name="actor">Who deletes.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The recurring entry.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task DeleteAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryWrite, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var recurring = await uow.Repository<RecurringEntry, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
await uow.Repository<RecurringEntry, long>().DeleteAsync(id, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Delete, id, recurring, null, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>Writes the recurring entries due up to a day.</summary>
/// <param name="actor">Who writes them.</param>
/// <param name="companyCode">The company.</param>
/// <param name="upTo">Up to this day.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The entries written and the problems met.</returns>
public async Task<(int Written, IReadOnlyList<string> Problems)> GenerateAsync(Actor actor, string companyCode, DateOnly upTo, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryWrite, cancellationToken).ConfigureAwait(false);
IReadOnlyList<RecurringEntry> due;
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
due = (await uow.Repository<RecurringEntry, long>().ListAsync(
Query.For<RecurringEntry>().Where(r => !r.Disabled && r.NextDate <= upTo).OrderBy(r => r.NextDate), cancellationToken).ConfigureAwait(false)).Items;
}
var written = 0;
var problems = new List<string>();
foreach (var recurring in due)
{
while (recurring.NextDate <= upTo && (recurring.EndDate is null || recurring.NextDate <= recurring.EndDate))
{
var model = await _journal.GetAsync(actor, company, recurring.ModelEntryId, cancellationToken).ConfigureAwait(false);
if (model is null)
{
problems.Add(recurring.Description + ": " + LedgerErrors.RecurringModel);
break;
}
EntryView entry;
try
{
entry = await _journal.SaveAsync(actor, company, new EntryInput(
null,
recurring.NextDate,
model.Entry.Description,
[.. model.Lines.Select(JournalEntryService.Draft)])
{
JournalTemplateId = model.Entry.JournalTemplateId,
PartyId = model.Entry.PartyId,
Notes = recurring.Description,
Post = true,
}, cancellationToken).ConfigureAwait(false);
}
catch (ValidationFailedException ex)
{
problems.Add(recurring.Description + " " + LedgerReport.Date(recurring.NextDate) + ": " + string.Join(", ", ex.Errors));
break;
}
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var source = nameof(GlEntrySource.Recurring);
var entryId = entry.Entry.Id;
await uow.ExecuteAsync(SqlFragment.Of($"UPDATE gl_entries SET source = {source} WHERE id = {entryId}"), cancellationToken).ConfigureAwait(false);
recurring.LastEntryId = entryId;
recurring.NextDate = Next(recurring.NextDate, recurring.Frequency);
if (recurring.EndDate is { } end && recurring.NextDate > end)
{
recurring.Disabled = true;
}
await uow.Repository<RecurringEntry, long>().UpdateAsync(recurring, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
written++;
}
}
return (written, problems);
}
/// <summary>The date after a due date.</summary>
/// <param name="date">The due date.</param>
/// <param name="frequency">How often.</param>
/// <returns>The next due date (the end of the month stays the end of the month).</returns>
public static DateOnly Next(DateOnly date, RecurrenceFrequency frequency)
{
var months = frequency switch
{
RecurrenceFrequency.Quarterly => 3,
RecurrenceFrequency.HalfYearly => 6,
RecurrenceFrequency.Yearly => 12,
_ => 1,
};
var endOfMonth = date.Day == DateTime.DaysInMonth(date.Year, date.Month);
var next = date.AddMonths(months);
return endOfMonth ? new DateOnly(next.Year, next.Month, DateTime.DaysInMonth(next.Year, next.Month)) : next;
}
}
/// <summary>Writes the recurring entries due of every active company with the ledger, every morning.</summary>
/// <param name="companies">The companies.</param>
/// <param name="service">The recurring entries.</param>
/// <param name="license">The licence.</param>
/// <param name="clock">The clock.</param>
public sealed class RecurringEntriesJob(ICompanyRegistry companies, RecurringEntryService service, ILicenseGate license, TimeProvider clock) : IScheduledJob
{
/// <summary>The job type.</summary>
public const string JobType = "ledger.recurring";
/// <inheritdoc />
public string Type => JobType;
/// <inheritdoc />
public async Task<string?> RunAsync(JobContext context, CancellationToken cancellationToken)
{
if (!license.IsModuleActive(ModuleCodes.Accounting))
{
return "Modulo contabilità non attivo.";
}
var today = DateOnly.FromDateTime(clock.GetLocalNow().DateTime);
int written = 0, done = 0;
var problems = new List<string>();
foreach (var company in await companies.ListAsync(cancellationToken).ConfigureAwait(false))
{
if (company.Status is CompanyStatus.Disabled)
{
continue;
}
var (w, p) = await service.GenerateAsync(Actor.System, company.Code, today, cancellationToken).ConfigureAwait(false);
written += w;
problems.AddRange(p.Select(x => company.Code + " - " + x));
done++;
}
return string.Create(CultureInfo.InvariantCulture, $"{done} aziende, {written} registrazioni ricorrenti scritte.")
+ (problems.Count > 0 ? " Non scritte: " + string.Join("; ", problems) : string.Empty);
}
}
@@ -0,0 +1,848 @@
using System.Globalization;
using Khaemhat.Application.Audit;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Accounting;
using Khaemhat.Core.Documents;
using Khaemhat.Core.Parties;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
using Khaemhat.Fiscal.Abstractions;
using Khaemhat.Infrastructure.Files;
namespace Khaemhat.Application.Ledger;
/// <summary>A withholding with the name of its party.</summary>
/// <param name="Withholding">The withholding.</param>
/// <param name="PartyName">The supplier or customer.</param>
/// <param name="PartyTaxCode">Its tax code (or VAT number).</param>
public sealed record WithholdingRow(Withholding Withholding, string PartyName, string? PartyTaxCode);
/// <summary>The stamp duty on the e-invoices of a quarter.</summary>
/// <param name="Year">The year.</param>
/// <param name="Quarter">The quarter.</param>
/// <param name="Documents">The invoices with stamp duty.</param>
/// <param name="Amount">The duty.</param>
/// <param name="DueDate">When it is paid (moved to a later quarter below the threshold).</param>
/// <param name="Payment">The F24 line, once recorded.</param>
public sealed record StampDutyQuarter(int Year, int Quarter, int Documents, decimal Amount, DateOnly DueDate, TaxPayment? Payment);
/// <summary>An invoice with stamp duty.</summary>
/// <param name="DocumentId">The invoice.</param>
/// <param name="DocumentNumber">Its number.</param>
/// <param name="DocumentDate">Its date.</param>
/// <param name="PartyName">The customer.</param>
/// <param name="Taxable">The taxable amount.</param>
/// <param name="StampDuty">The duty.</param>
/// <param name="Charged">Charged to the customer (otherwise borne by the company).</param>
/// <param name="Kind">The kind of document.</param>
public sealed record StampDutyDocument(long DocumentId, string? DocumentNumber, DateOnly DocumentDate, string? PartyName, decimal Taxable, decimal StampDuty, bool Charged, DocumentKind Kind);
/// <summary>A line of the F24 written by hand.</summary>
/// <param name="Id">The line, or <see langword="null"/> for a new one.</param>
/// <param name="DueDate">The due date.</param>
/// <param name="PaymentCode">The payment code.</param>
/// <param name="ReferenceYear">The reference year.</param>
/// <param name="ReferencePeriod">The month or installment.</param>
/// <param name="Description">What it pays.</param>
/// <param name="Amount">The amount (negative for a credit used in compensation).</param>
public sealed record TaxPaymentInput(long? Id, DateOnly DueDate, string PaymentCode, int ReferenceYear, string? ReferencePeriod, string Description, decimal Amount);
/// <summary>
/// The taxes that the ledger pays and keeps (SPEC §11.7, issues #65-#66, mockups 047 and 060, ADR 0037): the lines of
/// the F24 with their data file and their payment entry; the withholdings operated on the fees received (due when the
/// invoice is paid, by the 16th of the next month) and suffered on the fees issued, with the data for the CU; the
/// quarterly stamp duty on the e-invoices.
/// </summary>
public sealed class TaxService
{
/// <summary>The stamp duty of a quarter at or below this moves to the next due date (DM 4/12/2023).</summary>
public const decimal StampDutyThreshold = 5000m;
// The sale documents that carry the stamp duty of the quarter: invoices, fees, debit and credit notes.
private static readonly SqlFragment StampKinds = SqlFragment.Join(", ", new[]
{
DocumentKind.ImmediateInvoice, DocumentKind.AccompanyingInvoice, DocumentKind.DeferredInvoice, DocumentKind.DownPaymentInvoice,
DocumentKind.CreditNote, DocumentKind.DebitNote, DocumentKind.Fee,
}.Select(k => SqlFragment.Parameter(k.ToString())));
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
private readonly CompanyFiscalContext _packs;
private readonly AuditTrail _audit;
private readonly TimeProvider _clock;
/// <summary>Creates the service.</summary>
/// <param name="factory">The units of work.</param>
/// <param name="permissions">The permissions.</param>
/// <param name="packs">The fiscal pack of each company.</param>
/// <param name="audit">The history.</param>
/// <param name="clock">The clock.</param>
public TaxService(IUnitOfWorkFactory factory, PermissionService permissions, CompanyFiscalContext packs, AuditTrail audit, TimeProvider clock)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(packs);
ArgumentNullException.ThrowIfNull(audit);
ArgumentNullException.ThrowIfNull(clock);
_factory = factory;
_permissions = permissions;
_packs = packs;
_audit = audit;
_clock = clock;
}
/// <summary>The F24 lines due in a year.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="year">The year of the due dates.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The lines, by due date and code.</returns>
public async Task<IReadOnlyList<TaxPayment>> PaymentsAsync(Actor actor, string companyCode, int year, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var from = new DateOnly(year, 1, 1);
var to = new DateOnly(year, 12, 31);
return (await uow.Repository<TaxPayment, long>().ListAsync(
Query.For<TaxPayment>().Where(t => t.DueDate >= from && t.DueDate <= to).OrderBy(t => t.DueDate).OrderBy(t => t.PaymentCode), cancellationToken).ConfigureAwait(false)).Items;
}
/// <summary>Writes a line of the F24 by hand (a tax the ledger does not compute, or a credit used in compensation).</summary>
/// <param name="actor">Who writes.</param>
/// <param name="companyCode">The company.</param>
/// <param name="input">The line.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The line.</returns>
public async Task<TaxPayment> SavePaymentAsync(Actor actor, string companyCode, TaxPaymentInput input, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
ArgumentNullException.ThrowIfNull(input);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementConfirm, cancellationToken).ConfigureAwait(false);
var errors = new List<string>();
if (string.IsNullOrWhiteSpace(input.PaymentCode) || input.PaymentCode.Trim().Length > 10)
{
errors.Add("PaymentCode:" + LedgerErrors.AmountRequired);
}
if (string.IsNullOrWhiteSpace(input.Description))
{
errors.Add("Description:" + LedgerErrors.DescriptionRequired);
}
if (input.Amount == 0m)
{
errors.Add("Amount:" + LedgerErrors.AmountRequired);
}
if (errors.Count > 0)
{
throw new ValidationFailedException(errors);
}
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var payments = uow.Repository<TaxPayment, long>();
TaxPayment? before = null;
TaxPayment payment;
if (input.Id is { } id)
{
payment = await payments.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
if (payment.PaidOn is not null || payment.Source != TaxPaymentSource.Manual)
{
throw new ValidationFailedException(["Id:" + LedgerErrors.PaymentPaid]);
}
before = Copy(payment);
}
else
{
payment = new TaxPayment { Source = TaxPaymentSource.Manual };
}
payment.DueDate = input.DueDate;
payment.PaymentCode = input.PaymentCode.Trim();
payment.ReferenceYear = input.ReferenceYear;
payment.ReferencePeriod = LedgerStore.Trim(input.ReferencePeriod?.Trim(), 10);
payment.Description = LedgerStore.Trim(input.Description.Trim(), 200)!;
payment.Amount = input.Amount;
if (before is null)
{
payment.Id = await payments.InsertAsync(payment, cancellationToken).ConfigureAwait(false);
}
else
{
await payments.UpdateAsync(payment, cancellationToken).ConfigureAwait(false);
}
await _audit.RecordAsync(uow, before is null ? AuditAction.Insert : AuditAction.Update, payment.Id, before, payment, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return payment;
}
/// <summary>Deletes a line written by hand and not paid.</summary>
/// <param name="actor">Who deletes.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The line.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task DeletePaymentAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementConfirm, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var payment = await uow.Repository<TaxPayment, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
if (payment.PaidOn is not null || payment.Source != TaxPaymentSource.Manual)
{
throw new ValidationFailedException(["Id:" + LedgerErrors.PaymentPaid]);
}
await uow.Repository<TaxPayment, long>().DeleteAsync(id, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Delete, id, payment, null, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>The F24 of a due date: its unpaid lines, one per code and period.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="dueDate">The due date.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The form.</returns>
public async Task<TaxPaymentForm> FormAsync(Actor actor, string companyCode, DateOnly dueDate, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return await FormAsync(uow, dueDate, paid: false, cancellationToken).ConfigureAwait(false);
}
/// <summary>The data file of the F24 of a due date.</summary>
/// <param name="actor">Who asks.</param>
/// <param name="companyCode">The company.</param>
/// <param name="dueDate">The due date.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The file.</returns>
public async Task<LedgerFile> ExportFormAsync(Actor actor, string companyCode, DateOnly dueDate, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementRead, cancellationToken).ConfigureAwait(false);
var exporter = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require<ITaxPaymentFormExporter>();
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var form = await FormAsync(uow, dueDate, paid: null, cancellationToken).ConfigureAwait(false);
return new LedgerFile(exporter.FileName(form), "text/csv", exporter.Export(form));
}
/// <summary>
/// Records the payment of the F24 of a due date: its lines are paid, the withholdings in it are paid, and the entry
/// <c>F24</c> moves the tax accounts against the bank.
/// </summary>
/// <param name="actor">Who records it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="dueDate">The due date.</param>
/// <param name="paidOn">The day of payment.</param>
/// <param name="bankAccountId">The bank account debited; <see langword="null"/> for the default one.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The payment entry, if the ledger has the template.</returns>
public async Task<GlEntry?> PayAsync(Actor actor, string companyCode, DateOnly dueDate, DateOnly paidOn, long? bankAccountId = null, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementConfirm, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var payments = (await uow.Repository<TaxPayment, long>().ListAsync(
Query.For<TaxPayment>().Where(t => t.DueDate == dueDate && t.PaidOn == null).OrderBy(t => t.PaymentCode), cancellationToken).ConfigureAwait(false)).Items;
if (payments.Count == 0)
{
throw new ValidationFailedException(["DueDate:" + LedgerErrors.PaymentPaid]);
}
var bank = await BankAsync(uow, bankAccountId, cancellationToken).ConfigureAwait(false);
GlEntry? entry = null;
if (await LedgerStore.TemplateAsync(uow, "F24", cancellationToken).ConfigureAwait(false) is { } found)
{
var (template, templateLines) = found;
long? Role(PostingRole role) => templateLines.FirstOrDefault(l => l.Role == role && l.AccountId is not null)?.AccountId;
var stampAccount = templateLines.FirstOrDefault(l => l.Role == PostingRole.Account && l.AccountId is not null)?.AccountId;
var bankAccount = (await LedgerStore.AccountAsync(uow, bank?.AccountCode, cancellationToken).ConfigureAwait(false))?.Id ?? Role(PostingRole.Bank);
var lines = new List<EntryLineDraft>();
foreach (var payment in payments)
{
var account = payment.Source switch
{
TaxPaymentSource.Withholding => Role(PostingRole.WithholdingPayable),
TaxPaymentSource.StampDuty => stampAccount,
_ => Role(PostingRole.VatSettlement),
};
if (account is null)
{
throw new ValidationFailedException(["Ledger:" + LedgerErrors.RoleAccountMissing]);
}
var text = LedgerStore.Trim(payment.PaymentCode + " " + payment.Description, 200);
lines.Add(payment.Amount >= 0m
? new EntryLineDraft(account, null, text, payment.Amount, 0m)
: new EntryLineDraft(account, null, text, 0m, -payment.Amount));
}
var total = payments.Sum(p => p.Amount);
if (bankAccount is null)
{
throw new ValidationFailedException(["BankAccountId:" + LedgerErrors.BankAccountMissing]);
}
if (total != 0m)
{
lines.Add(total > 0m ? new EntryLineDraft(bankAccount, null, "Addebito F24", 0m, total) : new EntryLineDraft(bankAccount, null, "Addebito F24", -total, 0m));
}
entry = await LedgerStore.InsertAsync(uow, new GlEntry
{
EntryDate = paidOn,
JournalTemplateId = template.Id,
TemplateCode = template.Code,
Description = LedgerStore.Trim(template.Description + " scadenza " + LedgerReport.Date(dueDate), 200)!,
Status = GlEntryStatus.Posted,
Source = GlEntrySource.TaxPayment,
IsDemo = payments.All(p => p.IsDemo),
}, lines, [], cancellationToken).ConfigureAwait(false);
}
foreach (var payment in payments)
{
var before = Copy(payment);
payment.PaidOn = paidOn;
payment.BankAccountId = bank?.Id;
payment.GlEntryId = entry?.Id;
await uow.Repository<TaxPayment, long>().UpdateAsync(payment, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, payment.Id, before, payment, actor.UserName, cancellationToken).ConfigureAwait(false);
if (payment.Source == TaxPaymentSource.Withholding)
{
var paymentId = payment.Id;
var paidStatus = nameof(WithholdingStatus.Paid);
await uow.ExecuteAsync(SqlFragment.Of($"UPDATE withholdings SET status = {paidStatus} WHERE tax_payment_id = {paymentId}"), cancellationToken).ConfigureAwait(false);
}
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return entry;
}
/// <summary>Takes back the payment of an F24: the entry goes (or is reversed when final), the lines are unpaid.</summary>
/// <param name="actor">Who does it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="dueDate">The due date.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task UnpayAsync(Actor actor, string companyCode, DateOnly dueDate, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementConfirm, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var payments = (await uow.Repository<TaxPayment, long>().ListAsync(
Query.For<TaxPayment>().Where(t => t.DueDate == dueDate && t.PaidOn != null), cancellationToken).ConfigureAwait(false)).Items;
foreach (var entryId in payments.Select(p => p.GlEntryId).OfType<long>().Distinct())
{
if (await uow.Repository<GlEntry, long>().GetAsync(entryId, cancellationToken).ConfigureAwait(false) is not { } entry)
{
continue;
}
if (entry.Status == GlEntryStatus.Final)
{
await JournalEntryService.ReverseAsync(uow, entry, Today(), actor.UserName, cancellationToken).ConfigureAwait(false);
}
else
{
await LedgerStore.DeleteAsync(uow, entryId, cancellationToken).ConfigureAwait(false);
}
}
foreach (var payment in payments)
{
var before = Copy(payment);
payment.PaidOn = null;
payment.GlEntryId = null;
payment.BankAccountId = null;
await uow.Repository<TaxPayment, long>().UpdateAsync(payment, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, payment.Id, before, payment, actor.UserName, cancellationToken).ConfigureAwait(false);
var paymentId = payment.Id;
var due = nameof(WithholdingStatus.Due);
await uow.ExecuteAsync(SqlFragment.Of($"UPDATE withholdings SET status = {due} WHERE tax_payment_id = {paymentId}"), cancellationToken).ConfigureAwait(false);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>The withholdings of the documents of a year.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="year">The year of the documents.</param>
/// <param name="direction">Operated or suffered; <see langword="null"/> for both.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The withholdings, by date.</returns>
public async Task<IReadOnlyList<WithholdingRow>> WithholdingsAsync(
Actor actor, string companyCode, int year, WithholdingDirection? direction = null, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var from = new DateOnly(year, 1, 1);
var to = new DateOnly(year, 12, 31);
var query = Query.For<Withholding>().Where(w => w.DocumentDate >= from && w.DocumentDate <= to);
if (direction is { } d)
{
query = query.Where(w => w.Direction == d);
}
var items = (await uow.Repository<Withholding, long>().ListAsync(query.OrderBy(w => w.DocumentDate), cancellationToken).ConfigureAwait(false)).Items;
return await RowsAsync(uow, items, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Records that the invoice of a withholding has been paid. An operated withholding becomes due: the entry
/// <c>RIT</c> moves it from the supplier to the tax authority, and it joins the F24 line of its code due on the
/// 16th of the next month. A suffered withholding: the entry <c>RITS</c> moves it from the customer to the tax credit.
/// </summary>
/// <param name="actor">Who records it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The withholding.</param>
/// <param name="paidOn">The day the invoice was paid.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The withholding.</returns>
public async Task<Withholding> InvoicePaidAsync(Actor actor, string companyCode, long id, DateOnly paidOn, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementConfirm, cancellationToken).ConfigureAwait(false);
var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
var settlementRules = pack.Require<IVatSettlementRules>();
var withholdingRules = pack.GetFeature<IWithholdingRules>();
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var withholding = await uow.Repository<Withholding, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
if (withholding.InvoicePaidOn is not null)
{
throw new ValidationFailedException(["Id:" + LedgerErrors.PaymentPaid]);
}
var before = Copy(withholding);
var operated = withholding.Direction == WithholdingDirection.Operated;
var entry = await PostWithholdingAsync(uow, withholding, paidOn, operated ? "RIT" : "RITS", cancellationToken).ConfigureAwait(false);
withholding.InvoicePaidOn = paidOn;
withholding.GlEntryId = entry?.Id;
if (operated)
{
withholding.Status = WithholdingStatus.Due;
withholding.PaymentCode ??= PaymentCodeOf(withholding, withholdingRules);
var due = settlementRules.WithholdingDue(paidOn.Year, paidOn.Month);
var code = withholding.PaymentCode;
var payments = uow.Repository<TaxPayment, long>();
var period = paidOn.Month.ToString("00", CultureInfo.InvariantCulture);
var year = paidOn.Year;
var payment = await payments.FindAsync(
Query.For<TaxPayment>().Where(t => t.Source == TaxPaymentSource.Withholding && t.PaymentCode == code && t.ReferenceYear == year
&& t.ReferencePeriod == period && t.PaidOn == null),
cancellationToken).ConfigureAwait(false);
if (payment is null)
{
payment = new TaxPayment
{
DueDate = due,
PaymentCode = code,
ReferenceYear = year,
ReferencePeriod = period,
Description = LedgerStore.Trim("Ritenute d'acconto " + paidOn.ToString("MMMM yyyy", CultureInfo.GetCultureInfo("it-IT")), 200)!,
Amount = withholding.Amount,
Source = TaxPaymentSource.Withholding,
IsDemo = withholding.IsDemo,
};
payment.Id = await payments.InsertAsync(payment, cancellationToken).ConfigureAwait(false);
}
else
{
payment.Amount += withholding.Amount;
await payments.UpdateAsync(payment, cancellationToken).ConfigureAwait(false);
}
withholding.TaxPaymentId = payment.Id;
}
await uow.Repository<Withholding, long>().UpdateAsync(withholding, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, withholding.Id, before, withholding, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return withholding;
}
/// <summary>Takes back the payment of the invoice of a withholding while its F24 line is not paid.</summary>
/// <param name="actor">Who does it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The withholding.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The withholding.</returns>
public async Task<Withholding> UndoInvoicePaidAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementConfirm, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var withholding = await uow.Repository<Withholding, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
if (withholding.Status == WithholdingStatus.Paid)
{
throw new ValidationFailedException(["Id:" + LedgerErrors.PaymentPaid]);
}
var before = Copy(withholding);
if (withholding.TaxPaymentId is { } paymentId && await uow.Repository<TaxPayment, long>().GetAsync(paymentId, cancellationToken).ConfigureAwait(false) is { } payment)
{
payment.Amount -= withholding.Amount;
if (payment.Amount == 0m)
{
await uow.Repository<TaxPayment, long>().DeleteAsync(paymentId, cancellationToken).ConfigureAwait(false);
}
else
{
await uow.Repository<TaxPayment, long>().UpdateAsync(payment, cancellationToken).ConfigureAwait(false);
}
}
if (withholding.GlEntryId is { } entryId && await uow.Repository<GlEntry, long>().GetAsync(entryId, cancellationToken).ConfigureAwait(false) is { } entry)
{
if (entry.Status == GlEntryStatus.Final)
{
await JournalEntryService.ReverseAsync(uow, entry, Today(), actor.UserName, cancellationToken).ConfigureAwait(false);
}
else
{
await LedgerStore.DeleteAsync(uow, entryId, cancellationToken).ConfigureAwait(false);
}
}
withholding.InvoicePaidOn = null;
withholding.GlEntryId = null;
withholding.TaxPaymentId = null;
withholding.Status = withholding.Direction == WithholdingDirection.Operated ? WithholdingStatus.Waiting : WithholdingStatus.Suffered;
await uow.Repository<Withholding, long>().UpdateAsync(withholding, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, withholding.Id, before, withholding, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return withholding;
}
/// <summary>
/// The data for the single certifications (CU) of a year: one row per payee with the fees paid in the year, the
/// taxable amount, the withholdings and the reason, as the intermediary needs them to fill the model.
/// </summary>
/// <param name="actor">Who asks.</param>
/// <param name="companyCode">The company.</param>
/// <param name="year">The year of payment.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The CSV file.</returns>
public async Task<LedgerFile> CertificationsAsync(Actor actor, string companyCode, int year, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var from = new DateOnly(year, 1, 1);
var to = new DateOnly(year, 12, 31);
var items = (await uow.Repository<Withholding, long>().ListAsync(
Query.For<Withholding>().Where(w => w.Direction == WithholdingDirection.Operated && w.InvoicePaidOn >= from && w.InvoicePaidOn <= to).OrderBy(w => w.PartyId),
cancellationToken).ConfigureAwait(false)).Items;
var rows = await RowsAsync(uow, items, cancellationToken).ConfigureAwait(false);
using var buffer = new MemoryStream();
await using (var csv = new CsvWriter(buffer, CsvOptions.Italian, leaveOpen: true))
{
await csv.WriteRowAsync(
["codice_fiscale", "denominazione", "causale", "anno", "compenso_lordo", "somme_non_soggette", "imponibile", "ritenute", "codice_tributo", "documenti"],
cancellationToken).ConfigureAwait(false);
foreach (var group in rows.GroupBy(r => (r.Withholding.PartyId, r.Withholding.Reason, r.Withholding.PaymentCode)))
{
var first = group.First();
var gross = group.Sum(r => r.Withholding.Taxable);
var taxable = group.Sum(r => Math.Round(r.Withholding.Taxable * r.Withholding.BasePercent / 100m, 2, MidpointRounding.AwayFromZero));
await csv.WriteRowAsync(
[first.PartyTaxCode, first.PartyName, group.Key.Reason, year, gross, gross - taxable, taxable, group.Sum(r => r.Withholding.Amount), group.Key.PaymentCode,
string.Join(' ', group.Select(r => r.Withholding.DocumentNumber))],
cancellationToken).ConfigureAwait(false);
}
}
return new LedgerFile(string.Create(CultureInfo.InvariantCulture, $"CU_{year}.csv"), "text/csv", buffer.ToArray());
}
/// <summary>The stamp duty on the e-invoices of each quarter of a year.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="year">The year.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>Four quarters.</returns>
public async Task<IReadOnlyList<StampDutyQuarter>> StampDutyAsync(Actor actor, string companyCode, int year, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementRead, cancellationToken).ConfigureAwait(false);
var rules = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require<IVatSettlementRules>();
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return await StampDutyAsync(uow, rules, year, cancellationToken).ConfigureAwait(false);
}
/// <summary>The sale invoices with stamp duty of a quarter.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="year">The year.</param>
/// <param name="quarter">The quarter.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The invoices, by date.</returns>
public async Task<IReadOnlyList<StampDutyDocument>> StampDutyDocumentsAsync(Actor actor, string companyCode, int year, int quarter, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var from = new DateOnly(year, ((quarter - 1) * 3) + 1, 1);
var to = from.AddMonths(3).AddDays(-1);
var draft = nameof(DocumentStatus.Draft);
var cancelled = nameof(DocumentStatus.Cancelled);
return await uow.QueryAsync<StampDutyDocument>(SqlFragment.Of($"""
SELECT d.id AS document_id, d.document_number AS document_number, d.document_date AS document_date, p.name AS party_name,
d.taxable_amount AS taxable, d.stamp_duty AS stamp_duty, d.stamp_duty_charged AS charged, d.kind AS kind
FROM sale_documents d LEFT JOIN parties p ON p.id = d.party_id
WHERE d.stamp_duty > 0 AND d.document_date >= {from} AND d.document_date <= {to} AND d.status <> {draft} AND d.status <> {cancelled} AND d.kind IN ({StampKinds})
ORDER BY d.document_date, d.number
"""), cancellationToken).ConfigureAwait(false);
}
/// <summary>Records the F24 line of the stamp duty of a quarter (or updates it while unpaid).</summary>
/// <param name="actor">Who records it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="year">The year.</param>
/// <param name="quarter">The quarter.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The line, or <see langword="null"/> when no duty is due.</returns>
public async Task<TaxPayment?> StampDutyPaymentAsync(Actor actor, string companyCode, int year, int quarter, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
ArgumentOutOfRangeException.ThrowIfLessThan(quarter, 1);
ArgumentOutOfRangeException.ThrowIfGreaterThan(quarter, 4);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementConfirm, cancellationToken).ConfigureAwait(false);
var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
var rules = pack.Require<IVatSettlementRules>();
var form = pack.Require<ITaxPaymentFormExporter>();
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var data = (await StampDutyAsync(uow, rules, year, cancellationToken).ConfigureAwait(false))[quarter - 1];
if (data.Payment is { PaidOn: not null })
{
throw new ValidationFailedException(["Quarter:" + LedgerErrors.PaymentPaid]);
}
if (data.Amount == 0m)
{
if (data.Payment is { } stale)
{
await uow.Repository<TaxPayment, long>().DeleteAsync(stale.Id, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
return null;
}
var payment = data.Payment ?? new TaxPayment { Source = TaxPaymentSource.StampDuty, SourceId = (year * 10L) + quarter, ReferenceYear = year };
var before = data.Payment is null ? null : Copy(payment);
payment.DueDate = data.DueDate;
payment.PaymentCode = form.StampDutyCode(quarter);
payment.Description = string.Create(CultureInfo.InvariantCulture, $"Imposta di bollo fatture elettroniche {quarter}° trimestre {year} ({data.Documents} fatture)");
payment.Amount = data.Amount;
if (before is null)
{
payment.Id = await uow.Repository<TaxPayment, long>().InsertAsync(payment, cancellationToken).ConfigureAwait(false);
}
else
{
await uow.Repository<TaxPayment, long>().UpdateAsync(payment, cancellationToken).ConfigureAwait(false);
}
await _audit.RecordAsync(uow, before is null ? AuditAction.Insert : AuditAction.Update, payment.Id, before, payment, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return payment;
}
/// <summary>
/// The stamp duty of each quarter from the issued sale invoices with the duty, with the due date moved when the
/// amount stays below the threshold: the first quarter with the second, the first two with the third.
/// </summary>
internal static async Task<IReadOnlyList<StampDutyQuarter>> StampDutyAsync(IUnitOfWork uow, IVatSettlementRules rules, int year, CancellationToken cancellationToken)
{
var from = new DateOnly(year, 1, 1);
var to = new DateOnly(year, 12, 31);
var draft = nameof(DocumentStatus.Draft);
var cancelled = nameof(DocumentStatus.Cancelled);
var rows = await uow.QueryAsync<StampRow>(SqlFragment.Of($"""
SELECT document_date AS document_date, stamp_duty AS stamp_duty FROM sale_documents
WHERE stamp_duty > 0 AND document_date >= {from} AND document_date <= {to} AND status <> {draft} AND status <> {cancelled} AND kind IN ({StampKinds})
"""), cancellationToken).ConfigureAwait(false);
var payments = (await uow.Repository<TaxPayment, long>().ListAsync(
Query.For<TaxPayment>().Where(t => t.Source == TaxPaymentSource.StampDuty && t.ReferenceYear == year), cancellationToken).ConfigureAwait(false)).Items;
var result = new List<StampDutyQuarter>();
var carried = 0m;
for (var q = 1; q <= 4; q++)
{
var quarter = rows.Where(r => ((r.DocumentDate.Month - 1) / 3) + 1 == q).ToList();
var amount = quarter.Sum(r => r.StampDuty);
var due = rules.StampDutyDue(year, q);
if (q == 1 && amount <= StampDutyThreshold)
{
due = rules.StampDutyDue(year, 2);
carried = amount;
}
else if (q == 2 && carried > 0m && carried + amount <= StampDutyThreshold)
{
due = rules.StampDutyDue(year, 3);
carried += amount;
}
else
{
carried = 0m;
}
var sourceId = (year * 10L) + q;
result.Add(new StampDutyQuarter(year, q, quarter.Count, amount, due, payments.FirstOrDefault(p => p.SourceId == sourceId)));
}
// A first quarter moved to the second, when the second goes over the threshold, keeps the due date of the second.
if (result[0].DueDate == rules.StampDutyDue(year, 2) && result[1].DueDate == rules.StampDutyDue(year, 3))
{
result[0] = result[0] with { DueDate = rules.StampDutyDue(year, 3) };
}
return result;
}
private static async Task<TaxPaymentForm> FormAsync(IUnitOfWork uow, DateOnly dueDate, bool? paid, CancellationToken cancellationToken)
{
var query = Query.For<TaxPayment>().Where(t => t.DueDate == dueDate);
query = paid switch
{
true => query.Where(t => t.PaidOn != null),
false => query.Where(t => t.PaidOn == null),
_ => query,
};
var payments = (await uow.Repository<TaxPayment, long>().ListAsync(query.OrderBy(t => t.PaymentCode), cancellationToken).ConfigureAwait(false)).Items;
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
var lines = payments
.GroupBy(p => (p.PaymentCode, p.ReferencePeriod, p.ReferenceYear))
.Select(g =>
{
var amount = g.Sum(p => p.Amount);
return new TaxPaymentFormLine(g.Key.PaymentCode, g.Key.ReferencePeriod, g.Key.ReferenceYear, Math.Max(0m, amount), Math.Max(0m, -amount), g.First().Description);
})
.ToList();
return new TaxPaymentForm(dueDate, profile?.TaxCode ?? profile?.VatNumber ?? string.Empty, profile?.LegalName ?? string.Empty, lines);
}
private static async Task<BankAccount?> BankAsync(IUnitOfWork uow, long? id, CancellationToken cancellationToken)
{
var banks = uow.Repository<BankAccount, long>();
if (id is { } bankId)
{
return await banks.GetAsync(bankId, cancellationToken).ConfigureAwait(false) ?? throw new ValidationFailedException(["BankAccountId:" + LedgerErrors.BankAccountMissing]);
}
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
if (profile?.DefaultBankAccountId is { } defaultId && await banks.GetAsync(defaultId, cancellationToken).ConfigureAwait(false) is { } preferred)
{
return preferred;
}
return await banks.FindAsync(Query.For<BankAccount>().Where(b => b.IsDefault), cancellationToken).ConfigureAwait(false);
}
// The entry of a withholding when its invoice is paid: operated, supplier debit / withholdings payable credit;
// suffered, withholdings credit debit / customer credit. The party keeps its own account when it has one.
private static async Task<GlEntry?> PostWithholdingAsync(IUnitOfWork uow, Withholding withholding, DateOnly date, string templateCode, CancellationToken cancellationToken)
{
if (await LedgerStore.TemplateAsync(uow, templateCode, cancellationToken).ConfigureAwait(false) is not { } found)
{
return null;
}
var (template, templateLines) = found;
var operated = withholding.Direction == WithholdingDirection.Operated;
var party = await uow.Repository<Party, long>().GetAsync(withholding.PartyId, cancellationToken).ConfigureAwait(false);
var partyRole = operated ? PostingRole.Supplier : PostingRole.Customer;
var taxRole = operated ? PostingRole.WithholdingPayable : PostingRole.WithholdingCredit;
var partyAccount = (await LedgerStore.AccountAsync(uow, operated ? party?.SupplierAccountCode : party?.CustomerAccountCode, cancellationToken).ConfigureAwait(false))?.Id
?? templateLines.FirstOrDefault(l => l.Role == partyRole)?.AccountId;
var taxAccount = templateLines.FirstOrDefault(l => l.Role == taxRole)?.AccountId;
if (partyAccount is null || taxAccount is null)
{
throw new ValidationFailedException(["Ledger:" + LedgerErrors.RoleAccountMissing]);
}
var amount = Math.Abs(withholding.Amount);
var credit = withholding.Amount < 0m;
var text = LedgerStore.Trim("Ritenuta fattura " + withholding.DocumentNumber, 200);
EntryLineDraft Line(long account, long? partyId, bool debit) =>
debit != credit ? new EntryLineDraft(account, partyId, text, amount, 0m) : new EntryLineDraft(account, partyId, text, 0m, amount);
IReadOnlyList<EntryLineDraft> lines = operated
? [Line(partyAccount.Value, withholding.PartyId, debit: true), Line(taxAccount.Value, null, debit: false)]
: [Line(taxAccount.Value, null, debit: true), Line(partyAccount.Value, withholding.PartyId, debit: false)];
return await LedgerStore.InsertAsync(uow, new GlEntry
{
EntryDate = date,
JournalTemplateId = template.Id,
TemplateCode = template.Code,
Description = LedgerStore.Trim(template.Description + " " + withholding.DocumentNumber, 200)!,
Status = GlEntryStatus.Posted,
Source = GlEntrySource.Withholding,
SourceFamily = withholding.SourceFamily,
SourceDocumentId = withholding.SourceDocumentId,
DocumentNumber = withholding.DocumentNumber,
DocumentDate = withholding.DocumentDate,
PartyId = withholding.PartyId,
IsDemo = withholding.IsDemo,
}, lines, [], cancellationToken).ConfigureAwait(false);
}
private static string PaymentCodeOf(Withholding withholding, IWithholdingRules? rules)
{
var kinds = rules?.Kinds ?? [];
var kind = kinds.FirstOrDefault(k => k.InvoiceType == withholding.WithholdingType && k.Rate == withholding.Rate && k.PaymentReason == withholding.Reason)
?? kinds.FirstOrDefault(k => k.InvoiceType == withholding.WithholdingType && k.PaymentReason == withholding.Reason)
?? kinds.FirstOrDefault(k => k.InvoiceType == withholding.WithholdingType);
return kind?.PaymentCode ?? "1040";
}
private static async Task<IReadOnlyList<WithholdingRow>> RowsAsync(IUnitOfWork uow, IReadOnlyList<Withholding> items, CancellationToken cancellationToken)
{
var ids = items.Select(w => w.PartyId).Distinct().ToList();
var parties = ids.Count == 0
? []
: (await uow.Repository<Party, long>().ListAsync(Query.For<Party>().Where(p => ids.Contains(p.Id)), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(p => p.Id);
return [.. items.Select(w => parties.TryGetValue(w.PartyId, out var p)
? new WithholdingRow(w, p.Name, p.TaxCode ?? p.VatNumber)
: new WithholdingRow(w, string.Empty, null))];
}
private DateOnly Today() => DateOnly.FromDateTime(_clock.GetLocalNow().DateTime);
private static TaxPayment Copy(TaxPayment p) => new()
{
Id = p.Id,
DueDate = p.DueDate,
PaymentCode = p.PaymentCode,
ReferenceYear = p.ReferenceYear,
ReferencePeriod = p.ReferencePeriod,
Description = p.Description,
Amount = p.Amount,
Source = p.Source,
PaidOn = p.PaidOn,
GlEntryId = p.GlEntryId,
};
private static Withholding Copy(Withholding w) => new()
{
Id = w.Id,
Direction = w.Direction,
DocumentNumber = w.DocumentNumber,
Amount = w.Amount,
Status = w.Status,
InvoicePaidOn = w.InvoicePaidOn,
TaxPaymentId = w.TaxPaymentId,
GlEntryId = w.GlEntryId,
};
private sealed record StampRow(DateOnly DocumentDate, decimal StampDuty);
}
@@ -0,0 +1,770 @@
using System.Globalization;
using Khaemhat.Application.Audit;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Accounting;
using Khaemhat.Core.Tables;
using Khaemhat.Core.Tax;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Application.Ledger;
/// <summary>A line of a VAT register.</summary>
/// <param name="EntryId">The entry.</param>
/// <param name="EntryNumber">The number of the entry.</param>
/// <param name="VatProtocol">The protocol.</param>
/// <param name="VatDate">The VAT date.</param>
/// <param name="DocumentNumber">The number of the document.</param>
/// <param name="DocumentDate">The date of the document.</param>
/// <param name="PartyName">The customer or supplier.</param>
/// <param name="Rate">The rate.</param>
/// <param name="Nature">The nature.</param>
/// <param name="Exigibility">When the VAT is due.</param>
/// <param name="Taxable">The taxable amount.</param>
/// <param name="Tax">The VAT.</param>
/// <param name="NonDeductibleTax">The VAT not deductible.</param>
/// <param name="Status">The state of the entry.</param>
public sealed record VatRegisterRow(
long EntryId, string? EntryNumber, long? VatProtocol, DateOnly VatDate, string? DocumentNumber, DateOnly? DocumentDate, string? PartyName,
decimal Rate, string? Nature, TaxExigibility Exigibility, decimal Taxable, decimal Tax, decimal NonDeductibleTax, GlEntryStatus Status);
/// <summary>A total by rate of a VAT register.</summary>
/// <param name="Rate">The rate.</param>
/// <param name="Nature">The nature.</param>
/// <param name="Taxable">The taxable amount.</param>
/// <param name="Tax">The VAT.</param>
/// <param name="NonDeductibleTax">The VAT not deductible.</param>
public sealed record VatRateTotal(decimal Rate, string? Nature, decimal Taxable, decimal Tax, decimal NonDeductibleTax);
/// <summary>A VAT register in a period.</summary>
/// <param name="Register">The register.</param>
/// <param name="Rows">The lines, by date and protocol.</param>
/// <param name="Totals">The totals by rate.</param>
public sealed record VatRegisterView(VatRegister Register, IReadOnlyList<VatRegisterRow> Rows, IReadOnlyList<VatRateTotal> Totals);
/// <summary>A settlement with its lines and the names of its registers.</summary>
/// <param name="Settlement">The settlement.</param>
/// <param name="Lines">One line per register.</param>
/// <param name="Registers">The registers, by id.</param>
public sealed record VatSettlementView(VatSettlement Settlement, IReadOnlyList<VatSettlementLine> Lines, IReadOnlyDictionary<long, VatRegister> Registers);
/// <summary>A file produced by the ledger.</summary>
/// <param name="FileName">The name proposed.</param>
/// <param name="MediaType">The media type.</param>
/// <param name="Content">The content.</param>
public sealed record LedgerFile(string FileName, string MediaType, byte[] Content);
/// <summary>
/// The VAT of the ledger (SPEC §11.7, issue #65, mockups 045-046, ADR 0037): the registers read from the VAT lines of
/// the posted entries, their provisional print and their final print with the pages numbered by year; the periodic
/// settlement, monthly or quarterly as the company profile says, with the credit and the debit below the minimum
/// carried, the interest of quarterly payers, the pro rata and the December advance; its confirmation settles the
/// periods (no more VAT documents in them), posts the entry that closes the VAT accounts and writes the F24 line; the
/// communication of the settlements (LIPE) of a quarter.
/// </summary>
public sealed class VatService
{
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
private readonly CompanyFiscalContext _packs;
private readonly FiscalYearService _fiscal;
private readonly AuditTrail _audit;
private readonly TimeProvider _clock;
/// <summary>Creates the service.</summary>
/// <param name="factory">The units of work.</param>
/// <param name="permissions">The permissions.</param>
/// <param name="packs">The fiscal pack of each company.</param>
/// <param name="fiscal">The fiscal calendar.</param>
/// <param name="audit">The history.</param>
/// <param name="clock">The clock.</param>
public VatService(IUnitOfWorkFactory factory, PermissionService permissions, CompanyFiscalContext packs, FiscalYearService fiscal, AuditTrail audit, TimeProvider clock)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(packs);
ArgumentNullException.ThrowIfNull(fiscal);
ArgumentNullException.ThrowIfNull(audit);
ArgumentNullException.ThrowIfNull(clock);
_factory = factory;
_permissions = permissions;
_packs = packs;
_fiscal = fiscal;
_audit = audit;
_clock = clock;
}
/// <summary>A VAT register in a period.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="registerId">The register.</param>
/// <param name="from">From this VAT date.</param>
/// <param name="to">Up to this VAT date.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The register.</returns>
public async Task<VatRegisterView> RegisterAsync(Actor actor, string companyCode, long registerId, DateOnly from, DateOnly to, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.VatRegisterRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return await RegisterAsync(uow, registerId, from, to, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The print of a register: provisional (any period, nothing recorded) or final (from the day after the last final
/// print, numbering the pages after the last page of the year).
/// </summary>
/// <param name="actor">Who prints.</param>
/// <param name="companyCode">The company.</param>
/// <param name="registerId">The register.</param>
/// <param name="from">From this day (for a final print, the day after the last one).</param>
/// <param name="to">Up to this day.</param>
/// <param name="final">A final print.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The PDF.</returns>
public async Task<LedgerFile> PrintRegisterAsync(Actor actor, string companyCode, long registerId, DateOnly from, DateOnly to, bool final, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(
_permissions, actor, companyCode, final ? LedgerPermissions.SettlementConfirm : LedgerPermissions.VatRegisterRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var register = await uow.Repository<VatRegister, long>().GetAsync(registerId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.VatRegisterRequired);
var firstPage = 1;
if (final)
{
var expected = register.LastPrintedDate is { } last && last.Year == to.Year ? last.AddDays(1) : new DateOnly(to.Year, 1, 1);
if (from != expected || to < from || to.Year != from.Year)
{
throw new ValidationFailedException(["From:" + LedgerErrors.PrintOrder]);
}
firstPage = register.PrintYear == to.Year ? register.LastPage + 1 : 1;
}
var view = await RegisterAsync(uow, registerId, from, to, cancellationToken).ConfigureAwait(false);
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
var rows = new List<IReadOnlyList<string?>>();
foreach (var row in view.Rows)
{
rows.Add([
row.VatProtocol?.ToString(CultureInfo.InvariantCulture), LedgerReport.Date(row.VatDate), row.DocumentNumber, LedgerReport.Date(row.DocumentDate), row.PartyName,
row.Nature ?? row.Rate.ToString("0.##", CultureInfo.InvariantCulture) + "%", LedgerReport.Money(row.Taxable), LedgerReport.Money(row.Tax),
LedgerReport.Money(row.NonDeductibleTax),
]);
}
foreach (var total in view.Totals)
{
rows.Add(["**Totale", null, null, null, null, total.Nature ?? total.Rate.ToString("0.##", CultureInfo.InvariantCulture) + "%",
LedgerReport.Money(total.Taxable), LedgerReport.Money(total.Tax), LedgerReport.Money(total.NonDeductibleTax)]);
}
rows.Add(["**Totale registro", null, null, null, null, null, LedgerReport.Money(view.Totals.Sum(t => t.Taxable)), LedgerReport.Money(view.Totals.Sum(t => t.Tax)),
LedgerReport.Money(view.Totals.Sum(t => t.NonDeductibleTax))]);
var (file, pages) = await LedgerReport.WriteAsync(
CompanyLine(profile),
register.Code + " - " + register.Description,
(final ? "Stampa definitiva" : "Stampa provvisoria") + " dal " + LedgerReport.Date(from) + " al " + LedgerReport.Date(to),
[new("Prot.", 40), new("Data reg.", 55), new("Documento", 75), new("Data doc.", 55), new("Controparte", 210), new("Aliquota", 50), new("Imponibile", 85, true),
new("Imposta", 75, true), new("Indetraibile", 70, true)],
rows,
to.Year,
firstPage,
cancellationToken).ConfigureAwait(false);
if (final)
{
var before = new VatRegister { Id = register.Id, Code = register.Code, PrintYear = register.PrintYear, LastPage = register.LastPage, LastPrintedDate = register.LastPrintedDate };
register.PrintYear = to.Year;
register.LastPage = firstPage + pages - 1;
register.LastPrintedDate = to;
await uow.Repository<VatRegister, long>().UpdateAsync(register, cancellationToken).ConfigureAwait(false);
await uow.Repository<VatRegisterPrint, long>().InsertAsync(new VatRegisterPrint
{
VatRegisterId = register.Id,
Year = to.Year,
FromDate = from,
ToDate = to,
FirstPage = firstPage,
LastPage = register.LastPage,
PrintedAt = _clock.GetUtcNow().UtcDateTime,
PrintedBy = actor.UserName,
}, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, register.Id, before, register, actor.UserName, cancellationToken).ConfigureAwait(false);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return new LedgerFile(
string.Create(CultureInfo.InvariantCulture, $"{register.Code}_{from:yyyyMMdd}_{to:yyyyMMdd}{(final ? "_definitivo" : string.Empty)}.pdf"),
Infrastructure.Files.PdfWriter.MediaType,
file);
}
/// <summary>The settlements of a year.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="year">The year.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The settlements, by period.</returns>
public async Task<IReadOnlyList<VatSettlement>> SettlementsAsync(Actor actor, string companyCode, int year, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return (await uow.Repository<VatSettlement, long>().ListAsync(Query.For<VatSettlement>().Where(s => s.Year == year).OrderBy(s => s.Number), cancellationToken)
.ConfigureAwait(false)).Items;
}
/// <summary>A settlement with its lines.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The settlement.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The settlement, or none.</returns>
public async Task<VatSettlementView?> SettlementAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return await ViewAsync(uow, id, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Computes (again) the settlement of a period from the registers: the VAT due and deductible, the credit and the
/// debit carried from the previous settlement, the advance for the last period, interest and minimum.
/// </summary>
/// <param name="actor">Who computes: needs <c>vat.settlement.read</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="year">The year.</param>
/// <param name="number">The month or quarter.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The settlement, as a draft.</returns>
public async Task<VatSettlementView> ComputeAsync(Actor actor, string companyCode, int year, int number, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementRead, cancellationToken).ConfigureAwait(false);
var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
var rules = pack.Require<IVatSettlementRules>();
long id;
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
var periodicity = profile?.VatPeriodicity ?? VatPeriodicity.Monthly;
var period = TaxPeriod.Of(year, number, periodicity);
var settlements = uow.Repository<VatSettlement, long>();
var existing = await settlements.FindAsync(
Query.For<VatSettlement>().Where(s => s.Year == year && s.Number == number && s.Periodicity == periodicity), cancellationToken).ConfigureAwait(false);
if (existing is { Status: VatSettlementStatus.Confirmed })
{
throw new ValidationFailedException(["Number:" + LedgerErrors.SettlementConfirmed]);
}
var later = await settlements.CountAsync(
Query.For<VatSettlement>().Where(s => s.Status == VatSettlementStatus.Confirmed && s.StartDate > period.End), cancellationToken).ConfigureAwait(false);
if (later > 0)
{
throw new ValidationFailedException(["Number:" + LedgerErrors.SettlementLater]);
}
var previousList = (await settlements.ListAsync(
Query.For<VatSettlement>().Where(s => s.Status == VatSettlementStatus.Confirmed && s.EndDate < period.Start).OrderByDescending(s => s.EndDate).Take(1),
cancellationToken).ConfigureAwait(false)).Items;
var previous = previousList.Count > 0 ? previousList[0] : null;
var last = number == (periodicity == VatPeriodicity.Monthly ? 12 : 4);
var advance = 0m;
if (last)
{
advance = await uow.QuerySingleAsync<decimal?>(
SqlFragment.Of($"SELECT SUM(amount) FROM tax_payments WHERE source = {nameof(TaxPaymentSource.VatAdvance)} AND reference_year = {year}"),
cancellationToken).ConfigureAwait(false) ?? 0m;
}
var totals = await TotalsAsync(uow, period.Start, period.End, cancellationToken).ConfigureAwait(false);
var terms = new VatSettlementTerms(
ProRataPercent: profile?.ProRataPercent is > 0m and var p ? p : 100m,
PreviousCredit: previous?.CreditCarried ?? 0m,
PreviousDebit: previous?.DebitCarried ?? 0m,
AdvancePaid: advance,
InterestPercent: pack.Calendar.VatInterestRate(periodicity),
MinimumPayment: rules.MinimumPayment);
var result = VatSettlementCalculator.Compute(totals, terms);
var settlement = existing ?? new VatSettlement { Year = year, Number = number, Periodicity = periodicity };
settlement.StartDate = period.Start;
settlement.EndDate = period.End;
settlement.SettlementDate = period.End;
settlement.Status = VatSettlementStatus.Draft;
settlement.SalesTax = result.SalesTax;
settlement.PurchaseTax = result.PurchaseTax;
settlement.NonDeductibleTax = result.NonDeductibleTax;
settlement.DeferredTax = result.DeferredTax;
settlement.ProRataPercent = terms.ProRataPercent;
settlement.PreviousCredit = terms.PreviousCredit;
settlement.PreviousDebit = terms.PreviousDebit;
settlement.AdvancePaid = terms.AdvancePaid;
settlement.InterestPercent = terms.InterestPercent;
settlement.Interest = result.Interest;
settlement.AmountDue = result.AmountDue;
settlement.CreditCarried = result.CreditCarried;
settlement.DebitCarried = result.DebitCarried;
settlement.PaymentCode = rules.PaymentCode(period);
settlement.DueDate = pack.Calendar.VatPaymentDue(period);
if (existing is null)
{
settlement.Id = await settlements.InsertAsync(settlement, cancellationToken).ConfigureAwait(false);
}
else
{
await settlements.UpdateAsync(settlement, cancellationToken).ConfigureAwait(false);
}
var settlementId = settlement.Id;
await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM vat_settlement_lines WHERE settlement_id = {settlementId}"), cancellationToken).ConfigureAwait(false);
foreach (var total in totals)
{
await uow.Repository<VatSettlementLine, long>().InsertAsync(new VatSettlementLine
{
SettlementId = settlementId,
VatRegisterId = total.RegisterId,
RegisterKind = total.Kind,
Documents = total.Documents,
Taxable = total.Taxable,
Tax = total.Tax,
NonDeductibleTax = total.NonDeductibleTax,
DeferredTax = total.DeferredTax,
}, cancellationToken).ConfigureAwait(false);
}
id = settlementId;
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
return await SettlementAsync(actor, company, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
}
/// <summary>
/// Confirms a settlement: the periods become settled, the entry <c>LIQ</c> closes the VAT accounts into the VAT
/// settlement account (with the interest and the pro rata) and the amount due becomes an F24 line.
/// </summary>
/// <param name="actor">Who confirms: needs <c>vat.settlement.confirm</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The settlement.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The settlement as confirmed.</returns>
public async Task<VatSettlementView> ConfirmAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementConfirm, cancellationToken).ConfigureAwait(false);
var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
var rules = pack.Require<IVatSettlementRules>();
var form = pack.GetFeature<ITaxPaymentFormExporter>();
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var settlements = uow.Repository<VatSettlement, long>();
var settlement = await settlements.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
if (settlement.Status == VatSettlementStatus.Confirmed)
{
throw new ValidationFailedException(["Id:" + LedgerErrors.SettlementConfirmed]);
}
var start = settlement.StartDate;
var earlier = await settlements.CountAsync(
Query.For<VatSettlement>().Where(s => s.Status == VatSettlementStatus.Draft && s.StartDate < start), cancellationToken).ConfigureAwait(false);
if (earlier > 0)
{
throw new ValidationFailedException(["Id:" + LedgerErrors.SettlementPrevious]);
}
var before = Copy(settlement);
var entry = await PostSettlementAsync(uow, settlement, cancellationToken).ConfigureAwait(false);
settlement.GlEntryId = entry?.Id;
if (settlement.AmountDue > 0m)
{
var period = TaxPeriod.Of(settlement.Year, settlement.Number, settlement.Periodicity);
var paymentId = await uow.Repository<TaxPayment, long>().InsertAsync(new TaxPayment
{
DueDate = settlement.DueDate ?? settlement.EndDate,
PaymentCode = settlement.PaymentCode ?? rules.PaymentCode(period),
ReferenceYear = settlement.Year,
ReferencePeriod = rules.PaymentPeriod(period),
Description = Describe(settlement, form),
Amount = settlement.AmountDue,
Source = TaxPaymentSource.VatSettlement,
SourceId = settlement.Id,
IsDemo = settlement.IsDemo,
}, cancellationToken).ConfigureAwait(false);
settlement.TaxPaymentId = paymentId;
}
settlement.Status = VatSettlementStatus.Confirmed;
settlement.ConfirmedAt = _clock.GetUtcNow().UtcDateTime;
settlement.ConfirmedBy = actor.UserName;
await settlements.UpdateAsync(settlement, cancellationToken).ConfigureAwait(false);
var end = settlement.EndDate;
var open = nameof(FiscalPeriodStatus.Open);
var settled = nameof(FiscalPeriodStatus.Settled);
await uow.ExecuteAsync(
SqlFragment.Of($"UPDATE fiscal_periods SET status = {settled} WHERE start_date >= {start} AND end_date <= {end} AND status = {open}"),
cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, settlement.Id, before, settlement, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
await _fiscal.InvalidateAsync(company, cancellationToken).ConfigureAwait(false);
return await SettlementAsync(actor, company, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
}
/// <summary>
/// Takes back the last confirmed settlement while its F24 line is not paid: the entry goes (or is reversed when
/// final), the periods open again, the settlement becomes a draft.
/// </summary>
/// <param name="actor">Who does it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The settlement.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The settlement as a draft.</returns>
public async Task<VatSettlementView> ReopenAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementConfirm, cancellationToken).ConfigureAwait(false);
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var settlements = uow.Repository<VatSettlement, long>();
var settlement = await settlements.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
var end = settlement.EndDate;
if (await settlements.CountAsync(Query.For<VatSettlement>().Where(s => s.Status == VatSettlementStatus.Confirmed && s.StartDate > end), cancellationToken)
.ConfigureAwait(false) > 0)
{
throw new ValidationFailedException(["Id:" + LedgerErrors.SettlementLater]);
}
if (settlement.TaxPaymentId is { } paymentId && await uow.Repository<TaxPayment, long>().GetAsync(paymentId, cancellationToken).ConfigureAwait(false) is { } payment)
{
if (payment.PaidOn is not null)
{
throw new ValidationFailedException(["Id:" + LedgerErrors.PaymentPaid]);
}
await uow.Repository<TaxPayment, long>().DeleteAsync(paymentId, cancellationToken).ConfigureAwait(false);
}
if (settlement.GlEntryId is { } entryId && await uow.Repository<GlEntry, long>().GetAsync(entryId, cancellationToken).ConfigureAwait(false) is { } entry)
{
if (entry.Status == GlEntryStatus.Final)
{
await JournalEntryService.ReverseAsync(uow, entry, DateOnly.FromDateTime(_clock.GetLocalNow().DateTime), actor.UserName, cancellationToken).ConfigureAwait(false);
}
else
{
await LedgerStore.DeleteAsync(uow, entryId, cancellationToken).ConfigureAwait(false);
}
}
var before = Copy(settlement);
settlement.Status = VatSettlementStatus.Draft;
settlement.GlEntryId = null;
settlement.TaxPaymentId = null;
settlement.ConfirmedAt = null;
settlement.ConfirmedBy = null;
await settlements.UpdateAsync(settlement, cancellationToken).ConfigureAwait(false);
var start = settlement.StartDate;
var open = nameof(FiscalPeriodStatus.Open);
var settled = nameof(FiscalPeriodStatus.Settled);
await uow.ExecuteAsync(
SqlFragment.Of($"UPDATE fiscal_periods SET status = {open} WHERE start_date >= {start} AND end_date <= {end} AND status = {settled}"),
cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, settlement.Id, before, settlement, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
await _fiscal.InvalidateAsync(company, cancellationToken).ConfigureAwait(false);
return await SettlementAsync(actor, company, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
}
/// <summary>The base of the December advance for each method, as the ledger knows it.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="year">The year of the advance.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The historical base (last period of the previous year, before its advance) and the actual one (VAT due from the start of the last period to 20 December).</returns>
public async Task<(decimal Historical, decimal Actual)> AdvanceBasisAsync(Actor actor, string companyCode, int year, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
var periodicity = profile?.VatPeriodicity ?? VatPeriodicity.Monthly;
var lastNumber = periodicity == VatPeriodicity.Monthly ? 12 : 4;
var previousYear = year - 1;
var previous = await uow.Repository<VatSettlement, long>().FindAsync(
Query.For<VatSettlement>().Where(s => s.Year == previousYear && s.Number == lastNumber && s.Status == VatSettlementStatus.Confirmed), cancellationToken).ConfigureAwait(false);
var historical = previous is null ? 0m : previous.AmountDue - previous.Interest + previous.AdvancePaid;
var period = TaxPeriod.Of(year, lastNumber, periodicity);
var totals = await TotalsAsync(uow, period.Start, new DateOnly(year, 12, 20), cancellationToken).ConfigureAwait(false);
var actual = VatSettlementCalculator.Compute(totals, new VatSettlementTerms(profile?.ProRataPercent is > 0m and var p ? p : 100m)).Balance;
return (Math.Max(0m, historical), Math.Max(0m, actual));
}
/// <summary>Records the December advance as an F24 line due on 27 December.</summary>
/// <param name="actor">Who records it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="year">The year.</param>
/// <param name="method">The method.</param>
/// <param name="basis">The base of the method.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The F24 line, or <see langword="null"/> when nothing is due.</returns>
public async Task<TaxPayment?> AdvanceAsync(Actor actor, string companyCode, int year, VatAdvanceMethod method, decimal basis, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementConfirm, cancellationToken).ConfigureAwait(false);
var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
var rules = pack.Require<IVatSettlementRules>();
var form = pack.Require<ITaxPaymentFormExporter>();
var amount = VatAdvanceCalculator.Compute(method, basis, rules.AdvancePercent, rules.AdvanceMinimum);
if (amount == 0m)
{
return null;
}
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
var payments = uow.Repository<TaxPayment, long>();
var existing = await payments.FindAsync(
Query.For<TaxPayment>().Where(t => t.Source == TaxPaymentSource.VatAdvance && t.ReferenceYear == year), cancellationToken).ConfigureAwait(false);
if (existing is { PaidOn: not null })
{
throw new ValidationFailedException(["Year:" + LedgerErrors.PaymentPaid]);
}
var payment = existing ?? new TaxPayment { Source = TaxPaymentSource.VatAdvance, ReferenceYear = year };
payment.DueDate = rules.AdvanceDue(year);
payment.PaymentCode = form.VatAdvanceCode(profile?.VatPeriodicity ?? VatPeriodicity.Monthly);
payment.Description = "Acconto IVA " + year.ToString(CultureInfo.InvariantCulture) + " (metodo " + method switch
{
VatAdvanceMethod.Historical => "storico",
VatAdvanceMethod.Forecast => "previsionale",
_ => "analitico",
} + ")";
payment.Amount = amount;
if (existing is null)
{
payment.Id = await payments.InsertAsync(payment, cancellationToken).ConfigureAwait(false);
}
else
{
await payments.UpdateAsync(payment, cancellationToken).ConfigureAwait(false);
}
await _audit.RecordAsync(uow, existing is null ? AuditAction.Insert : AuditAction.Update, payment.Id, existing, payment, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return payment;
}
/// <summary>The communication of the settlements of a quarter (LIPE) from its confirmed settlements.</summary>
/// <param name="actor">Who asks.</param>
/// <param name="companyCode">The company.</param>
/// <param name="year">The year.</param>
/// <param name="quarter">The quarter.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The file.</returns>
public async Task<LedgerFile> PeriodicReturnAsync(Actor actor, string companyCode, int year, int quarter, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementRead, cancellationToken).ConfigureAwait(false);
var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
var writer = pack.Require<IPeriodicVatReturnWriter>();
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
var first = new DateOnly(year, ((quarter - 1) * 3) + 1, 1);
var last = first.AddMonths(3).AddDays(-1);
var settlements = (await uow.Repository<VatSettlement, long>().ListAsync(
Query.For<VatSettlement>().Where(s => s.Status == VatSettlementStatus.Confirmed && s.StartDate >= first && s.EndDate <= last).OrderBy(s => s.StartDate),
cancellationToken).ConfigureAwait(false)).Items;
if (settlements.Count == 0)
{
throw new ValidationFailedException(["Quarter:" + LedgerErrors.SettlementPrevious]);
}
var modules = new List<PeriodicVatReturnModule>();
foreach (var s in settlements)
{
var settlementId = s.Id;
var lines = (await uow.Repository<VatSettlementLine, long>().ListAsync(Query.For<VatSettlementLine>().Where(l => l.SettlementId == settlementId), cancellationToken)
.ConfigureAwait(false)).Items;
var balance = s.AmountDue > 0m ? s.AmountDue : s.DebitCarried > 0m ? 0m : -s.CreditCarried;
modules.Add(new PeriodicVatReturnModule(
TaxPeriod.Of(s.Year, s.Number, s.Periodicity),
lines.Where(l => l.RegisterKind != VatRegisterKind.Purchases).Sum(l => l.Taxable),
lines.Where(l => l.RegisterKind == VatRegisterKind.Purchases).Sum(l => l.Taxable),
s.SalesTax,
s.PurchaseTax,
s.PreviousDebit,
s.PreviousCredit,
s.Interest,
s.AdvancePaid,
balance));
}
var data = new PeriodicVatReturn(
year, quarter, profile?.TaxCode ?? profile?.VatNumber ?? string.Empty, profile?.VatNumber ?? string.Empty, null, profile?.IntermediaryTaxCode,
DateOnly.FromDateTime(_clock.GetLocalNow().DateTime), modules);
return new LedgerFile(writer.FileName(data), "application/xml", writer.Write(data));
}
/// <summary>The VAT of each register in a period, from the posted entries.</summary>
internal static async Task<IReadOnlyList<VatRegisterTotals>> TotalsAsync(IUnitOfWork uow, DateOnly from, DateOnly to, CancellationToken cancellationToken)
{
var draft = nameof(GlEntryStatus.Draft);
var immediate = nameof(TaxExigibility.Immediate);
var rows = await uow.QueryAsync<TotalsRow>(SqlFragment.Of($"""
SELECT v.vat_register_id AS register_id, r.kind AS kind, COUNT(DISTINCT v.entry_id) AS documents,
SUM(v.taxable) AS taxable, SUM(v.tax) AS tax, SUM(v.non_deductible_tax) AS non_deductible_tax,
SUM(CASE WHEN v.exigibility <> {immediate} THEN v.tax ELSE 0 END) AS deferred_tax
FROM gl_entry_vat v JOIN vat_registers r ON r.id = v.vat_register_id
WHERE v.status <> {draft} AND v.vat_date >= {from} AND v.vat_date <= {to}
GROUP BY v.vat_register_id, r.kind
"""), cancellationToken).ConfigureAwait(false);
return [.. rows.Select(r => new VatRegisterTotals(r.RegisterId, r.Kind, (int)r.Documents, r.Taxable ?? 0m, r.Tax ?? 0m, r.NonDeductibleTax ?? 0m, r.DeferredTax ?? 0m))];
}
/// <summary>The lines and totals of a register in a period.</summary>
internal static async Task<VatRegisterView> RegisterAsync(IUnitOfWork uow, long registerId, DateOnly from, DateOnly to, CancellationToken cancellationToken)
{
var register = await uow.Repository<VatRegister, long>().GetAsync(registerId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.VatRegisterRequired);
var draft = nameof(GlEntryStatus.Draft);
var rows = await uow.QueryAsync<VatRegisterRow>(SqlFragment.Of($"""
SELECT v.entry_id AS entry_id, e.entry_number AS entry_number, e.vat_protocol AS vat_protocol, v.vat_date AS vat_date,
e.document_number AS document_number, e.document_date AS document_date, p.name AS party_name, v.rate AS rate, v.nature AS nature,
v.exigibility AS exigibility, v.taxable AS taxable, v.tax AS tax, v.non_deductible_tax AS non_deductible_tax, v.status AS status
FROM gl_entry_vat v JOIN gl_entries e ON e.id = v.entry_id LEFT JOIN parties p ON p.id = e.party_id
WHERE v.vat_register_id = {registerId} AND v.status <> {draft} AND v.vat_date >= {from} AND v.vat_date <= {to}
ORDER BY v.vat_date, e.vat_protocol, e.id, v.line_number
"""), cancellationToken).ConfigureAwait(false);
var totals = rows.GroupBy(r => (r.Rate, r.Nature))
.Select(g => new VatRateTotal(g.Key.Rate, g.Key.Nature, g.Sum(r => r.Taxable), g.Sum(r => r.Tax), g.Sum(r => r.NonDeductibleTax)))
.OrderByDescending(t => t.Rate).ThenBy(t => t.Nature, StringComparer.Ordinal)
.ToList();
return new VatRegisterView(register, rows, totals);
}
/// <summary>The name and VAT number of the company for the heading of the prints.</summary>
internal static string CompanyLine(CompanyProfile? profile) =>
profile is null ? string.Empty : profile.LegalName + (profile.VatNumber is { Length: > 0 } vat ? " - P.IVA " + vat : string.Empty);
private static async Task<VatSettlementView?> ViewAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken)
{
if (await uow.Repository<VatSettlement, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } settlement)
{
return null;
}
var lines = (await uow.Repository<VatSettlementLine, long>().ListAsync(Query.For<VatSettlementLine>().Where(l => l.SettlementId == id), cancellationToken)
.ConfigureAwait(false)).Items;
var registers = (await uow.Repository<VatRegister, long>().ListAsync(Query.For<VatRegister>(), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(r => r.Id);
return new VatSettlementView(settlement, [.. lines.OrderBy(l => l.RegisterKind).ThenBy(l => registers.TryGetValue(l.VatRegisterId, out var r) ? r.Code : string.Empty, StringComparer.Ordinal)], registers);
}
// The entry LIQ: VAT on sales debit, VAT on purchases credit (what is deducted and the share lost to the pro rata),
// the pro rata to its cost, the interest debit, the balance to the VAT settlement account.
private static async Task<GlEntry?> PostSettlementAsync(IUnitOfWork uow, VatSettlement settlement, CancellationToken cancellationToken)
{
if (await LedgerStore.TemplateAsync(uow, "LIQ", cancellationToken).ConfigureAwait(false) is not { } found)
{
return null;
}
var (template, templateLines) = found;
long? Role(PostingRole role, string? description = null) =>
templateLines.FirstOrDefault(l => l.Role == role && l.AccountId is not null && (description is null || l.Description == description))?.AccountId;
var salesVat = Role(PostingRole.SalesVat);
var purchaseVat = Role(PostingRole.PurchaseVat);
var settlementAccount = Role(PostingRole.VatSettlement);
var interestAccount = templateLines.FirstOrDefault(l => l.Role == PostingRole.Account && l.AccountId is not null)?.AccountId;
var proRataAccount = Role(PostingRole.Cost);
if (salesVat is null || purchaseVat is null || settlementAccount is null)
{
throw new ValidationFailedException(["Ledger:" + LedgerErrors.RoleAccountMissing]);
}
var proRata = await ProRataShareAsync(uow, settlement, cancellationToken).ConfigureAwait(false);
var lines = new List<EntryLineDraft>();
void Add(long? account, decimal amount, AccountSide side, string description)
{
if (amount == 0m || account is null)
{
return;
}
if (amount < 0m)
{
amount = -amount;
side = side == AccountSide.Debit ? AccountSide.Credit : AccountSide.Debit;
}
lines.Add(new EntryLineDraft(account, null, description, side == AccountSide.Debit ? amount : 0m, side == AccountSide.Debit ? 0m : amount));
}
Add(salesVat, settlement.SalesTax, AccountSide.Debit, "IVA a debito del periodo");
Add(purchaseVat, settlement.PurchaseTax + proRata, AccountSide.Credit, "IVA a credito del periodo");
Add(proRata == 0m ? null : proRataAccount ?? settlementAccount, proRata, AccountSide.Debit, "IVA indetraibile da pro rata");
var interest = interestAccount is null ? 0m : settlement.Interest;
Add(interestAccount, interest, AccountSide.Debit, "Interessi trimestrali");
Add(settlementAccount, settlement.SalesTax - settlement.PurchaseTax + interest, AccountSide.Credit, "Saldo della liquidazione");
if (lines.Count == 0)
{
return null;
}
var entry = new GlEntry
{
EntryDate = settlement.EndDate,
JournalTemplateId = template.Id,
TemplateCode = template.Code,
Description = LedgerStore.Trim(template.Description + " " + PeriodText(settlement), 200)!,
Status = GlEntryStatus.Posted,
Source = GlEntrySource.VatSettlement,
IsDemo = settlement.IsDemo,
};
return await LedgerStore.InsertAsync(uow, entry, lines, [], cancellationToken).ConfigureAwait(false);
}
// The VAT of the purchase registers lost to the pro rata (beyond what the codes already make non-deductible).
private static async Task<decimal> ProRataShareAsync(IUnitOfWork uow, VatSettlement settlement, CancellationToken cancellationToken)
{
if (settlement.ProRataPercent >= 100m)
{
return 0m;
}
var totals = await TotalsAsync(uow, settlement.StartDate, settlement.EndDate, cancellationToken).ConfigureAwait(false);
var byCode = totals.Where(t => t.Kind == VatRegisterKind.Purchases).Sum(t => t.NonDeductibleTax);
return settlement.NonDeductibleTax - byCode;
}
private static string PeriodText(VatSettlement settlement) =>
settlement.Periodicity == VatPeriodicity.Monthly
? settlement.StartDate.ToString("MMMM yyyy", CultureInfo.GetCultureInfo("it-IT"))
: settlement.Number.ToString(CultureInfo.InvariantCulture) + "° trimestre " + settlement.Year.ToString(CultureInfo.InvariantCulture);
private static string Describe(VatSettlement settlement, ITaxPaymentFormExporter? form)
{
var code = settlement.PaymentCode;
// The description of the code already names the month or the quarter: only the year is added.
var text = form?.Codes.FirstOrDefault(c => c.Code == code)?.Description;
return LedgerStore.Trim(text is null ? "Versamento IVA " + PeriodText(settlement) : text + " " + settlement.Year.ToString(CultureInfo.InvariantCulture), 200)!;
}
private static VatSettlement Copy(VatSettlement s) => new()
{
Id = s.Id,
Year = s.Year,
Number = s.Number,
Status = s.Status,
AmountDue = s.AmountDue,
CreditCarried = s.CreditCarried,
GlEntryId = s.GlEntryId,
TaxPaymentId = s.TaxPaymentId,
};
private sealed record TotalsRow(long RegisterId, VatRegisterKind Kind, long Documents, decimal? Taxable, decimal? Tax, decimal? NonDeductibleTax, decimal? DeferredTax);
}
@@ -0,0 +1,123 @@
using Khaemhat.Application.Instance;
using Khaemhat.Application.Ledger;
using Khaemhat.Application.Security;
using Khaemhat.Core.Accounting;
using Khaemhat.Core.Tables;
using Khaemhat.Core.Tax;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Seeding;
/// <summary>
/// The demo accounting (SPEC §14, issue #68): the demo documents posted, the professional's invoice paid so that its
/// withholding is due, the monthly rental of the office printer as a recurring entry, the VAT settlements of the periods already
/// ended confirmed, and the F24 already due paid. It runs after the demo sales and purchases and only once: when
/// the company has typed or settled anything in the ledger it adds nothing.
/// </summary>
/// <param name="ledger">Posts the documents.</param>
/// <param name="journal">Writes the model entry of the rental.</param>
/// <param name="vat">Computes and confirms the settlements.</param>
/// <param name="taxes">Withholdings, stamp duty and F24.</param>
/// <param name="recurring">The recurring rental.</param>
/// <param name="factory">Reads the ledger.</param>
/// <param name="clock">Today.</param>
public sealed class DemoLedgerSeeder(
LedgerService ledger, JournalEntryService journal, VatService vat, TaxService taxes, RecurringEntryService recurring, IUnitOfWorkFactory factory, TimeProvider clock)
: ICompanySeeder
{
/// <summary>The account of the rental, from the Italian chart of accounts (Noleggi).</summary>
public const string RentAccount = "22.01.003";
/// <summary>The bank account that pays it.</summary>
public const string BankAccount = "07.01.001";
/// <summary>The monthly rental of the demo office printer.</summary>
public const decimal Rent = 45m;
private static readonly Actor Seed = Actor.System;
/// <inheritdoc />
public int Order => 40;
/// <inheritdoc />
public async Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(context);
if (!context.Demo)
{
return;
}
var today = DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(clock.GetUtcNow(), TimeZoneInfo.Local).DateTime);
var start = new DateOnly(today.Year, 1, 1);
long? rentId;
long? bankId;
VatPeriodicity periodicity;
await using (var uow = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false))
{
var accounts = uow.Repository<GlAccount, long>();
if (await accounts.CountAsync(Query.For<GlAccount>(), cancellationToken).ConfigureAwait(false) == 0)
{
return; // No chart of accounts: the company has no accounting module.
}
if (await uow.Repository<GlEntry, long>().CountAsync(
Query.For<GlEntry>().Where(e => e.Source == GlEntrySource.Manual || e.Source == GlEntrySource.VatSettlement), cancellationToken).ConfigureAwait(false) > 0
|| await uow.Repository<VatSettlement, long>().CountAsync(Query.For<VatSettlement>(), cancellationToken).ConfigureAwait(false) > 0)
{
return;
}
rentId = (await accounts.FindAsync(Query.For<GlAccount>().Where(a => a.Code == RentAccount), cancellationToken).ConfigureAwait(false))?.Id;
bankId = (await accounts.FindAsync(Query.For<GlAccount>().Where(a => a.Code == BankAccount), cancellationToken).ConfigureAwait(false))?.Id;
periodicity = (await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false))?.VatPeriodicity
?? VatPeriodicity.Monthly;
}
// The documents confirmed before the ledger existed.
await ledger.PostPendingAsync(Seed, companyCode, start, today, cancellationToken: cancellationToken).ConfigureAwait(false);
// The professionals' invoices paid ten days after their date: their withholdings become due.
foreach (var row in await taxes.WithholdingsAsync(Seed, companyCode, today.Year, WithholdingDirection.Operated, cancellationToken).ConfigureAwait(false))
{
if (row.Withholding.Status == WithholdingStatus.Waiting)
{
var paid = row.Withholding.DocumentDate.AddDays(10);
await taxes.InvoicePaidAsync(Seed, companyCode, row.Withholding.Id, paid > today ? today : paid, cancellationToken).ConfigureAwait(false);
}
}
// The printer rental of January, and the same entry every month after as a recurring entry.
if (rentId is { } rent && bankId is { } bank)
{
var first = new DateOnly(today.Year, 1, 5);
var model = await journal.SaveAsync(Seed, companyCode, new EntryInput(null, first, "Noleggio stampante multifunzione",
[new EntryLineDraft(rent, null, null, Rent, 0m), new EntryLineDraft(bank, null, null, 0m, Rent)]) { Post = true }, cancellationToken).ConfigureAwait(false);
await recurring.SaveAsync(Seed, companyCode, new RecurringEntryInput(null, "Noleggio mensile stampante", model.Entry.Id, RecurrenceFrequency.Monthly,
RecurringEntryService.Next(first, RecurrenceFrequency.Monthly), null, false), cancellationToken).ConfigureAwait(false);
await recurring.GenerateAsync(Seed, companyCode, today, cancellationToken).ConfigureAwait(false);
}
// The settlements of the periods already ended, in order, and the stamp duty of the quarters ended.
var periods = periodicity == VatPeriodicity.Quarterly ? (today.Month - 1) / 3 : today.Month - 1;
for (var number = 1; number <= periods; number++)
{
var computed = await vat.ComputeAsync(Seed, companyCode, today.Year, number, cancellationToken).ConfigureAwait(false);
await vat.ConfirmAsync(Seed, companyCode, computed.Settlement.Id, cancellationToken).ConfigureAwait(false);
}
for (var quarter = 1; quarter <= (today.Month - 1) / 3; quarter++)
{
await taxes.StampDutyPaymentAsync(Seed, companyCode, today.Year, quarter, cancellationToken).ConfigureAwait(false);
}
// The F24 already due are paid on their day; those still to come stay to pay.
var dues = (await taxes.PaymentsAsync(Seed, companyCode, today.Year, cancellationToken).ConfigureAwait(false))
.Where(p => p.PaidOn is null && p.DueDate < today).Select(p => p.DueDate).Distinct().Order().ToList();
foreach (var due in dues)
{
await taxes.PayAsync(Seed, companyCode, due, due, cancellationToken: cancellationToken).ConfigureAwait(false);
}
}
}
@@ -0,0 +1,124 @@
using Khaemhat.Application.Modules;
using Khaemhat.Core.Accounting;
using Khaemhat.Core.Tables;
using Khaemhat.Data.Querying;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Application.Seeding;
/// <summary>
/// The ledger of the base data (SPEC §14, issue #62): the model chart of accounts of the country pack in three levels,
/// the VAT registers, the journal templates with their lines and, on the document types that have none, the template
/// and the register they post with. Like every base seeder it adds only what is missing.
/// </summary>
public sealed class LedgerSeeder : ISeeder
{
/// <inheritdoc />
public string ModuleCode => ModuleCodes.Accounting;
/// <inheritdoc />
public SeedKind Kind => SeedKind.Base;
/// <inheritdoc />
public int Order => 50;
/// <inheritdoc />
public async Task RunAsync(SeedContext context, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
if (context.Pack.GetFeature<ILedgerTemplate>() is not { } ledger)
{
return;
}
var accounts = await SeedAccountsAsync(context, ledger, cancellationToken).ConfigureAwait(false);
await context.EnsureAsync(
"vat_registers",
ledger.VatRegisters.Select(r => new VatRegister { Code = r.Code, Description = r.Description, Kind = r.Kind, ReverseCharge = r.ReverseCharge }),
cancellationToken).ConfigureAwait(false);
await SeedTemplatesAsync(context, ledger, accounts, cancellationToken).ConfigureAwait(false);
var types = context.UnitOfWork.Repository<DocumentType, long>();
foreach (var posting in ledger.DocumentPostings)
{
var type = await types.FindAsync(Query.For<DocumentType>().Where(t => t.Code == posting.DocumentTypeCode), cancellationToken).ConfigureAwait(false);
if (type is not null && type.JournalTemplateCode is null && type.VatRegisterCode is null)
{
type.JournalTemplateCode = posting.JournalTemplateCode;
type.VatRegisterCode = posting.VatRegisterCode;
await types.UpdateAsync(type, cancellationToken).ConfigureAwait(false);
context.Count("document_types");
}
}
}
private static async Task<Dictionary<string, GlAccount>> SeedAccountsAsync(SeedContext context, ILedgerTemplate ledger, CancellationToken cancellationToken)
{
var repository = context.UnitOfWork.Repository<GlAccount, long>();
var existing = (await repository.ListAsync(Query.For<GlAccount>(), cancellationToken).ConfigureAwait(false)).Items
.ToDictionary(a => a.Code, StringComparer.Ordinal);
var parents = ledger.Accounts.Where(a => a.ParentCode is not null).Select(a => a.ParentCode!).ToHashSet(StringComparer.Ordinal);
foreach (var template in ledger.Accounts.OrderBy(a => a.Level).ThenBy(a => a.Code, StringComparer.Ordinal))
{
if (existing.ContainsKey(template.Code))
{
continue;
}
var account = new GlAccount
{
Code = template.Code,
Description = template.Description,
Level = template.Level,
ParentId = template.ParentCode is { } parent && existing.TryGetValue(parent, out var found) ? found.Id : null,
Nature = template.Nature,
Type = template.Type,
StatementLine = template.StatementLine,
SubLedger = template.SubLedger,
VatRelevant = template.VatRelevant,
ClosesAutomatically = template.Nature != AccountNature.Memorandum,
Postable = !parents.Contains(template.Code),
};
account.Id = await repository.InsertAsync(account, cancellationToken).ConfigureAwait(false);
existing[account.Code] = account;
context.Count("gl_accounts");
}
return existing;
}
private static async Task SeedTemplatesAsync(
SeedContext context, ILedgerTemplate ledger, Dictionary<string, GlAccount> accounts, CancellationToken cancellationToken)
{
var repository = context.UnitOfWork.Repository<JournalTemplate, long>();
var lines = context.UnitOfWork.Repository<JournalTemplateLine, long>();
var existing = (await repository.ListAsync(Query.For<JournalTemplate>(), cancellationToken).ConfigureAwait(false)).Items
.Select(t => t.Code).ToHashSet(StringComparer.OrdinalIgnoreCase);
foreach (var template in ledger.JournalTemplates.Where(t => !existing.Contains(t.Code)))
{
var id = await repository.InsertAsync(new JournalTemplate
{
Code = template.Code,
Description = template.Description,
Area = template.Area,
VatRegisterCode = template.VatRegisterCode,
OpensItems = template.OpensItems,
Reverses = template.Reverses,
}, cancellationToken).ConfigureAwait(false);
context.Count("gl_journal_templates");
for (var i = 0; i < template.Lines.Count; i++)
{
var line = template.Lines[i];
await lines.InsertAsync(new JournalTemplateLine
{
JournalTemplateId = id,
SortOrder = (i + 1) * 10,
Role = line.Role,
Side = line.Side,
AccountId = line.AccountCode is { } code && accounts.TryGetValue(code, out var account) ? account.Id : null,
Description = line.Description,
}, cancellationToken).ConfigureAwait(false);
}
}
}
}