' SummaryPage2_BankAccountEnquiryReport_BankStatements
Option Explicit On
Option Strict On

' #################################################################
' BankStatements Bank Account Report Summary Page Script
'
' Version: 2.25 (27/08/2024)
'
' Usage: Bank Account Enquiry and Log forms
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    2.00  31/01/2017  ISS      J018448   Summary Page updated to version 2
'    2.01  09/03/2017  ISS      J018678   Summary Page now better highlights negative values
'    2.02  13/03/2017  ISS      J018620   Time zones
'    2.03  14/04/2017  ISS      J018881   Summary Page not displaying Centrelink details
'    2.04  10/05/2017  ISS      J018965   Added option to specify the number of days of data to retrieve
'    2.05  22/05/2017  ISS      J019063   Company Name omitted from report
'    2.05  08/06/2017  ISS      J018893   updated to version 20170401
'    2.06  22/11/2017  ISS      J019845   New data points available
'    2.07  31/10/2018  ISS      J020588   New Zealand Production URL updated
'    2.08  15/02/2019  ISS      J021872   Address data may be omitted
'    2.09  23/07/2019  ISS      J022178   Updated Summary Page to add Email and SMS buttons to send documents
'    2.11  13/03/2020  ISS      J023808   Links between sections such as accounts
'    2.12  28/05/2020  ISS      J023448   Support for BrokerFlow
'    2.13  18/06/2020  ISS      J024382   Renamed "Bank Statements" to "BankStatements"
'    2.14  15/07/2020  ISS      J024624   Updated Summary Page to use Cost Centre settings
'    2.15  22/01/2021  ISS      J025369   Added support for API Version
'    2.16  04/03/2021  ISS      J026100   Summary Page report displays extra cell in Account Summary table
'    2.16  04/03/2021  ISS      J026007   Debug Trace warnings when viewing the Summary Page
'    2.17  14/05/2021  ISS      J026575   Replace obsoleted properties and remove unused variables
'    2.18  07/10/2021  ISS      J027531   Top level account and decision metric objects
'    2.19  26/10/2021  ISS      J027637   Account date range for Alerts updated
'    2.20  14/02/2022  ISS      J028147   Account summary totals misaligned
'    2.21  17/03/2022  ISS      J025875   Multibank support
'    2.22  10/08/2022  ISS      J029338   BrokerFlow failing if data version is 20190901
'    2.23  21/09/2022  ISS      J029522   Add ServiceLogPk and ServiceLogBranchPk to Application Shortcut
'    2.24  08/03/2024  ISS      J033039   Retrieve Reports button not showing in finCC
'          22/03/2024  ISS      J032910   Add Score Models
'    2.25  27/08/2024  ISS      J034076   New data field - Period of Extracted Transactions
' #################################################################

'#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

' Properties
Private mVersion As String

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

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

  ' Validate
  If Main Then
    If ServiceLogs.Count = 0 Then
      Main = False
      finBL.Error.ErrorBegin("Invalid Service Log. Not a Bank Account Enquiry.")
    ElseIf ServiceLogs(0).RequestStatus <> iseAuditLogStatus.Success Then
      Main = False
      finBL.Error.ErrorBegin("Invalid Service Log. Initial Request was not successful.")
    ElseIf ServiceLogs(0).ExResponse Is Nothing Then
      Main = False
      finBL.Error.ErrorBegin("Invalid Service Log." & "Nothing")
    Else
      Select Case ServiceLogs(0).ExResponse.GetType()
        Case GetType(ISBankAccountEnquiryResponse_BankStatements_BrokerFlow)
          Response = DirectCast(ServiceLogs(0).ExResponse, ISBankAccountEnquiryResponse)
        Case GetType(ISBankAccountEnquiryResponse_BankStatements_RequestStatus)
          Response = DirectCast(ServiceLogs(0).ExResponse, ISBankAccountEnquiryResponse)
        Case Else
          Main = False
          finBL.Error.ErrorBegin("Invalid Service Log." & typename(ServiceLogs(0).ExResponse) )
      End Select
    End If
  End If

  ' Handle Events
  If Main Then
    Select Case eventId
      Case ""
        ' Main event, i.e., return main page content
        Main = CreatePage(ServiceLogs, 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
    ' 1B3B6D, C0C0C0, F2F2F2
    .HtmlHeaderInsertServiceReportTheme("#1B3B6D", "#D0D0D0", "", "#F2F2F2")

    ' 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_BankStatements_BrokerFlow)
      Me.CreatePage_BankStatement_BrokerFlow(ServiceLogs, DirectCast(Response, ISBankAccountEnquiryResponse_BankStatements_BrokerFlow), HtmlSummaryPage2StringBuilder)

    Case GetType(ISBankAccountEnquiryResponse_BankStatements_RequestStatus)
      Me.CreatePage_BankStatement(ServiceLogs, HtmlSummaryPage2StringBuilder)

    Case Else
      ' Error
      finBL.Error.ErrorBegin("Invalid Service Log." & typename(Response))
  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_BankStatement_BrokerFlow(serviceLogs As ISServiceLogs,
                                                responseResult As ISBankAccountEnquiryResponse_BankStatements_BrokerFlow,
                                                htmlSummaryPage2StringBuilder As finHtmlSummaryPage2StringBuilder)

  Dim AccountApp As finAccountApp
  Dim AccountAppApplicant As finAccountAppApplicant
  Dim AccountAppLog As finAccountAppLog
  Dim Accounts As ISBankAccountEnquiryResponse_BankStatements_DownloadDataAccounts
  Dim Bank As ISBankAccountEnquiryResponse_BankStatements_DownloadDataProvisoMultiBank
  Dim Client As finClient
  Dim ClientLog As finClientLog
  Dim ClientName As String
  Dim SubmissionUtcDate As Date

  ' Determine Version
  mVersion = ResponseResult.DataVersion

  ' 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)
          ClientName = AccountAppApplicant.Name
        Else
          ClientName = "Account Application Client not found."
        End If
      Else
        ClientName = "Account Application Client not found."
      End If

    Case "Client"
      Client = finBL.CreateClient()
      If Client.LoadPk(ServiceLogs(0).SourcePk) Then
        ClientName = Client.Name
      Else
        ClientName = "Client not found."
      End If

    Case "ClientLog"
      ClientLog = finBL.CreateClientLog
      If ClientLog.Load(ServiceLogs(0).SourcePk) Then
        Client = finBL.CreateClient()
        If Client.LoadPk(ClientLog.ClientPk) Then
          ClientName = Client.Name
        Else
          ClientName = "Client not found."
        End If
      Else
        ClientName = "Client not found."
      End If

    Case Else
      ClientName = "No Associated Client - Imported log"
  End Select

  With HtmlSummaryPage2StringBuilder
    ' Heading
    .AppendH1(ClientName)
    .AppendH2(String.Format("BrokerFlow Bank Account Enquiry Report - {0}", responseResult.ServiceName))

    .SummaryTablesAppend(Me.BankStatements_BrokerFlow_EnquiryDetails(responseResult, accountApp, AccountAppApplicant, Client, AccountAppLog, ClientLog))
    .SummaryTablesAppend(Me.BankStatements_BrokerFlow_Alerts(serviceLogs, responseResult))

    ' Accounts - dependent on v1 etc.
    Accounts = responseResult.Accounts
    Select Case mVersion
      Case "20170401"
        SubmissionUtcDate = responseResult.ProvisoReport.SubmissionUtcDate
        .SummaryTablesAppend(Me.BankStatements_Summary(Accounts, SubmissionUtcDate))

      Case "20190901"
        SubmissionUtcDate = responseResult.ProvisoMultiBankReport.SubmissionUtcDate
        For Each Bank In ResponseResult.ProvisoMultiBankReport.Banks
          .SummaryTablesAppend(Me.BankStatements_Summary(bank.Accounts, SubmissionUtcDate))
        Next
    End Select

    ' Account Summary
    If Accounts IsNot Nothing AndAlso Accounts.Count > 1 Then
      .SummaryTablesAppend(Me.BankStatements_AccountSummary(Accounts, responseResult.TotalBalanceAvailable, responseResult.TotalBalanceClosing))
    End If

    ' Decision Metrics
    If responseResult.DecisionMetrics IsNot Nothing AndAlso responseResult.DecisionMetrics.HasData() Then
      .SummaryTablesAppend(Me.BankStatements_DecisionMetrics(ResponseResult.DecisionMetrics))
    End If

    ' Show Bank Account information
    If Accounts IsNot Nothing AndAlso Accounts.Count <> 0 Then
      .SummaryTablesAppend(Me.BankStatements_Accounts(Accounts))
    End If

    ' Centrelink
    If ResponseResult.CentrelinkData IsNot Nothing AndAlso ResponseResult.CentrelinkData.HasData() Then
      .SummaryTablesAppend(Me.BankStatements_CentrelinkData(ResponseResult.CentrelinkData))
    End If
  End With

End Sub

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

  Dim AccountApp As finAccountApp
  Dim AccountAppApplicant As finAccountAppApplicant
  Dim AccountAppLog As finAccountAppLog
  Dim Accounts As ISBankAccountEnquiryResponse_BankStatements_DownloadDataAccounts
  Dim Bank As ISBankAccountEnquiryResponse_BankStatements_DownloadDataProvisoMultiBank
  Dim Client As finClient
  Dim ClientLog As finClientLog
  Dim ClientName As String
  Dim i As Integer
  Dim ResponseBrokerFlow As ISBankAccountEnquiryResponse_BankStatements_BrokerFlow
  Dim ResponseCreate As ISBankAccountEnquiryResponse_BankStatements_RequestStatus
  Dim ResponseDelete As ISBankAccountEnquiryResponse_BankStatements_RequestStatus
  Dim ResponseResult As ISBankAccountEnquiryResponse_BankStatements_DownloadData
  Dim ServiceLogFiles As ISServiceLog
  Dim SubmissionUtcDate As Date

  ' Get initial Request

  ' Get Responses
  ResponseCreate = DirectCast(serviceLogs(0).ExResponse, ISBankAccountEnquiryResponse_BankStatements_RequestStatus)
  For i = serviceLogs.Count - 1 To 0 Step -1
    If serviceLogs(i).RequestStatus = iseAuditLogStatus.Success Then
      Select Case serviceLogs(i).ExResponse.GetType()
        Case GetType(ISBankAccountEnquiryResponse_BankStatements_BrokerFlow)
          ResponseBrokerFlow  = DirectCast(serviceLogs(i).ExResponse, ISBankAccountEnquiryResponse_BankStatements_BrokerFlow)

        Case GetType(ISBankAccountEnquiryResponse_BankStatements_RequestStatus)
          ' Check if "Deleted"
          With DirectCast(serviceLogs(i).ExResponse, ISBankAccountEnquiryResponse_BankStatements_RequestStatus)
            If .Status = iseBankStatementsRequestStatus.Deleted Then
              ResponseDelete = DirectCast(serviceLogs(i).ExResponse, ISBankAccountEnquiryResponse_BankStatements_RequestStatus)
              Exit For
            End If
          End With

        Case GetType(ISBankAccountEnquiryResponse_BankStatements_DownloadData)
          If ResponseResult Is Nothing Then
            ResponseResult = DirectCast(serviceLogs(i).ExResponse, ISBankAccountEnquiryResponse_BankStatements_DownloadData)

            ' Determine Version
            mVersion = ResponseResult.DataVersion
          End If

        Case GetType(ISBankAccountEnquiryResponse_BankStatements_DownloadFiles)
          ServiceLogFiles = serviceLogs(i)
      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)
          ClientName = AccountAppApplicant.Name
        Else
          ClientName = "Account Application Client not found."
        End If
      Else
        ClientName = "Account Application Client not found."
      End If

    Case "Client"
      Client = finBL.CreateClient()
      If Client.LoadPk(ServiceLogs(0).SourcePk) Then
        ClientName = Client.Name
      Else
        ClientName = "Client not found."
      End If

    Case "ClientLog"
      ClientLog = finBL.CreateClientLog
      If ClientLog.Load(ServiceLogs(0).SourcePk) Then
        Client = finBL.CreateClient()
        If Client.LoadPk(ClientLog.ClientPk) Then
          ClientName = Client.Name
        Else
          ClientName = "Client not found."
        End If
      Else
        ClientName = "Client not found."
      End If

    Case Else
      ClientName = "No Associated Client - Imported log"
  End Select

  With HtmlSummaryPage2StringBuilder
    ' Heading
    .AppendH1(ClientName)
    .AppendH2(String.Format("Bank Account Enquiry Report - {0}", ResponseCreate.ServiceName))

    .SummaryTablesAppend(Me.BankStatements_EnquiryDetails(serviceLogs, ResponseCreate, ResponseDelete, ResponseResult, accountApp, AccountAppApplicant, Client, AccountAppLog, ClientLog))
    .SummaryTablesAppend(Me.BankStatements_Alerts(serviceLogs, ResponseCreate, ResponseResult, ResponseDelete))

    If ResponseResult Is Nothing Then
       ' Show Service Log history
      .SummaryTablesAppend(Me.BankStatements_History(serviceLogs, ResponseCreate))
    Else
      
      ' Accounts, etc. - dependent on v1 etc.
      Accounts = responseResult.Accounts
      Select Case mVersion
        Case "1.00"
          SubmissionUtcDate = Nothing

        Case "20170401"
          SubmissionUtcDate = ResponseResult.ProvisoReport.SubmissionUtcDate
          .SummaryTablesAppend(Me.BankStatements_Summary(Accounts, SubmissionUtcDate))

        Case "20190901"
          SubmissionUtcDate = ResponseResult.ProvisoMultiBankReport.SubmissionUtcDate
          For Each Bank In ResponseResult.ProvisoMultiBankReport.Banks
            .SummaryTablesAppend(Me.BankStatements_Summary(bank.Accounts, SubmissionUtcDate))
          Next
      End Select
      
      ' Score Models
      If ResponseResult.ScoreModels IsNot Nothing AndAlso ResponseResult.ScoreModels.HasData() Then
        .SummaryTablesAppend(Me.BankStatements_ScoreModels(ResponseResult.ScoreModels))
      End If
      
      ' Account Summary
      If Accounts IsNot Nothing AndAlso Accounts.Count > 1 Then
        .SummaryTablesAppend(Me.BankStatements_AccountSummary(Accounts, ResponseResult.TotalBalanceAvailable, ResponseResult.TotalBalanceClosing))
      End If

       ' Available Reports
      .SummaryTablesAppend(Me.BankStatements_AvailableReports(serviceLogs, ServiceLogFiles ,ResponseResult))

      ' Decision Metrics
      If ResponseResult.DecisionMetrics IsNot Nothing AndAlso ResponseResult.DecisionMetrics.HasData() Then
        .SummaryTablesAppend(Me.BankStatements_DecisionMetrics(ResponseResult.DecisionMetrics))
      End If

      ' Show Bank Account information
      If Accounts IsNot Nothing AndAlso Accounts.Count <> 0 Then
        .SummaryTablesAppend(Me.BankStatements_Accounts(Accounts))
      End If

      ' Centrelink
      If ResponseResult.Centrelink IsNot Nothing AndAlso ResponseResult.Centrelink.HasData() Then
        ' Version 1
        .SummaryTablesAppend(Me.BankStatements_Centrelink(ResponseResult.Centrelink))
      ElseIf ResponseResult.CentrelinkData IsNot Nothing AndAlso ResponseResult.CentrelinkData.HasData() Then
        ' Other Versions
        .SummaryTablesAppend(Me.BankStatements_CentrelinkData(ResponseResult.CentrelinkData))
      End If
    End If
  End With

