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;
/// A list with its lines and the names of the parties.
/// The list.
/// The lines, by section.
/// The names of the parties, by id.
public sealed record IntrastatListView(IntrastatList List, IReadOnlyList Lines, IReadOnlyDictionary PartyNames);
///
/// 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.
///
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;
/// Creates the service.
/// The units of work.
/// The permissions.
/// The fiscal packs.
/// The history.
/// The clock.
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;
}
/// The lists of a year.
/// Who reads.
/// The company.
/// The year.
/// Cancellation.
/// The lists, the latest first.
public async Task> 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().ListAsync(
Query.For().Where(l => l.Year == year).OrderByDescending(l => l.Period).OrderBy(l => l.Flow), cancellationToken).ConfigureAwait(false)).Items;
}
/// A list with its lines.
/// Who reads.
/// The company.
/// The list.
/// Cancellation.
/// The list, or none.
public async Task 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);
}
/// How often the lists of a flow are due in a period, from the four quarters before it.
/// Who reads.
/// The company.
/// Sales or purchases.
/// The year.
/// The quarter, 1-4.
/// Cancellation.
/// The periodicity of goods and services.
public async Task 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();
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return await DueAsync(uow, exporter, flow, year, quarter, cancellationToken).ConfigureAwait(false);
}
///
/// Generates the list of a period from the documents, keeping the lines typed by hand; a sent list is read only.
///
/// Who generates.
/// The company.
/// Sales or purchases.
/// The year.
/// Monthly or quarterly.
/// The month or the quarter.
/// Cancellation.
/// The list.
public async Task 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();
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);
}
/// Adds or changes a line by hand: a new generation keeps it.
/// Who writes.
/// The company.
/// The line; id 0 for a new one.
/// Cancellation.
/// The list.
public async Task 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();
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();
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);
}
/// Removes a line.
/// Who removes.
/// The company.
/// The line.
/// Cancellation.
/// A task.
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();
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);
}
/// Writes the file of a list for the customs; refused while lines are incomplete.
/// Who exports.
/// The company.
/// The list.
/// Cancellation.
/// The file.
public async Task 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();
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().FindAsync(Query.For(), 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().UpdateAsync(list, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return new LedgerFile(list.FileName, "text/plain", content);
}
/// Records that a list was sent, with the protocol of the customs: from then on it is read only.
/// Who records.
/// The company.
/// The list.
/// The protocol.
/// Cancellation.
/// A task.
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().UpdateAsync(list, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
internal static async Task 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 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();
var list = await lists.FindAsync(
Query.For().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().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();
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;
}
/// The lines a period would have, from the documents (not written).
internal static async Task> CandidatesAsync(
IUnitOfWork uow, IIntrastatExporter exporter, IntrastatFlow flow, DateOnly from, DateOnly to, CancellationToken cancellationToken)
{
var documents = flow == IntrastatFlow.Sales
? await DocumentsAsync(uow, SaleKinds, from, to, cancellationToken).ConfigureAwait(false)
: await DocumentsAsync(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().ListAsync(Query.For().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- ().ListAsync(Query.For
- ().Where(i => itemIds.Contains(i.Id)), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(i => i.Id);
var profile = await uow.Repository().FindAsync(Query.For(), cancellationToken).ConfigureAwait(false);
var result = new List();
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
Lines)>> DocumentsAsync(
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 wanted = [.. kinds];
var headers = (await uow.Repository().ListAsync(
Query.For().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().ListAsync(Query.For().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().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().ListAsync(Query.For().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().UpdateAsync(list, cancellationToken).ConfigureAwait(false);
}
private static async Task EditableAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken)
{
var list = await uow.Repository().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 ViewAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken)
{
if (await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } list)
{
return null;
}
var lines = (await uow.Repository().ListAsync(
Query.For().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];
}
}