Refactor FinalizeDocumentJob for DI and logging improvements
Refactored FinalizeDocumentJob to use dependency injection for all major services and models, replacing manual initialization. Updated all logging to use injected ILogger with structured messages. Removed obsolete initialization methods. Marked class as [Obsolete] pending migration from CommonServices.Jobs. Improved exception handling and code clarity for better testability and maintainability.
This commit is contained in:
@@ -1,8 +1,5 @@
|
||||
using System.Data;
|
||||
using System.IO;
|
||||
using DigitalData.Modules.Base;
|
||||
using DigitalData.Modules.Database;
|
||||
using DigitalData.Modules.Logging;
|
||||
using EnvelopeGenerator.Domain.Constants;
|
||||
using EnvelopeGenerator.Domain.Entities;
|
||||
using EnvelopeGenerator.ServiceHost.Exceptions;
|
||||
@@ -10,35 +7,19 @@ using EnvelopeGenerator.ServiceHost.Jobs.FinalizeDocument;
|
||||
using GdPicture14;
|
||||
using Microsoft.Data.SqlClient;
|
||||
using Microsoft.Extensions.Options;
|
||||
using EnvelopeGenerator.ServiceHost.Extensions;
|
||||
|
||||
namespace EnvelopeGenerator.ServiceHost.Jobs;
|
||||
|
||||
public class FinalizeDocumentJob(IOptions<WorkerOptions> options, IConfiguration config)
|
||||
[Obsolete("ActionService is a placeholder service added by copilot. Migrate the actual logic from CommonServices.Jobs")]
|
||||
public class FinalizeDocumentJob(IOptions<WorkerOptions> options, IConfiguration config, ILogger<FinalizeDocumentJob> logger, TempFiles tempFiles, ActionService actionService, PDFBurner pdfBurner, PDFMerger pdfMerger, ReportCreator reportCreator, ConfigModel _configModel, EnvelopeModel _envelopeModel, ReportModel _reportModel, MSSQLServer _database, GdViewer? _gdViewer, LicenseManager licenseManager)
|
||||
{
|
||||
private readonly WorkerOptions _options = options.Value;
|
||||
|
||||
private readonly LicenseManager _licenseManager = new();
|
||||
private GdViewer? _gdViewer;
|
||||
|
||||
private LogConfig? _logConfig;
|
||||
private Logger? _logger;
|
||||
private MSSQLServer? _database;
|
||||
private DbConfig? _config;
|
||||
private string _databaseConnectionString = string.Empty;
|
||||
|
||||
private ConfigModel? _configModel;
|
||||
private EnvelopeModel? _envelopeModel;
|
||||
private ReportModel? _reportModel;
|
||||
|
||||
private ActionService? _actionService;
|
||||
|
||||
private PDFBurner? _pdfBurner;
|
||||
private PDFMerger? _pdfMerger;
|
||||
private ReportCreator? _reportCreator;
|
||||
|
||||
|
||||
private const int CompleteWaitTime = 1;
|
||||
private string _parentFolderUid = string.Empty;
|
||||
private TempFiles? _tempFiles;
|
||||
|
||||
private sealed class EnvelopeData
|
||||
{
|
||||
@@ -52,48 +33,17 @@ public class FinalizeDocumentJob(IOptions<WorkerOptions> options, IConfiguration
|
||||
public Task ExecuteAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
var gdPictureKey = _options.GdPictureLicenseKey;
|
||||
_logConfig = new LogConfig { Debug = _options.Debug };
|
||||
_logger = _logConfig.GetLogger();
|
||||
_tempFiles = new TempFiles(_logConfig);
|
||||
_tempFiles.Create();
|
||||
tempFiles.Create();
|
||||
var jobId = typeof(FinalizeDocumentJob).FullName;
|
||||
_logger.LogDebug("Starting job {0}", jobId);
|
||||
logger.LogDebug("Starting job {jobId}", jobId);
|
||||
|
||||
try
|
||||
{
|
||||
_logger.LogDebug("Loading GdViewer..");
|
||||
_gdViewer = new GdViewer();
|
||||
_licenseManager.RegisterKEY(gdPictureKey);
|
||||
logger.LogDebug("Loading Configuration..");
|
||||
_config = _configModel?.LoadConfiguration() ?? throw new InvalidOperationException("Configuration could not be loaded because there is no record");
|
||||
|
||||
_logger.LogDebug("Loading Database..");
|
||||
var connectionString = config.GetConnectionString("Default") ?? throw new InvalidOperationException("Connection string 'Default' not found.");
|
||||
_databaseConnectionString = MSSQLServer.DecryptConnectionString(connectionString);
|
||||
_database = new MSSQLServer(_logConfig, _databaseConnectionString);
|
||||
|
||||
_logger.LogDebug("Loading Models & Services");
|
||||
var state = GetState();
|
||||
InitializeModels(state);
|
||||
|
||||
_logger.LogDebug("Loading Configuration..");
|
||||
_config = _configModel?.LoadConfiguration() ?? new DbConfig();
|
||||
state.DbConfig = _config;
|
||||
|
||||
InitializeServices(state);
|
||||
|
||||
_logger.LogDebug("Loading PDFBurner..");
|
||||
var pdfBurnerParams = _options.PdfBurner;
|
||||
_pdfBurner = new PDFBurner(_logConfig, gdPictureKey, pdfBurnerParams, _databaseConnectionString);
|
||||
|
||||
_logger.LogDebug("Loading PDFMerger..");
|
||||
_pdfMerger = new PDFMerger(_logConfig, gdPictureKey);
|
||||
|
||||
_logger.LogDebug("Loading ReportCreator..");
|
||||
_reportCreator = new ReportCreator(_logConfig, state);
|
||||
|
||||
_config.DocumentPath = _config.DocumentPath;
|
||||
|
||||
_logger.LogDebug("DocumentPath: [{0}]", _config.DocumentPath);
|
||||
_logger.LogDebug("ExportPath: [{0}]", _config.ExportPath);
|
||||
logger.LogDebug("DocumentPath: [{documentPath}]", _config.DocumentPath);
|
||||
logger.LogDebug("ExportPath: [{exportPath}]", _config.ExportPath);
|
||||
|
||||
var completeStatus = EnvelopeStatus.EnvelopeCompletelySigned;
|
||||
var sql = $"SELECT * FROM TBSIG_ENVELOPE WHERE STATUS = {completeStatus} AND DATEDIFF(minute, CHANGED_WHEN, GETDATE()) >= {CompleteWaitTime} ORDER BY GUID";
|
||||
@@ -105,7 +55,7 @@ public class FinalizeDocumentJob(IOptions<WorkerOptions> options, IConfiguration
|
||||
|
||||
if (envelopeIds.Count > 0)
|
||||
{
|
||||
_logger.LogInformation("Found [{0}] completed envelopes.", envelopeIds.Count);
|
||||
logger.LogInformation("Found [{count}] completed envelopes.", envelopeIds.Count);
|
||||
}
|
||||
|
||||
var total = envelopeIds.Count;
|
||||
@@ -113,58 +63,58 @@ public class FinalizeDocumentJob(IOptions<WorkerOptions> options, IConfiguration
|
||||
|
||||
foreach (var id in envelopeIds)
|
||||
{
|
||||
_logger.LogInformation("Finalizing Envelope [{0}] ({1}/{2})", id, current, total);
|
||||
logger.LogInformation("Finalizing Envelope [{id}] ({current}/{total})", id, current, total);
|
||||
try
|
||||
{
|
||||
var envelope = _envelopeModel?.GetById(id);
|
||||
if (envelope is null)
|
||||
{
|
||||
_logger.LogWarning("Envelope could not be loaded for Id [{0}]!", id);
|
||||
logger.LogWarning("Envelope could not be loaded for Id [{id}]!", id);
|
||||
throw new ArgumentNullException(nameof(EnvelopeData));
|
||||
}
|
||||
|
||||
_logger.LogDebug("Loading Envelope Data..");
|
||||
logger.LogDebug("Loading Envelope Data..");
|
||||
var envelopeData = GetEnvelopeData(id);
|
||||
|
||||
if (envelopeData is null)
|
||||
{
|
||||
_logger.LogWarning("EnvelopeData could not be loaded for Id [{0}]!", id);
|
||||
logger.LogWarning("EnvelopeData could not be loaded for Id [{id}]!", id);
|
||||
throw new ArgumentNullException(nameof(EnvelopeData));
|
||||
}
|
||||
|
||||
_logger.LogDebug("Burning Annotations to pdf ...");
|
||||
logger.LogDebug("Burning Annotations to pdf ...");
|
||||
var burnedDocument = BurnAnnotationsToPdf(envelopeData);
|
||||
if (burnedDocument is null)
|
||||
{
|
||||
_logger.LogWarning("Document could not be finalized!");
|
||||
logger.LogWarning("Document could not be finalized!");
|
||||
throw new ApplicationException("Document could not be finalized");
|
||||
}
|
||||
|
||||
if (_actionService?.CreateReport(envelope) == false)
|
||||
if (actionService?.CreateReport(envelope) == false)
|
||||
{
|
||||
_logger.LogWarning("Document Report could not be created!");
|
||||
logger.LogWarning("Document Report could not be created!");
|
||||
throw new ApplicationException("Document Report could not be created");
|
||||
}
|
||||
|
||||
_logger.LogDebug("Creating report..");
|
||||
var report = _reportCreator!.CreateReport(envelope);
|
||||
_logger.LogDebug("Report created!");
|
||||
logger.LogDebug("Creating report..");
|
||||
var report = reportCreator!.CreateReport(envelope);
|
||||
logger.LogDebug("Report created!");
|
||||
|
||||
_logger.LogDebug("Merging documents ...");
|
||||
var mergedDocument = _pdfMerger!.MergeDocuments(burnedDocument, report);
|
||||
_logger.LogDebug("Documents merged!");
|
||||
logger.LogDebug("Merging documents ...");
|
||||
var mergedDocument = pdfMerger!.MergeDocuments(burnedDocument, report);
|
||||
logger.LogDebug("Documents merged!");
|
||||
|
||||
var outputDirectoryPath = Path.Combine(_config.ExportPath, _parentFolderUid);
|
||||
_logger.LogDebug("oOutputDirectoryPath is {0}", outputDirectoryPath);
|
||||
logger.LogDebug("oOutputDirectoryPath is {outputDirectoryPath}", outputDirectoryPath);
|
||||
if (!Directory.Exists(outputDirectoryPath))
|
||||
{
|
||||
_logger.LogDebug("Directory not existing. Creating ... ");
|
||||
logger.LogDebug("Directory not existing. Creating ... ");
|
||||
Directory.CreateDirectory(outputDirectoryPath);
|
||||
}
|
||||
|
||||
var outputFilePath = Path.Combine(outputDirectoryPath, $"{envelope.Uuid}.pdf");
|
||||
_logger.LogDebug("Writing finalized Pdf to disk..");
|
||||
_logger.LogInformation("Output path is [{0}]", outputFilePath);
|
||||
logger.LogDebug("Writing finalized Pdf to disk..");
|
||||
logger.LogInformation("Output path is [{outputFilePath}]", outputFilePath);
|
||||
|
||||
try
|
||||
{
|
||||
@@ -172,11 +122,11 @@ public class FinalizeDocumentJob(IOptions<WorkerOptions> options, IConfiguration
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning("Could not export final document to disk!");
|
||||
logger.LogWarning("Could not export final document to disk!");
|
||||
throw new ExportDocumentException("Could not export final document to disk!", ex);
|
||||
}
|
||||
|
||||
_logger.LogDebug("Writing EB-bytes to database...");
|
||||
logger.LogDebug("Writing EB-bytes to database...");
|
||||
UpdateFileDb(outputFilePath, envelope.Id);
|
||||
|
||||
if (!SendFinalEmails(envelope))
|
||||
@@ -184,45 +134,45 @@ public class FinalizeDocumentJob(IOptions<WorkerOptions> options, IConfiguration
|
||||
throw new ApplicationException("Final emails could not be sent!");
|
||||
}
|
||||
|
||||
_logger.LogInformation("Report-mails successfully sent!");
|
||||
logger.LogInformation("Report-mails successfully sent!");
|
||||
|
||||
_logger.LogDebug("Setting envelope status..");
|
||||
if (_actionService?.FinalizeEnvelope(envelope) == false)
|
||||
logger.LogDebug("Setting envelope status..");
|
||||
if (actionService?.FinalizeEnvelope(envelope) == false)
|
||||
{
|
||||
_logger.LogWarning("Envelope could not be finalized!");
|
||||
logger.LogWarning("Envelope could not be finalized!");
|
||||
throw new ApplicationException("Envelope could not be finalized");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.Error(ex);
|
||||
_logger.LogWarning(ex, "Unhandled exception while working envelope [{0}]", id);
|
||||
logger.LogError(ex);
|
||||
logger.LogWarning(ex, "Unhandled exception while working envelope [{id}]", id);
|
||||
}
|
||||
|
||||
current += 1;
|
||||
_logger.LogInformation("Envelope [{0}] finalized!", id);
|
||||
logger.LogInformation("Envelope [{id}] finalized!", id);
|
||||
}
|
||||
|
||||
_logger.LogDebug("Completed job {0} successfully!", jobId);
|
||||
logger.LogDebug("Completed job {jobId} successfully!", jobId);
|
||||
}
|
||||
catch (MergeDocumentException ex)
|
||||
{
|
||||
_logger.LogWarning("Certificate Document job failed at step: Merging documents!");
|
||||
_logger.Error(ex);
|
||||
logger.LogWarning("Certificate Document job failed at step: Merging documents!");
|
||||
logger.LogError(ex);
|
||||
}
|
||||
catch (ExportDocumentException ex)
|
||||
{
|
||||
_logger.LogWarning("Certificate Document job failed at step: Exporting document!");
|
||||
_logger.Error(ex);
|
||||
logger.LogWarning("Certificate Document job failed at step: Exporting document!");
|
||||
logger.LogError(ex);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning("Certificate Document job failed!");
|
||||
_logger.Error(ex);
|
||||
logger.LogWarning("Certificate Document job failed!");
|
||||
logger.LogError(ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_logger.LogDebug("Job execution for [{0}] ended", jobId);
|
||||
logger.LogDebug("Job execution for [{jobId}] ended", jobId);
|
||||
}
|
||||
|
||||
return Task.FromResult(true);
|
||||
@@ -245,7 +195,7 @@ public class FinalizeDocumentJob(IOptions<WorkerOptions> options, IConfiguration
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger?.Error(ex);
|
||||
logger?.LogError(ex);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -265,22 +215,22 @@ public class FinalizeDocumentJob(IOptions<WorkerOptions> options, IConfiguration
|
||||
|
||||
if (mailToCreator != FinalEmailType.No)
|
||||
{
|
||||
_logger?.LogDebug("Sending email to creator ...");
|
||||
logger?.LogDebug("Sending email to creator ...");
|
||||
SendFinalEmailToCreator(envelope, mailToCreator);
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger?.LogWarning("No SendFinalEmailToCreator - oMailToCreator [{0}] <> [{1}] ", mailToCreator, FinalEmailType.No);
|
||||
logger?.LogWarning("No SendFinalEmailToCreator - oMailToCreator [{0}] <> [{1}] ", mailToCreator, FinalEmailType.No);
|
||||
}
|
||||
|
||||
if (mailToReceivers != FinalEmailType.No)
|
||||
{
|
||||
_logger?.LogDebug("Sending emails to receivers..");
|
||||
logger?.LogDebug("Sending emails to receivers..");
|
||||
SendFinalEmailToReceivers(envelope, mailToReceivers);
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger?.LogWarning("No SendFinalEmailToReceivers - oMailToCreator [{0}] <> [{1}] ", mailToReceivers, FinalEmailType.No);
|
||||
logger?.LogWarning("No SendFinalEmailToReceivers - oMailToCreator [{0}] <> [{1}] ", mailToReceivers, FinalEmailType.No);
|
||||
}
|
||||
|
||||
return true;
|
||||
@@ -289,11 +239,11 @@ public class FinalizeDocumentJob(IOptions<WorkerOptions> options, IConfiguration
|
||||
private bool SendFinalEmailToCreator(Envelope envelope, FinalEmailType mailToCreator)
|
||||
{
|
||||
var includeAttachment = SendFinalEmailWithAttachment(mailToCreator);
|
||||
_logger?.LogDebug("Attachment included: [{0}]", includeAttachment);
|
||||
logger?.LogDebug("Attachment included: [{0}]", includeAttachment);
|
||||
|
||||
if (_actionService?.CompleteEnvelope(envelope) == false)
|
||||
if (actionService?.CompleteEnvelope(envelope) == false)
|
||||
{
|
||||
_logger?.LogError(new Exception("CompleteEnvelope failed"), "Envelope could not be completed for receiver [{0}]", envelope.User?.Email);
|
||||
logger?.LogError(new Exception("CompleteEnvelope failed"), "Envelope could not be completed for receiver [{0}]", envelope.User?.Email);
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -303,13 +253,13 @@ public class FinalizeDocumentJob(IOptions<WorkerOptions> options, IConfiguration
|
||||
private bool SendFinalEmailToReceivers(Envelope envelope, FinalEmailType mailToReceivers)
|
||||
{
|
||||
var includeAttachment = SendFinalEmailWithAttachment(mailToReceivers);
|
||||
_logger?.LogDebug("Attachment included: [{0}]", includeAttachment);
|
||||
logger?.LogDebug("Attachment included: [{0}]", includeAttachment);
|
||||
|
||||
foreach (var receiver in envelope.EnvelopeReceivers ?? Enumerable.Empty<EnvelopeReceiver>())
|
||||
{
|
||||
if (_actionService?.CompleteEnvelope(envelope, receiver.Receiver) == false)
|
||||
if (actionService?.CompleteEnvelope(envelope, receiver.Receiver) == false)
|
||||
{
|
||||
_logger?.LogError(new Exception("CompleteEnvelope failed"), "Envelope could not be completed for receiver [{0}]", receiver.Receiver?.EmailAddress);
|
||||
logger?.LogError(new Exception("CompleteEnvelope failed"), "Envelope could not be completed for receiver [{0}]", receiver.Receiver?.EmailAddress);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -326,19 +276,19 @@ public class FinalizeDocumentJob(IOptions<WorkerOptions> options, IConfiguration
|
||||
{
|
||||
var envelopeId = envelopeData.EnvelopeId;
|
||||
|
||||
_logger?.LogInformation("Burning [{0}] signatures", envelopeData.AnnotationData.Count);
|
||||
logger?.LogInformation("Burning [{0}] signatures", envelopeData.AnnotationData.Count);
|
||||
var annotations = envelopeData.AnnotationData;
|
||||
var inputPath = string.Empty;
|
||||
if (envelopeData.DocAsByte is null)
|
||||
{
|
||||
inputPath = envelopeData.DocumentPath;
|
||||
_logger?.LogInformation("Input path: [{0}]", inputPath);
|
||||
logger?.LogInformation("Input path: [{0}]", inputPath);
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger?.LogDebug("we got bytes..");
|
||||
logger?.LogDebug("we got bytes..");
|
||||
inputPath = _config!.DocumentPathOrigin;
|
||||
_logger?.LogDebug("oInputPath: {0}", _config.DocumentPathOrigin);
|
||||
logger?.LogDebug("oInputPath: {0}", _config.DocumentPathOrigin);
|
||||
}
|
||||
|
||||
if (envelopeData.DocAsByte is null)
|
||||
@@ -352,7 +302,7 @@ public class FinalizeDocumentJob(IOptions<WorkerOptions> options, IConfiguration
|
||||
_parentFolderUid = envelopeData.EnvelopeUuid;
|
||||
}
|
||||
|
||||
_logger?.LogInformation("ParentFolderUID: [{0}]", _parentFolderUid);
|
||||
logger?.LogInformation("ParentFolderUID: [{0}]", _parentFolderUid);
|
||||
byte[] inputDocumentBuffer;
|
||||
if (envelopeData.DocAsByte is not null)
|
||||
{
|
||||
@@ -370,7 +320,7 @@ public class FinalizeDocumentJob(IOptions<WorkerOptions> options, IConfiguration
|
||||
}
|
||||
}
|
||||
|
||||
return _pdfBurner!.BurnAnnotsToPDF(inputDocumentBuffer, annotations, envelopeId);
|
||||
return pdfBurner!.BurnAnnotsToPDF(inputDocumentBuffer, annotations, envelopeId);
|
||||
}
|
||||
|
||||
private EnvelopeData? GetEnvelopeData(int envelopeId)
|
||||
@@ -393,7 +343,7 @@ public class FinalizeDocumentJob(IOptions<WorkerOptions> options, IConfiguration
|
||||
EnvelopeUuid = row.ItemEx("ENVELOPE_UUID", string.Empty)
|
||||
};
|
||||
|
||||
_logger?.LogDebug("Document path: [{0}]", data.DocumentPath);
|
||||
logger?.LogDebug("Document path: [{0}]", data.DocumentPath);
|
||||
|
||||
return data;
|
||||
}
|
||||
@@ -407,28 +357,4 @@ public class FinalizeDocumentJob(IOptions<WorkerOptions> options, IConfiguration
|
||||
.Select(r => r.ItemEx("VALUE", string.Empty))
|
||||
.ToList();
|
||||
}
|
||||
|
||||
private void InitializeServices(State state)
|
||||
{
|
||||
_actionService = new ActionService(state, _database!);
|
||||
}
|
||||
|
||||
private void InitializeModels(State state)
|
||||
{
|
||||
_configModel = new ConfigModel(state);
|
||||
_envelopeModel = new EnvelopeModel(state);
|
||||
_reportModel = new ReportModel(state);
|
||||
}
|
||||
|
||||
private State GetState()
|
||||
{
|
||||
return new State
|
||||
{
|
||||
LogConfig = _logConfig!,
|
||||
Database = _database!,
|
||||
UserId = 0,
|
||||
Config = null,
|
||||
DbConfig = null
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user