' SummaryPage2_CreditEnquiryReport_Aply
Option Explicit On
Option Strict On

' #################################################################
' Aply Credit Enquiry Report Summary Page Script
'
' Version: 1.16 (05/09/2024)
'
' Usage: Credit Enquiry and Log forms
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.03  23/04/2021  ISS
'    1.04  28/07/2022  ISS      J029086   Added Device, Map, Biometrics
'    1.05  29/08/2022  ISS      J029253   Add Reference and External Id
'    1.06  26/08/2022  ISS      J029116   Support for Webhook callback authentication
'    1.07  19/09/2022  ISS      J029620   Modernise code
'    1.08  22/09/2022  ISS      J029595   Support for Update report function
'    1.09  12/10/2022  ISS      J029668   Added Verification face images 
'    1.10  04/11/2022  ISS      J029880   Added AU Drivers Licence Card Number
'    1.11  30/05/2023  ISS      J031147   Removed reference to obsoleted property
'    1.12  12/07/2023  ISS      J031474   Added StartProcessUrl
'    1.13  15/08/2023  ISS      J031584   Added Manual Verify
'    1.14  28/08/2023  ISS      J031834   Fixed Save Document function
'    1.15  12/03/2024  ISS      J032933   Changed Google Map to static version
'    1.16  05/09/2024  ISS      J034203   Added option for Fraud Analytics to Verify product
' #################################################################

'#Const "OutOfDateWarningDays",Integer,30,"Number of days before warning the Enquiry is out-of-date."
'#Const "ShowPortalUrl",Boolean,True,"Show link to Aply portal to review Verifications."

' Constants
Private OutOfDateWarningDays As Integer = 30
Private ShowPortalUrl As Boolean = True

' Special Constants
Const TestMode As Boolean = False

' Properties
Private AccountAppApplicant As finAccountAppApplicant
Private AccountAppLog As finAccountAppLog
Private Client As finClient
Private ClientLog As finClientLog

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 Response As ISCreditEnquiryResponse
  Dim ServiceLog As ISServiceLog
  Dim ServiceLogs As ISServiceLogs

  ' Assume Success
  Main = True

  ' Get Constants
  With ScriptInfo.Constants
    OutOfDateWarningDays = .GetInteger("OutOfDateWarningDays", OutOfDateWarningDays)
    ShowPortalUrl = .GetBoolean("ShowPortalUrl", ShowPortalUrl)
  End With

  ' Get Service Logs
  Try
    Main = finBL.CreditBureau.GetCreditEnquiryServiceLogs(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 a Credit Enquiry.")
    ElseIf ServiceLogs(0).RequestStatus <> iseAuditLogStatus.Success Then
      Main = False
      finBL.Error.ErrorBegin("Invalid Service Log. Initial Request was not successful.")
    Else
      ServiceLog = ServiceLogs(0)
      Response = DirectCast(ServiceLogs(0).ExResponse, ISCreditEnquiryResponse)
    End If
  End If

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

End Function

Private Function CreatePage(serviceLogs As ISServiceLogs,
                            serviceLog As ISServiceLog,
                            response As ISCreditEnquiryResponse,
                            ByRef html As String) As Boolean

  Dim HtmlSummaryPage2StringBuilder As finHtmlSummaryPage2StringBuilder
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise ByRef
  html = ""

  ' Initialise
  HtmlSummaryPage2StringBuilder = finBL.CreateHtmlSummaryPage2StringBuilder()

  ' Initialise HTML
  With HtmlSummaryPage2StringBuilder
    ' Display test watermark
    If serviceLog.TestMode Then .Watermark = "Test Mode"

    ' Note: Embed images (and also CSS) since we want to be able to easily produce a PDF document
    .Initialise(ScriptInfo, False, True)

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

    ' Theme
    .HtmlHeaderInsertServiceReportTheme("#04A5C0", "#D0D0D0", "", "#F2F2F2")

    ' Intersoft PDF Options (including style tweaks)
    .HtmlHeaderInsertPdfGenerationHints("A4", "Portrait", 880, "1.5cm", "1.5cm", "1cm", "1cm", "font-size:0.9em", "print")
    
    ' Finalise HTML Header
    .HtmlHeaderEnd()
  End With

  Select Case response.GetType()
    Case GetType(ISCreditEnquiryResponse_Aply_ManualVerify)
      Me.CreatePage_Aply_ManualVerify(serviceLogs, DirectCast(response, ISCreditEnquiryResponse_Aply_ManualVerify), HtmlSummaryPage2StringBuilder)

    Case GetType(ISCreditEnquiryResponse_Aply_Verify)
      Me.CreatePage_Aply_Verify(serviceLogs, DirectCast(response, ISCreditEnquiryResponse_Aply_Verify), HtmlSummaryPage2StringBuilder)
      
    Case Else
      Success = False
      finBL.Error.ErrorBeginFormat("Unexpected Response Type '{0}'.", TypeName(response))
  End Select

  ' Disclaimer
  HtmlSummaryPage2StringBuilder.AppendLine("<hr>")
  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.EnquiryDate, True, True, True) &"}}")

  ' Finalise HTML
  HtmlSummaryPage2StringBuilder.HtmlFinalise()

  ' Resolve Templates
  html = HtmlSummaryPage2StringBuilder.ToString(True)

  Return Success

End Function

' ===== Manual Verify =====
Private Sub CreatePage_Aply_ManualVerify(serviceLogs As ISServiceLogs,
                                         response_ManualVerify As ISCreditEnquiryResponse_Aply_ManualVerify,
                                         sb As finHtmlSummaryPage2StringBuilder)

  Dim AccountApp As finAccountApp
  
  ' From Client based upon Request
  If Len(response_ManualVerify.Request.ClientId) <> 0 Then
    Client = finBL.CreateClient()
    If Client.Load(response_ManualVerify.Request.ClientId) Then
      If Client.IsNew Then Client = Nothing
    Else
      Client = Nothing
    End If
  End If

  ' From Client (or Applicant) based upon Source
  Select Case serviceLogs(0).SourceType
    Case "AccountAppLog"
      If Client Is Nothing Then
        AccountAppLog = finBL.CreateAccountAppLog()
        If AccountAppLog.Load(serviceLogs(0).SourcePk) Then
          AccountApp = finBL.CreateAccountApp()
          If AccountApp.LoadPk(AccountAppLog.AccountAppPk) Then
            If Not AccountApp.IsNew Then
              AccountAppApplicant = AccountApp.Applicants.ItemByPk(AccountAppLog.AccountAppApplicantPk)
            End If
          End If
        End If
      End If
      
    Case "Client"
      If Client Is Nothing Then
        Client = finBL.CreateClient()
        If Client.LoadPk(serviceLogs(0).SourcePk) Then
          If Client.IsNew Then Client = Nothing
        Else
          Client = Nothing
        End If
      End If
      
    Case "ClientLog"
      ClientLog = finBL.CreateClientLog
      If ClientLog.Load(serviceLogs(0).SourcePk) Then
        If Client Is Nothing Then
          Client = finBL.CreateClient()
          If Client.LoadPk(ClientLog.ClientPk) Then
            If Client.IsNew Then Client = Nothing
          Else
            Client = Nothing
          End If
        ElseIf Client.Pk <> ClientLog.ClientPk Then
          ClientLog = Nothing
        End If  
      End If
  End Select
  
  
  With sb
    ' Heading
    .AppendH1(response_ManualVerify.Request.Name)

    .AppendH2(String.Format("{0} - {1}", serviceLogs(0).ProductId, response_ManualVerify.ServiceName))

    .SummaryTablesAppend(Me.Aply_ManualVerify_EnquiryDetails(serviceLogs, response_ManualVerify))
    .SummaryTablesAppend(Me.Aply_ManualVerify_Result(serviceLogs, response_ManualVerify))
  End With

  If TestMode Then 
    sb.SummaryTablesAppend(Me.Aply_History(serviceLogs))
  End If

End Sub

