' SummaryPage2_ElectronicSignatureSummary_SecuredSigning
Option Explicit On
Option Strict On

' #################################################################
' Secured Signing Electronic Signature Summary Page Script
'
' Version: 2.14 (01/06/2023)
'
' Usage: Log Forms, Pending Service Request wizard
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    2.07  14/05/2021  ISS
'    2.08  04/11/2021  ISS      J027713   Updated obsoleted functions
'    2.09  14/07/2022  ISS      J029159   Updated div colour to ensure Test Mode watermark is visible
'    2.10  15/07/2022  ISS      J029160   Updated theme
'    2.11  03/11/2022  ISS      J029944   Added ID Check Status
'    2.12  20/03/2023  ISS      J027938   Application shortcut not visible on web pages
'    2.13  08/05/2023  ISS      J030883   Support for retrieving ID Verification reports
'    2.14  18/05/2023  ISS      J031060   Added IDVerificationStatus,FaceMatchResult, LivenessResult columns
'          18/05/2023  ISS      J031074   Added Alerts 
'          01/06/2023  ISS      J031087   Better handling of Documents not enclosed in a Package
' #################################################################

'#Const "ExtendDays",Integer,2,"Days to extend Due Date from today (Negative number disallows)"
'#Const "ShowDocumentFieldData",Boolean,False,"Show Document Field Data information?"

' Constants
Private ExtendDays As Integer = 2
Private ShowDocumentFieldData As Boolean = False

' Special Constants
Const TestMode As Boolean = False

Public Function Main(source As Object,
                     eventId As String,
                     eventArgs As ISKeyValueList,
                     ByRef handled As Boolean,
                     ByRef returnValues As ISKeyValueList,
                     ByRef text As String) As Boolean

  Dim ServiceLogs As ISServiceLogs
  
  ' Assume Success
  Main = True

  ' Get Constants
  With ScriptInfo.Constants
    ExtendDays = .GetInteger("ExtendDays", ExtendDays)
    ShowDocumentFieldData = .GetBoolean("ShowDocumentFieldData", ShowDocumentFieldData)
  End With

  ' Get Service Logs (ignoring any errors)
  Try
    Main = finBL.ElectronicSignature.GetServiceLogs(CInt(source), ServiceLogs)
  Catch ex As Exception
    Main = False
    finBL.Error.ErrorBeginFromException(ex)
  End Try
  If Main Then
    If ServiceLogs.Count = 0 Then
      Main = False
      finBL.Error.ErrorBegin("Invalid Service Log for an Electronic Signature.")
    ElseIf ServiceLogs(0).RequestStatus <> iseAuditLogStatus.Success Then
      Main = False
      finBL.Error.ErrorBegin("Invalid Service Log. Initial Request was not successful.")
    Else
      Select Case TypeName(ServiceLogs(0).ExResponse)
        Case "ISElectronicSignatureResponse_SecuredSigning_DocumentStatus"
        Case "ISElectronicSignatureResponse_SecuredSigning_PackageStatus"
        Case "ISElectronicSignatureResponse_SecuredSigning_SmartTagSend"
        Case Else
          finBL.Error.ErrorBegin("Invalid Service Log. Request is not for a Secured Signing Electronic Signature.")
          Return False
      End Select
    End If
  End If

  ' Handle Events
  If Main Then
    Select Case eventId
      Case ""
        ' Main event, i.e., return main page content
        Main = CreatePage(ServiceLogs, text)
    End Select
  End If

End Function

Private Function CreatePage(serviceLogs As ISServiceLogs,
                            ByRef html As String) As Boolean

  Dim HtmlSummaryPage2StringBuilder As finHtmlSummaryPage2StringBuilder
  Dim Response As ISElectronicSignatureResponse
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise ByRef
  html = ""

  ' Get Initial Response
  Response = DirectCast(serviceLogs(0).ExResponse, ISElectronicSignatureResponse)

  ' Initialise HTML
  HtmlSummaryPage2StringBuilder = finBL.CreateHtmlSummaryPage2StringBuilder()
  With HtmlSummaryPage2StringBuilder
    ' Initialise
    ' Note: Embed images (will also embed CSS) since we want to be able to easily produce a PDF document
    .Initialise(ScriptInfo, False, True)

    ' Display Test watermark
    If serviceLogs(0).TestMode Then .Watermark = "Test Mode"

    ' Begin HTML Header
    .HtmlHeaderBegin(String.Format("{0} {1}", Response.ServiceName, Response.ProductId), isefinSummaryPageStyle.ServiceReport)

    ' Theme
    .HtmlHeaderInsertServiceReportTheme("#1c5b7c", "#adadad", "", "#ececec")

    ' Intersoft PDF Options (including style tweaks)
    .HtmlHeaderInsertPdfGenerationHints("A4", "Portrait", 880, "1.5cm", "1.5cm", "1cm", "1cm", "font-size:0.9em")

    ' Finalise HTML Header
    .HtmlHeaderEnd()
  End With
  
  Select Case TypeName(Response)
    Case "ISElectronicSignatureResponse_SecuredSigning_DocumentStatus"
      ' Created from an existing Electronic Signature
      CreatePage_DocumentStatus(HtmlSummaryPage2StringBuilder, DirectCast(Response, ISElectronicSignatureResponse_SecuredSigning_DocumentStatus), serviceLogs)

    Case "ISElectronicSignatureResponse_SecuredSigning_PackageStatus"
      ' Created from an existing Electronic Signature
      CreatePage_PackageStatus(HtmlSummaryPage2StringBuilder, DirectCast(Response, ISElectronicSignatureResponse_SecuredSigning_PackageStatus), serviceLogs)

    Case "ISElectronicSignatureResponse_SecuredSigning_SmartTagSend"
      CreatePage_SmartTagSend(HtmlSummaryPage2StringBuilder, DirectCast(Response, ISElectronicSignatureResponse_SecuredSigning_SmartTagSend), serviceLogs)

    Case Else
      Success = False
      finBL.Error.ErrorBeginFormat("Unexpected Response Type '{0}'.", TypeName(Response))
  End Select

  If Success Then
    ' Disclaimer
    HtmlSummaryPage2StringBuilder.AppendLine("{{disclaimer|This report was produced by finPOWER Connect version " & finBL.VersionMajorMinorBuild & " using information retrieved from the " & Response.ServiceName & " service on " & finBL.FormatDateTime(Response.RequestDate, True, True, True) &"}}")

    ' Finalise HTML
    HtmlSummaryPage2StringBuilder.HtmlFinalise()

    ' Resolve Templates
    html = HtmlSummaryPage2StringBuilder.ToString(True)
  End If

  Return Success