End Sub

Private Function BankStatements_Accounts(accounts As ISBankAccountEnquiryResponse_BankStatements_DownloadDataAccounts) As ISSummaryTables

  Dim Account As ISBankAccountEnquiryResponse_BankStatements_DownloadDataAccount
  Dim AddressDetails As ISAddressDetails
  Dim i As Integer
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  i = 0
  For Each Account In accounts
    If Len(Account.AccountId) <> 0 Then
      SummaryTable = SummaryTables.CreateSummaryTableInformation(String.Format("{0} - {1}: {2}", Account.AccountId, Account.Institution, Account.AccountName), "Account" & Account.SummaryPageId, 2, 30, 30, TestMode)
      With SummaryTable
        If i <> 0 Then
          .Actions.AddUrl(String.Format("PreviousFrom{0}", Account.SummaryPageId), String.Format("Previous: {0}", accounts(i - 1).AccountName), String.Format("#Account{0}", accounts(i - 1).SummaryPageId), True)
        End If
        If i < accounts.Count - 1 Then
          .Actions.AddUrl(String.Format("NextFrom{0}", Account.SummaryPageId), String.Format("Next: {0}", accounts(i + 1).AccountName), String.Format("#Account{0}", accounts(i + 1).SummaryPageId), True)
        End If
        .Actions.AddUrl(String.Format("AnalysisCategoriesFrom{0}", Account.SummaryPageId), "Analysis Categories", String.Format("#AnalysisCategories{0}", Account.SummaryPageId), True)
        .Actions.AddUrl(String.Format("AccountTransactionsFrom{0}", Account.SummaryPageId), "Transactions", String.Format("#Account_{0}_Transactions", Account.SummaryPageId), True)
      End With
      SummaryTables.Add(Account.SummaryPageId & "Hyperlinks", SummaryTable)

      SummaryTable = SummaryTables.CreateSummaryTableInformation("", "", 3, 30, 30, TestMode)
      With SummaryTable
        .Align = "Left"
        .AddRowCaptionText("Holder:", Account.AccountHolder)
        Select Case mVersion
          Case "20170401","20190901"
            .AddRowCaptionText("Card Holder Relationship:", Account.CardholderRelationship, False)
            .AddRowCaptionText("Phone:", Account.Phone, False)
            .AddRowCaptionText("Email:", Account.Email, False)
            AddressDetails = Account.Address.ToAddressDetails()
            If AddressDetails.HasValue Then
              .AddRowCaptionAddressDetailsPhysical("Address:", AddressDetails, False)
            Else
              .AddRowCaptionText("Address:", Account.Address.Text, False)
            End If
        End Select
        .AddRowCaptionText("Institution:", Account.Institution)
        If Len(Account.AccountBSB)<> 0 Then .AddRowCaptionText("Account BSB:", Me.GetBSBText(Account.AccountBSB))
        .AddRowCaptionText("Account Number:", Account.AccountNumber)
        .AddRowCaptionDateTime("Date as at:", Account.DateEnd)

        If Len(Account.ErrorMessage) <> 0 Then .AddRowCaptionText("Error:", Account.ErrorMessage)
      End With
      SummaryTables.Add("Account" & Account.SummaryPageId, SummaryTable)

      SummaryTable = SummaryTables.CreateSummaryTableInformation("", Account.SummaryPageId & "Summary", 3, 30, 30, TestMode)
      With SummaryTable
        .Align = "Left"

        Select Case mVersion
          Case "1.00"
            .AddRowCaptionText("Period of Extracted Transactions:", String.Format("{0} to {1} ({2} days)", finBL.FormatDateLong(Account.DateStart), finBL.FormatDateLong(Account.DateEnd), DateDiff(DateInterval.Day, Account.DateStart, Account.DateEnd) + 1))
          Case "20170401","20190901"
            If Len(Account.PeriodOfExtractedTransactions) = 0 Then
              .AddRowCaptionText("Period of Extracted Transactions:", String.Format("{0} to {1} ({2} days)", finBL.FormatDateLong(Account.SearchPeriodStart), finBL.FormatDateLong(Account.SearchPeriodEnd), DateDiff(DateInterval.Day, Account.SearchPeriodStart, Account.SearchPeriodEnd) + 1))
            Else
              .AddRowCaptionText("Period of Extracted Transactions:", Account.PeriodOfExtractedTransactions, False)
            End If
        End Select
        .AddRowCaptionCurrency("Opening Balance:", Account.BalanceOpening, True)
        .AddRowCaptionCurrency("Deposits/Credits:", Account.TotalCredits, True)
        .AddRowCaptionCurrency("Withdrawals/Debits:", Account.TotalDebits, True)
        .AddRowCaptionCurrency("Closing Balance:", Account.BalanceClosing, True)
        .AddRowCaptionCurrency("Available Balance:", Account.BalanceAvailable, True)
        Select Case mVersion
          Case "1.00"
            .AddRowCaptionText("Balance Range:", String.Format("{0} to {1}", finBL.FormatCurrency(Account.BalanceMinimum, True), finBL.FormatCurrency(Account.BalanceClosing, True)))
          Case "20170401","20190901"
            .AddRowCaptionText("Balance Range:", String.Format("{0} to {1}", finBL.FormatCurrency(Account.MinDayEndBalance, True), finBL.FormatCurrency(Account.BalanceClosing, True)))
        End Select
        If Me.DisplayNegativeData(Account.AccountType) Then
          If Account.DaysInNegative = 0 Then
            .AddRowCaptionInteger("Days in Negative:", Account.DaysInNegative, True, True)
          Else
            .Rows.AddCaptionInteger("Days in Negative:", Account.DaysInNegative).Cells(1).ForegroundColour = "red"
          End If
        End If
      End With
      SummaryTables.Add(Account.SummaryPageId & "Summary", SummaryTable)

      ' Additional Information
      Select Case mVersion
        Case "20170401","20190901"
          SummaryTable = SummaryTables.CreateSummaryTableInformation("", Account.SummaryPageId & "Summary", 3, 30, 30, TestMode)
          With SummaryTable
            ' Additional Information
            .AddRowCaptionDate("Date Opened:", Account.OpenDate, False)
            .AddRowCaptionPercentage("Interest Rate:", Account.InterestRate, 2, True, False)
            .AddRowCaptionPercentage("Bonus Interest Rate:", Account.BonusInterestRate, 2, True, False)
            .AddRowCaptionPercentage("Debit Interest Rate:", Account.DebitInterestRate, 2, True, False)

            ' Loan Account Information
            .AddRowCaptionCurrency("Redraw Amount:", Account.Redraw, True, False)
            .AddRowCaptionDate("Next Payment Date:", Account.NextPaymentDate, False)
            .AddRowCaptionCurrency("Next Payment Amount:", Account.NextPaymentAmount, True, False)
            .AddRowCaptionDate("Loan Maturity Date:", Account.MaturityDate, False)
            .AddRowCaptionText("Interest Rate Type:", Account.InterestRateType, False)
            .AddRowCaptionText("Repayment Type:", Account.RepaymentType, False)
            .AddRowCaptionDate("Repayment Type Expiry Date:", Account.RepaymentTypeExpiryDate, False)
            .AddRowCaptionText("Contracted Loan Term:", Account.ContractedLoanTerm, False)
            .AddRowCaptionCurrency("Loan Service Fee:", Account.LoanServiceFee, False, False)
            .AddRowCaptionText("Remaining Loan Term:", Account.RemainingLoanTerm, False)
            .AddRowCaptionText("Interest Payment Frequency:", Account.InterestPaymentFrequency, False)
            .AddRowCaptionDate("Interest Rate Type Expiry Date:", Account.InterestRateTypeExpiryDate, False)
            .AddRowCaptionDate("Next Interest Payment:", Account.NextInterestPayment, False)

            ' Credit Account Information
            .AddRowCaptionCurrency("Credit Limit:", Account.CreditLimit, True, False)
            .AddRowCaptionDate("Next Payment Due Date:", Account.NextPaymentDue, False)
            .AddRowCaptionDate("Minimum Amount Due Date:", Account.MinimumAmountDueDate, False)
            .AddRowCaptionCurrency("Minimum Amount Due:", Account.MinimumAmountDue, True, False)
            .AddRowCaptionDate("Last Payment Date:", Account.LastPayment, False)
            
            ' Overdraft Information
            If Account.OverdraftLimit <> 0 OrElse Account.OverdraftUsed <> 0 OrElse Account.OverdraftRemaining <> 0 Then
              .AddRowCaptionCurrency("Overdraft Limit:", Account.OverdraftLimit, True, True)
              .AddRowCaptionCurrency("Overdraft Used:", Account.OverdraftUsed, True, True)
              .AddRowCaptionCurrency("Overdraft Remaining:", Account.OverdraftRemaining, True, True)
            End If
          End With
          If SummaryTable.Rows.Count <> 0 Then
            SummaryTables.Add(Account.SummaryPageId & "AdditionalInformation", SummaryTable)
          End If
      End Select

      ' Transaction Analysis
      Select Case mVersion
        Case "1.00"
          If Account.AnalysisGroups.Count <> 0 Then SummaryTables.AppendSummaryTables(Me.BankStatements_TransactionAnalysis(Account.AnalysisGroups))
        Case "20170401","20190901"
          If Account.AnalysisCategories.Count <> 0 Then SummaryTables.AppendSummaryTables(Me.BankStatements_StatementAnalysisCategories(Account.SummaryPageId, Account.AnalysisCategories))
      End Select

      ' Transaction Summary
      SummaryTables.AppendSummaryTables(Me.BankStatements_AccountTransactions(Account.SummaryPageId, Account.Transactions))
    End If
    i += 1
  Next

  Return SummaryTables