' ===== Verify =====
Private Sub CreatePage_Aply_Verify(serviceLogs As ISServiceLogs,
                                   response_Verify As ISCreditEnquiryResponse_Aply_Verify,
                                   sb As finHtmlSummaryPage2StringBuilder)

  Dim AccountApp As finAccountApp
  Dim Response_VerifyResult As ISCreditEnquiryResponse_Aply_VerifyResult
  Dim Response_Verification As ISCreditEnquiryResponse_Aply_Verification
  Dim ServiceLog As ISServiceLog

  ' Find Responses
  For Each ServiceLog In serviceLogs
    If ServiceLog.RequestStatus = iseAuditLogStatus.Success Then
      Select Case ServiceLog.ExResponse.GetType()
        Case GetType(ISCreditEnquiryResponse_Aply_VerifyDownloadJson)
          Select Case DirectCast(ServiceLog.ExResponse,ISCreditEnquiryResponse_Aply_VerifyDownloadJson).Verification.Status
            Case  iseCreditBureau_Aply_VerificationStatus.Incomplete
            Case Else  
              Response_Verification = DirectCast(ServiceLog.ExResponse,ISCreditEnquiryResponse_Aply_VerifyDownloadJson).Verification
          End Select
          
        Case GetType(ISCreditEnquiryResponse_Aply_VerifyResult)
          Response_VerifyResult = DirectCast(ServiceLog.ExResponse, ISCreditEnquiryResponse_Aply_VerifyResult)

          Select Case Response_VerifyResult.Event
            Case iseCreditBureau_Aply_Event.Completed, iseCreditBureau_Aply_Event.Updated
              Response_Verification = DirectCast(ServiceLog.ExResponse,ISCreditEnquiryResponse_Aply_VerifyResult).Verification
          End Select
      End Select
    End If
  Next

  ' From Client based upon Request
  If Len(response_Verify.Request.ClientId) <> 0 Then
    Client = finBL.CreateClient()
    If Client.Load(response_Verify.Request.ClientId) Then
      If Client.IsNew Then Client = Nothing
    Else
      Client = Nothing
    End If
  End If

  ' From Client (or Applicant) based upon Source
  Select Case serviceLogs(0).SourceType
    Case "AccountAppLog"
      If Client Is Nothing Then
        AccountAppLog = finBL.CreateAccountAppLog()
        If AccountAppLog.Load(serviceLogs(0).SourcePk) Then
          AccountApp = finBL.CreateAccountApp()
          If AccountApp.LoadPk(AccountAppLog.AccountAppPk) Then
            If Not AccountApp.IsNew Then
              AccountAppApplicant = AccountApp.Applicants.ItemByPk(AccountAppLog.AccountAppApplicantPk)
            End If
          End If
        End If
      End If
      
    Case "Client"
      If Client Is Nothing Then
        Client = finBL.CreateClient()
        If Client.LoadPk(serviceLogs(0).SourcePk) Then
          If Client.IsNew Then Client = Nothing
        Else
          Client = Nothing
        End If
      End If
      
    Case "ClientLog"
      ClientLog = finBL.CreateClientLog
      If ClientLog.Load(serviceLogs(0).SourcePk) Then
        If Client Is Nothing Then
          Client = finBL.CreateClient()
          If Client.LoadPk(ClientLog.ClientPk) Then
            If Client.IsNew Then Client = Nothing
          Else
            Client = Nothing
          End If
        ElseIf Client.Pk <> ClientLog.ClientPk Then
          ClientLog = Nothing
        End If  
      End If
  End Select

  With sb
    ' Heading
    If Len(response_Verify.Request.Name) = 0 Then
      .AppendH1(response_Verify.Request.ContactPhone)
    Else
      .AppendH1(response_Verify.Request.Name)
    End If
    .AppendH2(String.Format("{0} - {1}", serviceLogs(0).ProductId, response_Verify.ServiceName))

    .SummaryTablesAppend(Me.Aply_Verify_EnquiryDetails(serviceLogs, response_Verify))
    If Response_Verification IsNot Nothing Then 
      .SummaryTablesAppend(Me.Aply_Verify_Outcome(serviceLogs, Response_Verification))
      .SummaryTablesAppend(Me.Aply_Verify_Alerts(serviceLogs, response_Verify, Response_Verification))
      .SummaryTablesAppend(Me.Aply_Verify_Verification_PersonalData(serviceLogs, response_Verify, response_Verification))
      .SummaryTablesAppend(Me.Aply_Verify_Verification_IdDocument(serviceLogs, response_Verification))
      .SummaryTablesAppend(Me.Aply_Verify_Verification_Result(response_Verification))
      .SummaryTablesAppend(Me.Aply_Verify_Device(Response_Verification.Device))
      .SummaryTablesAppend(Me.Aply_Biometrics(Response_Verification.Biometrics))
      .SummaryTablesAppend(Me.Aply_FraudAnalytics(Response_Verification.FraudAnalytics))
    End If
  End With

  If Response_Verification Is Nothing OrElse TestMode Then 
    sb.SummaryTablesAppend(Me.Aply_History(serviceLogs))
  End If

End Sub

Private Sub AddCellSuccessFail(cells As ISSummaryTableCells,
                               value As iseCreditBureau_Aply_FraudAnalyticsRisk,
                               valueRaw As String)

  Select Case value
    Case iseCreditBureau_Aply_FraudAnalyticsRisk.High
      cells.AddWiki("{{icon|Outcome_Failed}} High")
    Case iseCreditBureau_Aply_FraudAnalyticsRisk.Low
      cells.AddWiki("{{icon|Outcome_Success}} Low")
    Case iseCreditBureau_Aply_FraudAnalyticsRisk.Medium
      cells.AddWiki("{{icon|Outcome_Invalid}} Medium")
    Case iseCreditBureau_Aply_FraudAnalyticsRisk.Neutral
      cells.AddWiki("{{icon|Outcome_Neutral}} Neutral")
    Case iseCreditBureau_Aply_FraudAnalyticsRisk.Undefined
      cells.AddText(valueRaw)  
  End Select

End Sub

Private Sub AddRowCaptionInteger(summaryTable As ISSummaryTable,
                                 caption As String,
                                 value As Integer?)

  If value.HasValue Then
    summaryTable.AddRowCaptionText(caption, value.Value.ToString())
  Else
    summaryTable.AddRowCaptionText(caption, "Unknown")
  End If

End Sub

Private Sub AddRowCaptionSuccessFail(summaryTable As ISSummaryTable,
                                     caption As String,
                                     value As Boolean,
                                     Optional hasData As Boolean = True)

  If hasData Then
    If value Then
      summaryTable.AddRowCaptionText(caption,"{{icon|Outcome_Success}}")
    Else
      summaryTable.AddRowCaptionText(caption, "{{icon|Outcome_Failed}}")
    End If
  Else
    summaryTable.AddRowCaptionText(caption, "{{icon|Outcome_Unknown}} Unknown")
  End If

End Sub

Private Sub AddRowCaptionSuccessFail(summaryTable As ISSummaryTable,
                                     caption As String,
                                     value As iseCreditBureau_Aply_FaceMatchResult)

  Select Case value
    Case iseCreditBureau_Aply_FaceMatchResult.Pass
      summaryTable.AddRowCaptionText(caption, "{{icon|Outcome_Success}} Pass")
    Case iseCreditBureau_Aply_FaceMatchResult.Fail
      summaryTable.AddRowCaptionText(caption, "{{icon|Outcome_Failed}} Fail")
    Case iseCreditBureau_Aply_FaceMatchResult.Undefined
      summaryTable.AddRowCaptionText(caption, "{{icon|Outcome_Unknown}} Unknown")
  End Select

End Sub

Private Sub AddRowCaptionSuccessFail(summaryTable As ISSummaryTable,
                                     caption As String,
                                     value As iseCreditBureau_Aply_LivenessGesturesResult)

  Select Case value
    Case iseCreditBureau_Aply_LivenessGesturesResult.Pass
      summaryTable.AddRowCaptionText(caption, "{{icon|Outcome_Success}} Pass")
    Case iseCreditBureau_Aply_LivenessGesturesResult.Fail
      summaryTable.AddRowCaptionText(caption, "{{icon|Outcome_Failed}} Fail")
    Case iseCreditBureau_Aply_LivenessGesturesResult.Undefined
      summaryTable.AddRowCaptionText(caption, "{{icon|Outcome_Unknown}} Unknown")
  End Select

End Sub

Private Sub AddRowCaptionSuccessFail(summaryTable As ISSummaryTable,
                                     caption As String,
                                     value As iseCreditBureau_Aply_LivenessSpoofingResult)

  Select Case value
    Case iseCreditBureau_Aply_LivenessSpoofingResult.LowRisk
      summaryTable.AddRowCaptionText(caption, "{{icon|Outcome_Success}} Low Risk")
    Case iseCreditBureau_Aply_LivenessSpoofingResult.HighRisk
      summaryTable.AddRowCaptionText(caption, "{{icon|Outcome_Failed}} High Risk")
    Case iseCreditBureau_Aply_LivenessSpoofingResult.NotApplicable
      summaryTable.AddRowCaptionText(caption, "{{icon|Outcome_Unknown}} Not Applicable")
    Case iseCreditBureau_Aply_LivenessSpoofingResult.Undefined
      summaryTable.AddRowCaptionText(caption, "{{icon|Outcome_Unknown}} Unknown")
  End Select

End Sub

Private Sub AddRowCaptionSuccessFail(summaryTable As ISSummaryTable,
                                     caption As String,
                                     value As Boolean?,
                                     Optional hasData As Boolean = True)

  If hasData AndAlso value.HasValue Then
    If value Then
      summaryTable.AddRowCaptionText(caption,"{{icon|Outcome_Success}} Pass")
    Else
      summaryTable.AddRowCaptionText(caption, "{{icon|Outcome_Failed}} Fail")
    End If
  Else
    summaryTable.AddRowCaptionText(caption, "{{icon|Outcome_Unknown}} Unknown")
  End If

End Sub

Private Function Aply_Biometrics(responseBiometrics As ISCreditEnquiryResponse_Aply_VerificationBiometrics) As ISSummaryTables

  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Create Objects
  SummaryTables = finBL.CreateSummaryTables()

  ' Biometrics Table
  SummaryTable = SummaryTables.CreateSummaryTableInformation("Biometrics", "Biometrics", 2, , , TestMode)
  SummaryTable.Columns(1).WidthChars = 20
  Me.AddRowCaptionSuccessFail(SummaryTable, "Overall", responseBiometrics.Overall)
  SummaryTables.Add("Biometrics", SummaryTable)

  ' Facematch Table
  If responseBiometrics.Details.FaceMatch.HasData Then
    SummaryTable = SummaryTables.CreateSummaryTableInformation("Facematch", "BiometricsFacematch", 3, , , TestMode)
    SummaryTable.Columns(1).WidthChars = 20
    Me.AddRowCaptionSuccessFail(SummaryTable, "Overall:", responseBiometrics.Details.FaceMatch.Overall)
    Me.AddRowCaptionSuccessFail(SummaryTable, "Left Eye:", responseBiometrics.Details.FaceMatch.LeftEye)
    Me.AddRowCaptionSuccessFail(SummaryTable, "Right Eye:", responseBiometrics.Details.FaceMatch.RightEye)
    Me.AddRowCaptionSuccessFail(SummaryTable, "Left Brow:", responseBiometrics.Details.FaceMatch.LeftBrow)
    Me.AddRowCaptionSuccessFail(SummaryTable, "Right Brow:", responseBiometrics.Details.FaceMatch.RightBrow)
    Me.AddRowCaptionSuccessFail(SummaryTable, "Forehead:", responseBiometrics.Details.FaceMatch.Forehead)
    Me.AddRowCaptionSuccessFail(SummaryTable, "Middle Forehead:", responseBiometrics.Details.FaceMatch.MiddleForehead)
    Me.AddRowCaptionSuccessFail(SummaryTable, "Nose:", responseBiometrics.Details.FaceMatch.Nose)
    Me.AddRowCaptionSuccessFail(SummaryTable, "Philtrum:", responseBiometrics.Details.FaceMatch.Philtrum)
    Me.AddRowCaptionSuccessFail(SummaryTable, "Mouth:", responseBiometrics.Details.FaceMatch.Mouth)
    Me.AddRowCaptionSuccessFail(SummaryTable, "Jaw:", responseBiometrics.Details.FaceMatch.Jaw)
    Me.AddRowCaptionSuccessFail(SummaryTable, "Left Cheek:", responseBiometrics.Details.FaceMatch.LeftCheek)
    Me.AddRowCaptionSuccessFail(SummaryTable, "Right Cheek:", responseBiometrics.Details.FaceMatch.RightCheek)
    SummaryTables.Add("BiometricsFacematch", SummaryTable)
  End If

  ' Liveness Table
  If responseBiometrics.Details.Liveness.HasData Then
    SummaryTable = SummaryTables.CreateSummaryTableInformation("Liveness", "Liveness", 3, , , TestMode)
    SummaryTable.Columns(1).WidthChars = 20
    Me.AddRowCaptionSuccessFail(SummaryTable,"Overall:", responseBiometrics.Details.Liveness.Overall)
    Me.AddRowCaptionSuccessFail(SummaryTable,"Gestures:", responseBiometrics.Details.Liveness.Gestures)
    Me.AddRowCaptionSuccessFail(SummaryTable,"Spoofing:", responseBiometrics.Details.Liveness.Spoofing)
    Me.AddRowCaptionInteger(SummaryTable, "Attempt Count:", responseBiometrics.Details.Liveness.AttemptCount)
    SummaryTables.Add("BiometricsLiveness", SummaryTable)
  End If

  Return SummaryTables