End Function

Private Sub CreatePage_DocumentStatus(htmlSummaryPage2StringBuilder As finHtmlSummaryPage2StringBuilder,
                                      documentStatus As ISElectronicSignatureResponse_SecuredSigning_DocumentStatus,
                                      serviceLogs As ISServiceLogs)

  With htmlSummaryPage2StringBuilder
    ' Heading
    .AppendH1(documentStatus.Document.Name)
    .AppendH2(documentStatus.ServiceName)
    .SummaryTablesAppend(Me.SecuredSigning_Actions(serviceLogs))
    Me.SecuredSigning_CurrentStatus(htmlSummaryPage2StringBuilder, serviceLogs)
    .SummaryTablesAppend(Me.SecuredSigning_History(serviceLogs))
  End With

End Sub

Private Sub CreatePage_PackageStatus(htmlSummaryPage2StringBuilder As finHtmlSummaryPage2StringBuilder,
                                     packageStatus As ISElectronicSignatureResponse_SecuredSigning_PackageStatus,
                                     serviceLogs As ISServiceLogs)

  With htmlSummaryPage2StringBuilder
    ' Heading
    .AppendH1(packageStatus.Package.PackageName)
    .AppendH2(packageStatus.ServiceName)
    .SummaryTablesAppend(Me.SecuredSigning_Actions(serviceLogs))
    Me.SecuredSigning_CurrentStatus(htmlSummaryPage2StringBuilder, serviceLogs)
    .SummaryTablesAppend(Me.SecuredSigning_History(serviceLogs))
  End With

End Sub

Private Sub CreatePage_SmartTagSend(htmlSummaryPage2StringBuilder As finHtmlSummaryPage2StringBuilder,
                                    smartTagSend As ISElectronicSignatureResponse_SecuredSigning_SmartTagSend,
                                    serviceLogs As ISServiceLogs)

  With htmlSummaryPage2StringBuilder
    ' Heading
    If smartTagSend.IsPackage Then
      .AppendH1(smartTagSend.Package.PackageName)
    Else
      .AppendH1(smartTagSend.Documents.Item(0).Name)
    End If
    .AppendH2(smartTagSend.ServiceName)
    .SummaryTablesAppend(Me.SecuredSigning_Actions(serviceLogs))
    Me.SecuredSigning_CurrentStatus(htmlSummaryPage2StringBuilder, serviceLogs)
    .AppendH2("Original Document Details")
    Me.SecuredSigning_OriginalDetails(htmlSummaryPage2StringBuilder, smartTagSend)
    .SummaryTablesAppend(Me.SecuredSigning_History(serviceLogs))
  End With

End Sub

