' SummaryPage2_BankAccountEnquiryReport_DecisionLogic

Option Explicit On
Option Strict On

' #################################################################
' DecisionLogic Bank Account Report Summary Page Script
'
' Version: 2.04 (04/11/2021)
'
' Usage: Bank Account Enquiry and Log forms
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    2.03  22/05/2017  ISS
'    2.04  04/11/2021  ISS      J027713   Updated obsoleted functions
' #################################################################

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

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

  ' Response and service log
  If Main Then
    Try
      Main = finBL.CreditBureau.GetBankAccountEnquiryServiceLogs(CInt(source), ServiceLogs)
      If Main Then Response = DirectCast(ServiceLogs(0).ExResponse, ISBankAccountEnquiryResponse)
    Catch ex As Exception
      Main = False
      finBL.Error.ErrorBeginFromException(ex)
    End Try
  End If

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

End Function

' CreatePage
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
    ' 006599, C0C0C0, E8E8E8
    .HtmlHeaderInsertServiceReportTheme("#006599", "#C0C0C0", "", "#E8E8E8")

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

    ' Finalise HTML Header
    .HtmlHeaderEnd()
  End With

  ' Get original Create Response
  Select Case TypeName(Response)
    Case "ISBankAccountEnquiryResponse_DecisionLogic_CreateRequest"
      Me.CreatePage_DecisionLogic(ServiceLogs, response, HtmlSummaryPage2StringBuilder)
    Case Else
      ' Error
      finBL.Error.ErrorBegin("Invalid opening Service Log for a Bank Account Enquiry.")
  End Select

  ' Disclaimer
  HtmlSummaryPage2StringBuilder.Append("<hr/>")
  HtmlSummaryPage2StringBuilder.AppendLine("{{disclaimer|This report was produced by finPOWER Connect version " & finBL.VersionMajorMinorBuild & " using information retrieved from the " & response.ServiceName & " service on " & finBL.FormatDateTime(response.EnquiryDate, True, True, True) &"}}")

  ' Finalise HTML
  HtmlSummaryPage2StringBuilder.HtmlFinalise()

  ' Resolve Templates
  html = HtmlSummaryPage2StringBuilder.ToString(True)

  Return Success

End Function

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

  Dim AccountApp As finAccountApp
  Dim AccountAppApplicant As finAccountAppApplicant
  Dim AccountAppLog As finAccountAppLog
  Dim Client As finClient
  Dim ClientLog As finClientLog
  Dim i As Integer
  Dim ResponseCreate As ISBankAccountEnquiryResponse_DecisionLogic_CreateRequest
  Dim ResponseDelete As ISBankAccountEnquiryResponse_DecisionLogic_DeleteRequest
  Dim ResponseResult As ISBankAccountEnquiryResponse_DecisionLogic_Report

  ' Initialise
  ResponseCreate = DirectCast(response, ISBankAccountEnquiryResponse_DecisionLogic_CreateRequest)

  ' Get Other Responses
  For i = serviceLogs.Count - 1 To 0 Step -1
    If serviceLogs(i).RequestStatus = iseAuditLogStatus.Success Then
      response = DirectCast(ServiceLogs(i).ExResponse, ISBankAccountEnquiryResponse)
      If response.IsDeletedRequest Then
        ResponseDelete = DirectCast(response, ISBankAccountEnquiryResponse_DecisionLogic_DeleteRequest)
      ElseIf Response.IsReport Then
        ResponseResult = DirectCast(response, ISBankAccountEnquiryResponse_DecisionLogic_Report)
      End If
    End If
  Next

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

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

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

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

    .SummaryTablesAppend(Me.DecisionLogic_EnquiryDetails(serviceLogs, ResponseCreate, ResponseDelete, ResponseResult, accountApp, AccountAppApplicant, Client))
    .SummaryTablesAppend(Me.DecisionLogic_Alerts(serviceLogs, ResponseCreate, ResponseResult, ResponseDelete))

    ' History
    If ServiceLogs IsNot Nothing AndAlso ResponseResult Is Nothing Then .SummaryTablesAppend(Me.DecisionLogic_History(serviceLogs))

    ' Report already Retrieved
    If ResponseResult IsNot Nothing Then .SummaryTablesAppend(Me.DecisionLogic_BankResponseReport(ResponseResult))
  End With
End Sub