End Function

Private Function BankStatements_AccountSummary(accounts As ISBankAccountEnquiryResponse_BankStatements_DownloadDataAccounts,
                                               totalBalanceAvailable As Decimal,
                                               totalBalanceClosing As Decimal) As ISSummaryTables

  Dim Account As ISBankAccountEnquiryResponse_BankStatements_DownloadDataAccount
  Dim BsbText As String
  Dim HasBSBs As Boolean
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim TotalCredits As Decimal
  Dim TotalDebits As Decimal

  ' Initialise
  HasBSBs = accounts.HasBSBs
  SummaryTables = finBL.CreateSummaryTables()
  TotalCredits = 0
  TotalDebits = 0
  TotalDebits = 0

  SummaryTable = SummaryTables.CreateSummaryTableTabular("Account Summary", "AccountSummary",2, TestMode)
  With SummaryTable
    ' Columns
    With .Columns
      .AddText("Institution")
      .AddText("Account Details")
      .AddText("Account Name")
      .AddText("Holder")
      .AddCurrency("Available Balance", 16).NoBreakChars = 20
      .AddCurrency("Current Balance", 16).NoBreakChars = 20
      .AddCurrency("Total Credits", 16).NoBreakChars = 20
      .AddCurrency("Total Debits", 16).NoBreakChars = 20
      .AddInteger("Days in Negative", 16).NoBreakChars = 20

      'If HasBSBs Then .AddText("BSB")
    End With

    ' Rows
    With .Rows
      For Each Account In accounts
        With .Add.Cells
          TotalCredits += Account.TotalCredits
          TotalDebits += Account.TotalDebits
          BsbText = Me.GetBSBText(Account.AccountBSB)

          .AddText(Account.Institution)
          If Len(BsbText) = 0 Then
            .AddText(Account.AccountNumber).Hyperlink = "#Account" & Account.SummaryPageId
          Else
            .AddText(String.Format("{0}, {1}",BsbText, Account.AccountNumber)).Hyperlink = "#Account" & Account.SummaryPageId
          End If
          .AddText(Account.AccountName)
          .AddText(Account.AccountHolder)
          With .AddCurrency(Account.BalanceAvailable, True, False)
            If Account.BalanceAvailable < 0 Then .CellClass = iseSummaryTableCellClass.WarningBold
          End With
          With .AddCurrency(Account.BalanceClosing, True, False)
            If Account.BalanceClosing < 0 Then .CellClass = iseSummaryTableCellClass.WarningBold
          End With
          With .AddCurrency(Account.TotalCredits, True, False)
            If Account.TotalCredits < 0 Then .CellClass = iseSummaryTableCellClass.WarningBold
          End With
          With .AddCurrency(Account.TotalDebits, True, False)
            If Account.TotalDebits < 0 Then .CellClass = iseSummaryTableCellClass.WarningBold
          End With
          If Me.DisplayNegativeData(Account.AccountType) Then
            With .AddInteger(Account.DaysInNegative, False)
              If Account.DaysInNegative <> 0 Then .CellClass = iseSummaryTableCellClass.WarningBold
            End With
          End If
          'If HasBSBs Then .AddText(Me.GetBSBText(Account.AccountBSB))
        End With
      Next

      ' Total Row
      With .Add(iseSummaryTableRowClass.FooterBold).Cells
        .AddText("")
        .AddText("")
        .AddText("")
        .AddText("")
        With .AddCurrency(totalBalanceAvailable, True, False, iseSummaryTableCellTextAlign.Right)
          If totalBalanceAvailable < 0 Then .CellClass = iseSummaryTableCellClass.WarningBold
        End With
        With .AddCurrency(totalBalanceClosing, True, False, iseSummaryTableCellTextAlign.Right)
          If totalBalanceClosing < 0 Then .CellClass = iseSummaryTableCellClass.WarningBold
        End With
        With .AddCurrency(TotalCredits, True, False, iseSummaryTableCellTextAlign.Right)
          If TotalCredits < 0 Then .CellClass = iseSummaryTableCellClass.WarningBold
        End With
        With .AddCurrency(TotalDebits, True, False, iseSummaryTableCellTextAlign.Right)
          If TotalDebits < 0 Then .CellClass = iseSummaryTableCellClass.WarningBold
        End With
        .AddText("")
        'If HasBSBs Then .AddText("")
      End With
    End With
  End With
  SummaryTables.Add("AccountSummary", SummaryTable)

  Return SummaryTables

End Function

Private Function BankStatements_AccountTransactions(summaryPageId As String,
                                                    transactions As ISBankAccountEnquiryResponse_BankStatements_DownloadDataTransactions) As ISSummaryTables

  Dim CellClass As iseSummaryTableCellClass
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim TagColour As String
  Dim Transaction As ISBankAccountEnquiryResponse_BankStatements_DownloadDataTransaction
  'Dim LinkId As String

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

  If transactions.Count = 0 Then
    SummaryTables.CreateSummaryTableBlank("Transactions", "No Transactions found.", String.Format("Account_{0}_Transactions", summaryPageId), 3)
  Else
    SummaryTable = SummaryTables.CreateSummaryTableTabular("Transactions", String.Format("Account_{0}_Transactions", summaryPageId), 3, TestMode)
    With SummaryTable
      '.Actions.AddUrl(summaryPageId, "Top", "#" & summaryPageId, True)

      ' Columns
      With .Columns
        .AddDate("Date")
        .AddText(" ") ' Icon
        If transactions.HasTags Then .AddText("Tags")
        .AddText("Description")
        If transactions.HasNotes Then .AddText("Notes")
        .AddCurrency("Withdrawal")
        .AddCurrency("Deposit")
        .AddCurrency("Balance")
      End With

      ' Rows
      With .Rows
        For Each Transaction In transactions
          ' Cell class
          If InStr(Transaction.Tags, "Dishonours", CompareMethod.Text) <> 0 Then
            CellClass = iseSummaryTableCellClass.WarningBold
          ElseIf Transaction.Amount < 0 Then
            CellClass = iseSummaryTableCellClass.NormalBold
          Else
            CellClass = iseSummaryTableCellClass.Normal
          End If

          With .Add.Cells
            'LinkId = String.Format("{0}_{1}_{2}_{3}", summaryPageId, Format(Transaction.Date, "ddd dd MMM yyyy"), Transaction.Text, -Transaction.Amount)

            .AddDate(Transaction.Date).CellClass = CellClass
            .Add(Me.GetColourBlock(Transaction.Tags, Transaction.Amount))'.ElementId = LinkId
            If transactions.HasTags Then .AddText(Me.GetTagText(Transaction.Tags)).CellClass = CellClass
            .AddText(Transaction.Text).CellClass = CellClass
            If transactions.HasNotes Then .AddText(Transaction.Notes).CellClass = CellClass
            If Transaction.Amount < 0 Then
              .AddText("")
              .AddCurrency(-Transaction.Amount, True).CellClass = CellClass
            Else
              .AddCurrency(Transaction.Amount, True).CellClass = CellClass
              .AddText("")
            End If
            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(String.Format("Account_{0}_Transactions", summaryPageId), SummaryTable)
  End If

  Return SummaryTables

End Function

Private Function GetTagText(tag As String) As String

  Dim Tags() As String
  Dim Item As String

  GetTagText = ""

  Tags = tag.Split(New Char() {","c}, StringSplitOptions.RemoveEmptyEntries)

  For Each Item In Tags
    If StrComp(Item, "debit", CompareMethod.Text) = 0 Then
      ' Ignore Debit tag
    ElseIf StrComp(Item, "credit", CompareMethod.Text) = 0 Then
      ' Ignore Credit tag
    Else
      If Len(GetTagText) <> 0 Then GetTagText &= ", "
      GetTagText &= Item
    End If
  Next

  Return GetTagText

End Function

Public Function DisplayNegativeData(accountType As String) As Boolean

  ' List of account types that should not display things like days in negative as it makes no logical sense
  Select UCase(accountType)
    Case "CREDIT CARD"
      Return False
    Case Else
      Return True
  End Select
  
End Function