Private Function SecuredSigning_Actions(serviceLogs As ISServiceLogs) As ISSummaryTables

  Dim DueDateEarliest As Date
  Dim DueDate As Date
  Dim IsPackage As Boolean
  Dim Response_Package As ISElectronicSignatureResponse_SecuredSigning_Package
  Dim ServiceLog As ISServiceLog
  Dim strTemp As String
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Get Type
  Select Case TypeName(ServiceLogs(0).ExResponse)
    Case "ISElectronicSignatureResponse_SecuredSigning_DocumentStatus"
      IsPackage = False
    Case "ISElectronicSignatureResponse_SecuredSigning_PackageStatus"
      IsPackage = True
    Case "ISElectronicSignatureResponse_SecuredSigning_SmartTagSend"
      IsPackage = DirectCast(ServiceLogs(0).ExResponse, ISElectronicSignatureResponse_SecuredSigning_SmartTagSend).IsPackage
  End Select

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  ' Create Summary Table
  SummaryTable = SummaryTables.CreateSummaryTableBlank("", "", "", 2)

  ' Add Actions
  With SummaryTable.Actions
    ' Add Action to Update Status
    Select Case serviceLogs(0).ResponseStatus
      Case iseServiceLogResponseStatus.InProgress
        ' Warning if doing too often
        If finBL.TimeZoneFunctions.GetCurrentUtcDateTime() > serviceLogs(0).ResponseNextCheckUtcDate Then
          strTemp = ""
        Else
          strTemp = String.format(" !!WARNING: Not due to be re-checked until {0}!!", finBL.FormatDateTimeLong(serviceLogs(0).ResponseNextCheckDate))
        End If
        .AddApplicationShortcutUrl("UpdateStatus", "Update Status", String.Format("app://global?type=ElectronicSignature.UpdateStatus&serviceLogPk={0}", serviceLogs(0).Pk), True).ShowInWebInterfaces = True
    End Select

    ' Add Action to Extend
    Select Case serviceLogs(0).ResponseStatus
      Case iseServiceLogResponseStatus.Expired, iseServiceLogResponseStatus.InProgress
        If IsPackage AndAlso ExtendDays >= 0 Then
          ' Get Package
          For Each ServiceLog In serviceLogs
            Select Case TypeName(ServiceLog.ExResponse)
              Case "ISElectronicSignatureResponse_SecuredSigning_PackageExtend"
                Response_Package = DirectCast(ServiceLog.ExResponse, ISElectronicSignatureResponse_SecuredSigning_PackageExtend).Package
              Case "ISElectronicSignatureResponse_SecuredSigning_PackageStatus"
                Response_Package = DirectCast(ServiceLog.ExResponse, ISElectronicSignatureResponse_SecuredSigning_PackageStatus).Package
              Case "ISElectronicSignatureResponse_SecuredSigning_SmartTagSend"
                Response_Package = DirectCast(ServiceLog.ExResponse, ISElectronicSignatureResponse_SecuredSigning_SmartTagSend).Package
            End Select
          Next

          ' Find new Due Date
          DueDate = finBL.TimeZoneFunctions.GetCurrentDatabaseDate.AddDays(ExtendDays)
          DueDateEarliest = Response_Package.Documents.GetEarliestRemainingDueDate().Date

          If DueDate < DueDateEarliest Then
            .AddApplicationShortcutUrl("Extend", String.Format("Shorten to {0}", finBL.FormatDateLong(DueDate)), String.Format("app://global?type=ElectronicSignature.Extend&serviceLogPk={0}&DueDate={1}", serviceLogs(0).Pk, format(DueDate,"yyyy-MM-dd")), True).ShowInWebInterfaces = True
          ElseIf DueDate > DueDateEarliest Then
            .AddApplicationShortcutUrl("Extend", String.Format("Extend to {0}", finBL.FormatDateLong(DueDate)), String.Format("app://global?type=ElectronicSignature.Extend&serviceLogPk={0}&DueDate={1}", serviceLogs(0).Pk, format(DueDate,"yyyy-MM-dd")), True).ShowInWebInterfaces = True
          End If
        End If
    End Select

    ' Add Action to Cancel Electronic Signature
    Select Case serviceLogs(0).ResponseStatus
      Case iseServiceLogResponseStatus.InProgress
        .AddApplicationShortcutUrl("Cancel", "Cancel", String.Format("app://global?type=ElectronicSignature.Cancel&serviceLogPk=" & serviceLogs(0).Pk), True).ShowInWebInterfaces = True
    End Select
  End With

  ' Add Summary Table
  If SummaryTable.Actions.Count <> 0 Then SummaryTables.Add("Actions", SummaryTable)

  Return SummaryTables

End Function

Private Sub SecuredSigning_CurrentStatus(htmlSummaryPage2StringBuilder As finHtmlSummaryPage2StringBuilder,
                                         serviceLogs As ISServiceLogs)

  Dim DeleteReason As String
  Dim DocumentIndex As Integer
  Dim Response_Document As ISElectronicSignatureResponse_SecuredSigning_Document
  Dim Response_DocumentDelete As ISElectronicSignatureResponse_SecuredSigning_DocumentDelete
  Dim Response_Package As ISElectronicSignatureResponse_SecuredSigning_Package
  Dim Response_PackageDelete As ISElectronicSignatureResponse_SecuredSigning_PackageDelete
  Dim IsPackage As Boolean
  Dim OddRow As Boolean
  Dim ServiceLog As ISServiceLog
  Dim SummaryTable As ISSummaryTable

  ' Get Type
  Select Case TypeName(ServiceLogs(0).ExResponse)
    Case "ISElectronicSignatureResponse_SecuredSigning_DocumentStatus"
      IsPackage = False
    Case "ISElectronicSignatureResponse_SecuredSigning_PackageStatus"
      IsPackage = True
    Case "ISElectronicSignatureResponse_SecuredSigning_SmartTagSend"
      IsPackage = DirectCast(ServiceLogs(0).ExResponse, ISElectronicSignatureResponse_SecuredSigning_SmartTagSend).IsPackage
  End Select

  If IsPackage Then
    ' PACKAGE
    ' Get Latest Status
    For Each ServiceLog In serviceLogs
      Select Case TypeName(ServiceLog.ExResponse)
        Case "ISElectronicSignatureResponse_SecuredSigning_PackageDelete"
          Response_PackageDelete = DirectCast(ServiceLog.ExResponse, ISElectronicSignatureResponse_SecuredSigning_PackageDelete)
        Case "ISElectronicSignatureResponse_SecuredSigning_PackageExtend"
          Response_Package = DirectCast(ServiceLog.ExResponse, ISElectronicSignatureResponse_SecuredSigning_PackageExtend).Package
        Case "ISElectronicSignatureResponse_SecuredSigning_PackageStatus"
          Response_Package = DirectCast(ServiceLog.ExResponse, ISElectronicSignatureResponse_SecuredSigning_PackageStatus).Package
        Case "ISElectronicSignatureResponse_SecuredSigning_SmartTagSend"
          Response_Package = DirectCast(ServiceLog.ExResponse, ISElectronicSignatureResponse_SecuredSigning_SmartTagSend).Package
      End Select
    Next

    With HtmlSummaryPage2StringBuilder
      If Response_Package Is Nothing Then
        ' Should never get here!
      Else
        ' Package Details
        SummaryTable = finBL.CreateSummaryTables.CreateSummaryTableInformation("Current Package Status", "CurrentStatus", 2,,, TestMode)
        With SummaryTable
          .AddRowCaptionText("Package Name:", Response_Package.PackageName, True)
          If Response_Package.StatusTerminal Then
            If Response_Package.StatusComplete Then
              .AddRowCaptionWiki("Status:", String.Format("**++{0} (Closed)++**", Response_Package.Status), True, iseSummaryTableCellClass.Highlight2)
            Else
              .AddRowCaptionWiki("Status:", String.Format("**!!{0} (Closed)!!**", Response_Package.Status), True, iseSummaryTableCellClass.Highlight2)
            End If
            If Response_PackageDelete IsNot Nothing Then
              .AddRowCaptionText("Reason:", Response_PackageDelete.Request.Comment, False)
            End If
          Else
            .AddRowCaptionText("Status:", Response_Package.Status, True)
          End If
        End With
        .SummaryTableAppend(SummaryTable)

        ' Alerts
        .SummaryTablesAppend(Me.SecuredSigning_Alerts(serviceLogs))
        
        ' Documents
        OddRow = False
        For DocumentIndex = 0 To Response_Package.Documents.Count - 1
          Response_Document = Response_Package.Documents.Item(DocumentIndex)
          OddRow = Not OddRow
          If OddRow Then
            .Append("<div>")
          Else
            .Append("<div style='background-color:#F8F8F8'>")
          End If
          .SummaryTablesAppend(Me.SecuredSigning_CurrentStatusDocument(serviceLogs, True, Response_Document, DocumentIndex, ""))
          .Append("</div>")
        Next
      End If
    End With
  Else
    ' DOCUMENT
    ' Get Latest Status
    For Each ServiceLog In serviceLogs
      Select Case TypeName(ServiceLog.ExResponse)
        Case "ISElectronicSignatureResponse_SecuredSigning_DocumentDelete"
          Response_DocumentDelete = DirectCast(ServiceLog.ExResponse, ISElectronicSignatureResponse_SecuredSigning_DocumentDelete)
          DeleteReason = Response_DocumentDelete.Request.Comment
        Case "ISElectronicSignatureResponse_SecuredSigning_DocumentStatus"
          Response_Document = DirectCast(ServiceLog.ExResponse, ISElectronicSignatureResponse_SecuredSigning_DocumentStatus).Document
        Case "ISElectronicSignatureResponse_SecuredSigning_SmartTagSend"
          Response_Document = DirectCast(ServiceLog.ExResponse, ISElectronicSignatureResponse_SecuredSigning_SmartTagSend).Documents(0)
      End Select
    Next

    If Response_Document Is Nothing Then
      ' Should never get here!
    Else
      With HtmlSummaryPage2StringBuilder
        ' Alerts
        .SummaryTablesAppend(Me.SecuredSigning_Alerts(serviceLogs))
        ' Document
        .SummaryTablesAppend(Me.SecuredSigning_CurrentStatusDocument(serviceLogs, False, Response_Document, 0, ""))
      End With 
    End If
  End If

