' SummaryPage2_BankAccountEnquiryReport_CreditSense2
Option Explicit On
Option Strict On

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

' Version: 1.06 (19/10/2023)

' Usage: Bank Account Enquiry and Log forms
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.01  15/12/2020  ISS      J022868   Added ability to load existing Applications
'    1.02  10/03/2021  ISS      J025554   Added ability to extend Quick Link expiry
'    1.02  25/03/2021  ISS      J026004   Added ability to refresh an existing Bank Account Enquiry
'    1.03  23/03/2022  ISS      J027749   Version 2.2
'    1.04  21/09/2022  ISS      J029522   Add ServiceLogPk and ServiceLogBranchPk to Application Shortcut
'    1.05  19/05/2023  ISS      J031082   Supporting Documents handling enhanced
'    1.06  19/10/2023  ISS      J032176   New Centrelink / WINZ statuses
' #################################################################

'#Const "OutOfDateWarningDays",Integer,30,"Number of days before warning the Enquiry is out-of-date."
'#Const "ShowColourBackground",Boolean,False,"True=Show coloured background. False=Show Colour column."

' Constants
Private OutOfDateWarningDays As Integer = 30
Private ShowColourBackground As Boolean = False

' Special Constants
Const TestMode As Boolean = False

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

  Dim Response As ISBankAccountEnquiryResponse
  Dim ServiceLogs As ISServiceLogs

  ' Assume Success
  Main = True

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

  ' Get Service Logs
  Try
    Main = finBL.CreditBureau.GetBankAccountEnquiryServiceLogs(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 Bank Account Enquiry.")
    ElseIf ServiceLogs(0).RequestStatus <> iseAuditLogStatus.Success Then
      Main = False
      finBL.Error.ErrorBegin("Invalid Service Log. Initial Request was not successful.")
    Else
      Response = DirectCast(ServiceLogs(0).ExResponse, ISBankAccountEnquiryResponse)
    End If
  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("#314E9F9", "#97C1EF", "", "#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 Response.GetType()
    Case GetType(ISBankAccountEnquiryResponse_CreditSense2_CreateQuickLink)
      Me.CreatePage_CreditSense2_Application(ServiceLogs, response, HtmlSummaryPage2StringBuilder)
    Case GetType(ISBankAccountEnquiryResponse_CreditSense2_SearchApplications)
      Me.CreatePage_CreditSense2_Application(ServiceLogs, response, HtmlSummaryPage2StringBuilder)
    Case GetType(ISBankAccountEnquiryResponse_CreditSense2_RefreshApplication)
      Me.CreatePage_CreditSense2_Application(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_CreditSense2_Application(serviceLogs As ISServiceLogs,
                                                response As ISBankAccountEnquiryResponse,
                                                HtmlSummaryPage2StringBuilder As finHtmlSummaryPage2StringBuilder)

  Dim ResponseCreateQuickLink As ISBankAccountEnquiryResponse_CreditSense2_CreateQuickLink
  Dim ResponseExpireQuickLink As ISBankAccountEnquiryResponse_CreditSense2_ExpireQuickLink
  Dim ResponseGetApplicationData As ISBankAccountEnquiryResponse_CreditSense2_GetApplicationData
  Dim ResponseGetQuickLinkDetails As ISBankAccountEnquiryResponse_CreditSense2_GetQuickLinkDetails
  Dim ResponseRefreshApplication As ISBankAccountEnquiryResponse_CreditSense2_RefreshApplication
  Dim ResponseSearchApplications As ISBankAccountEnquiryResponse_CreditSense2_SearchApplications
  Dim ServiceLog As ISServiceLog
  Dim ServiceLog_SourceObjects As finServiceLogSourceObjects
  Dim ReportList As ISList

  ' Initialise
  ReportList = finBL.Runtime.CreateList()

  ' Find Responses
  For Each ServiceLog In serviceLogs
    If ServiceLog.ExResponse IsNot Nothing Then
      Select Case ServiceLog.ExResponse.GetType()
        Case GetType(ISBankAccountEnquiryResponse_CreditSense2_CreateQuickLink)
          ResponseCreateQuickLink = DirectCast(ServiceLog.ExResponse, ISBankAccountEnquiryResponse_CreditSense2_CreateQuickLink)
        Case GetType(ISBankAccountEnquiryResponse_CreditSense2_ExpireQuickLink)
          ResponseExpireQuickLink = DirectCast(ServiceLog.ExResponse, ISBankAccountEnquiryResponse_CreditSense2_ExpireQuickLink)
        Case GetType(ISBankAccountEnquiryResponse_CreditSense2_GetApplicationData)
          ResponseGetApplicationData = DirectCast(ServiceLog.ExResponse, ISBankAccountEnquiryResponse_CreditSense2_GetApplicationData)
        Case GetType(ISBankAccountEnquiryResponse_CreditSense2_GetApplicationReport)
          With DirectCast(servicelog.ExResponse, ISBankAccountEnquiryResponse_CreditSense2_GetApplicationReport)
            ReportList.Add(.Request_GetApplicationReport.ReportCode)
          End With
        Case GetType(ISBankAccountEnquiryResponse_CreditSense2_GetQuickLinkDetails)
          ResponseGetQuickLinkDetails = DirectCast(ServiceLog.ExResponse, ISBankAccountEnquiryResponse_CreditSense2_GetQuickLinkDetails)
        Case GetType(ISBankAccountEnquiryResponse_CreditSense2_RefreshApplication)
          ResponseRefreshApplication = DirectCast(ServiceLog.ExResponse, ISBankAccountEnquiryResponse_CreditSense2_RefreshApplication)
        Case GetType(ISBankAccountEnquiryResponse_CreditSense2_SearchApplications)
          ResponseSearchApplications = DirectCast(ServiceLog.ExResponse, ISBankAccountEnquiryResponse_CreditSense2_SearchApplications)
        Case GetType(ISBankAccountEnquiryResponse_CreditSense2_GetApplicationSupportingDocument)
          With DirectCast(servicelog.ExResponse, ISBankAccountEnquiryResponse_CreditSense2_GetApplicationSupportingDocument)
            ReportList.Add(.Request_GetApplicationSupportingDocument.SupportingDocumentText)
          End With  
      End Select
    End If
  Next

  ' Get Source Objects
  ServiceLog_SourceObjects = finBL.CreateServiceLogSourceObjects
  ServiceLog_SourceObjects.Load(serviceLogs(0))

  With HtmlSummaryPage2StringBuilder
     ' Heading
    If ServiceLog_SourceObjects.Client IsNot Nothing Then
      .AppendH1(ServiceLog_SourceObjects.Client.Name)
    ElseIf ServiceLog_SourceObjects.AccountAppApplicant IsNot Nothing Then
      .AppendH1(ServiceLog_SourceObjects.AccountAppApplicant.Name)
    ElseIf ResponseCreateQuickLink IsNot Nothing Then
      .AppendH1(String.Format("Reference - {0}", ResponseCreateQuickLink.Request_CreateQuickLink.ApplicationReference))
    ElseIf ResponseSearchApplications IsNot Nothing Then
      .AppendH1(String.Format("Reference - {0}", ResponseSearchApplications.Request_SearchApplications.ApplicationId))
    End If
    .AppendH2(String.Format("Bank Account Enquiry Report - {0}", response.ServiceName))

    .SummaryTablesAppend(Me.CreditSense_EnquiryDetails(serviceLogs, ServiceLog_SourceObjects, ResponseCreateQuickLink, ResponseGetQuickLinkDetails, ResponseSearchApplications, responseGetApplicationData, ResponseRefreshApplication, ReportList))
    .SummaryTablesAppend(Me.CreditSense_Alerts(serviceLogs, ResponseGetQuickLinkDetails, ResponseExpireQuickLink, ResponseSearchApplications, ResponseGetApplicationData))
    If ResponseGetApplicationData Is Nothing Then
      .SummaryTablesAppend(Me.CreditSense_History(serviceLogs))
    Else
      .SummaryTablesAppend(Me.CreditSense_DecisionPoints(ResponseGetApplicationData))
      .SummaryTablesAppend(Me.CreditSense_BankAccountSummary(ResponseGetApplicationData))
      .SummaryTablesAppend(Me.CreditSense_BankAccounts(serviceLogs, ResponseGetApplicationData))
    End If
End With

End Sub

Public Function CreditSense_Alerts(serviceLogs As ISServiceLogs,
                                   responseGetQuickLinkDetails As ISBankAccountEnquiryResponse_CreditSense2_GetQuickLinkDetails,
                                   responseExpireQuickLink As ISBankAccountEnquiryResponse_CreditSense2_ExpireQuickLink,
                                   responseSearchApplications As ISBankAccountEnquiryResponse_CreditSense2_SearchApplications,
                                   responseGetApplicationData As ISBankAccountEnquiryResponse_CreditSense2_GetApplicationData) As ISSummaryTables

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

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

  ' Overall Status (based upon Service Log)
  Select Case ServiceLogs(0).ResponseStatus
    Case iseServiceLogResponseStatus.Complete
      If responseGetApplicationData Is Nothing Then
        Warnings.AddWarning("Bank Account Enquiry has been completed but data has not been downloaded. Please Get the Report again.",,, isefinWarningLevel.Critical)
      End If

    Case iseServiceLogResponseStatus.Deleted
      Warnings.AddWarning("Bank Account Enquiry has been deleted.",,, isefinWarningLevel.Critical)

    Case iseServiceLogResponseStatus.Expired
      Warnings.AddWarning("Bank Account Enquiry has expired.",,, isefinWarningLevel.Critical)

    Case iseServiceLogResponseStatus.InProgress
      If responseExpireQuickLink IsNot Nothing Then
        Warnings.AddWarning("Bank Account Enquiry is not correctly deleted. Please try to Delete again.",,, isefinWarningLevel.Critical)
      End If
      If responseGetApplicationData IsNot Nothing Then
        Warnings.AddWarning("Bank Account Enquiry is not correctly completed. Please try to Get the Report again.",,, isefinWarningLevel.Critical)
      End If
      If responseGetQuickLinkDetails IsNot Nothing AndAlso responseGetQuickLinkDetails.Data.IsExpired Then
        Warnings.AddWarning("Quick Link has expired.",,, isefinWarningLevel.Critical)
      End If
  End Select

  ' Build Warning lists
  If responseGetApplicationData IsNot Nothing Then
    With responseGetApplicationData
      ' Out of Date
      If .Data.Accounts.Count > 0 Then
        Days = CInt(DateDiff(DateInterval.Day, .Data.Accounts(0).LastTransactionDate, 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 .Data.Accounts.Count = 0 Then
        Warnings.AddWarning("No Account information returned.",,, isefinWarningLevel.Critical)
      Else
        For Each Account In .Data.Accounts
          ' Balance
          If Account.BankCurrentBalance < 0 Then
            Warnings.AddWarning(String.Format("'{0}' Current Balance is overdrawn.", Account.AccountName),,, isefinWarningLevel.Critical, "#BankAccount_" & CStr(Account.AccountIndex))
          ElseIf Account.BankAvailableBalance < 0 Then
            Warnings.AddWarning(String.Format("'{0}' Available Balance is overdrawn.", Account.AccountName),,, isefinWarningLevel.Critical, "#BankAccount_" & CStr(Account.AccountIndex))
          End If

          If Account.DishonourCount > 0 Then
            Warnings.AddWarning(String.Format("'{0}' has had {1} dishonours.", Account.AccountName, Account.DishonourCount),,, isefinWarningLevel.Critical, "#BankAccount_" & CStr(Account.AccountIndex))
          End If
        Next
      End If
    End With
  End If

  ' Centrelink
  If finBL.CreditBureau.Service_CreditSense2.SupportsCentrelink AndAlso responseSearchApplications IsNot Nothing AndAlso responseSearchApplications.Data.Applications.Count <> 0 Then
    Select Case ServiceLogs(0).ResponseStatus
      Case iseServiceLogResponseStatus.Complete, iseServiceLogResponseStatus.InProgress
        Select Case responseSearchApplications.Data.Applications(0).CentrelinkStatus
          Case iseCreditBureau_CreditSense_ApplicationCentrelinkStatus.Success
            ' Success
          Case iseCreditBureau_CreditSense_ApplicationCentrelinkStatus.NotApplicable
            Warnings.AddWarning(finBL.CreditBureau.Service_CreditSense2.CentrelinkTerminology & " status is '" & responseSearchApplications.Data.Applications(0).CentrelinkStatusText & "' - not configured.",,, isefinWarningLevel.Medium)
          Case Else
            Warnings.AddWarning(finBL.CreditBureau.Service_CreditSense2.CentrelinkTerminology & " status is '" & responseSearchApplications.Data.Applications(0).CentrelinkStatusText & "'.",,, isefinWarningLevel.Critical)
        End Select
    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_BankAccounts(serviceLogs As ISServiceLogs,
                                          response As ISBankAccountEnquiryResponse_CreditSense2_GetApplicationData) As ISSummaryTables

  Dim Account As ISBankAccountEnquiryResponse_CreditSense2_DataAccount
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  For Each Account In response.Data.Accounts
    SummaryTable = SummaryTables.CreateSummaryTableInformation(String.Format("Summary: {0} - ({1})", Account.AccountName, Account.AccountNumber), "BankAccount_" & CStr(Account.AccountIndex), 2, , , TestMode)
    With SummaryTable
      .Align = "Left"
      .WidthHtml = "100%"
      .MaxWidthHtml = "500px"

      .AddRowCaptionText("Owner:", Account.AccountHolder)
      If StrComp(Account.AccountHolder, Account.SecondaryAccountHolder) <> 0 Then .AddRowCaptionText("Secondary Owner:", Account.SecondaryAccountHolder)
      .AddRowCaptionText("Bank:", Account.BankName)
      .AddRowCaptionText(finBL.SupportedCountries.CurrentSupportedCountry.Terminology(isefinCountryTerminology.BankSortCode) & ":", Account.AccountBSB)
      .AddRowCaptionText("Account Number:", Account.AccountNumber)
      .AddRowCaptionText("Account Name:", Account.AccountName)
      .AddRowCaptionText("Account Type:", finBL.Runtime.TextUtilities.ProperCase(Account.AccountType))
      If Account.MaxAmountOverdraft <> 0 Then
        .AddRowCaptionCurrency("Maximum Overdrawn:", -Account.MaxAmountOverdraft)
      End If
      .AddRowCaptionInteger("Days Overdrawn:", Account.DaysOverdraft, True, True)
      .AddRowCaptionInteger("Dishonour Count:", Account.DishonourCount, True, True)

      If Account.AccountCategory = iseCreditBureau_CreditSense_AccountCategory.Loans Then
        .AddRowCaptionText("Loan Type:", Account.LoanTypeRaw, True)
        .AddRowCaptionText("Loan Description:", Account.AccountName, True)
        .AddRowCaptionText("Loan Term:", Account.LoanTerm, True)
      End If

      If Account.AccountCategory = iseCreditBureau_CreditSense_AccountCategory.Credits Then
        .AddRowCaptionDate("Credit Card Due Date:", Account.CardDueDate, True)
      End If
    End With
    SummaryTables.Add("BankAccount_" & CStr(Account.AccountIndex), SummaryTable)

    SummaryTable = SummaryTables.CreateSummaryTableInformation("", "BankAccountSummary_" & CStr(Account.AccountIndex), 3,,, TestMode)
    With SummaryTable
      .Align = "Left"
      .WidthHtml = "100%"
      .MaxWidthHtml = "500px"

      .AddRowCaptionDateTime("Date as at:", Account.CreateDate)
      .AddRowCaptionText("Transaction Period:", finBL.FormatDateLong(Account.FirstTransactionDate) & " to " & finBL.FormatDateLong(Account.LastTransactionDate))
      .AddRowCaptionCurrency("Available Balance:", Account.BankAvailableBalance, True, True)
      .AddRowCaptionCurrency("Current Balance:", Account.BankCurrentBalance, True, True)
      .AddRowCaptionCurrency("1 Day Ago Balance:", Account.DayAgoBalance, True)

      If Account.AccountCategory = iseCreditBureau_CreditSense_AccountCategory.Loans Then
        .AddRowCaptionText("Loan Interest Type:", Account.LoanInterestRateTypeText, True)
        .AddRowCaptionPercentage("Loan Interest Rate:", Account.InterestRate, 2, True)
        .AddRowCaptionDate("Loan Next Due Date:", Account.DueDateLoan, True)
        .AddRowCaptionDate("Loan Last Pay Date:", Account.LastPaymentDate, True)
      End If

      If Account.AccountCategory = iseCreditBureau_CreditSense_AccountCategory.Credits Then
        .AddRowCaptionCurrency("Credit Card Limit:", Account.CardTotalCreditLine, True, True)
        .AddRowCaptionCurrency("Credit Card Minimum Payment:", Account.CardMinimumPayment, True, True)
      End If

      .AddRowCaptionCurrency("Deposits/Credits:", Account.TotalCredits, True)
      .AddRowCaptionCurrency("Withdrawals/Debits:", Account.TotalDebits, True)
    End With
    SummaryTables.Add("BankAccountSummary_" & CStr(Account.AccountIndex), SummaryTable)

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

    ' Transaction Summary
    SummaryTables.AppendSummaryTables(Me.CreditSense_Transactions(Account))
  Next

  Return SummaryTables

End Function

Private Function CreditSense_BankAccountSummary(response As ISBankAccountEnquiryResponse_CreditSense2_GetApplicationData) As ISSummaryTables

  Dim Account As ISBankAccountEnquiryResponse_CreditSense2_DataAccount
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  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
      .AddText("Category")
      .AddCurrency("Available Balance", 18)
      .AddCurrency("Current Balance", 16)
    End With

    ' Rows
    With .Rows
      For Each Account In response.Data.Accounts
        With .Add.Cells
          .AddText(Account.AccountName).Hyperlink = "#BankAccount_" & CStr(Account.AccountIndex)
          .AddText(Account.AccountHolder)
          .AddText(Account.AccountBSB)
          .AddText(Account.AccountNumber)
          .AddText(Account.AccountName)
          .AddText(finBL.Runtime.TextUtilities.ProperCase(Account.AccountType))
          .AddText(Account.AccountCategoryText)
          .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("")
        .AddText("")
        .AddCurrency(response.Data.Accounts.GetTotalAvailableBalance(), True, False)
        .AddCurrency(response.Data.Accounts.GetTotalCurrentBalance(), True, False)
      End With
    End With
  End With
  SummaryTables.Add("Accounts", SummaryTable)

  Return SummaryTables

End Function

Private Function CreditSense_DecisionPoints(response As ISBankAccountEnquiryResponse_CreditSense2_GetApplicationData) As ISSummaryTables

  Dim DecisionPoint As ISBankAccountEnquiryResponse_CreditSense2_DataDecisionPoint
  Dim Heading As String
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()
  Heading = ""

  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 response.Data.DecisionPoints
        If Not IsNumeric(DecisionPoint.DecisionPointGroupDescription) AndAlso StrComp(Heading, DecisionPoint.DecisionPointGroupDescription, CompareMethod.Text) <> 0 Then
          Heading = DecisionPoint.DecisionPointGroupDescription
          .Add(iseSummaryTableRowClass.FooterBold).Cells.AddText(DecisionPoint.DecisionPointGroupDescription).ColSpan = 3
        End If
        With .Add.Cells
          .AddText(DecisionPoint.DecisionPointId)
          .AddText(DecisionPoint.Title)
          .AddText(DecisionPoint.ScoreText)
        End With
      Next
    End With
  End With
  SummaryTables.Add("DecisionPoints", SummaryTable)

  Return SummaryTables

End Function

Private Function CreditSense_EnquiryDetails(serviceLogs As ISServiceLogs,
                                            serviceLog_SourceObjects As finServiceLogSourceObjects,
                                            responseCreateQuickLink As ISBankAccountEnquiryResponse_CreditSense2_CreateQuickLink,
                                            responseGetQuickLinkDetails As ISBankAccountEnquiryResponse_CreditSense2_GetQuickLinkDetails,
                                            responseSearchApplications As ISBankAccountEnquiryResponse_CreditSense2_SearchApplications,
                                            responseGetApplicationData As ISBankAccountEnquiryResponse_CreditSense2_GetApplicationData,
                                            responseRefreshApplication As ISBankAccountEnquiryResponse_CreditSense2_RefreshApplication,
                                            reportList As ISList) As ISSummaryTables

  Dim ApplicationId As String
  Dim ApplicationReference As String
  Dim ApplicationShortCut As ISApplicationShortcut
  Dim BranchPk As Integer
  Dim CanRefresh As Boolean
  Dim CostCentreResolved As finCostCentreResolved
  Dim Days As Integer
  Dim DocumentId As String
  Dim HasActions As Boolean
  Dim HasSupportingDocuments As Boolean
  Dim ReportCodeDescriptionListSchema1 As ISCodeDescriptionList
  Dim ReportCodeDescriptionListSchema2 As ISCodeDescriptionList
  Dim ReportItem As ISCodeDescriptionListItem
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim SupportingDocuments As ISCodeDescriptionList
  Dim TransferToken As String
  Dim Warnings As String
  Dim RefreshDetails() As String

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()
  ApplicationId = ""
  ApplicationReference = ""
  CanRefresh = True
  TransferToken = ""

  ' Branch
  If responseCreateQuickLink IsNot Nothing Then
    BranchPk = responseCreateQuickLink.Request_CreateQuickLink.BranchPk
  ElseIf responseSearchApplications IsNot Nothing Then
    BranchPk = responseSearchApplications.Request_SearchApplications.BranchPk
  End If

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

  ' Application Id
  If Len(ApplicationId) = 0 Then
    If responseGetApplicationData IsNot Nothing Then ApplicationId = responseGetApplicationData.Data.AppId
  End If
  If Len(ApplicationId) = 0 Then
    If responseSearchApplications IsNot Nothing Then ApplicationId = responseSearchApplications.Request_SearchApplications.ApplicationId
  End If
  If Len(ApplicationId) = 0 Then
    If responseSearchApplications IsNot Nothing AndAlso responseSearchApplications.Data.Applications.Count <> 0 Then ApplicationId = responseSearchApplications.Data.Applications(0).AppId
  End If
  If Len(ApplicationId) = 0 Then
    If responseRefreshApplication IsNot Nothing AndAlso responseRefreshApplication.Data.Count <> 0 Then ApplicationId = responseRefreshApplication.Data(0).AppId
  End If

  ' Application Reference
  If Len(ApplicationReference) = 0 Then
    If responseCreateQuickLink IsNot Nothing Then ApplicationReference = responseCreateQuickLink.Request_CreateQuickLink.ApplicationReference
  End If
  If Len(ApplicationReference) = 0 Then
    If responseGetApplicationData IsNot Nothing Then ApplicationReference = responseGetApplicationData.Data.AppReference
  End If
  If Len(ApplicationReference) = 0 Then
    If responseSearchApplications IsNot Nothing Then ApplicationReference = responseSearchApplications.Request_SearchApplications.ApplicationReference
  End If
  If Len(ApplicationReference) = 0 Then
    If responseRefreshApplication IsNot Nothing AndAlso responseRefreshApplication.Data.Count <> 0 Then ApplicationId = responseRefreshApplication.Data(0).AppRef
  End If

  ' Transfer Token
  If Len(TransferToken) = 0 Then
    If responseGetApplicationData IsNot Nothing Then TransferToken = responseGetApplicationData.Data.TransferToken
  End If

  ' Are there Supporting Documents
  HasSupportingDocuments = False
  If responseSearchApplications IsNot Nothing Then    
    ' Can't have supporting documents until there is a search application completed so that we have the application id
    SupportingDocuments = finBL.CreditBureau.Service_CreditSense2.GetSupportingDocuments(BranchPk)
    If SupportingDocuments.Count <> 0 Then
      If responseSearchApplications IsNot Nothing AndAlso responseSearchApplications.Service.SupportsCentrelink Then
        Select Case responseSearchApplications.Data.Applications(0).CentrelinkStatus
          Case iseCreditBureau_CreditSense_ApplicationCentrelinkStatus.Skipped, iseCreditBureau_CreditSense_ApplicationCentrelinkStatus.Failure, iseCreditBureau_CreditSense_ApplicationCentrelinkStatus.NotApplicable
          Case Else
            HasSupportingDocuments = True
        End Select      
      ElseIf responseCreateQuickLink IsNot Nothing AndAlso responseCreateQuickLink.Service.SupportsCentrelink Then
        Select Case responseCreateQuickLink.Request_CreateQuickLink.CentrelinkQuery
          Case iseCreditBureau_CreditSense_CentrelinkQuery.Ask, iseCreditBureau_CreditSense_CentrelinkQuery.Force
            HasSupportingDocuments = True
        End Select
      End If
    End If
  End If
  
  SummaryTable = SummaryTables.CreateSummaryTableInformation("", "EnquiryDetails",,,, TestMode)
  With SummaryTable
    If responseCreateQuickLink IsNot Nothing Then
      .AddRowCaptionUtcDateTimeWithTimeZone("Date:", responseCreateQuickLink.EnquiryUtcDate, finBL.Settings.TimeZoneId)
    ElseIf responseSearchApplications IsNot Nothing Then
      .AddRowCaptionUtcDateTimeWithTimeZone("Date:", responseSearchApplications.EnquiryUtcDate, finBL.Settings.TimeZoneId)
    End If

    If serviceLog_SourceObjects.Client IsNot Nothing Then
      With .Rows.AddCaptionCodeDescription("Client:", serviceLog_SourceObjects.Client.ClientId, serviceLog_SourceObjects.Client.Name)
        .Cells(1).HyperlinkSetFormShow("Clients", serviceLog_SourceObjects.Client.ClientId)
      End With
    ElseIf serviceLog_SourceObjects.AccountAppApplicant IsNot Nothing Then
      With .Rows.AddCaptionCodeDescription("Applicant:", serviceLog_SourceObjects.AccountApp.AccountAppId, String.Format("{0} ({1})", serviceLog_SourceObjects.AccountApp.Name, serviceLog_SourceObjects.AccountAppApplicant.Name))
        .Cells(1).HyperlinkSetFormShow("AccountApps", serviceLog_SourceObjects.AccountApp.AccountAppId, "Applicants")
      End With
    End If
    .AddRowCaptionText("Application Reference:", ApplicationReference)
    .AddRowCaptionText("Application Id:", ApplicationId)
    .AddRowCaptionText("Transfer Token:", TransferToken)

    If responseCreateQuickLink IsNot Nothing AndAlso responseCreateQuickLink.Service.SupportsCentrelink Then
      .AddRowCaptionText(finBL.CreditBureau.Service_CreditSense2.CentrelinkTerminology & " Option:", responseCreateQuickLink.Request_CreateQuickLink.CentrelinkQueryText)
    End If

    If responseGetApplicationData IsNot Nothing AndAlso responseGetApplicationData.Data IsNot Nothing Then
      .AddRowCaptionText("Data Report:", responseGetApplicationData.Data.ReportCodeDescription, False)
    End If

    ' Warnings
    Warnings = ""
    If responseCreateQuickLink IsNot Nothing Then
      Days = CInt(DateDiff(DateInterval.Day, responseCreateQuickLink.EnquiryUtcDate, finBL.TimeZoneFunctions.GetCurrentUtcDateTime()))
    ElseIf ResponseSearchApplications IsNot Nothing Then
      Days = CInt(DateDiff(DateInterval.Day, ResponseSearchApplications.EnquiryUtcDate, finBL.TimeZoneFunctions.GetCurrentUtcDateTime()))
    Else
      Days = 0
    End If
    If Days > OutOfDateWarningDays Then
       Warnings &= "{{Warning|This Report is " & CStr(Days) & " days old.}}"
    End If
    .TextAfter = Warnings
  End With
  SummaryTables.Add("EnquiryDetails", SummaryTable)

  ' Actions
  HasActions = False
  SummaryTable = SummaryTables.CreateSummaryTableInformation("Actions", "Actions",2,,, TestMode)

  ' Refresh
  If Len(serviceLogs(0).FollowupReference) <> 0 AndAlso Instr(serviceLogs(0).FollowupReference, "|", CompareMethod.Text) <> 0 Then
    RefreshDetails = Split(serviceLogs(0).FollowupReference, "|", ,CompareMethod.Text)
    If RefreshDetails.Length = 3 Then
      CanRefresh = False
      With SummaryTable
        .AddRowCaptionDateTime("Last Refreshed:", finBL.Runtime.TimeZoneUtilities.ConvertUtcToLocalDateTime(CDate(RefreshDetails(2))), True)
        .AddRowCaptionText("New Application Id:", RefreshDetails(1), True)
        '.AddRowCaptionText("New Service Log Pk:", RefreshDetails(0), True)
        With .Actions
          HasActions = True
          ApplicationShortcut = finBL.CreateApplicationShortcut()
          With ApplicationShortCut
            .Action = "FormShow"
            With .Parameters
              .SetString("form", "ServiceLog")
              .SetString("id", RefreshDetails(0))
              .SetString("page", "Bank Account Enquiry")
              .SetInteger("replyLogPk", ServiceLog_SourceObjects.ClientLog.Pk)
            End With
          End With
          .AddApplicationShortcut("FormShowServiceLog", "View Refresh Report", ApplicationShortCut).ShowInWebInterfaces = True
        End With
      End With
    End If
  End If
  
  Select Case ServiceLogs(0).ResponseStatus
    Case iseServiceLogResponseStatus.Complete
      If CanRefresh AndAlso CostCentreResolved.CreditSense.BankAccountEnquiryEnableBankAccountEnquiryRefresh Then
        ' Refresh
        If responseSearchApplications IsNot Nothing Then
          If responseSearchApplications.Data.Applications.Count <> 0 Then
            If responseSearchApplications.Data.Applications(0).RefreshAuthority.IsActive Then
              If DateDiff(DateInterval.Day, responseSearchApplications.Data.Applications(0).RefreshAuthority.RevokeUtcDate, finBL.TimeZoneFunctions.GetCurrentUtcDateTime()) > 0 Then
                With SummaryTable.Actions
                  HasActions = True
                  .AddApplicationShortcutUrl("Refresh", "Get Refresh Report", String.Format("App://Global?Type=BankAccountEnquiry.Refresh&ServiceLogPk={0}", ServiceLogs(0).Pk), True).ShowInWebInterfaces = True
                End With
              End If
            End If
          End If
        End If
      End If

    Case iseServiceLogResponseStatus.InProgress
      With SummaryTable
        HasActions = True
        If responseCreateQuickLink IsNot Nothing Then
          .Rows.AddCaptionText("Quick Link:", finBL.HtmlEncode(responseCreateQuickLink.Service.GetTokenUrl(responseCreateQuickLink.Token))).Cells(1).HyperlinkSetExternal(finBL.HtmlEncode(responseCreateQuickLink.Service.GetTokenUrl(responseCreateQuickLink.Token)))
        End If

        ' Actions
        With .Actions
          .AddApplicationShortcutUrl("Update", "Update", String.Format("App://Global?Type=BankAccountEnquiry.Update&ServiceLogPk={0}", ServiceLogs(0).Pk), True).ShowInWebInterfaces = True

          If responseCreateQuickLink IsNot Nothing Then
            .AddApplicationShortcutUrl("Extend", "Extend", String.Format("App://Global?Type=BankAccountEnquiry.Extend&ServiceLogPk={0}", ServiceLogs(0).Pk), True).ShowInWebInterfaces = True
            .AddApplicationShortcutUrl("Delete", "Delete", String.Format("App://Global?Type=BankAccountEnquiry.Delete&ServiceLogPk={0}", ServiceLogs(0).Pk), True).ShowInWebInterfaces = True

            ' Create Application Shortcut
            Select Case ServiceLog_SourceObjects.SourceType
              Case isefinServiceLogSourceType.AccountAppLog
                ApplicationShortcut = finBL.CreateApplicationShortcut()
                With ApplicationShortCut
                  .Action = "FormShow"
                  With .Parameters
                    .SetString("form", "DocumentCreateClient_AccountApp")
                    .SetString("id", ServiceLog_SourceObjects.AccountApp.AccountAppId)
                    .SetInteger("accountAppApplicantPk", ServiceLog_SourceObjects.AccountAppLog.AccountAppApplicantPk)
                    .SetInteger("replyLogPk", ServiceLog_SourceObjects.AccountAppLog.Pk)
                    .SetInteger("serviceLogPk", ServiceLogs(0).Pk)
                    .SetInteger("serviceLogBranchPk", BranchPk)
                  End With
                End With

              Case isefinServiceLogSourceType.ClientLog
                ApplicationShortcut = finBL.CreateApplicationShortcut()
                With ApplicationShortCut
                  .Action = "FormShow"
                  With .Parameters
                    .SetString("form", "DocumentCreateClient")
                    .SetString("id", ServiceLog_SourceObjects.Client.ClientId)
                    .SetInteger("replyLogPk", ServiceLog_SourceObjects.ClientLog.Pk)
                    .SetInteger("serviceLogPk", ServiceLogs(0).Pk)
                    .SetInteger("serviceLogBranchPk", BranchPk)
                  End With
                End With
            End Select

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

              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
          End If
        End With
      End With
  End Select
  If HasActions Then
    SummaryTables.Add("Actions", SummaryTable)
  End If
  
  ' Supplemental Reports
  If HasSupportingDocuments OrElse ServiceLogs(0).ResponseStatus = iseServiceLogResponseStatus.Complete Then
    SummaryTables.AddSummaryTableBlank("Reports", "Reports", "&nbsp;", "Reports", 2)
  End If
    
  Select Case ServiceLogs(0).ResponseStatus
    Case iseServiceLogResponseStatus.Complete
      ReportCodeDescriptionListSchema1 = finBL.CreditBureau.Service_CreditSense2.GetReportCodeAndDescriptions(BranchPk, "1")
      ReportCodeDescriptionListSchema2 = finBL.CreditBureau.Service_CreditSense2.GetReportCodeAndDescriptions(BranchPk, "2")

      If ReportCodeDescriptionListSchema1.Count <> 0 Then
        SummaryTable = SummaryTables.CreateSummaryTableinformation("", "Reports1", 3,,, TestMode)
        With SummaryTable
          .Align = "Left"
          .WidthHtml = "100%"
          .MaxWidthHtml = "500px"

          With .Columns
            .AddText("", 100).NoBreakChars = 100
          End With

          If ReportCodeDescriptionListSchema2.Count <> 0 Then
            With .Rows.Add()
              .Cells.Add("Schema version 1", iseSummaryTableCellClass.SectionHeading3)
            End With
          End If
          
          For Each ReportItem In ReportCodeDescriptionListSchema1
            With .Rows.Add()
              If reportList.Exists(ReportItem.Code, True) Then
                .Cells.AddWiki(Reportitem.Description & " ++{{icon|document}}++").HyperlinkSetGlobalAction("BankAccountEnquiry.SupplementalReport", String.Format("ServiceLogPk={0}&ReportKey={1}&Title={2}", ServiceLogs(0).Pk, ReportItem.Code, finBL.UrlEncode(reportitem.Code)))
              Else
                .Cells.AddWiki(Reportitem.Description & " ++{{icon|download}}++").HyperlinkSetGlobalAction("BankAccountEnquiry.SupplementalReport", String.Format("ServiceLogPk={0}&ReportKey={1}&Title={2}", ServiceLogs(0).Pk, ReportItem.Code, finBL.UrlEncode(reportitem.Code)))
              End If
            End With
          Next
        End With
        SummaryTables.Add("Reports1", SummaryTable)
      End If
    
      If ReportCodeDescriptionListSchema2.Count <> 0 Then
        SummaryTable = SummaryTables.CreateSummaryTableinformation("", "Reports2", 3,,, TestMode)
        With SummaryTable
          .Align = "Left"
          .WidthHtml = "100%"
          .MaxWidthHtml = "500px"

          With .Columns
            .AddText("", 100).NoBreakChars = 100
          End With

          If ReportCodeDescriptionListSchema1.Count <> 0 Then
            With .Rows.Add()
              .Cells.Add("Schema version 2", iseSummaryTableCellClass.SectionHeading3)
            End With
          End If
          
          For Each ReportItem In ReportCodeDescriptionListSchema2
            With .Rows.Add()
              If reportList.Exists(ReportItem.Code, True) Then
                .Cells.AddWiki(Reportitem.Description & " ++{{icon|document}}++").HyperlinkSetGlobalAction("BankAccountEnquiry.SupplementalReport", String.Format("ServiceLogPk={0}&ReportKey={1}&Title={2}", ServiceLogs(0).Pk, ReportItem.Code, finBL.UrlEncode(reportitem.Code)))
              Else
                .Cells.AddWiki(Reportitem.Description & " ++{{icon|download}}++").HyperlinkSetGlobalAction("BankAccountEnquiry.SupplementalReport", String.Format("ServiceLogPk={0}&ReportKey={1}&Title={2}", ServiceLogs(0).Pk, ReportItem.Code, finBL.UrlEncode(reportitem.Code)))
              End If
            End With
          Next
        End With
        SummaryTables.Add("Reports2", SummaryTable)
      End If
  End Select

  ' Supporting Document
  If HasSupportingDocuments Then
    SummaryTable = SummaryTables.CreateSummaryTableinformation("Supporting Documents", "SupportingDocuments", 3, 100,, TestMode)
    With SummaryTable
      With .Columns
        .AddText("", 100).NoBreakChars = 100
      End With

      For Each ReportItem In SupportingDocuments
        With .Rows.Add()
          If reportList.Exists(ReportItem.Code, True) Then
            .Cells.AddWiki(Reportitem.Description & " ++{{icon|document}}++").HyperlinkSetGlobalAction("BankAccountEnquiry.SupplementalReport", String.Format("ServiceLogPk={0}&ReportKey=SupportingDocument.{1}&Title={2}", ServiceLogs(0).Pk, ReportItem.Code, finBL.UrlEncode(ReportItem.Description)))
          Else
            .Cells.AddWiki(Reportitem.Description & " ++{{icon|download}}++").HyperlinkSetGlobalAction("BankAccountEnquiry.SupplementalReport", String.Format("ServiceLogPk={0}&ReportKey=SupportingDocument.{1}&Title={2}", ServiceLogs(0).Pk, ReportItem.Code, finBL.UrlEncode(ReportItem.Description)))
          End If
        End With
      Next
    End With
    SummaryTables.Add("SupportingDocuments", SummaryTable)
  End If
  
  Return SummaryTables

End Function

Private Function CreditSense_History(serviceLogs As ISServiceLogs) As ISSummaryTables

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

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  SummaryTable = SummaryTables.CreateSummaryTableTabular("History", "History",2, TestMode)
  With SummaryTable
    ' Columns
    With .Columns
      .AddText("Service Log")
      .AddDate("Date")
      .AddText("User")
      .AddText("Type")
      .AddText("Status")
      If finBL.CreditBureau.Service_CreditSense2.SupportsCentrelink Then .AddText(finBL.CreditBureau.Service_CreditSense2.CentrelinkTerminology)
    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 finBL.CreditBureau.Service_CreditSense2.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_TransactionOverviews(account As ISBankAccountEnquiryResponse_CreditSense2_DataAccount) As ISSummaryTables

  Dim H1Key As String
  Dim H1Keys As ISList
  Dim MonthlyAmount As Decimal
  Dim OverviewsByH1Key As ISBankAccountEnquiryResponse_CreditSense2_DataAccountOverviews
  Dim Overview As ISBankAccountEnquiryResponse_CreditSense2_DataAccountOverview
  Dim TotalAmount As Decimal
  Dim TotalInAmount As Decimal
  Dim TotalOutAmount As Decimal
  Dim strTemp As String
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Initialise
  H1Keys = account.GetOverviewsH1List()
  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 H1Key In H1Keys
      OverviewsByH1Key = account.GetOverviews(H1Key, "")
      account.GetTotalsFromOverviews(H1Key, "", TotalAmount, TotalInAmount, TotalOutAmount, MonthlyAmount)

      SummaryTable = SummaryTables.CreateSummaryTableTabular(H1Key, String.Format("TransactionOverviewSummary_{0}_{1}", Account.AccountIndex, H1Key), 4, TestMode)
      With SummaryTable
        ' Columns
        With .Columns
          If Not ShowColourBackground Then .AddText(" ") ' Icon
          .AddText("Category", 32)
          .AddText("Description", 70)
          .AddInteger("#", 4)
          .AddText("Frequency", 21)
          .AddInteger("Freq Amount", 14)
          .AddCurrency("Total Amount", 14)
          .AddCurrency("Total In", 14)
          .AddCurrency("Total Out", 14)
          .AddCurrency("Monthly", 14)
        End With

        ' Rows
        With .Rows
          For Each Overview In OverviewsByH1Key
            With .Add.Cells
              If ShowColourBackground Then
                .Row.BackgroundColour = Me.GetCategoryColour(Overview.H2, Overview.DisplayColour)
                .Row.ForegroundColour = Me.GetTextColour(Me.GetCategoryColour(Overview.H2, Overview.DisplayColour))
              Else
                .Add(Me.GetCategoryColourBlock(Overview.H2, Overview.DisplayColour))
              End If

              If StrComp(Overview.H1, Overview.H2, CompareMethod.Text) = 0 Then
                strTemp = ""
              Else
                strTemp = Overview.H2
              End If
              If len(Overview.SubCategory) <> 0 AndAlso StrComp(Overview.H2, Overview.SubCategory, CompareMethod.Text) <> 0 Then
                If Len(strTemp) = 0 Then
                  strTemp &= Overview.SubCategory
                Else
                  strTemp &= " (" & Overview.SubCategory & ")"
                End If
              End If
              With .AddText(strTemp)
                 .ElementId = String.Format("TransactionOverviewSummary_{0}_{1}", account.AccountIndex, Overview.GroupId)
              End With

              .AddText(Overview.Description)
              .AddInteger(Overview.Count)
              .AddText(String.format("{0}{1}{2}", finBL.HtmlEncode(Overview.FrequencyDescription), vbNewLine, finBL.HtmlEncode(Overview.FrequencyWeekday)))
              If Overview.FrequencyAmount <> 0 AndAlso Len(Overview.FrequencyAmountRange) <> 0 Then
                .AddText(finBL.FormatCurrency(Overview.FrequencyAmount, True, False) & vbNewLine & finBL.HtmlEncode(Overview.FrequencyAmountRange))
              ElseIf Overview.FrequencyAmount <> 0 Then
                .AddCurrency(Overview.FrequencyAmount, True)
              ElseIf Len(Overview.FrequencyAmountRange) <> 0 Then
                finBL.HtmlEncode(Overview.FrequencyAmountRange)
              Else
                .AddText("")
              End If
              'If Len(Overview.FrequencyAmountRange) <> 0  Then
              '  .AddText(finBL.FormatCurrency(Overview.FrequencyAmount, True, False) & vbNewLine & finBL.HtmlEncode(Overview.FrequencyAmountRange))
              'Else
              '  .AddCurrency(Overview.FrequencyAmount, True)
              'End If
              .AddCurrency(Overview.TotalAmount, True)
              .AddCurrency(Overview.TotalInAmount, True)
              .AddCurrency(Overview.TotalOutAmount, True)
              .AddCurrency(Overview.MonthlyAmount, True)
            End With
          Next

          ' Total Row
          With .Add(iseSummaryTableRowClass.FooterBold).Cells
            .AddText("")
            .AddText("")
            .AddText("")
            .AddText("")
            .AddText("")
            If Not ShowColourBackground Then.AddText("")
            .AddCurrency(TotalAmount, True)
            .AddCurrency(TotalInAmount, True)
            .AddCurrency(TotalOutAmount, True)
            .AddCurrency(MonthlyAmount, True)
          End With
        End With
      End With
      SummaryTables.Add(String.Format("TransactionOverviewSummary_{0}_{1}", Account.AccountIndex, H1Key), SummaryTable)
    Next
  End If

  Return SummaryTables

End Function

Private Function CreditSense_Transactions(account As ISBankAccountEnquiryResponse_CreditSense2_DataAccount) As ISSummaryTables

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

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

  If account.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
        If Not ShowColourBackground Then .AddText(" ") ' Icon
        .AddDate("Date")
        .AddText("Description")
'        .AddText("Group")
        .AddText("Category")
        .AddCurrency("Withdrawal", 15)
        .AddCurrency("Deposit", 15)
        .AddCurrency("Balance", 15)
      End With

      ' Rows
      With .Rows
        For Each Transaction In account.Transactions
          ' Cell class
          Select Case Transaction.BaseType
            Case iseCreditBureau_CreditSense_AccountTransactionBaseType.Credit
              CellClass = iseSummaryTableCellClass.NormalBold
            Case Else
              CellClass = iseSummaryTableCellClass.Normal
          End Select

          With .Add.Cells
            If ShowColourBackground Then
              .Row.BackgroundColour = Me.GetCategoryColour(Transaction.Category, Transaction.DisplayColour)
              .Row.ForegroundColour = Me.GetTextColour(Me.GetCategoryColour(Transaction.Category, Transaction.DisplayColour))
            Else
              With .Add(Me.GetCategoryColourBlock(Transaction.Category, Transaction.DisplayColour))
                .HyperlinkSetBookmark(String.Format("TransactionOverviewSummary_{0}_{1}", account.AccountIndex, Transaction.GroupId))
              End With
            End If

            .AddDate(Transaction.Date).CellClass = CellClass
            .AddText(Transaction.CleanDescription).CellClass = CellClass
'            .AddText(Transaction.GroupId).CellClass = CellClass
            .AddText(Transaction.Category).CellClass = CellClass
            Select Case Transaction.BaseType
              Case iseCreditBureau_CreditSense_AccountTransactionBaseType.Credit
                .AddText("")
                .AddCurrency(Transaction.Amount).CellClass = CellClass
              Case Else
                .AddCurrency(Transaction.Amount).CellClass = CellClass
                .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 GetCategoryColour(category As String,
                                  displayColour As String) As String

  If Len(displayColour) <> 0 Then Return displayColour

  Select Case UCase(category)
    ' Ignore
    Case "" : Return ""

    ' Income
    Case "SALARY" : Return "#C5F6C5"
    Case "BENEFITS" : Return "#C5F6C5"
    Case "OTHER INCOME" : Return "#C5F6C5"
    Case "NON-INCOME DEPOSITS": Return "#C5F6C5"

    ' Loans
    Case "SMALL AMOUNT LOANS" : Return "#FFC3C7"
    Case "SMALL AMOUNT REPAYMENTS": Return "#FFC3C7"
    Case "OTHER LOANS" : Return "#FFC3C7"
    Case "OTHER REPAYMENTS" : Return "#FFC3C7"

    ' Dishonours
    Case "DISHONOURS" :  Return "#CC99FF"

    ' Expenses
    Case "HOUSING AND UTILITIES" : Return "#95E0F1"
    Case "INTERNET TELEPHONE AND PAY TV" : Return "#95E0F1"
    Case "GROCERIES" : Return "#95E0F1"
    Case "RECREATION AND ENTERTAINMENT" : Return "#F5C77D"
    Case "CLOTHING AND PERSONAL CARE" : Return "#95E0F1"
    Case "MEDICAL AND HEALTH" : Return "#95E0F1"
    Case "TRANSPORT" : Return "#95E0F1"
    Case "EDUCATION AND CHILDCARE" : Return "#95E0F1"
    Case "INSURANCE" : Return "#95E0F1"
    Case "ATM" : Return "#95E0F1"
    Case "FEES" : Return "#95E0F1"
    Case "KNOWN EXPENSES" : Return "#95E0F1"
    Case "OTHER EXPENSES" : Return "#95E0F1"

    ' Other
    Case "TRANSFERS" : Return "#95E0F1"
  End Select

  ' Fallback Colour
  Return ""

End Function

Public Function GetCategoryColourBlock(category As String,
                                       displayColour As String) As String

  Dim Colour As String

  Colour = Me.GetCategoryColour(category, displayColour)

  If Len(Colour) = 0 Then
    Return "{{colourblock|white}}"
  Else
    Return "{{colourblock|" & Colour & "}}"
  End If

End Function

Public Function GetTextColour(backColour As String) As String

  If finBL.Runtime.ColourUtilities.HtmlColourIsDark(backColour) Then
    Return "White"
  Else
    Return "Black"
  End If

End Function