Public Function BankStatements_Alerts(serviceLogs As ISServiceLogs,
                                      responseCreate As ISBankAccountEnquiryResponse_BankStatements_RequestStatus,
                                      responseResult As ISBankAccountEnquiryResponse_BankStatements_DownloadData,
                                      responseDelete As ISBankAccountEnquiryResponse_BankStatements_RequestStatus) As ISSummaryTables

  Dim Account As ISBankAccountEnquiryResponse_BankStatements_DownloadDataAccount
  Dim Accounts As ISBankAccountEnquiryResponse_BankStatements_DownloadDataAccounts
  Dim DateEnd As Date
  Dim DateStart As Date
  Dim Days As Integer
  Dim ScoreModel As ISBankAccountEnquiryResponse_BankStatements_DownloadDataScoreModel
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim Warnings As finWarnings

  ' Create Objects
  SummaryTables = finBL.CreateSummaryTables ()
  Warnings = finBL.CreateWarnings
  ' Expired?
  If responseResult Is Nothing AndAlso responseDelete Is Nothing AndAlso responseCreate.Status <> iseBankStatementsRequestStatus.Complete Then
    If responseCreate.Expired Then
      Warnings.AddWarning("Request has expired.",,, isefinWarningLevel.Critical)
    ElseIf responseCreate.ExpiryDate <> Nothing Then
      If finBL.Runtime.TimeZoneUtilities.GetCurrentLocalDate() > responseCreate.ExpiryDate Then
        Warnings.AddWarning(String.Format("This Request expired on {0}.", finBL.FormatDateTimeLong(responseCreate.ExpiryDate, , , True)),,, isefinWarningLevel.Critical)
      Else
        Warnings.AddWarning(String.Format("This Request expires on {0}.", finBL.FormatDateTimeLong(responseCreate.ExpiryDate, , , True)),,, isefinWarningLevel.High)
      End If
    End If
  End If

  If responseResult IsNot Nothing Then
    ' 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
    DateEnd = responseResult.AccountsDateEnd
    DateStart =  responseResult.AccountsDateStart

    ' Warnings
    If DateStart = Nothing AndAlso DateEnd = Nothing Then
      Warnings.AddWarning("Could not determine Report Account date range.",,, isefinWarningLevel.Critical)
    End If
    If DateStart = Nothing AndAlso DateEnd <> Nothing Then
      Warnings.AddWarning("Could not determine Report Account earliest date.",,, isefinWarningLevel.Critical)
    End If
    If DateEnd = Nothing AndAlso DateStart <> Nothing Then
      Warnings.AddWarning("Could not determine Report Account latest date.",,, isefinWarningLevel.Critical)
    End If
    If DateEnd <> Nothing Then
      Days = CInt(DateDiff(DateInterval.Day, DateEnd, finBL.TimeZoneFunctions.GetCurrentLocalDateTime()))
      If Days > OutOfDateWarningDays Then
        Warnings.AddWarning(String.Format("This is an OLD Report, data is from {0} days ago.", Days),,, isefinWarningLevel.Critical)
      End If
    End If

    ' Information
    If DateStart <> Nothing AndAlso DateEnd <> Nothing Then
      Warnings.AddWarning(String.Format("Report Account date range from {0:d} to {1:d}.", DateStart, DateEnd),,, isefinWarningLevel.Low)
    End If

    ' Accounts - dependent on v1 etc.
    Accounts = responseResult.Accounts
    If Accounts Is Nothing Then
      Warnings.AddWarning("No Account information returned.",,, isefinWarningLevel.Critical)
    ElseIf Accounts IsNot Nothing AndAlso Accounts.Count = 0 Then
      Warnings.AddWarning("No Account information returned.",,, isefinWarningLevel.Critical)
    Else
      ' Duplicate accounts
      If Accounts.HasDuplicateAccounts Then
        Warnings.AddWarning("Duplicate Account information found.",,, isefinWarningLevel.High)
      End If

      For Each Account In Accounts
        With Account
          If Me.DisplayNegativeData(.AccountType) Then
            ' Balance
            If .BalanceClosing < 0 Then
              Warnings.AddWarning(String.Format("'{0} - {1}' Current Balance is negative.", .AccountId, .AccountName),,, isefinWarningLevel.Critical, "#" & .SummaryPageId)
            ElseIf .BalanceAvailable < 0 Then
              Warnings.AddWarning(String.Format("'{0} - {1}' Available Balance is negative.", .AccountId, .AccountName),,, isefinWarningLevel.Critical, "#" & .SummaryPageId)
            End If

            ' Days in Negative
            If .DaysInNegative = 0 Then
            ElseIf .DaysInNegative = 1 Then
              Warnings.AddWarning(String.Format("'{0} - {1}' has been in negative for 1 day.", .AccountId, .AccountName),,, isefinWarningLevel.Critical, "#" & .SummaryPageId)
            ElseIf .DaysInNegative > 0 Then
              Warnings.AddWarning(String.Format("'{0} - {1}' has been in negative for {2} days.", .AccountId, .AccountName, .DaysInNegative),,, isefinWarningLevel.Critical, "#" & .SummaryPageId)
            End If
          End If
        End With
      Next
    End If

    ' Centrelink
    If responseCreate.SupportsCentrelink AndAlso responseCreate.WithCentrelink Then
      Select Case mVersion
        Case "1.00"
          If Not responseResult.Centrelink.HasData Then
            Warnings.AddWarning("Centrelink Income Statement not included.",,, isefinWarningLevel.Critical)
          End If

        Case Else
          If responseResult.CentrelinkData IsNot Nothing AndAlso Not responseResult.CentrelinkData.HasData Then
            Warnings.AddWarning("Centrelink Income Statement not included.",,, isefinWarningLevel.Critical)
          End If
      End Select
    End If
  ElseIf responseDelete IsNot Nothing Then
    ' Deleted
    If ServiceLogs(0).ResponseStatus = iseServiceLogResponseStatus.Deleted Then
      Warnings.AddWarning("Request deleted.",,, isefinWarningLevel.Critical)
    Else
      Warnings.AddWarning("Request is not correctly deleted - please Delete the Request again.",,, isefinWarningLevel.Critical)
    End If
  Else
    ' Not yet completed
    Warnings.AddWarning("Report not yet downloaded.",,, isefinWarningLevel.Critical)
  End If

  ' Score Models
  If responseResult IsNot Nothing AndAlso responseResult.ScoreModels IsNot Nothing Then
    For Each ScoreModel In responseResult.ScoreModels
      If ScoreModel.HasScoreModelErrors Then
        Warnings.AddWarning("Errors reported for Score Model " & ScoreModel.ModelName & ".",,, isefinWarningLevel.High, "#" & ScoreModel.SummaryPageId)
      End If
    Next
  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

Public Function BankStatements_BrokerFlow_Alerts(serviceLogs As ISServiceLogs,
                                                 response As ISBankAccountEnquiryResponse_BankStatements_BrokerFlow) As ISSummaryTables

  Dim Account As ISBankAccountEnquiryResponse_BankStatements_DownloadDataAccount
  Dim Accounts As ISBankAccountEnquiryResponse_BankStatements_DownloadDataAccounts
  Dim DateEnd As Date
  Dim DateStart As Date
  Dim Days As Integer
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim Warnings As finWarnings

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

  If response IsNot Nothing Then
    ' Out of Date
    DateEnd = response.AccountsDateEnd
    DateStart =  response.AccountsDateStart

    ' Warnings
    If DateStart = Nothing AndAlso DateEnd = Nothing Then
      Warnings.AddWarning("Could not determine Report Account date range.",,, isefinWarningLevel.Critical)
    End If
    If DateStart = Nothing AndAlso DateEnd <> Nothing Then
      Warnings.AddWarning("Could not determine Report Account earliest date.",,, isefinWarningLevel.Critical)
    End If
    If DateEnd = Nothing AndAlso DateStart <> Nothing Then
      Warnings.AddWarning("Could not determine Report Account latest date.",,, isefinWarningLevel.Critical)
    End If
    If DateEnd <> Nothing Then
      Days = CInt(DateDiff(DateInterval.Day, DateEnd, finBL.TimeZoneFunctions.GetCurrentLocalDateTime()))
      If Days > OutOfDateWarningDays Then
        Warnings.AddWarning(String.Format("This is an OLD Report, data is from {0} days ago.", Days),,, isefinWarningLevel.Critical)
      End If
    End If

    ' Information
    If DateStart <> Nothing AndAlso DateEnd <> Nothing Then
      Warnings.AddWarning(String.Format("Report Account date range from {0:d} to {1:d}.", DateStart, DateEnd),,, isefinWarningLevel.Low)
    End If

    ' Accounts
    Accounts = response.Accounts
    If Accounts IsNot Nothing AndAlso Accounts.Count = 0 Then
      Warnings.AddWarning("No Account information returned.",,, isefinWarningLevel.Critical)
    Else
      For Each Account In Accounts
        With Account
          If Me.DisplayNegativeData(.AccountType) Then
            ' Balance
            If .BalanceClosing < 0 Then
              Warnings.AddWarning(String.Format("'{0} - {1}' Current Balance is negative.", .AccountId, .AccountName),,, isefinWarningLevel.Critical, "#" & .SummaryPageId)
            ElseIf .BalanceAvailable < 0 Then
              Warnings.AddWarning(String.Format("'{0} - {1}' Available Balance is negative.", .AccountId, .AccountName),,, isefinWarningLevel.Critical, "#" & .SummaryPageId)
            End If

            ' Days in Negative
            If .DaysInNegative = 0 Then
            ElseIf .DaysInNegative = 1 Then
              Warnings.AddWarning(String.Format("'{0} - {1}' has been in negative for 1 day.", .AccountId, .AccountName),,, isefinWarningLevel.Critical, "#" & .SummaryPageId)
            ElseIf .DaysInNegative > 0 Then
              Warnings.AddWarning(String.Format("'{0} - {1}' has been in negative for {2} days.", .AccountId, .AccountName, .DaysInNegative),,, isefinWarningLevel.Critical, "#" & .SummaryPageId)
            End If
          End If
        End With
      Next
    End If
  End If

  ' Add Alerts
  If Warnings.Count <> 0 Then
    SummaryTable = SummaryTables.CreateSummaryTableInformation("Alerts", "Alerts", 2)
    SummaryTable.TextAfter = Warnings.GetHtmlTemplateText()
    SummaryTables.Add("Alerts", SummaryTable)
  End If

  Return SummaryTables

End Function

Private Function BankStatements_BrokerFlow_AvailableReports(serviceLogs As ISServiceLogs,
                                                            serviceLogFiles As ISServiceLog,
                                                            response As ISBankAccountEnquiryResponse_BankStatements_BrokerFlow) As ISSummaryTables

  Dim Filename As String
  Dim i As Integer
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim ZipArchive As ISZipArchive
  Dim ZipBytes As Byte()

  ' Initialise
  i = 1
  SummaryTables = finBL.CreateSummaryTables()

  SummaryTable = SummaryTables.CreateSummaryTableInformation("Available Reports", "AvailableReports", 2,10,, TestMode)
  With SummaryTable
    ' Reports
    If ServiceLogFiles Is Nothing Then
      .Actions.AddApplicationShortcutUrl("RetrieveReports", "Retrieve Reports", String.Format("App://Global?Type=BankAccountEnquiry.SupplementalReport&ServiceLogPk={0}&ReportKey=Bank.Reports&Title=Reports&ShowReport=False", ServiceLogs(0).Pk), True).ShowInWebInterfaces = True
    Else
      ' Already Downloaded
      .Actions.AddApplicationShortcutUrl("OpenalldownloadedReports", "Open all downloaded Reports", String.Format("App://Global?Type=ServiceLog.ZipData&ServiceLogPk={0}", ServiceLogFiles.Pk), True).ShowInWebInterfaces = True

      If finBL.CreditBureau.GetBankAccountEnquirySupplementalReport(ServiceLogFiles.Pk, "Bank.Reports", "", "", False, ZipBytes) Then
        If finBL.Runtime.CompressionUtilities.ZipArchiveOpenFromByteArray(ZipBytes, ZipArchive) Then
          For Each Filename In ZipArchive.GetEntriesList()
            With .Rows.AddCaptionText(String.Format("Report {0}:", i), finBL.HtmlEncode(Filename))
              .Cells(1).HyperlinkSetGlobalAction("ServiceLog.ZipData", String.Format("ServiceLogPk={0}&Entry={1}", ServiceLogFiles.Pk, finBL.UrlEncode(Filename)))
            End With
            i += 1
          Next
        End If
      End If
    End If
  End With
  SummaryTables.Add("OtherOptions", SummaryTable)

  Return SummaryTables