End Sub

Private Function SecuredSigning_Alerts(serviceLogs As ISServiceLogs) As ISSummaryTables
  
  Dim Document As ISElectronicSignatureResponse_SecuredSigning_Document
  Dim DocumentIndex As Integer
  Dim IDVerificationIsRequested As Boolean
  Dim i As Integer
  Dim PackageStatus As String
  Dim RequestUtcDate As Date
  Dim ServiceLog As ISServiceLog
  Dim SummaryTable As ISSummaryTable                                       
  Dim SummaryTables As ISSummaryTables
  Dim Warnings As finWarnings

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()
  Warnings = finBL.CreateWarnings
  IDVerificationIsRequested = False
  
  ' Get the most recent package status (or document status if there is no package)
  ServiceLog = Nothing
  For i = serviceLogs.Count - 1 To 0 Step -1
    Select Case ServiceLogs(i).ExResponse.GetType()
      Case GetType(ISElectronicSignatureResponse_SecuredSigning_DocumentStatus), 
           GetType(ISElectronicSignatureResponse_SecuredSigning_PackageStatus), 
           GetType(ISElectronicSignatureResponse_SecuredSigning_SmartTagSend)
             ServiceLog = ServiceLogs(i)
             Exit For
    End Select
  Next  
  
  ' Document Alerts
  If ServiceLog IsNot Nothing Then
    Select Case ServiceLog.ExResponse.GetType()
      Case GetType(ISElectronicSignatureResponse_SecuredSigning_DocumentStatus)
        With DirectCast(ServiceLog.ExResponse, ISElectronicSignatureResponse_SecuredSigning_DocumentStatus)
          RequestUtcDate = .RequestUtcDate
          PackageStatus = DirectCast(ServiceLog.ExResponse, ISElectronicSignatureResponse_SecuredSigning_DocumentStatus).Document.Status
          If .Document.IDVerificationRequested Then
            IDVerificationIsRequested = True
          End If 
          SecuredSigning_AlertsDocument(Warnings, .Document, 0, "")
        End With
        
      Case GetType(ISElectronicSignatureResponse_SecuredSigning_PackageStatus)
        With DirectCast(ServiceLog.ExResponse, ISElectronicSignatureResponse_SecuredSigning_PackageStatus)
          RequestUtcDate = .RequestUtcDate
          PackageStatus = DirectCast(ServiceLog.ExResponse, ISElectronicSignatureResponse_SecuredSigning_PackageStatus).Package.Status
          For DocumentIndex = 0 To .Package.Documents.Count - 1
            Document = .Package.Documents.Item(DocumentIndex)
            If document.IDVerificationRequested Then
              IDVerificationIsRequested = True
            End If 
            SecuredSigning_AlertsDocument(Warnings, Document, DocumentIndex, PackageStatus)
          Next
        End With
        
      Case GetType(ISElectronicSignatureResponse_SecuredSigning_SmartTagSend)
        With DirectCast(ServiceLog.ExResponse, ISElectronicSignatureResponse_SecuredSigning_SmartTagSend)
          RequestUtcDate = .RequestUtcDate
          If DirectCast(ServiceLog.ExResponse, ISElectronicSignatureResponse_SecuredSigning_SmartTagSend).IsPackage Then
            PackageStatus = DirectCast(ServiceLog.ExResponse, ISElectronicSignatureResponse_SecuredSigning_SmartTagSend).Package.Status
          Else
            PackageStatus = ""
          End If
          For DocumentIndex = 0 To .Documents.Count - 1
            Document = .Documents.Item(DocumentIndex)
            If Document.IDVerificationRequested Then
              IDVerificationIsRequested = True
            End If 
            SecuredSigning_AlertsDocument(Warnings, Document, DocumentIndex, PackageStatus)
          Next
        End With
    End Select
    
    ' ID Verification
    Select Case UCase(PackageStatus)
      Case "CANCELLED", "DELETED"
      Case Else
        If IDVerificationIsRequested Then
          warnings.AddWarning("ID Verification has been requested.",,, isefinWarningLevel.Low)
        End If 
    End Select
  
    ' Check for Delete
    Select Case UCase(PackageStatus)
      Case "DELETED"
        warnings.AddWarning("Package has been deleted.",,, isefinWarningLevel.Critical)
    End Select  
  End If
  
  ' Add Alerts
  If Warnings.Count <> 0 Then
    SummaryTable = SummaryTables.CreateSummaryTableInformation("Alerts", "Alerts", 2)
    SummaryTable.TextAfter = Warnings.GetHtmlTemplateText()
    SummaryTables.Add("Alerts", SummaryTable)
  End If
  
  Return SummaryTables
  