End Function

Private Function Aply_FraudAnalytics(response As ISCreditEnquiryResponse_Aply_VerificationFraudAnalytics) As ISSummaryTables

  Dim NetworkActivity As ISCreditEnquiryResponse_Aply_VerificationFraudAnalyticsResultsNetworkActivity
  Dim OtherIndicator As ISCreditEnquiryResponse_Aply_VerificationFraudAnalyticsResultsOtherIndicator
  Dim RiskIndicator As ISCreditEnquiryResponse_Aply_VerificationFraudAnalyticsResultsRiskIndicator
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Create Objects
  SummaryTables = finBL.CreateSummaryTables()

  ' Fraud Analytic Table
  If response.HasData Then
    SummaryTables.AddSummaryTableBlank("FraudAnalytics", "Fraud Analytics", "<div></div>", "FraudAnalytics", 2)
    
    SummaryTable = SummaryTables.CreateSummaryTableInformation("Details", "FraudAnalyticsDetails", 3, , , TestMode)
    With SummaryTable
      .AddRowCaptionText("Full Name:", response.FullName, False)
      .AddRowCaptionText("Email:", response.Email, False)
      .AddRowCaptionText("Contact Phone:", response.ContactPhone, False)
      .AddRowCaptionText("IP Address:", response.IpAddress, False)
      .AddRowCaptionText("Address:", response.Address, False)
    End With
    SummaryTables.Add("FraudAnalyticsDetails", SummaryTable)
    
    SummaryTable = SummaryTables.CreateSummaryTableTabular("Risk Indicators", "FraudAnalyticsRiskIndicators", 3, TestMode)
    With SummaryTable
      ' Columns
      With .Columns
        .AddText("Type")
        .AddText("Indicator")
        .AddDouble("Score")
        .AddText("")
      End With
      
      ' Rows
      With .Rows
          For Each RiskIndicator In response.Results.RiskIndicators
            With .Add
              With .Cells
                .AddText(RiskIndicator.Type)
                .AddText(RiskIndicator.Indicator)
                .AddText(RiskIndicator.ScoreResolved)
              End With
              AddCellSuccessFail(.Cells, RiskIndicator.RiskValue, RiskIndicator.RiskValueRaw)
            End With
          Next        
      End With
    End With
    SummaryTables.Add("FraudAnalyticsRiskIndicators", SummaryTable)
  
    SummaryTable = SummaryTables.CreateSummaryTableTabular("Other Indicators", "FraudAnalyticsOtherIndicators", 3, TestMode)
    With SummaryTable
      ' Columns
      With .Columns
        .AddText("Type")
        .AddText("Value")
        .AddText(" ")
      End With
      
      ' Rows
      With .Rows
          For Each OtherIndicator In response.Results.OtherIndicators
            With .Add
              With .Cells
                .AddText(OtherIndicator.Type)
                .AddText(OtherIndicator.ValueResolved)
              End With
              AddCellSuccessFail(.Cells, OtherIndicator.RiskValue, OtherIndicator.RiskValueRaw)
            End With
          Next        
      End With
    End With
    SummaryTables.Add("FraudAnalyticsOtherIndicators", SummaryTable)
  
    SummaryTable = SummaryTables.CreateSummaryTableTabular("Network Activity", "FraudAnalyticNetworkActivity", 3, TestMode)
    With SummaryTable
      ' Columns
      With .Columns
        .AddText("Type")
        .AddDouble("Value")
        .AddText("")
      End With
      
      ' Rows
      With .Rows
          For Each NetworkActivity In response.Results.NetworkActivities
            With .Add
              With .Cells
                .AddText(NetworkActivity.Type)
                .AddText(NetworkActivity.ValueResolved)
              End With
              AddCellSuccessFail(.Cells, NetworkActivity.RiskValue, NetworkActivity.RiskValueRaw)
            End With
          Next        
      End With
    End With
    SummaryTables.Add("FraudAnalyticsNetworkActivity", SummaryTable)    
  End If

  Return SummaryTables

End Function

Private Function Aply_History(serviceLogs As ISServiceLogs) As ISSummaryTables

  Dim HasUserLogsToShow As Boolean
  Dim LinkedLogs As finLogs
  Dim Log As finLogRO
  Dim ServiceLog As ISServiceLog
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  ' Check for webhook errors
    HasUserLogsToShow = False
    If ServiceLogs(0).ResponseStatus = iseServiceLogResponseStatus.InProgress Then
    If finBL.Utilities.GetServiceLogLinkedLogs(serviceLogs(0).Pk, LinkedLogs) AndAlso LinkedLogs.Count <> 0 Then
      SummaryTable = SummaryTables.CreateSummaryTableTabular("User Logs", "UserLogs", 2, TestMode)
      With SummaryTable
        ' Columns
        With .Columns
          .AddText("User Log")
          .AddDate("Date")
          .AddText("User")
          .AddText("Subject")
          .AddText("Notes")
        End With
        
        ' Rows
        With .Rows
          For Each Log In LinkedLogs
            If Log.LogSource = isefinLogSource.Webhook AndAlso Log.ActionUtcDate <> Nothing AndAlso Log.ActionCompleteUtcDate = Nothing Then
              HasUserLogsToShow = True
              With .Add
                With .Cells
                  .AddText(CStr(Log.Pk)).HyperlinkSetFormShow("UserLog", CStr(Log.Pk))
                  .AddDateTime(Log.CreatedDate,, True)
                  .AddCodeDescription(Log.CreatedUserPk, finBL.Users)
                  .AddText(Log.Subject)
                  .AddText(Log.Notes)
                End With
              End With
            End If
          Next
        End With
      End With
      If HasUserLogsToShow Then
        SummaryTables.Add("UserLogs", SummaryTable)
      End If
    End If
  End If

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

    ' Rows
    With .Rows
      For Each ServiceLog In serviceLogs
        With .Add
          If Len(ServiceLog.ExStatusHtmlColour) <> 0 Then
            .BackgroundColour = ServiceLog.ExStatusHtmlColour
            If finBL.Runtime.ColourUtilities.HtmlColourIsDark(ServiceLog.ExStatusHtmlColour) Then .ForegroundColour = "white"
          End If
          With .Cells
            .AddText(CStr(ServiceLog.Pk)).HyperlinkSetFormShow("ServiceLog", CStr(ServiceLog.Pk))
            .AddDateTime(ServiceLog.CreatedDate,, True)
            .AddCodeDescription(ServiceLog.CreatedUserPk, finBL.Users)
            Select Case TypeName(ServiceLog.ExResponse)
              Case "ISCreditEnquiryResponse_Aply_Verify"
                .AddText(ServiceLog.ResponseReference)
              Case Else
                .AddText(ServiceLog.RequestReference)
            End Select
            .AddText(ServiceLog.ProductId)
            .AddText(ServiceLog.ExStatus).Tooltip = ServiceLog.ExStatusTooltip
          End With
        End With
      Next
    End With
  End With
  SummaryTables.Add("History", SummaryTable)

  Return SummaryTables

End Function