End Function

Private Function BankStatements_AvailableReports(serviceLogs As ISServiceLogs,
                                                 serviceLogFiles As ISServiceLog,
                                                 responseResult As ISBankAccountEnquiryResponse_BankStatements_DownloadData) As ISSummaryTables

  Dim Filename As String
  Dim i As Integer
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim ZipArchive As ISZipArchive
  Dim ZipBytes As Byte()

  ' Initialise
  i = 1
  SummaryTables = finBL.CreateSummaryTables()

  SummaryTable = SummaryTables.CreateSummaryTableInformation("Available Reports", "AvailableReports", 2,10,, TestMode)
  With SummaryTable
    ' Centrelink
    Select Case mVersion
      Case "1.00"
        If responseResult.Centrelink.HasData() Then
          .Actions.AddUrl("CentrelinkIncomeSummary", "Centrelink Income Summary", "#Centrelink", True)
        End If

      Case Else
        If responseResult.CentrelinkData IsNot Nothing AndAlso responseResult.CentrelinkData.HasData() Then
          .Actions.AddUrl("CentrelinkIncomeSummary", "Centrelink Income Summary", "#Centrelink", True)
        End If
    End Select

    ' Reports
    If ServiceLogFiles Is Nothing Then
      .Actions.AddApplicationShortcutUrl("RetrieveReports", "Retrieve Reports", String.Format("App://Global?Type=BankAccountEnquiry.SupplementalReport&ServiceLogPk={0}&ReportKey=Bank.Reports&Title=Reports&ShowReport=False", ServiceLogs(0).Pk), True).ShowInWebInterfaces = True
    Else
      ' Already Downloaded
      .Actions.AddApplicationShortcutUrl("OpenalldownloadedReports", "Open all downloaded Reports", String.Format("App://Global?Type=ServiceLog.ZipData&ServiceLogPk={0}", ServiceLogFiles.Pk), True).ShowInWebInterfaces = True

      If finBL.CreditBureau.GetBankAccountEnquirySupplementalReport(ServiceLogFiles.Pk, "Bank.Reports", "", "", False, ZipBytes) Then
        If finBL.Runtime.CompressionUtilities.ZipArchiveOpenFromByteArray(ZipBytes, ZipArchive) Then
          For Each Filename In ZipArchive.GetEntriesList()
            With .Rows.AddCaptionText(String.Format("Report {0}:", i), finBL.HtmlEncode(Filename))
              .Cells(1).HyperlinkSetGlobalAction("ServiceLog.ZipData", String.Format("ServiceLogPk={0}&Entry={1}", ServiceLogFiles.Pk, finBL.UrlEncode(Filename)))
            End With
            i += 1
          Next
        End If
      End If
    End If
  End With
  SummaryTables.Add("OtherOptions", SummaryTable)

  Return SummaryTables

End Function

Private Function BankStatements_Centrelink(centrelink As ISBankAccountEnquiryResponse_BankStatements_DownloadDataCentrelink) As ISSummaryTables

  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  SummaryTables.AddSummaryTableBlank("Centrelink", "Centrelink Income Summary", "<div/>", "Centrelink", 2)

  SummaryTable = SummaryTables.CreateSummaryTableInformation("Summary", , 3, , , TestMode)
  With SummaryTable
    .AddRowCaptionText("Name:", centrelink.AccountHolder, True)
    .AddRowCaptionText("CRN:", centrelink.CRN, False)
    .AddRowCaptionText("Activity Dates:", String.Format("{0} to {1} ({2} days)", finBL.FormatDateLong(centrelink.DateStart), finBL.FormatDateTime(centrelink.DateEnd, True, True, True), DateDiff(DateInterval.Day, centrelink.DateStart, centrelink.DateEnd)))
  End With
  SummaryTables.Add("CentrelinkSummary", SummaryTable)

  ' Transaction Analysis
  If centrelink.AnalysisGroups IsNot Nothing Then SummaryTables.AppendSummaryTables(Me.BankStatements_TransactionAnalysis(centrelink.AnalysisGroups))

  ' Transaction Summary
  If centrelink.Transactions IsNot Nothing Then SummaryTables.AppendSummaryTables(Me.BankStatements_CentrelinkTransactions(centrelink.Transactions))

  Return SummaryTables

End Function

Private Function BankStatements_CentrelinkData(centrelink As ISBankAccountEnquiryResponse_BankStatements_DownloadDataCentrelinkData) As ISSummaryTables

  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  SummaryTables.AddSummaryTableBlank("Centrelink", "Centrelink Income Summary", "<div/>", "Centrelink", 2)

  SummaryTable = SummaryTables.CreateSummaryTableInformation("Summary", , 3, , , TestMode)
  With SummaryTable
    .AddRowCaptionText("Name:", centrelink.AccountHolder, True)
    .AddRowCaptionText("Address:", centrelink.Address, False)
    .AddRowCaptionText("CRN:", centrelink.CRN, False)
    .AddRowCaptionDate("Date of Birth:", centrelink.DateofBirth, False)
    .AddRowCaptionText("Gender:", centrelink.Gender, False)
    .AddRowCaptionAddressDetailsPhysical("Address:", centrelink.ToAddressDetails(), False)
  End With
  SummaryTables.Add("CentrelinkSummary", SummaryTable)

  ' Summary
  If centrelink.Summaries IsNot Nothing Then SummaryTables.AppendSummaryTables(Me.BankStatements_CentrelinkDataSummaries(centrelink.Summaries))

  ' Transaction Summary
  If centrelink.Payments IsNot Nothing Then SummaryTables.AppendSummaryTables(Me.BankStatements_CentrelinkDataPayments(centrelink.Payments))

  Return SummaryTables

End Function

Private Function BankStatements_CentrelinkDataPayments(payments As ISBankAccountEnquiryResponse_BankStatements_DownloadDataCentrelinkDataPayments) As ISSummaryTables

  Dim Payment As ISBankAccountEnquiryResponse_BankStatements_DownloadDataCentrelinkDataPayment
  Dim Part As ISBankAccountEnquiryResponse_BankStatements_DownloadDataCentrelinkDataPaymentPart
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  If payments.Count = 0 Then
    SummaryTables.AddSummaryTableBlank("CentrelinkPayments", "Payments", "No Payments found.", "CentrelinkPayments", 3)
  Else
    SummaryTable = SummaryTables.CreateSummaryTableTabular("Payments", "CentrelinkPayments", 3, TestMode)
    With SummaryTable
      ' Columns
      With .Columns
        .AddText(" ", 1)
        .AddDate("Date")
        .AddText("Description")
        .AddCurrency("Breakdown")
        .AddCurrency("Amount")
      End With

      ' Rows
      With .Rows
        For Each Payment In payments
          With .Add(iseSummaryTableRowClass.NormalBold).Cells
            .Add(Me.GetColourBlock(Payment.Description, -Payment.Amount))
            .AddDate(Payment.Date)
            .AddText(Payment.Description)
            .AddText("")
            .AddCurrency(Payment.Amount)
          End With
          For Each Part In Payment.PaymentBreakdown
            With .Add().Cells
              .AddText("")
              .AddText("")
              .AddText("    " & Part.Description)
              If Part.IsDeduction Then
                .AddCurrency(-Part.Amount)
              Else
                .AddCurrency(Part.Amount)
              End If
              .AddText("")
            End With
          Next
        Next
      End With
    End With
    SummaryTables.Add("CentrelinkPayments", SummaryTable)
  End If

  Return SummaryTables

End Function

Private Function BankStatements_CentrelinkDataSummaries(summaries As ISBankAccountEnquiryResponse_BankStatements_DownloadDataCentrelinkDataSummaries) As ISSummaryTables

  Dim Summary As ISBankAccountEnquiryResponse_BankStatements_DownloadDataCentrelinkDataSummary
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  If summaries.Count = 0 Then
    SummaryTables.AddSummaryTableBlank("CentrelinkSummary", "Summary", "No Transaction Analysis found.", "CentrelinkSummary", 3)
  Else
    SummaryTable = SummaryTables.CreateSummaryTableTabular("Summary", "CentrelinkSummary", 3, TestMode)
    With SummaryTable
      ' Columns
      With .Columns
        .AddText(" ", 1)
        .AddText("Type", 30)
        .AddInteger("Transactions", 6)
        .AddCurrency("Total", 15)
        .AddCurrency("Monthly Avg", 15)
        .AddCurrency("Avg Value", 15)
        .AddDate("Dates")
        .AddCurrency("Values", 15)
        .AddText("Regular", 3)
        .AddText("Frequency", 8)
        .AddText("Payment Day", 8)
      End With

      ' Rows
      With .Rows
        For Each Summary In summaries
          With .Add.Cells
            .Add(Me.GetColourBlock(Summary.Type, -Summary.MaxValue))
            .AddText(Summary.Type)
            .AddInteger(Summary.TransactionCount)
            .AddCurrency(Summary.TotalValue, True)
            .AddCurrency(Summary.MonthAvg, True)
            .AddCurrency(Summary.AvgValue, True)
            If Summary.FirstTransaction = Summary.LastTransaction Then
              .AddDate(Summary.FirstTransaction)
            Else
              .AddText(String.Format("{0} " & vbNewLine & "to {1}", finBL.FormatDateLong(Summary.LastTransaction), finBL.FormatDateLong(Summary.FirstTransaction)))
            End If
            If Summary.MinValue = Summary.MaxValue Then
              .AddCurrency(Summary.MinValue, True)
            Else
              .AddText(String.Format("{0} " & vbNewLine & "to {1}", finBL.FormatCurrency(Summary.MinValue, True), finBL.FormatCurrency(Summary.MaxValue, True)))
            End If
            .AddTick(Summary.PeriodIsRegular)
            If Summary.Period = 0 Then
              .AddText("")
            Else
              .AddText(String.Format("{0} days", finBL.Runtime.NumberUtilities.RoundDouble(Summary.Period, 0)))
            End If
            .AddText(Summary.PaymentDay)
          End With
        Next
      End With
    End With
    SummaryTables.Add("CentrelinkSummary", SummaryTable)
  End If

  Return SummaryTables

End Function