End Function

Private Sub SecuredSigning_AlertsDocument(warnings As finWarnings,
                                          document As ISElectronicSignatureResponse_SecuredSigning_Document,
                                          documentIndex As Integer,
                                          packageStatus As String) 
                                          
  Dim HasIDVerificationFail As Boolean                                          
  Dim HasIDVerificationError As Boolean                                          
  Dim Signer As ISElectronicSignatureResponse_SecuredSigning_Signer                                       

  ' Check for Declines
  If document.Signers.HasDeclinedReason Then
    warnings.AddWarning(String.Format("At least one signer has declined to sign the document, {0}.", document.Name),,, isefinWarningLevel.Critical, "#" & GetShortcutUrl("signers", documentIndex))
  End If  

  ' Check for ID Check opt-out
  If document.Signers.HasIDCheckOptOut Then
    warnings.AddWarning(String.Format("At least one signer has opted out of the ID check for document {0}.", document.Name),,, isefinWarningLevel.Critical, "#" & GetShortcutUrl("signers", documentIndex))
  End If  

  ' Overdue
  If Not document.StatusTerminal AndAlso Document.DueUtcDate <> Nothing AndAlso finBL.TimeZoneFunctions.GetCurrentUtcDateTime > Document.DueUtcDate Then
    warnings.AddWarning(String.Format("Signing for document {0} is overdue.", document.Name),,, isefinWarningLevel.High)
  End If

  ' ID Verification issues
  HasIDVerificationError = False
  If document.IDVerificationRequested And document.StatusComplete Then
    For Each Signer In document.Signers
      If Signer.IDVerificationResult = iseElectronicSignatures_SecuredSigningIDVerificationResult.Failed Then
        HasIDVerificationFail = True
      End If
      If Signer.IDVerificationFaceMatchResult = iseElectronicSignatures_SecuredSigningIDVerificationFaceMatchResult.Failed Then
        HasIDVerificationError = True
      End If
      If Signer.IDVerificationLivenessResult = iseElectronicSignatures_SecuredSigningIDVerificationLivenessResult.Failed Then
        HasIDVerificationError = True
      End If
    Next
  End If
  If HasIDVerificationFail Then
    warnings.AddWarning(String.Format("Document {0} ID Verification has failed for at least one signer.",document.Name),,, isefinWarningLevel.Critical, "#" & GetShortcutUrl("signers", documentIndex))
  ElseIf HasIDVerificationError Then
    warnings.AddWarning(String.Format("Document {0} ID Verification has errors for at least one signer.",document.Name),,, isefinWarningLevel.High, "#" & GetShortcutUrl("signers", documentIndex))
  End If
                                          
End Sub

Private Function GetShortcutUrl(tableName As String,
                                documentIndex As Integer) As String

  Return String.Format("{0}_{1}", tableName, documentIndex)                                                   
                                                   
End Function