Private Function DecisionLogic_EnquiryDetails(serviceLogs As ISServiceLogs,
                                              responseCreate As ISBankAccountEnquiryResponse_DecisionLogic_CreateRequest,
                                              responseDelete As ISBankAccountEnquiryResponse_DecisionLogic_DeleteRequest,
                                              responseResult As ISBankAccountEnquiryResponse_DecisionLogic_Report,
                                              accountApp As finAccountApp,
                                              accountAppApplicant As finAccountAppApplicant,
                                              client As finClient) As ISSummaryTables

  Dim Days As Integer
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim Warnings As String
  
  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

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

    If client IsNot Nothing Then
      With .Rows.AddCaptionCodeDescription("Client:", client.ClientId, client.Name)
        .Cells(1).HyperlinkSetFormShow("Clients", client.ClientId)
      End With
    ElseIf AccountAppApplicant IsNot Nothing Then
      With .Rows.AddCaptionCodeDescription("Applicant:", AccountApp.AccountAppId, String.Format("{0} ({1})", AccountApp.Name, AccountAppApplicant.Name))
        .Cells(1).HyperlinkSetFormShow("AccountApps", AccountApp.AccountAppId, "Applicant")
      End With
    End If
    .AddRowCaptionText("Code:", responseCreate.Token)
    
    ' 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 ResponseResult Is Nothing AndAlso ResponseDelete Is Nothing Then
      .Rows.AddCaptionText("Website:", responseCreate.Service.GetTokenUrl("")).Cells(1).HyperlinkSetExternal(responseCreate.Service.GetTokenUrl(""))
      .Rows.AddCaptionText("Website Link:", finBL.HtmlEncode(responseCreate.Service.GetTokenUrl(responseCreate.Token))).Cells(1).HyperlinkSetExternal(finBL.HtmlEncode(responseCreate.Service.GetTokenUrl(responseCreate.Token)))
      With .Actions
        .AddApplicationShortcutUrl("GetReport", "Get Report", String.Format("App://Global?Type=BankAccountEnquiry.GetReport&ServiceLogPk={0}", ServiceLogs(0).Pk), True)
        .AddApplicationShortcutUrl("DeleteRequest", "Delete Request", String.Format("App://Global?Type=BankAccountEnquiry.Delete&ServiceLogPk={0}", ServiceLogs(0).Pk), True)
      End With
    End If
  End With
  SummaryTables.Add("Actions", SummaryTable)

  Return SummaryTables

End Function