Private Function Aply_ManualVerify_EnquiryDetails(serviceLogs As ISServiceLogs,
                                                  response_ManualVerify As ISCreditEnquiryResponse_Aply_ManualVerify) As ISSummaryTables

  Dim Days As Integer
  Dim PdfReportServiceLogPk As Integer
  Dim PepWatchlistServiceLogPk As Integer
  Dim ServiceLog As ISServiceLog
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim Warnings As String

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  SummaryTable = SummaryTables.CreateSummaryTableInformation("", "EnquiryDetails", , , , TestMode)
  SummaryTable.Columns(1).WidthChars = 50
  With SummaryTable
    .AddRowCaptionUtcDateTimeWithTimeZone("Date:", response_ManualVerify.EnquiryUtcDate, finBL.Settings.TimeZoneId)
    .AddRowCaptionText("Reference:", response_ManualVerify.Request.ReferenceResolved)
    .AddRowCaptionText("External Id:", serviceLogs(0).RequestReference)

    If Client IsNot Nothing Then
      With .Rows.AddCaptionCodeDescription("Client:", client.ClientId, client.Name)
        .Cells(1).HyperlinkSetFormShow("Clients", client.ClientId)
      End With
    ElseIf AccountAppApplicant IsNot Nothing Then
      With .Rows.AddCaptionCodeDescription("Applicant:", AccountAppApplicant.AccountApp.AccountAppId, AccountAppApplicant.Name)
        .Cells(1).HyperlinkSetFormShow("AccountApps", AccountAppApplicant.AccountApp.AccountAppId, "Applicants")
      End With
    ElseIf Len(response_ManualVerify.Request.ClientId) <> 0 Then
      .AddRowCaptionWiki("Client:", String.Format("**{0} !!Not Found!!**", response_ManualVerify.Request.ClientId))
    End If

    ' Actions
    For Each ServiceLog In serviceLogs
      If ServiceLog.RequestStatus = iseAuditLogStatus.Success Then
        Select Case TypeName(ServiceLog.ExResponse)
          Case "ISCreditEnquiryResponse_Aply_ManualVerifyDownloadPdfReport"
            PdfReportServiceLogPk = ServiceLog.Pk
          Case "ISCreditEnquiryResponse_Aply_ManualVerifyDownloadPepWatchlist"
            PepWatchlistServiceLogPk = ServiceLog.Pk
        End Select
      End If
    Next
    If PdfReportServiceLogPk = 0 Then
      .Actions.AddApplicationShortcutUrl("GetReport", "Get Report", String.Format("app://global?type=CreditEnquiry.GetDocuments&serviceLogPk={0}&DocumentKey={1}", serviceLogs(0).Pk, ""), True).ShowInWebInterfaces = True
    Else
      .Actions.AddApplicationShortcutUrl("OpenReport", "View Report", String.Format("app://global?type=CreditEnquiry.OpenDocument&serviceLogPk={0}&DocumentKey={1}", PdfReportServiceLogPk, ""), True).ShowInWebInterfaces = True
    End If
    If Not response_ManualVerify.Results.PEPClear Then
      If PepWatchlistServiceLogPk = 0 Then
        .Actions.AddApplicationShortcutUrl("GetPEP", "Get PEP Watchlist", String.Format("app://global?type=CreditEnquiry.GetDocuments&serviceLogPk={0}&DocumentKey={1}", serviceLogs(0).Pk, "PEPWATCHLIST"), True).ShowInWebInterfaces = True
      Else
        .Actions.AddApplicationShortcutUrl("OpenPEP", "View PEP Watchlist", String.Format("app://global?type=CreditEnquiry.OpenDocument&serviceLogPk={0}&DocumentKey={1}", PepWatchlistServiceLogPk, "PEPWATCHLIST"), True).ShowInWebInterfaces = True
      End If
    End If
    
    ' Warnings
    Warnings = ""

    ' Out of date
    Days = CInt(DateDiff(DateInterval.Day, response_ManualVerify.EnquiryUtcDate, finBL.TimeZoneFunctions.GetCurrentUtcDateTime()))
    If Days > OutOfDateWarningDays Then
       Warnings &= "{{Warning|This Report is " & CStr(Days) & " days old.}}"
    End If

    .TextAfter = Warnings
  End With
  SummaryTables.Add("EnquiryDetails", SummaryTable)

  SummaryTable = SummaryTables.CreateSummaryTableInformation("Individual", "Individual", , , , TestMode)
  SummaryTable.Columns(1).WidthChars = 50
  With SummaryTable
    .AddRowCaptionText("First Name:", response_ManualVerify.Request.FirstName, True)
    .AddRowCaptionText("Middle Names:", response_ManualVerify.Request.MiddleNames, False)
    .AddRowCaptionText("Last Name:", response_ManualVerify.Request.LastName, True)
    .AddRowCaptionDate("Date of Birth:", response_ManualVerify.Request.DateOfBirth, True)
    .AddRowCaptionText("Gender:", response_ManualVerify.Request.Gender, True)
    .AddRowCaptionAddressDetailsPhysical("Address:", response_ManualVerify.Request.ToAddressDetails(False))
  End With
  SummaryTables.Add("Individual", SummaryTable)
  
  SummaryTable = SummaryTables.CreateSummaryTableInformation("Identity Document", "IdentityDocument", , , , TestMode)
  SummaryTable.Columns(1).WidthChars = 50
  With SummaryTable
    Select Case response_ManualVerify.Request.IdentityDocumentType
      Case iseCreditBureau_Aply_IdDocumentType.DriversLicence
        Select Case response_ManualVerify.Request.IdentityDocumentCountry
          Case "AUS"    
            .AddRowCaptionText("Type:", "Australian Driver Licence", True)
            .AddRowCaptionText("Licence Number:", response_ManualVerify.Request.DriversLicenceNumber, True)
            .AddRowCaptionText("Card Number:", response_ManualVerify.Request.DriversLicenceCardNumber, True)
            .AddRowCaptionText("State:", response_ManualVerify.Request.DriversLicenceState, True)
          Case "GBR"
            .AddRowCaptionText("Type:", "United Kingdom Driver Licence", True)
            .AddRowCaptionText("Number:", response_ManualVerify.Request.DriversLicenceNumber, True)
          Case "NZL"
            .AddRowCaptionText("Type:", "New Zealand Driver Licence", True)
            .AddRowCaptionText("Number-Version:", response_ManualVerify.Request.DriversLicenceNumberWithVersion, True)
          Case Else
            .AddRowCaptionText("Type:", String.Format("{0} Driver Licence",response_ManualVerify.Request.IdentityDocumentCountry), True)
            .AddRowCaptionText("Number:", response_ManualVerify.Request.DriversLicenceNumber, False)
        End Select
      Case iseCreditBureau_Aply_IdDocumentType.Passport
        Select Case response_ManualVerify.Request.IdentityDocumentCountry
          Case "AUS"    
            .AddRowCaptionText("Type:", "Australian Passport", True)
            .AddRowCaptionText("Number:", response_ManualVerify.Request.PassportNumber, False)
            .AddRowCaptionDate("Expiry Date:", response_ManualVerify.Request.PassportExpiry, True)
          Case "GBR"
            .AddRowCaptionText("Type:", "United Kingdom Passport", True)
            .AddRowCaptionText("Number:", response_ManualVerify.Request.PassportNumber, False)
          Case "NZL"
            .AddRowCaptionText("Type:", "New Zealand Passport", True)
            .AddRowCaptionText("Number:", response_ManualVerify.Request.PassportNumber, False)
            .AddRowCaptionDate("Expiry Date:", response_ManualVerify.Request.PassportExpiry, True)
          Case Else
            .AddRowCaptionText("Type:", String.Format("{0} Passport",response_ManualVerify.Request.IdentityDocumentCountry), True)
            .AddRowCaptionText("Number:", response_ManualVerify.Request.PassportNumber, False)
        End Select
    End Select
  End With
  SummaryTables.Add("IdentityDocument", SummaryTable)
  
  Return SummaryTables

End Function

Private Function Aply_ManualVerify_Result(serviceLogs As ISServiceLogs,
                                          response_ManualVerify As ISCreditEnquiryResponse_Aply_ManualVerify) As ISSummaryTables

  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  SummaryTable = SummaryTables.CreateSummaryTableInformation("Results", "Results", , , , TestMode)
  SummaryTable.Columns(1).WidthChars = 50
  
  If response_ManualVerify.Results.Overall Then
    With summaryTable.Rows.AddCaptionText("Overall Assessment", "{{icon|Outcome_Success}} PASS")
      .BackgroundColour = response_ManualVerify.Results.OverallAssessmentHtmlColour
    End With
  Else
    With summaryTable.Rows.AddCaptionText("Overall Assessment", "{{icon|Outcome_Failed}} FAIL")
      .BackgroundColour = response_ManualVerify.Results.OverallAssessmentHtmlColour
    End With
  End If
  
  AddRowCaptionSuccessFail(summaryTable, "Name", response_ManualVerify.Results.Name)
  AddRowCaptionSuccessFail(summaryTable, "Date-of-Birth", response_ManualVerify.Results.DateOfBirth)
  AddRowCaptionSuccessFail(summaryTable, "Address", response_ManualVerify.Results.Address)
  AddRowCaptionSuccessFail(summaryTable, "PEP Clear", response_ManualVerify.Results.PEPClear)
  AddRowCaptionSuccessFail(summaryTable, "ID Document", response_ManualVerify.Results.Document)
  SummaryTables.Add("Results", SummaryTable)

  Return SummaryTables

End Function

