CI / Build and test (SQLite) (pull_request) Successful in 4m35s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / YAML check (pull_request) Successful in 5s
CI / Docker image (pull_request) Successful in 1m24s
M10 gives the ledger its year end. Fixed assets get categories with the ministerial coefficients, a civil and a fiscal plan, depreciation posted per category and undoable, disposals with gain or loss and the register print (ADR 0041). Intrastat lists are generated from confirmed invoices with the due periodicity and the SCAMBI.CEE file; declarations of intent get their own register and the N3.5 ceiling is checked when an invoice is confirmed (ADR 0042). Accruals, deferrals and exchange differences feed a nine-step guided closing that can repeat or undo its last step until the final prints, reopens the next year and locks the closed one; the CEE statements (ordinary, abbreviated, micro), the reclassified statements, the ratios and the accountant export read the year's balances (ADR 0043). The demo seed now opens the year with assets, stock, bank and capital, so the integration test closes the demo year from the checks to the lock on SQLite and PostgreSQL. Docs: wiki pages with screenshots, ADR 0041-0043, MODULES, STATUS, DATA-MODEL and the 0.10.0 changelog. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
582 lines
32 KiB
C#
582 lines
32 KiB
C#
using Khaemhat.Application.Audit;
|
|
using Khaemhat.Application.Ledger;
|
|
using Khaemhat.Application.Security;
|
|
using Khaemhat.Application.Tables;
|
|
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;
|
|
using Khaemhat.Fiscal.Abstractions;
|
|
|
|
namespace Khaemhat.Application.YearEnd;
|
|
|
|
/// <summary>A list with its lines and the names of the parties.</summary>
|
|
/// <param name="List">The list.</param>
|
|
/// <param name="Lines">The lines, by section.</param>
|
|
/// <param name="PartyNames">The names of the parties, by id.</param>
|
|
public sealed record IntrastatListView(IntrastatList List, IReadOnlyList<IntrastatListLine> Lines, IReadOnlyDictionary<long, string> PartyNames);
|
|
|
|
/// <summary>
|
|
/// The Intrastat lists (SPEC §11.7, issue #83, mockup 049, ADR 0042): the periodicity from the amounts of the four
|
|
/// quarters before, the lists generated from the confirmed invoices and credit notes with the parties of the other member
|
|
/// states (goods grouped by party, nomenclature and nature of the transaction; services one line per invoice), the lines
|
|
/// typed by hand that a new generation keeps, the checks of every line and the file for the customs.
|
|
/// </summary>
|
|
public sealed class IntrastatService
|
|
{
|
|
private static readonly DocumentKind[] SaleKinds =
|
|
[DocumentKind.ImmediateInvoice, DocumentKind.AccompanyingInvoice, DocumentKind.DeferredInvoice, DocumentKind.DownPaymentInvoice, DocumentKind.DebitNote, DocumentKind.CreditNote];
|
|
|
|
private static readonly DocumentKind[] PurchaseKinds = [DocumentKind.PurchaseInvoice, DocumentKind.PurchaseCreditNote];
|
|
|
|
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 packs.</param>
|
|
/// <param name="audit">The history.</param>
|
|
/// <param name="clock">The clock.</param>
|
|
public IntrastatService(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 lists 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 lists, the latest first.</returns>
|
|
public async Task<IReadOnlyList<IntrastatList>> ListsAsync(Actor actor, string companyCode, int year, CancellationToken cancellationToken = default)
|
|
{
|
|
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.IntrastatRead, cancellationToken).ConfigureAwait(false);
|
|
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
|
return (await uow.Repository<IntrastatList, long>().ListAsync(
|
|
Query.For<IntrastatList>().Where(l => l.Year == year).OrderByDescending(l => l.Period).OrderBy(l => l.Flow), cancellationToken).ConfigureAwait(false)).Items;
|
|
}
|
|
|
|
/// <summary>A list with its lines.</summary>
|
|
/// <param name="actor">Who reads.</param>
|
|
/// <param name="companyCode">The company.</param>
|
|
/// <param name="id">The list.</param>
|
|
/// <param name="cancellationToken">Cancellation.</param>
|
|
/// <returns>The list, or none.</returns>
|
|
public async Task<IntrastatListView?> GetAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
|
|
{
|
|
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.IntrastatRead, 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>How often the lists of a flow are due in a period, from the four quarters before it.</summary>
|
|
/// <param name="actor">Who reads.</param>
|
|
/// <param name="companyCode">The company.</param>
|
|
/// <param name="flow">Sales or purchases.</param>
|
|
/// <param name="year">The year.</param>
|
|
/// <param name="quarter">The quarter, 1-4.</param>
|
|
/// <param name="cancellationToken">Cancellation.</param>
|
|
/// <returns>The periodicity of goods and services.</returns>
|
|
public async Task<IntrastatDue> DueAsync(Actor actor, string companyCode, IntrastatFlow flow, int year, int quarter, CancellationToken cancellationToken = default)
|
|
{
|
|
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.IntrastatRead, cancellationToken).ConfigureAwait(false);
|
|
var exporter = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require<IIntrastatExporter>();
|
|
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
|
return await DueAsync(uow, exporter, flow, year, quarter, cancellationToken).ConfigureAwait(false);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Generates the list of a period from the documents, keeping the lines typed by hand; a sent list is read only.
|
|
/// </summary>
|
|
/// <param name="actor">Who generates.</param>
|
|
/// <param name="companyCode">The company.</param>
|
|
/// <param name="flow">Sales or purchases.</param>
|
|
/// <param name="year">The year.</param>
|
|
/// <param name="periodicity">Monthly or quarterly.</param>
|
|
/// <param name="period">The month or the quarter.</param>
|
|
/// <param name="cancellationToken">Cancellation.</param>
|
|
/// <returns>The list.</returns>
|
|
public async Task<IntrastatListView> GenerateAsync(
|
|
Actor actor, string companyCode, IntrastatFlow flow, int year, IntrastatPeriodicity periodicity, int period, CancellationToken cancellationToken = default)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(actor);
|
|
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.IntrastatWrite, cancellationToken).ConfigureAwait(false);
|
|
var exporter = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require<IIntrastatExporter>();
|
|
long id;
|
|
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
|
|
{
|
|
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
|
id = (await GenerateAsync(uow, exporter, flow, year, periodicity, period, false, cancellationToken).ConfigureAwait(false)).Id;
|
|
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
|
}
|
|
|
|
return await GetAsync(actor, company, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(YearEndErrors.NotFound);
|
|
}
|
|
|
|
/// <summary>Adds or changes a line by hand: a new generation keeps it.</summary>
|
|
/// <param name="actor">Who writes.</param>
|
|
/// <param name="companyCode">The company.</param>
|
|
/// <param name="line">The line; id 0 for a new one.</param>
|
|
/// <param name="cancellationToken">Cancellation.</param>
|
|
/// <returns>The list.</returns>
|
|
public async Task<IntrastatListView> SaveLineAsync(Actor actor, string companyCode, IntrastatListLine line, CancellationToken cancellationToken = default)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(actor);
|
|
ArgumentNullException.ThrowIfNull(line);
|
|
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.IntrastatWrite, cancellationToken).ConfigureAwait(false);
|
|
var exporter = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require<IIntrastatExporter>();
|
|
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
|
|
{
|
|
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
|
var list = await EditableAsync(uow, line.ListId, cancellationToken).ConfigureAwait(false);
|
|
line.CountryCode = (line.CountryCode ?? string.Empty).Trim().ToUpperInvariant();
|
|
if (!exporter.MemberStates.Contains(line.CountryCode))
|
|
{
|
|
throw new ValidationFailedException(["CountryCode:" + YearEndErrors.CountryNotMember]);
|
|
}
|
|
|
|
if (line.Amount <= 0m)
|
|
{
|
|
throw new ValidationFailedException(["Amount:" + YearEndErrors.AmountRequired]);
|
|
}
|
|
|
|
line.Manual = true;
|
|
line.IsDemo = list.IsDemo;
|
|
line.VatNumber = Clean(line.VatNumber, 20);
|
|
line.NomenclatureCode = Clean(line.NomenclatureCode, 10);
|
|
line.Check = CheckOf(exporter, line);
|
|
var repository = uow.Repository<IntrastatListLine, long>();
|
|
if (line.Id == 0)
|
|
{
|
|
line.Id = await repository.InsertAsync(line, cancellationToken).ConfigureAwait(false);
|
|
await _audit.RecordAsync(uow, AuditAction.Insert, line.Id, null, line, actor.UserName, cancellationToken).ConfigureAwait(false);
|
|
}
|
|
else
|
|
{
|
|
var before = await repository.GetAsync(line.Id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(YearEndErrors.NotFound);
|
|
line.RowVersion = before.RowVersion;
|
|
await repository.UpdateAsync(line, cancellationToken).ConfigureAwait(false);
|
|
await _audit.RecordAsync(uow, AuditAction.Update, line.Id, before, line, actor.UserName, cancellationToken).ConfigureAwait(false);
|
|
}
|
|
|
|
await TotalsAsync(uow, list, cancellationToken).ConfigureAwait(false);
|
|
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
|
}
|
|
|
|
return await GetAsync(actor, company, line.ListId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(YearEndErrors.NotFound);
|
|
}
|
|
|
|
/// <summary>Removes a line.</summary>
|
|
/// <param name="actor">Who removes.</param>
|
|
/// <param name="companyCode">The company.</param>
|
|
/// <param name="lineId">The line.</param>
|
|
/// <param name="cancellationToken">Cancellation.</param>
|
|
/// <returns>A task.</returns>
|
|
public async Task DeleteLineAsync(Actor actor, string companyCode, long lineId, CancellationToken cancellationToken = default)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(actor);
|
|
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.IntrastatWrite, 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<IntrastatListLine, long>();
|
|
var line = await repository.GetAsync(lineId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(YearEndErrors.NotFound);
|
|
var list = await EditableAsync(uow, line.ListId, cancellationToken).ConfigureAwait(false);
|
|
await repository.DeleteAsync(lineId, cancellationToken).ConfigureAwait(false);
|
|
await _audit.RecordAsync(uow, AuditAction.Delete, lineId, line, (IntrastatListLine?)null, actor.UserName, cancellationToken).ConfigureAwait(false);
|
|
await TotalsAsync(uow, list, cancellationToken).ConfigureAwait(false);
|
|
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
|
}
|
|
|
|
/// <summary>Writes the file of a list for the customs; refused while lines are incomplete.</summary>
|
|
/// <param name="actor">Who exports.</param>
|
|
/// <param name="companyCode">The company.</param>
|
|
/// <param name="id">The list.</param>
|
|
/// <param name="cancellationToken">Cancellation.</param>
|
|
/// <returns>The file.</returns>
|
|
public async Task<LedgerFile> ExportAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(actor);
|
|
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.IntrastatExport, cancellationToken).ConfigureAwait(false);
|
|
var exporter = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require<IIntrastatExporter>();
|
|
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
|
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
|
var view = await ViewAsync(uow, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(YearEndErrors.NotFound);
|
|
if (view.List.Problems > 0)
|
|
{
|
|
throw new ValidationFailedException(["Id:" + YearEndErrors.ListIncomplete]);
|
|
}
|
|
|
|
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
|
|
if (string.IsNullOrWhiteSpace(profile?.VatNumber))
|
|
{
|
|
throw new ValidationFailedException(["Id:" + YearEndErrors.CompanyVatMissing]);
|
|
}
|
|
|
|
var intrastatReturn = new IntrastatReturn(view.List, view.Lines, profile.VatNumber);
|
|
var content = exporter.Write(intrastatReturn);
|
|
var list = view.List;
|
|
if (list.Status == IntrastatStatus.Draft)
|
|
{
|
|
list.Status = IntrastatStatus.Generated;
|
|
}
|
|
|
|
list.GeneratedAt = _clock.GetUtcNow().UtcDateTime;
|
|
list.FileName = exporter.FileName(intrastatReturn);
|
|
await uow.Repository<IntrastatList, long>().UpdateAsync(list, cancellationToken).ConfigureAwait(false);
|
|
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
|
return new LedgerFile(list.FileName, "text/plain", content);
|
|
}
|
|
|
|
/// <summary>Records that a list was sent, with the protocol of the customs: from then on it is read only.</summary>
|
|
/// <param name="actor">Who records.</param>
|
|
/// <param name="companyCode">The company.</param>
|
|
/// <param name="id">The list.</param>
|
|
/// <param name="protocol">The protocol.</param>
|
|
/// <param name="cancellationToken">Cancellation.</param>
|
|
/// <returns>A task.</returns>
|
|
public async Task MarkSentAsync(Actor actor, string companyCode, long id, string? protocol, CancellationToken cancellationToken = default)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(actor);
|
|
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.IntrastatExport, cancellationToken).ConfigureAwait(false);
|
|
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
|
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
|
var list = await EditableAsync(uow, id, cancellationToken).ConfigureAwait(false);
|
|
list.Status = IntrastatStatus.Sent;
|
|
list.Protocol = Clean(protocol, 40);
|
|
await uow.Repository<IntrastatList, long>().UpdateAsync(list, cancellationToken).ConfigureAwait(false);
|
|
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
|
}
|
|
|
|
internal static async Task<IntrastatDue> DueAsync(IUnitOfWork uow, IIntrastatExporter exporter, IntrastatFlow flow, int year, int quarter, CancellationToken cancellationToken)
|
|
{
|
|
var goods = 0m;
|
|
var services = 0m;
|
|
for (var back = 1; back <= 4; back++)
|
|
{
|
|
var q = quarter - back;
|
|
var y = year;
|
|
while (q < 1)
|
|
{
|
|
q += 4;
|
|
y--;
|
|
}
|
|
|
|
var from = new DateOnly(y, ((q - 1) * 3) + 1, 1);
|
|
var lines = await CandidatesAsync(uow, exporter, flow, from, from.AddMonths(3).AddDays(-1), cancellationToken).ConfigureAwait(false);
|
|
goods = Math.Max(goods, lines.Where(l => l.Section is IntrastatSection.Goods && l.Included).Sum(l => l.Amount));
|
|
services = Math.Max(services, lines.Where(l => l.Section is IntrastatSection.Services && l.Included).Sum(l => l.Amount));
|
|
}
|
|
|
|
return exporter.Due(flow, goods, services);
|
|
}
|
|
|
|
internal static async Task<IntrastatList> GenerateAsync(
|
|
IUnitOfWork uow, IIntrastatExporter exporter, IntrastatFlow flow, int year, IntrastatPeriodicity periodicity, int period, bool isDemo, CancellationToken cancellationToken)
|
|
{
|
|
if (periodicity == IntrastatPeriodicity.NotDue || period < 1 || period > (periodicity == IntrastatPeriodicity.Monthly ? 12 : 4))
|
|
{
|
|
throw new ValidationFailedException(["Period:" + YearEndErrors.PeriodInvalid]);
|
|
}
|
|
|
|
var lists = uow.Repository<IntrastatList, long>();
|
|
var list = await lists.FindAsync(
|
|
Query.For<IntrastatList>().Where(l => l.Flow == flow && l.Year == year && l.Periodicity == periodicity && l.Period == period), cancellationToken).ConfigureAwait(false);
|
|
if (list is { Status: IntrastatStatus.Sent })
|
|
{
|
|
throw new ValidationFailedException(["Id:" + YearEndErrors.ListSent]);
|
|
}
|
|
|
|
if (list is null)
|
|
{
|
|
var last = await lists.FindAsync(Query.For<IntrastatList>().Where(l => l.Year == year).OrderByDescending(l => l.Progressive), cancellationToken).ConfigureAwait(false);
|
|
list = new IntrastatList
|
|
{
|
|
Flow = flow,
|
|
Year = year,
|
|
Period = period,
|
|
Periodicity = periodicity,
|
|
Status = IntrastatStatus.Draft,
|
|
Progressive = (last?.Progressive ?? 0) + 1,
|
|
IsDemo = isDemo,
|
|
};
|
|
list.Id = await lists.InsertAsync(list, cancellationToken).ConfigureAwait(false);
|
|
}
|
|
else
|
|
{
|
|
var listId = list.Id;
|
|
await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM intrastat_list_lines WHERE list_id = {listId} AND manual = {false}"), cancellationToken).ConfigureAwait(false);
|
|
list.Status = IntrastatStatus.Draft;
|
|
}
|
|
|
|
var from = periodicity == IntrastatPeriodicity.Monthly ? new DateOnly(year, period, 1) : new DateOnly(year, ((period - 1) * 3) + 1, 1);
|
|
var to = from.AddMonths(periodicity == IntrastatPeriodicity.Monthly ? 1 : 3).AddDays(-1);
|
|
var quarter = ((from.Month - 1) / 3) + 1;
|
|
var due = await DueAsync(uow, exporter, flow, year, quarter, cancellationToken).ConfigureAwait(false);
|
|
var candidates = await CandidatesAsync(uow, exporter, flow, from, to, cancellationToken).ConfigureAwait(false);
|
|
var repository = uow.Repository<IntrastatListLine, long>();
|
|
foreach (var line in candidates)
|
|
{
|
|
// A category not due (purchases below the threshold) stays out of the list.
|
|
var category = line.Section is IntrastatSection.Goods or IntrastatSection.GoodsCorrection ? due.Goods : due.Services;
|
|
if (category == IntrastatPeriodicity.NotDue && flow == IntrastatFlow.Purchases)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
line.ListId = list.Id;
|
|
line.IsDemo = isDemo || line.IsDemo;
|
|
await repository.InsertAsync(line, cancellationToken).ConfigureAwait(false);
|
|
}
|
|
|
|
await TotalsAsync(uow, list, cancellationToken).ConfigureAwait(false);
|
|
return list;
|
|
}
|
|
|
|
/// <summary>The lines a period would have, from the documents (not written).</summary>
|
|
internal static async Task<List<IntrastatListLine>> CandidatesAsync(
|
|
IUnitOfWork uow, IIntrastatExporter exporter, IntrastatFlow flow, DateOnly from, DateOnly to, CancellationToken cancellationToken)
|
|
{
|
|
var documents = flow == IntrastatFlow.Sales
|
|
? await DocumentsAsync<SaleDocument, SaleDocumentLine>(uow, SaleKinds, from, to, cancellationToken).ConfigureAwait(false)
|
|
: await DocumentsAsync<PurchaseDocument, PurchaseDocumentLine>(uow, PurchaseKinds, from, to, cancellationToken).ConfigureAwait(false);
|
|
if (documents.Count == 0)
|
|
{
|
|
return [];
|
|
}
|
|
|
|
var partyIds = documents.Select(d => d.Header.PartyId).Where(p => p is not null).Select(p => p!.Value).Distinct().ToList();
|
|
var parties = (await uow.Repository<Party, long>().ListAsync(Query.For<Party>().Where(p => partyIds.Contains(p.Id)), cancellationToken).ConfigureAwait(false)).Items
|
|
.ToDictionary(p => p.Id);
|
|
var foreign = documents.Where(d => d.Header.PartyId is { } p && parties.TryGetValue(p, out var party) && !string.Equals(party.CountryCode, "IT", StringComparison.OrdinalIgnoreCase))
|
|
.ToList();
|
|
var itemIds = foreign.SelectMany(d => d.Lines).Where(l => l.ItemId is not null).Select(l => l.ItemId!.Value).Distinct().ToList();
|
|
var items = itemIds.Count == 0
|
|
? []
|
|
: (await uow.Repository<Item, long>().ListAsync(Query.For<Item>().Where(i => itemIds.Contains(i.Id)), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(i => i.Id);
|
|
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
|
|
var result = new List<IntrastatListLine>();
|
|
var goods = new Dictionary<(long Party, string? Code), IntrastatListLine>();
|
|
foreach (var (header, lines) in foreign.OrderBy(d => d.Header.DocumentDate).ThenBy(d => d.Header.Id))
|
|
{
|
|
var party = parties[header.PartyId!.Value];
|
|
var country = string.Equals(party.CountryCode, "EL", StringComparison.OrdinalIgnoreCase) ? "GR" : party.CountryCode.ToUpperInvariant();
|
|
var sign = header.Kind is DocumentKind.CreditNote or DocumentKind.PurchaseCreditNote ? -1m : 1m;
|
|
var rate = header.ExchangeRate <= 0m ? 1m : header.ExchangeRate;
|
|
var family = flow == IntrastatFlow.Sales ? DocumentFamily.SaleDocument : DocumentFamily.PurchaseDocument;
|
|
var vat = VatOf(party.VatNumber, country);
|
|
decimal services = 0m, servicesCurrency = 0m;
|
|
string? serviceCode = null;
|
|
string? serviceText = null;
|
|
foreach (var line in lines.Where(l => l.Kind is DocumentLineKind.Item or DocumentLineKind.Free && l.TaxableAmount != 0m))
|
|
{
|
|
var item = line.ItemId is { } i && items.TryGetValue(i, out var it) ? it : null;
|
|
var euro = Math.Round(line.TaxableAmount / rate, 2, MidpointRounding.AwayFromZero) * sign;
|
|
if (item?.Kind == ItemKind.Service)
|
|
{
|
|
services += euro;
|
|
servicesCurrency += line.TaxableAmount * sign;
|
|
serviceCode ??= item.CustomsCode;
|
|
serviceText ??= line.Description;
|
|
continue;
|
|
}
|
|
|
|
var code = item?.CustomsCode?.Trim();
|
|
if (!goods.TryGetValue((party.Id, code), out var target))
|
|
{
|
|
target = new IntrastatListLine
|
|
{
|
|
Section = IntrastatSection.Goods,
|
|
SourceFamily = family,
|
|
SourceDocumentId = header.Id,
|
|
DocumentNumber = header.DocumentNumber,
|
|
DocumentDate = header.DocumentDate,
|
|
PartyId = party.Id,
|
|
CountryCode = country,
|
|
VatNumber = vat,
|
|
NomenclatureCode = code,
|
|
Description = Clean(item?.Description ?? line.Description, 200),
|
|
TransactionNature = "11",
|
|
DeliveryTerms = "DAP",
|
|
TransportMode = "3",
|
|
OriginCountry = flow == IntrastatFlow.Purchases ? country : null,
|
|
Province = Clean(profile?.ProvinceCode, 2),
|
|
IsDemo = header.IsDemo,
|
|
};
|
|
goods[(party.Id, code)] = target;
|
|
result.Add(target);
|
|
}
|
|
|
|
target.Amount += euro;
|
|
target.CurrencyAmount = flow == IntrastatFlow.Purchases && rate != 1m ? (target.CurrencyAmount ?? 0m) + (line.TaxableAmount * sign) : target.CurrencyAmount;
|
|
if (item?.NetWeight is { } weight && weight > 0m)
|
|
{
|
|
target.NetMass = (target.NetMass ?? 0m) + Math.Round(weight * line.Quantity * sign, 3, MidpointRounding.AwayFromZero);
|
|
}
|
|
}
|
|
|
|
if (services != 0m)
|
|
{
|
|
result.Add(new IntrastatListLine
|
|
{
|
|
Section = sign < 0m ? IntrastatSection.ServicesCorrection : IntrastatSection.Services,
|
|
SourceFamily = family,
|
|
SourceDocumentId = header.Id,
|
|
DocumentNumber = header.DocumentNumber,
|
|
DocumentDate = header.DocumentDate,
|
|
PartyId = party.Id,
|
|
CountryCode = country,
|
|
VatNumber = vat,
|
|
Amount = Math.Abs(services),
|
|
CurrencyAmount = flow == IntrastatFlow.Purchases && rate != 1m ? Math.Abs(servicesCurrency) : null,
|
|
NomenclatureCode = Clean(serviceCode, 10),
|
|
Description = Clean(serviceText, 200),
|
|
SupplyMode = "I",
|
|
PaymentMode = "B",
|
|
PaymentCountry = country,
|
|
CorrectedYear = sign < 0m ? header.DocumentDate.Year : null,
|
|
CorrectedPeriod = sign < 0m ? header.DocumentDate.Month : null,
|
|
CorrectionSign = sign < 0m ? "-" : null,
|
|
IsDemo = header.IsDemo,
|
|
});
|
|
}
|
|
}
|
|
|
|
foreach (var line in result.Where(l => l.Section == IntrastatSection.Goods && l.Amount < 0m))
|
|
{
|
|
// Credit notes beyond the sales of the period are corrections of an earlier one.
|
|
line.Section = IntrastatSection.GoodsCorrection;
|
|
line.Amount = -line.Amount;
|
|
line.NetMass = line.NetMass is { } m ? Math.Abs(m) : null;
|
|
line.CorrectionSign = "-";
|
|
line.CorrectedYear = line.DocumentDate?.Year;
|
|
line.CorrectedPeriod = line.DocumentDate?.Month;
|
|
}
|
|
|
|
result.RemoveAll(l => l.Amount == 0m);
|
|
foreach (var line in result)
|
|
{
|
|
line.Amount = Math.Round(line.Amount, 2, MidpointRounding.AwayFromZero);
|
|
line.StatisticalValue = line.Section == IntrastatSection.Goods ? line.Amount : null;
|
|
line.Check = exporter.MemberStates.Contains(line.CountryCode) && line.CountryCode != "IT" ? CheckOf(exporter, line) : IntrastatCheck.OutsideEu;
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
private static async Task<List<(DocumentHeader Header, List<DocumentLine> Lines)>> DocumentsAsync<THeader, TLine>(
|
|
IUnitOfWork uow, DocumentKind[] kinds, DateOnly from, DateOnly to, CancellationToken cancellationToken)
|
|
where THeader : DocumentHeader, new()
|
|
where TLine : DocumentLine, new()
|
|
{
|
|
var draft = DocumentStatus.Draft;
|
|
var cancelled = DocumentStatus.Cancelled;
|
|
List<DocumentKind> wanted = [.. kinds];
|
|
var headers = (await uow.Repository<THeader, long>().ListAsync(
|
|
Query.For<THeader>().Where(h => h.DocumentDate >= from && h.DocumentDate <= to && h.Status != draft && h.Status != cancelled && wanted.Contains(h.Kind)),
|
|
cancellationToken).ConfigureAwait(false)).Items;
|
|
if (headers.Count == 0)
|
|
{
|
|
return [];
|
|
}
|
|
|
|
var ids = headers.Select(h => h.Id).ToList();
|
|
var lines = (await uow.Repository<TLine, long>().ListAsync(Query.For<TLine>().Where(l => ids.Contains(l.DocumentId)).OrderBy(l => l.LineNumber), cancellationToken)
|
|
.ConfigureAwait(false)).Items;
|
|
return [.. headers.Select(h => ((DocumentHeader)h, lines.Where(l => l.DocumentId == h.Id).Cast<DocumentLine>().ToList()))];
|
|
}
|
|
|
|
private static IntrastatCheck CheckOf(IIntrastatExporter exporter, IntrastatListLine line)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(line.VatNumber))
|
|
{
|
|
return IntrastatCheck.MissingVatNumber;
|
|
}
|
|
|
|
if (line.Section is IntrastatSection.Goods or IntrastatSection.GoodsCorrection)
|
|
{
|
|
if (!exporter.ValidNomenclature(line.NomenclatureCode))
|
|
{
|
|
return IntrastatCheck.MissingNomenclature;
|
|
}
|
|
|
|
if (line.Section == IntrastatSection.Goods && line.NetMass is null or <= 0m && line.SupplementaryUnits is null or <= 0m)
|
|
{
|
|
return IntrastatCheck.MissingMass;
|
|
}
|
|
}
|
|
else if (line.NomenclatureCode is not { Length: >= 5 })
|
|
{
|
|
return IntrastatCheck.MissingServiceCode;
|
|
}
|
|
|
|
return IntrastatCheck.Ok;
|
|
}
|
|
|
|
private static async Task TotalsAsync(IUnitOfWork uow, IntrastatList list, CancellationToken cancellationToken)
|
|
{
|
|
var listId = list.Id;
|
|
var lines = (await uow.Repository<IntrastatListLine, long>().ListAsync(Query.For<IntrastatListLine>().Where(l => l.ListId == listId), cancellationToken)
|
|
.ConfigureAwait(false)).Items;
|
|
list.GoodsAmount = lines.Where(l => l.Included && l.Section is IntrastatSection.Goods).Sum(l => l.Amount)
|
|
- lines.Where(l => l.Included && l.Section is IntrastatSection.GoodsCorrection && l.CorrectionSign == "-").Sum(l => l.Amount);
|
|
list.ServicesAmount = lines.Where(l => l.Included && l.Section is IntrastatSection.Services).Sum(l => l.Amount)
|
|
- lines.Where(l => l.Included && l.Section is IntrastatSection.ServicesCorrection && l.CorrectionSign == "-").Sum(l => l.Amount);
|
|
list.Problems = lines.Count(l => l.Included && l.Check != IntrastatCheck.Ok);
|
|
await uow.Repository<IntrastatList, long>().UpdateAsync(list, cancellationToken).ConfigureAwait(false);
|
|
}
|
|
|
|
private static async Task<IntrastatList> EditableAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken)
|
|
{
|
|
var list = await uow.Repository<IntrastatList, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(YearEndErrors.NotFound);
|
|
return list.Status == IntrastatStatus.Sent ? throw new ValidationFailedException(["Id:" + YearEndErrors.ListSent]) : list;
|
|
}
|
|
|
|
private static async Task<IntrastatListView?> ViewAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken)
|
|
{
|
|
if (await uow.Repository<IntrastatList, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } list)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
var lines = (await uow.Repository<IntrastatListLine, long>().ListAsync(
|
|
Query.For<IntrastatListLine>().Where(l => l.ListId == id).OrderBy(l => l.Section).OrderBy(l => l.DocumentDate).OrderBy(l => l.Id), cancellationToken)
|
|
.ConfigureAwait(false)).Items;
|
|
var names = await JournalEntryService.PartyNamesAsync(uow, lines.Select(l => l.PartyId), cancellationToken).ConfigureAwait(false);
|
|
return new IntrastatListView(list, lines, names);
|
|
}
|
|
|
|
private static string? VatOf(string? vatNumber, string country)
|
|
{
|
|
var vat = vatNumber?.Replace(" ", string.Empty, StringComparison.Ordinal).ToUpperInvariant();
|
|
if (string.IsNullOrEmpty(vat))
|
|
{
|
|
return null;
|
|
}
|
|
|
|
var prefix = country == "GR" ? "EL" : country;
|
|
return vat.StartsWith(prefix, StringComparison.Ordinal) ? vat[prefix.Length..] : vat;
|
|
}
|
|
|
|
private static string? Clean(string? text, int length)
|
|
{
|
|
var value = text?.Trim();
|
|
return string.IsNullOrEmpty(value) ? null : value.Length <= length ? value : value[..length];
|
|
}
|
|
}
|