Private Function BankStatements_CentrelinkTransactions(transactions As ISBankAccountEnquiryResponse_BankStatements_DownloadDataTransactions) As ISSummaryTables

  Dim CellClass As iseSummaryTableCellClass
  Dim HasNotes As Boolean
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim Transaction As ISBankAccountEnquiryResponse_BankStatements_DownloadDataTransaction

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  If transactions.Count = 0 Then
    SummaryTables.AddSummaryTableBlank("CentrelinkTransactions", "Transactions", "No Transactions found.", "CentrelinkTransactions", 3)
  Else
    ' Get Flags
    HasNotes = transactions.HasNotes

    SummaryTable = SummaryTables.CreateSummaryTableTabular("Transactions", "CentrelinkTransactions", 3, TestMode)
    With SummaryTable
      ' Columns
      With .Columns
        .AddText(" ", 1)
        .AddDate("Date")
        .AddText("Description")
        If HasNotes Then .AddText("Notes")
        .AddCurrency("Withdrawal")
        .AddCurrency("Deposit")
      End With

      ' Rows
      With .Rows
        For Each Transaction In transactions
          ' Row class
          If InStr(Transaction.Tags, "Dishonours", CompareMethod.Text) <> 0 Then
            CellClass = iseSummaryTableCellClass.WarningBold
          ElseIf Transaction.Amount < 0 Then
            CellClass = iseSummaryTableCellClass.NormalBold
          Else
            CellClass = iseSummaryTableCellClass.Normal
          End If

          With .Add.Cells
            .Add(Me.GetColourBlock(Transaction.Text, Transaction.Amount))
            .AddDate(Transaction.Date).CellClass = CellClass
            .AddText(Transaction.Text).CellClass = CellClass
            If HasNotes Then .AddText(Transaction.Notes).CellClass = CellClass
            If Transaction.Amount < 0 Then
              .AddText("").CellClass = CellClass
              .AddCurrency(-Transaction.Amount).CellClass = CellClass
            Else
              .AddCurrency(Transaction.Amount).CellClass = CellClass
              .AddText("").CellClass = CellClass
            End If
          End With
        Next
      End With
    End With
    SummaryTables.Add("CentrelinkTransactions", SummaryTable)
  End If

  Return SummaryTables

End Function

Private Function BankStatements_DecisionMetrics(decisionMetrics As ISBankAccountEnquiryResponse_BankStatements_DownloadDataDecisionMetrics) As ISSummaryTables

  Dim DecisionMetric As ISBankAccountEnquiryResponse_BankStatements_DownloadDataDecisionMetric
  Dim HasDescriptors As Boolean
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Initialise
  HasDescriptors = decisionMetrics.HasDescriptors
  SummaryTables = finBL.CreateSummaryTables()

  SummaryTable = SummaryTables.CreateSummaryTableTabular("Decision Metrics", "DecisionMetrics", 2, TestMode)
  With SummaryTable
    ' Columns
    With .Columns
      .AddText("Ref")
      If HasDescriptors Then.AddText("Descriptor")
      .AddText("Description")
      .AddText("Value").TextAlign = iseSummaryTableCellTextAlign.Right
    End With

    ' Rows
    With .Rows
      For Each DecisionMetric In decisionMetrics
        With .Add.Cells
          .AddText(DecisionMetric.Id)
          If HasDescriptors Then .AddText(DecisionMetric.Descriptor)
          .AddText(DecisionMetric.Name)
          Select Case ucase(DecisionMetric.Type)
            Case "DATE"
              .AddDate(DecisionMetric.ValueAsDate)
            Case "INTEGER"
              .AddInteger(DecisionMetric.ValueAsInteger, False)
            Case "MONEY"
              With .AddCurrency(DecisionMetric.ValueAsMoney, True, False)
                If DecisionMetric.ValueAsMoney < 0 Then
                  .CellClass = iseSummaryTableCellClass.WarningBold
                End If
              End With
            Case "PERCENTAGE"
              .AddPercent(DecisionMetric.ValueAsPercentage / 100, 2, False)
            Case Else
              .AddText(DecisionMetric.ValueAsString)
          End Select
        End With
      Next
    End With
  End With
  SummaryTables.Add("DecisionMetrics", SummaryTable)

  Return SummaryTables

End Function

Private Function BankStatements_EnquiryDetails(serviceLogs As ISServiceLogs,
                                               responseCreate As ISBankAccountEnquiryResponse_BankStatements_RequestStatus,
                                               responseDelete As ISBankAccountEnquiryResponse_BankStatements_RequestStatus,
                                               responseResult As ISBankAccountEnquiryResponse_BankStatements_DownloadData,
                                               accountApp As finAccountApp,
                                               accountAppApplicant As finAccountAppApplicant,
                                               client As finClient,
                                               accountAppLog As finAccountAppLog,
                                               clientLog As finClientLog) As ISSummaryTables

  Dim ApplicationShortCut As ISApplicationShortcut
  Dim ApplicationLinkUrlResolved As String
  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 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 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.CreatedUtcDate, finBL.Settings.TimeZoneId, , True)

    If client IsNot Nothing AndAlso Not client.IsNew Then
      With .Rows.AddCaptionCodeDescription("Client:", client.ClientId, client.Name)
        .Cells(1).HyperlinkSetFormShow("Clients", client.ClientId)
      End With
      .AddRowCaptionText("Name:", client.Name, True)
    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
      .AddRowCaptionText("Name:", AccountAppApplicant.Name, True)
    Else
      .AddRowCaptionText("Client:", "", True)
    End If

    .AddRowCaptionText("Referral Code:", responseCreate.ReferralCode, True)
    If ResponseCreate.SupportsCentrelink Then
      .AddRowCaptionText("Centrelink Option:", If(responseCreate.WithCentrelink, "Yes", "No"))
    End If
    If Len(responseCreate.ReferralCode) = 0 Then
      .AddRowCaptionInteger("Export Day Count:", responseCreate.ExportDayCount, False, False)
    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 responseDelete IsNot Nothing Then
      ' Special case (database failed to update); we have a successful Delete 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())
      ApplicationLinkUrlResolved = finBL.CreditBureau.Service_IllionBankStatements.GetApplicationLinkUrlResolved(responseCreate)
      If Len(ApplicationLinkUrlResolved) <> 0 Then
        .Rows.AddCaptionText("Application Link:", ApplicationLinkUrlResolved).Cells(1).HyperlinkSetExternal(ApplicationLinkUrlResolved)
      End If

      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)
                .SetInteger("serviceLogPk", ServiceLogs(0).Pk)
                .SetInteger("serviceLogBranchPk", BranchPk)
              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)
                .SetInteger("serviceLogPk", ServiceLogs(0).Pk)
                .SetInteger("serviceLogBranchPk", BranchPk)
              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)
                .SetInteger("serviceLogPk", ServiceLogs(0).Pk)
                .SetInteger("serviceLogBranchPk", BranchPk)
              End If
            End With
          End With

          ' Email
          DocumentID =  CostCentreResolved.IllionBankStatements.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.IllionBankStatements.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)

  Return SummaryTables

End Function

Private Function BankStatements_History(serviceLogs As ISServiceLogs,
                                        responseCreate As ISBankAccountEnquiryResponse_BankStatements_RequestStatus) 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 responseCreate.WithCentrelink Then .AddText("Centrelink")
      .AddText(" ")
    End With

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

  Return SummaryTables

End Function

Private Function BankStatements_ScoreModels(scoreModels As ISBankAccountEnquiryResponse_BankStatements_DownloadDataScoreModels) As ISSummaryTables

  Dim Html As String
  Dim KeyInfluencingFactor As ISBankAccountEnquiryResponse_BankStatements_DownloadDataScoreModelKeyInfluencingFactor
  Dim ScoreChartDiagramOptions As finScoreChartDiagramOptions
  Dim ScoreModel As ISBankAccountEnquiryResponse_BankStatements_DownloadDataScoreModel
  Dim ScoreModelError As ISBankAccountEnquiryResponse_BankStatements_DownloadDataScoreModelError
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim Warnings As finWarnings

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()
  Warnings = finBL.CreateWarnings

  For Each ScoreModel In scoreModels
    ' Score model main table
    SummaryTable = SummaryTables.CreateSummaryTableInformation(ScoreModel.ModelName & " Score", ScoreModel.SummaryPageId, 2,,, TestMode)

    ' Chart
    ScoreChartDiagramOptions = finBL.CreateScoreChartDiagramOptions()
    With ScoreChartDiagramOptions
      .Style = isefinScoreChartDiagramStyle.BarRedToGreenIllionBankStatements
      .MaxWidth = "500px"
    End With
    Html = finBL.SummaryPageStandardBlocks.ScoreChartDiagram(Nothing, 0, 1000, ScoreModel.ModelScore, ScoreChartDiagramOptions)
    Html &= "<br/>"
    SummaryTable.TextBefore = Html      
    
    ' Alerts for Score Model errors
    If ScoreModel.ScoreModelErrors.Count <> 0 Then
      Warnings.Clear()
      For Each ScoreModelError In ScoreModel.ScoreModelErrors
        Warnings.AddWarning(ScoreModelError.ErrorMessage,,, isefinWarningLevel.High)
      Next  
      If Warnings.Count <> 0 Then
        SummaryTable.TextAfter = Warnings.GetHtmlTemplateText()
      End If
    End If
    
    SummaryTables.Add(ScoreModel.SummaryPageId, SummaryTable)
  
    ' Key Influencing factors table
    SummaryTable = SummaryTables.CreateSummaryTableTabular("Score Key Influencing Factors (KIFs)", , 3, TestMode)
    With SummaryTable
      .AutoStripe = False
      
      ' Columns
      With .Columns
        ' No headings
        .AddText("").WidthHtml = "250px"
        .AddText("")
      End With
  
      ' Rows
      With .Rows
        For Each KeyInfluencingFactor In ScoreModel.KeyInfluencingFactors
          With .Add.Cells
            .AddText(KeyInfluencingFactor.FactorName)
            .Addwiki(KIFBlock(KeyInfluencingFactor.FactorValue))
          End With
        Next
      End With
    End With
    
    SummaryTables.Add(ScoreModel.SummaryPageId & ".KIF", SummaryTable)
  Next
  
  Return SummaryTables

End Function

Private Function KIFBlock(FactorValue As Integer) As String
  
  Dim Block As String
  
  For i As Integer = -3 To 3
    ' Skip zero
    If i <> 0 Then
      If i = FactorValue Then
        Block &= KIFTag(i)
      Else
        Block &= KIFTag(0)
      End If
      ' spacing
      If i < 3 Then
        Block &= " "
      End If
    End If
  Next
  
  Return Block
  
End Function

Private Function KIFTag(FactorValue As Integer) As String
  
  Select Case FactorValue
  Case -3
    Return "{{TEXTCOLOURBLOCK|-3|white|#FF3300|40|20}}"
  Case -2
    Return "{{TEXTCOLOURBLOCK|-2|white|#FFB89A|40|20}}"
  Case -1
    Return "{{TEXTCOLOURBLOCK|-1|black|#FFE3CD|40|20}}"
  Case 1
    Return "{{TEXTCOLOURBLOCK|1|black|#C6DE80|40|20}}"
  Case 2
    Return "{{TEXTCOLOURBLOCK|2|white|#93D687|40|20}}"
  Case 3
    Return "{{TEXTCOLOURBLOCK|3|white|#61CC94|40|20}}"
  Case Else
    Return "{{TEXTCOLOURBLOCK||black|#F0F0F0|40|20}}"
  End Select
  
End Function