Public Function Aply_Verify_Alerts(serviceLogs As ISServiceLogs,
                                   response_Verify As ISCreditEnquiryResponse_Aply_Verify,
                                   response_Verification As ISCreditEnquiryResponse_Aply_Verification) As ISSummaryTables

  Dim Days As Integer
  Dim LinkedLogs As finLogs
  Dim Log As finLogRO
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim Warnings As finWarnings

  ' Create Objects
  SummaryTables = finBL.CreateSummaryTables()
  Warnings = finBL.CreateWarnings

  ' Check for webhook errors
  If ServiceLogs(0).ResponseStatus = iseServiceLogResponseStatus.InProgress Then
    If finBL.Utilities.GetServiceLogLinkedLogs(serviceLogs(0).Pk, LinkedLogs) Then
      For Each Log In LinkedLogs
        If Log.LogSource = isefinLogSource.Webhook AndAlso Log.ActionUtcDate <> Nothing AndAlso Log.ActionCompleteUtcDate = Nothing Then
          Warnings.AddWarning(Log.Subject,,, isefinWarningLevel.Critical)
        End If
      Next
    End If
  End If

  ' Status
  Select Case ServiceLogs(0).ResponseStatus
    Case iseServiceLogResponseStatus.Deleted
      Warnings.AddWarning("Request deleted.",,, isefinWarningLevel.Critical)
    Case iseServiceLogResponseStatus.Declined
      Warnings.AddWarning(String.Format("Request declined on {0}.", finBL.FormatDateTime(ServiceLogs(0).CreatedDate, True, True, True)),,, isefinWarningLevel.Critical)
    Case iseServiceLogResponseStatus.Failed
      Warnings.AddWarning("Request failed.",,, isefinWarningLevel.Critical)
    Case iseServiceLogResponseStatus.InProgress
      Warnings.AddWarning("Report not yet complete.",,, isefinWarningLevel.High)
  End Select
  
  ' Out of Date
  If response_Verification IsNot Nothing Then
    Days = CInt(DateDiff(DateInterval.Day, ServiceLogs(0).CreatedDate, finBL.TimeZoneFunctions.GetCurrentLocalDateTime()))
    If Days > OutOfDateWarningDays Then
      Warnings.AddWarning(String.Format("This is an OLD Report, data is from {0} days ago.", Days),,, isefinWarningLevel.Critical)
    End If
  End If

  ' Verification Alerts
  If response_Verification IsNot Nothing Then
    ' ID Document Expired
    If response_Verification.Data.IdDocument.ExpiryDate <> Nothing Then
      Select Case response_Verification.Data.IdDocument.ExpiryDate
        Case <= ServiceLogs(0).CreatedDate
          Warnings.AddWarning(String.Format("{0} expired on {1}.", response_Verification.Data.IdDocument.TypeText, finBL.FormatDateLong(response_Verification.Data.IdDocument.ExpiryDate)),,, isefinWarningLevel.Critical)
        Case < ServiceLogs(0).CreatedDate.AddDays(30)
          Warnings.AddWarning(String.Format("{0} expires on {1}.", response_Verification.Data.IdDocument.TypeText, finBL.FormatDateLong(response_Verification.Data.IdDocument.ExpiryDate)),,, isefinWarningLevel.Medium)
        Case <= finBL.Runtime.TimeZoneUtilities.GetCurrentLocalDate()
          Warnings.AddWarning(String.format("{0} is now expired.", response_Verification.Data.IdDocument.TypeText),,, isefinWarningLevel.High)
      End Select
    End If
  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 Function Aply_Verify_Device(responseDevice As ISCreditEnquiryResponse_Aply_VerificationDevice) As ISSummaryTables

  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Create Objects
  SummaryTables = finBL.CreateSummaryTables()

  ' Device Details
  SummaryTable = SummaryTables.CreateSummaryTableInformation("Device Details", "", 2, , , TestMode)
  With SummaryTable
    .Align = "Left"
    .WidthHtml = "100%"
    .MaxWidthHtml = "300px"

    .AddRowCaptionText("Device:", responseDevice.Device)
    .AddRowCaptionText("Operating System:", responseDevice.Os)
    .AddRowCaptionText("Browser:", responseDevice.Browser)
    .AddRowCaptionText("IP:", responseDevice.Ip)
    .AddRowCaptionText("ISP:", responseDevice.Isp)
    .AddRowCaptionNullableBooleanYesNo("VPN:", responseDevice.Vpn, True, "Unknown")
  End With 
  SummaryTables.Add("DeviceDetails", SummaryTable)
  
  ' Add Location
  If responseDevice.GeoLocation.HasData OrElse responseDevice.IpLocation.HasData Then
    ' Add Maps or Table?
    If Len(finBL.Settings.AddressingGoogleMapsApiKeyBrowser) = 0 Then
      ' Table
      SummaryTable = SummaryTables.CreateSummaryTableTabular("Device Location", "DeviceLocation", 3, TestMode)
      With SummaryTable
        .WidthHtml = "100%"
        .MaxWidthHtml = "300px"
        
        ' Columns
        With .Columns
          .AddText("Type", 20)
          .AddText("Latitude", 24, iseSummaryTableCellTextAlign.Right)
          .AddText("Longitude", 24, iseSummaryTableCellTextAlign.Right)
        End With

        ' Add Distance note
        If responseDevice.GeoLocation.HasData AndAlso responseDevice.IpLocation.HasData AndAlso responseDevice.LocDistance IsNot Nothing  Then
          .TextBefore = "{{info|" & String.Format("Distance between locations {0:0.0} kms.", responseDevice.LocDistance) & "}}"
        End If

        ' Rows
        With .Rows
          If responseDevice.GeoLocation.HasData Then
            With .Add
              With .Cells
                .AddText("Location")
                .AddDouble(responseDevice.Geolocation.Latitude, 12)
                .AddDouble(responseDevice.Geolocation.Longitude, 12)
              End With
            End With
          End If
          If responseDevice.IpLocation.HasData Then
            With .Add
              With .Cells
                .AddText("IP Location")
                .AddDouble(responseDevice.IpLocation.Latitude, 12)
                .AddDouble(responseDevice.IpLocation.Longitude, 12)
              End With
            End With
          End If
        End With
      End With
      SummaryTables.Add("DeviceLocation", SummaryTable)
    Else
      ' Maps
      SummaryTable = SummaryTables.CreateSummaryTableInformation("", , 3, , , TestMode)
      With SummaryTable
        .Align = "Left"
        .WidthHtml = "100%"
        .MaxWidthHtml = "300px"
        
        If responseDevice.GeoLocation.HasData Then
          If ScriptInfo.Target = iseSummaryPageTarget.Report Then 
            .TextAfter = finBL.SummaryPageStandardBlocks.Client_StaticMapFromCoordinates(ScriptInfo, responseDevice.GeoLocation.Latitude, responseDevice.GeoLocation.Longitude, 320, 480)
          Else
            .TextAfter = String.Format("<div class='is-noscreen'>{0}</div><div class='is-noprint'>{1}</div>",
              finBL.SummaryPageStandardBlocks.Client_StaticMapFromCoordinates(ScriptInfo, responseDevice.GeoLocation.Latitude, responseDevice.GeoLocation.Longitude, 320, 480),
              finBL.SummaryPageStandardBlocks.Client_MapFromCoordinates(ScriptInfo, responseDevice.GeoLocation.Latitude, responseDevice.GeoLocation.Longitude, "320px", "480px"))
          End If
        Else
          If ScriptInfo.Target = iseSummaryPageTarget.Report Then 
            .TextAfter = finBL.SummaryPageStandardBlocks.Client_StaticMapFromCoordinates(ScriptInfo, responseDevice.IpLocation.Latitude, responseDevice.IpLocation.Longitude, 320, 480)
          Else
            .TextAfter = finBL.SummaryPageStandardBlocks.Client_MapFromCoordinates(ScriptInfo, responseDevice.IpLocation.Latitude, responseDevice.IpLocation.Longitude, "320px", "480px")
          End If
          .TextAfter &= "{{info|Note, the map shows the location of the IP address used, not necessarily the exact device location.}}"
        End If  
      End With
      SummaryTables.Add("DeviceLocation", SummaryTable)
    End If
  End If

  Return SummaryTables

End Function

Private Function Aply_Verify_EnquiryDetails(serviceLogs As ISServiceLogs,
                                            response_Verify As ISCreditEnquiryResponse_Aply_Verify) As ISSummaryTables


  Dim Days As Integer
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim Warnings As String

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  SummaryTable = SummaryTables.CreateSummaryTableInformation("", "EnquiryDetails", , , , TestMode)
  SummaryTable.Columns(1).WidthChars = 50
  With SummaryTable
    .AddRowCaptionUtcDateTimeWithTimeZone("Date:", response_Verify.EnquiryUtcDate, finBL.Settings.TimeZoneId)
    .AddRowCaptionText("Reference:", response_Verify.Request.ReferenceResolved)
    .AddRowCaptionText("External Id:", serviceLogs(0).RequestReference)
    Select Case response_Verify.Request.FlowType
      Case iseCreditBureau_Aply_FlowType.SIMPLE2
      Case Else  
        .AddRowCaptionText("Flow Type:", response_Verify.Request.FlowTypeText)
    End Select

    If Client IsNot Nothing Then
      With .Rows.AddCaptionCodeDescription("Client:", client.ClientId, client.Name)
        .Cells(1).HyperlinkSetFormShow("Clients", client.ClientId)
      End With
    ElseIf AccountAppApplicant IsNot Nothing Then
      With .Rows.AddCaptionCodeDescription("Applicant:", AccountAppApplicant.AccountApp.AccountAppId, AccountAppApplicant.Name)
        .Cells(1).HyperlinkSetFormShow("AccountApps", AccountAppApplicant.AccountApp.AccountAppId, "Applicants")
      End With
    ElseIf Len(response_Verify.Request.ClientId) <> 0 Then
      .AddRowCaptionWiki("Client:", String.Format("**{0} !!Not Found!!**", response_Verify.Request.ClientId))
    End If

    .AddRowCaptionText("Contact Phone:", response_Verify.Request.ContactPhone)
    .AddRowCaptionText("First Name:", response_Verify.Request.FirstName, True)
    .AddRowCaptionText("Last Name:", response_Verify.Request.LastName, True)

    ' Add Actions
    If ServiceLogs(0).ResponseStatus = iseServiceLogResponseStatus.InProgress Then
      .AddRowCaptionText("Start-Process URL:", response_Verify.StartProcessUrl, False)
      .Actions.AddApplicationShortcutUrl("Refresh", "Refresh", String.Format("app://global?type=ServiceLog.Refresh&serviceLogPk={0}&NotifyAction=CreditEnquiry.Refresh", serviceLogs(0).Pk), True).ShowInWebInterfaces = True
      .Actions.AddApplicationShortcutUrl("UpdateStatus", "Update Status", String.Format("app://global?type=CreditEnquiry.GetReport&serviceLogPk={0}&NotifyAction=CreditEnquiry.Refresh", serviceLogs(0).Pk), True).ShowInWebInterfaces = True
    End If

    ' Warnings
    Warnings = ""

    ' Out of date
    Days = CInt(DateDiff(DateInterval.Day, response_Verify.EnquiryUtcDate, finBL.TimeZoneFunctions.GetCurrentUtcDateTime()))
    If Days > OutOfDateWarningDays Then
       Warnings &= "{{Warning|This Report is " & CStr(Days) & " days old.}}"
    End If

    .TextAfter = Warnings
  End With
  SummaryTables.Add("EnquiryDetails", SummaryTable)

  Return SummaryTables

End Function

