using Khaemhat.Application.Purchases;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.EInvoicing;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Application.EInvoicing;
/// The filter of the invoices received.
/// Only this state.
/// Supplier, VAT number, number or file name.
public sealed record InboxFilter(InboxFileStatus? Status = null, string? Search = null);
/// A received file stored, or why not.
/// The file.
/// The row of the inbox.
/// Its state.
/// Why it was not stored (error code).
public sealed record InboxStored(string FileName, long? Id, InboxFileStatus? Status, string? Error);
/// A received invoice registered as a supplier document, or why not.
/// The row of the inbox.
/// The file.
/// The draft supplier document.
/// Why it was not registered (error code).
/// What to check on the draft (codes).
public sealed record InboxRegistered(long Id, string FileName, long? PurchaseDocumentId, string? Error, IReadOnlyList Warnings);
///
/// The invoices received from the SDI (SPEC ยง11.9, issue #79): every file that arrives through a channel, or that the
/// user uploads, is kept as it was received with its metadata file (MT); the user registers it as a draft supplier
/// invoice (with the import of mockup 034), or discards it. A file is kept once, by its hash.
///
/// Permissions: einvoice.inbox.read to see, einvoice.inbox.import to upload, register and discard
/// (registering also needs purchases.invoice.write).
public sealed class SdiInboxService
{
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
private readonly CompanyFiscalContext _packs;
private readonly PurchaseInvoiceImportService _import;
private readonly TimeProvider _clock;
/// Creates the service.
/// The units of work.
/// The permissions.
/// The fiscal pack of each company.
/// The import of supplier invoices.
/// The clock.
public SdiInboxService(IUnitOfWorkFactory factory, PermissionService permissions, CompanyFiscalContext packs, PurchaseInvoiceImportService import, TimeProvider clock)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(packs);
ArgumentNullException.ThrowIfNull(import);
ArgumentNullException.ThrowIfNull(clock);
_factory = factory;
_permissions = permissions;
_packs = packs;
_import = import;
_clock = clock;
}
/// The invoices received, newest first (files not loaded).
/// Who looks: needs einvoice.inbox.read.
/// The company.
/// The filter.
/// Cancellation.
/// The rows.
public async Task> ListAsync(Actor actor, string companyCode, InboxFilter filter, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(filter);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.InboxRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var query = Query.For();
if (filter.Status is { } status)
{
query = query.Where(f => f.Status == status);
}
var rows = (await uow.Repository().ListAsync(query.OrderByDescending(f => f.ReceivedAt), cancellationToken).ConfigureAwait(false)).Items
.Select(Light);
if (!string.IsNullOrWhiteSpace(filter.Search))
{
var text = filter.Search.Trim();
rows = rows.Where(f => Has(f.SupplierName, text) || Has(f.SupplierVat, text) || Has(f.Number, text) || Has(f.FileName, text) || Has(f.ExchangeId, text));
}
return [.. rows];
}
/// The received file, as it arrived.
/// Who downloads: needs einvoice.inbox.read.
/// The company.
/// The row.
/// The metadata file (MT) instead of the invoice.
/// Cancellation.
/// Name and content.
public async Task<(string FileName, byte[] Content)> FileAsync(Actor actor, string companyCode, long id, bool metadata = false, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.InboxRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var row = await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound);
return metadata
? (row.MetadataFileName ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound), row.Metadata ?? [])
: (row.FileName, row.Content);
}
/// Stores files the user uploads (downloaded from the portal of the AdE or received elsewhere).
/// Who uploads: needs einvoice.inbox.import.
/// The company.
/// The files.
/// Cancellation.
/// What happened to each.
public async Task> UploadAsync(
Actor actor, string companyCode, IReadOnlyList<(string FileName, byte[] Content)> files, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(files);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.InboxImport, cancellationToken).ConfigureAwait(false);
var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
var reader = pack.GetFeature();
var receipts = pack.GetFeature();
var result = new List();
foreach (var (name, content) in files)
{
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
InboxStored stored;
if (receipts is not null && receipts.IsReceipt(name, content) && TryRead(receipts, name, content) is { Kind: EInvoiceReceiptKind.Metadata } meta)
{
var row = await AttachMetadataCoreAsync(uow, meta, cancellationToken).ConfigureAwait(false);
stored = new InboxStored(name, row?.Id, row?.Status, row is null ? EInvoiceErrors.ReceiptUnmatched : null);
}
else
{
stored = await StoreCoreAsync(uow, reader, name, content, _clock.GetUtcNow().UtcDateTime, EInvoiceStore.ManualChannel, null, false, cancellationToken)
.ConfigureAwait(false);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
result.Add(stored);
}
return result;
}
///
/// Registers received invoices as draft supplier documents, through the import of supplier invoices: the supplier is
/// found or added, the lines take their items and tax codes, the file is attached.
///
/// Who registers: needs einvoice.inbox.import and purchases.invoice.write.
/// The company.
/// The rows.
/// Cancellation.
/// What happened to each.
public async Task> RegisterAsync(Actor actor, string companyCode, IReadOnlyList ids, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
ArgumentNullException.ThrowIfNull(ids);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.InboxImport, cancellationToken).ConfigureAwait(false);
var result = new List();
foreach (var id in ids.Distinct())
{
EInvoiceInboxFile row;
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
row = await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound);
}
if (row.Status != InboxFileStatus.New)
{
result.Add(new InboxRegistered(id, row.FileName, row.PurchaseDocumentId, EInvoiceErrors.InboxState, []));
continue;
}
var reading = await _import.ReadAsync(actor, company, [(row.FileName, row.Content)], cancellationToken).ConfigureAwait(false);
if (reading.Rejected.Count > 0 || reading.Invoices.Count == 0)
{
result.Add(new InboxRegistered(id, row.FileName, null, (reading.Rejected.Count > 0 ? reading.Rejected[0].Error : PurchaseInvoiceImportService.EmptyArchive), []));
continue;
}
var blocked = reading.Invoices.FirstOrDefault(c => !c.CanImport);
if (blocked is not null)
{
result.Add(new InboxRegistered(id, row.FileName, null, (blocked.Problems.Count > 0 ? blocked.Problems[0] : PurchaseInvoiceImportService.UnsupportedType), blocked.Problems));
continue;
}
var imported = await _import.ImportAsync(actor, company, reading.Invoices, cancellationToken).ConfigureAwait(false);
var failed = imported.FirstOrDefault(i => i.Error is not null);
var first = imported.FirstOrDefault(i => i.Record is not null);
var documentId = first?.Record?.Header.Id;
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var current = await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound);
if (documentId is not null)
{
current.Status = InboxFileStatus.Registered;
current.PurchaseDocumentId = documentId;
current.PartyId = first!.Record!.Header.PartyId ?? current.PartyId;
}
current.Error = failed?.Error;
await uow.Repository().UpdateAsync(current, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
result.Add(new InboxRegistered(id, row.FileName, documentId, failed?.Error, [.. imported.SelectMany(i => i.Warnings).Distinct(StringComparer.Ordinal)]));
}
return result;
}
/// Discards a received invoice (a copy, a file not for the company), or takes it back.
/// Who does it: needs einvoice.inbox.import.
/// The company.
/// The row.
/// Discard, or take back.
/// Cancellation.
/// A task.
public async Task DiscardAsync(Actor actor, string companyCode, long id, bool discard, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.InboxImport, 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 row = await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound);
var allowed = discard ? row.Status is InboxFileStatus.New or InboxFileStatus.Unreadable : row.Status == InboxFileStatus.Discarded;
if (!allowed)
{
throw new ValidationFailedException([":" + EInvoiceErrors.InboxState]);
}
row.Status = discard ? InboxFileStatus.Discarded : row.SupplierVat is null && row.Number is null ? InboxFileStatus.Unreadable : InboxFileStatus.New;
await repository.UpdateAsync(row, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
///
/// Stores a received file in the transaction of the caller: read by the pack for the list (supplier, number, date,
/// total); a file the pack cannot read is kept as unreadable, a file already kept is not stored again.
///
internal static async Task StoreCoreAsync(
IUnitOfWork uow, IIncomingInvoiceReader? reader, string fileName, byte[] content, DateTime receivedAt, string? channel, string? exchangeId, bool demo,
CancellationToken cancellationToken)
{
var repository = uow.Repository();
var hash = EInvoiceStore.Hash(content);
if (await repository.FindAsync(Query.For().Where(f => f.Hash == hash), cancellationToken).ConfigureAwait(false) is { } known)
{
return new InboxStored(fileName, known.Id, known.Status, EInvoiceErrors.InboxDuplicate);
}
var row = new EInvoiceInboxFile
{
FileName = EInvoiceStore.Trim(Path.GetFileName(fileName), 200) ?? "fattura.xml",
Hash = hash,
Content = content,
ReceivedAt = receivedAt,
ChannelCode = channel,
ExchangeId = EInvoiceStore.Trim(exchangeId, 40),
Status = InboxFileStatus.Unreadable,
IsDemo = demo,
};
try
{
if (reader is not null && reader.CanRead(fileName, content))
{
var file = reader.Read(fileName, content);
var invoice = file.Invoices[0];
row.SupplierVat = EInvoiceStore.Trim((file.Supplier.CountryCode ?? string.Empty) + (file.Supplier.VatNumber ?? file.Supplier.TaxCode), 30);
row.SupplierName = EInvoiceStore.Trim(file.Supplier.DisplayName, 200);
row.DocumentType = invoice.DocumentType;
row.Number = EInvoiceStore.Trim(invoice.Number, 40);
row.DocumentDate = invoice.Date;
row.TotalAmount = file.Invoices.Count == 1 ? invoice.Total ?? invoice.TaxSummary.Sum(t => t.Taxable + t.Tax) : null;
row.PartyId = await PurchaseInvoiceImportService.FindSupplierAsync(uow, file.Supplier, cancellationToken).ConfigureAwait(false);
row.Status = InboxFileStatus.New;
}
else
{
row.Error = IncomingInvoiceErrors.NotReadable;
}
}
catch (IncomingInvoiceException ex)
{
row.Error = ex.Code;
}
row.Id = await repository.InsertAsync(row, cancellationToken).ConfigureAwait(false);
return new InboxStored(fileName, row.Id, row.Status, null);
}
/// Keeps the metadata file (MT) with the invoice it describes, by the name of the invoice file.
internal static async Task AttachMetadataCoreAsync(IUnitOfWork uow, EInvoiceReceipt metadata, CancellationToken cancellationToken)
{
var repository = uow.Repository();
var stem = metadata.InvoiceFileName is { } name ? EInvoiceStore.Stem(name) : EInvoiceStore.InvoiceStem(metadata.FileName);
if (stem is null)
{
return null;
}
EInvoiceInboxFile? row = null;
foreach (var candidate in new[] { stem + ".xml", stem + ".xml.p7m" })
{
row = await repository.FindAsync(Query.For().Where(f => f.FileName == candidate).OrderByDescending(f => f.Id), cancellationToken).ConfigureAwait(false);
if (row is not null)
{
break;
}
}
if (row is null)
{
return null;
}
row.MetadataFileName = EInvoiceStore.Trim(metadata.FileName, 200);
row.Metadata = metadata.Content;
row.ExchangeId ??= EInvoiceStore.Trim(metadata.ExchangeId, 40);
await repository.UpdateAsync(row, cancellationToken).ConfigureAwait(false);
return row;
}
private static EInvoiceReceipt? TryRead(IEInvoiceReceiptReader reader, string name, byte[] content)
{
try
{
return reader.Read(name, content);
}
catch (IncomingInvoiceException)
{
return null;
}
}
private static EInvoiceInboxFile Light(EInvoiceInboxFile row)
{
var copy = EInvoiceStore.Clone(row);
copy.Content = [];
copy.Metadata = null;
return copy;
}
private static bool Has(string? value, string text) => value?.Contains(text, StringComparison.CurrentCultureIgnoreCase) == true;
}