Public Function DecisionLogic_Alerts(serviceLogs As ISServiceLogs,
                                     responseCreateRequest As ISBankAccountEnquiryResponse_DecisionLogic_CreateRequest,
                                     responseReport As ISBankAccountEnquiryResponse_DecisionLogic_Report,
                                     responseDelete As ISBankAccountEnquiryResponse_DecisionLogic_DeleteRequest) As ISSummaryTables

  Dim Account As ISBankAccountEnquiryResponse_DecisionLogic_ReportAccount
  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 responseReport Is Nothing AndAlso responseDelete Is Nothing Then
    If DateDiff(DateInterval.Day, responseCreateRequest.EnquiryDate.Date, finBL.Runtime.TimeZoneUtilities.GetCurrentLocalDate()) > 30 Then
      Warnings.AddWarning("Request more than 30 days old.",,, isefinWarningLevel.Critical)
    End If
  End If

  ' Build Warning lists
  If responseReport IsNot Nothing Then
    With responseReport
      ' Out of Date
      If .Accounts.Count > 0 Then
        Days = CInt(DateDiff(DateInterval.Day, .Accounts(0).ActivityEndDate, finBL.Runtime.TimeZoneUtilities.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

      ' Accounts
      If responseReport.Accounts.Count = 0 Then
        Warnings.AddWarning("No Account information returned.",,, isefinWarningLevel.Critical)
      Else
        For Each Account In responseReport.Accounts
          With Account
            Select Case .NameConfidence
              Case 0, 1: Warnings.AddWarning(String.Format("'{0}' Name: {1}", .Description, .NameConfidenceDescription),,, isefinWarningLevel.Critical)
              Case 2, 3: Warnings.AddWarning(String.Format("'{0}' Name: {1}", .Description, .NameConfidenceDescription),,, isefinWarningLevel.High)
              Case 4: ' Good Match
              Case 5: ' Exact Match
            End Select

            Select Case .AccountNumberConfidence
              Case 0: Warnings.AddWarning(String.Format("'{0}' Number: {1}", .Description, .AccountNumberConfidenceDescription),,, isefinWarningLevel.Critical)
              Case 1, 2, 3: Warnings.AddWarning(String.Format("'{0}' Number: {1}", .Description, .AccountNumberConfidenceDescription),,, isefinWarningLevel.High)
              Case 4: ' Exact Match
            End Select

            ' Balance
            If .CurrentBalance < 0 Then
              Warnings.AddWarning(String.Format("'{0}' Current Balance is overdrawn.", .Description),,, isefinWarningLevel.Critical)
            ElseIf .AvailableBalance < 0 Then
              Warnings.AddWarning(String.Format("'{0}' Available Balance is overdrawn.", .Description),,, isefinWarningLevel.Critical)
            End If
          End With
        Next
      End If
    End With
  ElseIf responseDelete IsNot Nothing Then
    ' Deleted
    Select Case ServiceLogs(0).ResponseStatus
      Case iseServiceLogResponseStatus.Deleted
        Warnings.AddWarning("Request deleted.",,, isefinWarningLevel.Critical)
      Case Else
        Warnings.AddWarning("Request is not correctly deleted - please Delete the Request again.",,, isefinWarningLevel.Critical)
    End Select
  Else
    ' Not yet completed
    Warnings.AddWarning("Report not yet downloaded.",,, isefinWarningLevel.Critical)
  End If

  ' 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 DecisionLogic_History(serviceLogs As ISServiceLogs) As ISSummaryTables

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

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

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

    ' Rows
    With .Rows
      For Each ServiceLog In serviceLogs
        With .Add
          If Len(ServiceLog.ExStatusHtmlColour) <> 0 Then
            .BackgroundColour = ServiceLog.ExStatusHtmlColour
            If finBL.Runtime.ColourUtilities.HtmlColourIsDark(ServiceLog.ExStatusHtmlColour) Then .ForegroundColour = "white"
          End If
          With .Cells
            .AddInteger(ServiceLog.Pk).HyperlinkSetFormShow("ServiceLog", CStr(ServiceLog.Pk))
            .AddDateTime(ServiceLog.CreatedDate,, True)
            .AddCodeDescription(ServiceLog.CreatedUserPk, finBL.Users)
            .AddText(ServiceLog.ExStatus)
          End With
        End With
      Next
    End With
  End With
  SummaryTables.Add("History", SummaryTable)

  Return SummaryTables

End Function

Private Function CurrencyCellClass(currency As Decimal,
                          Optional bold As Boolean = False) As iseSummaryTableCellClass

  If currency < 0 Then
    If bold Then
      Return iseSummaryTableCellClass.WarningBold
    Else
      Return iseSummaryTableCellClass.Warning
    End If
  Else
    If bold Then
      Return iseSummaryTableCellClass.NormalBold
    Else
      Return iseSummaryTableCellClass.Normal
    End If
  End If
End Function

Private Function DecisionLogic_BankResponseReport(responseReport As ISBankAccountEnquiryResponse_DecisionLogic_Report) As ISSummaryTables

  Dim Account As ISBankAccountEnquiryResponse_DecisionLogic_ReportAccount
  Dim CellClass As iseSummaryTableCellClass
  Dim Count As Integer
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Initialise
  CellClass = iseSummaryTableCellClass.Normal
  Count = 0
  Account = responseReport.Accounts(0)
  SummaryTables = finBL.CreateSummaryTables()

  SummaryTable = SummaryTables.CreateSummaryTableInformation("Request (Information Entered)", "RequestInfoEntered",2,,, TestMode)
  With SummaryTable
    .AddRowCaptionText("Name:", Account.NameEntered)
    .AddRowCaptionText("Institution Name:", Account.InstitutionName)
    .AddRowCaptionText("Routing Number:", Account.RoutingNumberEntered)
    .AddRowCaptionText("Account Number:", Account.AccountNumberEntered)
  End With
  SummaryTables.Add("RequestInfoEntered", SummaryTable)

  If responseReport.Accounts.Count > 1 Then
    SummaryTable = SummaryTables.CreateSummaryTableTabular("Responses (Information Returned by Bank)", "ResponsesInformationReturnedbyBank",2, TestMode)
    With SummaryTable
      ' Columns
      With .Columns
        .AddText("Description")
        .AddText("Name")
        .AddText("Account Number")
        .AddText("Account Name")
        .AddText("Account Type", 15)
        .AddCurrency("Available Balance", 17)
        .AddCurrency("Current Balance",17)
        .AddCurrency("Average Balance", 17)
        .AddCurrency("Avg Bal Latest Month", 20)
      End With

      ' Rows
      With .Rows
        For Each Account In responseReport.Accounts
          With .Add.Cells
            .AddText(Account.Description).Hyperlink = "#" & Account.Description
            .AddText(Account.NameFound)
            .AddText(Account.AccountNumberFound)
            .AddText(Account.AccountName)
            .AddText(Account.AccountType)
            .AddCurrency(Account.AvailableBalance, True).CellClass = Me.CurrencyCellClass(Account.AvailableBalance)
            .AddCurrency(Account.CurrentBalance, True).CellClass = Me.CurrencyCellClass(Account.CurrentBalance)
            .AddCurrency(Account.AverageBalance, True).CellClass = Me.CurrencyCellClass(Account.AverageBalance)
            .AddCurrency(Account.AverageBalanceRecent, True).CellClass = Me.CurrencyCellClass(Account.AverageBalanceRecent)
          End With
        Next

        ' Total Row
        With .Add(iseSummaryTableRowClass.FooterBold).Cells
          .AddText("")
          .AddText("")
          .AddText("")
          .AddText("")
          .AddText("")
          .AddCurrency(responseReport.TotalAvailableBalance, True).CellClass = Me.CurrencyCellClass(responseReport.TotalAvailableBalance, True)
          .AddCurrency(responseReport.TotalCurrentBalance, True).CellClass = Me.CurrencyCellClass(responseReport.TotalCurrentBalance, True)
          .AddCurrency(responseReport.TotalAverageBalance, True).CellClass = Me.CurrencyCellClass(responseReport.TotalAverageBalance, True)
          .AddCurrency(responseReport.TotalAverageBalanceRecent, True).CellClass = Me.CurrencyCellClass(responseReport.TotalAverageBalanceRecent, True)
        End With
      End With
    End With
    SummaryTables.Add("ResponsesInformationReturnedbyBank", SummaryTable)
  End If

  For Each Account In responseReport.Accounts
    ' Heading
    SummaryTables.AddSummaryTableBlank(Account.Description, String.Format("{0} : {1}", Account.Description, Account.AccountNumberFound),"<div></div>",Account.Description,2)

    SummaryTable = SummaryTables.CreateSummaryTableInformation("Response (Information Returned by Bank)","",3,,, TestMode)
    With SummaryTable
      .AddRowCaptionText("Name:", Account.NameFound)
      .AddRowCaptionText(" Confidence:", String.Format("{0} ({1})", Account.NameConfidenceDescription, Account.NameConfidence))
      .AddRowCaptionText("Account Number:", Account.AccountNumberFound)
      .AddRowCaptionText(" Confidence:", String.Format("{0} ({1})", Account.AccountNumberConfidenceDescription, Account.AccountNumberConfidence))
      .AddRowCaptionText("Account Name:", Account.AccountName)
      .AddRowCaptionText("Account Type:", UCase(Account.AccountType))
    End With
    SummaryTables.Add(Account.Description & Count, SummaryTable)

    ' Summary
    SummaryTable = SummaryTables.CreateSummaryTableInformation("Summary","Summary" & Account.Description,3,,, TestMode)
    With SummaryTable
      .AddRowCaptionDateTime("Date as at:", Account.AsOfDate.ToLocalTime())
      .AddRowCaptionCurrency("Available Balance:", Account.AvailableBalance, True)
      .AddRowCaptionCurrency("Current Balance:", Account.CurrentBalance, True)
      .AddRowCaptionCurrency("Deposits/Credits:", Account.TotalCredits, True)
      .AddRowCaptionCurrency("Withdrawals/Debits:", Account.TotalDebits, True)
      .AddRowCaptionCurrency("Average Balance:", Account.AverageBalance, True)
      .AddRowCaptionCurrency("Avg Bal Latest Month:", Account.AverageBalanceRecent, True)
    End With
    SummaryTables.Add(String.Format("Summary{0}", Account.Description).Replace(" ",""), SummaryTable)

    ' Notes
    If Len(Account.Notes) <> 0 Then
      SummaryTables.AddSummaryTableBlank(String.Format("Notes{0}", Account.Description),"Notes",Account.Notes,,3)
    End If

    ' Transaction Analysis Summary
    SummaryTables.AppendSummaryTables(Me.DecisionLogic_TransactionAnalyisSummary(Account.TransactionAnalysisSummaries))

    ' Transaction Summary
    SummaryTables.AppendSummaryTables(Me.DecisionLogic_TransactionSummary(Account.TransactionSummaries))
  Next

  Return SummaryTables

End Function

Private Function DecisionLogic_TransactionAnalyisSummary(analysisSummaries As ISBankAccountEnquiryResponse_DecisionLogic_ReportTransactionAnalysisSummaries) As ISSummaryTables

  Dim AnalysisSummary As ISBankAccountEnquiryResponse_DecisionLogic_ReportTransactionAnalysisSummary
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  If analysisSummaries.Count = 0 Then
    SummaryTables.AddSummaryTableBlank("TransactionAnalysisSummary", "Transaction Analysis Summary", "No Transaction Analysis Summaries found.", "TransactionAnalysisSummary",3)
  Else
    SummaryTable = SummaryTables.CreateSummaryTableTabular("Transaction Analysis Summary", "TransactionAnalysisSummary",3, TestMode)
    With SummaryTable
      ' Columns
      With .Columns
        .AddText("Description")
        .AddText("Code")
        .AddCurrency("This Month Transactions")
        .AddCurrency("This Month Total",12)
        .AddCurrency("Last Month Transactions")
        .AddCurrency("Last Month Total",12)
      End With

      ' Rows
      With .Rows
        For Each AnalysisSummary In analysisSummaries
          With .Add.Cells
            .AddText(AnalysisSummary.TypeName)
            .AddText(AnalysisSummary.TypeCode)
            .AddInteger(AnalysisSummary.TotalCount)
            With .AddCurrency(AnalysisSummary.TotalAmount, True)
              If AnalysisSummary.TotalAmount < 0 Then
                .ForegroundColour = "red"
              End If
            End With
            .AddInteger(AnalysisSummary.RecentCount)
            With .AddCurrency(AnalysisSummary.RecentAmount, True)
              If AnalysisSummary.RecentAmount < 0 Then
                .ForegroundColour = "red"
              End If
            End With
          End With
        Next
      End With
    End With
    SummaryTables.Add("TransactionAnalysisSummary", SummaryTable)
  End If

  Return SummaryTables

End Function

Private Function DecisionLogic_TransactionSummary(transactionSummaries As ISBankAccountEnquiryResponse_DecisionLogic_ReportTransactionSummaries) As ISSummaryTables

  Dim RowClass As iseSummaryTableRowClass
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim TransactionSummary As ISBankAccountEnquiryResponse_DecisionLogic_ReportTransactionSummary

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  If transactionSummaries.Count = 0 Then
    SummaryTables.AddSummaryTableBlank("TransactionSummary","Transaction Summary","No Transaction Summaries found.","TransactionSummary",3)
  Else
    SummaryTable = SummaryTables.CreateSummaryTableTabular("Transaction Summary", "TransactionSummary",3, TestMode)
    With SummaryTable
      ' Columns
      With .Columns
        .AddDate("Date")
        .AddText("Code")
        .AddText("Description")
        .AddCurrency("Withdrawal")
        .AddCurrency("Deposit")
        .AddCurrency("Balance")
      End With

      ' Rows
      With .Rows
        For Each TransactionSummary In transactionSummaries
          If TransactionSummary.Amount > 0 Then RowClass = iseSummaryTableRowClass.NormalBold Else RowClass = iseSummaryTableRowClass.Normal
          With .Add(RowClass).Cells
            .AddDate(TransactionSummary.TransactionDate)
            .AddText(TransactionSummary.TypeCodes)

            If StrComp(TransactionSummary.Status, "POSTED", CompareMethod.Text) = 0 Then
              .AddText(TransactionSummary.Description)
            Else
              .AddText(TransactionSummary.Description & " (" & TransactionSummary.Status & ")")
            End If

            If TransactionSummary.Amount > 0 Then
              .AddText("")
              .AddCurrency(TransactionSummary.Amount, True)
            Else
              .AddCurrency(-TransactionSummary.Amount, True)
              .AddText("")
            End If
            With .AddCurrency(TransactionSummary.RunningBalance, True)
              If TransactionSummary.RunningBalance < 0 Then
                .ForegroundColour = "red"
              End If
            End With
          End With
        Next
      End With
    End With
    SummaryTables.Add("TransactionSummary", SummaryTable)
  End If

  Return SummaryTables

End Function