Private Function Aply_Verify_Outcome(serviceLogs As ISServiceLogs,
                                     response_Verification As ISCreditEnquiryResponse_Aply_Verification) As ISSummaryTables

  Dim Outcome As String
  Dim OutcomeColour As String
  Dim ServiceLog As ISServiceLog
  Dim ServiceLog_VerifyDownloadPdfReport As ISServiceLog
  Dim ServiceLog_VerifyDownloadPdfReport_IsLatest As Boolean
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim Warnings As String

  ' Find Pdf Report
  ServiceLog_VerifyDownloadPdfReport = Nothing
  ServiceLog_VerifyDownloadPdfReport_IsLatest = False
  For Each ServiceLog In serviceLogs
    If ServiceLog.RequestStatus = iseAuditLogStatus.Success Then
      Select Case TypeName(ServiceLog.ExResponse)
        Case "ISCreditEnquiryResponse_Aply_VerifyResult"
          Select Case DirectCast(ServiceLog.ExResponse, ISCreditEnquiryResponse_Aply_VerifyResult).Event
            Case iseCreditBureau_Aply_Event.Completed, iseCreditBureau_Aply_Event.Updated
              ServiceLog_VerifyDownloadPdfReport_IsLatest = False
          End Select
        Case "ISCreditEnquiryResponse_Aply_VerifyDownloadPdfReport"
          ServiceLog_VerifyDownloadPdfReport_IsLatest = True
          ServiceLog_VerifyDownloadPdfReport = ServiceLog
      End Select
    End If
  Next

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  SummaryTable = SummaryTables.CreateSummaryTableInformation("Verification Outcome", "Verification", 2, , , TestMode)
  SummaryTable.Columns(1).WidthChars = 20
  With SummaryTable
    ' Rows
    .AddRowCaptionText("Type:", response_Verification.TypeText)

    ' Outcome Text/ Colour
    Select Case response_Verification.Status
      Case iseCreditBureau_Aply_VerificationStatus.Fail
        Outcome = "FAIL"
        OutcomeColour = "pink"
      Case iseCreditBureau_Aply_VerificationStatus.Pass
        Outcome = "PASS"
        OutcomeColour = "lightgreen"
      Case Else
        Outcome = UCase(response_Verification.StatusText)
        OutcomeColour = "orange"
    End Select
    With .Rows.AddCaptionText("Outcome:", Outcome)
      .BackgroundColour = OutcomeColour
    End With

    ' Overview
    Me.AddRowCaptionSuccessFail(SummaryTable, "Biometrics:", response_Verification.Biometrics.Overall, response_Verification.Biometrics.HasData)
    Me.AddRowCaptionSuccessFail(SummaryTable, "Tampering Checks:", response_Verification.TamperingChecks.Overall, response_Verification.TamperingChecks.HasData)
    Me.AddRowCaptionSuccessFail(SummaryTable, "Location:", response_Verification.Location.Overall, response_Verification.Location.HasData)
    Me.AddRowCaptionSuccessFail(SummaryTable, "PEP Watchlist clear:", response_Verification.Pep.Overall, response_Verification.pep.HasData)

    ' Add Actions
    'If response_VerifyResultComplete IsNot Nothing Then
    If response_Verification IsNot Nothing Then
      If ShowPortalUrl AndAlso Len(response_Verification.AplyPortalUrl) <> 0 Then
        .Actions.AddApplicationShortcutUrl("OpenPortal", "Open in Portal", "External?file=" & finBL.UrlEncode(response_Verification.AplyPortalUrl)).ShowInWebInterfaces = True
      End If
      If ServiceLog_VerifyDownloadPdfReport Is Nothing Then
        Select Case response_Verification.Status
          Case iseCreditBureau_Aply_VerificationStatus.Review
            ' Not available
          Case Else
            .Actions.AddApplicationShortcutUrl("GetDocument", "Get Report", String.Format("app://global?type=CreditEnquiry.GetDocuments&serviceLogPk={0}", serviceLogs(0).Pk), True).ShowInWebInterfaces = True
        End Select
      ElseIf ServiceLog_VerifyDownloadPdfReport_IsLatest Then
        .Actions.AddApplicationShortcutUrl("OpenDocument", "View Report", String.Format("app://global?type=CreditEnquiry.OpenDocument&serviceLogPk={0}", ServiceLog_VerifyDownloadPdfReport.Pk), True).ShowInWebInterfaces = True

        ' Save report if missing from Application or Client Log
        If AccountAppApplicant IsNot Nothing AndAlso AccountAppLog IsNot Nothing Then
          If Len(AccountAppLog.DocumentFileName) = 0 Then
            .Actions.AddApplicationShortcutUrl("SaveDocument", "Save Report", String.Format("app://global?type=CreditEnquiry.SaveDocument&serviceLogPk={0}", ServiceLog_VerifyDownloadPdfReport.Pk), True).ShowInWebInterfaces = True
          End If
        ElseIf Client IsNot Nothing AndAlso ClientLog IsNot Nothing Then
          If Len(ClientLog.DocumentFileName) = 0 Then
            .Actions.AddApplicationShortcutUrl("SaveDocument", "Save Report", String.Format("app://global?type=CreditEnquiry.SaveDocument&serviceLogPk={0}", ServiceLog_VerifyDownloadPdfReport.Pk), True).ShowInWebInterfaces = True
          End If
        End If
      Else
        .Actions.AddApplicationShortcutUrl("GetDocument", "Get Latest Report", String.Format("app://global?type=CreditEnquiry.GetDocuments&serviceLogPk={0}", serviceLogs(0).Pk), True).ShowInWebInterfaces = True
        .Actions.AddApplicationShortcutUrl("OpenDocument", "View Old Report", String.Format("app://global?type=CreditEnquiry.OpenDocument&serviceLogPk={0}", ServiceLog_VerifyDownloadPdfReport.Pk), True).ShowInWebInterfaces = True
      End If
    End If

    ' Warnings
    Warnings = ""
    Select Case response_Verification.Status
      Case iseCreditBureau_Aply_VerificationStatus.Review
        If Not response_Verification.Reviewed Then
          Warnings &= "{{info|This verification needs to be reviewed in the APLYiD Portal.}}"
        End If
    End Select
    If response_Verification.Reviewed Then
      Warnings &= "{{info|Verification has been reviewed.}}"
    End If

    .TextAfter = Warnings
  End With
  SummaryTables.Add("Verification", SummaryTable)

  ' Notes
  If response_Verification.Notes.HasData Then
    SummaryTable = SummaryTables.CreateSummaryTableInformation("Notes", "Notes", 3, , , TestMode)
    With SummaryTable
      .AddRowCaptionText("Author:", response_Verification.Notes.Author)
      .AddRowCaptionText("Notes:", response_Verification.Notes.text)
    End With
    SummaryTables.Add("Notes", SummaryTable)
  End If

  Return SummaryTables

End Function

