2025-05-09 16:51:31 +02:00

222 lines
9.9 KiB
VB.net

Imports DigitalData.Modules.Database
Imports DigitalData.Modules.Logging
Imports DigitalData.Modules.Base
Imports GdPicture14
Imports Quartz
Imports System.Security.Cryptography
Imports System.IO
Imports EnvelopeGenerator.Common.Jobs.FinalizeDocument.FinalizeDocumentExceptions
Imports EnvelopeGenerator.Common.Jobs.FinalizeDocument
Imports EnvelopeGenerator.Common.Constants
Imports DevExpress.DataProcessing
Imports System.Data.SqlClient
Imports DevExpress.XtraRichEdit.Layout.Engine
Namespace Jobs
Public Class APIEnvelopeJob
Implements IJob
Private LogConfig As LogConfig
Private Logger As Logger
Private Database As MSSQLServer
Private Config As DbConfig
Private ConfigModel As ConfigModel
Private EnvelopeModel As EnvelopeModel
Private ReceiverModel As ReceiverModel
Private ActionService As ActionService
Private ReadOnly CompleteWaitTime As Integer = 1
Private myTempFiles As TempFiles
Private Class EnvelopeData
Public EnvelopeId As Integer
Public EnvelopeUUID As String
Public DocumentPath As String
End Class
Public Function Execute(pContext As IJobExecutionContext) As Task Implements IJob.Execute
LogConfig = pContext.MergedJobDataMap.Item(Constants.LOGCONFIG)
Logger = LogConfig.GetLogger()
myTempFiles = New TempFiles(LogConfig)
myTempFiles.Create()
Dim JobId = pContext.JobDetail.Key
Logger.Debug("API Envelopes - Starting job {0}", JobId)
Try
Logger.Debug("API Envelopes - Loading Database..")
Database = GetDatabase(pContext, LogConfig)
Logger.Debug("API Envelopes - Loading Models & Services")
Dim oState = GetState()
InitializeModels(oState)
Logger.Debug("API Envelopes - Loading Configuration..")
Config = ConfigModel.LoadConfiguration()
oState.DbConfig = Config
InitializeServices(oState)
Config.DocumentPath = Config.DocumentPath
Logger.Debug("API Envelopes - ExportPath: [{0}]", Config.ExportPath)
Dim oSql = $"SELECT * FROM TBSIG_ENVELOPE where SOURCE = 'API' AND STATUS = 1003 order by guid"
Dim oDTEnv_invitations = Database.GetDatatable(oSql)
Dim oEnvelopeIds As List(Of Integer) = oDTEnv_invitations.Rows.Cast(Of DataRow).
Select(Function(r) r.Item("GUID")).
Cast(Of Integer).
ToList()
If oEnvelopeIds.Count > 0 Then
Logger.Info("SendInvMail - Found [{0}] envelopes.", oEnvelopeIds.Count)
End If
Dim oTotal As Integer = oEnvelopeIds.Count
Dim oCurrent As Integer = 1
For Each oId In oEnvelopeIds
Logger.Info("SendInvMail - Gathering Info for Envelope [{0}] ({1}/{2})", oId, oCurrent, oTotal)
Try
Dim oEnvelope = EnvelopeModel.GetById(oId)
If oEnvelope Is Nothing Then
Logger.Warn("SendInvMail - Envelope could not be loaded for Id [{0}]!", oId)
Throw New ArgumentNullException("EnvelopeData")
End If
oEnvelope.CURRENT_WORK_APP = "signFLOW_API_EnvJob_InvMail"
Logger.Debug("SendInvMail - Loading Envelope Data..")
Dim oEnvelopeData = GetEnvelopeData(oId)
oEnvelope.Receivers = ReceiverModel.ListEnvelopeReceivers(oEnvelope.Id).ToList()
Logger.Debug("SendInvMail - Created Reveivers!")
If oEnvelopeData Is Nothing Then
Logger.Warn("SendInvMail - EnvelopeData could not be loaded for Id [{0}]!", oId)
Throw New ArgumentNullException("EnvelopeData")
End If
Logger.Info("SendInvMail - Sending InvitationMails for Envelope [{0}]", oId)
If ActionService.SendEnvelope(oEnvelope) = False Then
Logger.Warn("SendInvMail - Could not send the InvitationMails for Envelope [{0}]", oId)
Throw New ArgumentNullException("EnvelopeData")
End If
Catch ex As Exception
Logger.Warn(ex, $"SendInvMail - Unhandled exception while working envelope [{oId}]")
End Try
oCurrent += 1
Logger.Info("SendInvMail - Envelope finalized!")
Next
'Hier nun der Teil um zurückgezogene Envelopes abzuarbeiten
oSql = $"SELECT ENV.GUID,REJ.COMMENT REJECTION_REASON FROM
(SELECT * FROM TBSIG_ENVELOPE where STATUS = 1009 AND SOURCE = 'API') ENV INNER JOIN
(SELECT MAX(GUID) GUID,ENVELOPE_ID,MAX(ADDED_WHEN) ADDED_WHEN,MAX(ACTION_DATE) ACTION_DATE, COMMENT FROM TBSIG_ENVELOPE_HISTORY where STATUS = 1009 GROUP BY ENVELOPE_ID,COMMENT ) REJ ON ENV.GUID = REJ.ENVELOPE_ID LEFT JOIN
(SELECT * FROM TBSIG_ENVELOPE_HISTORY where STATUS = 3004 ) M_Send ON ENV.GUID = M_Send.ENVELOPE_ID
where M_Send.GUID IS NULL"
Dim oDT_EnvWithdrawn = Database.GetDatatable(oSql)
oEnvelopeIds = oDTEnv_invitations.Rows.Cast(Of DataRow).
Select(Function(r) r.Item("GUID")).
Cast(Of Integer).
ToList()
If oEnvelopeIds.Count > 0 Then
Logger.Info("WithdrawnEnv - Found [{0}] envelopes.", oEnvelopeIds.Count)
End If
oTotal = oEnvelopeIds.Count
oCurrent = 1
Dim oEnvID As Integer
For Each oRow As DataRow In oDT_EnvWithdrawn.Rows
oEnvID = oRow.Item("GUID")
Dim oReason = oRow.Item("REJECTION_REASON")
Logger.Info("WithdrawnEnv - Gathering Info for Envelope [{0}] ({1}/{2})", oEnvID, oCurrent, oTotal)
Try
Dim oEnvelope = EnvelopeModel.GetById(oEnvID)
If oEnvelope Is Nothing Then
Logger.Warn("WithdrawnEnv - Envelope could not be loaded for Id [{0}]!", oEnvID)
Throw New ArgumentNullException("EnvelopeData")
End If
oEnvelope.CURRENT_WORK_APP = "signFLOW_API_EnvJob_Withdrawn"
oEnvelope.Receivers = ReceiverModel.ListEnvelopeReceivers(oEnvelope.Id).ToList()
Logger.Debug("WithdrawnEnv - Sending Withdrawn Mails..")
If ActionService.API_SendWithdrawn_Mails(oEnvelope, oReason) = False Then
Logger.Warn("Could not send the Mails for withdrawn Envelope")
Else
Dim oStatInsert = $"INSERT INTO TBSIG_ENVELOPE_HISTORY (ENVELOPE_ID,STATUS,USER_REFERENCE,ADDED_WHEN,ACTION_DATE) VALUES ('{oEnvelope.Id}',3004,'API',GETDATE(),GETDATE())"
Database.ExecuteNonQuery(oStatInsert)
End If
Catch ex As Exception
Logger.Warn(ex, $"WithdrawnEnv - Unhandled exception while working envelope [{oEnvID}]")
End Try
oCurrent += 1
Logger.Info("WithdrawnEnv - Envelope finalized!")
Next
Logger.Debug("API Envelopes - Completed job {0} successfully!", JobId)
Catch ex As Exception
Logger.Warn("API Envelopes job failed!")
Logger.Error(ex)
Finally
Logger.Debug("API Envelopes execution for [{0}] ended", JobId)
End Try
Return Task.FromResult(True)
End Function
Private Sub InitializeModels(pState As State)
ConfigModel = New ConfigModel(pState)
EnvelopeModel = New EnvelopeModel(pState)
ReceiverModel = New ReceiverModel(pState)
End Sub
Private Sub InitializeServices(pState As State)
ActionService = New ActionService(pState, Database)
End Sub
Private Function GetDatabase(pContext As IJobExecutionContext, pLogConfig As LogConfig) As MSSQLServer
Dim oConnectionString As String = pContext.MergedJobDataMap.Item(Constants.DATABASE)
Dim Database = New MSSQLServer(pLogConfig, MSSQLServer.DecryptConnectionString(oConnectionString))
Return Database
End Function
Private Function GetEnvelopeData(pEnvelopeId As Integer) As EnvelopeData
Dim oSql = $"SELECT T.GUID, T.ENVELOPE_UUID,T2.FILEPATH, T2.BYTE_DATA FROM [dbo].[TBSIG_ENVELOPE] T
JOIN TBSIG_ENVELOPE_DOCUMENT T2 ON T.GUID = T2.ENVELOPE_ID
WHERE T.GUID = {pEnvelopeId}"
Dim oTable As DataTable = Database.GetDatatable(oSql)
Dim oRow As DataRow = oTable.Rows.Cast(Of DataRow).SingleOrDefault()
If oRow Is Nothing Then
Return Nothing
End If
Dim oData As New EnvelopeData With {
.EnvelopeId = pEnvelopeId,
.DocumentPath = oRow.ItemEx("FILEPATH", ""),
.EnvelopeUUID = oRow.ItemEx("ENVELOPE_UUID", "")
}
Logger.Debug("Document path: [{0}]", oData.DocumentPath)
Return oData
End Function
Private Function GetState() As State
Return New State With {
.LogConfig = LogConfig,
.Database = Database,
.UserId = 0,
.Config = Nothing,
.DbConfig = Nothing
}
End Function
End Class
End Namespace