69 lines
3.1 KiB
C#
69 lines
3.1 KiB
C#
using ComplianceNFs.Core.Entities;
|
|
using ComplianceNFs.Core.Application;
|
|
using ComplianceNFs.Core.Application.Services;
|
|
|
|
namespace ComplianceNFs.Service;
|
|
|
|
public class Worker(ILogger<Worker> logger,
|
|
IInvoiceIngestionService ingestionService,
|
|
IMatchingService matchingService,
|
|
IComplianceService complianceService,
|
|
INotificationService notificationService,
|
|
IArchivingService archivingService) : BackgroundService
|
|
{
|
|
private readonly ILogger<Worker> _logger = logger;
|
|
private readonly IInvoiceIngestionService _ingestionService = ingestionService;
|
|
private readonly IMatchingService _matchingService = matchingService;
|
|
private readonly IComplianceService _complianceService = complianceService;
|
|
private readonly INotificationService _notificationService = notificationService;
|
|
private readonly IArchivingService _archivingService = archivingService;
|
|
|
|
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
|
{
|
|
_logger.LogInformation("Worker starting at: {time}", DateTimeOffset.Now);
|
|
try
|
|
{
|
|
// Start mail ingestion (starts listening for new mail)
|
|
await _ingestionService.IngestAsync();
|
|
// Subscribe to new invoice events and orchestrate workflow
|
|
if (_ingestionService is InvoiceIngestionService ingestionImpl)
|
|
{
|
|
ingestionImpl.InvoiceProcessed += async invoice =>
|
|
{
|
|
try
|
|
{
|
|
// 1. Match invoice
|
|
await _matchingService.MatchAsync(invoice);
|
|
// 2. Compliance validation
|
|
await _complianceService.ValidateAsync(invoice);
|
|
// 3. Notify if needed
|
|
if (invoice.Status == InvoiceStatus.TaxMismatch || invoice.Status == InvoiceStatus.VolumeMismatch || invoice.Status == InvoiceStatus.PriceMismatch)
|
|
{
|
|
await _notificationService.NotifyAsync(invoice, invoice.DiscrepancyNotes ?? "Discrepancy detected");
|
|
_logger.LogWarning("Invoice {NumeroNF} has a discrepancy: {Notes}", invoice.NumeroNF, invoice.DiscrepancyNotes);
|
|
}
|
|
// 4. Archive
|
|
// (Assume raw file is available or can be loaded if needed)
|
|
await _archivingService.ArchiveAsync(invoice);
|
|
_logger.LogInformation("Invoice {NumeroNF} processed with status: {Status}", invoice.NumeroNF, invoice.Status);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(ex, "Error processing invoice {NumeroNF}", invoice.NumeroNF);
|
|
}
|
|
};
|
|
}
|
|
// Keep the worker alive
|
|
while (!stoppingToken.IsCancellationRequested)
|
|
{
|
|
await Task.Delay(1000, stoppingToken);
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogCritical(ex, "Worker encountered a fatal error and is stopping.");
|
|
throw;
|
|
}
|
|
}
|
|
}
|