Private Function BankStatements_StatementAnalysisCategories(summaryPageId As String,
                                                            analysisCategories As ISBankAccountEnquiryResponse_BankStatements_DownloadDataAnalysisCategories) As ISSummaryTables

  Dim AnalysisCategory As ISBankAccountEnquiryResponse_BankStatements_DownloadDataAnalysisCategory
  Dim AnalysisPoint As ISBankAccountEnquiryResponse_BankStatements_DownloadDataAnalysisPoint
  Dim AnalysisPointCount As Integer
  Dim CaptionId As String
  Dim TransactionGroupCount As Integer
  Dim SplitPoint As Integer
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTableLeft As ISSummaryTable
  Dim SummaryTableRight As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim Transaction As ISBankAccountEnquiryResponse_BankStatements_DownloadDataTransaction
  Dim TransactionGroup As ISBankAccountEnquiryResponse_BankStatements_DownloadDataTransactionGroup

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  If analysisCategories.Count = 0 Then
    SummaryTables.AddSummaryTableBlank("AnalysisCategories", "Analysis Categories", "No Analysis Categories found.", "AnalysisCategories" & summaryPageId, 3)
  Else
    ' Table of Contents
    SummaryTable = SummaryTables.CreateSummaryTableTabular("Analysis Categories", "AnalysisCategories" & summaryPageId, 3, TestMode)
    With SummaryTable
      ' Columns
      With .Columns
        .AddText(" ", 1)
        .AddText("Category")
        .AddText("Transaction Group")
        .AddInteger("Count")
        .AddCurrency("Total")
      End With

      ' Rows
      With .Rows
        TransactionGroupCount = 0
        For Each AnalysisCategory In analysisCategories
          If AnalysisCategory.TransactionGroups.Count <> 0 Then
            For Each TransactionGroup In AnalysisCategory.TransactionGroups
              TransactionGroupCount += 1
              CaptionId = String.Format("Account_{0}_TransactionGroup_{1}", summaryPageId, TransactionGroupCount)
              With .Add.Cells
                .Add(Me.GetColourBlock(AnalysisCategory.Name, 0))
                .AddText(AnalysisCategory.Name)
                .AddText(TransactionGroup.Name).HyperlinkSetBookmark(CaptionId)
                .AddInteger(TransactionGroup.Transactions.Count)

                With .AddCurrency(TransactionGroup.Transactions.Total, True)
                  If TransactionGroup.Transactions.Total < 0 Then
                    .ForegroundColour = "red"
                  End If
                End With
              End With
            Next
          End If
        Next
      End With
    End With
    SummaryTables.Add("AnalysisCategories" & summaryPageId, SummaryTable)

    ' Detail
    TransactionGroupCount = 0
    For Each AnalysisCategory In analysisCategories
      If AnalysisCategory.TransactionGroups.Count <> 0 Then
        For Each TransactionGroup In AnalysisCategory.TransactionGroups
          TransactionGroupCount += 1
          CaptionId = String.Format("Account_{0}_TransactionGroup_{1}", summaryPageId, TransactionGroupCount)

          ' Start Colour Block
          If TransactionGroupCount Mod 2 <> 0 Then
            SummaryTables.AddSummaryTableBlank(String.Format("{0}__{1}_Start_{2}", AnalysisCategory.Name, TransactionGroup.Name, TransactionGroupCount), "", "<div style='background-color:#F2F2F2'>", "", 4)
          Else
            SummaryTables.AddSummaryTableBlank(String.Format("{0}__{1}_Start_{2}", AnalysisCategory.Name, TransactionGroup.Name, TransactionGroupCount), "", "<div>", "", 4)
          End If

          ' Analysis Points
          SummaryTableLeft = SummaryTables.CreateSummaryTableInformation(Me.GetColourBlock(AnalysisCategory.Name, 0) & "  " & String.Format("{0}: {1}", AnalysisCategory.Name, TransactionGroup.Name), CaptionId, 3, 26, 40, TestMode)
          SummaryTableLeft.Align = "Left"
          SummaryTableRight = SummaryTables.CreateSummaryTableInformation("", "", 3, 26, 40, TestMode)
          SummaryTableRight.Align = "Left"
          AnalysisPointCount = 0
          If TransactionGroup.AnalysisPoints.Count Mod 2 = 0 Then
            SplitPoint = CInt(TransactionGroup.AnalysisPoints.Count / 2)
          Else
            SplitPoint = CInt((TransactionGroup.AnalysisPoints.Count + 1) / 2)
          End If

          For Each AnalysisPoint In TransactionGroup.AnalysisPoints
            AnalysisPointCount += 1
            If AnalysisPointCount <= SplitPoint Then
              Me.BankStatements_StatementAnalysisCategories_Split(SummaryTableLeft, AnalysisPoint)
            Else
              Me.BankStatements_StatementAnalysisCategories_Split(SummaryTableRight, AnalysisPoint)
            End If
          Next
          SummaryTables.Add(CaptionId & "_Left", SummaryTableLeft)
          SummaryTables.Add(CaptionId & "_Right", SummaryTableRight)

          ' Transactions
          If TransactionGroup.Transactions.Count <> 0 Then
            SummaryTable = SummaryTables.CreateSummaryTableTabular("", CaptionId & "_Transactions", 3, TestMode)
            With SummaryTable
              '.Actions.AddUrl(accountId, "Top", "#" & accountId, True)
'.ShowHiddenRowsCaption = "More data..."
'.MaxDisplayRows = 5
              ' Columns
              With .Columns
                .AddDate("Date")
                .AddText("Description")
                .AddCurrency("Withdrawal")
                .AddCurrency("Deposit")
                '.AddCurrency("Balance")
              End With

              ' Rows
              With .Rows
                For Each Transaction In TransactionGroup.Transactions
                  With .Add.Cells
                    .AddText(Format(Transaction.Date, "ddd dd MMM yyyy"))
                    .AddText(Transaction.Text)
                    If Transaction.Amount < 0 Then
                      .AddText("")
                      .AddCurrency(-Transaction.Amount, True)
                    Else
                      .AddCurrency(Transaction.Amount, True)
                      .AddText("")
                    End If
'                    With .AddCurrency(Transaction.Balance, True)
'                      If Transaction.Balance < 0 Then
'                        .ForegroundColour = "red"
'                      End If
'                    End With
                  End With
                Next
              End With
            End With
            SummaryTables.Add(CaptionId & "_Transactions", SummaryTable)
          End If

          ' End Colour Block
          SummaryTables.AddSummaryTableBlank(String.Format("{0}__{1}_End_{2}", AnalysisCategory.Name, TransactionGroup.Name, TransactionGroupCount), "", "</div>", "", 3)
        Next
      End If
    Next
  End If

  Return SummaryTables

End Function

Private Sub BankStatements_StatementAnalysisCategories_Split(ByRef summaryTable As ISSummaryTable,
                                                             analysisPoint As ISBankAccountEnquiryResponse_BankStatements_DownloadDataAnalysisPoint)

  With summaryTable
    Select Case UCase(AnalysisPoint.DataType)
      Case "DATE"
        .AddRowCaptionDate(AnalysisPoint.Title & ":", AnalysisPoint.ValueAsDate, True)
      Case "INTEGER"
        .AddRowCaptionInteger(AnalysisPoint.Title & ":", AnalysisPoint.ValueAsInteger, True, True)
      Case "MONEY"
        .AddRowCaptionCurrency(AnalysisPoint.Title & ":", AnalysisPoint.ValueAsMoney, True, True)
      Case "PERCENTAGE"
        .AddRowCaptionText(AnalysisPoint.Title & ":", String.Format("{0}%", AnalysisPoint.ValueAsPercentage / 100), True)
      Case Else
        .AddRowCaptionText(AnalysisPoint.Title & ":", AnalysisPoint.ValueAsString, True)
    End Select
  End With

End Sub

Private Function BankStatements_Summary(accounts As ISBankAccountEnquiryResponse_BankStatements_DownloadDataAccounts,
                                        submissionUtcDate As Date) As ISSummaryTables

  Dim Account As ISBankAccountEnquiryResponse_BankStatements_DownloadDataAccount
  Dim AccountHolders As List(Of String)
  Dim AccountHolder As String
  Dim AddressDetails As ISAddressDetails
  Dim Count As Integer
  Dim Email As String
  Dim Emails As List(Of String)
  Dim EndDate As Date
  Dim Institution As String
  Dim Period As String
  Dim Phone As String
  Dim Phones As List(Of String)
  Dim StartDate As Date
  Dim strTemp As String
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  If accounts.Count <> 0 Then
    AccountHolder = ""
    AccountHolders = New List(Of String)()
    Emails = New List(Of String)()
    EndDate = Nothing
    Institution = ""
    Period = ""
    Phones = New List(Of String)()
    StartDate = Nothing

    For Each Account In accounts
      If Len(Account.AccountId) <> 0 Then
        ' Account Holder
        If Not AccountHolders.Contains(Account.AccountHolder) Then
          AccountHolders.Add(Account.AccountHolder)
        End If

        ' Additional Information - Email
        If Not Emails.Contains(Account.Email) Then
          Emails.Add(Account.Email)
        End If

        ' Additional Information - Phone
        If Not Phones.Contains(Account.Phone) Then
          Phones.Add(Account.Phone)
        End If

        ' Institution
        If Len(Institution) = 0 Then Institution = Account.Institution

        ' Period
        If StartDate = Nothing Then
          StartDate = Account.SearchPeriodStart
        ElseIf Account.SearchPeriodStart < StartDate Then
          StartDate = Account.SearchPeriodStart
        End If
        If EndDate = Nothing Then
          EndDate = Account.SearchPeriodEnd
        ElseIf Account.SearchPeriodEnd > EndDate Then
          EndDate = Account.SearchPeriodEnd
        End If
      End If
    Next

    ' Account Holders List
    Count = 0
    For Each strTemp In AccountHolders
      Count += 1
      If Len(AccountHolder) <> 0 Then AccountHolder &= vbNewLine
      If AccountHolders.Count = 1 Then
        AccountHolder &= strTemp
      Else
        AccountHolder &= String.Format("{0}. {1}", count, strTemp)
      End If
    Next

    ' Phones
    Count = 0
    For Each strTemp In Emails
      Count += 1
      If Len(Email) <> 0 Then Email &= vbNewLine
      If Emails.Count = 1 Then
        Email &= strTemp
      Else
        Email &= String.Format("{0}. {1}", count, strTemp)
      End If
    Next

    ' Phones
    Count = 0
    For Each strTemp In Phones
      Count += 1
      If Len(Phone) <> 0 Then Phone &= vbNewLine
      If Phones.Count = 1 Then
        Phone &= strTemp
      Else
        Phone &= String.Format("{0}. {1}", count, strTemp)
      End If
    Next

    ' Period
    If StartDate <> Nothing AndAlso EndDate <> Nothing Then
      Period = String.Format("{0} to {1} ({2} days)", finBL.FormatDateLong(StartDate), finBL.FormatDateLong(EndDate), DateDiff(DateInterval.Day, StartDate, EndDate) + 1)
    End If

    SummaryTable = SummaryTables.CreateSummaryTableInformation(String.Format("{0} Summary", Institution), "Summary", 2, , , TestMode)
    With SummaryTable
      If AccountHolders.Count > 1 Then
        .AddRowCaptionText("Account Holders:", AccountHolder, True)
      Else
        .AddRowCaptionText("Account Holder:", AccountHolder, True)
      End If
      If Phones.Count > 1 Then
        .AddRowCaptionText("Phones:", Phone, False)
      Else
        .AddRowCaptionText("Phone:", Phone, False)
      End If
      If Emails.Count > 1 Then
        .AddRowCaptionText("Emails:", Email, False)
      Else
        .AddRowCaptionText("Email:", Email, False)
      End If
      If Account.Address IsNot Nothing Then
        AddressDetails = Account.Address.ToAddressDetails()
        If AddressDetails.HasValue Then
          .AddRowCaptionAddressDetailsPhysical("Address:", AddressDetails, False)
        Else
          .AddRowCaptionText("Address:", Account.Address.Text, False)
        End If
      End If
      .AddRowCaptionText("Institution:", Institution, True)
      .AddRowCaptionText("Period:", Period, True)
      .AddRowCaptionUtcDateTimeWithTimeZone("Submission Time:", submissionUtcDate, finBL.Settings.TimeZoneId,, True)
    End With
    SummaryTables.Add("Summary", SummaryTable)
  End If

  Return SummaryTables