Private Function Aply_Verify_Verification_IdDocument(serviceLogs As ISServiceLogs,
                                                     response_Verification As ISCreditEnquiryResponse_Aply_Verification) As ISSummaryTables
  Dim ClientIdCardNumber As String
  Dim ClientIdExpiryDate As Date
  Dim ClientIdNumber As String
  Dim ClientIdState As String
  Dim ClientIdVersion As String
  Dim IdDocument As ISCreditEnquiryResponse_Aply_VerificationDataIdDocument
  Dim ImageIndex As Integer
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim Warnings As String

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()                                                       
  
  ' Get ID Document
  IdDocument = response_Verification.Data.IdDocument

  ' ID Document
  SummaryTable = SummaryTables.CreateSummaryTableInformation("ID Document", "IDDocument", 2, , , TestMode)
  With SummaryTable
    .WidthHtml = "100%"
    .MaxWidthHtml = "600px"

    .AddRowCaptionText("Country:", IdDocument.Country, True)
    .AddRowCaptionText("Type:", IdDocument.TypeText, True)

    Select Case IdDocument.CountryCode
      Case "AUS"
        Select Case IdDocument.Type
          Case iseCreditBureau_Aply_IdDocumentType.DriversLicence
            .AddRowCaptionText("State:", IdDocument.State)
            .AddRowCaptionText("Licence Number:", IdDocument.Number)
            .AddRowCaptionText("Card Number:", IdDocument.CardNumber)
          Case iseCreditBureau_Aply_IdDocumentType.Passport
            .AddRowCaptionText("Passport Number:", IdDocument.Number)
          Case Else
            .AddRowCaptionText("ID Number:", IdDocument.Number)
        End Select

      Case "NZL"
        Select Case IdDocument.Type
          Case iseCreditBureau_Aply_IdDocumentType.DriversLicence
            .AddRowCaptionText("Licence Number:", IdDocument.Number)
            .AddRowCaptionText("Version:", IdDocument.Version)
          Case iseCreditBureau_Aply_IdDocumentType.Passport
            .AddRowCaptionText("Passport Number:", IdDocument.Number)
          Case Else
            .AddRowCaptionText("ID Number:", IdDocument.Number)
        End Select

      Case Else
        .AddRowCaptionText("ID Number:", IdDocument.Number)
    End Select

    If IdDocument.ExpiryDate = Nothing Then
      ' Ignore
    ElseIf IdDocument.ExpiryDate <= ServiceLogs(0).CreatedDate Then  
      .AddRowCaptionDate("Expiry Date:", IdDocument.ExpiryDate,, "Expired", iseSummaryTableCellClass.Warning)
    Else
      .AddRowCaptionDate("Expiry Date:", IdDocument.ExpiryDate)
    End If

    ' Warnings
    Warnings = ""
  
    ' Client/ Applicant Warnings
    If Client IsNot Nothing Then
      Select Case IdDocument.CountryCode
        Case "AUS"
          Select Case IdDocument.Type
            Case iseCreditBureau_Aply_IdDocumentType.DriversLicence
              If Client.IdentificationItems.GetDriversLicence2("AU", ClientIdNumber, "", ClientIdExpiryDate, ClientIdState,, ClientIdCardNumber) Then
                If StrComp(IdDocument.State, ClientIdState, CompareMethod.Text) <> 0 Then
                  Warnings &= "{{warning|Drivers Licence State does not match Client.}}"
                End If
                If StrComp(IdDocument.Number, ClientIdNumber, CompareMethod.Text) <> 0 Then
                  Warnings &= "{{warning|Drivers Licence Number does not match Client.}}"
                End If
                If len(ClientIdCardNumber) = 0 AndAlso Len(IdDocument.CardNumber) <> 0 Then
                  Warnings &= "{{warning|Card Number not recorded in Client Drivers Licence.}}"
                ElseIf StrComp(IdDocument.CardNumber, ClientIdCardNumber, CompareMethod.Text) <> 0 Then
                  Warnings &= "{{warning|Drivers Licence Card Number does not match Client.}}"
                End If
                If IdDocument.ExpiryDate <> ClientIdExpiryDate Then
                  Warnings &= "{{warning|Expiry Date does not match Client.}}"
                End If
              Else
                Warnings &= "{{info|Client Drivers Licence not found.}}"
              End If
  
            Case iseCreditBureau_Aply_IdDocumentType.Passport
              If Client.IdentificationItems.GetPassport2("AU", ClientIdNumber, "", ClientIdExpiryDate) Then
                If StrComp(IdDocument.Number, ClientIdNumber, CompareMethod.Text) <> 0 Then
                  Warnings &= "{{warning|Passport Number does not match Client.}}"
                End If
                If IdDocument.ExpiryDate <> ClientIdExpiryDate Then
                  Warnings &= "{{warning|Expiry Date does not match Client.}}"
                End If
              Else
                Warnings &= "{{info|Client Passport not found.}}"
              End If
          End Select
  
        Case "NZL"
          Select Case IdDocument.Type
            Case iseCreditBureau_Aply_IdDocumentType.DriversLicence
              If Client.IdentificationItems.GetDriversLicence2("NZ", ClientIdNumber, ClientIdVersion, ClientIdExpiryDate) Then
                If StrComp(IdDocument.Number, ClientIdNumber, CompareMethod.Text) <> 0 Then
                  Warnings &= "{{warning|Drivers Licence Number does not match Client.}}"
                ElseIf StrComp(IdDocument.Version, ClientIdVersion, CompareMethod.Text) <> 0 Then
                  Warnings &= "{{warning|Drivers Licence Version does not match Client.}}"
                End If
                If IdDocument.ExpiryDate <> ClientIdExpiryDate Then
                  Warnings &= "{{warning|Expiry Date does not match Client.}}"
                End If
              Else
                Warnings &= "{{info|Client Drivers Licence not found.}}"
              End If
  
            Case iseCreditBureau_Aply_IdDocumentType.Passport
              If Client.IdentificationItems.GetPassport2("NZ", ClientIdNumber, "", ClientIdExpiryDate) Then
                If StrComp(IdDocument.Number, ClientIdNumber, CompareMethod.Text) <> 0 Then
                  Warnings &= "{{warning|Passport Number does not match Client.}}"
                End If
                If IdDocument.ExpiryDate <> ClientIdExpiryDate Then
                  Warnings &= "{{warning|Expiry Date does not match Client.}}"
                End If
              Else
                Warnings &= "{{info|Client Passport not found.}}"
              End If
          End Select
      End Select
    ElseIf AccountAppApplicant IsNot Nothing Then
      ' Applicant
      Select Case IdDocument.CountryCode
        Case "AUS"
          Select Case IdDocument.Type
            Case iseCreditBureau_Aply_IdDocumentType.DriversLicence
              If AccountAppApplicant.DriversLicenceSpecialType = isefinIdentificationTypeSpecialType.AU_DriversLicence Then
                If Len(AccountAppApplicant.DriversLicenceNumber) = 0 Then
                  Warnings &= "{{info|Applicant Drivers Licence not found.}}"
                Else
                  If StrComp(IdDocument.State, AccountAppApplicant.DriversLicenceIssuer, CompareMethod.Text) <> 0 Then
                    Warnings &= "{{warning|Drivers Licence State does not match Applicant.}}"
                  End If
                  If StrComp(IdDocument.Number, AccountAppApplicant.DriversLicenceNumber, CompareMethod.Text) <> 0 Then
                    Warnings &= "{{warning|Drivers Licence Number does not match Applicant.}}"
                  End If
                  If IdDocument.ExpiryDate <> AccountAppApplicant.DriversLicenceExpiryDate Then
                    Warnings &= "{{warning|Expiry Date does not match Applicant.}}"
                  End If
                End If
              Else
                Warnings &= "{{info|Applicant Drivers Licence not found.}}"
              End If
  
            Case iseCreditBureau_Aply_IdDocumentType.Passport
              If Len(AccountAppApplicant.PassportNumber) = 0 Then
                Warnings &= "{{info|Applicant Passport not found.}}"
              Else
                If StrComp(IdDocument.Number, AccountAppApplicant.PassportNumber, CompareMethod.Text) <> 0 Then
                  Warnings &= "{{warning|Passport Number does not match Applicant.}}"
                End If
                If IdDocument.ExpiryDate <> AccountAppApplicant.PassportExpiryDate Then
                  Warnings &= "{{warning|Expiry Date does not match Applicant.}}"
                End If
              End If
          End Select
  
        Case "NZL"
          Select Case IdDocument.Type
            Case iseCreditBureau_Aply_IdDocumentType.DriversLicence
              If AccountAppApplicant.DriversLicenceSpecialType = isefinIdentificationTypeSpecialType.NZ_DriversLicence Then
                If Len(AccountAppApplicant.DriversLicenceNumber) = 0 Then
                  Warnings &= "{{info|Applicant Drivers Licence not found.}}"
                Else
                  If StrComp(IdDocument.Number & "-" & IdDocument.Version, AccountAppApplicant.DriversLicenceNumber, CompareMethod.Text) <> 0 Then
                    Warnings &= "{{warning|Drivers Licence Number/ Version does not match Applicant.}}"
                  End If
                  If IdDocument.ExpiryDate <> AccountAppApplicant.DriversLicenceExpiryDate Then
                    Warnings &= "{{warning|Expiry Date does not match Applicant.}}"
                  End If
                End If
              Else
                Warnings &= "{{info|Applicant Drivers Licence not found.}}"
              End If
  
            Case iseCreditBureau_Aply_IdDocumentType.Passport
              If Len(AccountAppApplicant.PassportNumber) = 0 Then
                Warnings &= "{{info|Applicant Passport not found.}}"
              Else
                If StrComp(IdDocument.Number, AccountAppApplicant.PassportNumber, CompareMethod.Text) <> 0 Then
                  Warnings &= "{{warning|Passport Number does not match Applicant.}}"
                End If
                If IdDocument.ExpiryDate <> AccountAppApplicant.PassportExpiryDate Then
                  Warnings &= "{{warning|Expiry Date does not match Applicant.}}"
                End If
              End If
          End Select
      End Select
    End If
  
    If Len(Warnings) <> 0 Then
      .TextAfter = Warnings 
    End If
    
    ' ID Document Images
    .TextRight = ""
    ImageIndex = finBL.CreditBureau.Service_Aply.GetDownloadedFile(serviceLogs, "IdDocument.FrontImage")
    If ImageIndex <> -1 Then
      .TextRight &= "{{ServiceLogImage MaxWidth='270px' ServiceLogPk='" & CStr(serviceLogs(ImageIndex).Pk) & "'}}"
    End If  
    ImageIndex = finBL.CreditBureau.Service_Aply.GetDownloadedFile(serviceLogs, "IdDocument.BackImage")
    If ImageIndex <> -1 Then
      .TextRight &= "{{ServiceLogImage MaxWidth='270px' ServiceLogPk='" & CStr(serviceLogs(ImageIndex).Pk) & "'}}"
    End If  
  End With

  SummaryTables.Add("IDDocument", SummaryTable)
  
  Return SummaryTables
  
End Function                                                       