Private Function SecuredSigning_CurrentStatusDocument(serviceLogs As ISServiceLogs,
                                                      isPackage As Boolean,
                                                      document As ISElectronicSignatureResponse_SecuredSigning_Document,
                                                      documentIndex As Integer,
                                                      deleteReason As String) As ISSummaryTables

  Dim DocumentLog As ISElectronicSignatureResponse_SecuredSigning_DocumentLog
  Dim FormField As ISElectronicSignatureResponse_SecuredSigning_FormField
  Dim HasDeclinedReason As Boolean
  Dim HasIDCheck As Boolean
  Dim Response_DocumentGetFieldData As ISElectronicSignatureResponse_SecuredSigning_DocumentGetFieldData
  Dim ServiceLog As ISServiceLog
  Dim ServiceLog_DownloadGetDocumentData As ISServiceLog
  Dim ServiceLog_DownloadIDVerification As ISServiceLog
  Dim ShowSendReminder As Boolean
  Dim Signer As ISElectronicSignatureResponse_SecuredSigning_Signer
  Dim SignerIndex As Integer
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  ' Document
  If isPackage Then
    SummaryTable = summaryTables.CreateSummaryTableInformation(Document.Name, "", 2,,, TestMode)
  Else
    SummaryTable = summaryTables.CreateSummaryTableInformation("Current Document Status", "", 2,,, TestMode)
  End If
  With SummaryTable
    .AddRowCaptionText("Folder:", Document.FolderText, True)
    If Document.StatusTerminal Then
      If Document.StatusComplete Then
        .AddRowCaptionWiki("Status:", String.Format("**++{0} (Closed)++**", Document.Status), True, iseSummaryTableCellClass.Highlight2)
      Else
        .AddRowCaptionWiki("Status:", String.Format("**!!{0} (Closed)!!**", Document.Status), True, iseSummaryTableCellClass.Highlight2)
      End If
      .AddRowCaptionText("Reason:", deleteReason, False)
      If Document.DueUtcDate <> Nothing Then
        .AddRowCaptionWiki("Due Date:", String.Format("**{0}**", finBL.FormatDateTimeLong(Document.DueDate)))
      End If
    Else
      .AddRowCaptionText("Status:", Document.Status, True)
      If Document.DueUtcDate = Nothing Then
        ' No expiry
      ElseIf finBL.TimeZoneFunctions.GetCurrentUtcDateTime > Document.DueUtcDate Then
        ' Expired
        .AddRowCaptionWiki("Due Date:", String.Format("**!!Expired on {0}!!**", finBL.FormatDateTimeLong(Document.DueDate)))
      Else
        .AddRowCaptionWiki("Due Date:", String.Format("**{0}**", finBL.FormatDateTimeLong(Document.DueDate)))
      End If
    End If
    If Document.LastSignedUtcDate <> Nothing Then
      .AddRowCaptionWiki("Last Signed:", String.Format("**{0}**", finBL.FormatDateTimeLong(Document.LastSignedDate)))
    End If

    ' Find Downloaded Document
    For Each ServiceLog In serviceLogs
      Select Case TypeName(ServiceLog.ExResponse)
        Case "ISElectronicSignatureResponse_SecuredSigning_DownloadGetDocumentData"
          If DirectCast(ServiceLog.ExResponse, ISElectronicSignatureResponse_SecuredSigning_DownloadGetDocumentData).Request.DocumentReference = Document.Reference Then
            ServiceLog_DownloadGetDocumentData = ServiceLog
          End If
        Case "ISElectronicSignatureResponse_SecuredSigning_DownloadIDVerification"
          If DirectCast(ServiceLog.ExResponse, ISElectronicSignatureResponse_SecuredSigning_DownloadIDVerification).Request.DocumentReference = Document.Reference Then
            ServiceLog_DownloadIDVerification = ServiceLog
          End If
      End Select
    Next
    
    If ServiceLog_DownloadGetDocumentData Is Nothing Then
      ' Add Action to Get Document
      If Document.StatusComplete Then
        .Actions.AddApplicationShortcutUrl("GetDocument", "Get Document", String.Format("app://global?type=ElectronicSignature.GetDocuments&serviceLogPk={0}&DocumentReference={1}", serviceLogs(0).Pk, finBL.Runtime.HtmlUtilities.UrlEncode(Document.Reference)), True).ShowInWebInterfaces = True
      End If
    Else
     ' Add Action to View Document
     .Actions.AddApplicationShortcutUrl("OpenDocument", "View Document", String.Format("app://global?type=ElectronicSignature.OpenDocument&serviceLogPk={0}", ServiceLog_DownloadGetDocumentData.Pk), True).ShowInWebInterfaces = True
    End If

    If Document.IDVerificationRequested Then
      If ServiceLog_DownloadIDVerification IsNot Nothing Then 
        ' Add Action to View ID Verification
        .Actions.AddApplicationShortcutUrl("OpenIDVerification", "View ID Verification", String.Format("app://global?type=ElectronicSignature.OpenIDVerification&serviceLogPk={0}", ServiceLog_DownloadIDVerification.Pk), True).ShowInWebInterfaces = True
      ElseIf Document.Status = "Complete"
        ' Add Action to Get ID Verification
        .Actions.AddApplicationShortcutUrl("GetIDVerification", "Get ID Verification", String.Format("app://global?type=ElectronicSignature.GetIDVerification&serviceLogPk={0}&DocumentReference={1}", serviceLogs(0).Pk, finBL.Runtime.HtmlUtilities.UrlEncode(Document.Reference)), True).ShowInWebInterfaces = True
      End If
    End If
  End With
  summaryTables.Add(String.Format("Document.{0}", Document.Reference), SummaryTable)

  ' Signers
  SummaryTable = summaryTables.CreateSummaryTableTabular("Signers", GetShortcutUrl("signers", documentIndex), 3, TestMode)
  With SummaryTable
    ' Cache Settings
    HasIDCheck = Not HasDeclinedReason AndAlso Document.Signers.HasIDCheck 
    HasDeclinedReason = Document.Signers.HasDeclinedReason
    
    If Document.DueUtcDate <> Nothing AndAlso finBL.TimeZoneFunctions.GetCurrentUtcDateTime > Document.DueUtcDate Then
      ShowSendReminder = False
    ElseIf serviceLogs(0).ResponseStatus <> iseServiceLogResponseStatus.InProgress Then
      ShowSendReminder = False
    Else
      ShowSendReminder = True
    End If

    ' Define Columns
    With .Columns
      .AddText("Signed")
      .AddText("Name")
      .AddText("Email")
      If HasIDCheck Then .AddText("ID Check Status")
      If HasDeclinedReason Then .AddText("Declined Reason")
      If Document.IDVerificationRequested Then 
        .AddText("ID Verification Status")
        .AddText("ID Verification Result")
        .AddText("FaceMatch Result")
        .AddText("Liveness Result")
      End If
      If ShowSendReminder Then .AddText("Send Reminder")
    End With

    ' Add Rows
    For SignerIndex = 0 To Document.Signers.Count - 1
      Signer = Document.Signers(SignerIndex)

      With .Rows.Add().Cells
        If len(Signer.DeclinedReason) <> 0 Then
          .AddWiki("{{icon|outcome_failed}}")
        Else If Signer.HasSigned Then
          .AddWiki("{{icon|Outcome_Success}}")
        Else
          .AddText("")
        End If
        .AddText(Signer.FirstName & " " & Signer.LastName)
        .AddText(Signer.Email)
        If HasIDCheck Then 
          Select Case ucase(Signer.IDCheckStatus)
            Case ""
              .AddText("")
            Case "SUCCESS"
              .AddWiki("{{icon|outcome_success}} Success")
            Case "THIS ID CHECK HAS NOT BEEN DONE YET", "INCOMPLETE"
              .AddText(Signer.IDCheckStatus)
            Case "THIS ID CHECK HAS BEEN OPTED OUT", "THIS ID CHECK HAS BEEN CANCELLED BY THE DOCUMENT OWNER"
              .AddWiki("!!**" & Signer.IDCheckStatus & "**!!")
            Case Else
              .AddWiki("!!**" & Signer.IDCheckStatus & "**!!")
          End Select
        End If  
        If HasDeclinedReason Then .AddText(Signer.DeclinedReason)
        If Document.IDVerificationRequested Then 
          .AddText(Signer.IDVerificationStatus)
          Select Case Signer.IDVerificationResult
            Case iseElectronicSignatures_SecuredSigningIDVerificationResult.Passed
              .AddWiki( "{{icon|Outcome_Success}} " & Signer.IDVerificationResultText)
            Case iseElectronicSignatures_SecuredSigningIDVerificationResult.Failed
              .AddWiki( "{{icon|Outcome_Failed}} " & Signer.IDVerificationResultText)
            Case Else
              .AddWiki( Signer.IDVerificationResultText)
          End Select
          Select Case Signer.IDVerificationFaceMatchResult
            Case iseElectronicSignatures_SecuredSigningIDVerificationFaceMatchResult.Passed
              .AddWiki( "{{icon|Outcome_Success}} " & Signer.IDVerificationFaceMatchResultText)
            Case iseElectronicSignatures_SecuredSigningIDVerificationFaceMatchResult.Failed
              .AddWiki( "{{icon|Outcome_Failed}} " & Signer.IDVerificationFaceMatchResultText)
            Case Else
              .AddWiki( Signer.IDVerificationFaceMatchResultText)
          End Select
          Select Case Signer.IDVerificationLivenessResult
            Case iseElectronicSignatures_SecuredSigningIDVerificationLivenessResult.Passed
              .AddWiki( "{{icon|Outcome_Success}} " & Signer.IDVerificationLivenessResultText)
            Case iseElectronicSignatures_SecuredSigningIDVerificationLivenessResult.Failed
              .AddWiki( "{{icon|Outcome_Failed}} " & Signer.IDVerificationLivenessResultText)
            Case Else
              .AddWiki( Signer.IDVerificationLivenessResultText)
          End Select
        End If
        If ShowSendReminder Then
          If Signer.HasSigned Then
            .AddText("")
          Else
            .AddText(String.Format("{{{{action caption='Send Reminder' hyperlink='app://global?type=ElectronicSignature.SendReminder&serviceLogPk={0}&DocumentReference={1}&SignerIndex={2}'}}}}", serviceLogs(0).Pk, document.Reference, SignerIndex))
          End If
         End If
      End With
    Next
  End With
  SummaryTables.Add("signers", SummaryTable)

  ' Log
  If Document.Logs.Count <> 0 Then
    SummaryTable = SummaryTables.CreateSummaryTableTabular("Log", "", 3, TestMode)
    With SummaryTable
      ' Define Columns
      With .Columns
        .AddDateTime("Date")
        .AddText("Name")
        .AddText("Role")
        .AddText("Action")
      End With

      ' Add Rows
      For Each DocumentLog In Document.Logs
        With .Rows.Add().Cells
          .AddDateTime(DocumentLog.LogDate, True, True)
          .AddText(DocumentLog.Name)
          .AddText(DocumentLog.Role)
          .AddText(DocumentLog.Action)
        End With
      Next
    End With
    SummaryTables.Add(String.Format("Document.{0}.Logs", Document.Reference), SummaryTable)
  End If

  ' Document Field Data
  If ShowDocumentFieldData AndAlso Document.StatusComplete Then
    ' Find Document Field Data
    For Each ServiceLog In serviceLogs
      Select Case TypeName(ServiceLog.ExResponse)
        Case "ISElectronicSignatureResponse_SecuredSigning_DocumentGetFieldData"
          If DirectCast(ServiceLog.ExResponse, ISElectronicSignatureResponse_SecuredSigning_DocumentGetFieldData).Request.DocumentReference = Document.Reference Then
            Response_DocumentGetFieldData = DirectCast(ServiceLog.ExResponse, ISElectronicSignatureResponse_SecuredSigning_DocumentGetFieldData)
          End If
      End Select
    Next

    If Response_DocumentGetFieldData Is Nothing Then
      ' Add Action to get Document Field Data
      With SummaryTables.AddSummaryTableBlank(String.Format("Document.{0}.FieldData", Document.Reference), "Document Field Data", "",, 3)
        .Actions.AddApplicationShortcutUrl("Get", "Get Field Data", String.Format("app://global?type=ElectronicSignature.GetDocumentData&serviceLogPk={0}&DocumentReference={1}", serviceLogs(0).Pk, finBL.Runtime.HtmlUtilities.UrlEncode(Document.Reference)), True).ShowInWebInterfaces = True
      End With
    ElseIf Response_DocumentGetFieldData.FormFields.Count = 0 Then
      SummaryTables.AddSummaryTableBlank(String.Format("Document.{0}.FieldData", Document.Reference), "Document Field Data", "No Document fields found.",, 3)
    Else
      SummaryTable = SummaryTables.CreateSummaryTableTabular("Document Field Data", "", 3, TestMode)
      With SummaryTable
        ' Define Columns
        With .Columns
          .AddText("Field")
          .AddText("Label")
          .AddText("Type")
          .AddText("Value")
          .AddText("Reference")
        End With

        ' Add Rows
        For Each FormField In Response_DocumentGetFieldData.FormFields
          With .Rows.Add().Cells
            .AddText(FormField.ClientField)
            .AddText(FormField.Label)
            .AddText(FormField.FieldType)
            .AddText(FormField.Value)
            .AddText(FormField.Reference)
          End With
        Next
      End With
      SummaryTables.Add(String.Format("Document.{0}.FieldData", Document.Reference), SummaryTable)
    End If
  End If

  Return SummaryTables