End Function

Private Function BankStatements_TransactionAnalysis(analysisGroups As ISBankAccountEnquiryResponse_BankStatements_DownloadDataAnalysisGroups) As ISSummaryTables

  Dim AnalysisGroup As  ISBankAccountEnquiryResponse_BankStatements_DownloadDataAnalysisGroup
  Dim AnalysisItem As ISBankAccountEnquiryResponse_BankStatements_DownloadDataAnalysisItem
  Dim AnalysisItemTotal As ISBankAccountEnquiryResponse_BankStatements_DownloadDataAnalysisItem
  Dim ApplicationShortcut As ISApplicationShortcut
  Dim HasPaymentDay As Boolean
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  If analysisGroups.Count = 0 Then
    SummaryTables.AddSummaryTableBlank("TransactionAnalysis", "Transaction Analysis", "No Transaction Analysis found.", "TransactionAnalysis", 3)
  Else
    SummaryTables.AddSummaryTableBlank("TransactionAnalysis", "Transaction Analysis", "<div></div>", "TransactionAnalysis", 3)

    ' Get Flags
    HasPaymentDay = analysisGroups.HasPaymentDay

    For Each AnalysisGroup In analysisGroups
      If AnalysisGroup.Items.Count > 1 Then
        SummaryTable = SummaryTables.CreateSummaryTableTabular(finbl.HtmlEncode(AnalysisGroup.TypeText), "",4, TestMode)
        With SummaryTable
          ' Columns
          With .Columns
            .AddText(" ", 1)
            .AddText("Name", 30)
            .AddInteger("Transactions", 6)
            .AddCurrency("Total", 15)
            .AddCurrency("Monthly Avg", 15)
            .AddCurrency("Avg Value", 15)
            .AddDate("Dates")
            .AddCurrency("Values", 15)
            .AddText("Regular", 3)
            .AddText("Frequency", 8)
            If HasPaymentDay Then .AddText("Payment Day", 8)
          End With

          ' Rows
          With .Rows
            AnalysisItemTotal = Nothing
            For Each AnalysisItem In AnalysisGroup.Items
              With .Add.Cells
                If AnalysisItem.Name = "Total" Then
                  AnalysisItemTotal = AnalysisItem
                Else
                  .Add(Me.GetColourBlock(AnalysisGroup.TypeText, 0))

                  ' Create Popup hyperlink (compact due to hyperlink size limit)
                  ApplicationShortcut = Nothing
                  If ScriptInfo.Target = iseSummaryPageTarget.Form AndAlso AnalysisItem.Transactions.Count <> 0 Then
                    ApplicationShortcut = finBL.CreateApplicationShortcut()
                    With ApplicationShortcut
                      .Action = "HtmlShow"

                      With .Parameters
                        .SetBoolean("popup", True)
                        .SetString("title", "Analysis")
                        .SetString("html", Me.BankStatements_TransactionAnalysis_Popup(AnalysisItem.Transactions))
                      End With
                    End With
                    .AddText(finBL.Runtime.TextUtilities.SplitWordsAtCapitals(AnalysisItem.Name)).HyperlinkSetApplicationShortcutUrl(ApplicationShortcut.ToUrlString())
                  Else
                    .AddText(finBL.Runtime.TextUtilities.SplitWordsAtCapitals(AnalysisItem.Name))
                  End If

                  .AddInteger(AnalysisItem.TransactionCount)
                  .AddCurrency(AnalysisItem.TotalValue, True)
                  .AddCurrency(AnalysisItem.MonthlyAverage, True)
                  .AddCurrency(AnalysisItem.AverageValue, True)
                  If AnalysisItem.TransactionDateFirst = AnalysisItem.TransactionDateLast Then
                    .AddDate(AnalysisItem.TransactionDateFirst)
                  Else
                    .AddText(String.Format("{0}" & vbNewline & "to {1}", finBL.FormatDateLong(AnalysisItem.TransactionDateFirst), finBL.FormatDateLong(AnalysisItem.TransactionDateLast)))
                  End If
                  If AnalysisItem.MinimumValue = AnalysisItem.MaxmiumValue Then
                    .AddCurrency(AnalysisItem.MinimumValue)
                  Else
                    .AddText(String.Format("{0}" & vbNewline & "to {1}", finBL.FormatCurrency(AnalysisItem.MinimumValue, True), finBL.FormatCurrency(AnalysisItem.MaxmiumValue, True)))
                  End If
                  .AddTick(AnalysisItem.PeriodIsRegular)
                  If AnalysisItem.Period = 0 Then
                    .AddText("")
                  Else
                    .AddText(String.Format("{0} days", finBL.Runtime.NumberUtilities.RoundDouble(AnalysisItem.Period, 0)))
                  End If
                  If HasPaymentDay Then .AddText(AnalysisItem.PaymentDay)
                End If
              End With
            Next

            ' Total
            With .Add(iseSummaryTableRowClass.FooterBold).Cells
              If AnalysisItemTotal IsNot Nothing AndAlso AnalysisGroup.Items.Count > 2 Then
                .AddText("")
                .AddText("")
                .AddInteger(AnalysisItemTotal.TransactionCount)
                .AddCurrency(AnalysisItemTotal.TotalValue, True)
                .AddCurrency(AnalysisItemTotal.MonthlyAverage, True)
                .AddText("")
                .AddText("")
                .AddText("")
                .AddText("")
                .AddText("")
                If HasPaymentDay Then .AddText("")
              End If
            End With
          End With
        End With
        SummaryTables.Add(finbl.HtmlEncode(AnalysisGroup.TypeText), SummaryTable)
      End If
    Next
  End If

  Return SummaryTables

End Function

Private Function BankStatements_TransactionAnalysis_Popup(transactions As ISBankAccountEnquiryResponse_BankStatements_DownloadDataTransactions) As String

  Dim HtmlSummaryPage2StringBuilder As finHtmlSummaryPage2StringBuilder
  Dim Transaction As ISBankAccountEnquiryResponse_BankStatements_DownloadDataTransaction
  Dim SummaryTable As ISSummaryTable

  ' Initialise
  HtmlSummaryPage2StringBuilder = finBL.CreateHtmlSummaryPage2StringBuilder()
  SummaryTable = finBL.CreateSummaryTable()

  With SummaryTable
    .TableClass = iseSummaryTableClass.TabularData

    ' Columns
    With .Columns
      .AddText("")
      .AddDate("")
      .AddCurrency("")
    End With

    ' Rows
    With .Rows
      For Each Transaction In transactions
        With .Add.Cells
          .AddText(finBL.HtmlEncode(Transaction.Text))
          .AddDate(Transaction.Date)
          .AddCurrency(Transaction.Amount, True)
        End With
      Next
    End With
  End With
  HtmlSummaryPage2StringBuilder.SummaryTableAppend(SummaryTable)

  ' Finalise HTML
  HtmlSummaryPage2StringBuilder.HtmlFinalise()

  Return HtmlSummaryPage2StringBuilder.ToString(True)

End Function

Private Function GetBSBText(bsb As String) As String

  If Len(bsb) = 0 Then
    Return ""
  ElseIf strcomp(bsb, "NONE", CompareMethod.Text) = 0 Then
    Return ""
  ElseIf Len(bsb) = 6 AndAlso IsNumeric(bsb) Then
    Return String.Format("{0}-{1}", Left(bsb, 3), Right(bsb, 3))
  Else
    Return bsb
  End If

End Function

Private Function GetColourBlock(tag As String,
                                amount As Decimal) As String

  If InStr(tag, "CENTRELINK", CompareMethod.Text) <> 0 OrElse InStr(tag, "BENEFITS", CompareMethod.Text) <> 0 Then
    ' Yellow
    Return "{{colourblock|#FFD35C}}"
  ElseIf InStr(tag, "DISHONOURED", CompareMethod.Text) <> 0 OrElse InStr(tag, "DISHONOURS", CompareMethod.Text) <> 0 Then
    ' Red
    Return "{{colourblock|#C72C3A}}"
  ElseIf InStr(tag, "LOANS", CompareMethod.Text) <> 0 Then
    ' Pink
    Return "{{colourblock|#EA3E70}}"
  ElseIf InStr(tag, "INCOME", CompareMethod.Text) <> 0 OrElse InStr(tag, "WAGE", CompareMethod.Text) <> 0 Then
    ' Green
    Return "{{colourblock|#02B5A0}}"
  ElseIf InStr(tag, "GAMBLING", CompareMethod.Text) <> 0 Then
    ' Orange
    Return "{{colourblock|#FF8201}}"
  ElseIf InStr(tag, "RENT", CompareMethod.Text) <> 0 Then
    ' Olive
    Return "{{colourblock|#8A9747}}"
  ElseIf InStr(tag, "DEBIT", CompareMethod.Text) <> 0 OrElse amount > 0 Then
    ' Purple
    Return "{{colourblock|#954567}}"
  ElseIf InStr(tag, "CREDIT", CompareMethod.Text) <> 0 OrElse amount <= 0 Then
    ' Blue
    Return "{{colourblock|#0180B5}}"
  Else
    Return "{{colourblock|white}}"
  End If

End Function

Private Function BankStatements_BrokerFlow_EnquiryDetails(response As ISBankAccountEnquiryResponse_BankStatements_BrokerFlow,
                                                          accountApp As finAccountApp,
                                                          accountAppApplicant As finAccountAppApplicant,
                                                          client As finClient,
                                                          accountAppLog As finAccountAppLog,
                                                          clientLog As finClientLog) As ISSummaryTables

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

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  SummaryTable = SummaryTables.CreateSummaryTableInformation("", "EnquiryDetails",,,, TestMode)
  With SummaryTable
    .AddRowCaptionUtcDateTimeWithTimeZone("Date:", response.EnquiryUtcDate, finBL.Settings.TimeZoneId, , True)
    .AddRowCaptionText("Document Id:", response.DocumentId, True)

    If client IsNot Nothing AndAlso Not client.IsNew Then
      With .Rows.AddCaptionCodeDescription("Client:", client.ClientId, client.Name)
        .Cells(1).HyperlinkSetFormShow("Clients", client.ClientId)
      End With
      .AddRowCaptionText("Name:", client.Name, True)
    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
      .AddRowCaptionText("Name:", AccountAppApplicant.Name, True)
    Else
      .AddRowCaptionText("Client:", "", True)
    End If

    ' Warnings
    Warnings = ""
    Days = CInt(DateDiff(DateInterval.Day, response.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
    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
      End If
    End With
  End With
  SummaryTables.Add("Actions", SummaryTable)

  Return SummaryTables

End Function