Private Function Aply_Verify_Verification_PersonalData(serviceLogs As ISServiceLogs,
                                                       response_Verify As ISCreditEnquiryResponse_Aply_Verify,
                                                       response_Verification As ISCreditEnquiryResponse_Aply_Verification) As ISSummaryTables

  Dim Address As ISCreditEnquiryResponse_Aply_VerificationDataAddress
  Dim AddressDetailsAply As ISAddressDetails
  Dim AddressDetailsClient As ISAddressDetails
  Dim Age As String
  Dim CurrentAge As Integer
  Dim EnquiryAge As Integer
  Dim ImageIndex As Integer                                                                 
  Dim PersonalData As ISCreditEnquiryResponse_Aply_VerificationDataPersonal
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim Warnings As String

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  ' Cache
  Address = response_Verification.Data.Address
  PersonalData = response_Verification.Data.Personal

  ' Personal Data
  SummaryTable = SummaryTables.CreateSummaryTableInformation("Personal Information", "Personal", 2, , , TestMode)
  With SummaryTable
    .WidthHtml = "100%"
    .MaxWidthHtml = "600px"
    
    .AddRowCaptionText("First Name:", PersonalData.FirstName)
    .AddRowCaptionText("Middle Name:", PersonalData.MiddleName)
    .AddRowCaptionText("Last Name:", PersonalData.LastName)
    If PersonalData.DateOfBirth = Nothing Then
      .AddRowCaptionText("Date of Birth:", "Unknown")
    Else
      ' Get Age
      CurrentAge = finBL.Runtime.DateUtilities.AgeInYears(PersonalData.DateOfBirth, finBL.Runtime.TimeZoneUtilities.GetCurrentLocalDate())
      EnquiryAge = finBL.Runtime.DateUtilities.AgeInYears(PersonalData.DateOfBirth, response_Verify.EnquiryDate.Date)
      If CurrentAge = EnquiryAge Then
        Age = String.Format("{0} years", EnquiryAge)
      Else
        Age = String.Format("{0} years (currently {1} years)", EnquiryAge, CurrentAge)
      End If
      .AddRowCaptionDate("Date of Birth:", PersonalData.DateOfBirth,, Age)
    End If
    .AddRowCaptionText("Gender:", PersonalData.GenderText, False)
    .AddRowCaptionAddressDetailsPhysical("Address:", Address.ToAddressDetails())

    ' Warnings
    Warnings = ""
    If Len(PersonalData.FirstName) <> 0 AndAlso Len(response_Verify.Request.FirstName) <> 0 Then
      If strcomp(PersonalData.FirstName, response_Verify.Request.FirstName, CompareMethod.Text) <> 0 Then
        Warnings &= "{{warning|First Name does not match Request.}}"
      End If
    End If
    If Len(PersonalData.LastName) <> 0 AndAlso Len(response_Verify.Request.LastName) <> 0 Then
      If strcomp(PersonalData.LastName, response_Verify.Request.LastName, CompareMethod.Text) <> 0 Then
        Warnings &= "{{warning|Last Name does not match Request.}}"
      End If
    End If
  
    ' Get APLYiD Address
    AddressDetailsAply = finBL.CreateAddressDetails()
    With AddressDetailsAply
      AddressDetailsAply = Address.ToAddressDetails()
  
      ' If Suburb and City the same clear Suburb for better matching
      If StrComp(.Suburb, .City, CompareMethod.Text) = 0 Then
        .Suburb = ""
      End If
    End With
  
    ' Client/ Applicant Warnings
    If Client IsNot Nothing Then
      ' Client
      If StrComp(PersonalData.FirstName, Client.FirstName, CompareMethod.Text) <> 0 Then
        Warnings &= "{{warning|" & String.Format("First Name does not match Client - '{0}'.", Client.FirstName) & "}}"
      End If
      If Len(PersonalData.MiddleName) <> 0 AndAlso Len(Client.MiddleNames) <> 0 Then
        If StrComp(PersonalData.MiddleName, Client.MiddleNames, CompareMethod.Text) <> 0 Then
          Warnings &= "{{warning|" & String.Format("Middle Name does not match Client - '{0}'.", Client.MiddleNames) & "}}"
        End If
      End If
      If StrComp(PersonalData.LastName, Client.LastName, CompareMethod.Text) <> 0 Then
        Warnings &= "{{warning|" & String.Format("Last Name does not match Client - '{0}'.", Client.LastName) & "}}"
      End If
      If PersonalData.DateOfBirth <> Nothing Then
        If Client.DateOfBirth = Nothing Then
          Warnings &= "{{info|Client's Date of Birth not found.}}"
        ElseIf PersonalData.DateOfBirth <> Client.DateOfBirth Then
          Warnings &= "{{warning|" & String.Format("Date of Birth does not match Client - {0}.", finBL.FormatDateLong(Client.DateOfBirth)) & "}}"
        End If
      End If
      If Len(PersonalData.Gender) <> 0 Then
        Select Case PersonalData.GenderText
          Case "Female"
            Select Case Client.Gender
              Case isefinGender.Female
              Case Else
                Warnings &= "{{warning|Gender does not match Client.}}"
            End Select
          Case "Male"
            Select Case Client.Gender
              Case isefinGender.Male
              Case Else
                Warnings &= "{{warning|Gender does not match Client.}}"
            End Select
          Case "Other"
            Select Case Client.Gender
              Case isefinGender.Female, isefinGender.Male
                Warnings &= "{{warning|Gender does not match Client.}}"
            End Select
        End Select
      End If
  
      AddressDetailsClient = Client.ContactAddresses.GetCurrentAddress().ToAddressDetails()
      With AddressDetailsClient
        .Instructions = ""
        .Addressee = ""
        .OrganisationName = ""
        .StreetUnit = ""
        .StreetNumber = ""
        .StreetName = ""
        .StreetType = ""
        .StreetDirection = ""
        .PostalId = ""
  
        ' If Suburb and City the same clear Suburb for better matching
        If StrComp(.Suburb, .City, CompareMethod.Text) = 0 Then
          .Suburb = ""
        End If
      End With
      If Not AddressDetailsAply.HasValue Then
        Warnings &= "{{info|Address not found.}}"
      ElseIf AddressDetailsClient.HasValue Then
        If Not AddressDetailsAply.CompareTo(AddressDetailsClient, True) Then
          AddressDetailsAply.Suburb = ""
          AddressDetailsClient.Suburb = ""
  
          If AddressDetailsAply.CompareTo(AddressDetailsClient, True) Then
            Warnings &= "{{info|Partial Address match - check Suburb.}}"
          Else
            Warnings &= "{{warning|Address does not match Client.}}"
          End If
        End If
      End If
    ElseIf AccountAppApplicant IsNot Nothing Then
      ' Applicant
      If StrComp(PersonalData.FirstName, AccountAppApplicant.FirstName, CompareMethod.Text) <> 0 Then
        Warnings &= "{{warning|" & String.Format("First Name does not match Applicant - '{0}'.", AccountAppApplicant.FirstName) & "}}"
      End If
      If Len(PersonalData.MiddleName) <> 0 AndAlso Len(AccountAppApplicant.MiddleNames) <> 0 Then
        If StrComp(PersonalData.MiddleName, AccountAppApplicant.MiddleNames, CompareMethod.Text) <> 0 Then
          Warnings &= "{{warning|" & String.Format("Middle Name does not match Applicant - '{0}'.", AccountAppApplicant.MiddleNames) & "}}"
        End If
      End If
      If StrComp(PersonalData.LastName, AccountAppApplicant.LastName, CompareMethod.Text) <> 0 Then
        Warnings &= "{{warning|" & String.Format("Last Name does not match Applicant - '{0}'.", AccountAppApplicant.LastName) & "}}"
      End If
      If PersonalData.DateOfBirth <> Nothing Then
        If AccountAppApplicant.DateOfBirth = Nothing Then
          Warnings &= "{{info|Applicant's Date of Birth not found.}}"
        ElseIf PersonalData.DateOfBirth <> AccountAppApplicant.DateOfBirth Then
          Warnings &= "{{warning|" & String.Format("Date of Birth does not match Applicant - {0}.", finBL.FormatDateLong(AccountAppApplicant.DateOfBirth)) & "}}"
        End If
      End If
      If Len(PersonalData.Gender) <> 0 Then
        Select Case PersonalData.GenderText
          Case "Female"
            Select Case AccountAppApplicant.Gender
              Case isefinGender.Female
              Case Else
                Warnings &= "{{warning|Gender does not match Applicant.}}"
            End Select
          Case "Male"
            Select Case AccountAppApplicant.Gender
              Case isefinGender.Male
              Case Else
                Warnings &= "{{warning|Gender does not match Applicant.}}"
            End Select
          Case "Other"
            Select Case AccountAppApplicant.Gender
              Case isefinGender.Female, isefinGender.Male
                Warnings &= "{{warning|Gender does not match Applicant.}}"
            End Select
        End Select
      End If
  
      AddressDetailsClient = AccountAppApplicant.AddressPostal
      With AddressDetailsClient
        .Instructions = ""
        .Addressee = ""
        .OrganisationName = ""
        .StreetUnit = ""
        .StreetNumber = ""
        .StreetName = ""
        .StreetType = ""
        .StreetDirection = ""
        .PostalId = ""
  
        ' If Suburb and City the same clear Suburb for better matching
        If StrComp(.Suburb, .City, CompareMethod.Text) = 0 Then
          .Suburb = ""
        End If
      End With
      If Not AddressDetailsAply.HasValue Then
        Warnings &= "{{info|Address not found.}}"
      ElseIf AddressDetailsClient.HasValue Then
        If Not AddressDetailsAply.CompareTo(AddressDetailsClient, True) Then
          AddressDetailsAply.Suburb = ""
          AddressDetailsClient.Suburb = ""
  
          If AddressDetailsAply.CompareTo(AddressDetailsClient, True) Then
            Warnings &= "{{info|Partial Address match - check Suburb.}}"
          Else
            Warnings &= "{{warning|Address does not match Client.}}"
          End If
        End If
      End If
    End If
  
    If Len(Warnings) <> 0 Then
      .TextAfter = Warnings 
    End If

    ' Face Image (Right Hand Side)
    ImageIndex = finBL.CreditBureau.Service_Aply.GetDownloadedFile(serviceLogs, "face.image")
    If ImageIndex <> -1 Then
      .TextRight = "{{ServiceLogImage MaxWidth='270px' ServiceLogPk='" & CStr(serviceLogs(ImageIndex).Pk) & "'}}"
    End If 
  End With
  SummaryTables.Add("Personal", SummaryTable)
  
  Return SummaryTables
  
End Function  

Private Function Aply_Verify_Verification_Result(response_Verification As ISCreditEnquiryResponse_Aply_Verification) As ISSummaryTables

  Dim Result As ISCreditEnquiryResponse_Aply_VerificationResult
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  Result = response_Verification.Result
  If Result IsNot Nothing Then
    SummaryTable = SummaryTables.CreateSummaryTableInformation("Results", "Results", 2 , , , TestMode)
    SummaryTable.Columns(1).WidthChars = 20
    With SummaryTable
      Me.AddRowCaptionSuccessFail(SummaryTable, "Overall:", Result.Overall)
      Me.AddRowCaptionSuccessFail(SummaryTable, "ID Document:", Result.IdDocument)
      Me.AddRowCaptionSuccessFail(SummaryTable, "Document Checks:", Result.DocumentChecks)
      Me.AddRowCaptionSuccessFail(SummaryTable, "Biometrics:", Result.Biometrics)
      Me.AddRowCaptionSuccessFail(SummaryTable, "PEP:", Result.Pep)
      Me.AddRowCaptionSuccessFail(SummaryTable, "Full Name:", Result.FullName)
      Me.AddRowCaptionSuccessFail(SummaryTable, "Date of Birth:", Result.DateOfBirth)
      Me.AddRowCaptionSuccessFail(SummaryTable, "Address:", Result.Address)
    End With
    SummaryTables.Add("Results", SummaryTable)
  End If

  Return SummaryTables

End Function