' SummaryPage2_BankAccountEnquiryReport_CreditSense
Option Explicit On
Option Strict On

' #################################################################
' Credit Sense (Version 1) Bank Account Report Summary Page Script

' Version: 2.10 (14/05/2021)

' Usage: Bank Account Enquiry and Log forms
' #################################################################

'#Const "OutOfDateWarningDays",Integer,30,"Number of days before warning the Enquiry is out-of-date."

' Constants
Private OutOfDateWarningDays As Integer = 30

' 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 Response As ISBankAccountEnquiryResponse
  Dim ServiceLogs As ISServiceLogs

  ' Assume Success
  Main = True

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

  ' Get Bank Account Enquiry Service Logs
  If Main Then
    Main = finBL.CreditBureau.GetBankAccountEnquiryServiceLogs(CInt(source), ServiceLogs)
  End If

  ' Response and service log
  If Main Then
    Try
      Main = finBL.CreditBureau.GetBankAccountEnquiryResponseFromServiceLogPk(ServiceLogs(0).Pk, Response)
    Catch ex As Exception
      Main = False
      finBL.Error.ErrorBeginFromException(ex)
    End Try
  End If

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

End Function

Private Function CreatePage(serviceLogs As ISServiceLogs,
                            response As ISBankAccountEnquiryResponse,
                            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 serviceLogs(0).TestMode Then .Watermark = "Test Mode"

    ' Note: Embed images (will also embed 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, response.ProductId), isefinSummaryPageStyle.ServiceReport)

    ' Theme
    .HtmlHeaderInsertServiceReportTheme("#006599", "#C0C0C0", "", "#E8E8E8")

    ' 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

  ' Get original Create Response
  Select Case TypeName(Response)
    Case "ISBankAccountEnquiryResponse_CreditSense_CreateToken"
      Me.CreatePage_CreditSense(ServiceLogs, response, HtmlSummaryPage2StringBuilder)

    Case Else
      ' Error
      finBL.Error.ErrorBegin("Invalid opening Service Log for a Bank Account Enquiry.")
  End Select

  ' Disclaimer
  HtmlSummaryPage2StringBuilder.Append("<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

Private Sub CreatePage_CreditSense(serviceLogs As ISServiceLogs,
                                   response As ISBankAccountEnquiryResponse,
                                   HtmlSummaryPage2StringBuilder As finHtmlSummaryPage2StringBuilder)

  Dim AccountApp As finAccountApp
  Dim AccountAppApplicant As finAccountAppApplicant
  Dim AccountAppLog As finAccountAppLog
  Dim Client As finClient
  Dim ClientLog As finClientLog
  Dim i As Integer
  Dim ResponseCreate As ISBankAccountEnquiryResponse_CreditSense_CreateToken
  Dim ResponseDelete As ISBankAccountEnquiryResponse_CreditSense_ExpireToken
  Dim ResponseResult As ISBankAccountEnquiryResponse_CreditSense_DownloadBankXML
  Dim ResponseStatus As ISBankAccountEnquiryResponse_CreditSense_ApplicationStatus

  ' Initialise
  ResponseCreate = DirectCast(Response, ISBankAccountEnquiryResponse_CreditSense_CreateToken)

  ' Get Other Responses
  For i = serviceLogs.Count - 1 To 0 Step -1
    If serviceLogs(i).RequestStatus = iseAuditLogStatus.Success Then
      response = DirectCast(serviceLogs(i).ExResponse, ISBankAccountEnquiryResponse)
      Select Case TypeName(Response)
        Case "ISBankAccountEnquiryResponse_CreditSense_ApplicationStatus"
          If ResponseStatus Is Nothing Then
            ResponseStatus= DirectCast(Response, ISBankAccountEnquiryResponse_CreditSense_ApplicationStatus)
          End If
        Case "ISBankAccountEnquiryResponse_CreditSense_ExpireToken"
          ' Check if "Deleted"
          If DirectCast(Response, ISBankAccountEnquiryResponse_CreditSense_ExpireToken).IsDeletedRequest Then
            ResponseDelete = DirectCast(Response, ISBankAccountEnquiryResponse_CreditSense_ExpireToken)
            Exit For
          End If
        Case "ISBankAccountEnquiryResponse_CreditSense_DownloadBankXML"
          If ResponseResult Is Nothing Then
            ResponseResult = DirectCast(Response, ISBankAccountEnquiryResponse_CreditSense_DownloadBankXML)
          End If
      End Select
    End If
  Next

  ' Get Client/ Applicant (ignore errors)
  Select Case ServiceLogs(0).SourceType
    Case "AccountAppLog"
      AccountAppLog = finBL.CreateAccountAppLog()
      If AccountAppLog.Load(ServiceLogs(0).SourcePk) Then
        AccountApp = finBL.CreateAccountApp()
        If AccountApp.LoadPk(AccountAppLog.AccountAppPk) Then
          AccountAppApplicant = AccountApp.Applicants.ItemByPk(AccountAppLog.AccountAppApplicantPk)
        End If
      End If

    Case "Client"
      Client = finBL.CreateClient()
      Client.LoadPk(ServiceLogs(0).SourcePk)

    Case "ClientLog"
      ClientLog = finBL.CreateClientLog
      If ClientLog.Load(ServiceLogs(0).SourcePk) Then
        Client = finBL.CreateClient()
        Client.LoadPk(ClientLog.ClientPk)
      End If
  End Select

  With HtmlSummaryPage2StringBuilder
     ' Heading
    If client IsNot Nothing Then
      .AppendH1(Client.Name)
    ElseIf AccountAppApplicant IsNot Nothing Then
      .AppendH1(AccountAppApplicant.Name)
    Else
      .AppendH1(String.Format("Application - {0}", ResponseCreate.ApplicationId))
    End If
    .AppendH2(String.Format("Bank Account Enquiry Report - {0}", response.ServiceName))

    .SummaryTablesAppend(Me.CreditSense_EnquiryDetails(serviceLogs, ResponseCreate, ResponseDelete, ResponseResult, ResponseStatus, accountApp, AccountAppApplicant, Client, AccountAppLog, ClientLog))
    .SummaryTablesAppend(Me.CreditSense_Alerts(serviceLogs, ResponseCreate, ResponseDelete, ResponseResult, ResponseStatus))

    ' History
    If ServiceLogs IsNot Nothing AndAlso ResponseResult Is Nothing Then .SummaryTablesAppend(Me.CreditSense_History(serviceLogs, ResponseCreate.Service))

    ' Report already Retrieved
    If responseResult IsNot Nothing Then
      ' Decision Points
      If responseResult.DecisionPoints.Count > 1 Then .SummaryTablesAppend(Me.CreditSense_DecisionPoints(serviceLogs, ResponseResult))

      ' Account Summary
      If responseResult.Accounts.Count <> 1 Then .SummaryTablesAppend(Me.CreditSense_BankAccountSummary(serviceLogs, ResponseResult))

      ' Account Detail
      If responseResult.Accounts.Count <> 0 Then .SummaryTablesAppend(Me.CreditSense_BankAccounts(ResponseResult))
    End If
  End With

End Sub

Private Function CreditSense_EnquiryDetails(serviceLogs As ISServiceLogs,
                                            responseCreate As ISBankAccountEnquiryResponse_CreditSense_CreateToken,
                                            responseDelete As ISBankAccountEnquiryResponse_CreditSense_ExpireToken,
                                            responseResult As ISBankAccountEnquiryResponse_CreditSense_DownloadBankXML,
                                            responseStatus As ISBankAccountEnquiryResponse_CreditSense_ApplicationStatus,
                                            accountApp As finAccountApp,
                                            accountAppApplicant As finAccountAppApplicant,
                                            client As finClient,
                                            accountAppLog As finAccountAppLog,
                                            clientLog As finClientLog) As ISSummaryTables

  Dim ApplicationShortCut As ISApplicationShortcut
  Dim BranchPk As Integer
  Dim CostCentreResolved As finCostCentreResolved
  Dim Days As Integer
  Dim DocumentId As String
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim SupplementalReports As ISList
  Dim Warnings As String

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()
  BranchPk = 0

  ' Determine the Branch
  If responseCreate IsNot Nothing AndAlso responseCreate.Request IsNot Nothing Then
    BranchPk = responseCreate.Request.BranchPk
  ElseIf responseStatus IsNot Nothing AndAlso responseStatus.Request IsNot Nothing Then
    BranchPk = responseStatus.Request.BranchPk
  ElseIf responseResult IsNot Nothing AndAlso responseResult.Request IsNot Nothing Then
    BranchPk = responseResult.Request.BranchPk
  ElseIf responseDelete IsNot Nothing AndAlso responseDelete.Request IsNot Nothing Then
    BranchPk = responseDelete.Request.BranchPk
  End If

  ' Cost Centre
  CostCentreResolved = finBL.CostCentresResolved.ItemByBranchPk(BranchPk)

  SummaryTable = SummaryTables.CreateSummaryTableInformation("", "EnquiryDetails",,,, TestMode)
  With SummaryTable
    .AddRowCaptionUtcDateTimeWithTimeZone("Date:", responseCreate.EnquiryUtcDate, finBL.Settings.TimeZoneId)

    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:", AccountApp.AccountAppId, String.Format("{0} ({1})", AccountApp.Name, AccountAppApplicant.Name))
        .Cells(1).HyperlinkSetFormShow("AccountApps", AccountApp.AccountAppId, "Applicants")
      End With
    End If
    .AddRowCaptionText("Application Id:", responseCreate.ApplicationId)
    If responseCreate.Service.SupportsCentrelink Then
      If responseStatus Is Nothing Then
        .AddRowCaptionText("Centrelink Option:", "")
      Else
        .AddRowCaptionText("Centrelink Option:", ResponseStatus.CentrelinkOption)
      End If
    End If

    ' Warnings
    Warnings = ""
    Days = CInt(DateDiff(DateInterval.Day, responseCreate.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)

  ' Actions
  SummaryTable = SummaryTables.CreateSummaryTableInformation("Actions", "Actions",2,,, TestMode)
  With SummaryTable
    If ServiceLogs(0).ResponseStatus = iseServiceLogResponseStatus.InProgress AndAlso responseResult IsNot Nothing Then
      ' Special case (database failed to update); we have a successful Result Request, but the original Service Log is still "In Progress"
      .Rows.AddText("Delete Request").Cells(0).Hyperlink = String.Format("App://Global?Type=BankAccountEnquiry.Delete&ServiceLogPk={0}", ServiceLogs(0).Pk)
    ElseIf ServiceLogs(0).ResponseStatus = iseServiceLogResponseStatus.InProgress AndAlso responseResult IsNot Nothing Then
      ' Special case (database failed to update); we have a successful Result Request, but the original Service Log is still "In Progress"
      .Rows.AddText("Get Report").Cells(0).Hyperlink = String.Format("App://Global?Type=BankAccountEnquiry.GetReport&ServiceLogPk={0}", ServiceLogs(0).Pk)
    ElseIf responseResult Is Nothing AndAlso responseDelete Is Nothing Then
      .Rows.AddCaptionText("Website:", responseCreate.Service.GetDefaultUrl).Cells(1).HyperlinkSetExternal(responseCreate.Service.GetDefaultUrl)
      .Rows.AddCaptionText("Website Link:", finBL.HtmlEncode(responseCreate.Service.GetTokenUrl(responseCreate.Token))).Cells(1).HyperlinkSetExternal(finBL.HtmlEncode(responseCreate.Service.GetTokenUrl(responseCreate.Token)))
      With .Actions
        If (client IsNot Nothing AndAlso clientLog IsNot Nothing) OrElse (accountAppApplicant IsNot Nothing AndAlso accountAppLog IsNot Nothing) Then
          ' Create Application Shortcut
          ApplicationShortcut = finBL.CreateApplicationShortcut()
          With ApplicationShortCut
            .Action = "FormShow"
            With .Parameters
              If client IsNot Nothing Then
                ' Client
                .SetString("form", "DocumentCreateClient")
                .SetString("id", client.ClientId)
                .SetInteger("replyLogPk", clientLog.Pk)
              ElseIf accountAppApplicant IsNot Nothing AndAlso accountAppApplicant.ClientPk <> 0 Then
                .SetString("form", "DocumentCreateClient_AccountApp")
                .SetString("id", accountAppApplicant.AccountApp.AccountAppId)
                .SetInteger("accountAppApplicantPk", accountAppApplicant.Pk)
                .SetInteger("replyLogPk", accountAppLog.Pk)
              Else
                ' Application (not linked to an existing Client)
                .SetString("form", "DocumentCreateClient_AccountApp")
                .SetString("id", accountAppApplicant.AccountApp.AccountAppId)
                .SetInteger("accountAppApplicantPk", accountAppApplicant.Pk)
                .SetInteger("replyLogPk", accountAppLog.Pk)
              End If
            End With
          End With

          ' Email
          DocumentID =  CostCentreResolved.CreditSense.BankAccountEnquiryEmailDocumentId
          If Len(DocumentId) <> 0 Then
            ApplicationShortCut.Parameters.SetString("documentId", DocumentId)
            .AddApplicationShortcut("FormShowEmail", "Send Email", ApplicationShortCut).ShowInWebInterfaces = True
          End If

          ' SMS
          If finBL.Settings.AddOns.Messaging Then
            DocumentID =  CostCentreResolved.CreditSense.BankAccountEnquirySmsDocumentId
            If Len(DocumentId) <> 0 Then
              ApplicationShortCut.Parameters.SetString("documentId", DocumentId)
              .AddApplicationShortcut("FormShowSms", "Send SMS", ApplicationShortCut).ShowInWebInterfaces = True
            End If
          End If
        End If

        .AddApplicationShortcutUrl("GetReport", "Get Report", String.Format("App://Global?Type=BankAccountEnquiry.GetReport&ServiceLogPk={0}", ServiceLogs(0).Pk), True).ShowInWebInterfaces = True
        .AddApplicationShortcutUrl("DeleteRequest", "Delete Request", String.Format("App://Global?Type=BankAccountEnquiry.Delete&ServiceLogPk={0}", ServiceLogs(0).Pk), True).ShowInWebInterfaces = True
      End With
    End If
  End With
  SummaryTables.Add("Actions", SummaryTable)

  ' Supplemental Reports
  If ResponseDelete Is Nothing Then
    SummaryTable = SummaryTables.CreateSummaryTableInformation("Supplemental Reports", "SupplementalReports",2,,, TestMode)
    With SummaryTable
      If responseResult IsNot Nothing Then
        ' Get list of Supplemental Report
        SupplementalReports = New ISList(CostCentreResolved.CreditSense.BankAccountEnquiryReportTypes)
        If Len(responseResult.TemplateReportId) <> 0 Then SupplementalReports.Add(responseResult.TemplateReportId, True)
        If SupplementalReports.Count = 0 Then
          ' Add defaults
          SupplementalReports.Add("3")
          SupplementalReports.Add("4")
          SupplementalReports.Add("7")
          SupplementalReports.Add("10")
        End If
        SupplementalReports.Sort()

        With .Rows
          If SupplementalReports.Exists("3") Then
            With .AddCaptionText("Report 3:", "SACC Report (first account by total credits)")
              .Cells(1).HyperlinkSetGlobalAction("BankAccountEnquiry.SupplementalReport", String.Format("ServiceLogPk={0}&ReportKey=3&Title=3%20SACC%20Report%20(first%20account%20by%20total%20credits)", ServiceLogs(0).Pk))
            End With
          End If
          If SupplementalReports.Exists("4") Then
            With .AddCaptionText("Report 4:", "SACC Full Report")
              .Cells(1).HyperlinkSetGlobalAction("BankAccountEnquiry.SupplementalReport", String.Format("ServiceLogPk={0}&ReportKey=4&Title=4%20SACC%20Full%20Report", ServiceLogs(0).Pk))
            End With
          End If
          If SupplementalReports.Exists("7") Then
            With .AddCaptionText("Report 7:", "SACC New Report")
              .Cells(1).HyperlinkSetGlobalAction("BankAccountEnquiry.SupplementalReport", String.Format("ServiceLogPk={0}&ReportKey=7&Title=7%20SACC%20New%20Report", ServiceLogs(0).Pk))
            End With
          End If
          If SupplementalReports.Exists("9") Then
            With .AddCaptionText("Report 9:", "Enhanced Income Liabilities Report")
              .Cells(1).HyperlinkSetGlobalAction("BankAccountEnquiry.SupplementalReport", String.Format("ServiceLogPk={0}&ReportKey=9&Title=9%20Enhanced%20Income%20Liabilities%20Report", ServiceLogs(0).Pk))
            End With
          End If
          If SupplementalReports.Exists("10") Then
            With .AddCaptionText("Report 10:", "SACC New Full Report")
              .Cells(1).HyperlinkSetGlobalAction("BankAccountEnquiry.SupplementalReport", String.Format("ServiceLogPk={0}&ReportKey=10&Title=10%20SACC%20New%20Full%20Report", ServiceLogs(0).Pk))
            End With
          End If
          If SupplementalReports.Exists("12") Then
            With .AddCaptionText("Report 12:", "Enhanced Income Liabilities Full Report")
              .Cells(1).HyperlinkSetGlobalAction("BankAccountEnquiry.SupplementalReport", String.Format("ServiceLogPk={0}&ReportKey=12&Title=12%20Enhanced%20Income%20Liabilities%20Full%20Report", ServiceLogs(0).Pk))
            End With
          End If
          If SupplementalReports.Exists("14") Then
            With .AddCaptionText("Report 14:", "SME Report")
              .Cells(1).HyperlinkSetGlobalAction("BankAccountEnquiry.SupplementalReport", String.Format("ServiceLogPk={0}&ReportKey=14&Title=14%20SME%20Report", ServiceLogs(0).Pk))
            End With
          End If
          If SupplementalReports.Exists("15") Then
            With .AddCaptionText("Report 15:", "Data Only")
              .Cells(1).HyperlinkSetGlobalAction("BankAccountEnquiry.SupplementalReport", String.Format("ServiceLogPk={0}&ReportKey=15&Title=15%Data%20Only", ServiceLogs(0).Pk))
            End With
          End If
          If SupplementalReports.Exists("16") Then
            With .AddCaptionText("Report 16:", "Categorised")
              .Cells(1).HyperlinkSetGlobalAction("BankAccountEnquiry.SupplementalReport", String.Format("ServiceLogPk={0}&ReportKey=16&Title=16%20Categorised", ServiceLogs(0).Pk))
            End With
          End If
        End With
      End If
      If responseStatus IsNot Nothing Then
        If UCase(ResponseStatus.CentrelinkOption) = "YES" Then
          With .Actions
            .AddApplicationShortcutUrl("CentrelinkReport", "Centrelink Report", String.Format("App://Global?Type=BankAccountEnquiry.SupplementalReport&ServiceLogPk={0}&ReportKey=Centrelink&Title=Centrelink%20Report", ServiceLogs(0).Pk), True)
          End With
        End If
      End If
    End With
    SummaryTables.Add("SupplementalReports", SummaryTable)
  End If

  Return SummaryTables

End Function

Public Function CreditSense_Alerts(serviceLogs As ISServiceLogs,
                                   responseCreate As ISBankAccountEnquiryResponse_CreditSense_CreateToken,
                                   responseDelete As ISBankAccountEnquiryResponse_CreditSense_ExpireToken,
                                   responseResult As ISBankAccountEnquiryResponse_CreditSense_DownloadBankXML,
                                   responseStatus As ISBankAccountEnquiryResponse_CreditSense_ApplicationStatus) As ISSummaryTables

  Dim Account As ISBankAccountEnquiryResponse_CreditSense_DownloadBankXMLAccount
  Dim Days As Integer
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim Warnings As finWarnings

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

  ' Expired?
  If responseStatus IsNot Nothing AndAlso responseStatus.IsExpired Then
    Warnings.AddWarning("Request has expired.",,, isefinWarningLevel.Critical)
  End If

  ' Build Warning lists
  If responseResult IsNot Nothing Then
    With responseResult
      ' Completed
      Select Case ServiceLogs(0).ResponseStatus
        Case iseServiceLogResponseStatus.Deleted, iseServiceLogResponseStatus.Expired
          Warnings.AddWarning("Request deleted.",,, isefinWarningLevel.Critical)
        Case iseServiceLogResponseStatus.InProgress
          Warnings.AddWarning("Request is not correctly completed - please Get the Report again.",,, isefinWarningLevel.Critical)
        Case Else
      End Select

      ' Out of Date
      If .Accounts.Count > 0 Then
        Days = CInt(DateDiff(DateInterval.Day, responseResult.Accounts(0).MostRecentTransaction, finBL.TimeZoneFunctions.GetCurrentUtcDateTime()))
        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

      ' Accounts
      If responseResult.Accounts.Count = 0 Then
        Warnings.AddWarning("No Account information returned.",,, isefinWarningLevel.Critical)
      Else
        For Each Account In responseResult.Accounts
          With Account
            ' Balance
            If .BankCurrentBalance < 0 Then
              Warnings.AddWarning(String.Format("'{0}' Current Balance is overdrawn.", .Description),,, isefinWarningLevel.Critical, "#" & .AccountId)
            ElseIf .BankAvailableBalance < 0 Then
              Warnings.AddWarning(String.Format("'{0}' Available Balance is overdrawn.", .Description),,, isefinWarningLevel.Critical, "#" & .AccountId)
            End If

            If .DishonourCount > 0 Then
              Warnings.AddWarning(String.Format("'{0}' has had {1} dishonours.", .Description, .DishonourCount),,, isefinWarningLevel.Critical, "#" & .AccountId)
            End If
          End With
        Next
      End If
    End With
  ElseIf responseDelete IsNot Nothing Then
    ' Deleted
    Select Case ServiceLogs(0).ResponseStatus
      Case iseServiceLogResponseStatus.Deleted, iseServiceLogResponseStatus.Expired
        Warnings.AddWarning("Request deleted.",,, isefinWarningLevel.Critical)
      Case Else
        Warnings.AddWarning("Request is not correctly deleted - please Delete the Request again.",,, isefinWarningLevel.Critical)
    End Select
  Else
    ' Not yet completed
    Warnings.AddWarning("Report not yet downloaded.",,, isefinWarningLevel.Critical)
  End If

  ' Centrelink
  If responseStatus IsNot Nothing AndAlso responseStatus.Service.SupportsCentrelink AndAlso responseDelete Is Nothing Then
    Select Case UCase(responseStatus.CentrelinkStatus)
      Case "", "SUCCESS"
      Case Else
        If responseStatus.CentrelinkStatus = responseStatus.CentrelinkTextStatus Then
          Warnings.AddWarning("Centrelink status is '" & responseStatus.CentrelinkTextStatus & "'.",,, isefinWarningLevel.Critical)
        Else
          Warnings.AddWarning("Centrelink status is '" & responseStatus.CentrelinkTextStatus & "' ('" & responseStatus.CentrelinkStatus & "').",,, isefinWarningLevel.Critical)
        End If
    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 Function CreditSense_History(serviceLogs As ISServiceLogs,
                                     service As ISServiceCreditSense) As ISSummaryTables

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

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  SummaryTable = SummaryTables.CreateSummaryTableTabular("History", "History",2, TestMode)
  With SummaryTable
    ' Columns
    With .Columns
      .AddText("Service Log")
      .AddDate("Date")
      .AddText("User")
      .AddText("Type")
      .AddText("Status")
      If service.SupportsCentrelink Then .AddText("Centrelink")
    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
            .AddInteger(ServiceLog.Pk).HyperlinkSetFormShow("ServiceLog", CStr(ServiceLog.Pk))
            .AddDateTime(ServiceLog.CreatedDate)
            .AddCodeDescription(ServiceLog.CreatedUserPk, finBL.Users)
            .AddText(ServiceLog.ProductId)
            .AddText(ServiceLog.ExStatus)
            If service.SupportsCentrelink Then .AddText(ServiceLog.ExStatusTooltip)
          End With
        End With
      Next
    End With
  End With
  SummaryTables.Add("History", SummaryTable)

  Return SummaryTables

End Function

Private Function CreditSense_DecisionPoints(serviceLogs As ISServiceLogs,
                                            responseResult As ISBankAccountEnquiryResponse_CreditSense_DownloadBankXML) As ISSummaryTables

  Dim DecisionPoint As ISBankAccountEnquiryResponse_CreditSense_DownloadBankXmlDecisionPoint
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  SummaryTable = SummaryTables.CreateSummaryTableTabular("Decision Points", "DecisionPoints",2, TestMode)
  With SummaryTable
    ' Columns
    With .Columns
      .AddText("ID")
      .AddText("Criteria")
      .AddInteger("Score", 16).NoBreakChars = 32
    End With

    ' Rows
    With .Rows
      For Each DecisionPoint In responseResult.DecisionPoints
        With .Add.Cells
          .AddText(finBL.HtmlEncode(DecisionPoint.CriteriaId, True, True))
          .AddText(finBL.HtmlEncode(DecisionPoint.CriteriaName, True, True))
          .AddText(finBL.HtmlEncode(DecisionPoint.ScoreText, True, True))
        End With
      Next
    End With
  End With
  SummaryTables.Add("DecisionPoints", SummaryTable)

  Return SummaryTables

End Function

Private Function CreditSense_BankAccountSummary(serviceLogs As ISServiceLogs,
                                                responseResult As ISBankAccountEnquiryResponse_CreditSense_DownloadBankXML) As ISSummaryTables

  Dim Account As ISBankAccountEnquiryResponse_CreditSense_DownloadBankXMLAccount
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  ' Account Summary
  If responseResult.Accounts.Count = 0 Then
    SummaryTables.AddSummaryTableBlank("Accounts", "Accounts", "No Account information returned.", "Accounts", 2)
  ElseIf responseResult.Accounts.Count > 1 Then
    SummaryTable = SummaryTables.CreateSummaryTableTabular("Accounts", "Accounts",2, TestMode)
    With SummaryTable
      ' Columns
      With .Columns
        .AddText("Description")
        .AddText("Name", 12).NoBreakChars = 30
        .AddText(finBL.SupportedCountries.CurrentSupportedCountry.Terminology(isefinCountryTerminology.BankSortCode), 6).NoBreakChars = 10
        .AddText("Account Number", 12).NoBreakChars = 20
        .AddText("Account Name", 12).NoBreakChars = 20
        .AddText("Account Type", 12).NoBreakChars = 20
        .AddCurrency("Available Balance", 18)
        .AddCurrency("Current Balance", 16)
      End With

    ' Rows
      With .Rows
        For Each Account In responseResult.Accounts
          With .Add.Cells
            .AddText(Account.AccountName).Hyperlink = "#" & Account.AccountIndex
            .AddText(Account.AccountHolder)
            .AddText(Account.AccountBSB)
            .AddText(Account.AccountNumber)
            .AddText(Account.AccountName)
            .AddText(Account.AccountType)
            .AddCurrency(Account.BankAvailableBalance, True, False)
            .AddCurrency(Account.BankCurrentBalance, True, False)
          End With
        Next

        ' Total Row
        With .Add(iseSummaryTableRowClass.FooterBold).Cells
          .AddText("")
          .AddText("")
          .AddText("")
          .AddText("")
          .AddText("")
          .AddText("")
          .AddCurrency(responseResult.TotalAvailableBalance, True, False)
          .AddCurrency(responseResult.TotalCurrentBalance, True, False)
        End With
      End With
    End With
    SummaryTables.Add("Accounts", SummaryTable)
  End If

  Return SummaryTables

End Function

Private Function CreditSense_BankAccounts(responseResult As ISBankAccountEnquiryResponse_CreditSense_DownloadBankXML) As ISSummaryTables

  Dim Account As ISBankAccountEnquiryResponse_CreditSense_DownloadBankXMLAccount
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  For Each Account In responseResult.Accounts
    SummaryTable = SummaryTables.CreateSummaryTableInformation(String.Format("{0} - {1}", Account.AccountId, Account.AccountName), Account.AccountIndex,2,,, TestMode)
    With SummaryTable
      ' .Rows.AddSectionHeading2("Response (Information Returned by Bank)")
      .AddRowCaptionText("Bank:", Account.BankName)
      .AddRowCaptionText("Owner:", Account.AccountHolder)
      If StrComp(Account.AccountHolder, Account.SecondaryAccountHolder) <> 0 Then .AddRowCaptionText("Secondary Owner:", Account.SecondaryAccountHolder)
      .AddRowCaptionText(finBL.SupportedCountries.CurrentSupportedCountry.Terminology(isefinCountryTerminology.BankSortCode) & ":", Account.AccountBSB)
      .AddRowCaptionText("Account Number:", Account.AccountNumber)
      .AddRowCaptionText("Account Name:", Account.AccountName)
      .AddRowCaptionText("Account Type:", UCase(Account.AccountType))
    End With
    SummaryTables.Add(Account.AccountId, SummaryTable)

    SummaryTable = SummaryTables.CreateSummaryTableInformation("Summary", Account.AccountId & "Summary", 3,,, TestMode)
    With SummaryTable
      .AddRowCaptionDateTime("Date as at:", Account.CreatedDate)
      .AddRowCaptionText("Activity Dates:", finBL.FormatDateLong(Account.OldestTransaction) & " to " & finBL.FormatDateTime(Account.MostRecentTransaction, True, True, True))
      .AddRowCaptionCurrency("Available Balance:", Account.BankAvailableBalance, True)
      .AddRowCaptionCurrency("Current Balance:", Account.BankCurrentBalance, True)
      .AddRowCaptionCurrency("Deposits/Credits:", Account.TotalCredits, True)
      .AddRowCaptionCurrency("Withdrawals/Debits:", Account.TotalDebits, True)
    End With
    SummaryTables.Add(Account.AccountId & "Summary", SummaryTable)

    ' Transaction Analysis Summary
    SummaryTables.AppendSummaryTables(Me.CreditSense_TransactionOverviews(Account))

    ' Transaction Summary
    SummaryTables.AppendSummaryTables(Me.CreditSense_Transaction(Account.Transactions))
  Next

  Return SummaryTables

End Function

Private Function CreditSense_TransactionOverviews(account As ISBankAccountEnquiryResponse_CreditSense_DownloadBankXMLAccount) As ISSummaryTables

  Dim ParentKey As String
  Dim ParentKeys() As String
  Dim Key As String
  Dim MonthlyAmount As Decimal
  Dim Overview As  ISBankAccountEnquiryResponse_CreditSense_DownloadBankXmlAccountOverview
  Dim OverviewItem As ISBankAccountEnquiryResponse_CreditSense_DownloadBankXmlAccountOverviewItem
  Dim OverviewItems As ISBankAccountEnquiryResponse_CreditSense_DownloadBankXmlAccountOverviewItems
  Dim OverviewItemByKey As ISBankAccountEnquiryResponse_CreditSense_DownloadBankXmlAccountOverviewItem
  Dim OverviewItemsByKey As ISBankAccountEnquiryResponse_CreditSense_DownloadBankXmlAccountOverviewItems
  Dim SubCategory As String
  Dim TotalAmount As Decimal
  Dim TotalInAmount As Decimal
  Dim TotalOutAmount As Decimal
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Initialise
  ParentKeys = {"Income", "Loans", "Outgoings"}
  SummaryTables = finBL.CreateSummaryTables()

  If Account.Overviews.Count = 0 Then
    SummaryTables.AddSummaryTableBlank("TransactionOverviewSummary", "Transaction Overview Summary", "No Transaction Overview Summaries found.", "TransactionOverviewSummary", 3)
  Else
    SummaryTables.AddSummaryTableBlank("TransactionOverviewSummary", "Transaction Overview Summary", "<div></div>", "TransactionOverviewSummary", 3)
    For Each Overview In account.Overviews
      For Each ParentKey In ParentKeys
        OverviewItems = account.GetItems(ParentKey, "")
        If OverviewItems.HasData Then
          ' Sub Headeng - Item Type
          SummaryTables.AddSummaryTableBlank(ParentKey, ParentKey, "<div></div>", "ItemType", 4)

          Key = ""
          For Each OverviewItem In OverviewItems
            If Key <> OverviewItem.Key Then
              Key = OverviewItem.Key
              OverviewItemsByKey = account.GetItems(ParentKey, Key)
              account.GetTotals(parentKey, Key, TotalAmount, TotalInAmount, TotalOutAmount, MonthlyAmount)

              SubCategory = ""
              If Len(OverviewItem.H2) > 0 Then
                SubCategory &= OverviewItem.H2
              Else
                SubCategory &= Key
              End If
              If Len(OverviewItem.H3) > 0 Then
                SubCategory &= " - " & OverviewItem.H3
              End If

              ' Sub heading
              SummaryTable = SummaryTables.CreateSummaryTableInformation("","",,,, TestMode)
              SummaryTable.Rows.AddText(SubCategory, iseSummaryTableCellClass.NormalBold)
              If Not OverviewItemsByKey.HasData Then SummaryTable.Rows.AddText("No Matches")
              SummaryTables.Add(SubCategory & "Heading", SummaryTable)

              If OverviewItemsByKey.HasData Then
                SummaryTable = SummaryTables.CreateSummaryTableTabular("","", 4, TestMode)
                With SummaryTable
                  ' Columns
                  With .Columns
                    .AddText("Description", 70)
                    .AddInteger("#", 4)
                    .AddText("Frequency", 20)
                    .AddInteger("Freq Amount", 15)
                    .AddCurrency("Total Amount", 14)
                    .AddCurrency("Total In", 14)
                    .AddCurrency("Total Out", 14)
                    .AddCurrency("Monthly", 14)
                  End With

                  ' Rows
                  With .Rows
                    For Each OverviewItemByKey In OverviewItemsByKey
                      If OverviewItemByKey.HasData Then
                        With .Add.Cells
                          .AddText(OverviewItemByKey.Description)
                          .AddInteger(OverviewItemByKey.Count)
                          .AddText(String.format("{0}{1}{2}", finbl.HtmlEncode(OverviewItemByKey.FrequencyDescription), vbNewLine, finbl.HtmlEncode(OverviewItemByKey.FrequencyWeekday)))
                          If OverviewItemByKey.FrequencyAmountRangeMin <> 0 OrElse OverviewItemByKey.FrequencyAmountRangeMax <> 0 Then
                            .AddText(String.format("{0}{1}{2}-{3}", finBL.FormatCurrency(OverviewItemByKey.FrequencyAmount, True, False), vbNewLine, Me.FormatCurrencyNoDecimal(OverviewItemByKey.FrequencyAmountRangeMin, True, False), Me.FormatCurrencyNoDecimal(OverviewItemByKey.FrequencyAmountRangeMax, True, False)))
                          Else
                            .AddCurrency(OverviewItemByKey.FrequencyAmount, True)
                          End If
                          .AddCurrency(OverviewItemByKey.TotalAmount, True)
                          .AddCurrency(OverviewItemByKey.TotalInAmount, True)
                          .AddCurrency(OverviewItemByKey.TotalOutAmount, True)
                          .AddCurrency(OverviewItemByKey.MonthlyAmount, True)
                        End With
                      End If
                    Next

                    ' Total Row
                    With .Add(iseSummaryTableRowClass.FooterBold).Cells
                      .AddCurrency(TotalAmount, True).ColSpan = 5
                      .AddCurrency(TotalInAmount, True)
                      .AddCurrency(TotalOutAmount, True)
                      .AddCurrency(MonthlyAmount, True)
                    End With
                  End With
                End With
                SummaryTables.Add(SubCategory, SummaryTable)
              End If
            End If
          Next
        Else
          SummaryTables.AddSummaryTableBlank(ParentKey, ParentKey, "No Subcategory Matches", "ItemType", 4)
        End If
      Next
    Next
  End If

  Return SummaryTables

End Function

Private Function CreditSense_Transaction(transactions As ISBankAccountEnquiryResponse_CreditSense_DownloadBankXMLAccountTransactions) As ISSummaryTables

  Dim CellClass As iseSummaryTableCellClass
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim Transaction As ISBankAccountEnquiryResponse_CreditSense_DownloadBankXMLAccountTransaction

  ' Initialise
  CellClass = iseSummaryTableCellClass.Normal
  SummaryTables = finBL.CreateSummaryTables()

  If transactions.Count = 0 Then
    SummaryTables.CreateSummaryTableBlank("Transactions", "No Transactions found.", "Transactions", 3)
  Else
    SummaryTable = SummaryTables.CreateSummaryTableTabular("Transactions", "Transactions",3, TestMode)
    With SummaryTable
      ' Columns
      With .Columns
        .AddDate("Date")
        .AddText("Description")
        .AddText("Category")
        .AddCurrency("Withdrawal", 15)
        .AddCurrency("Deposit", 15)
        .AddCurrency("Balance", 15)
      End With

      ' Rows
      With .Rows
        For Each Transaction In transactions
          ' Cell class
          If Transaction.TranBaseType = "credit" Then
            CellClass = iseSummaryTableCellClass.NormalBold
          Else
            CellClass = iseSummaryTableCellClass.Normal
          End If

          With .Add.Cells
            .AddDate(Transaction.TranDate).CellClass = CellClass
            .AddText(Transaction.CleanDesc).CellClass = CellClass
            .AddText(Transaction.Category).CellClass = CellClass

            ' Withdrawal/Deposit
            Select Case Transaction.TranBaseType
            Case "credit"
              .AddText("")
              .AddCurrency(Transaction.TranAmount, True).CellClass = CellClass
            Case "debit"
              .AddCurrency(Transaction.TranAmount, True).CellClass = CellClass
              .AddText("")
            Case Else
              .AddText("")
              .AddText("")
            End Select

            With .AddCurrency(Transaction.Balance, True)
              .CellClass = CellClass
              If Transaction.Balance < 0 Then
                .ForegroundColour = "red"
              End If
            End With
          End With
        Next
      End With
    End With
    SummaryTables.Add("Transactions", SummaryTable)
  End If

  Return SummaryTables

End Function

Public Function FormatCurrencyNoDecimal(value As Decimal,
                                        includeSymbol As Boolean,
                                        blankIfZero As Boolean) As String

  Dim CurrencyString As String

  CurrencyString = finbl.FormatCurrency(value, includeSymbol, blankIfZero)
  CurrencyString = CurrencyString.Substring(0, Len(CurrencyString) - 3)

  Return CurrencyString

End Function