using System.Globalization;
using Khaemhat.Application.Documents;
using Khaemhat.Application.Files;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Documents;
using Khaemhat.Core.EInvoicing;
using Khaemhat.Core.Logging;
using Khaemhat.Core.Parties;
using Khaemhat.Core.Security;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
using Khaemhat.Fiscal.Abstractions;
using Microsoft.Extensions.Logging;
namespace Khaemhat.Application.EInvoicing;
///
/// The electronic invoices of the company (SPEC ยง11.9, mockup 058, ADR 0039, issues #74-#75): the dashboard, the file
/// of each issued document written and checked by the fiscal pack, sending through the channel the router chooses
/// (with its fallback), the notifications of the SDI that move the e-invoice and its document, the correction of a
/// rejected invoice and the courtesy copy.
///
///
/// Permissions: einvoice.document.read to see, einvoice.document.send to generate, send and import
/// notifications. The state of the document follows the e-invoice in the same transaction (generated, sent, delivered,
/// rejected, not delivered); a rejected invoice can be changed and generated again with a new progressive.
///
public sealed partial class EInvoiceService
{
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
private readonly CompanyFiscalContext _packs;
private readonly DocumentEngine _engine;
private readonly ISecretProtector _secrets;
private readonly DocumentPdfGenerator _pdf;
private readonly TimeProvider _clock;
private readonly ILogger _logger;
/// Creates the service.
/// The units of work.
/// The permissions.
/// The fiscal pack of each company.
/// The document engine.
/// Opens the secrets of the channels.
/// The print of the documents (courtesy copy).
/// The clock.
/// The log (section SDI).
public EInvoiceService(
IUnitOfWorkFactory factory, PermissionService permissions, CompanyFiscalContext packs, DocumentEngine engine, ISecretProtector secrets,
DocumentPdfGenerator pdf, TimeProvider clock, ILogger logger)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(packs);
ArgumentNullException.ThrowIfNull(engine);
ArgumentNullException.ThrowIfNull(secrets);
ArgumentNullException.ThrowIfNull(pdf);
ArgumentNullException.ThrowIfNull(clock);
ArgumentNullException.ThrowIfNull(logger);
_factory = factory;
_permissions = permissions;
_packs = packs;
_engine = engine;
_secrets = secrets;
_pdf = pdf;
_clock = clock;
_logger = logger;
}
/// The dashboard: the e-invoices of the view, the documents to generate, the counters.
/// Who looks: needs einvoice.document.read.
/// The company.
/// The filter.
/// Cancellation.
/// The dashboard.
public async Task DashboardAsync(Actor actor, string companyCode, EInvoiceFilter filter, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(filter);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.Read, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var query = Query.For().Where(e => !e.Superseded);
if (filter.From is { } from)
{
query = query.Where(e => e.DocumentDate >= from);
}
if (filter.To is { } to)
{
query = query.Where(e => e.DocumentDate <= to);
}
var all = (await uow.Repository().ListAsync(query.OrderByDescending(e => e.DocumentDate), cancellationToken).ConfigureAwait(false)).Items
.Select(EInvoiceStore.Light)
.ToList();
var pending = await PendingAsync(uow, filter, cancellationToken).ConfigureAwait(false);
var received = await uow.Repository().CountAsync(Query.For().Where(f => f.Status == InboxFileStatus.New), cancellationToken)
.ConfigureAwait(false);
var counters = new EInvoiceCounters(
pending.Count(p => p.Status == DocumentStatus.Issued),
all.Count(e => e.Status == EInvoiceStatus.Generated),
all.Count(e => e.Status == EInvoiceStatus.Sent),
all.Count(e => EInvoiceStates.IsIssued(e.Status) && e.Status is not (EInvoiceStatus.Refused or EInvoiceStatus.NotDelivered or EInvoiceStatus.Undeliverable)),
all.Count(e => EInvoiceStates.NeedsAction(e.Status)),
all.Count(e => e.Status is EInvoiceStatus.NotDelivered or EInvoiceStatus.Undeliverable),
received);
IEnumerable rows = filter.View switch
{
EInvoiceView.SelfInvoices => all.Where(e => e.Kind == DocumentKind.SelfInvoice),
EInvoiceView.ToDo => all.Where(e => e.Status == EInvoiceStatus.Generated || EInvoiceStates.NeedsAction(e.Status)),
_ => all.Where(e => e.Kind != DocumentKind.SelfInvoice),
};
if (filter.Status is { } status)
{
rows = rows.Where(e => e.Status == status);
}
var list = rows.ToList();
var parties = await PartiesAsync(uow, list.Select(e => e.PartyId).OfType(), cancellationToken).ConfigureAwait(false);
var result = list.Select(e => new EInvoiceRow(e, parties.GetValueOrDefault(e.PartyId ?? 0)?.Code, parties.GetValueOrDefault(e.PartyId ?? 0)?.Name));
if (!string.IsNullOrWhiteSpace(filter.Search))
{
var text = filter.Search.Trim();
result = result.Where(r => Contains(r.Invoice.DocumentNumber, text) || Contains(r.Invoice.FileName, text) || Contains(r.Invoice.ExchangeId, text)
|| Contains(r.PartyName, text) || Contains(r.PartyCode, text));
}
var visiblePending = filter.View switch
{
EInvoiceView.SelfInvoices => pending.Where(p => p.Kind == DocumentKind.SelfInvoice),
EInvoiceView.ToDo => pending,
_ => pending.Where(p => p.Kind != DocumentKind.SelfInvoice),
};
return new EInvoiceDashboard([.. result], [.. visiblePending], counters);
}
/// The e-invoices of a document with their notifications, newest first (the page of the document).
/// Who looks.
/// The company.
/// The family.
/// The document.
/// Cancellation.
/// The files and their notifications.
public async Task Notifications)>> HistoryAsync(
Actor actor, string companyCode, DocumentFamily family, long documentId, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.Read, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var invoices = (await uow.Repository()
.ListAsync(Query.For().Where(e => e.Family == family && e.DocumentId == documentId).OrderByDescending(e => e.Id), cancellationToken).ConfigureAwait(false)).Items;
var result = new List<(EInvoice, IReadOnlyList)>();
foreach (var invoice in invoices)
{
var id = invoice.Id;
var notifications = (await uow.Repository()
.ListAsync(Query.For().Where(n => n.EInvoiceId == id).OrderBy(n => n.ReceivedAt), cancellationToken).ConfigureAwait(false)).Items;
result.Add((EInvoiceStore.Light(invoice), [.. notifications.Select(n => { n.Content = []; return n; })]));
}
return result;
}
/// The notifications received in a period, newest first (files not loaded).
/// Who looks: needs einvoice.document.read.
/// The company.
/// From this day.
/// Up to this day.
/// Cancellation.
/// The notifications.
public async Task> NotificationsAsync(Actor actor, string companyCode, DateOnly from, DateOnly to, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.Read, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var start = from.ToDateTime(TimeOnly.MinValue, DateTimeKind.Utc);
var end = to.AddDays(1).ToDateTime(TimeOnly.MinValue, DateTimeKind.Utc);
var rows = (await uow.Repository()
.ListAsync(Query.For().Where(n => n.ReceivedAt >= start && n.ReceivedAt < end).OrderByDescending(n => n.ReceivedAt).Take(2000), cancellationToken)
.ConfigureAwait(false)).Items;
foreach (var row in rows)
{
row.Content = [];
}
return rows;
}
/// Checks the file a document would have, without writing it.
/// Who checks: needs einvoice.document.read.
/// The company.
/// The family.
/// The document.
/// Cancellation.
/// The problems, empty when the file can be sent.
public async Task> CheckAsync(Actor actor, string companyCode, DocumentFamily family, long documentId, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.Read, cancellationToken).ConfigureAwait(false);
var (writer, validator, _) = await FeaturesAsync(company, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var record = await DocumentEngine.LoadAsync(uow, family, documentId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound);
if (!EInvoiceBuilder.IsElectronic(record.Header.Kind))
{
return [Problem(EInvoiceErrors.NotElectronic)];
}
var (file, _, _) = await EInvoiceBuilder.BuildAsync(uow, record, cancellationToken).ConfigureAwait(false);
file = file with { FileName = writer.FileName(file.TransmitterCountry ?? "IT", file.TransmitterId ?? "0", 1), ProgressiveNumber = writer.Progressive(1) };
var problems = validator.Validate(file).ToList();
if (problems.All(p => p.Severity != EInvoiceProblemSeverity.Error))
{
problems.AddRange(validator.ValidateXml(writer.Write(file)));
}
return problems;
}
///
/// Writes the file of an issued document (or of one rejected by the SDI): built from the document, checked against
/// the rules of the pack and its schema; the document goes to XML generato. A file generated and not sent is
/// written again with the same name; a rejected one is kept, superseded, and the new file has a new progressive.
///
/// Who generates: needs einvoice.document.send.
/// The company.
/// The family.
/// The document.
/// Cancellation.
/// The e-invoice, or the errors.
public async Task GenerateAsync(Actor actor, string companyCode, DocumentFamily family, long documentId, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.Send, cancellationToken).ConfigureAwait(false);
var (writer, validator, _) = await FeaturesAsync(company, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var result = await GenerateCoreAsync(uow, writer, validator, family, documentId, actor.UserName, cancellationToken).ConfigureAwait(false);
if (result.Success)
{
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
using (_logger.BeginScope(LogSections.Scope(LogSection.EInvoicing)))
{
LogGenerated(_logger, result.Invoice!.FileName, result.Invoice.DocumentNumber, company);
}
}
return result;
}
/// Generates the files of several documents and sends them (the button Genera e invia).
/// Who sends.
/// The company.
/// The documents.
/// Cancellation.
/// For each document, the generation and the sending.
public async Task> GenerateAndSendAsync(
Actor actor, string companyCode, IReadOnlyList<(DocumentFamily Family, long DocumentId)> documents, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(documents);
var result = new List<(PendingEInvoice?, EInvoiceGeneration, EInvoiceSendOutcome?)>();
foreach (var (family, id) in documents)
{
var generation = await GenerateAsync(actor, companyCode, family, id, cancellationToken).ConfigureAwait(false);
EInvoiceSendOutcome? sending = null;
if (generation.Invoice is { } invoice)
{
sending = (await SendAsync(actor, companyCode, [invoice.Id], cancellationToken).ConfigureAwait(false))[0];
}
result.Add((null, generation, sending));
}
return result;
}
///
/// Sends generated files through the channel the router chooses; when the channel refuses the file the fallback of
/// the rule is tried. A file a channel took goes to Inviato with its document; one no channel took keeps its
/// state and the error.
///
/// Who sends: needs einvoice.document.send.
/// The company.
/// The e-invoices.
/// Cancellation.
/// What happened to each.
public async Task> SendAsync(Actor actor, string companyCode, IReadOnlyList ids, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
ArgumentNullException.ThrowIfNull(ids);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.Send, cancellationToken).ConfigureAwait(false);
var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
var channels = pack.GetFeature();
var result = new List();
foreach (var id in ids.Distinct())
{
result.Add(await SendOneAsync(company, channels, id, actor.UserName, cancellationToken).ConfigureAwait(false));
}
return result;
}
/// Records that a generated file was sent outside Khaemhat (portal of the AdE, another program).
/// Who records it: needs einvoice.document.send.
/// The company.
/// The e-invoice.
/// The identifier of the SDI, when known.
/// Cancellation.
/// The e-invoice.
public async Task MarkSentAsync(Actor actor, string companyCode, long id, string? exchangeId, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.Send, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var invoice = await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound);
if (invoice.Superseded || invoice.Status != EInvoiceStatus.Generated)
{
throw new ValidationFailedException([":" + EInvoiceErrors.AlreadySent]);
}
await MarkSentCoreAsync(uow, invoice, EInvoiceStore.ManualChannel, EInvoiceStore.Trim(exchangeId, 40), null, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return EInvoiceStore.Light(invoice);
}
/// Imports notifications downloaded from the portal of the AdE or from another program.
/// Who imports: needs einvoice.document.send.
/// The company.
/// The files.
/// Cancellation.
/// What happened to each.
public async Task> ImportReceiptsAsync(
Actor actor, string companyCode, IReadOnlyList<(string FileName, byte[] Content)> files, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
ArgumentNullException.ThrowIfNull(files);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.Send, cancellationToken).ConfigureAwait(false);
var reader = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).GetFeature()
?? throw new ValidationFailedException([":" + EInvoiceErrors.NotSupported]);
var result = new List();
foreach (var (name, content) in files)
{
EInvoiceReceipt receipt;
try
{
if (!reader.IsReceipt(name, content))
{
result.Add(new ReceiptOutcome(name, null, null, null, null, EInvoiceErrors.NotAReceipt));
continue;
}
receipt = reader.Read(name, content);
}
catch (IncomingInvoiceException)
{
result.Add(new ReceiptOutcome(name, null, null, null, null, EInvoiceErrors.NotAReceipt));
continue;
}
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var outcome = await ApplyReceiptCoreAsync(uow, receipt, EInvoiceStore.ManualChannel, actor.UserName, false, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
result.Add(outcome);
}
return result;
}
/// The file of an e-invoice, as sent.
/// Who downloads: needs einvoice.document.read.
/// The company.
/// The e-invoice.
/// Cancellation.
/// Name and content.
public async Task<(string FileName, byte[] Content)> FileAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.Read, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var invoice = await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound);
return (invoice.FileName, invoice.Content);
}
/// The file of a notification.
/// Who downloads: needs einvoice.document.read.
/// The company.
/// The notification.
/// Cancellation.
/// Name and content.
public async Task<(string FileName, byte[] Content)> NotificationFileAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.Read, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var notification = await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false)
?? throw new KeyNotFoundException(EInvoiceErrors.NotFound);
return (notification.FileName, notification.Content);
}
/// The courtesy copy: the print of the document with the XML of the e-invoice embedded.
/// Who downloads: needs einvoice.document.read and to read the document.
/// The company.
/// The e-invoice.
/// Cancellation.
/// Name and content of the PDF.
public async Task<(string FileName, byte[] Content)> CourtesyCopyAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
var (name, xml) = await FileAsync(actor, companyCode, id, cancellationToken).ConfigureAwait(false);
EInvoice invoice;
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false))
{
invoice = await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound);
}
using var output = new MemoryStream();
var context = new FileGenerationContext(actor, companyCode, DocumentPrintService.EntityOf(invoice.Family), invoice.DocumentId, CultureInfo.GetCultureInfo("it-IT"), _clock.GetUtcNow().UtcDateTime);
await _pdf.CourtesyCopyAsync(context, name, xml, output, cancellationToken).ConfigureAwait(false);
return (EInvoiceStore.Stem(name) + ".pdf", output.ToArray());
}
/// The core of the generation, in the transaction of the caller (also the demo seed).
internal async Task GenerateCoreAsync(
IUnitOfWork uow, IEInvoiceWriter writer, IEInvoiceValidator validator, DocumentFamily family, long documentId, string userName, CancellationToken cancellationToken)
{
var record = await DocumentEngine.LoadAsync(uow, family, documentId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound);
var header = record.Header;
if (!EInvoiceBuilder.IsElectronic(header.Kind))
{
return new(null, [Problem(EInvoiceErrors.NotElectronic)]);
}
if (header.Status is DocumentStatus.Draft or DocumentStatus.Cancelled)
{
return new(null, [Problem(EInvoiceErrors.NotIssued)]);
}
var repository = uow.Repository();
var active = await repository.FindAsync(Query.For().Where(e => e.Family == family && e.DocumentId == documentId && !e.Superseded), cancellationToken)
.ConfigureAwait(false);
if (header.Status is not (DocumentStatus.Issued or DocumentStatus.SdiGenerated or DocumentStatus.SdiRejected)
|| active is { Status: not (EInvoiceStatus.Generated or EInvoiceStatus.Rejected) })
{
return new(null, [Problem(EInvoiceErrors.AlreadySent)]);
}
var (file, party, _) = await EInvoiceBuilder.BuildAsync(uow, record, cancellationToken).ConfigureAwait(false);
var problems = validator.Validate(file).ToList();
if (problems.Any(p => p.Severity == EInvoiceProblemSeverity.Error))
{
return new(null, problems);
}
var reuse = active is { Status: EInvoiceStatus.Generated };
var progressive = reuse ? active!.Progressive : await NextProgressiveAsync(uow, cancellationToken).ConfigureAwait(false);
var fileName = reuse ? active!.FileName : writer.FileName(file.TransmitterCountry ?? "IT", file.TransmitterId ?? string.Empty, progressive);
file = file with { FileName = fileName, ProgressiveNumber = writer.Progressive(progressive) };
var xml = writer.Write(file);
var schema = validator.ValidateXml(xml);
if (schema.Any(p => p.Severity == EInvoiceProblemSeverity.Error))
{
return new(null, [.. problems, .. schema]);
}
var now = _clock.GetUtcNow().UtcDateTime;
var invoice = reuse ? active! : new EInvoice();
invoice.Family = family;
invoice.DocumentId = documentId;
invoice.Kind = header.Kind;
invoice.DocumentNumber = header.DocumentNumber;
invoice.DocumentDate = header.DocumentDate;
invoice.PartyId = party.Id;
invoice.DocumentType = file.Invoices[0].DocumentType;
invoice.FileName = fileName;
invoice.Progressive = progressive;
invoice.Format = file.TransmissionFormat ?? string.Empty;
invoice.RecipientCode = file.RecipientCode;
invoice.RecipientPec = file.RecipientPec;
invoice.TotalAmount = header.TotalAmount;
invoice.Status = EInvoiceStatus.Generated;
invoice.GeneratedAt = now;
invoice.LastMessage = null;
invoice.Content = xml;
invoice.IsDemo = header.IsDemo;
if (reuse)
{
await repository.UpdateAsync(invoice, cancellationToken).ConfigureAwait(false);
}
else
{
if (active is not null)
{
active.Superseded = true;
await repository.UpdateAsync(active, cancellationToken).ConfigureAwait(false);
}
invoice.Id = await repository.InsertAsync(invoice, cancellationToken).ConfigureAwait(false);
}
await _engine.AdvanceExchangeAsync(uow, family, documentId, s => EInvoiceStates.StepsTo(s, EInvoiceStatus.Generated), userName, cancellationToken).ConfigureAwait(false);
return new(invoice, problems);
}
/// A file taken by a channel: Inviato, with the document.
internal async Task MarkSentCoreAsync(IUnitOfWork uow, EInvoice invoice, string channel, string? exchangeId, string? messageId, string userName, CancellationToken cancellationToken)
{
invoice.Status = EInvoiceStatus.Sent;
invoice.SentAt = _clock.GetUtcNow().UtcDateTime;
invoice.ChannelCode = channel;
invoice.ExchangeId = exchangeId ?? invoice.ExchangeId;
invoice.MessageId = EInvoiceStore.Trim(messageId, 200);
invoice.LastMessage = null;
await uow.Repository().UpdateAsync(invoice, cancellationToken).ConfigureAwait(false);
await _engine.AdvanceExchangeAsync(uow, invoice.Family, invoice.DocumentId, s => EInvoiceStates.StepsTo(s, EInvoiceStatus.Sent), userName, cancellationToken).ConfigureAwait(false);
}
///
/// Applies a notification in the transaction of the caller: kept as received (once: the file name is unique), the
/// e-invoice found by file name or identifier of the SDI gets the new state and its document follows.
///
internal async Task ApplyReceiptCoreAsync(
IUnitOfWork uow, EInvoiceReceipt receipt, string? channel, string userName, bool demo, CancellationToken cancellationToken)
{
var notifications = uow.Repository();
var name = receipt.FileName;
if (await notifications.FindAsync(Query.For().Where(n => n.FileName == name), cancellationToken).ConfigureAwait(false) is { } known)
{
return new ReceiptOutcome(name, receipt.Code, known.InvoiceFileName, known.EInvoiceId, null, EInvoiceErrors.ReceiptDuplicate);
}
var invoice = await FindInvoiceAsync(uow, receipt, cancellationToken).ConfigureAwait(false);
var errors = receipt.Errors.Count == 0 ? null : string.Join('\n', receipt.Errors.Select(e => e.Code + " - " + e.Description + (e.Hint is null ? string.Empty : " (" + e.Hint + ")")));
var receivedAt = (receipt.ReceivedAt ?? _clock.GetUtcNow()).UtcDateTime;
await notifications.InsertAsync(
new EInvoiceNotification
{
EInvoiceId = invoice?.Id,
Code = receipt.Code,
FileName = EInvoiceStore.Trim(name, 100)!,
InvoiceFileName = EInvoiceStore.Trim(receipt.InvoiceFileName ?? invoice?.FileName, 100),
ExchangeId = EInvoiceStore.Trim(receipt.ExchangeId, 40),
ReceivedAt = receivedAt,
Outcome = EInvoiceStore.Trim(receipt.Outcome, 10),
Description = EInvoiceStore.Trim(receipt.Description, 1000),
Errors = errors,
ChannelCode = channel,
Content = receipt.Content,
IsDemo = demo || invoice?.IsDemo == true,
},
cancellationToken).ConfigureAwait(false);
if (invoice is null)
{
return new ReceiptOutcome(name, receipt.Code, receipt.InvoiceFileName, null, null, receipt.Code is "MT" or "SE" ? null : EInvoiceErrors.ReceiptUnmatched);
}
var next = EInvoiceStates.After(receipt.Code, receipt.Outcome);
if (next is { } status)
{
if (invoice.Status == EInvoiceStatus.Generated)
{
invoice.SentAt ??= receivedAt;
invoice.ChannelCode ??= channel;
}
invoice.Status = status;
invoice.ExchangeId ??= EInvoiceStore.Trim(receipt.ExchangeId, 40);
invoice.LastNotificationAt = receivedAt;
invoice.LastMessage = EInvoiceStore.Trim(errors ?? receipt.Description, 1000);
await uow.Repository().UpdateAsync(invoice, cancellationToken).ConfigureAwait(false);
await _engine.AdvanceExchangeAsync(uow, invoice.Family, invoice.DocumentId, s => EInvoiceStates.StepsTo(s, status), userName, cancellationToken).ConfigureAwait(false);
using (_logger.BeginScope(LogSections.Scope(LogSection.EInvoicing)))
{
LogReceipt(_logger, receipt.Code, invoice.FileName, status);
}
}
return new ReceiptOutcome(name, receipt.Code, invoice.FileName, invoice.Id, next, null);
}
private static async Task FindInvoiceAsync(IUnitOfWork uow, EInvoiceReceipt receipt, CancellationToken cancellationToken)
{
var repository = uow.Repository();
var stem = receipt.InvoiceFileName is { } invoiceName ? EInvoiceStore.Stem(invoiceName) : EInvoiceStore.InvoiceStem(receipt.FileName);
if (stem is not null)
{
foreach (var candidate in new[] { stem + ".xml", stem + ".xml.p7m" })
{
if (await repository.FindAsync(Query.For().Where(e => e.FileName == candidate), cancellationToken).ConfigureAwait(false) is { } byName)
{
return byName;
}
}
}
if (receipt.ExchangeId is { Length: > 0 } exchange)
{
return await repository.FindAsync(Query.For().Where(e => e.ExchangeId == exchange).OrderByDescending(e => e.Id), cancellationToken).ConfigureAwait(false);
}
return null;
}
private async Task SendOneAsync(string company, IEInvoiceChannels? channels, long id, string userName, CancellationToken cancellationToken)
{
EInvoice invoice;
List<(string Code, EInvoiceChannelSettings Settings)> route;
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
invoice = await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound);
if (invoice.Superseded || invoice.Status != EInvoiceStatus.Generated)
{
return new EInvoiceSendOutcome(id, invoice.FileName, invoice.DocumentNumber, false, invoice.ChannelCode, EInvoiceErrors.AlreadySent);
}
route = await RouteAsync(uow, channels, invoice, cancellationToken).ConfigureAwait(false);
}
if (route.Count == 0 || channels is null)
{
return new EInvoiceSendOutcome(id, invoice.FileName, invoice.DocumentNumber, false, null, EInvoiceErrors.NoChannel);
}
EInvoiceSendResult? result = null;
string? used = null;
var errors = new List();
foreach (var (code, settings) in route)
{
var transport = channels.Find(code)!.Transport;
used = code;
result = await transport.SendAsync(settings, new EInvoiceOutgoing(invoice.FileName, invoice.Content, invoice.DocumentNumber), cancellationToken).ConfigureAwait(false);
if (result.Accepted)
{
break;
}
errors.Add(code + ": " + result.Error);
using (_logger.BeginScope(LogSections.Scope(LogSection.EInvoicing)))
{
LogSendFailed(_logger, invoice.FileName, code, result.Error);
}
}
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 (result is { Accepted: true })
{
await MarkSentCoreAsync(uow, current, used!, EInvoiceStore.Trim(result.ExchangeId, 40), result.MessageId, userName, cancellationToken).ConfigureAwait(false);
}
else
{
current.SendAttempts++;
current.LastMessage = EInvoiceStore.Trim(string.Join(" | ", errors), 1000);
await uow.Repository().UpdateAsync(current, cancellationToken).ConfigureAwait(false);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
if (result is { Accepted: true })
{
using (_logger.BeginScope(LogSections.Scope(LogSection.EInvoicing)))
{
LogSent(_logger, invoice.FileName, used!, company);
}
}
return new EInvoiceSendOutcome(id, invoice.FileName, invoice.DocumentNumber, result?.Accepted == true, used, result?.Accepted == true ? null : string.Join(" | ", errors));
}
// The channels to try, in order: the one of the router, then its fallback; each with its settings.
private async Task> RouteAsync(IUnitOfWork uow, IEInvoiceChannels? channels, EInvoice invoice, CancellationToken cancellationToken)
{
if (channels is null)
{
return [];
}
var rows = (await uow.Repository().ListAsync(Query.For().Where(c => c.Enabled && !c.Paused), cancellationToken)
.ConfigureAwait(false)).Items.ToDictionary(c => c.Code, StringComparer.OrdinalIgnoreCase);
var usable = channels.All.Select(c => c.Code).Where(rows.ContainsKey).ToList();
var rules = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items;
var party = invoice.PartyId is { } partyId ? await uow.Repository().GetAsync(partyId, cancellationToken).ConfigureAwait(false) : null;
var today = _clock.GetUtcNow().UtcDateTime.Date;
var sentToday = await uow.Repository().CountAsync(Query.For().Where(e => e.SentAt >= today), cancellationToken).ConfigureAwait(false);
var choice = SdiRouter.Choose(new SdiRoutingInput(invoice.DocumentType, party?.Code, invoice.Format == "FPA12", sentToday), rules, usable);
if (choice is null)
{
return [];
}
return [.. new[] { choice.Channel, choice.Fallback }.OfType().Distinct(StringComparer.OrdinalIgnoreCase)
.Select(code => (code, EInvoiceStore.Settings(rows[code], _secrets)))];
}
private async Task<(IEInvoiceWriter Writer, IEInvoiceValidator Validator, IFiscalPack Pack)> FeaturesAsync(string company, CancellationToken cancellationToken)
{
var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
var writer = pack.GetFeature();
var validator = pack.GetFeature();
return writer is null || validator is null ? throw new ValidationFailedException([":" + EInvoiceErrors.NotSupported]) : (writer, validator, pack);
}
private static async Task NextProgressiveAsync(IUnitOfWork uow, CancellationToken cancellationToken)
{
var last = await uow.Repository().FindAsync(Query.For().OrderByDescending(e => e.Progressive), cancellationToken).ConfigureAwait(false);
return (last?.Progressive ?? 0L) + 1L;
}
// Issued (or rejected) electronic documents without a file ready to send.
private static async Task> PendingAsync(IUnitOfWork uow, EInvoiceFilter filter, CancellationToken cancellationToken)
{
var query = Query.For().Where(d => d.Status == DocumentStatus.Issued || d.Status == DocumentStatus.SdiRejected);
if (filter.From is { } from)
{
query = query.Where(d => d.DocumentDate >= from);
}
if (filter.To is { } to)
{
query = query.Where(d => d.DocumentDate <= to);
}
var documents = (await uow.Repository().ListAsync(query.OrderBy(d => d.DocumentDate), cancellationToken).ConfigureAwait(false)).Items
.Where(d => EInvoiceBuilder.IsElectronic(d.Kind))
.ToList();
var parties = await PartiesAsync(uow, documents.Select(d => d.PartyId).OfType(), cancellationToken).ConfigureAwait(false);
return [.. documents.Select(d => new PendingEInvoice(DocumentFamily.SaleDocument, d.Id, d.Kind, d.DocumentNumber, d.DocumentDate,
parties.GetValueOrDefault(d.PartyId ?? 0)?.Name, d.TotalAmount, d.Status))];
}
private static async Task> PartiesAsync(IUnitOfWork uow, IEnumerable ids, CancellationToken cancellationToken)
{
var set = ids.Distinct().ToList();
var result = new Dictionary();
foreach (var chunk in set.Chunk(500))
{
var list = chunk.ToList();
foreach (var party in (await uow.Repository().ListAsync(Query.For().Where(p => list.Contains(p.Id)), cancellationToken).ConfigureAwait(false)).Items)
{
result[party.Id] = party;
}
}
return result;
}
private static bool Contains(string? value, string text) => value?.Contains(text, StringComparison.CurrentCultureIgnoreCase) == true;
private static EInvoiceProblem Problem(string code) => new(code, string.Empty, code, EInvoiceProblemSeverity.Error);
[LoggerMessage(EventId = 9101, Level = LogLevel.Information, Message = "E-invoice {FileName} generated for document {Number} in {Company}.")]
private static partial void LogGenerated(ILogger logger, string fileName, string? number, string company);
[LoggerMessage(EventId = 9102, Level = LogLevel.Information, Message = "E-invoice {FileName} sent through {Channel} in {Company}.")]
private static partial void LogSent(ILogger logger, string fileName, string channel, string company);
[LoggerMessage(EventId = 9103, Level = LogLevel.Warning, Message = "E-invoice {FileName} not taken by channel {Channel}: {Error}")]
private static partial void LogSendFailed(ILogger logger, string fileName, string channel, string? error);
[LoggerMessage(EventId = 9104, Level = LogLevel.Information, Message = "Notification {Code} for {FileName}: now {Status}.")]
private static partial void LogReceipt(ILogger logger, string code, string fileName, EInvoiceStatus status);
}