End Function

Private Sub SecuredSigning_OriginalDetails(htmlSummaryPage2StringBuilder As finHtmlSummaryPage2StringBuilder,
                                           smartTagSend As ISElectronicSignatureResponse_SecuredSigning_SmartTagSend)

  Dim Document As ISElectronicSignatureResponse_SecuredSigning_Document
  Dim OddRow As Boolean

  With HtmlSummaryPage2StringBuilder
    If smartTagSend.Documents.Count = 0 Then
      ' Should never get here!
    Else
      If smartTagSend.IsPackage Then
        OddRow = False
        For Each Document In smartTagSend.Documents
          OddRow = Not OddRow
          If OddRow Then
            .Append("<div>")
          Else
            .Append("<div style='background-color:#F8F8F8'>")
          End If
          .SummaryTablesAppend(Me.SecuredSigning_OriginalDetailsDocument(Document))
          .Append("</div>")
        Next
      Else
        .SummaryTablesAppend(Me.SecuredSigning_OriginalDetailsDocument(smartTagSend.Documents(0)))
      End If
    End If
  End With

End Sub

Private Function SecuredSigning_OriginalDetailsDocument(document As ISElectronicSignatureResponse_SecuredSigning_Document) As ISSummaryTables

  Dim HasMobileNumber As Boolean
  Dim Signer As ISElectronicSignatureResponse_SecuredSigning_Signer
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  ' Document
  SummaryTable = SummaryTables.CreateSummaryTableInformation(Document.Name, "", 3,,, TestMode)
  With SummaryTable
    If Document.DueUtcDate <> Nothing Then .AddRowCaptionDateTime("Due Date:", Document.DueDate)
    .AddRowCaptionText("Form Direct Reference:", Document.FormDirectReference, False)
  End With
  SummaryTables.Add(String.Format("Document.{0}", Document.Reference), SummaryTable)

  ' Signers
  If Document.Signers.Count <> 0 Then
    SummaryTable = SummaryTables.CreateSummaryTableTabular("Signers", "Signers", 4, TestMode)
    With SummaryTable
      ' Cache Settings
      HasMobileNumber = Document.Signers.HasMobileNumber

      ' Define Columns
      With .Columns
        .AddText("First Name")
        .AddText("Last Name")
        .AddText("Email")
        If HasMobileNumber Then .AddText("Mobile")
      End With

      ' Add Rows
      For Each Signer In Document.Signers
        With .Rows.Add().Cells
          .AddText(Signer.FirstName)
          .AddText(Signer.LastName)
          .AddText(Signer.Email)
          If HasMobileNumber Then .AddText(Signer.MobileCountry & " " & Signer.MobileNumber)
        End With
      Next
    End With
    SummaryTables.Add(String.Format("Document.{0}.Signers", Document.Reference), SummaryTable)
  End If

  Return SummaryTables

End Function

Private Function SecuredSigning_History(serviceLogs As ISServiceLogs) As ISSummaryTables

  Dim ServiceLog As ISServiceLog
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  SummaryTable = SummaryTables.CreateSummaryTableTabular("History", "", 2, TestMode)
  With SummaryTable
    ' Define Columns
    With .Columns
      .AddText("Service Log")
      .AddDateTime("Date")
      .AddText("User")
      .AddText("Type")
      .AddText("Status")
    End With

    ' Add Rows
    For Each ServiceLog In serviceLogs
      With .Rows.Add().Cells
        With .AddText(CStr(serviceLog.Pk))
          .HyperlinkSetApplicationShortcutUrl(String.Format("FormShow?form=ServiceLog&id={0}", ServiceLog.Pk))
        End With
        .AddDateTime(ServiceLog.CreatedDate, True, True)
        .AddText(finBL.Users.GetRecordCodeDescription(ServiceLog.CreatedUserPk, ""))
        .AddText(finBL.Runtime.TextUtilities.SplitWordsAtCapitals(ServiceLog.ProductId))
        .AddText(ServiceLog.RequestStatusText)
      End With
    Next
  End With
  SummaryTables.Add("History", SummaryTable)

  Return SummaryTables

End Function

