' ###########################################################
' When Adding or updating code:
'   1. Ensure there is a Version History block at the top of the code and update.
'      Move Version/ Date in the <summary> comment at the top of the function to the Version History block.
'      Example shown below:
'
' #################################################################
' Account_BankingDetailsSummary
'
' Version: 1.10 (23/07/2021)
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.09  04/05/2021  ISS                  
'    1.10  23/07/2021  ISS      J027056            
' #################################################################
'
'   2. Update SummaryPageStandardBlocks.txt file in the "Templates/Sample Scripts" folder.
'
'   3. Test that the block can be successfully called from a 'SummaryPageStandardBlocks' Script.
'
'   4. Do not use Debug.Assert since it is incompatible with Scripts.
'   4a. Do not use String interpolation since it is incompatible with Scripts.
'
'   5. NEVER add more parameters (optional or otherwise) to existing Overridable methods.
'      This is a Base Class and will break existing Scripts. Instead, consider adding
'      a new method and obsoleting the existing one.
' ###########################################################

''' <summary>
'''  Represents the base class for producing and overriding standard Summary Page blocks.
''' </summary>
Partial Public Class finSummaryPageStandardBlocksBase

  ' Properties
  Public finBL As ISfinSupport
  Public ScriptInfo As ISScriptExecutionInfo

  Public Sub New()
    ' Public, with no parameters is required for Script inheritance
  End Sub

  ''' <summary>
  '''  Account Accounting Ledger General Ledger (Version 1.02, Last updated 18/08/2020).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="accountAccountingLedger">
  '''  The Accounting Ledger to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Accounting Ledgers page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Summary.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_AccountingLedgers_GeneralLedger(callerScriptInfo As ISScriptExecutionInfo,
                                                                      accountAccountingLedger As finAccountAccountingLedger,
                                                             Optional includeActions As Boolean = True,
                                                             Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim EarnedText As String
    Dim UnearnedText As String
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      .Columns.AddText(12).NoBreakChars = 15
      .Columns.AddText()

      If accountAccountingLedger Is Nothing Then
        ' Accounting Ledger not specified
      Else
        ' Terminology
        Select Case accountAccountingLedger.Type
          Case isefinAccountingLedgerType.SimpleJournal
            EarnedText = "Credit"
            UnearnedText = "Debit"
          Case Else
            EarnedText = "Earned"
            UnearnedText = "Unearned"
        End Select

        With .Rows
          ' GL Account
          If Len(accountAccountingLedger.UnearnedGlAccountId) = 0 Then
            .AddCaptionText("GL Account:", "Not specified", iseSummaryTableCellClass.Warning)
          ElseIf Not finBL.GlAccounts.Exists(accountAccountingLedger.UnearnedGlAccountId) Then
            .AddCaptionText("GL Account:", "Invalid", iseSummaryTableCellClass.Warning)
          ElseIf Len(accountAccountingLedger.GlAccountId) = 0 Then
            .AddCaptionText("GL Account:", "Not specified", iseSummaryTableCellClass.Warning)
          ElseIf Not finBL.GlAccounts.Exists(accountAccountingLedger.GlAccountId) Then
            .AddCaptionText("GL Account:", "Invalid", iseSummaryTableCellClass.Warning)
          ElseIf accountAccountingLedger.UnearnedGlAccountId = accountAccountingLedger.GlAccountId Then
            .AddCaptionCodeDescription("GL Account:", accountAccountingLedger.UnearnedGlAccountId, finBL.GlAccounts)
          Else
            .AddCaptionWiki("GL Account:", String.Format("**{0}**, {1} --({2})--", accountAccountingLedger.UnearnedGlAccountId, finBL.GlAccounts(accountAccountingLedger.UnearnedGlAccountId).Description, UnearnedText))
            .AddCaptionWiki("", String.Format("**{0}**, {1} --({2})--", accountAccountingLedger.GlAccountId, finBL.GlAccounts(accountAccountingLedger.GlAccountId).Description, EarnedText))
          End If

          ' Branch
          If Len(accountAccountingLedger.UnearnedBranchId) = 0 Then
            .AddCaptionText("Branch:", "Not specified", iseSummaryTableCellClass.Warning)
          ElseIf Not finBL.Branches.Exists(accountAccountingLedger.UnearnedBranchId) Then
            .AddCaptionText("Branch:", "Invalid", iseSummaryTableCellClass.Warning)
          ElseIf Len(accountAccountingLedger.BranchId) = 0 Then
            .AddCaptionText("Branch:", "Not specified", iseSummaryTableCellClass.Warning)
          ElseIf Not finBL.Branches.Exists(accountAccountingLedger.BranchId) Then
            .AddCaptionText("Branch:", "Invalid", iseSummaryTableCellClass.Warning)
          ElseIf accountAccountingLedger.UnearnedBranchId = accountAccountingLedger.BranchId Then
            .AddCaptionCodeDescription("Branch:", accountAccountingLedger.UnearnedBranchId, finBL.Branches(accountAccountingLedger.UnearnedBranchId).Description)
          Else
            .AddCaptionWiki("Branch:", String.Format("**{0}**, {1} --({2})--", accountAccountingLedger.UnearnedBranchId, finBL.Branches(accountAccountingLedger.UnearnedBranchId).Description, UnearnedText))
            .AddCaptionWiki("", String.Format("**{0}**, {1} --({2})--", accountAccountingLedger.BranchId, finBL.Branches(accountAccountingLedger.BranchId).Description, EarnedText))
          End If

          ' Department
          If Len(accountAccountingLedger.UnearnedDepartmentId) = 0 Then
            .AddCaptionText("Department:", "Not specified", iseSummaryTableCellClass.Warning)
          ElseIf Not finBL.Departments.Exists(accountAccountingLedger.UnearnedDepartmentId) Then
            .AddCaptionText("Department:", "Invalid", iseSummaryTableCellClass.Warning)
          ElseIf Len(accountAccountingLedger.UnearnedDepartmentId) = 0 Then
            .AddCaptionText("Department:", "Not specified", iseSummaryTableCellClass.Warning)
          ElseIf Not finBL.Departments.Exists(accountAccountingLedger.UnearnedDepartmentId) Then
            .AddCaptionText("Department:", "Invalid", iseSummaryTableCellClass.Warning)
          ElseIf accountAccountingLedger.UnearnedDepartmentId = accountAccountingLedger.DepartmentId Then
            .AddCaptionCodeDescription("Department:", accountAccountingLedger.UnearnedDepartmentId, finBL.Departments(accountAccountingLedger.UnearnedDepartmentId).Description)
          Else
            .AddCaptionWiki("Department:", String.Format("**{0}**, {1} --({2})--", accountAccountingLedger.UnearnedDepartmentId, finBL.Departments(accountAccountingLedger.UnearnedDepartmentId).Description, UnearnedText))
            .AddCaptionWiki("", String.Format("**{0}**, {1} --({2})--", accountAccountingLedger.DepartmentId, finBL.Departments(accountAccountingLedger.DepartmentId).Description, EarnedText))
          End If
        End With
      End If

      ' Warnings
      If accountAccountingLedger.GlEomSplit Then
        Warnings &= "{{info|Journals will be split and apportioned at month end.}}"
      End If
      .TextAfter = Warnings
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Accounting Ledger Journals (Version 1.0, Last updated 23/02/2016).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="accountAccountingLedger">
  '''  The Accounting Ledger to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Accounting Ledgers page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Summary.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_AccountingLedgers_Journals(callerScriptInfo As ISScriptExecutionInfo,
                                                                 accountAccountingLedger As finAccountAccountingLedger,
                                                        Optional includeActions As Boolean = True,
                                                        Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim Accrual As finAccountAccountingLedgerAccrual
    Dim i As Integer
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .AutoStripe = True
      .Caption = ""
      .WidthHtml = "*"

      If accountAccountingLedger Is Nothing Then
        ' Accounting Ledger not specified
      Else
        If accountAccountingLedger.Accruals.Count = 0 Then
          If accountAccountingLedger.Status = isefinAccountingLedgerStatus.Hold Then
            Warnings &= "{{info|Not yet specified.}}"
          Else
            Warnings &= "{{warning|Not specified.}}"
          End If
        Else
          ' Columns
          With .Columns
            .AddInteger("#", 3)
            .AddDate("Date")
            .AddBoolean("Opening")
            .AddCurrency("Value", 20)
            .AddCurrency("Transferred", 20)
            .AddCurrency("Remaining", 20)
          End With

          ' Add Accrual Rows
          For i = 0 To accountAccountingLedger.Accruals.Count - 1
            Accrual = accountAccountingLedger.Accruals(i)

            With .Rows.Add().Cells
              .AddInteger(i)
              .AddDate(Accrual.Date)
              .AddTick(Accrual.Opening, False, True)
              .AddCurrency(Accrual.Value, True)
              .AddCurrency(Accrual.ValueTransferred, True)
              .AddCurrency(Accrual.ValueRemaining, True)
            End With
          Next
        End If
      End If

      ' Warnings
      .TextAfter = Warnings
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Accounting Ledger Summary (Version 1.0, Last updated 24/02/2016).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="accountAccountingLedgers">
  '''  The Accounting Ledger collection to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Accounting Ledgers page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Summary.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_AccountingLedgers_Summary(callerScriptInfo As ISScriptExecutionInfo,
                                                                accountAccountingLedgers As finAccountAccountingLedgers,
                                                       Optional includeActions As Boolean = True,
                                                       Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim strTemp As String
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""

      ' Columns
      With .Columns
        .AddText(12).NoBreakChars = 15
        .AddCurrency(15)
        .AddText()
      End With

      With .Rows
        ' General
        If accountAccountingLedgers.TotalHeld <> 0 Then
          With .AddCaptionCurrency("On Hold:", accountAccountingLedgers.TotalValueHeld, True)
            If accountAccountingLedgers.TotalHeld = 1 Then
              .Cells.AddWiki("1 Accounting Ledger 'On Hold'")
            Else
              .Cells.AddWiki(String.Format("{0} Accounting Ledgers 'On Hold'", accountAccountingLedgers.TotalHeld))
            End If
          End With
        End If
        With .AddCaptionCurrency("Active:", accountAccountingLedgers.TotalValueOpeningActive, "", True)
          strTemp = ""
          Select Case accountAccountingLedgers.TotalActive
            Case 0
            Case 1
              strTemp &= "1 'Active' Accounting Ledger"
            Case Else
              strTemp &= String.Format("{0} 'Active' Accounting Ledgers", accountAccountingLedgers.TotalActive)
          End Select
          Select Case accountAccountingLedgers.TotalSuspended
            Case 0
            Case 1
              If Len(strTemp) <> 0 Then strTemp &= " and "
              strTemp &= "1 'Suspended' Accounting Ledger"
              Warnings &= "{{warning|There is a 'Suspended' Accounting Ledger.}}"
            Case Else
              If Len(strTemp) <> 0 Then strTemp &= " and "
              strTemp &= String.Format("{0} 'Suspended' Accounting Ledgers", accountAccountingLedgers.TotalSuspended)
              Warnings &= "{{warning|There are 'Suspended' Accounting Ledgers.}}"
          End Select

          If Len(strTemp) <> 0 Then .Cells.AddWiki(strTemp)
        End With
        .AddCaptionCurrency(" Transferred:", accountAccountingLedgers.TotalValueTransferredEarnedActive, "", True)
        .AddCaptionCurrency(" Remaining:", accountAccountingLedgers.TotalValueRemainingActive, "", True)
      End With

      ' Warnings
      .TextAfter = Warnings
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Accounting Ledger Summary Item (Version 1.0, Last updated 23/02/2016).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="accountAccountingLedger">
  '''  The Accounting Ledger to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Accounting Ledgers page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Summary.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_AccountingLedgers_SummaryItem(callerScriptInfo As ISScriptExecutionInfo,
                                                                    accountAccountingLedger As finAccountAccountingLedger,
                                                           Optional includeActions As Boolean = True,
                                                           Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim strTemp As String
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      .Columns.AddText(12).NoBreakChars = 15
      .Columns.AddText()

      With .Rows
        If accountAccountingLedger Is Nothing Then
          If accountAccountingLedger.Account.AccountingLedgers.Count = 0 Then
            Warnings &= "{{info|No Accounting Ledgers entered.}}"
          Else
            Warnings &= "{{info|Please select an Accounting Ledger.}}"
          End If
        Else
          ' Used in the Activate Accounting Ledgers wizard
          If accountAccountingLedger.ParentAccountAccountingLedgersActivateItem IsNot Nothing Then
            With .AddCaptionText("Code:", accountAccountingLedger.ParentAccountAccountingLedgersActivateItem.AccountId)
              .Cells(1).HyperlinkSetFormShow("Accounts", accountAccountingLedger.ParentAccountAccountingLedgersActivateItem.AccountId, "Accounting Ledgers")
            End With
            .AddCaptionText("Name:", accountAccountingLedger.ParentAccountAccountingLedgersActivateItem.AccountName, iseSummaryTableCellClass.Highlight1)
            .AddSectionHeading2("Accounting Ledger Details")
          End If

          ' General
          .AddCaptionText("Description:", accountAccountingLedger.Description)
          .AddCaptionCodeDescription("Element:", accountAccountingLedger.ElementId, finBL.Elements)
          Select Case accountAccountingLedger.Status
            Case isefinAccountingLedgerStatus.Active
              .AddCaptionText("Status:", accountAccountingLedger.StatusText, iseSummaryTableCellClass.PositiveBold)
            Case isefinAccountingLedgerStatus.Hold
              .AddCaptionText("Status:", accountAccountingLedger.StatusText, iseSummaryTableCellClass.WarningBold)
            Case isefinAccountingLedgerStatus.Cancel, isefinAccountingLedgerStatus.Cancelled, isefinAccountingLedgerStatus.Reverse, isefinAccountingLedgerStatus.Reversed
              If accountAccountingLedger.CancelledDate = Nothing Then
                .AddCaptionText("Status:", accountAccountingLedger.StatusText, iseSummaryTableCellClass.WarningBold)
              Else
                .AddCaptionWiki("Status:", String.Format("!!**{0}**!! --by {1}--", accountAccountingLedger.StatusText, finBL.Utilities.GetUserAndDateWikiText("", accountAccountingLedger.CancelledUserPk, accountAccountingLedger.CancelledDate)))
              End If
            Case Else
              .AddCaptionText("Status:", accountAccountingLedger.StatusText)
          End Select
          .AddCaptionText("Classification:", accountAccountingLedger.Classification)

          If (accountAccountingLedger.Status = isefinAccountingLedgerStatus.Active Or accountAccountingLedger.Status = isefinAccountingLedgerStatus.Complete) AndAlso accountAccountingLedger.Accruals.TotalTransferredEarned <> 0 Then
            strTemp = String.Format("--({0} transferred)--", finBL.FormatCurrency(-accountAccountingLedger.Accruals.TotalTransferredEarned, True))
          Else
            strTemp = ""
          End If
          .AddCaptionCurrency("Value:", accountAccountingLedger.Value, strTemp, True)

          ' Method
          .AddText("Method", iseSummaryTableCellClass.SectionHeading2)
          .AddCaptionText("Type:", accountAccountingLedger.TypeText)
          .AddCaptionText("Method:", accountAccountingLedger.MethodDescription)
          .AddCaptionDate("Opening:", accountAccountingLedger.DateBegin)

          ' Frequency
          Select Case accountAccountingLedger.Method
            Case isefinAccountingLedgerMethod.AtClose
            Case isefinAccountingLedgerMethod.AtMaturity
              If accountAccountingLedger.DateEnd = Nothing Then
                .AddCaptionText("Ending:", "Not specified", iseSummaryTableCellClass.Warning)
              Else
                .AddCaptionDate("Ending:", accountAccountingLedger.DateEnd)
              End If
            Case isefinAccountingLedgerMethod.ContractualInterest
            Case isefinAccountingLedgerMethod.Custom
            Case isefinAccountingLedgerMethod.OnDate
              If accountAccountingLedger.DateEnd = Nothing Then
                .AddCaptionText("Ending:", "Not specified")
              Else
                .AddCaptionDate("Ending:", accountAccountingLedger.DateEnd)
              End If
            Case Else
              If accountAccountingLedger.NumberOfPeriods = 0 Then
                .AddCaptionText("Frequency:", "Not specified", iseSummaryTableCellClass.Warning)
              ElseIf Right(finBL.Utilities.DateCycleGetMnemonicFriendly(True, accountAccountingLedger.FrequencyCycle), 2) = "ly" Then
                .AddCaptionText("Frequency:", String.Format("{0} due {1}", accountAccountingLedger.NumberOfPeriods, finBL.Utilities.DateCycleGetMnemonicFriendly(True, accountAccountingLedger.FrequencyCycle)))
              Else
                .AddCaptionText("Frequency:", String.Format("{0} due {1}", accountAccountingLedger.NumberOfPeriods, accountAccountingLedger.FrequencyCycleDescription))
              End If
              If accountAccountingLedger.DateFirst = Nothing Then
                .AddCaptionText("First:", "Not specified", iseSummaryTableCellClass.Warning)
              Else
                .AddCaptionDate("First:", accountAccountingLedger.DateFirst)
              End If
              If accountAccountingLedger.DateEnd = Nothing Then
                .AddCaptionText("Ending:", "Not specified", iseSummaryTableCellClass.Warning)
              Else
                .AddCaptionDate("Ending:", accountAccountingLedger.DateEnd)
              End If
          End Select
        End If
      End With

      ' Warnings
      .TextAfter = Warnings
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Financial Summary.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="account">
  '''  The Account to summarise.
  ''' </param>
  ''' <param name="accountCalc">
  '''  The Account Calculation.
  ''' </param>
  ''' <param name="accountSummary">
  '''  The Account Summary.
  ''' </param>
  ''' <param name="includeAccruals">
  '''  Indicates whether to include accrued Interest etc.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Account Financial page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_FinancialSummary(callerScriptInfo As ISScriptExecutionInfo,
                                                       account As finAccount,
                                              Optional accountCalc As finAccountCalc = Nothing,
                                              Optional accountSummary As finAccountSummary = Nothing,
                                              Optional includeAccruals As Boolean = True,
                                              Optional includeActions As Boolean = True,
                                              Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' Account_FinancialSummary
    '
    ' Version: 1.07 (24/07/2024)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.05  22/11/2018  ISS                  
    '    1.06  04/01/2024  ISS      J032505   Remove reference to obsoleted finBL.Settings.AccountProcessAllowOptimisations property
    '    1.07  24/07/2024  ISS      J032515   Updated to use Other Interest description
    ' #################################################################

    Dim AccountSummaryItem As finAccountSummaryItem
    Dim AccruedInterest As Decimal
    Dim AccruedDefaultInterest As Decimal
    Dim AccruedOtherInterest As Decimal
    Dim AccruedToDate As String
    Dim AccruedWithholdingTax As Decimal
    Dim Balance As Decimal
    Dim DateAsAt As Date
    Dim RowClass As iseSummaryTableRowClass
    Dim SummaryTableRow As ISSummaryTableRow
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim UnpostedDefaultFees As Decimal
    Dim UnpostedFacilityFees As Decimal
    Dim UnpostedOverLimitFees As Decimal
    Dim UnpostedStandardTransactions As Decimal
    Dim Warnings As String

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Date As At
    DateAsAt = finBL.TimeZoneFunctions.GetCurrentDatabaseDate()

    ' Get Calculation
    If accountCalc Is Nothing Then
      accountCalc = account.Calculation
      accountSummary = account.Summary
      includeAccruals = (account.Status = isefinAccountStatus.Open)
    End If

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .Caption = ""
      .Columns.AddText().NoBreakChars = 20
      .Columns.AddCurrency()

      If accountSummary IsNot Nothing Then
        For Each AccountSummaryItem In accountSummary
          With AccountSummaryItem
            ' Row Class
            If .IsTotalItem Then
              RowClass = iseSummaryTableRowClass.FooterBold
            ElseIf .GroupValue Then
              RowClass = iseSummaryTableRowClass.Alt2
            Else
              RowClass = iseSummaryTableRowClass.Alt1
            End If

            ' Add Row
            SummaryTableRow = SummaryTableMain.Rows.Add(RowClass)
            If .IsTotalItem Then
              SummaryTableRow.Cells.AddCaption(.Description)
              ' Reverse signs for Deposits
              Select Case account.AccountClass
                Case isefinAccountClass.Deposit
                  SummaryTableRow.Cells.AddCurrency(- .Balance, True)
                Case Else
                  SummaryTableRow.Cells.AddCurrency(.Balance, True)
              End Select
            Else
              If .ElementType = isefinElementType.Interest AndAlso includeAccruals Then
                If accountCalc.OptionInterestChargeUpfront Then
                  If .ElementPk = accountCalc.AccountType.InterestCreditElementPk OrElse .ElementPk = accountCalc.AccountType.InterestDebitElementPk Then
                    SummaryTableRow.Cells.AddCaption(String.Format("{0} precomputed to {1}", .Description, finBL.FormatDate(accountCalc.DateMaturity.AddDays(-1), True)))
                  ElseIf .ElementPk = accountCalc.AccountType.DefaultInterestElementPk Then
                    SummaryTableRow.Cells.AddCaption(String.Format("{0} to {1}", .Description, finBL.FormatDate(accountCalc.InterestChargedTo, True)))
                  Else
                    SummaryTableRow.Cells.AddCaption(.Description)
                  End If
                Else
                  If .ElementPk = accountCalc.AccountType.InterestCreditElementPk OrElse .ElementPk = accountCalc.AccountType.InterestDebitElementPk Then
                    If accountCalc.InterestChargedTo <> Nothing Then
                      SummaryTableRow.Cells.AddCaption(String.Format("{0} to {1}", .Description, finBL.FormatDate(accountCalc.InterestChargedTo, True)))
                    Else
                      SummaryTableRow.Cells.AddCaption(.Description)
                    End If
                  Else
                    SummaryTableRow.Cells.AddCaption(.Description)
                  End If
                End If
              Else
                SummaryTableRow.Cells.AddCaption(.Description)
              End If

              ' Reverse signs for Deposits
              Select Case account.AccountClass
                Case isefinAccountClass.Deposit
                  SummaryTableRow.Cells.AddCurrency(- .Value)
                Case Else
                  SummaryTableRow.Cells.AddCurrency(.Value)
              End Select
            End If
          End With
        Next
      End If
    End With

    ' Balance plus Accruals to Net Balance
    If includeAccruals Then
      ' Get Values
      accountCalc.Schedule.GetAccruals(DateAsAt.AddDays(-1), AccruedInterest, AccruedDefaultInterest, AccruedOtherInterest,, AccruedWithholdingTax)
      accountCalc.Schedule.GetUnposted(DateAsAt, UnpostedDefaultFees, UnpostedOverLimitFees, UnpostedFacilityFees, UnpostedStandardTransactions)
      AccruedToDate = finBL.FormatDate(DateAsAt.AddDays(-1), True)
      If accountSummary Is Nothing OrElse accountSummary.Count = 0 Then
        Balance = 0
      Else
        Balance = accountSummary(accountSummary.Count - 1).Balance
      End If

      ' Reverse values for Deposits
      Select Case account.AccountClass
        Case isefinAccountClass.Deposit
          AccruedInterest = -AccruedInterest
          AccruedDefaultInterest = -AccruedDefaultInterest
          AccruedOtherInterest = -AccruedOtherInterest
          AccruedWithholdingTax = -AccruedWithholdingTax
          UnpostedDefaultFees = -UnpostedDefaultFees
          UnpostedOverLimitFees = -UnpostedOverLimitFees
          UnpostedFacilityFees = -UnpostedFacilityFees
          UnpostedStandardTransactions = -UnpostedStandardTransactions
          Balance = -Balance
      End Select

      If accountCalc.OptionInterestChargeUpfront AndAlso DateAsAt <= accountCalc.DateMaturity Then
        ' Ignore
      Else
        Select Case account.AccountClass
          Case isefinAccountClass.Disbursement
          Case Else
            If account.SuspendInterest Then
              SummaryTableMain.Rows.AddCaptionCurrency("Interest Suspended", AccruedInterest)
            ElseIf AccruedWithholdingTax = 0 Then
              SummaryTableMain.Rows.AddCaptionCurrency(String.Format("Accrued Interest to {0}", AccruedToDate), AccruedInterest)
            Else
              SummaryTableMain.Rows.AddCaptionCurrency(String.Format("Accrued Interest to {0}<br>  --{1} less Withholding Tax {2}--", AccruedToDate, finBL.FormatCurrency(AccruedInterest, True), finBL.FormatCurrency(-AccruedWithholdingTax, True)), AccruedInterest + AccruedWithholdingTax, "",,, True)
            End If
            AccruedToDate = ""

            ' Warning if Backdating
            If accountCalc.AccountType IsNot Nothing Then
              Select Case accountCalc.AccountType.OptionInterestBackdating
                Case isefinAccountInterestBackdating.Reverse
                  If accountCalc.InterestBackdatedTo <> Nothing AndAlso accountCalc.InterestBackdatedTo <= accountCalc.InterestChargedTo Then
                    Warnings &= "{{info|" & String.Format("Accruals backdated to {0}", finBL.FormatDate(accountCalc.InterestBackdatedTo, True) & "}}")
                  End If
              End Select
            End If
        End Select
      End If
      If AccruedDefaultInterest <> 0 Then
        If Len(AccruedToDate) = 0 Then
          SummaryTableMain.Rows.AddCaptionCurrency("Accrued Default Interest", AccruedDefaultInterest)
        Else
          SummaryTableMain.Rows.AddCaptionCurrency(String.Format("Accrued Default Interest to {0}", AccruedToDate), AccruedDefaultInterest)
          AccruedToDate = ""
        End If
      End If
      If AccruedOtherInterest <> 0 Then
        SummaryTableMain.Rows.AddCaptionCurrency("Accrued " & account.AccountType.OtherInterestDescriptionResolved, AccruedOtherInterest)
      End If
      If UnpostedDefaultFees <> 0 Then
        SummaryTableMain.Rows.AddCaptionCurrency("Default Fees not yet posted", UnpostedDefaultFees)
      End If
      If UnpostedOverLimitFees <> 0 Then
        SummaryTableMain.Rows.AddCaptionCurrency("Over Limit Fees not yet posted", UnpostedOverLimitFees)
      End If
      If UnpostedFacilityFees <> 0 Then
        SummaryTableMain.Rows.AddCaptionCurrency("Facility Fees not yet posted", UnpostedFacilityFees)
      End If
      If UnpostedStandardTransactions <> 0 Then
        SummaryTableMain.Rows.AddCaptionCurrency("Transactions not yet posted", UnpostedStandardTransactions)
      End If
      SummaryTableMain.Rows.AddCaptionCurrency("Net Balance", Balance + AccruedInterest + AccruedWithholdingTax + AccruedDefaultInterest + AccruedOtherInterest + UnpostedDefaultFees + UnpostedOverLimitFees + UnpostedFacilityFees + UnpostedStandardTransactions, True, iseSummaryTableRowClass.FooterBold)

      ' Next Process Date information
      If finBL.Runtime.IsIntersoftUser AndAlso account.DateProcessNext <> Nothing Then
        Warnings &= "{{info|" & String.Format("Next Process date {0}", finBL.FormatDateLong(account.DateProcessNext) & "}}")
      End If
    End If

    ' Warnings
    SummaryTableMain.TextAfter = Warnings

    ' Actions
    If includeActions Then
      With SummaryTableMain.Actions
        If account.SupportsInterest AndAlso includeAccruals Then
          .AddFormAction("InterestAdjustment", "Adjust Interest", Not finBL.Database.IsReadOnly AndAlso account.Status = isefinAccountStatus.Open AndAlso finBL.CurrentUser.Permissions.Allow("Account.InterestAdjustment")).ShowInWebInterfaces = True
        End If
      End With
    End If

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Banking Details Summary.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="account">
  '''  The Account to summarise.
  ''' </param>
  ''' <param name="accountBankingDetailsType">
  '''  The type of Banking Details to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Payments page and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_BankingDetailsSummary(callerScriptInfo As ISScriptExecutionInfo,
                                                            account As finAccount,
                                                            accountBankingDetailsType As isefinAccountBankingDetailsType,
                                                   Optional includeActions As Boolean = True,
                                                   Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' Account_BankingDetailsSummary
    '
    ' Version: 1.18 (08/08/2024)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.09  04/05/2021  ISS                  
    '    1.10  23/07/2021  ISS      J027056            
    '    1.11  06/09/2021  ISS      J027325   Re-brand Split to Zepto
    '    1.12  29/10/2021  ISS      J027660   Direct Debit Stop, apply to Minimum Payments only
    '    1.13  26/10/2022  ISS      J029865   Add Zepto NZ
    '    1.14  06/03/2023  ISS      J030593   Handle Deposit Maturity details better
    '          06/03/2023  ISS      J030594   Handle Deposit Interest details better
    '    1.15  21/08/2023  ISS      J031832   Added reference to finAccount.CanStopDirectDebits()
    '    1.16  20/02/2024  ISS      J032155   Add PayTo 
    '    1.17  01/07/2024  ISS      J032289   Add Monoova
    '    1.18  08/08/2024  ISS      J034055   Added Service for PayTo categories
    ' #################################################################

    Dim AccountBankingPayToItem As finAccountBankingPayToItem
    Dim BankDetails As String
    Dim BankingDetails As finBankingDetails
    Dim Caption As String
    Dim Code As String
    Dim CodeResolved As String
    Dim DateAsAt As Date
    Dim DescriptionResolved As String
    Dim Particulars As String
    Dim ParticularsResolved As String
    Dim PaymentMethod As finPaymentMethodRO
    Dim PaymentTypeCategory As isefinPaymentTypeCategory
    Dim Reference As String
    Dim ReferenceResolved As String
    Dim ShowWarning As Boolean
    Dim strTemp As String
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Date As At
    DateAsAt = finBL.TimeZoneFunctions.GetCurrentDatabaseDate()

    ' Get Payment Method
    If account.BankingDetails.ExistsBankingDetailsType(accountBankingDetailsType) Then
      PaymentMethod = account.BankingDetails(accountBankingDetailsType).BankingDetails.PaymentMethod
      If PaymentMethod IsNot Nothing Then
        PaymentTypeCategory = PaymentMethod.PaymentTypeCategory
      End If

      ' Get Bank Details, potentially masked
      BankingDetails = account.BankingDetails(accountBankingDetailsType).BankingDetails.CloneForDisplay()
    Else
      PaymentMethod = Nothing
    End If

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      .Columns.AddText(16).NoBreakChars = 16
      .Columns.AddText()

      If PaymentMethod Is Nothing Then
        ' No Details
        ShowWarning = True
        Select Case account.AccountClass
          Case isefinAccountClass.Deposit
            Select Case accountBankingDetailsType
              Case isefinAccountBankingDetailsType.Outgoing
                Select Case account.Calculation.InterestPaymentType
                  Case isefinAccountInterestPaymentType.Capitalise, isefinAccountInterestPaymentType.Compound, isefinAccountInterestPaymentType.Transfer
                    ShowWarning = False
                End Select

              Case isefinAccountBankingDetailsType.Maturity
                Select Case account.MaturityInstruction
                  Case isefinAccountMaturityInstruction.ToBeAdvised, isefinAccountMaturityInstruction.ReinvestAll
                    ShowWarning = False
                  Case Else
                    Select Case account.MaturityPaymentType
                      Case isefinAccountMaturityPaymentType.Transfer
                        ShowWarning = False
                    End Select
                End Select
            End Select
        End Select

        If ShowWarning Then
          Warnings &= "{{info|Payment details have not been entered for this Account.}}"
        End If
      ElseIf Not finBL.CurrentUser.Permissions.Allow("Banking.ShowAccountDetails") Then
        ' No Permission to view
        With .Rows
          .AddCaptionCodeDescription("Pay Method:", PaymentMethod.PaymentMethodId, PaymentMethod.Description)
        End With
      Else
        With .Rows
          ' General
          .AddCaptionCodeDescription("Pay Method:", PaymentMethod.PaymentMethodId, PaymentMethod.Description)

          ' Direct Debit
          If PaymentMethod.IsDirectDebit Then
            If account.PaymentDDStopToDate <> Nothing Then
              ' Stopped
              .AddCaptionDate("Stopped to:", account.PaymentDDStopToDate, "(including this date)")

              ' Warning if Currently Stopped
              If account.PaymentDDStopToDate >= DateAsAt Then
                If account.PaymentDDStopMinimumPaymentsOnly Then
                  Warnings &= "{{warning|Payments dated on or before **" & finBL.FormatDateLong(account.PaymentDDStopToDate) & "** will not be Direct Debited (applies to Minimum Payments only).}}"
                Else
                  Warnings &= "{{warning|Payments dated on or before **" & finBL.FormatDateLong(account.PaymentDDStopToDate) & "** will not be Direct Debited.}}"
                End If
              End If
            End If
          End If

          ' Type-Specific
          Select Case PaymentTypeCategory
            Case isefinPaymentTypeCategory.Bank
              ' ----
              ' Bank
              ' ----
              ' Find Bank/ Branch information
              If finBL.SupportedCountries.CurrentSupportedCountry.ValidateBankBranch(BankingDetails, "") Then
                With BankingDetails
                  If Len(.BankName) = 0 Then
                    BankDetails = finBL.Runtime.TextUtilities.ListSeparate(", ", .BankNameShort, .BankBranchName)
                  Else
                    BankDetails = finBL.Runtime.TextUtilities.ListSeparate(", ", .BankName & " (" & .BankNameShort & ")", .BankBranchName)
                  End If
                End With
              Else
                BankDetails = ""
              End If

              ' Bank Sort Code and Account Number
              If finBL.CurrentCountry.SupportsBankSortCode Then
                .AddCaptionText(finBL.CurrentCountry.Terminology(isefinCountryTerminology.BankSortCode, True) & ":", BankingDetails.AccountSortCode)
                If Len(BankDetails) <> 0 Then .AddCaptionText("", BankDetails)
                .AddCaptionText("Account No:", BankingDetails.AccountNumber)
              Else
                .AddCaptionText("Account No:", BankingDetails.AccountNumber)
                If Len(BankDetails) <> 0 Then .AddCaptionText("", BankDetails)
              End If

              ' Account Name
              .AddCaptionText("Name:", BankingDetails.AccountName)

              ' Reference
              Select Case finBL.CountryCode
                Case "NZ"
                  ' Split Reference into Particulars, Code and Reference and Resolve
                  BankingDetails.Reference_SplitNZ(Particulars, Code, Reference)
                  BankingDetails.ReferenceResolved_SplitNZ(account, ParticularsResolved, CodeResolved, ReferenceResolved)

                  With .AddCaptionWiki("Particulars:", "**" & Particulars & "**")
                    If Particulars <> ParticularsResolved Then .Cells(1).Value &= String.Format(" --resolves to-- **{0}**", ParticularsResolved)
                  End With
                  With .AddCaptionWiki("Code:", "**" & Code & "**")
                    If Code <> CodeResolved Then .Cells(1).Value &= String.Format(" --resolves to-- **{0}**", CodeResolved)
                  End With
                  With .AddCaptionWiki("Reference:", "**" & Reference & "**")
                    If Reference <> ReferenceResolved Then .Cells(1).Value &= String.Format(" --resolves to-- **{0}**", ReferenceResolved)
                  End With

                Case Else
                  ' Resolve Reference
                  ReferenceResolved = BankingDetails.ReferenceResolved(account)

                  With .AddCaptionWiki("Reference:", "**" & BankingDetails.Reference & "**")
                    If BankingDetails.Reference <> ReferenceResolved Then .Cells(1).Value &= String.Format(" --resolves to-- **{0}**", ReferenceResolved)
                  End With
              End Select

              ' Warnings
              If Not account.BankingDetails(accountBankingDetailsType).BankingDetails.IsValid(True, False) Then
                strTemp = finBL.Error.Message(True, True)
                If Len(strTemp) <> 0 Then
                  Warnings &= "{{warning|" & strTemp & "}}"
                End If
              End If

            Case isefinPaymentTypeCategory.Cheque
              ' ------
              ' Cheque
              ' ------
              If BankingDetails.PaymentFlowDirection = isefinPaymentMethodPaymentFlowDirection.Incoming Then
                ' Find Bank/ Branch information
                If Len(BankingDetails.AccountSortCode) <> 0 OrElse Len(BankingDetails.BankNameShort) <> 0 OrElse Len(BankingDetails.BankBranchName) <> 0 Then
                  If Len(BankingDetails.AccountSortCode) = 0 Then
                    Caption = "Bank/Branch"
                    strTemp = ""
                  Else
                    Caption = finBL.SupportedCountries.CurrentSupportedCountry.Terminology(isefinCountryTerminology.BankSortCode)
                    strTemp = BankingDetails.AccountSortCode
                    If Len(BankingDetails.BankNameShort) <> 0 OrElse Len(BankingDetails.BankBranchName) <> 0 Then If Len(strTemp) <> 0 Then strTemp &= "; "
                  End If
                  If Len(BankingDetails.BankNameShort) <> 0 Then
                    strTemp &= BankingDetails.BankNameShort
                    If Len(BankingDetails.BankBranchName) <> 0 Then strTemp &= ", "
                  End If
                  If Len(BankingDetails.BankBranchName) <> 0 Then
                    strTemp &= BankingDetails.BankBranchName
                  End If
                Else
                  Caption = "Bank/Branch"
                End If

                .AddCaptionText("Drawer:", BankingDetails.AccountName)
                .AddCaptionText(Caption & ":", strTemp)
              Else
                .AddCaptionText("Payee:", BankingDetails.AccountName)
              End If

            Case isefinPaymentTypeCategory.CreditCard, isefinPaymentTypeCategory.PosCard
              ' ----------------
              ' Credit/ POS Card
              ' ----------------
              ' Resolve Reference
              ReferenceResolved = BankingDetails.ReferenceResolved(account)

              .AddCaptionText("Card Type:", PaymentMethod.PaymentType.Description)
              .AddCaptionText("Card No:", BankingDetails.AccountNumber)
              .AddCaptionText("Card Name:", BankingDetails.AccountName)
              If BankingDetails.CardExpiryDate = Nothing Then
                .AddCaptionText("Card Expiry:", "")
              Else
                .AddCaptionText("Card Expiry:", Format(BankingDetails.CardExpiryDate, "MM/yyyy"))
              End If

              If Len(BankingDetails.Reference) <> 0 Then
                With .AddCaptionWiki("Reference:", "**" & BankingDetails.Reference & "**")
                  If BankingDetails.Reference <> ReferenceResolved Then
                    .Cells(1).Value &= String.Format(" --resolves to-- **{0}**", ReferenceResolved)
                  End If
                End With
              End If

              ' Warnings
              If PaymentTypeCategory = isefinPaymentTypeCategory.CreditCard Then
                If Not account.BankingDetails(accountBankingDetailsType).BankingDetails.IsValid(True, False) Then
                  Warnings &= "{{warning|" & finBL.Error.Message(True, True) & "}}"
                End If
              End If
              If BankingDetails.CardExpiryDate = Nothing Then
                Warnings &= "{{warning|Expiry date not entered.}}"
              ElseIf BankingDetails.CardExpiryDate < DateAsAt Then
                Warnings &= "{{warning|Card has expired.}}"
              ElseIf BankingDetails.CardExpiryDate < DateSerial(Year(DateAsAt), Month(DateAsAt) + 2, 1) Then
                Warnings &= "{{info|Card expires soon.}}"
              End If

            Case isefinPaymentTypeCategory.Ezidebit
              ' --------
              ' Ezidebit
              ' --------
              .AddCaptionText("Name:", BankingDetails.AccountName)
              .AddCaptionText("Ezidebit Customer:", BankingDetails.ExternalId)

              ' Warnings
              If Not BankingDetails.IsValid(False, False) Then
                Warnings &= "{{Warning|" & finBL.Error.Message(True, True) & "}}"
              End If

            Case isefinPaymentTypeCategory.Monoova
              ' -------
              ' Monoova
              ' -------
              ' Find Bank/ Branch information
              If finBL.SupportedCountries.CurrentSupportedCountry.ValidateBankBranch(BankingDetails, "") Then
                With BankingDetails
                  If Len(.BankName) = 0 Then
                    BankDetails = finBL.Runtime.TextUtilities.ListSeparate(", ", .BankNameShort, .BankBranchName)
                  Else
                    BankDetails = finBL.Runtime.TextUtilities.ListSeparate(", ", .BankName & " (" & .BankNameShort & ")", .BankBranchName)
                  End If
                End With
              Else
                BankDetails = ""
              End If

              ' Bank Sort Code and Account Number
              If finBL.CurrentCountry.SupportsBankSortCode Then
                .AddCaptionText(finBL.CurrentCountry.Terminology(isefinCountryTerminology.BankSortCode, True) & ":", BankingDetails.AccountSortCode)
                If Len(BankDetails) <> 0 Then .AddCaptionText("", BankDetails)
                .AddCaptionText("Account No:", BankingDetails.AccountNumber)
              Else
                .AddCaptionText("Account No:", BankingDetails.AccountNumber)
                If Len(BankDetails) <> 0 Then .AddCaptionText("", BankDetails)
              End If

              ' Account Name
              .AddCaptionText("Name:", BankingDetails.AccountName)

              ' Reference
              ReferenceResolved = BankingDetails.ReferenceResolved(account)
              With .AddCaptionWiki("Reference:", "**" & BankingDetails.Reference & "**")
                If BankingDetails.Reference <> ReferenceResolved Then .Cells(1).Value &= String.Format(" --resolves to-- **{0}**", ReferenceResolved)
              End With

              ' Warnings
              If Not account.BankingDetails(accountBankingDetailsType).BankingDetails.IsValid(True, False) Then
                strTemp = finBL.Error.Message(True, True)
                If Len(strTemp) <> 0 Then
                  Warnings &= "{{warning|" & strTemp & "}}"
                End If
              End If

            Case isefinPaymentTypeCategory.PayTo
              ' -----
              ' Pay To
              ' -----
              ' Get AccountBankingPayToItem
              AccountBankingPayToItem = account.BankingPayToItems.ItemByAgreementId(BankingDetails.ExternalId)

              ' Resolve Reference and Description
              ReferenceResolved = BankingDetails.ReferenceResolved(account)
              DescriptionResolved = BankingDetails.DescriptionResolved(account)

              If AccountBankingPayToItem Is Nothing Then
                .AddCaptionText("Agreement Id:", BankingDetails.ExternalId)
              Else
                .AddCaptionText("Service", AccountBankingPayToItem.ServiceName)
                With .AddCaptionText("Agreement Id:", AccountBankingPayToItem.AgreementId)
                  If finBL.CurrentUser.Permissions.Allow("ServiceLogs.View") Then .Cells(1).HyperlinkSetFormShow("ServiceLog", CStr(AccountBankingPayToItem.ServiceLogs(0).Pk), "Banking Interface Summary")
                End With
                .AddCaptionText("Name:", AccountBankingPayToItem.Name)
              End If

              If Len(BankingDetails.Reference) <> 0 Then
                With .AddCaptionWiki("Reference:", "**" & BankingDetails.Reference & "**")
                  If BankingDetails.Reference <> ReferenceResolved Then
                    .Cells(1).Value &= String.Format(" --resolves to-- **{0}**", ReferenceResolved)
                  End If
                End With
              End If
              If Len(BankingDetails.Description) <> 0 Then
                With .AddCaptionWiki("Description:", "**" & BankingDetails.Description & "**")
                  If BankingDetails.Description <> DescriptionResolved Then
                    .Cells(1).Value &= String.Format(" --resolves to-- **{0}**", DescriptionResolved)
                  End If
                End With
              End If

              ' Warnings
              If AccountBankingPayToItem Is Nothing Then
                Warnings &= "{{Warning|PayTo Agreement not found.|true}}"
              Else
                If AccountBankingPayToItem.BankAccountPk <> PaymentMethod.BankAccountPk Then
                  Warnings &= "{{Warning|PayTo Agreement is for another Bank Account and therefore may fail to be processed.|true}}"
                End If
                If AccountBankingPayToItem.State <> isefinBankInterface_PayTo_AgreementStatus.Active Then
                  Warnings &= "{{Warning|PayTo Agreement is not Active.|true}}"
                End If
              End If

            Case isefinPaymentTypeCategory.Split
              ' -------------
              ' Zepto (Split)
              ' -------------
              If finBL.CurrentCountry.SupportsBankSortCode Then
                .AddCaptionText(finBL.CurrentCountry.Terminology(isefinCountryTerminology.BankSortCode, True) & ":", BankingDetails.AccountSortCode)
              End If
              .AddCaptionText("Account No:", BankingDetails.AccountNumber)
              .AddCaptionText("Name:", BankingDetails.AccountName)
              .AddCaptionText("Email:", BankingDetails.AccountEmail)
              .AddCaptionText("Contact:", BankingDetails.ExternalId)

              ' Warnings
              If Not BankingDetails.IsValid(False, False) Then
                Warnings &= "{{Warning|" & finBL.Error.Message(True, True) & "}}"
              End If

            Case isefinPaymentTypeCategory.Token
              ' -----
              ' Token
              ' -----
              .AddCaptionText("Token:", BankingDetails.AccountNumber)
              .AddCaptionText("Name:", BankingDetails.AccountName)

              ' Reference
              Select Case finBL.CountryCode
                Case "NZ"
                  ' Split Reference into Particulars, Code and Reference and Resolve
                  BankingDetails.Reference_SplitNZ(Particulars, Code, Reference)
                  BankingDetails.ReferenceResolved_SplitNZ(account, ParticularsResolved, CodeResolved, ReferenceResolved)

                  With .AddCaptionWiki("Particulars:", "**" & Particulars & "**")
                    If Particulars <> ParticularsResolved Then .Cells(1).Value &= String.Format(" --resolves to-- **{0}**", ParticularsResolved)
                  End With
                  With .AddCaptionWiki("Code:", "**" & Code & "**")
                    If Code <> CodeResolved Then .Cells(1).Value &= String.Format(" --resolves to-- **{0}**", CodeResolved)
                  End With
                  With .AddCaptionWiki("Reference:", "**" & Reference & "**")
                    If Reference <> ReferenceResolved Then .Cells(1).Value &= String.Format(" --resolves to-- **{0}**", ReferenceResolved)
                  End With

                Case Else
                  ' Resolve Reference
                  ReferenceResolved = BankingDetails.ReferenceResolved(account)

                  With .AddCaptionWiki("Reference:", "**" & BankingDetails.Reference & "**")
                    If BankingDetails.Reference <> ReferenceResolved Then .Cells(1).Value &= String.Format(" --resolves to-- **{0}**", ReferenceResolved)
                  End With
              End Select

              ' Warnings
              If Not BankingDetails.IsValid(False, False) Then
                Warnings &= "{{Warning|" & finBL.Error.Message(True, True) & "}}"
              End If

            Case isefinPaymentTypeCategory.ZeptoNZ
              ' -----------------
              ' Zepto New Zealand
              ' -----------------
              .AddCaptionText("Account No:", BankingDetails.AccountNumber)
              .AddCaptionText("Name:", BankingDetails.AccountName)
              .AddCaptionText("Email:", BankingDetails.AccountEmail)
              .AddCaptionText("Phone:", BankingDetails.AccountPhone)
              .AddCaptionText("Contact:", BankingDetails.ExternalId)

              ' Warnings
              If Not BankingDetails.IsValid(False, False) Then
                Warnings &= "{{Warning|" & finBL.Error.Message(True, True) & "}}"
              End If
          End Select
        End With
      End If

      ' Additional Warnings for Deposit Accounts
      Select Case account.AccountClass
        Case isefinAccountClass.Deposit
          Select Case accountBankingDetailsType
            Case isefinAccountBankingDetailsType.Outgoing
              ' Interest
              Select Case account.Calculation.InterestPaymentType
                Case isefinAccountInterestPaymentType.Capitalise
                  Warnings &= "{{warning|Interest is capitalised.}}"
                Case isefinAccountInterestPaymentType.Compound
                  Warnings &= "{{warning|Interest is compounded.}}"
                Case isefinAccountInterestPaymentType.Transfer
                  Warnings &= "{{warning|Interest is transferred to another Account.}}"
              End Select

            Case isefinAccountBankingDetailsType.Maturity
              ' Maturity
              Select Case account.MaturityInstruction
                Case isefinAccountMaturityInstruction.ToBeAdvised
                  Warnings &= "{{warning|Maturity instructions are 'To Be Advised'.}}"
                Case isefinAccountMaturityInstruction.ReinvestAll
                  Warnings &= "{{warning|Maturity instructions are 'Reinvest All'.}}"
                Case Else
                  Select Case account.MaturityPaymentType
                    Case isefinAccountMaturityPaymentType.Transfer
                      Warnings &= "{{warning|Maturity payout is transferred to another Account.}}"
                  End Select
              End Select
          End Select
      End Select

      ' Warnings
      .TextAfter = Warnings

      ' Actions
      If includeActions Then
        With .Actions
          If (Not finBL.Database.IsReadOnly) AndAlso account.Status = isefinAccountStatus.Open AndAlso finBL.CurrentUser.Permissions.Allow("Account.PaymentDetailsUpdate") Then
            Select Case accountBankingDetailsType
              Case isefinAccountBankingDetailsType.Incoming
                .AddFormAction("PaymentDetailsIncomingEdit", "Edit").ShowInWebInterfaces = True
              Case isefinAccountBankingDetailsType.Maturity
                .AddFormAction("PaymentDetailsMaturityEdit", "Edit").ShowInWebInterfaces = True
              Case isefinAccountBankingDetailsType.Outgoing
                Select Case account.AccountClass
                  Case isefinAccountClass.Disbursement
                    .AddFormAction("PaymentDetailsOutgoingEdit", "Edit", finBL.CurrentUser.Permissions.Allow("Account.Disbursement.OutgoingPaymentDetailsUpdate")).ShowInWebInterfaces = True
                  Case isefinAccountClass.Deposit
                    .AddFormAction("PaymentDetailsInterestEdit", "Edit").ShowInWebInterfaces = True
                  Case Else
                    .AddFormAction("PaymentDetailsOutgoingEdit", "Edit").ShowInWebInterfaces = True
                End Select
            End Select
          End If
          If account.CanStopDirectDebits() Then
            If account.PaymentDDStopToDate < DateAsAt Then
              Caption = "Stop Direct Debits"
            Else
              Caption = "Restart Direct Debits"
            End If
            .AddFormAction("DirectDebitStop", Caption).ShowInWebInterfaces = True
          End If

          Select Case PaymentTypeCategory
            Case isefinPaymentTypeCategory.Ezidebit
              If Len(BankingDetails.ExternalId) = 0 Then
                .AddFormAction("EzidebiteDDR", "eDDR").ShowInWebInterfaces = True
              Else
                .AddFormAction("EzidebitVerify", "Verify").ShowInWebInterfaces = True
              End If

            Case isefinPaymentTypeCategory.Split
              If Len(BankingDetails.ExternalId) <> 0 Then
                .AddFormAction("SplitVerify." & accountBankingDetailsType.ToString(), "Verify").ShowInWebInterfaces = True
              End If

            Case isefinPaymentTypeCategory.ZeptoNZ
              If Len(BankingDetails.ExternalId) <> 0 Then
                .AddFormAction("ZeptoNZVerify." & accountBankingDetailsType.ToString(), "Verify").ShowInWebInterfaces = True
              End If
          End Select
        End With
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Bank Matches.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="account">
  '''  The Account to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Payments page and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_BankMatches(callerScriptInfo As ISScriptExecutionInfo,
                                                  account As finAccount,
                                         Optional includeActions As Boolean = True,
                                         Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' Account_BankMatches
    '
    ' Version: 1.02 (01/07/2024)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.01  02/08/2018  ISS
    '    1.02  01/07/2024  ISS      J033807   Added finCC Support for deleting Bank Matches
    ' #################################################################

    Dim BankMatches As ISListReadOnly
    Dim kvl As ISKeyValueList
    Dim s As String
    Dim ShowDelete As Boolean
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    kvl = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Bank Matches
    finBL.AccountFunctions.GetBankMatchesPk(account.Pk, BankMatches)

    ' Columns to show
    Select Case callerScriptInfo.Target
      Case iseSummaryPageTarget.Report, iseSummaryPageTarget.External
        ShowDelete = False
      Case Else
        ShowDelete = Not finBL.Database.IsReadOnly
    End Select

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .AutoStripe = True
      .Caption = ""
      .MaxDisplayRows = 5

      If BankMatches.Count = 0 AndAlso Len(account.BankMatchAlternate) = 0 Then
        ' No Bank Matches
        Warnings &= "{{info|No Bank Matches recorded.}}"
      Else
        ' Columns
        With .Columns
          .AddText(1, iseSummaryTableCellTextAlign.Center) ' Icon
          .AddText() ' Description
          If ShowDelete Then
            .AddText(1, iseSummaryTableCellTextAlign.Center) ' Delete
          End If
        End With

        With .Rows
          ' Bank Matches
          For Each s In BankMatches
            With .Add().Cells
              .AddText("{{icon|BankTransaction}}")
              .AddText(s)
              If ShowDelete Then
                kvl.Clear()
                With kvl
                  .SetString("id", s)
                  .SetString("accountId", account.AccountId)
                End With
                .AddText("{{icon|Delete}}").HyperlinkSetFormAction("BankMatchDelete", kvl.ToUrlString())
              End If
            End With
          Next

          ' Alt Bank Match
          If Len(account.BankMatchAlternate) <> 0 Then
            With .Add().Cells
              .AddText("{{icon|Account}}")
              .AddText(account.BankMatchAlternate)
              With .AddText("{{icon|Delete}}")
                kvl.Clear()
                With kvl
                  .SetString("accountId", account.AccountId)
                End With
                .HyperlinkSetFormAction("BankMatchAlternateDelete", kvl.ToUrlString())
              End With
            End With
          End If
        End With
      End If

      ' Warnings
      Warnings &= "{{help|Bank Matches are used when importing Bank Statement information to match the information to this Account.}}"
      .TextAfter = Warnings

      ' Actions
      If includeActions Then
        With .Actions
        End With
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Banking PayID Summary (Australia).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="account">
  '''  The Account to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Account Payments page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_BankingPayId(callerScriptInfo As ISScriptExecutionInfo,
                                                   account As finAccount,
                                          Optional includeActions As Boolean = True,
                                          Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' Account_BankingPayId
    '
    ' Version: 1.03 (06/05/2024)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.00  31/08/2023  ISS      J031120   Created
    '    1.01  27/09/2023  ISS      J032124   Respect "ServiceLogs.View" permission
    '    1.02  22/02/2024  ISS      J032951   Various updates
    '    1.03  06/05/2024  ISS      J033237   Open Account Log before Service Log
    ' #################################################################

    Dim AccountBankingPayIDItem As finAccountBankingPayIdItem
    Dim Include As Boolean
    Dim LinkedLogs As finLogs
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .Caption = ""
      .AutoStripe = True
      .MaxDisplayRows = 6
      .ShowHiddenRowsCaption = "Show More"

      ' Columns
      With .Columns
        .AddText(" ").WidthChars = 4
        .AddText("PayID Email")
        .AddText("Name")
        .AddText("Email")
        .AddText("Status")
        .AddText("Created")
      End With

      With .Rows
        For Each AccountBankingPayIDItem In account.BankingPayIDItems
          ' Include?
          Select Case AccountBankingPayIDItem.ServiceLogs(0).ResponseStatus
            Case iseServiceLogResponseStatus.Complete, iseServiceLogResponseStatus.InProgress
              Include = True
            Case Else
              Select Case account.Status
                Case isefinAccountStatus.Closed
                  Include = True
                Case Else
                  Include = False
              End Select
          End Select

          If Include Then
            ' Add Row
            With .Add().Cells
              With .AddWiki("{{icon|clipboard_copy}}")
                .Hyperlink = "javascript:navigator.clipboard.writeText('" & finBL.UrlEncode(AccountBankingPayIDItem.AliasValue) & "');"
                .Tooltip = "Copy email to clipboard"
              End With
              With .AddText(AccountBankingPayIDItem.AliasValue)
                If finBL.Utilities.GetServiceLogLinkedLogs(AccountBankingPayIDItem.ServiceLogs(0).Pk, LinkedLogs) AndAlso LinkedLogs IsNot Nothing AndAlso LinkedLogs.Count <> 0 AndAlso LinkedLogs(0).LogClass = isefinLogClass.Account Then
                  .HyperlinkSetFormShow(LinkedLogs(0).GetFormKey, CStr(LinkedLogs(0).Pk), "Banking Interface Summary")
                ElseIf finBL.CurrentUser.Permissions.Allow("ServiceLogs.View") Then
                  .HyperlinkSetFormShow("ServiceLog", CStr(AccountBankingPayIDItem.ServiceLogs(0).Pk), "Banking Interface Summary")
                End If
              End With
              .AddText(AccountBankingPayIDItem.ContactName)
              .AddText(AccountBankingPayIDItem.ContactEmail)
              With .AddText(AccountBankingPayIDItem.StateText)
                .BackgroundColour = AccountBankingPayIDItem.StateHtmlColour
              End With
              Select Case AccountBankingPayIDItem.State
                Case isefinBankInterface_PayId_State.Active
                  .AddText(finBL.FormatDateLong(AccountBankingPayIDItem.ServiceLogs(0).CreatedDate))
                Case Else
                  .AddText(finBL.FormatDateTimeLong(AccountBankingPayIDItem.ServiceLogs(0).CreatedDate))
              End Select
            End With
          End If
        Next
      End With

      ' If no Rows remove Column Header
      If .Rows.Count = 1 Then .Rows.Clear()

      ' Actions
      If includeActions Then
        With .Actions
          If account.BankingPayIDItems.CanAddPayId Then
            .AddFormAction("AccountPaymentPayIdCreate", "New PayID").ShowInWebInterfaces = True
          End If
        End With
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Banking PayTo Summary.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="account">
  '''  The Account to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Account Payments page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_BankingPayTo(callerScriptInfo As ISScriptExecutionInfo,
                                                   account As finAccount,
                                          Optional includeActions As Boolean = True,
                                          Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' Account_BankingPayTo
    '
    ' Version: 1.01 (06/05/2024)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.00  06/03/2024  ISS      J032155   Created
    '    1.01  06/05/2024  ISS      J033237   Open Account Log before Service Log
    ' #################################################################

    Dim AccountBankingPayToItem As finAccountBankingPayToItem
    Dim Include As Boolean
    Dim LinkedLogs As finLogs
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .Caption = ""
      .AutoStripe = True
      .MaxDisplayRows = 6
      .ShowHiddenRowsCaption = "Show More"

      ' Columns
      With .Columns
        .AddText(" ").WidthChars = 4
        .AddText("Agreement Id")
        .AddText("Description")
        .AddText("Name")
        .AddText("Status")
        .AddText("Created")
      End With

      With .Rows
        For Each AccountBankingPayToItem In account.BankingPayToItems
          ' Include?
          Select Case AccountBankingPayToItem.ServiceLogs(0).ResponseStatus
            Case iseServiceLogResponseStatus.Complete, iseServiceLogResponseStatus.InProgress
              Include = True
            Case Else
              Select Case account.Status
                Case isefinAccountStatus.Closed
                  Include = True
                Case Else
                  Include = False
              End Select
          End Select

          If Include Then
            ' Add Row
            With .Add()
              Select Case AccountBankingPayToItem.State
                Case isefinBankInterface_PayTo_AgreementStatus.Cancelled, isefinBankInterface_PayTo_AgreementStatus.Declined, isefinBankInterface_PayTo_AgreementStatus.Expired, isefinBankInterface_PayTo_AgreementStatus.Failed
                  .Visible = False
              End Select

              With .Cells
                With .AddWiki("{{icon|clipboard_copy}}")
                  .Hyperlink = "javascript:navigator.clipboard.writeText('" & finBL.UrlEncode(AccountBankingPayToItem.AgreementId) & "');"
                  .Tooltip = "Copy Agreement Id to clipboard"
                End With
                With .AddText(AccountBankingPayToItem.AgreementId)
                  If finBL.Utilities.GetServiceLogLinkedLogs(AccountBankingPayToItem.ServiceLogs(0).Pk, LinkedLogs) AndAlso LinkedLogs IsNot Nothing AndAlso LinkedLogs.Count <> 0 AndAlso LinkedLogs(0).LogClass = isefinLogClass.Account Then
                    .HyperlinkSetFormShow(LinkedLogs(0).GetFormKey, CStr(LinkedLogs(0).Pk), "Banking Interface Summary")
                  ElseIf finBL.CurrentUser.Permissions.Allow("ServiceLogs.View") Then
                    .HyperlinkSetFormShow("ServiceLog", CStr(AccountBankingPayToItem.ServiceLogs(0).Pk), "Banking Interface Summary")
                  End If
                End With
                .AddText(AccountBankingPayToItem.Description)
                .AddText(AccountBankingPayToItem.Name)
                With .AddText(AccountBankingPayToItem.StateText)
                  .BackgroundColour = AccountBankingPayToItem.StateHtmlColour
                End With
                Select Case AccountBankingPayToItem.State
                  Case isefinBankInterface_PayTo_AgreementStatus.Active
                    .AddText(finBL.FormatDateLong(AccountBankingPayToItem.ServiceLogs(0).CreatedDate))
                  Case Else
                    .AddText(finBL.FormatDateTimeLong(AccountBankingPayToItem.ServiceLogs(0).CreatedDate))
                End Select
              End With
            End With
          End If
        Next
      End With

      ' If no Rows remove Column Header
      If .Rows.Count = 1 Then .Rows.Clear()

      ' Actions
      If includeActions Then
        With .Actions
          If account.BankingPayToItems.CanAddPayToAgreement Then
            .AddFormAction("AccountPaymentPayToCreateAmend", "New PayTo").ShowInWebInterfaces = True
          End If
        End With
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Banking Reference (Version 1.01, Last updated 25/02/2014).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="account">
  '''  The Account to summarise.
  ''' </param>
  ''' <param name="bankReferenceLength">
  '''  The Bank Reference Length, if 0 will use Global Setting. Will left pad with zeros if necessary, 0 = no padding.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Payments page and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_BankingReference(callerScriptInfo As ISScriptExecutionInfo,
                                                       account As finAccount,
                                              Optional bankReferenceLength As Integer = 0,
                                              Optional includeActions As Boolean = True,
                                              Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim Reference As String
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      .Columns.AddText()

      If account.AccountType Is Nothing Then
        ' No Account Type, e.g., created from a partial Account Application
      ElseIf Not account.AccountType.ShowAccountIdWithCheckDigit Then
        ' No Payment Arrangements
        Warnings &= "{{info|Not supported for this Account Type.}}"
      Else
        ' Resolve Length
        If bankReferenceLength = 0 Then bankReferenceLength = finBL.Settings.AccountCheckDigitLength

        ' Calculate Reference
        Reference = finBL.AccountFunctions.CheckDigitCalculateWithPrefix(account.AccountId, finBL.Settings.AccountCheckDigitMethod, finBL.Settings.AccountCheckDigitPrefix, bankReferenceLength)

        If Len(Reference) = 0 Then
          Warnings &= "{{warning|Cannot generate reference.}}"
        Else
          With .Rows.Add().Cells
            With .AddWiki("++**" & Reference & "**++")
              .CellClass = iseSummaryTableCellClass.Highlight1
            End With
          End With
        End If
      End If

      ' Warnings
      .TextAfter = Warnings

      ' Actions
      If includeActions Then
        With .Actions
        End With
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Clients Summary (Version 1.05, Last updated 11/08/2020).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="account">
  '''  The Account to summarise.
  ''' </param>
  ''' <param name="showCity">
  '''  Indicates whether to include an 'Address' column containing the City with the full address shown in a popup.
  ''' </param>
  ''' <param name="showFullAddress">
  '''  Indicates whether to include an 'Address' column containing the full address (physical if available, if not, postal).
  ''' </param>
  ''' <param name="showContactMethods">
  '''  Indicates whether to include columns detailing the Client's Contact Methods.
  ''' </param>
  ''' <param name="contactMethodsIds">
  '''  A range of Contact Method Ids to include or a blank String to include all Contact Methods with no category.
  ''' </param>
  ''' <param name="showDateOfBirth">
  '''  Indicates whether to show the Client's Date of Birth.
  ''' </param>
  ''' <param name="showPassCode">
  '''  Indicates whether to show the Client's Pass Code.
  ''' </param>
  ''' <param name="includeRoleOwner">
  '''  Indicates whether to include Owners.
  ''' </param>
  ''' <param name="includeRoleGuarantor">
  '''  Indicates whether to include Guarantors.
  ''' </param>
  ''' <param name="includeRoleOther">
  '''  Indicates whether to include 'Other' Account Roles.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="maxDisplayRows">
  '''  The Maximum number of Rows to Display in the table before a 'Show Hidden' link is displayed.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Key Details page and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_Clients2(callerScriptInfo As ISScriptExecutionInfo,
                                               account As finAccount,
                                      Optional showCity As Boolean = True,
                                      Optional showFullAddress As Boolean = False,
                                      Optional showContactMethods As Boolean = False,
                                      Optional contactMethodsIds As String = "",
                                      Optional showDateOfBirth As Boolean = False,
                                      Optional showPassCode As Boolean = True,
                                      Optional includeRoleOwner As Boolean = True,
                                      Optional includeRoleGuarantor As Boolean = True,
                                      Optional includeRoleOther As Boolean = True,
                                      Optional maxDisplayRows As Integer = 20,
                                      Optional includeActions As Boolean = True,
                                      Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim AccountClient As finAccountClient
    Dim AddressDetails As ISAddressDetails
    Dim ApplicationShortcut As ISApplicationShortcut
    Dim City As String
    Dim ClientContactMethod As finClientContactMethod
    Dim ContactMethods As ISCodeDescriptionList
    Dim ContactMethodDescription As String
    Dim ContactMethodValue As String
    Dim Include As Boolean
    Dim RangeContactMethods As ISRanges
    Dim StatusIcons As String
    Dim strTemp As String
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()
    If showContactMethods AndAlso Len(contactMethodsIds) <> 0 Then
      RangeContactMethods = finBL.Runtime.CreateRanges(contactMethodsIds)
    End If

    ' Validate
    If account.IsNew AndAlso showPassCode Then
      ' Don't show Client Passwords since we're dealing with an unsaved Account, e.g., from an Account Application
      showPassCode = False
    End If

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .Caption = ""
      .AutoStripe = True
      .MaxDisplayRows = maxDisplayRows
      .ShowHiddenRowsCaption = "Show More Clients"

      ' Columns
      With .Columns
        .AddCode(" ", 1) ' Status Icons (don't centre since there may be multiple icons)
        .AddCode("Client", finBL.ClientFunctions.GetLongestCode())
        .AddText("Name")
        If showFullAddress Then
          .AddText("Address", 30).NoBreakChars = 30
        ElseIf showCity Then
          .AddText("Address", 15).NoBreakChars = 15
        End If
        If showContactMethods Then
          With .AddText("Contact", 30)
            If showFullAddress OrElse showCity Then
              .HideRule = iseSummaryTableColumnHideRule.DocumentWidthLessThan800px
            Else
              .HideRule = iseSummaryTableColumnHideRule.DocumentWidthLessThan640px
            End If
          End With
        End If
        .AddText("Role", 10).NoBreakChars = 15
        If showDateOfBirth Then .AddDate("DOB")
      End With

      With .Rows
        For Each AccountClient In account.Clients
          ' Include?
          Select Case AccountClient.RoleType
            Case isefinAccountRoleType.Guarantor : Include = includeRoleGuarantor
            Case isefinAccountRoleType.Other : Include = includeRoleOther
            Case isefinAccountRoleType.Owner : Include = includeRoleOwner
            Case Else : Include = True
          End Select

          If Include Then
            ' Add Row
            With .Add().Cells
              ' Status Icons
              If AccountClient.IsClientFilteredOut Then
                StatusIcons = "{{icon|Warning}}"
              Else
                Select Case AccountClient.ClientStatus
                  Case isefinClientStatus.None : StatusIcons = ""
                  Case Else : StatusIcons = "{{icon|ClientStatus" & AccountClient.ClientStatus.ToString() & "|Status: " & AccountClient.ClientStatusText & "}}"
                End Select
                If AccountClient.IsIndividualDeceased Then
                  StatusIcons &= "{{icon|ClientStatusDeceased|Deceased Individual}}"
                End If
                If Len(AccountClient.ClientAlertMessage) <> 0 Then
                  StatusIcons &= "{{icon|Alert|" & AccountClient.ClientAlertMessage & "}}"
                End If
              End If

              .AddText(StatusIcons)
              If AccountClient.IsClientFilteredOut Then
                ' Filtered Out (limited information)
                .AddText(AccountClient.ClientId)
                .AddWiki(AccountClient.ClientName & " --!!(Filtered Out)!!--")
                If showCity OrElse showFullAddress Then
                  .AddText("")
                End If
                If showContactMethods Then
                  .AddText("")
                  .AddText("")
                End If
                If AccountClient.RoleJoint Then
                  .AddWiki("--(Joint)--")
                Else
                  .AddText(finBL.AccountRoles(AccountClient.AccountRoleId).DescriptionShortResolved)
                End If
                .AddText("")
                If showDateOfBirth Then
                  .AddText("")
                End If
              Else
                ' Full Information
                With .AddText(AccountClient.ClientId)
                  .HyperlinkSetFormShow("Clients", AccountClient.ClientId)
                  If showPassCode AndAlso finBL.CurrentUser.Permissions.Allow("Client.Password") AndAlso Len(AccountClient.Client.PassCode) <> 0 Then
                    .TooltipSetPopupNoteHtml(String.Format("Client Pass Code is:<p><b style='font-size:1.5em'>{0}</b></p>", finBL.HtmlEncode(AccountClient.Client.PassCode)), "{{icon|Popup_Key|Click to view Pass Code}}")
                  End If
                End With
                .AddText(AccountClient.ClientName)

                ' Address/ City
                If showCity OrElse showFullAddress Then
                  ' Get Address
                  AddressDetails = AccountClient.Client.ContactAddresses.GetCurrentPhysicalAddress()
                  If Not AddressDetails.HasValue Then AddressDetails = AccountClient.Client.ContactAddresses.GetCurrentPostalAddress()

                  If AddressDetails.HasValue Then
                    If showFullAddress Then
                      ' Full Address
                      .AddAddressDetailsPhysical(AddressDetails)
                    Else
                      ' City (plus full Address popup)
                      Select Case finBL.CountryCode
                        Case "AU"
                          ' Suburb is generally used in Australia
                          City = AddressDetails.Suburb
                          If Len(City) = 0 Then City = AddressDetails.City
                        Case Else
                          ' If not City then list Suburb
                          City = AddressDetails.City
                          If Len(City) = 0 Then City = AddressDetails.Suburb
                      End Select

                      With .AddText(City)
                        If AddressDetails.HasValue Then
                          .TooltipSetPopupNote(finBL.Addressing.FormatAddressFromAddressDetails(AddressDetails, , True))
                        End If
                      End With
                    End If
                  Else
                    .AddText("")
                  End If
                End If

                If showContactMethods Then
                  ' Contact Methods
                  ContactMethods = finBL.Runtime.CreateCodeDescriptionList()
                  For Each ClientContactMethod In AccountClient.Client.ContactMethods
                    ' Include?
                    Include = ClientContactMethod.IsCurrent AndAlso ClientContactMethod.OwnedByClient
                    If Include AndAlso RangeContactMethods IsNot Nothing Then
                      Include = RangeContactMethods.IsValueInRange(ClientContactMethod.ContactMethodId)
                    End If

                    ' Add
                    If Include Then
                      ' Communication restrictions popup message
                      strTemp = ""
                      Select Case ClientContactMethod.ContactType
                        Case isefinContactType.Email
                          If Not AccountClient.Client.CommunicationGeneral OrElse (finBL.Settings.AddOns.ClientAdvanced AndAlso Not AccountClient.Client.CommunicationGeneralEmail) Then strTemp &= "<p>Do not use Email for <b>General</b> communication.<p>"
                          If Not AccountClient.Client.CommunicationMarketing OrElse (finBL.Settings.AddOns.ClientAdvanced AndAlso Not AccountClient.Client.CommunicationMarketingEmail) Then strTemp &= "<p>Do not use Email for <b>Marketing</b>.<p>"

                        Case isefinContactType.Phone
                          If ClientContactMethod.PhoneVoice Then
                            If Not AccountClient.Client.CommunicationGeneral OrElse (finBL.Settings.AddOns.ClientAdvanced AndAlso Not AccountClient.Client.CommunicationGeneralPhoneVoice) Then strTemp &= "<p>Do not use <b>voice calls</b> for <b>General</b> communication.<p>"
                            If Not AccountClient.Client.CommunicationMarketing OrElse (finBL.Settings.AddOns.ClientAdvanced AndAlso Not AccountClient.Client.CommunicationMarketingPhoneVoice) Then strTemp &= "<p>Do not use <b>voice calls</b> for <b>Marketing</b>.<p>"
                          End If
                          If ClientContactMethod.PhoneSms Then
                            If Not AccountClient.Client.CommunicationGeneral OrElse (finBL.Settings.AddOns.ClientAdvanced AndAlso Not AccountClient.Client.CommunicationGeneralSms) Then strTemp &= "<p>Do not use <b>SMS</b> for <b>General</b> communication.<p>"
                            If Not AccountClient.Client.CommunicationMarketing OrElse (finBL.Settings.AddOns.ClientAdvanced AndAlso Not AccountClient.Client.CommunicationMarketingSms) Then strTemp &= "<p>Do not use <b>SMS</b> for <b>Marketing</b>.<p>"
                          End If
                      End Select

                      ' Description
                      If Len(strTemp) = 0 Then
                        ContactMethodDescription = ClientContactMethod.ContactMethod.DescriptionShortResolved
                      Else
                        ApplicationShortcut = finBL.CreateApplicationShortcut()
                        With ApplicationShortcut
                          .Action = "HtmlShow"
                          With .Parameters
                            .SetString("html", String.Format("<h1>{0}: <a href='app://contact?clientId={2}&clientContactMethodPk={3}&accountId={4}'>{1}</a></h1>", finBL.HtmlEncode(ClientContactMethod.ContactMethod.DescriptionShortResolved), finBL.HtmlEncode(ClientContactMethod.Value), finBL.Runtime.HtmlUtilities.UrlEncode(AccountClient.ClientId), ClientContactMethod.Pk, finBL.UrlEncode(account.AccountId)) & strTemp)
                            .SetString("title", String.Format("Client Communication Settings for {0}, '{1}'", AccountClient.ClientId, AccountClient.ClientName))
                            .SetBoolean("popup", True)
                            .SetString("popupStyle", "note")
                          End With
                        End With
                        ContactMethodDescription = String.Format("[[{1}|{0}]]", ClientContactMethod.ContactMethod.DescriptionShortResolved & "{{icon|Popup_Note}}", ApplicationShortcut.ToUrlString(True))
                      End If

                      ' Value with hyperlink
                      If account.IsNew Then
                        ' Cannot hyperlink new records, e.g., from an Account Application
                        ContactMethodValue = ClientContactMethod.Value
                      Else
                        Select Case ClientContactMethod.ContactType
                          Case isefinContactType.Email
                            ContactMethodValue = String.Format("[[app://contact?clientId={0}&clientContactMethodPk={1}&accountId={2}&emailAddress={3}|{4}]]", finBL.UrlEncode(AccountClient.ClientId), ClientContactMethod.Pk, finBL.UrlEncode(account.AccountId), finBL.UrlEncode(ClientContactMethod.Value), ClientContactMethod.Value)

                          Case isefinContactType.Phone
                            ContactMethodValue = String.Format("[[app://contact?clientId={0}&clientContactMethodPk={1}&accountId={2}&phoneNumber={3}|{4}]]", finBL.UrlEncode(AccountClient.ClientId), ClientContactMethod.Pk, finBL.UrlEncode(account.AccountId), finBL.UrlEncode(ClientContactMethod.Value), ClientContactMethod.Value)

                          Case isefinContactType.WebPage
                            ContactMethodValue = String.Format("[[app://contact?clientId={0}&clientContactMethodPk={1}&accountId={2}&websiteUrl={3}|{4}]]", finBL.UrlEncode(AccountClient.ClientId), ClientContactMethod.Pk, finBL.UrlEncode(account.AccountId), finBL.UrlEncode(ClientContactMethod.Value), ClientContactMethod.Value)

                          Case Else
                            ContactMethodValue = String.Format("[[app://contact?clientId={0}&clientContactMethodPk={1}&accountId={2}|{3}]]", finBL.UrlEncode(AccountClient.ClientId), ClientContactMethod.Pk, finBL.UrlEncode(account.AccountId), ClientContactMethod.Value)
                        End Select
                      End If

                      ' Add
                      ContactMethods.Add(ContactMethodDescription, ContactMethodValue)
                    End If
                  Next

                  .AddCodeDescriptionListWiki(ContactMethods)
                End If

                If AccountClient.RoleJoint Then
                  .AddWiki("--(Joint)--")
                ElseIf AccountClient.AccountRolePk = 0 Then
                  ' Probably an unsaved Account Client, e.g., from an Account Application
                Else
                  .AddText(finBL.AccountRoles(AccountClient.AccountRoleId).DescriptionShortResolved)
                End If
                If showDateOfBirth Then
                  .AddDate(AccountClient.ClientDateOfBirth)
                End If
              End If
            End With
          End If
        Next
      End With

      ' Warnings
      .TextAfter = Warnings

      ' Actions
      If includeActions Then
        With .Actions
        End With
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Comprehensive Credit Reporting (Version 1.00, Last updated 29/11/2019).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="account">
  '''  The Account to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Payments page and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_ComprehensiveCreditReporting(callerScriptInfo As ISScriptExecutionInfo,
                                                                   account As finAccount,
                                                          Optional includeActions As Boolean = True,
                                                          Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim AccountCreditReport As finAccountCreditReport
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Find latest Credit Report
    AccountCreditReport = account.CreditReports.GetLatestCreditReport()

    ' Clear Warnings
    Warnings = ""

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""

      ' Columns
      .Columns.AddText(16).NoBreakChars = 16
      .Columns.AddText()

      If AccountCreditReport Is Nothing Then
        Warnings &= "{{info|No information found.}}"
      Else
        .AddRowCaptionText("Account Number:", AccountCreditReport.AccountData.AccountNumber, True)
        .AddRowCaptionDate("Last updated:", AccountCreditReport.Date)
      End If

      ' Warnings
      .TextAfter = Warnings

      ' Actions
      If includeActions Then
        With .Actions
        End With
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Consumer Regulation Summary for NZ High-Cost Consumer Credit Contracts (Version 1.01, Last updated 11/08/2020).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="account">
  '''  The Account to summarise.
  ''' </param>
  ''' <param name="accountCalc">
  '''  The Account Calculation or Nothing to use the current Account Calculation.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Account Financial page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''    <item><code>CostOfBorrowing</code><description>Cost of Borrowing details.</description></item>
  '''    <item><code>DefaultFees</code><description>Default Fee details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_ConsumerRegulation_NZHighCostConsumerCreditContract(callerScriptInfo As ISScriptExecutionInfo,
                                                                                          account As finAccount,
                                                                                 Optional accountCalc As finAccountCalc = Nothing,
                                                                                 Optional includeActions As Boolean = True,
                                                                                 Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim AccountWarning As finWarning
    Dim AccountWarnings As finWarnings
    Dim ShowRunningValues As Boolean
    Dim SummaryTableCostOfBorrowing As ISSummaryTable
    Dim SummaryTableDefaultFees As ISSummaryTable
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTableCostOfBorrowing = finBL.CreateSummaryTable()
    SummaryTableDefaultFees = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Calculation
    If accountCalc Is Nothing Then
      accountCalc = account.Calculation
    End If

    ' Other Initialisation
    ShowRunningValues = accountCalc.IsCalcVersionFuture OrElse accountCalc.IsCalcVersionClosing

    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .Caption = "Advance"
      .Columns.AddText().NoBreakChars = 20
      .Columns.AddCurrency()

      ' Clear Warnings
      Warnings = ""

      With .Rows
        If account.HighCostLoanFirstAccountPk = 0 Then
          With .Add(iseSummaryTableRowClass.FooterBold).Cells
            .AddCaption("First Advance")
            .AddCurrency(account.HighCostLoanAdvance, True)
          End With
        Else
          With .Add(iseSummaryTableRowClass.FooterBold).Cells
            .AddCaptionWiki(String.Format("**First Advance - [[app://formshow?form=Accounts&id={0}|{1}]]**", finBL.UrlEncode(account.HighCostLoanFirstAccount.AccountId), account.HighCostLoanFirstAccount.AccountId))
            .AddCurrency(account.HighCostLoanFirstAdvance, True)
          End With

          With .Add().Cells
            .AddCaption("Previous Advances")
            .AddCurrency(account.HighCostLoanAdvancePrevious, True)
          End With
          With .Add().Cells
            .AddCaption("Current Advance")
            .AddCurrency(account.HighCostLoanAdvance, True)
          End With
          With .Add(iseSummaryTableRowClass.NormalBold).Cells
            .AddCaption("Total Advances")
            .AddCurrency(account.HighCostLoanAdvancePrevious + account.HighCostLoanAdvance, True)
          End With
        End If
      End With

      ' Warnings
      If account.GetWarningsConsumerRegulations_NZ_HighCostConsumerCreditContract(AccountWarnings, accountCalc) Then
        For Each AccountWarning In AccountWarnings
          Select Case AccountWarning.Level
            Case isefinWarningLevel.Critical
              Warnings &= "{{warning|" & AccountWarning.Warning & "|True}}"
            Case isefinWarningLevel.High
              Warnings &= "{{warning|" & AccountWarning.Warning & "}}"
            Case Else
              Warnings &= "{{info|" & AccountWarning.Warning & "}}"
          End Select
        Next
      End If
      .TextAfter = Warnings

      ' Actions
      If includeActions Then
        With .Actions
        End With
      End If
    End With

    With SummaryTableCostOfBorrowing
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .Caption = "Cost of Borrowing"
      .Columns.AddText().NoBreakChars = 20
      .Columns.AddCurrency()

      ' Clear Warnings
      Warnings = ""

      With .Rows
        With .Add(iseSummaryTableRowClass.FooterBold).Cells
          .AddCaption("Maximum")
          .AddCurrency(account.HighCostLoanCostOfBorrowingMaximum, True)
        End With
        If account.HighCostLoanCostOfBorrowingPrevious <> 0 Then
          With .Add().Cells
            .AddCaption("Charged previously")
            .AddCurrency(account.HighCostLoanCostOfBorrowingPrevious, True)
          End With
        End If
        If ShowRunningValues Then
          With .Add().Cells
            .AddCaption("Charged to Date")
            .AddCurrency(account.HighCostLoanCostOfBorrowingToDate, True)
          End With
          If account.HighCostLoanCostOfBorrowingPrevious <> 0 Then
            With .Add(iseSummaryTableRowClass.NormalBold).Cells
              .AddCaption("Total charged")
              .AddCurrency(account.HighCostLoanCostOfBorrowingPrevious + account.HighCostLoanCostOfBorrowingToDate, True)
            End With
          End If
        End If
        If ShowRunningValues OrElse account.HighCostLoanCostOfBorrowingPrevious <> 0 Then
          With .Add(iseSummaryTableRowClass.FooterBold).Cells
            .AddCaption("Remaining")
            .AddCurrency(account.HighCostLoanCostOfBorrowingRemaining, True)
          End With
        End If
      End With

      ' Warnings
      .TextAfter = Warnings
    End With

    With SummaryTableDefaultFees
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .Caption = "Default Fees"
      .Columns.AddText().NoBreakChars = 20
      .Columns.AddCurrency()

      ' Clear Warnings
      Warnings = ""

      With .Rows
        If Not account.AccountType.DefaultFeeIgnoreLimit Then
          With .Add(iseSummaryTableRowClass.FooterBold).Cells
            .AddCaption("Maximum")
            .AddCurrency(account.HighCostLoanDefaultFeesMaximum, True)
          End With
        End If
        If account.HighCostLoanDefaultFeesPrevious <> 0 Then
          With .Add().Cells
            .AddCaption("Charged previously")
            .AddCurrency(account.HighCostLoanDefaultFeesPrevious, True)
          End With
        End If
        If ShowRunningValues Then
          With .Add().Cells
            .AddCaption("Charged to date")
            .AddCurrency(account.HighCostLoanDefaultFeesToDate, True)
          End With
          If account.HighCostLoanDefaultFeesPrevious <> 0 Then
            With .Add(iseSummaryTableRowClass.NormalBold).Cells
              .AddCaption("Total charged")
              .AddCurrency(account.HighCostLoanDefaultFeesPrevious + account.HighCostLoanDefaultFeesToDate, True)
            End With
          End If
        End If
        If (ShowRunningValues OrElse account.HighCostLoanDefaultFeesPrevious <> 0) AndAlso Not account.AccountType.DefaultFeeIgnoreLimit Then
          With .Add(iseSummaryTableRowClass.FooterBold).Cells
            .AddCaption("Remaining")
            .AddCurrency(account.HighCostLoanDefaultFeesRemaining, True)
          End With
        End If
      End With

      ' Warnings
      .TextAfter = Warnings
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)
    SummaryTables.Add("CostOfBorrowing", SummaryTableCostOfBorrowing)
    SummaryTables.Add("DefaultFees", SummaryTableDefaultFees)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Credit Bureau Default Summary (Version 1.04, Last updated 12/10/2020).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="account">
  '''  The Account to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Status page and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_CreditBureauDefault(callerScriptInfo As ISScriptExecutionInfo,
                                                          account As finAccount,
                                                 Optional includeActions As Boolean = True,
                                                 Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim AccountHistoryItem As finAccountHistoryItem
    Dim Count As Integer
    Dim HasCurrentCreditBureauDefault As Boolean
    Dim ServiceId As String
    Dim ServiceList As ISList
    Dim strTemp As String
    Dim SummaryTable As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim SuspendAction As String
    Dim SuspendActionInclude As Boolean
    Dim SuspendActionText As String
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    ServiceList = finBL.CreditBureau.GetCreditBureauDefaultServiceIdsList(account.BranchPk).ToList()
    SummaryTables = finBL.CreateSummaryTables()

    ' Defaults
    SuspendActionInclude = True

    If Not account.SuspendCreditBureauDefaults Then
      ' Ensure all current Services are included
      For Each ServiceId In account.HistoryItems.GetCurrentCreditBureauDefaultServices()
        ServiceList.Add(ServiceId, True)
      Next

      ' Ensure list order is always consistent
      ServiceList.Sort()

      ' Build Summary for each Service
      For Each ServiceId In ServiceList
        HasCurrentCreditBureauDefault = account.HistoryItems.HasCurrentCreditBureauDefault(ServiceId)
        Warnings = ""

        SummaryTable = finBL.CreateSummaryTable()
        With SummaryTable
          ' Initialise
          .TableClass = iseSummaryTableClass.Information
          .Caption = ""
          .Columns.AddText(10).NoBreakChars = 10
          .Columns.AddText()

          .Rows.AddSectionHeading2(finBL.CreditBureau.GetServiceName(ServiceId))

          If HasCurrentCreditBureauDefault Then
            ' List 'Pending' Defaults (could be registered with multiple Credit Bureaus if supported)
            For Each AccountHistoryItem In account.HistoryItems
              If AccountHistoryItem.HistoryType = isefinAccountHistoryType.CreditBureauDefault AndAlso AccountHistoryItem.Status = isefinAccountHistoryStatus.Pending AndAlso StrComp(AccountHistoryItem.CreditBureauServiceId, ServiceId, CompareMethod.Text) = 0 Then
                SuspendActionInclude = False

                ' Details
                If AccountHistoryItem.CreditBureauDefaultOriginalDateOfDefault = Nothing Then
                  .Rows.AddCaptionText("Original:", "")
                Else
                  .Rows.AddCaptionCurrency("Original:", AccountHistoryItem.CreditBureauDefaultOriginalDefault, String.Format("on **{0}**", finBL.FormatDateLong(AccountHistoryItem.CreditBureauDefaultOriginalDateOfDefault)), True)
                End If
                If AccountHistoryItem.CreditBureauDefaultLastDateExported <> Nothing Then
                  .Rows.AddCaptionCurrency("Last Update:", AccountHistoryItem.CreditBureauDefaultLastDefault, String.Format("on **{0}**", finBL.FormatDateLong(AccountHistoryItem.CreditBureauDefaultLastDateExported)), True)
                End If
                .Rows.AddCaptionText("Status:", AccountHistoryItem.CreditBureauDefaultLastDefaultStatusDescription)
                If AccountHistoryItem.CreditBureauDefaultIsUploadRequired Then
                  If AccountHistoryItem.CreditBureauDefaultIsCurrentStatusClosing Then
                    .Rows.AddCaptionWiki("Pending:", String.Format("**{0}** --(closes Default)--", AccountHistoryItem.CreditBureauDefaultCurrentDefaultStatusDescription))
                  Else
                    .Rows.AddCaptionCurrency("Pending:", AccountHistoryItem.CreditBureauDefaultCurrentDefault, AccountHistoryItem.CreditBureauDefaultCurrentDefaultStatusDescription, True)
                  End If
                  .Rows.AddText("{{warning|Upload required.}}")
                End If
              End If
            Next
          Else
            ' No Current Default
            .Rows.AddWiki("{{info|No Credit Bureau Default currently loaded.}}")
          End If

          ' List a count of Previous Defaults
          Count = 0
          For Each AccountHistoryItem In account.HistoryItems
            With AccountHistoryItem
              If .HistoryType = isefinAccountHistoryType.CreditBureauDefault AndAlso .Status = isefinAccountHistoryStatus.Complete AndAlso StrComp(.CreditBureauServiceId, ServiceId, CompareMethod.Text) = 0 Then
                Count += 1
              End If
            End With
          Next
          Select Case Count
            Case 0
            Case 1
              Warnings &= "{{info|**1** previous Default loaded.}}"
            Case Else
              Warnings &= "{{info|**" & CStr(Count) & "** previous Defaults loaded.}}"
          End Select

          ' Actions
          If includeActions Then
            With .Actions
              .AddFormAction("CreditBureauDefaults_" & ServiceId, "Review", Not finBL.Database.IsReadOnly).ShowInWebInterfaces = True

              If HasCurrentCreditBureauDefault Then
                strTemp = "Update"
              ElseIf account.Status = isefinAccountStatus.Open Then
                strTemp = "Load"
              Else
                strTemp = ""
              End If
              If Len(strTemp) <> 0 Then .AddFormAction("AccountCreditBureauDefault_" & ServiceId, strTemp, Not finBL.Database.IsReadOnly AndAlso finBL.CurrentUser.Permissions.Allow("Account.CreditBureauDefault.Upload") AndAlso Not account.SuspendCreditBureauDefaults).ShowInWebInterfaces = True
            End With
          End If

          ' Warnings
          .TextAfter = Warnings
        End With

        ' Add Summary Tables
        SummaryTables.Add(ServiceId, SummaryTable)
      Next
    End If

    ' Suspend
    If SuspendActionInclude AndAlso includeActions AndAlso account.Status = isefinAccountStatus.Open Then
      ' Display whether Credit Bureau Defaults are suspended
      If account.SuspendCreditBureauDefaults Then
        SuspendActionText = "Clear"
        SuspendAction = "AccountCreditBureauDefaultSuspendClear"
        Warnings = "{{warning|Credit Bureau Defaults suspended.}}"
      Else
        SuspendActionText = "Suspend"
        SuspendAction = "AccountCreditBureauDefaultSuspend"
        Warnings = "{{info|Not suspended.}}"
      End If

      If Len(SuspendAction) <> 0 Then
        SummaryTable = finBL.CreateSummaryTable()
        With SummaryTable
          ' Initialise
          .TableClass = iseSummaryTableClass.Information
          .Caption = ""
          .Columns.AddText(10).NoBreakChars = 10
          .Columns.AddText()

          .Rows.AddSectionHeading2("Suspension")

          .TextAfter = Warnings

          With .Actions
            .AddFormAction(SuspendAction, SuspendActionText, SuspendActionInclude AndAlso Not finBL.Database.IsReadOnly AndAlso finBL.CurrentUser.Permissions.Allow("Account.CreditBureauDefault.Suspend")).ShowInWebInterfaces = True
          End With
        End With
        SummaryTables.Add("Suspend", SummaryTable)
      End If
    End If

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Credit Bureau Default Details (Version 1.04, Last updated 17/08/2016).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="creditBureauDefault">
  '''  The Credit Bureau Default to summarise.
  ''' </param>
  ''' <param name="includeAllServices">
  '''  Indicates whether to include All Services in the Previous Defaults table.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Credit Bureau Default wizard.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''    <item><code>History</code><description>Upload history.</description></item>
  '''    <item><code>Previous</code><description>Previous defaults.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_CreditBureauDefaultDetails(callerScriptInfo As ISScriptExecutionInfo,
                                                                 creditBureauDefault As finCreditBureauDefault,
                                                        Optional includeAllServices As Boolean = False,
                                                        Optional includeActions As Boolean = True,
                                                        Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim AccountHistoryItem As finAccountHistoryItem
    Dim Response As ISCreditDefaultResponse
    Dim ServiceLog As ISServiceLog
    Dim ServiceLogs As ISServiceLogs
    Dim ShowStatus As Boolean
    Dim SummaryTableHistory As ISSummaryTable
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTablePrevious As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableHistory = finBL.CreateSummaryTable()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTablePrevious = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      .Columns.AddText(10).NoBreakChars = 10
      .Columns.AddText()

      ' Invalid Message (for when batch processing via the Credit Bureau Defaults wizard)
      If Len(creditBureauDefault.InvalidMessageProcessed) <> 0 Then
        Warnings &= "{{warning|" & creditBureauDefault.InvalidMessageProcessed & "}}"
      End If

      ' New?
      If creditBureauDefault.IsNew Then
        Warnings &= "{{info|This is a new Credit Bureau Default record.}}"
      ElseIf creditBureauDefault.SupportsUploading Then
        If creditBureauDefault.IsLoaded Then
          Warnings &= "{{info|**Active** Default last uploaded on **" & finBL.FormatDateLong(creditBureauDefault.LastDateExported) & "**.}}"
        End If
        If creditBureauDefault.IsUploadRequired Then
          Warnings &= "{{warning|Upload required.}}"
        End If
      End If

      ' Set Warnings Text Before
      .TextBefore = Warnings
      Warnings = ""

      With .Rows
        ' Existing details
        If Not creditBureauDefault.IsNew Then
          ' Original Uploaded
          .AddSectionHeading2("Original Details")
          .AddCaptionDate("Default Date:", creditBureauDefault.OriginalDateOfDefault)
          If creditBureauDefault.OriginalAccountBalance <> 0 Then
            .AddCaptionCurrency("Balance:", creditBureauDefault.OriginalAccountBalance, True)
          End If
          .AddCaptionCurrency("Default:", creditBureauDefault.OriginalDefault, True)
          If Len(creditBureauDefault.OriginalDefaultAccountTypeDescription) <> 0 Then
            .AddCaptionText("Account Type:", creditBureauDefault.OriginalDefaultAccountTypeDescription)
          End If
          If Len(creditBureauDefault.OriginalCreditProvider) <> 0 Then
            .AddCaptionText("Credit Provider:", creditBureauDefault.OriginalCreditProvider)
          End If

          ' Last Uploaded
          If creditBureauDefault.LastDateExported <> Nothing Then
            .AddSectionHeading2("Last Details")
            .AddCaptionCurrency("Default:", creditBureauDefault.LastDefault, True)
            .AddCaptionText("Status:", creditBureauDefault.LastDefaultStatusDescription)
            If Len(creditBureauDefault.LastDefaultAccountTypeDescription) <> 0 OrElse Len(creditBureauDefault.OriginalDefaultAccountTypeDescription) <> 0 Then
              .AddCaptionText("Account Type:", creditBureauDefault.LastDefaultAccountTypeDescription)
            End If
            If Len(creditBureauDefault.LastCreditProvider) <> 0 OrElse Len(creditBureauDefault.OriginalCreditProvider) <> 0 Then
              .AddCaptionText("Credit Provider:", creditBureauDefault.LastCreditProvider)
            End If
          End If
        End If
      End With
    End With

    ' Upload History
    If creditBureauDefault.Pk <> 0 AndAlso creditBureauDefault.CreditBureauService.SupportsUploadingDefaults Then
      With SummaryTableHistory
        ' Initialise
        .TableClass = iseSummaryTableClass.TabularData
        .Caption = "Upload History"
        .AutoStripe = True

        If finBL.CreditBureau.GetCreditDefaultServiceLogs(creditBureauDefault.Pk, ServiceLogs) Then
          ' Determine Columns to include
          ShowStatus = False
          For Each ServiceLog In ServiceLogs
            If ServiceLog.RequestStatus = iseAuditLogStatus.Pending Then ShowStatus = True
          Next

          ' Columns
          With .Columns
            .AddDate("Uploaded")
            .AddText("User")
            .AddCurrency("Amount")
            .AddText("Status")
            .AddText("Account Type")
            If ShowStatus Then .AddText(" ")
          End With

          For Each ServiceLog In ServiceLogs
            Response = DirectCast(ServiceLog.ExResponse, ISCreditBureau4.ISCreditDefaultResponse)

            With .Rows.Add().Cells
              .AddDateTime(ServiceLog.CreatedDate)
              .AddText(finBL.Users.ItemByPkSafe(ServiceLog.CreatedUserPk).UserIdResolved)
              .AddCurrency(Response.CurrentDefaultBalance)
              .AddText(Response.DefaultStatusDescription)
              .AddText(Response.AccountTypeDescription)
              If ShowStatus Then
                If ServiceLog.RequestStatus = iseAuditLogStatus.Pending Then
                  With .AddText("{{icon|Alert}}")
                    .Tooltip = "'Pending' request. No response was recorded from the Credit Bureau."
                  End With
                Else
                  .AddText("")
                End If
              End If
            End With
          Next
        Else
          ' Error
          .TextAfter = "{{warning|" & finBL.Error.Message(True) & "}}"
        End If

      End With
    End If

    ' Previous Defaults
    With SummaryTablePrevious
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      If includeAllServices Then
        .Caption = "Previous Defaults"
      Else
        .Caption = "Previous Defaults for " & creditBureauDefault.CreditBureauService.ServiceName
      End If
      .AutoStripe = True

      ' Columns
      With .Columns
        If includeAllServices Then .AddText("Service")
        .AddDate("Default Date")
        .AddCurrency("Original")
        .AddCurrency("Last")
        .AddText("Status")
      End With

      For Each AccountHistoryItem In creditBureauDefault.Account.HistoryItems
        If AccountHistoryItem.HistoryType = isefinAccountHistoryType.CreditBureauDefault AndAlso AccountHistoryItem.Status = isefinAccountHistoryStatus.Complete AndAlso
           (includeAllServices OrElse AccountHistoryItem.CreditBureauServiceId = creditBureauDefault.CreditBureauServiceId) Then
          With .Rows.Add().Cells
            If includeAllServices Then .AddText(AccountHistoryItem.CreditBureauServiceId)
            .AddDate(AccountHistoryItem.CreditBureauDefaultOriginalDateOfDefault)
            .AddCurrency(AccountHistoryItem.CreditBureauDefaultOriginalDefault)
            .AddCurrency(AccountHistoryItem.CreditBureauDefaultLastDefault)
            .AddText(AccountHistoryItem.CreditBureauDefaultLastDefaultStatusDescription)
          End With
        End If
      Next
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)
    If SummaryTableHistory.HasData Then SummaryTables.Add("History", SummaryTableHistory)
    If SummaryTablePrevious.HasData Then SummaryTables.Add("Previous", SummaryTablePrevious)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Credit Limits Summary.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="account">
  '''  The Account to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Status page and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_CreditLimits(callerScriptInfo As ISScriptExecutionInfo,
                                                   account As finAccount,
                                          Optional includeActions As Boolean = True,
                                          Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' Account_CreditLimits
    '
    ' Version: 1.09 (10/01/2024)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.07  28/05/2019  ISS      J031120   
    '    1.08  10/01/2024  ISS      J032713   Updated Permission Keys
    '    1.09  10/01/2024  ISS      J032720   Updated Permission Keys
    ' #################################################################

    Dim AvailableCredit1 As Decimal
    Dim AvailableCredit2 As Decimal
    Dim AvailableCredit3 As Decimal
    Dim Balance As Decimal
    Dim CreditLimit1 As Decimal
    Dim CreditLimit2 As Decimal
    Dim CreditLimit3 As Decimal
    Dim CreditLimit1FutureChange As Boolean
    Dim CreditLimit2FutureChange As Boolean
    Dim CreditLimit3FutureChange As Boolean
    Dim DateAsAt As Date
    Dim OtherDeductions As Decimal
    Dim PendingWithdrawals As Decimal
    Dim PendingWithdrawalsReview As Decimal
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim UnclearedFunds As Decimal
    Dim UseCreditLimit2 As Boolean
    Dim UseCreditLimit3 As Boolean
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Date As At
    DateAsAt = finBL.TimeZoneFunctions.GetCurrentDatabaseDate()

    With account
      ' Find Credit Limits in use
      UseCreditLimit2 = .AccountType.CreditLimitCount > 1
      UseCreditLimit3 = .AccountType.CreditLimitCount > 2

      ' Get Balance
      account.GetBalance(Balance)

      ' Get Pending Withdrawals
      .GetPendingWithdrawals(PendingWithdrawals, , PendingWithdrawalsReview)

      ' Get Uncleared Funds
      If .AccountType.CreditLimitUseUnclearedFunds Then
        .GetUnclearedFunds2(UnclearedFunds)
      Else
        UnclearedFunds = 0
      End If

      ' Get Credit Limits
      If Not .GetCreditLimits(DateAsAt, CreditLimit1, CreditLimit2, CreditLimit3, "", CreditLimit1FutureChange, CreditLimit2FutureChange, CreditLimit3FutureChange) Then
        ' No point continuing
        Return SummaryTables
      End If

      ' Other Deductions
      .GetCreditLimitOtherDeductions(OtherDeductions)

      ' Available Credit
      AvailableCredit1 = CreditLimit1 - Balance - PendingWithdrawals - UnclearedFunds - OtherDeductions
      AvailableCredit2 = CreditLimit2 - Balance - PendingWithdrawals - UnclearedFunds - OtherDeductions
      AvailableCredit3 = CreditLimit3 - Balance - PendingWithdrawals - UnclearedFunds - OtherDeductions
    End With

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .AutoStripe = True
      .Caption = ""

      ' Columns
      With .Columns
        .AddText(" ", 20).NoBreakChars = 20
        .AddCurrency(account.AccountType.CreditLimit1DescriptionResolved, 20)
        If UseCreditLimit2 Then .AddCurrency(account.AccountType.CreditLimit2DescriptionResolved, 20)
        If UseCreditLimit3 Then .AddCurrency(account.AccountType.CreditLimit3DescriptionResolved, 20)
      End With

      With .Rows
        ' Credit Limit
        With .Add(iseSummaryTableRowClass.FooterBold).Cells
          .AddCaption("Credit Limit")
          .AddCurrency(CreditLimit1)
          If UseCreditLimit2 Then .AddCurrency(CreditLimit2)
          If UseCreditLimit3 Then .AddCurrency(CreditLimit3)
        End With

        ' Less Balance
        With .Add().Cells
          .AddCaption("less Balance")
          .AddCurrency(Balance)
          If UseCreditLimit2 Then .AddCurrency(Balance)
          If UseCreditLimit3 Then .AddCurrency(Balance)
        End With

        ' Less Pending Withdrawals
        If PendingWithdrawals <> 0 Then
          With .Add().Cells
            .AddCaption("less Pending Withdrawals")
            .AddCurrency(PendingWithdrawals)
            If UseCreditLimit2 Then .AddCurrency(PendingWithdrawals)
            If UseCreditLimit3 Then .AddCurrency(PendingWithdrawals)
          End With
        End If

        ' Less Uncleared Funds
        If UnclearedFunds <> 0 Then
          With .Add().Cells
            .AddCaption("less Uncleared Funds")
            .AddCurrency(UnclearedFunds)
            If UseCreditLimit2 Then .AddCurrency(UnclearedFunds)
            If UseCreditLimit3 Then .AddCurrency(UnclearedFunds)
          End With
        End If

        ' Less Other Deductions
        If OtherDeductions <> 0 Then
          With .Add().Cells
            If OtherDeductions < 0 Then
              .AddCaption("plus " & account.AccountType.CreditLimitOtherDeductionsDescriptionResolved)
              .AddCurrency(-OtherDeductions)
              If UseCreditLimit2 Then .AddCurrency(-OtherDeductions)
              If UseCreditLimit3 Then .AddCurrency(-OtherDeductions)
            Else
              .AddCaption("less " & account.AccountType.CreditLimitOtherDeductionsDescriptionResolved)
              .AddCurrency(OtherDeductions)
              If UseCreditLimit2 Then .AddCurrency(OtherDeductions)
              If UseCreditLimit3 Then .AddCurrency(OtherDeductions)
            End If
          End With
        End If

        ' Available Credit
        With .Add(iseSummaryTableRowClass.FooterBold).Cells
          ' Credit Limit 1
          .AddCaption("Available Credit")
          With .AddCurrency(AvailableCredit1, True)
            If AvailableCredit1 < 0 Then .ForegroundColour = "red"
          End With

          ' Credit Limit 2
          If UseCreditLimit2 Then
            With .AddCurrency(AvailableCredit2, True)
              If AvailableCredit2 < 0 Then .ForegroundColour = "red"
            End With
          End If

          ' Credit Limit 3
          If UseCreditLimit3 Then
            With .AddCurrency(AvailableCredit3, True)
              If AvailableCredit3 < 0 Then .ForegroundColour = "red"
            End With
          End If
        End With
      End With

      ' Warnings
      If CreditLimit1FutureChange OrElse CreditLimit2FutureChange OrElse CreditLimit3FutureChange Then
        Warnings &= "{{warning|Future Credit Limit changes exist.}}"
      End If
      If PendingWithdrawalsReview <> 0 Then
        Warnings &= "{{warning|Pending Withdrawals require reviewing.}}"
      End If
      If account.SuspendWithdrawals Then
        Warnings &= "{{warning|Withdrawals are suspended.}}"
      End If
      If account.Transactions.HasFutureTransactionBalance Then
        Warnings &= "{{Warning|Balances include future transactions.}}"
      End If
      .TextAfter = Warnings

      ' Actions
      If includeActions Then
        With .Actions
          .AddFormAction("CreditLimitReview", "Review", finBL.CurrentUser.Permissions.Allow("Account.CreditLimit.View") AndAlso finBL.CurrentUser.Permissions.Allow("Account.Form.Page.Status") AndAlso Not account.IsQuoteOrClosedQuote).ShowInWebInterfaces = True
          .AddFormAction("PendingWithdrawalReview", "Review Pending Withdrawal", finBL.CurrentUser.Permissions.Allow("Account.PendingWithdrawal.View") AndAlso finBL.CurrentUser.Permissions.Allow("Account.Form.Page.Status") AndAlso finBL.CurrentUser.Permissions.Allow("Account.Form.Page.Status") AndAlso account.AccountType.CreditLimitUsePendingWithdrawals AndAlso Not account.IsQuoteOrClosedQuote).ShowInWebInterfaces = True
        End With
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Credit Limits Summary (Version 1.02, Last updated 28/05/2019).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="account">
  '''  The Account to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="dateAsAt">
  '''  The Date of the Transaction. The Credit Limit is found AS AT this date. All other values include all Transactions.
  ''' </param>
  ''' <param name="plusPayment">
  '''  A new Payment to include in the Summary.
  ''' </param>
  ''' <param name="lessWithdrawal">
  '''  A new Withdrawal to include in the Summary.
  ''' </param>
  ''' <param name="lessFees">
  '''  Fees to include in the Summary.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Status page and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_CreditLimits_ForTransaction(callerScriptInfo As ISScriptExecutionInfo,
                                                                  account As finAccount,
                                                                  dateAsAt As Date,
                                                         Optional plusPaymentCaption As String = "Payment",
                                                         Optional plusPayment As Decimal = 0,
                                                         Optional lessWithdrawalCaption As String = "Withdrawal",
                                                         Optional lessWithdrawal As Decimal = 0,
                                                         Optional lessFeesCaption As String = "Fees",
                                                         Optional lessFees As Decimal = 0,
                                                         Optional includeActions As Boolean = True,
                                                         Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim AvailableCredit1 As Decimal
    Dim AvailableCredit2 As Decimal
    Dim AvailableCredit3 As Decimal
    Dim Balance As Decimal
    Dim CreditLimit1 As Decimal
    Dim CreditLimit2 As Decimal
    Dim CreditLimit3 As Decimal
    Dim CreditLimit1FutureChange As Boolean
    Dim CreditLimit2FutureChange As Boolean
    Dim CreditLimit3FutureChange As Boolean
    Dim OtherDeductions As Decimal
    Dim PendingWithdrawals As Decimal
    Dim PendingWithdrawalsReview As Decimal
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim UnclearedFunds As Decimal
    Dim UseCreditLimit2 As Boolean
    Dim UseCreditLimit3 As Boolean
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Date As At
    If dateAsAt = Nothing Then
      dateAsAt = finBL.TimeZoneFunctions.GetCurrentDatabaseDate()
    Else
      dateAsAt = dateAsAt.Date
    End If

    With account
      ' Find Credit Limits in use
      UseCreditLimit2 = .AccountType.CreditLimitCount > 1
      UseCreditLimit3 = .AccountType.CreditLimitCount > 2

      ' Get Balance (all Transactions)
      account.GetBalance(Balance)

      ' Get Pending Withdrawals (all Transactions)
      .GetPendingWithdrawals(PendingWithdrawals, , PendingWithdrawalsReview)

      ' Get Uncleared Funds (all Transactions)
      If .AccountType.CreditLimitUseUnclearedFunds Then
        .GetUnclearedFunds2(UnclearedFunds)
      Else
        UnclearedFunds = 0
      End If

      ' Get Credit Limits
      If Not .GetCreditLimits(dateAsAt, CreditLimit1, CreditLimit2, CreditLimit3, "", CreditLimit1FutureChange, CreditLimit2FutureChange, CreditLimit3FutureChange) Then
        ' No point continuing
        Return SummaryTables
      End If

      ' Other Deductions
      .GetCreditLimitOtherDeductions(OtherDeductions)

      ' Available Credit
      AvailableCredit1 = CreditLimit1 - Balance - PendingWithdrawals - UnclearedFunds - OtherDeductions + plusPayment - lessWithdrawal - lessFees
      AvailableCredit2 = CreditLimit2 - Balance - PendingWithdrawals - UnclearedFunds - OtherDeductions + plusPayment - lessWithdrawal - lessFees
      AvailableCredit3 = CreditLimit3 - Balance - PendingWithdrawals - UnclearedFunds - OtherDeductions + plusPayment - lessWithdrawal - lessFees
    End With

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .AutoStripe = True
      .Caption = ""

      ' Columns
      With .Columns
        .AddText(" ", 30).NoBreakChars = 30
        .AddCurrency(account.AccountType.CreditLimit1DescriptionResolved, 20)
        If UseCreditLimit2 Then .AddCurrency(account.AccountType.CreditLimit2DescriptionResolved, 20)
        If UseCreditLimit3 Then .AddCurrency(account.AccountType.CreditLimit3DescriptionResolved, 20)
      End With

      With .Rows
        ' Credit Limit
        With .Add(iseSummaryTableRowClass.FooterBold).Cells
          .AddCaption("Credit Limit")
          .AddCurrency(CreditLimit1)
          If UseCreditLimit2 Then .AddCurrency(CreditLimit2)
          If UseCreditLimit3 Then .AddCurrency(CreditLimit3)
        End With

        ' Less Balance
        With .Add().Cells
          .AddCaption("less Balance")
          .AddCurrency(Balance)
          If UseCreditLimit2 Then .AddCurrency(Balance)
          If UseCreditLimit3 Then .AddCurrency(Balance)
        End With

        ' Less Pending Withdrawals
        If PendingWithdrawals <> 0 Then
          With .Add().Cells
            .AddCaption("less Pending Withdrawals")
            .AddCurrency(PendingWithdrawals)
            If UseCreditLimit2 Then .AddCurrency(PendingWithdrawals)
            If UseCreditLimit3 Then .AddCurrency(PendingWithdrawals)
          End With
        End If

        ' Payment
        If plusPayment <> 0 Then
          With .Add().Cells
            .AddCaption("plus " & plusPaymentCaption)
            .AddCurrency(plusPayment)
            If UseCreditLimit2 Then .AddCurrency(plusPayment)
            If UseCreditLimit3 Then .AddCurrency(plusPayment)
          End With
        End If

        ' Withdrawal
        If lessWithdrawal <> 0 Then
          With .Add().Cells
            .AddCaption("less " & lessWithdrawalCaption)
            .AddCurrency(lessWithdrawal)
            If UseCreditLimit2 Then .AddCurrency(lessWithdrawal)
            If UseCreditLimit3 Then .AddCurrency(lessWithdrawal)
          End With
        End If

        ' Fee
        If lessFees <> 0 Then
          With .Add().Cells
            .AddCaption("less " & lessFeesCaption)
            .AddCurrency(lessFees)
            If UseCreditLimit2 Then .AddCurrency(lessFees)
            If UseCreditLimit3 Then .AddCurrency(lessFees)
          End With
        End If

        ' Less Uncleared Funds
        If UnclearedFunds <> 0 Then
          With .Add().Cells
            .AddCaption("less Uncleared Funds")
            .AddCurrency(UnclearedFunds)
            If UseCreditLimit2 Then .AddCurrency(UnclearedFunds)
            If UseCreditLimit3 Then .AddCurrency(UnclearedFunds)
          End With
        End If

        ' Less Other Deductions
        If OtherDeductions <> 0 Then
          With .Add().Cells
            If OtherDeductions < 0 Then
              .AddCaption("plus " & account.AccountType.CreditLimitOtherDeductionsDescriptionResolved)
              .AddCurrency(-OtherDeductions)
              If UseCreditLimit2 Then .AddCurrency(-OtherDeductions)
              If UseCreditLimit3 Then .AddCurrency(-OtherDeductions)
            Else
              .AddCaption("less " & account.AccountType.CreditLimitOtherDeductionsDescriptionResolved)
              .AddCurrency(OtherDeductions)
              If UseCreditLimit2 Then .AddCurrency(OtherDeductions)
              If UseCreditLimit3 Then .AddCurrency(OtherDeductions)
            End If
          End With
        End If

        ' Available Credit
        With .Add(iseSummaryTableRowClass.FooterBold).Cells
          ' Credit Limit 1
          .AddCaption("Available Credit")
          With .AddCurrency(AvailableCredit1, True)
            If AvailableCredit1 < 0 Then .ForegroundColour = "red"
          End With

          ' Warning if Withdrawal and Credit Limit 1 exceeded
          If lessWithdrawal <> 0 AndAlso AvailableCredit1 < 0 Then
            Warnings &= "{{warning|This " & lessWithdrawalCaption & " will exceed '" & account.AccountType.CreditLimit1DescriptionResolved & "'.}}"
          End If

          ' Credit Limit 2
          If UseCreditLimit2 Then
            With .AddCurrency(AvailableCredit2, True)
              If AvailableCredit2 < 0 Then .ForegroundColour = "red"
            End With

            ' Warning if Withdrawal and Credit Limit 2 exceeded
            If lessWithdrawal <> 0 AndAlso AvailableCredit2 < 0 Then
              Warnings &= "{{warning|This " & lessWithdrawalCaption & " will exceed '" & account.AccountType.CreditLimit2DescriptionResolved & "'.}}"
            End If
          End If

          ' Credit Limit 3
          If UseCreditLimit3 Then
            With .AddCurrency(AvailableCredit3, True)
              If AvailableCredit3 < 0 Then .ForegroundColour = "red"
            End With

            ' Warning if Withdrawal and Credit Limit 3 exceeded
            If lessWithdrawal <> 0 AndAlso AvailableCredit3 < 0 Then
              Warnings &= "{{warning|This " & lessWithdrawalCaption & " will exceed '" & account.AccountType.CreditLimit3DescriptionResolved & "'.}}"
            End If
          End If
        End With
      End With

      ' Warnings
      If CreditLimit1FutureChange OrElse CreditLimit2FutureChange OrElse CreditLimit3FutureChange Then
        Warnings &= "{{warning|Future Credit Limit changes exist.}}"
      End If
      If PendingWithdrawalsReview <> 0 Then
        Warnings &= "{{warning|Pending Withdrawals require reviewing.}}"
      End If
      If account.SuspendWithdrawals Then
        Warnings &= "{{warning|Withdrawals are suspended.}}"
      End If
      If account.Transactions.HasFutureTransactionBalance Then
        Warnings &= "{{Warning|Balances include future transactions.}}"
      End If
      .TextAfter = Warnings

      ' Actions
      If includeActions Then
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account History Item Summary (Version 1.04, Last updated 11/08/2020).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="accountHistoryItem">
  '''  The Account History Item.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account History page and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Summary.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_HistoryItemSummary(callerScriptInfo As ISScriptExecutionInfo,
                                                         accountHistoryItem As finAccountHistoryItem,
                                                Optional includeActions As Boolean = True,
                                                Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim Account As finAccount
    Dim DateAsAt As Date
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Date As At
    DateAsAt = finBL.TimeZoneFunctions.GetCurrentDatabaseDate()

    ' Cache Account
    Account = accountHistoryItem.Account

    ' Summary table
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Columns.AddText(16).NoBreakChars = 16
      .Columns.AddText()

      If accountHistoryItem IsNot Nothing Then
        With .Rows
          ' General
          If accountHistoryItem.HistoryType = isefinAccountHistoryType.MonitorCategoryChange AndAlso Len(accountHistoryItem.MonitorCategoryId) = 0 Then
            With .AddCaptionText("Description:", "Monitor Category Cleared", iseSummaryTableCellClass.Highlight1)
              .Cells(1).Tooltip = String.Format("Primary Key: {0}", accountHistoryItem.Pk)
            End With
          Else
            With .AddCaptionText("Description:", accountHistoryItem.HistoryTypeText, iseSummaryTableCellClass.Highlight1)
              .Cells(1).Tooltip = String.Format("Primary Key: {0}", accountHistoryItem.Pk)
            End With
          End If
          .AddCaptionWiki("Created:", finBL.Utilities.GetUserAndDateWikiText("", accountHistoryItem.CreatedUserPk, accountHistoryItem.CreatedDate))
          If accountHistoryItem.CreatedUserPk <> accountHistoryItem.UpdatedUserPk OrElse accountHistoryItem.CreatedUtcDate <> accountHistoryItem.UpdatedUtcDate Then
            .AddCaptionWiki("Last Updated:", finBL.Utilities.GetUserAndDateWikiText("", accountHistoryItem.UpdatedUserPk, accountHistoryItem.UpdatedDate))
          End If

          ' Details
          .AddSectionHeading2("Details")
          .AddCaptionDate("Date:", accountHistoryItem.Date)
          If Len(accountHistoryItem.Reference) <> 0 Then
            .AddCaptionText("Reference:", accountHistoryItem.Reference)
          End If

          ' History Type Specific
          Select Case accountHistoryItem.HistoryType
            Case isefinAccountHistoryType.CreditBureauDefault
              ' Credit Bureau Default
              .AddCaptionText("Service:", accountHistoryItem.CreditBureauServiceId)
              If Len(accountHistoryItem.CreditBureauDefaultReference) <> 0 Then .AddCaptionText("Bureau Reference:", accountHistoryItem.CreditBureauDefaultReference)

            Case isefinAccountHistoryType.CreditLimitChange
              ' Credit Limit Change
              .AddCaptionCurrency(Account.AccountType.CreditLimit1DescriptionResolved & ":", accountHistoryItem.CreditLimit1, True)
              If Account.AccountType.CreditLimitCount > 1 Then
                .AddCaptionCurrency(Account.AccountType.CreditLimit2DescriptionResolved & ":", accountHistoryItem.CreditLimit2, True)
              End If
              If Account.AccountType.CreditLimitCount > 2 Then
                .AddCaptionCurrency(Account.AccountType.CreditLimit3DescriptionResolved & ":", accountHistoryItem.CreditLimit3, True)
              End If

            Case isefinAccountHistoryType.DefaultInterestRateChange
              ' Default Interest Rate Change
              .AddCaptionText("Basis:", accountHistoryItem.DefaultInterestRateBasisText)
              .AddCaptionPercentage("Rate:", accountHistoryItem.DefaultInterestRate / 100, 4, True)

            Case isefinAccountHistoryType.FloatingInterestRateChange
              ' Floating Interest Rate Change
              .AddCaptionText("Instruction:", accountHistoryItem.InterestInstructionText)
              .AddCaptionDate("Effective Date:", accountHistoryItem.DateEffective)
              .AddCaptionPercentage("Rate (Net):", accountHistoryItem.InterestRate / 100, 4, True)
              .AddCaptionPercentage("Premium:", accountHistoryItem.InterestRatePremium / 100, 4, True)

              ' New Values
              If accountHistoryItem.Status = isefinAccountHistoryStatus.Complete Then
                If accountHistoryItem.PaymentRegularFirstDate = Nothing Then
                  .AddCaptionCurrency("New Payment:", accountHistoryItem.PaymentRegular, True)
                Else
                  .AddCaptionWiki("New Payment:", String.Format("**{0}** from **{1}**", finBL.FormatCurrency(accountHistoryItem.PaymentRegular, True), finBL.FormatDateLong(accountHistoryItem.PaymentRegularFirstDate)))
                End If
                .AddCaptionDate("New Maturity:", accountHistoryItem.DateMaturity)
              End If

              ' Hold
              If accountHistoryItem.DateNotified = Nothing Then
                .AddCaptionText("Notified:", "Not yet notified")
              Else
                .AddCaptionDate("Notified:", accountHistoryItem.DateNotified)
              End If

            Case isefinAccountHistoryType.InterestCycleChange
              ' Interest Cycle Change
              .AddCaptionText("Cycle:", finBL.Utilities.DateCycleGetDescription(True, accountHistoryItem.InterestCycle))

            Case isefinAccountHistoryType.InterestPaymentTypeChange
              ' Interest Payment Type Change
              .AddCaptionText("Payment Type:", finBL.Utilities.DateCycleGetDescription(True, accountHistoryItem.InterestPaymentTypeText))
              Select Case accountHistoryItem.InterestPaymentType
                Case isefinAccountInterestPaymentType.Cheque, isefinAccountInterestPaymentType.DirectCredit
                  .AddCaptionCodeDescription("Payment Method:", accountHistoryItem.InterestPaymentMethodId, finBL.PaymentMethods)
                Case isefinAccountInterestPaymentType.Transfer
                  .AddCaptionCodeDescription("Transfer To:", accountHistoryItem.InterestTransferToAccountId, finBL.AccountFunctions)
              End Select

            Case isefinAccountHistoryType.InterestRateChange
              ' Interest Rate Change
              .AddCaptionText("Type:", accountHistoryItem.InterestTypeText)

              Select Case accountHistoryItem.InterestType
                Case isefinAccountInterestType.FixedRate
                  .AddCaptionPercentage("Rate:", accountHistoryItem.InterestRate / 100, 4, True)

                Case isefinAccountInterestType.FloatingRate
                  .AddCaptionPercentage("Rate (Net):", accountHistoryItem.InterestRate / 100, 4, True)
                  .AddCaptionPercentage("Premium:", accountHistoryItem.InterestRatePremium / 100, 4, True)

                Case isefinAccountInterestType.InterestFree

                Case isefinAccountInterestType.RateTable
                  .AddCaptionCodeDescription("Rate Table:", accountHistoryItem.InterestRateTableId, finBL.RateTables)
                  .AddCaptionPercentage("Premium:", accountHistoryItem.InterestRatePremium / 100, 4, True)
              End Select

            Case isefinAccountHistoryType.InvestmentValueChange
              .AddCaptionCurrency("Investment Value:", accountHistoryItem.InvestmentValue, True)

            Case isefinAccountHistoryType.MaturityDateChange
              ' Maturity Date Change
              If accountHistoryItem.Reference = "Opening" Then
                If Len(accountHistoryItem.TermCycle) = 0 Then
                  .AddCaptionDate("Maturity Date:", accountHistoryItem.DateMaturity)
                Else
                  If accountHistoryItem.TermCycle = "On Call" Then
                    .AddCaptionText("Term:", accountHistoryItem.TermCycleDescription)
                  Else
                    .AddCaptionWiki("Term:", String.Format("**{0}**, maturing on **{1}**", accountHistoryItem.TermCycleDescription, finBL.FormatDateLong(accountHistoryItem.DateMaturity)))
                  End If
                End If
              Else
                If Len(accountHistoryItem.TermCycle) = 0 Then
                  .AddCaptionDate("Old Maturity:", accountHistoryItem.DateMaturityOriginal)
                  .AddCaptionDate("New Maturity:", accountHistoryItem.DateMaturity)
                Else
                  If accountHistoryItem.TermCycleOriginal = "On Call" Then
                    .AddCaptionText("Old Term:", accountHistoryItem.TermCycleOriginalDescription)
                  Else
                    .AddCaptionWiki("Old Term:", String.Format("**{0}**, maturing on **{1}**", accountHistoryItem.TermCycleOriginalDescription, finBL.FormatDateLong(accountHistoryItem.DateMaturityOriginal)))
                  End If
                  If accountHistoryItem.TermCycle = "On Call" Then
                    .AddCaptionText("New Term:", accountHistoryItem.TermCycleDescription)
                  Else
                    .AddCaptionWiki("New Term:", String.Format("**{0}**, maturing on **{1}**", accountHistoryItem.TermCycleDescription, finBL.FormatDateLong(accountHistoryItem.DateMaturity)))
                  End If
                End If
              End If

            Case isefinAccountHistoryType.MaturityInstructionChange
              ' Maturity Instruction Change
              .AddCaptionText("Instruction:", accountHistoryItem.MaturityInstructionText)
              Select Case Account.MaturityInstruction
                Case isefinAccountMaturityInstruction.ReinvestAmount
                  .AddCaptionCurrency("Amount:", Account.MaturityValue, True)
              End Select
              Select Case Account.MaturityInstruction
                Case isefinAccountMaturityInstruction.ReinvestAll, isefinAccountMaturityInstruction.ReinvestAmount, isefinAccountMaturityInstruction.ReinvestPrincipal
                  If Len(Account.MaturityAccountId) <> 0 Then
                    With .AddCaptionCodeDescriptionWithFormShow("Reinvest:", Account.MaturityAccountPk, finBL.AccountFunctions, "Account")
                      .Cells(1).Value = "**Account** " & .Cells(1).Value
                    End With
                  ElseIf Len(Account.MaturityAccountTypeId) <> 0 Then
                    With .AddCaptionCodeDescription("Reinvest:", Account.MaturityAccountTypePk, finBL.AccountTypes)
                      .Cells(1).Value = "**Account Type** " & .Cells(1).Value
                    End With
                  Else
                    .AddCaptionText("Reinvest:", "")
                  End If
              End Select
              Select Case Account.MaturityInstruction
                Case isefinAccountMaturityInstruction.PayoutAll, isefinAccountMaturityInstruction.ReinvestAmount, isefinAccountMaturityInstruction.ReinvestPrincipal
                  Select Case Account.MaturityPaymentType
                    Case isefinAccountMaturityPaymentType.Transfer
                      If Len(Account.MaturityTransferToAccountId) = 0 Then
                        .AddCaptionText("Repayment:", Account.MaturityPaymentTypeText)
                      Else
                        .AddCaptionWiki("Repayment:", String.Format("**Transfer** to **[[app://formshow?form=Accounts&id={0}|{1}]]**", finBL.UrlEncode(Account.MaturityTransferToAccountId), Account.MaturityTransferToAccountId))
                      End If
                    Case Else
                      .AddCaptionText("Repayment:", Account.MaturityPaymentTypeText)
                  End Select
              End Select

            Case isefinAccountHistoryType.MinimumPaymentChange
              ' Minimum Payment Change
              .AddCaptionText("Basis:", accountHistoryItem.MinimumPaymentBasisText)

              Select Case accountHistoryItem.MinimumPaymentBasis
                Case isefinAccountMinimumPaymentBasis.Instalment
                  .AddCaptionDate("End Date:", accountHistoryItem.MinimumPaymentInstalmentEndDate)
                  .AddCaptionCurrency("Residual Value:", accountHistoryItem.MinimumPaymentInstalmentResidualValue, True)

                Case isefinAccountMinimumPaymentBasis.Higher
                  .AddCaptionWiki("Value/ Percent:", String.Format("**{0}** or **{1}**", finBL.FormatCurrency(accountHistoryItem.MinimumPaymentValue, True), finBL.FormatPercentage(accountHistoryItem.MinimumPaymentPercent / 100, 4)))

                Case isefinAccountMinimumPaymentBasis.OngoingSetValue, isefinAccountMinimumPaymentBasis.SetValue
                  .AddCaptionCurrency("Value:", accountHistoryItem.MinimumPaymentValue, True)

                Case isefinAccountMinimumPaymentBasis.PercentOfBalance
                  .AddCaptionPercentage("Percent:", accountHistoryItem.MinimumPaymentValue / 100, 4, True)
              End Select

              ' Due days
              If accountHistoryItem.MinimumPaymentDueDaysOverride Then
                .AddCaptionInteger("Due Days:", accountHistoryItem.MinimumPaymentDueDays)
                Warnings &= "{{info|Due days overrides the Account Type setting.}}"
              End If

              ' Hold
              If accountHistoryItem.MinimumPaymentHoldToDate <> Nothing AndAlso accountHistoryItem.MinimumPaymentHoldToDate >= DateAsAt Then
                .AddCaptionDate("Hold To:", accountHistoryItem.MinimumPaymentHoldToDate)
              End If

            Case isefinAccountHistoryType.MonitorCategoryChange
              ' Monitor Category Change
              If Len(accountHistoryItem.MonitorCategoryId) = 0 Then
                .AddCaptionText("Cleared from:", accountHistoryItem.AccountMonitorCategoryText)
              Else
                .AddCaptionCodeDescription("Moved into:", accountHistoryItem.MonitorCategoryId, accountHistoryItem.AccountMonitorCategoryText)
              End If

            Case isefinAccountHistoryType.OtherInterestRateChange
              ' Other Interest Rate Change
              .AddCaptionText("Type:", accountHistoryItem.OtherInterestTypeText)
              .AddCaptionPercentage("Rate:", accountHistoryItem.OtherInterestRate / 100, 4, True)

            Case isefinAccountHistoryType.PendingWithdrawal
              ' Pending Withdrawal
              .AddCaptionCurrency("Value:", accountHistoryItem.Value, True)
              .AddCaptionDate("Review On:", accountHistoryItem.DateReview)

            Case isefinAccountHistoryType.StatementChange
              ' Statement Change
              .AddCaptionText("Cycle:", finBL.Utilities.DateCycleGetDescription(True, accountHistoryItem.StatementCycle))
              If accountHistoryItem.Reference = "Opening" Then
                .AddCaptionDate("First Date:", accountHistoryItem.StatementDateNext)
              Else
                .AddCaptionDate("Next Date:", accountHistoryItem.StatementDateNext)
              End If

            Case isefinAccountHistoryType.StatusChangeRule
              ' Status Change Rule
              If Account.AccountType.Rules.Exists(accountHistoryItem.Reference) Then
                .AddCaptionCodeDescription("Rule applied:", accountHistoryItem.Reference, Account.AccountType.Rules(accountHistoryItem.Reference).Description)
              Else
                .AddCaptionText("Rule applied:", accountHistoryItem.Reference)
              End If

            Case isefinAccountHistoryType.TaxCategoryChange
              .AddCaptionCodeDescription("Tax Category:", accountHistoryItem.TaxCategoryPk, finBL.TaxCategories)

            Case Else
              Warnings &= "{{warning|History type '**" & accountHistoryItem.HistoryTypeText & "**' is not yet implemented.}}"
          End Select

          ' Notes
          If Len(accountHistoryItem.Notes) <> 0 Then
            .AddSectionHeading2("Notes")
            .AddText(accountHistoryItem.Notes)
          End If
        End With

        ' Warnings
        Select Case accountHistoryItem.Status
          Case isefinAccountHistoryStatus.Cancelled
            Warnings &= "{{warning|This " & accountHistoryItem.HistoryTypeText & " was " & finBL.Utilities.GetUserAndDateWikiText("cancelled", accountHistoryItem.UpdatedUserPk, accountHistoryItem.UpdatedDate) & ".}}"

          Case isefinAccountHistoryStatus.Complete
            Select Case accountHistoryItem.HistoryType
              Case isefinAccountHistoryType.PendingWithdrawal
                Warnings &= "{{info|This " & accountHistoryItem.HistoryTypeText & " was " & finBL.Utilities.GetUserAndDateWikiText("completed", accountHistoryItem.UpdatedUserPk, accountHistoryItem.UpdatedDate) & ".}}"
            End Select

          Case isefinAccountHistoryStatus.Pending
            Warnings &= "{{warning|This " & accountHistoryItem.HistoryTypeText & " is still outstanding.}}"
        End Select
        .TextAfter = Warnings

        ' Actions
        If includeActions Then
          With .Actions
          End With
        End If
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Summary", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account History Item Credit Bureau Default Summary (Version 1.03, Last updated 17/08/2016).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="accountHistoryItem">
  '''  The Account History Item.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account History page and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Summary.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_HistoryItem_CreditBureauDefaultSummary(callerScriptInfo As ISScriptExecutionInfo,
                                                                             accountHistoryItem As finAccountHistoryItem,
                                                                    Optional includeActions As Boolean = True,
                                                                    Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Summary table
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Columns.AddText(16).NoBreakChars = 16
      .Columns.AddText()

      If accountHistoryItem IsNot Nothing AndAlso accountHistoryItem.HistoryType = isefinAccountHistoryType.CreditBureauDefault Then
        ' Set Warnings Text Before
        If accountHistoryItem.Status = isefinAccountHistoryStatus.Complete Then
          If accountHistoryItem.CreditBureauDefaultIsCurrentStatusCancelling() Then
            Warnings &= "{{info|**Cancelled** on **" & finBL.FormatDateLong(accountHistoryItem.CreditBureauDefaultLastDateExported) & "**.}}"
          Else
            Warnings &= "{{info|Closed with a status of **" & accountHistoryItem.CreditBureauDefaultLastDefaultStatusDescription & "** on **" & finBL.FormatDateLong(accountHistoryItem.CreditBureauDefaultLastDateExported) & "**.}}"
          End If
        ElseIf accountHistoryItem.Status = isefinAccountHistoryStatus.Cancelled Then
          Warnings &= "{{info|**Cancelled**.}}"
        Else
          If accountHistoryItem.CreditBureauDefaultLastDateExported = Nothing Then
            ' Not yet uploaded
          Else
            Warnings &= "{{info|Open with a status of **" & finBL.HtmlEncode(accountHistoryItem.CreditBureauDefaultLastDefaultStatusDescription) & "**.}}"
          End If
        End If
        If accountHistoryItem.CreditBureauDefaultIsUploadRequired Then
          Warnings &= "{{warning|Upload required.}}"
        End If
        .TextBefore = Warnings
        Warnings = ""

        With .Rows
          ' Current Details
          If accountHistoryItem.Status = isefinAccountHistoryStatus.Pending Then
            .AddSectionHeading2("Current Details")
            .AddCaptionCurrency("Default:", accountHistoryItem.CreditBureauDefaultCurrentDefault, True)
            .AddCaptionText("Status:", accountHistoryItem.CreditBureauDefaultCurrentDefaultStatusDescription)
            .AddCaptionText("Account Type:", accountHistoryItem.CreditBureauDefaultCurrentDefaultAccountTypeDescription)
            If Len(accountHistoryItem.CreditBureauDefaultCurrentCreditProvider) <> 0 OrElse Len(accountHistoryItem.CreditBureauDefaultOriginalCreditProvider) <> 0 Then
              .AddCaptionText("Credit Provider:", accountHistoryItem.CreditBureauDefaultCurrentCreditProvider)
            End If
          End If

          ' Original Uploaded
          .AddSectionHeading2("Original Details")
          .AddCaptionDate("Default Date:", accountHistoryItem.CreditBureauDefaultOriginalDateOfDefault)
          If accountHistoryItem.CreditBureauDefaultOriginalAccountBalance <> 0 Then
            .AddCaptionCurrency("Balance:", accountHistoryItem.CreditBureauDefaultOriginalAccountBalance, True)
          End If
          .AddCaptionCurrency("Default:", accountHistoryItem.CreditBureauDefaultOriginalDefault, True)
          If Len(accountHistoryItem.CreditBureauDefaultOriginalDefaultAccountTypeDescription) <> 0 Then
            .AddCaptionText("Account Type:", accountHistoryItem.CreditBureauDefaultOriginalDefaultAccountTypeDescription)
          End If
          If Len(accountHistoryItem.CreditBureauDefaultOriginalCreditProvider) <> 0 Then
            .AddCaptionText("Credit Provider:", accountHistoryItem.CreditBureauDefaultOriginalCreditProvider)
          End If

          ' Last Uploaded
          If accountHistoryItem.CreditBureauDefaultLastDateExported <> Nothing Then
            .AddSectionHeading2("Last Details")
            .AddCaptionCurrency("Default:", accountHistoryItem.CreditBureauDefaultLastDefault, True)
            .AddCaptionText("Status:", accountHistoryItem.CreditBureauDefaultLastDefaultStatusDescription)
            If Len(accountHistoryItem.CreditBureauDefaultLastDefaultAccountTypeDescription) <> 0 OrElse Len(accountHistoryItem.CreditBureauDefaultOriginalDefaultAccountTypeDescription) <> 0 Then
              .AddCaptionText("Account Type:", accountHistoryItem.CreditBureauDefaultLastDefaultAccountTypeDescription)
            End If
            If Len(accountHistoryItem.CreditBureauDefaultLastCreditProvider) <> 0 OrElse Len(accountHistoryItem.CreditBureauDefaultOriginalCreditProvider) <> 0 Then
              .AddCaptionText("Credit Provider:", accountHistoryItem.CreditBureauDefaultLastCreditProvider)
            End If
            .AddCaptionDate("Uploaded:", accountHistoryItem.CreditBureauDefaultLastDateExported)
          End If
        End With

        ' Warnings
        .TextAfter = Warnings

        ' Actions
        If includeActions Then
          With .Actions
          End With
        End If
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Summary", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account History Item Credit Bureau Default Update History Summary (Version 1.03, Last updated 17/08/2016).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="accountHistoryItem">
  '''  The Account History Item.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account History page and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Summary.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_HistoryItem_CreditBureauDefaultUploadHistory(callerScriptInfo As ISScriptExecutionInfo,
                                                                                   accountHistoryItem As finAccountHistoryItem,
                                                                          Optional includeActions As Boolean = True,
                                                                          Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim Response As ISCreditDefaultResponse
    Dim ServiceLog As ISServiceLog
    Dim ServiceLogs As ISServiceLogs
    Dim ShowStatus As Boolean
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Summary table
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .AutoStripe = True

      If accountHistoryItem IsNot Nothing AndAlso accountHistoryItem.HistoryType = isefinAccountHistoryType.CreditBureauDefault AndAlso accountHistoryItem.CreditBureauDefaultSupportsUploadingDefaults Then
        ' Previous Defaults
        If finBL.CreditBureau.GetCreditDefaultServiceLogs(accountHistoryItem.Pk, ServiceLogs) Then
          If ServiceLogs.Count = 0 Then
            Warnings &= "{{info|This Credit Bureau Default record has not yet been uploaded.}}"
          Else
            ' Determine Columns to include
            ShowStatus = False
            For Each ServiceLog In ServiceLogs
              If ServiceLog.RequestStatus = iseAuditLogStatus.Pending Then ShowStatus = True
            Next

            ' Columns
            With .Columns
              .AddDate("Uploaded")
              .AddText("User")
              .AddCurrency("Amount")
              .AddText("Status")
              .AddText("Account Type")
              If ShowStatus Then .AddText(" ")
            End With

            For Each ServiceLog In ServiceLogs
              Response = DirectCast(ServiceLog.ExResponse, ISCreditBureau4.ISCreditDefaultResponse)

              With .Rows.Add().Cells
                .AddDateTime(ServiceLog.CreatedDate)
                .AddText(finBL.Users.ItemByPkSafe(ServiceLog.CreatedUserPk).UserIdResolved)
                .AddCurrency(Response.CurrentDefaultBalance)
                .AddText(Response.DefaultStatusDescription)
                .AddText(Response.AccountTypeDescription)
                If ShowStatus Then
                  If ServiceLog.RequestStatus = iseAuditLogStatus.Pending Then
                    With .AddText("{{icon|Alert}}")
                      .Tooltip = "'Pending' request. No response was recorded from the Credit Bureau."
                    End With
                  Else
                    .AddText("")
                  End If
                End If
              End With
            Next
          End If
        Else
          ' Error
          Warnings &= "{{warning|" & finBL.Error.Message(True) & "}}"
        End If

        ' Warnings
        .TextAfter = Warnings

        ' Actions
        If includeActions Then
          With .Actions
          End With
        End If
      End If
    End With

    ' Add Summary Tables
    If SummaryTableMain.HasData Then SummaryTables.Add("Summary", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account History Rating HTML Diagram (Version 1.00, Last updated 25/08/2015).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="accountHistoryRatingDiagram">
  '''  The Account History Ratings diagram collection.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  A String value containing HTML.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Account Key Details page.
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_HistoryRatingDiagram(callerScriptInfo As ISScriptExecutionInfo,
                                                           accountHistoryRatingDiagram As finAccountHistoryRatingDiagram,
                                                  Optional includeActions As Boolean = True,
                                                  Optional otherParameters As ISKeyValueList = Nothing) As String

    Dim BackgroundColour As String
    Dim Colour As String
    Dim CellWidth As Double
    Dim i As Integer
    Dim sb As StringBuilder

    ' Initialise
    sb = New StringBuilder()

    If accountHistoryRatingDiagram IsNot Nothing AndAlso accountHistoryRatingDiagram.Count <> 0 Then
      ' Initialise
      If accountHistoryRatingDiagram.Count <> 0 Then
        CellWidth = 100 / accountHistoryRatingDiagram.Count
      End If

      ' Initialise HTML
      If Len(accountHistoryRatingDiagram.Heading) <> 0 Then
        sb.Append("<h2>" & finBL.HtmlEncode(accountHistoryRatingDiagram.Heading, True, True) & "</h2>")
      End If
      sb.Append("<div style='box-sizing:border-box; font-size:0.9em'>")
      sb.Append("<table style='width:100%;border-collapse:collapse;")
      If Len(accountHistoryRatingDiagram.MaxWidth) <> 0 Then
        sb.AppendFormat("max-width:{0};", accountHistoryRatingDiagram.MaxWidth)
      End If
      sb.Append("'>")

      ' Caption Row
      If accountHistoryRatingDiagram.HasCaptions() Then
        sb.Append("<thead>")
        sb.Append("<tr>")
        For i = 0 To accountHistoryRatingDiagram.Count - 1
          sb.AppendFormat("<td style='width:{0}%;color:#808080;vertical-align:bottom;text-align:center'>{1}</td>", CellWidth, finBL.HtmlEncode(accountHistoryRatingDiagram(i).Caption))
        Next
        sb.Append("</tr>")
        sb.Append("</thead>")
      End If

      ' Values Row
      sb.Append("<tbody>")
      sb.Append("<tr>")
      For i = 0 To accountHistoryRatingDiagram.Count - 1
        With accountHistoryRatingDiagram(i)
          ' Get Cell Formatting
          If Len(.Value) = 0 Then
            BackgroundColour = accountHistoryRatingDiagram.Colours.GetString("-")
          Else
            BackgroundColour = accountHistoryRatingDiagram.Colours.GetString(.Value)
          End If
          If Len(BackgroundColour) = 0 Then
            BackgroundColour = "#FF00FF" ' Magenta
          End If
          With finBL.Runtime.ColourUtilities
            If .ColourIsDarkHtml(BackgroundColour) Then
              Colour = "white"
            Else
              Colour = "black"
            End If
          End With

          ' Cell Style
          sb.Append("<td style='border:2px solid white;text-align:center;font-weight:bold;padding:4px;")
          sb.AppendFormat("width:{0}%;", CellWidth)
          sb.AppendFormat("color:{0};", Colour)
          sb.AppendFormat("background-color:{0};", BackgroundColour)
          sb.Append("'>")

          sb.Append(finBL.HtmlEncode(.Value))
          sb.Append("</td>")
        End With
      Next
      sb.Append("</tr>")
      sb.Append("</tbody>")

      ' Finalise HTML
      sb.Append("</table>")
      sb.Append("</div>")
    End If

    Return sb.ToString()

  End Function

  ''' <summary>
  '''  Account History Rating HTML Diagrams (Version 1.00, Last updated 22/09/2016).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="account">
  '''  The Account to display History Rating diagrams for.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  A String value containing HTML.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Account Key Details page.
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_HistoryRatingDiagrams(callerScriptInfo As ISScriptExecutionInfo,
                                                            account As finAccount,
                                                            includeHistoryRating1 As Boolean,
                                                            historyRating1Heading As String,
                                                            includeHistoryRating2 As Boolean,
                                                            historyRating2Heading As String,
                                                            includeHistoryRating3 As Boolean,
                                                            historyRating3Heading As String,
                                                            maxWidth As String,
                                                   Optional includeActions As Boolean = True,
                                                   Optional otherParameters As ISKeyValueList = Nothing) As String

    Dim AccountHistoryRatingDiagram As finAccountHistoryRatingDiagram
    Dim sb As StringBuilder

    ' Initialise
    sb = New StringBuilder()

    If includeHistoryRating1 Then
      AccountHistoryRatingDiagram = account.GetHistoryRatingDiagram()
      With AccountHistoryRatingDiagram
        .Heading = historyRating1Heading
        .MaxWidth = maxWidth
      End With

      sb.AppendLine(finBL.SummaryPageStandardBlocks.Account_HistoryRatingDiagram(ScriptInfo, AccountHistoryRatingDiagram))
    End If

    If includeHistoryRating2 Then
      AccountHistoryRatingDiagram = account.GetHistoryRatingDiagram2()
      With AccountHistoryRatingDiagram
        .Heading = historyRating2Heading
        .MaxWidth = maxWidth
      End With

      sb.AppendLine(finBL.SummaryPageStandardBlocks.Account_HistoryRatingDiagram(ScriptInfo, AccountHistoryRatingDiagram))
    End If

    If includeHistoryRating3 Then
      AccountHistoryRatingDiagram = account.GetHistoryRatingDiagram3()
      With AccountHistoryRatingDiagram
        .Heading = historyRating3Heading
        .MaxWidth = maxWidth
      End With

      sb.AppendLine(finBL.SummaryPageStandardBlocks.Account_HistoryRatingDiagram(ScriptInfo, AccountHistoryRatingDiagram))
    End If

    Return sb.ToString()

  End Function

  ''' <summary>
  '''  Account Incomplete Workflows Summary.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="account">
  '''  The Account to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="maxDisplayRows">
  '''  The Maximum number of Rows to Display in the table before a 'Show Hidden' link is displayed.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Status and Key Details pages and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_IncompleteWorkflows(callerScriptInfo As ISScriptExecutionInfo,
                                                          account As finAccount,
                                                 Optional maxDisplayRows As Integer = 20,
                                                 Optional includeActions As Boolean = True,
                                                 Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' Account_IncompleteWorkflows
    '
    ' Version: 1.03 (23/08/2023)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.02  19/04/2016  ISS
    '    1.03  23/08/2023  ISS      J031278   Remove "Locate in Task Manager" link
    ' #################################################################

    Dim AccountWorkflow As finAccountWorkflow
    Dim DateAsAt As Date
    Dim ShowLocateInTaskManager As Boolean
    Dim StatusIcon As String
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim TooltipText As String
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Date As At
    DateAsAt = finBL.TimeZoneFunctions.GetCurrentDatabaseDate()

    ' Determine Columns to include
    Select Case callerScriptInfo.Target
      Case iseSummaryPageTarget.Form
        If finBL.Settings.UseTaskManager1Resolved Then
          ShowLocateInTaskManager = (account.Workflows.CountInTaskManager <> 0) AndAlso Not finBL.IsRunningFromWeb() AndAlso finBL.CurrentUser.Permissions.Allow("Menu.Process.TaskManager")
        End If
    End Select

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .Caption = ""
      .AutoStripe = True
      .MaxDisplayRows = maxDisplayRows
      .ShowHiddenRowsCaption = "Show More Workflows"

      If account.Workflows.CountNotClosed = 0 Then
        ' No Incomplete Workflows (should really have been checked before calling this method to avoid loading the Workflows collection unnecessarily)
        .TextAfter = "{{info|No current Workflows.}}"
      Else
        ' Columns
        With .Columns
          .AddText(" ", 1, iseSummaryTableCellTextAlign.Center) ' Flag Colour
          .AddText(" ", 1, iseSummaryTableCellTextAlign.Center) ' Status Icon
          .AddDate("Opened")
          .AddCode("Workflow", finBL.WorkflowFunctions.GetLongestCode())
          If ShowLocateInTaskManager Then
            With .AddText(" ", 1, iseSummaryTableCellTextAlign.Center) ' Locate in Task Manager Icon
              .HideRule = iseSummaryTableColumnHideRule.DocumentWidthLessThan800px
            End With
          End If
          .AddText("Description").HideRule = iseSummaryTableColumnHideRule.DocumentWidthLessThan640px
          .AddText("Current Item").HideRule = iseSummaryTableColumnHideRule.DocumentWidthLessThan800px
          .AddCode("Allocated", finBL.Users.GetLongestCode())
        End With

        With .Rows
          For Each AccountWorkflow In account.Workflows
            If AccountWorkflow.Status <> isefinWorkflowStatus.Closed Then
              ' Status Icon (not the real Status but something to bring this item to the User's attention)
              StatusIcon = "Blank"
              TooltipText = ""
              Select Case AccountWorkflow.Status
                Case isefinWorkflowStatus.OnHold
                  StatusIcon = "Hold"
                  TooltipText = "On Hold"
                Case isefinWorkflowStatus.Pending
                  StatusIcon = "WorkflowPending"
                  TooltipText = "Pending"
                Case isefinWorkflowStatus.Open
                  If AccountWorkflow.RecallImmediate OrElse (AccountWorkflow.RecallDate <> Nothing AndAlso AccountWorkflow.RecallDate < DateAsAt) Then
                    StatusIcon = "Review"
                    If AccountWorkflow.RecallImmediate Then
                      TooltipText = "Immediate Recall"
                    Else
                      TooltipText = String.Format("Recall due to Recall Date of {0} reached", finBL.FormatDate(AccountWorkflow.RecallDate, True))
                    End If
                  ElseIf Not AccountWorkflow.RecallImmediate AndAlso AccountWorkflow.RecallDate <> Nothing AndAlso AccountWorkflow.RecallDate > DateAsAt Then
                    StatusIcon = "Hourglass"
                    TooltipText = "Waiting for Recall Date to be reached"
                  End If
              End Select

              ' Add Row
              With .Add().Cells
                If Len(AccountWorkflow.FlagColour) = 0 Then
                  .AddText("")
                Else
                  .AddText("{{flag|" & AccountWorkflow.FlagColour & "}}").Tooltip = AccountWorkflow.FlagColour
                End If
                If Len(StatusIcon) = 0 Then
                  .AddText("")
                Else
                  .AddText("{{icon|" & StatusIcon & "}}").Tooltip = TooltipText
                End If
                .AddDate(AccountWorkflow.OpenedDate)
                With .AddText(AccountWorkflow.WorkflowId)
                  .HyperlinkSetFormShow("Workflows", AccountWorkflow.WorkflowId)
                End With
                If ShowLocateInTaskManager Then
                  If AccountWorkflow.IsInTaskManager() Then
                    With .AddText("{{icon|Task_Locate|Locate in Task Manager}}")
                      .HyperlinkSetFormAction("LocateWorkflow", "workflowId=" & finBL.UrlEncode(AccountWorkflow.WorkflowId), "TaskManager", True, True)
                    End With
                  Else
                    .AddText("")
                  End If
                End If
                .AddText(AccountWorkflow.Description)
                If AccountWorkflow.Workflow.GetCurrentItem() Is Nothing Then
                  .AddText("")
                Else
                  .AddText(AccountWorkflow.Workflow.GetCurrentItem().Description)
                End If
                .AddText(AccountWorkflow.AllocatedUserId)
              End With
            End If
          Next
        End With

        ' Warnings
        .TextAfter = Warnings

        ' Actions
        If includeActions Then
          With .Actions
          End With
        End If
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Interest Summary.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="account">
  '''  The Account to summarise.
  ''' </param>
  ''' <param name="accountCalc">
  '''  The Account Calculation or Nothing to use the current Account Calculation.
  ''' </param>
  ''' <param name="includeInterest">
  '''  Indicates whether to include the Main (Interest) Summary Table.
  ''' </param>
  ''' <param name="includeOtherInterest">
  '''  Indicates whether to include the Other (Other Interest) Summary Table.
  ''' </param>
  ''' <param name="includeDefaultInterest">
  '''  Indicates whether to include the Default (Default Interest) Summary Table.
  ''' </param>
  ''' <param name="includeInterestRateChangeInstructions">
  '''  Indicates whether to include the Instructions (Interest Rate Change Instructions) Summary Table.
  ''' </param>
  ''' <param name="dateAsAt">
  '''  Optional Date to display information for. If not specified the current date is used.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Account Financial page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main Interest details.</description></item>
  '''    <item><code>Other</code><description>Other Interest details.</description></item>
  '''    <item><code>Default</code><description>Default Interest details.</description></item>
  '''    <item><code>Instructions</code><description>Interest Instruction details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_Interest2(callerScriptInfo As ISScriptExecutionInfo,
                                               account As finAccount,
                                      Optional accountCalc As finAccountCalc = Nothing,
                                      Optional includeInterest As Boolean = True,
                                      Optional includeOtherInterest As Boolean = True,
                                      Optional includeDefaultInterest As Boolean = True,
                                      Optional includeInterestRateChangeInstructions As Boolean = True,
                                      Optional dateAsAt As Date = Nothing,
                                      Optional includeActions As Boolean = True,
                                      Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' Account_Interest2
    '
    ' Version: 1.17 (24/07/2024)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.07  06/07/2021  ISS                  
    '    1.08  24/09/2021  ISS      J027436   Added "Credit Limit" Other Interest basis
    '    1.09  27/10/2021  ISS      J027618   Added "Credit Limit 2/3" and "Utilisation 2/3" Other Interest basis
    '    1.10  05/09/2022  ISS      J029043   Added "Account Utilisation 1/2/3" Other Interest type
    '    1.11  12/10/2022  ISS      J029833   Closed Account showing original formatted Interest details
    '    1.12  10/01/2024  ISS      J032714   Updated Permission Keys
    '    1.13  10/01/2024  ISS      J032719   Updated Permission Keys
    '    1.14  10/01/2024  ISS      J032722   Updated Permission Keys
    '    1.15  10/01/2024  ISS      J032723   Updated Permission Keys
    '    1.16  24/01/2024  ISS      J032783   Updated Permission Keys
    '    1.17  24/07/2024  ISS      J032515   Updated to use Other Interest description
    ' #################################################################

    Dim AccountRegulations_NZ_HighCostConsumerCreditContract As finAccountRegulations_NZ_HighCostConsumerCreditContract
    Dim AccountHistoryItem As finAccountHistoryItem
    Dim Count As Integer
    Dim DateMaturityOrFinal As Date
    Dim dateTemp As Date
    Dim DefaultInterestFutureChange As Boolean
    Dim DefaultInterestRate As Double
    Dim DefaultInterestRateBasis As isefinDefaultInterestRateBasis
    Dim DefaultInterestRateCharge As Double
    Dim HighestInterestRate As Double
    Dim InterestCycle As String
    Dim InterestCycleFutureChange As Boolean
    Dim InterestCycleNextChangeDate As Date
    Dim InterestCycleNextDate As Date
    Dim InterestChargedTo As Date
    Dim InterestFutureChange As Boolean
    Dim InterestHeading As String
    Dim InterestNextChangeDate As Date
    Dim InterestRate As Double
    Dim InterestRatePremium As Double
    Dim InterestRateTableId As String
    Dim InterestRateTableIsTiered As Boolean
    Dim InterestRateTablePk As Integer
    Dim InterestType As isefinAccountInterestType
    Dim OtherInterestFutureChange As Boolean
    Dim OtherInterestRate As Double
    Dim OtherInterestType As isefinAccountOtherInterestType
    Dim ShowOriginalFormat As Boolean
    Dim strTemp As String
    Dim SummaryTableDefault As ISSummaryTable
    Dim SummaryTableInstructions As ISSummaryTable
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTableOther As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableDefault = finBL.CreateSummaryTable()
    SummaryTableInstructions = finBL.CreateSummaryTable()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTableOther = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Calculation
    If accountCalc Is Nothing Then
      accountCalc = account.Calculation
    End If

    ' Get Date As At
    dateAsAt = finBL.Runtime.Validation.ValidateDate(dateAsAt)
    If dateAsAt = Nothing Then
      If accountCalc.IsCalcVersionClosing Then
        dateAsAt = account.DateClosed
      Else
        dateAsAt = finBL.TimeZoneFunctions.GetCurrentDatabaseDate()
      End If
    End If

    ' Interest
    If includeInterest Then
      ' Get Values
      Select Case account.AccountClass
        Case isefinAccountClass.Deposit, isefinAccountClass.LoanFR, isefinAccountClass.LoanRC
          ShowOriginalFormat = accountCalc.IsQuote OrElse accountCalc.IsCalcVersionOpening
        Case Else
          ShowOriginalFormat = True
      End Select

      ' Warnings
      Warnings = ""
      If accountCalc.StartupInterestToDateResolved > accountCalc.DateMaturity AndAlso accountCalc.DateMaturity <> Nothing Then
        Warnings &= "{{Warning|Startup Interest period extends past Maturity date.}}"
      End If

      With SummaryTableMain
        ' Initialise
        .TableClass = iseSummaryTableClass.Information
        .Caption = "Interest"
        .Columns.AddText(13)
        .Columns.AddText()

        With .Rows
          If ShowOriginalFormat Then
            ' ORIGINAL FORMAT - as per New Account wizard

            ' Cycle and First Date
            Select Case account.AccountClass
              Case isefinAccountClass.Deposit
                .AddCaptionText("Credited:", accountCalc.InterestCycleDescription)
                If accountCalc.InterestCycleDateFirst <> Nothing Then .AddCaptionDate("First Date:", accountCalc.InterestCycleDateFirst)
              Case isefinAccountClass.LoanRC
                .AddCaptionText("Charged:", accountCalc.InterestCycleDescription)
                If accountCalc.InterestCycleDateFirst <> Nothing Then .AddCaptionDate("First Date:", accountCalc.InterestCycleDateFirst)
              Case Else
                .AddCaptionText("Charged:", accountCalc.InterestCycleDescription)
            End Select

            ' Last Date
            If accountCalc.InterestChargedTo <> Nothing Then
              .AddCaptionDate("Last Date:", accountCalc.InterestChargedTo)
            End If

            ' Payment Type
            Select Case account.AccountClass
              Case isefinAccountClass.Deposit
                .AddCaptionText("Pay Type:", accountCalc.InterestPaymentTypeText)
            End Select

            ' Startup
            Select Case accountCalc.StartupInterestType
              Case isefinAccountInterestType.FixedRate
                If accountCalc.OptionInterestFlatRate Then
                  strTemp = String.Format("**Fixed {0}** --(True Rate **{1}**)--", finBL.FormatPercentage(accountCalc.StartupInterestRateFlat / 100, 4), finBL.FormatPercentage(accountCalc.StartupInterestRate / 100, 4))
                Else
                  strTemp = String.Format("**Fixed {0}**", finBL.FormatPercentage(accountCalc.StartupInterestRate / 100, 4))
                End If
                If accountCalc.StartupInterestPeriod = "To Date" Then
                  .AddCaptionWiki("Startup:", strTemp & String.Format(" to **{0}**", finBL.FormatDateLong(accountCalc.StartupInterestToDateResolved)))
                Else
                  .AddCaptionWiki("Startup:", strTemp & String.Format("<br>for **{0}** --(to **{1}**)--", accountCalc.StartupInterestPeriodDescription, finBL.FormatDateLong(accountCalc.StartupInterestToDateResolved)))
                End If

              Case isefinAccountInterestType.FloatingRate
                If accountCalc.StartupInterestRatePremium = 0 Then
                  strTemp = String.Format("**Floating {0}**", finBL.FormatPercentage(accountCalc.StartupInterestRate / 100, 4))
                ElseIf accountCalc.StartupInterestRatePremium < 0 Then
                  strTemp = String.Format("**Floating {0}** --(base less **{1}**)--", finBL.FormatPercentage(accountCalc.StartupInterestRate / 100, 4), finBL.FormatPercentage(-accountCalc.StartupInterestRatePremium / 100, 4))
                Else
                  strTemp = String.Format("**Floating {0}** --(base plus **{1}**)--", finBL.FormatPercentage(accountCalc.StartupInterestRate / 100, 4), finBL.FormatPercentage(accountCalc.StartupInterestRatePremium / 100, 4))
                End If
                If accountCalc.StartupInterestPeriod = "To Date" Then
                  .AddCaptionWiki("Startup:", String.Format("{0} to **{1}**", strTemp, finBL.FormatDateLong(accountCalc.StartupInterestToDateResolved)))
                Else
                  .AddCaptionWiki("Startup:", String.Format("{0}<br>for **{1}** --(to **{2}**)--", strTemp, accountCalc.StartupInterestPeriodDescription, finBL.FormatDateLong(accountCalc.StartupInterestToDateResolved)))
                End If

              Case isefinAccountInterestType.InterestFree
                If accountCalc.StartupInterestPeriod = "To Date" Then
                  .AddCaptionWiki("Startup:", String.Format("**Interest Free** to **{0}**", finBL.FormatDateLong(accountCalc.StartupInterestToDateResolved)))
                Else
                  .AddCaptionWiki("Startup:", String.Format("**Interest Free**<br>for **{0}** --(to **{1}**)--", accountCalc.StartupInterestPeriodDescription, finBL.FormatDateLong(accountCalc.StartupInterestToDateResolved)))
                End If

              Case isefinAccountInterestType.RateTable
                If accountCalc.IsOpeningCalculation AndAlso accountCalc.OptionInterestFixRateTable Then
                  strTemp = String.Format("**Fixed {0}**", finBL.FormatPercentage(accountCalc.StartupInterestRate / 100, 4))
                Else
                  InterestRateTableId = accountCalc.StartupInterestRateTableIdResolved

                  If Len(InterestRateTableId) = 0 Then
                    strTemp = "Rate Table **invalid**"
                  Else
                    If accountCalc.OptionInterestFixRateTable Then
                      ' Will be converted to Fixed Rate when opened
                      strTemp = String.Format("**{0}**", finBL.FormatPercentage(accountCalc.StartupInterestRate / 100, 4))
                      If accountCalc.StartupInterestRatePremium = 0 Then
                        strTemp &= String.Format(" --(**{0}**)--", InterestRateTableId)
                      ElseIf accountCalc.StartupInterestRatePremium < 0 Then
                        strTemp &= String.Format(" --(**{0}** less **{1}**)--", InterestRateTableId, finBL.FormatPercentage(-accountCalc.StartupInterestRatePremium / 100, 4))
                      Else
                        strTemp &= String.Format(" --(**{0}** plus **{1}**)--", InterestRateTableId, finBL.FormatPercentage(accountCalc.StartupInterestRatePremium / 100, 4))
                      End If
                    Else
                      ' Get Interest Rate
                      InterestRate = finBL.RateTables(InterestRateTableId).GetRate(accountCalc.OpeningDate, 0, "", "", InterestRateTableIsTiered) + accountCalc.StartupInterestRatePremium

                      If accountCalc.StartupInterestRatePremium = 0 Then
                        strTemp = String.Format("**{0}**", InterestRateTableId)
                      ElseIf accountCalc.StartupInterestRatePremium < 0 Then
                        strTemp = String.Format("**{0}** less **{1}**", InterestRateTableId, finBL.FormatPercentage(-accountCalc.StartupInterestRatePremium / 100, 4))
                      Else
                        strTemp = String.Format("**{0}** plus **{1}**", InterestRateTableId, finBL.FormatPercentage(accountCalc.StartupInterestRatePremium / 100, 4))
                      End If
                      If Not InterestRateTableIsTiered Then
                        strTemp &= String.Format(" --(net **{0}**)--", finBL.FormatPercentage(InterestRate / 100, 4))
                      End If
                    End If
                  End If
                End If
                If Len(accountCalc.StartupInterestPeriod) = 0 Then
                  .AddCaptionWiki("Startup:", "!!**Period not defined**!!")
                ElseIf accountCalc.StartupInterestPeriod = "To Date" Then
                  .AddCaptionWiki("Startup:", String.Format("{0} to **{1}**", strTemp, finBL.FormatDateLong(accountCalc.StartupInterestToDateResolved)))
                Else
                  .AddCaptionWiki("Startup:", String.Format("{0}<br>for **{1}** --(to **{2}**)--", strTemp, accountCalc.StartupInterestPeriodDescription, finBL.FormatDateLong(accountCalc.StartupInterestToDateResolved)))
                End If
            End Select

            ' Ongoing
            Select Case accountCalc.InterestType
              Case isefinAccountInterestType.FixedRate
                If accountCalc.OptionInterestFlatRate Then
                  .AddCaptionWiki("Rate:", String.Format("**Fixed {0}** --(True Rate **{1}**)--", finBL.FormatPercentage(accountCalc.InterestRateFlat / 100, 4), finBL.FormatPercentage(accountCalc.InterestRate / 100, 4)))
                Else
                  .AddCaptionText("Rate:", String.Format("Fixed {0}", finBL.FormatPercentage(accountCalc.InterestRate / 100, 4)))
                End If

              Case isefinAccountInterestType.FloatingRate
                If accountCalc.InterestRatePremium = 0 Then
                  .AddCaptionText("Rate:", String.Format("Floating {0}", finBL.FormatPercentage(accountCalc.InterestRate / 100, 4)))
                ElseIf accountCalc.InterestRatePremium < 0 Then
                  .AddCaptionWiki("Rate:", String.Format("**Floating {0}** --(base less **{1}**)--", finBL.FormatPercentage(accountCalc.InterestRate / 100, 4), finBL.FormatPercentage(-accountCalc.InterestRatePremium / 100, 4)))
                Else
                  .AddCaptionWiki("Rate:", String.Format("**Floating {0}** --(base plus **{1}**)--", finBL.FormatPercentage(accountCalc.InterestRate / 100, 4), finBL.FormatPercentage(accountCalc.InterestRatePremium / 100, 4)))
                End If

              Case isefinAccountInterestType.InterestFree
                .AddCaptionText("Rate:", "Interest Free")

              Case isefinAccountInterestType.RateTable
                If accountCalc.IsOpeningCalculation AndAlso accountCalc.OptionInterestFixRateTable Then
                  .AddCaptionText("Rate:", String.Format("Fixed {0}", finBL.FormatPercentage(accountCalc.InterestRate / 100, 4)))
                Else
                  InterestRateTableId = accountCalc.InterestRateTableIdResolved

                  If Len(InterestRateTableId) = 0 Then
                    strTemp = "Rate Table **invalid**"
                  Else
                    If accountCalc.OptionInterestFixRateTable Then
                      ' Will be converted to Fixed Rate when opened
                      strTemp = String.Format("**{0}**", finBL.FormatPercentage(accountCalc.InterestRate / 100, 4))
                      If accountCalc.InterestRatePremium = 0 Then
                        strTemp &= String.Format(" --(**{0}**)--", InterestRateTableId)
                      ElseIf accountCalc.InterestRatePremium < 0 Then
                        strTemp &= String.Format(" --(**{0}** less **{1}**)--", InterestRateTableId, finBL.FormatPercentage(-accountCalc.InterestRatePremium / 100, 4))
                      Else
                        strTemp &= String.Format(" --(**{0}** plus **{1}**)--", InterestRateTableId, finBL.FormatPercentage(accountCalc.InterestRatePremium / 100, 4))
                      End If
                      If accountCalc.StartupInterestType <> isefinAccountInterestType.NotApplicable Then
                        strTemp &= String.Format(" from **{0}**", finBL.FormatDateLong(accountCalc.StartupInterestToDateResolved.AddDays(1)))
                      End If
                    Else
                      ' Get Interest Rate
                      If accountCalc.StartupInterestType = isefinAccountInterestType.NotApplicable Then
                        dateTemp = accountCalc.OpeningDate
                      Else
                        dateTemp = accountCalc.StartupInterestToDateResolved.AddDays(1)
                      End If
                      InterestRate = finBL.RateTables(InterestRateTableId).GetRate(dateTemp, 0, "", "", InterestRateTableIsTiered) + accountCalc.InterestRatePremium

                      If accountCalc.InterestRatePremium = 0 Then
                        strTemp = String.Format("**{0}**", InterestRateTableId)
                      ElseIf accountCalc.InterestRatePremium < 0 Then
                        strTemp = String.Format("**{0}** less **{1}**", InterestRateTableId, finBL.FormatPercentage(-accountCalc.InterestRatePremium / 100, 4))
                      Else
                        strTemp = String.Format("**{0}** plus **{1}**", InterestRateTableId, finBL.FormatPercentage(accountCalc.InterestRatePremium / 100, 4))
                      End If
                      If Not InterestRateTableIsTiered Then
                        If accountCalc.StartupInterestType = isefinAccountInterestType.NotApplicable Then
                          strTemp &= String.Format(" --(net **{0}**)--", finBL.FormatPercentage(InterestRate / 100, 4))
                        Else
                          strTemp &= String.Format(" --(net **{0}** on **{1}**)--", finBL.FormatPercentage(InterestRate / 100, 4), finBL.FormatDateLong(dateTemp))
                        End If
                      End If
                    End If
                  End If

                  .AddCaptionWiki("Rate:", strTemp)
                End If
            End Select

            ' FUDGE: Interest Rate change from finPOWER 5 Conversion - Opening Rate was overridden
            If account.AccountClass = isefinAccountClass.LoanFT AndAlso accountCalc.IsCalcVersionOpening Then
              For Each AccountHistoryItem In account.HistoryItems
                If AccountHistoryItem.HistoryType = isefinAccountHistoryType.InterestRateChange AndAlso AccountHistoryItem.Status = isefinAccountHistoryStatus.Complete AndAlso AccountHistoryItem.Reference = "Conversion" Then
                  Warnings &= "{{Warning|Original Interest Rate has been overridden in the Conversion process.}}"
                  Exit For
                End If
              Next
            End If
          Else
            ' CURRENT FORMAT - show future Interest changes

            ' Interest Cycle
            account.GetInterestCycle(dateAsAt, InterestCycle, InterestChargedTo, "", InterestCycleFutureChange, InterestCycleNextChangeDate, InterestCycleNextDate)

            ' Cycle
            Select Case account.AccountClass
              Case isefinAccountClass.Deposit
                .AddCaptionText("Credited:", finBL.Utilities.DateCycleGetDescription(True, InterestCycle))
                If accountCalc.InterestChargedTo <> Nothing Then
                  .AddCaptionDate("Last Date:", accountCalc.InterestChargedTo)
                End If
                Select Case InterestCycle
                  Case "At Maturity"
                  Case Else
                    If InterestCycleNextDate <> Nothing AndAlso InterestCycleNextDate > InterestChargedTo Then
                      .AddCaptionDate("Next Date:", InterestCycleNextDate)
                    End If
                End Select
              Case isefinAccountClass.LoanRC
                .AddCaptionText("Charged:", finBL.Utilities.DateCycleGetDescription(True, InterestCycle))
                If accountCalc.InterestChargedTo <> Nothing Then
                  .AddCaptionDate("Last Date:", accountCalc.InterestChargedTo)
                End If
                If InterestCycleNextDate <> Nothing AndAlso InterestCycleNextDate > InterestChargedTo Then
                  .AddCaptionDate("Next Date:", InterestCycleNextDate)
                End If
              Case Else
                .AddCaptionText("Charged:", finBL.Utilities.DateCycleGetDescription(True, InterestCycle))
                If accountCalc.InterestChargedTo <> Nothing Then
                  .AddCaptionDate("Last Date:", accountCalc.InterestChargedTo)
                End If
            End Select

            If InterestCycleFutureChange Then
              Warnings &= "{{Warning|Future Interest Cycle changes exist.}}"
            End If

            ' Pay Type
            Select Case account.AccountClass
              Case isefinAccountClass.Deposit
                Select Case accountCalc.InterestPaymentType
                  Case isefinAccountInterestPaymentType.Transfer
                    .AddCaptionWiki("Pay Type:", String.Format("**Transfer** to **[[app://formshow?form=Accounts&id={0}|{1}]]**", finBL.UrlEncode(account.InterestTransferToAccountId), account.InterestTransferToAccountId))
                  Case Else
                    .AddCaptionText("Pay Type:", accountCalc.InterestPaymentTypeText)
                End Select
            End Select

            ' Loop through all Rates into the future
            Count = 0
            InterestNextChangeDate = dateAsAt
            InterestHeading = "Current:"
            Do
              account.GetInterestRate(InterestNextChangeDate, InterestType, InterestRate, InterestRateTablePk, InterestRatePremium, "", InterestFutureChange, InterestNextChangeDate, InterestRateTableIsTiered)

              Select Case InterestType
                Case isefinAccountInterestType.FixedRate
                  .AddCaptionText(InterestHeading, String.Format("Fixed {0}", finBL.FormatPercentage(InterestRate / 100, 4)))

                Case isefinAccountInterestType.FloatingRate
                  If InterestRatePremium = 0 Then
                    .AddCaptionText(InterestHeading, String.Format("Floating {0}", finBL.FormatPercentage(InterestRate / 100, 4)))
                  ElseIf InterestRatePremium < 0 Then
                    .AddCaptionWiki(InterestHeading, String.Format("**Floating {0}** --(base less **{1}**)--", finBL.FormatPercentage(InterestRate / 100, 4), finBL.FormatPercentage(-InterestRatePremium / 100, 4)))
                  Else
                    .AddCaptionWiki(InterestHeading, String.Format("**Floating {0}** --(base plus **{1}**)--", finBL.FormatPercentage(InterestRate / 100, 4), finBL.FormatPercentage(InterestRatePremium / 100, 4)))
                  End If

                Case isefinAccountInterestType.InterestFree
                  .AddCaptionText(InterestHeading, "Interest Free")

                Case isefinAccountInterestType.RateTable
                  If InterestRateTablePk = 0 Then InterestRateTablePk = account.AccountType.StandardRateTablePk

                  If InterestRateTablePk = 0 Then
                    strTemp = "Rate Table **invalid**"
                  Else
                    InterestRateTableId = finBL.RateTables.ItemByPk(InterestRateTablePk).RateTableId

                    If InterestRatePremium = 0 Then
                      strTemp = String.Format("**{0}**", InterestRateTableId)
                    ElseIf InterestRatePremium < 0 Then
                      strTemp = String.Format("**{0}** less **{1}**", InterestRateTableId, finBL.FormatPercentage(-InterestRatePremium / 100, 4))
                    Else
                      strTemp = String.Format("**{0}** plus **{1}**", InterestRateTableId, finBL.FormatPercentage(InterestRatePremium / 100, 4))
                    End If
                    If Not InterestRateTableIsTiered Then
                      strTemp &= String.Format(" --(net **{0}**)--", finBL.FormatPercentage(InterestRate / 100, 4))
                    End If
                  End If

                  .AddCaptionWiki(InterestHeading, strTemp)
              End Select

              ' Quit
              Count += 1
              If Count > 3 OrElse Not InterestFutureChange Then Exit Do

              ' Next heading
              InterestHeading = finBL.FormatDate(InterestNextChangeDate, True) & ":"
            Loop

            ' Warnings
            If InterestFutureChange Then
              Warnings &= "{{Warning|Future Interest changes exist.}}"
            End If
            If account.HistoryItems.CountPendingFloatingInterestRateChanges <> 0 Then
              Warnings &= "{{Info|Pending Floating Interest Rate changes exist.}}"
            End If
          End If
        End With

        ' Warnings
        If account.AccountType IsNot Nothing Then
          If accountCalc.OptionInterestAccruedMethod <> account.AccountType.OptionInterestAccruedMethod Then
            Warnings &= "{{Info|" & String.Format("Interest accrual method is **{0}**.", accountCalc.OptionInterestAccruedMethodText) & "}}"
          End If
          If accountCalc.OptionInterestOnInterest <> account.AccountType.OptionInterestOnInterest Then
            If accountCalc.OptionInterestOnInterest Then
              Warnings &= "{{Info|Interest is charged on Interest.}}"
            Else
              Warnings &= "{{Info|Interest is NOT charged on Interest.}}"
            End If
          End If
          If finBL.CountryCode = "NZ" AndAlso accountCalc.AccountClass = isefinAccountClass.LoanFT AndAlso accountCalc.AccountType.CreditType = isefinAccountCreditType.Consumer Then
            Select Case account.ConsumerRegulationType
              Case isefinAccountConsumerRegulationType.NotApplicable
                AccountRegulations_NZ_HighCostConsumerCreditContract = finBL.AccountRegulations.GetAccountRegulations_NZ_HighCostConsumerCreditContract(account.DateOpened)
                If AccountRegulations_NZ_HighCostConsumerCreditContract.IsApplicable Then
                  HighestInterestRate = AccountRegulations_NZ_HighCostConsumerCreditContract.GetHighestTotalInterestRate(account)
                  If HighestInterestRate >= AccountRegulations_NZ_HighCostConsumerCreditContract.ThresholdInterestRate Then
                    Warnings &= "{{Warning|" & String.Format("Total Interest Rate calculated as {0}. Consider using a 'NZ {1}' instead.", finBL.FormatPercentage(HighestInterestRate / 100, 4), AccountRegulations_NZ_HighCostConsumerCreditContract.Description) & "|True}}"
                  End If
                End If
            End Select
          End If
        End If
        .TextAfter = Warnings

        ' Actions
        If includeActions Then
          With .Actions
            If Not ShowOriginalFormat Then
              Select Case account.AccountClass
                Case isefinAccountClass.Deposit
                  .AddFormAction("InterestCycleReview", "Review Cycle", finBL.CurrentUser.Permissions.Allow("Account.InterestCycle.View")).ShowInWebInterfaces = True
                  .AddFormAction("InterestPayTypeReview", "Review Pay Type", finBL.CurrentUser.Permissions.Allow("Account.InterestPayType.View")).ShowInWebInterfaces = True
                  .AddFormAction("InterestRateReview", "Review Rate", finBL.CurrentUser.Permissions.Allow("Account.InterestRate.View")).ShowInWebInterfaces = True

                Case isefinAccountClass.LoanFR
                  .AddFormAction("InterestCycleReview", "Review Cycle", finBL.CurrentUser.Permissions.Allow("Account.InterestCycle.View")).ShowInWebInterfaces = True
                  .AddFormAction("InterestRateReview", "Review Rate", finBL.CurrentUser.Permissions.Allow("Account.InterestRate.View")).ShowInWebInterfaces = True
                  .AddFormAction("PendingFloatingInterestRateReview", "Review Pending", account.HistoryItems.CountPendingFloatingInterestRateChanges <> 0)

                Case isefinAccountClass.LoanRC
                  .AddFormAction("InterestCycleReview", "Review Cycle", finBL.CurrentUser.Permissions.Allow("Account.InterestCycle.View")).ShowInWebInterfaces = True
                  .AddFormAction("InterestRateReview", "Review Rate", finBL.CurrentUser.Permissions.Allow("Account.InterestRate.View")).ShowInWebInterfaces = True
              End Select
            End If
          End With
        End If
      End With
    End If

    ' Other Interest
    If includeOtherInterest Then
      ' Get Values
      With accountCalc
        ' Show Original Rates?
        ShowOriginalFormat = .IsQuote OrElse .IsModeHistoric

        If ShowOriginalFormat Then
          ' Get straight from Calculation
          OtherInterestFutureChange = False
          OtherInterestRate = .OtherInterestRateResolved
          OtherInterestType = .OtherInterestType
        Else
          ' Get from History
          OtherInterestType = account.AccountType.OtherInterestTypeResolved

          Select Case OtherInterestType
            Case isefinAccountOtherInterestType.AccountUtilisation, isefinAccountOtherInterestType.AccountUtilisation2, isefinAccountOtherInterestType.AccountUtilisation3
              ' Get current Rate
              account.GetOtherInterestRate(dateAsAt, OtherInterestType, OtherInterestRate, , OtherInterestFutureChange)
            Case isefinAccountOtherInterestType.Custom
              ' Get current Rate
              account.GetOtherInterestRate(dateAsAt, OtherInterestType, OtherInterestRate, , OtherInterestFutureChange)
            Case isefinAccountOtherInterestType.NotApplicable
              OtherInterestRate = 0
              OtherInterestFutureChange = False
            Case isefinAccountOtherInterestType.CreditLimit, isefinAccountOtherInterestType.CreditLimit2, isefinAccountOtherInterestType.CreditLimit3
              ' Use Rate from Account Type
              OtherInterestRate = account.AccountType.OtherInterestRate
              OtherInterestFutureChange = False
            Case isefinAccountOtherInterestType.Utilisation, isefinAccountOtherInterestType.Utilisation2, isefinAccountOtherInterestType.Utilisation3
              ' Use Rate from Account Type
              OtherInterestRate = account.AccountType.OtherInterestRate
              OtherInterestFutureChange = False
          End Select
        End If
      End With

      If OtherInterestType <> isefinAccountOtherInterestType.NotApplicable Then
        With SummaryTableOther
          ' Initialise
          .TableClass = iseSummaryTableClass.Information
          .Caption = account.AccountType.OtherInterestDescriptionWithTypeResolved
          .Columns.AddText(13)
          .Columns.AddText()

          With .Rows
            If account.AccountType.CreditLimitCount > 1 Then
              Select Case OtherInterestType
                Case isefinAccountOtherInterestType.AccountUtilisation, isefinAccountOtherInterestType.CreditLimit, isefinAccountOtherInterestType.Utilisation
                  .AddCaptionText("Type:", account.AccountType.CreditLimit1DescriptionResolved)
                Case isefinAccountOtherInterestType.AccountUtilisation2, isefinAccountOtherInterestType.CreditLimit2, isefinAccountOtherInterestType.Utilisation2
                  .AddCaptionText("Type:", account.AccountType.CreditLimit2DescriptionResolved)
                Case isefinAccountOtherInterestType.AccountUtilisation3, isefinAccountOtherInterestType.CreditLimit3, isefinAccountOtherInterestType.Utilisation3
                  .AddCaptionText("Type:", account.AccountType.CreditLimit3DescriptionResolved)
              End Select
            End If
            .AddCaptionPercentage("Rate:", OtherInterestRate / 100, 4, True)
          End With

          ' Warnings
          Warnings = ""
          Select Case OtherInterestType
            Case isefinAccountOtherInterestType.AccountUtilisation, isefinAccountOtherInterestType.AccountUtilisation2, isefinAccountOtherInterestType.AccountUtilisation3, isefinAccountOtherInterestType.Custom
              If OtherInterestFutureChange Then
                Warnings &= "{{Warning|Future changes exist.}}"
              End If
          End Select
          .TextAfter = Warnings

          ' Actions
          If includeActions Then
            With .Actions
              Select Case OtherInterestType
                Case isefinAccountOtherInterestType.AccountUtilisation, isefinAccountOtherInterestType.AccountUtilisation2, isefinAccountOtherInterestType.AccountUtilisation3, isefinAccountOtherInterestType.Custom
                  If Not ShowOriginalFormat Then
                    .AddFormAction("OtherInterestRateReview", "Review", finBL.CurrentUser.Permissions.Allow("Account.OtherInterestRate.View")).ShowInWebInterfaces = True
                  End If
              End Select
            End With
          End If
        End With
      End If
    End If

    ' Default Interest
    If includeDefaultInterest AndAlso account.SupportsDefaultInterestandFees AndAlso account.AccountType IsNot Nothing Then
      ' Get Values
      With accountCalc
        ' Show Original Rates?
        ShowOriginalFormat = .IsQuote OrElse .IsModeHistoric

        If ShowOriginalFormat Then
          ' Get straight from Calculation
          DefaultInterestFutureChange = False
          DefaultInterestRate = .DefaultInterestRate
          DefaultInterestRateBasis = .DefaultInterestRateBasis

          ' Interest Rate
          InterestRate = .InterestRate
          InterestType = .InterestType

          ' Later of Maturity or Final Date; can't have a Payment Arrangement yet!
          Select Case .AccountClass
            Case isefinAccountClass.LoanFR, isefinAccountClass.LoanFT
              DateMaturityOrFinal = .DateMaturity
            Case Else
              DateMaturityOrFinal = Nothing
          End Select
        Else
          ' Get from History
          account.GetDefaultInterestRate(dateAsAt, DefaultInterestRateBasis, DefaultInterestRate, , DefaultInterestFutureChange)

          ' Interest Rate
          account.GetInterestRate(dateAsAt, InterestType, InterestRate, InterestRateTablePk, InterestRatePremium)

          ' Later of Maturity or Final Date
          Select Case .AccountClass
            Case isefinAccountClass.LoanFR, isefinAccountClass.LoanFT
              DateMaturityOrFinal = .DateMaturity
              If account.AccountType.DefaultInterestPostFinalDate Then
                If .PaymentArrangementDateFinal <> Nothing AndAlso .PaymentArrangementDateFinal > DateMaturityOrFinal Then
                  DateMaturityOrFinal = .PaymentArrangementDateFinal
                End If
              End If
            Case Else
              DateMaturityOrFinal = Nothing
          End Select
        End If
      End With

      With SummaryTableDefault
        ' Initialise
        .TableClass = iseSummaryTableClass.Information
        .Caption = "Default Interest"
        .Columns.AddText(13)
        .Columns.AddText()

        With .Rows
          Select Case DefaultInterestRateBasis
            Case isefinDefaultInterestRateBasis.FixedRate
              If account.AccountType.OptionInterestPostMaturityBasis = isefinInterestPostMaturityBasis.ChargeAsDefault AndAlso DateMaturityOrFinal <> Nothing AndAlso dateAsAt >= DateMaturityOrFinal Then
                ' Post Maturity
                .AddCaptionWiki("Rate:", String.Format("**Fixed at {0}** --(Post Maturity)--", finBL.FormatPercentage(DefaultInterestRate / 100, 4)))
              Else
                DefaultInterestRateCharge = DefaultInterestRate - InterestRate
                If DefaultInterestRateCharge < 0 Then DefaultInterestRateCharge = 0

                If DefaultInterestRateCharge = 0 Then
                  .AddCaptionText("Rate:", String.Format("Fixed at {0}", finBL.FormatPercentage(DefaultInterestRate / 100, 4)))
                Else
                  .AddCaptionWiki("Rate:", String.Format("**Fixed at {0}** --(charging **{1}**)--", finBL.FormatPercentage(DefaultInterestRate / 100, 4), finBL.FormatPercentage(DefaultInterestRateCharge / 100, 4)))
                End If
              End If

            Case isefinDefaultInterestRateBasis.PlusRate
              If account.AccountType.OptionInterestPostMaturityBasis = isefinInterestPostMaturityBasis.ChargeAsDefault AndAlso DateMaturityOrFinal <> Nothing AndAlso dateAsAt >= DateMaturityOrFinal Then
                ' Post Maturity
                .AddCaptionWiki("Rate:", String.Format("**Interest Rate plus {0}** --(charging **{1}** post Maturity)--", finBL.FormatPercentage(DefaultInterestRate / 100), finBL.FormatPercentage(DefaultInterestRateCharge / 100, 4)))
              Else
                .AddCaptionWiki("Rate:", String.Format("**Interest Rate plus {0}** --(charging **{1}**)--", finBL.FormatPercentage(DefaultInterestRate / 100, 4), finBL.FormatPercentage((DefaultInterestRate + InterestRate) / 100, 4)))
              End If

            Case isefinDefaultInterestRateBasis.PremiumRate
              If account.AccountType.OptionInterestPostMaturityBasis = isefinInterestPostMaturityBasis.ChargeAsDefault AndAlso DateMaturityOrFinal <> Nothing AndAlso dateAsAt >= DateMaturityOrFinal Then
                ' Post Maturity
                .AddCaptionWiki("Rate:", String.Format("**Premium of {0}** --(charging **{1}** post Maturity)--", finBL.FormatPercentage(DefaultInterestRate / 100, 4), finBL.FormatPercentage((DefaultInterestRate + InterestRate) / 100, 4)))
              Else
                .AddCaptionText("Rate:", String.Format("Premium of {0}", finBL.FormatPercentage(DefaultInterestRate / 100, 4)))
              End If
          End Select
        End With

        ' Warnings
        Warnings = ""
        If DefaultInterestFutureChange Then
          Warnings &= "{{Warning|Future Default Interest changes exist.}}"
        End If
        .TextAfter = Warnings

        ' Actions
        If includeActions Then
          With .Actions
            If Not ShowOriginalFormat Then
              .AddFormAction("DefaultInterestRateReview", "Review", finBL.CurrentUser.Permissions.Allow("Account.DefaultInterestRate.View")).ShowInWebInterfaces = True
            End If
          End With
        End If
      End With
    End If

    ' Interest Rate Change Instructions
    If includeInterestRateChangeInstructions Then
      Select Case account.AccountClass
        Case isefinAccountClass.LoanFR
          ' Get Values
          With accountCalc
            ' Show Original Rates?
            ShowOriginalFormat = .IsQuote OrElse .IsModeHistoric
          End With

          With SummaryTableInstructions
            ' Initialise
            .TableClass = iseSummaryTableClass.Information
            .Caption = "Instructions"
            .Columns.AddText(13)
            .Columns.AddText()

            With .Rows
              .AddCaptionText("Decrease:", accountCalc.InterestInstructionDownText)
              .AddCaptionText("Increase:", accountCalc.InterestInstructionUpText)
            End With

            ' Warnings
            Warnings = ""
            .TextAfter = Warnings

            ' Actions
            If includeActions Then
              With .Actions
                If Not ShowOriginalFormat Then
                  .AddFormAction("InterestInstructionReview", "Review", finBL.CurrentUser.Permissions.Allow("Account.InterestInstructionRevise")).ShowInWebInterfaces = True
                End If
              End With
            End If
          End With
      End Select
    End If

    ' Add Summary Tables
    If includeInterest Then SummaryTables.Add("Main", SummaryTableMain)
    If includeOtherInterest Then SummaryTables.Add("Other", SummaryTableOther)
    If includeDefaultInterest Then SummaryTables.Add("Default", SummaryTableDefault)
    If includeInterestRateChangeInstructions Then SummaryTables.Add("Instructions", SummaryTableInstructions)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Withholding Tax Details Summary.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="account">
  '''  The Account to summarise.
  ''' </param>
  ''' <param name="dateAsAt">
  '''  Optional Date to display information for. If not specified the current date is used.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Account Financial page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main Tax Category details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_WithholdingTaxDetails2(callerScriptInfo As ISScriptExecutionInfo,
                                                             account As finAccount,
                                                    Optional dateAsAt As Date = Nothing,
                                                    Optional includeActions As Boolean = True,
                                                    Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' Account_WithholdingTaxDetails2
    '
    ' Version: 1.01 (10/01/2024)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.00  11/04/2018  ISS                  
    '    1.01  10/01/2024  ISS      J032721   Updated Permission Keys
    ' #################################################################

    Dim AccountClient As finAccountClient
    Dim ClientTaxCategoryPk As Integer
    Dim Exempt As Boolean
    Dim ExemptionExpiryDate As Date
    Dim IsDeclaredRate As Boolean
    Dim Rate As Double
    Dim strTemp As String
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim TaxCategoryPk As Integer
    Dim TaxCategoryFromClient As Boolean
    Dim TaxCategoryFutureChange As Boolean
    Dim TaxCategoryNextChangeDate As Date
    Dim TransactionResidentStatus As isefinAccountTransactionResidentStatus
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Date As At
    dateAsAt = finBL.Runtime.Validation.ValidateDate(dateAsAt)
    If dateAsAt = Nothing Then dateAsAt = finBL.TimeZoneFunctions.GetCurrentDatabaseDate()

    If account.SupportsTaxCategories Then
      ' Get Tax Category details
      account.GetTaxCategoryWithClient(dateAsAt, TaxCategoryPk, TaxCategoryFromClient, "", TaxCategoryFutureChange, TaxCategoryNextChangeDate, TransactionResidentStatus, Exempt, ClientTaxCategoryPk, ExemptionExpiryDate, IsDeclaredRate, Rate)

      With SummaryTableMain
        ' Initialise
        .TableClass = iseSummaryTableClass.Information
        .Caption = "Withholding Tax Details"
        .Columns.AddText(13)
        .Columns.AddText()

        With .Rows
          ' General
          .AddCaptionCodeDescription("Category:", TaxCategoryPk, finBL.TaxCategories)
          Select Case TransactionResidentStatus
            Case isefinAccountTransactionResidentStatus.ApprovedIssuerLevy
              .AddCaptionText("Resident:", "Approved Issuer Levy")
            Case isefinAccountTransactionResidentStatus.NonResident
              .AddCaptionText("Resident:", "Non-Resident")
            Case isefinAccountTransactionResidentStatus.Resident
              .AddCaptionText("Resident:", "Resident")
            Case Else
              .AddCaptionText("Resident:", "")
          End Select
          If IsDeclaredRate Then strTemp = "" Else strTemp = "Undeclared"
          With .AddCaptionPercentage("Rate:", Rate / 100, 4, True, strTemp)
            .Cells(1).TextAlign = iseSummaryTableCellTextAlign.Left
          End With
        End With

        ' Warnings
        If TaxCategoryFutureChange Then
          Warnings &= "{{Warning|Future Tax Category changes exist.}}"
        End If
        If account.Clients.Count <> 0 Then
          If TaxCategoryPk <> ClientTaxCategoryPk Then
            If finBL.TaxCategories.ExistsPk(ClientTaxCategoryPk) Then
              Warnings &= "{{Warning|Tax Category does not match Client Tax Category '" & finBL.TaxCategories.ItemByPk(ClientTaxCategoryPk).TaxCategoryId & "'.}}"
            Else
              Warnings &= "{{Warning|Tax Category does not match Client Tax Category.}}"
            End If
          End If
          If Exempt Then
            If ExemptionExpiryDate = Nothing Then
              Warnings &= "{{Warning|Client does not have an Exemption Expiry Date entered.}}"
            ElseIf ExemptionExpiryDate < dateAsAt Then
              Warnings &= "{{Warning|Client Exemption Expiry Date **" & finBL.FormatDateLong(ExemptionExpiryDate) & "** has passed.}}"
            End If

            ' Account is Exempt but not all 'Owner' Clients are
            For Each AccountClient In account.Clients
              With AccountClient
                If .IsOwner AndAlso finBL.TaxCategories.ExistsPk(.ClientTaxCategoryPk) AndAlso Not finBL.TaxCategories.ItemByPk(AccountClient.ClientTaxCategoryPk).Exempt Then
                  Warnings &= "{{Warning|Client [[" & finBL.CreateApplicationShortcutFormShow("Clients", AccountClient.ClientId).ToUrlString(True) & "|" & AccountClient.ClientId & "]], '" & AccountClient.ClientName & "' Tax Category '" & AccountClient.ClientTaxCategoryId & "' is not Exempt.}}"
                End If
              End With
            Next
          End If
          Select Case TransactionResidentStatus
            Case isefinAccountTransactionResidentStatus.ApprovedIssuerLevy, isefinAccountTransactionResidentStatus.NonResident
              For Each AccountClient In account.Clients
                With AccountClient
                  If .IsOwner AndAlso finBL.TaxCategories.ExistsPk(.ClientTaxCategoryPk) AndAlso finBL.TaxCategories.ItemByPk(AccountClient.ClientTaxCategoryPk).Resident Then
                    Warnings &= "{{Warning|Client [[" & finBL.CreateApplicationShortcutFormShow("Clients", AccountClient.ClientId).ToUrlString(True) & "|" & AccountClient.ClientId & "]], '" & AccountClient.ClientName & "' Tax Category '" & AccountClient.ClientTaxCategoryId & "' is Resident.}}"
                  End If
                End With
              Next
          End Select
          If TaxCategoryFromClient Then
            Warnings &= "{{Info|Tax Category from Client [[" & finBL.CreateApplicationShortcutFormShow("Clients", account.Clients(0).ClientId).ToUrlString(True) & "|" & account.Clients(0).ClientId & "]], '" & account.Clients(0).ClientName & "'.}}"
          End If
        End If
        If Not IsDeclaredRate Then
          Warnings &= "{{Warning|Using Undeclared Tax Rate.}}"
        End If
        .TextAfter = Warnings

        ' Actions
        If includeActions Then
          With .Actions
            .AddFormAction("TaxCategoryReview", "Review", finBL.CurrentUser.Permissions.Allow("Account.TaxCategory.View")).ShowInWebInterfaces = True
          End With
        End If
      End With
    End If

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Minimum Payments Due Summary (Version 1.01, Last updated 19/04/2016).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="account">
  '''  The Account to summarise.
  ''' </param>
  ''' <param name="accountOverdues">
  '''  A finAccountOverdues object or Nothing. If Nothing then the overdues will be created and returned as a ByRef parameter.
  ''' </param>
  ''' <param name="accountCalc">
  '''  The Account Calculation or Nothing to use the current Account Calculation.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Key page and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_MinimumPaymentsDue(callerScriptInfo As ISScriptExecutionInfo,
                                                         account As finAccount,
                                                Optional ByRef accountOverdues As finAccountOverdues = Nothing,
                                                Optional accountCalc As finAccountCalc = Nothing,
                                                Optional includeActions As Boolean = True,
                                                Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim AccountCalcScheduleItem As finAccountCalcScheduleItem
    Dim AccountOverdue As finAccountOverdue
    Dim DateAsAt As Date
    Dim Include As Boolean
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Get Date As At - weird function as ByRef accountOverdues and accountOverduesC could be passed in
    DateAsAt = finBL.TimeZoneFunctions.GetCurrentDatabaseDate()

    ' Initialise ByRef Parameters
    If account.Status = isefinAccountStatus.Open AndAlso account.AccountClass = isefinAccountClass.LoanRC Then
      If accountOverdues Is Nothing Then
        ' Load Overdues
        accountOverdues = finBL.CreateAccountOverdues()
        accountOverdues.LoadFromAccount(account, False, DateAsAt)
      End If
    End If

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Calculation
    If accountCalc Is Nothing Then accountCalc = account.Calculation

    ' Main
    If account.Status = isefinAccountStatus.Open AndAlso account.AccountClass = isefinAccountClass.LoanRC Then
      With SummaryTableMain
        ' Initialise
        .TableClass = iseSummaryTableClass.TabularData
        .AutoStripe = True
        .Caption = ""

        ' Columns
        With .Columns
          .AddDate("Due")
          .AddCode("Type", 8)
          .AddText("Notes")
          .AddCurrency("Value")
        End With

        ' Overdues
        For Each AccountOverdue In accountOverdues
          With .Rows.Add()
            ' Make Promises Red
            If AccountOverdue.ScheduleType = isefinAccountCalcScheduleType.PaymentPromise Then
              .ForegroundColour = "red"
            End If

            ' Values
            With .Cells
              .AddDate(AccountOverdue.Date)
              Select Case AccountOverdue.ScheduleType
                Case isefinAccountCalcScheduleType.Opening
                  .AddText(AccountOverdue.Reference)
                Case isefinAccountCalcScheduleType.PaymentDueMinimum
                  .AddText("Overdue")
                Case isefinAccountCalcScheduleType.Transaction
                  Select Case AccountOverdue.TransactionSource
                    Case isefinTransactionSource.AccountBalanceAdjustment
                      .AddText("Adjustment")
                    Case Else
                      .AddText("")
                  End Select
                Case Else
                  .AddText(AccountOverdue.ScheduleTypeText)
              End Select
              If AccountOverdue.Notes = AccountOverdue.ScheduleTypeText Then
                ' Don't show notes if they mimic the Schedule Type
                .AddText("")
              Else
                .AddText(AccountOverdue.Notes)
              End If
              .AddCurrency(AccountOverdue.ValueDue)
            End With
          End With
        Next

        ' Future
        For Each AccountCalcScheduleItem In accountCalc.Schedule
          ' Include?
          If AccountCalcScheduleItem.IsExisting Then
            Include = False
          Else
            Select Case AccountCalcScheduleItem.ScheduleType
              Case isefinAccountCalcScheduleType.Payment, isefinAccountCalcScheduleType.PaymentAdditional, isefinAccountCalcScheduleType.PaymentBalloon, isefinAccountCalcScheduleType.PaymentOverridden, isefinAccountCalcScheduleType.PaymentPromise, isefinAccountCalcScheduleType.PaymentTransaction
                If AccountCalcScheduleItem.ScheduleSubType = isefinAccountCalcScheduleSubType.PaymentGrace Then
                  Include = False
                ElseIf AccountCalcScheduleItem.Value < 0 OrElse AccountCalcScheduleItem.TransactionValue < 0 Then
                  Include = True
                Else
                  Include = False
                End If
              Case Else
                Include = False
            End Select
          End If

          ' Add Row
          If Include Then
            With .Rows.Add().Cells
              If AccountCalcScheduleItem.Date = DateAsAt Then
                .AddText("Due Today")
              Else
                .AddDate(AccountCalcScheduleItem.Date)
              End If
              .AddText("")
              If AccountCalcScheduleItem.Notes = AccountCalcScheduleItem.ScheduleTypeText Then
                ' Don't show notes if they mimic the Schedule Type
                .AddText("")
              Else
                .AddText(AccountCalcScheduleItem.Notes)
              End If
              .AddCurrency(-AccountCalcScheduleItem.Value)
            End With
          End If
        Next

        ' Warnings
        If .Rows.Count = 1 Then
          ' No entries (just header row)
          .Rows.Clear()
          Warnings &= "{{info|No Minimum Payments due.}}"
        End If
        .TextAfter = Warnings
      End With
    End If

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Minimum Payments Summary
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="account">
  '''  The Account to summarise.
  ''' </param>
  ''' <param name="accountCalc">
  '''  The Account Calculation or Nothing to use the current Account Calculation.
  ''' </param>
  ''' <param name="scheduleIndex">
  '''  The finAccountCalcVersions index to chow a schedule for, or -1 to show the current Schedule.
  ''' </param>
  ''' <param name="showScheduleAction">
  '''  Show the 'Schedule' action?
  ''' </param>
  ''' <param name="showScheduleWithoutPaymentsAction">
  '''  Show the 'Schedule omitting future Payments' action?
  ''' </param>
  ''' <param name="dateAsAt">
  '''  Optional Date to display information for. If not specified the current date is used.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Payments page and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_MinimumPaymentsSummary2(callerScriptInfo As ISScriptExecutionInfo,
                                                             account As finAccount,
                                                    Optional accountCalc As finAccountCalc = Nothing,
                                                    Optional scheduleIndex As Integer = -1,
                                                    Optional showScheduleAction As Boolean = False,
                                                    Optional showScheduleWithoutPaymentsAction As Boolean = False,
                                                    Optional dateAsAt As Date = Nothing,
                                                    Optional includeActions As Boolean = True,
                                                    Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' Account_MinimumPaymentsSummary2
    '
    ' Version: 1.04 (08/01/2024)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.02  05/03/2021  ISS                  
    '    1.03  14/09/2021  ISS      J027291   New Minimum Payment Basis - Interest Balance, Interest and Fees Balance
    '    1.04  08/01/2024  ISS      J032699   Updated Permission Keys
    ' #################################################################

    Dim FutureChange As Boolean
    Dim MinimumPaymentBasis As isefinAccountMinimumPaymentBasis
    Dim MinimumPaymentDirectDebitFullBalance As Boolean
    Dim MinimumPaymentDueDays As Integer
    Dim MinimumPaymentDueDaysOverride As Boolean
    Dim MinimumPaymentDueDaysResolved As Integer
    Dim MinimumPaymentHoldToDate As Date
    Dim MinimumPaymentInstalmentEndDate As Date
    Dim MinimumPaymentInstalmentResidualValue As Decimal
    Dim MinimumPaymentPercent As Double
    Dim MinimumPaymentValue As Decimal
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Date As At
    dateAsAt = finBL.Runtime.Validation.ValidateDate(dateAsAt)
    If dateAsAt = Nothing Then dateAsAt = finBL.TimeZoneFunctions.GetCurrentDatabaseDate()

    ' Get Calculation
    If accountCalc Is Nothing Then
      accountCalc = account.Calculation
      If showScheduleAction OrElse showScheduleWithoutPaymentsAction Then
        scheduleIndex = account.CalculationVersions.Count - 1
      End If
    End If

    ' Get Information
    If accountCalc.IsCalcVersionOpening Then
      With accountCalc
        MinimumPaymentBasis = .MinimumPaymentBasis
        MinimumPaymentValue = .MinimumPaymentValue
        MinimumPaymentPercent = .MinimumPaymentPercent
        MinimumPaymentInstalmentEndDate = .MinimumPaymentInstalmentEndDate
        MinimumPaymentInstalmentResidualValue = .MinimumPaymentInstalmentResidualValue
        MinimumPaymentDueDaysOverride = .MinimumPaymentDueDaysOverride
        MinimumPaymentDueDays = .MinimumPaymentDueDays
        MinimumPaymentHoldToDate = .MinimumPaymentHoldToDateResolved
        MinimumPaymentDirectDebitFullBalance = .MinimumPaymentDirectDebitFullBalance
        FutureChange = False

        ' Resolve Minimum Due Days
        If MinimumPaymentDueDaysOverride Then
          MinimumPaymentDueDaysResolved = MinimumPaymentDueDays
        Else
          MinimumPaymentDueDaysResolved = .AccountType.MinimumPaymentDueDays
        End If
        If MinimumPaymentDueDaysResolved < 0 Then MinimumPaymentDueDaysResolved = 0
      End With
    Else
      account.GetMinimumPaymentDetails(dateAsAt, MinimumPaymentBasis, MinimumPaymentValue, MinimumPaymentPercent, MinimumPaymentInstalmentEndDate, MinimumPaymentInstalmentResidualValue, MinimumPaymentDueDaysOverride, MinimumPaymentDueDays, MinimumPaymentDueDaysResolved, MinimumPaymentHoldToDate, MinimumPaymentDirectDebitFullBalance, "", FutureChange)
    End If

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      .Columns.AddText(12).NoBreakChars = 12
      .Columns.AddText()

      With .Rows
        ' Basis
        .AddCaptionText("Basis:", finBL.Enums.isefinAccountMinimumPaymentBasis_ToString(MinimumPaymentBasis))
        Select Case MinimumPaymentBasis
          Case isefinAccountMinimumPaymentBasis.Custom
            If MinimumPaymentValue <> 0 AndAlso MinimumPaymentPercent <> 0 Then
              .AddCaptionWiki("Value:", String.Format("**{0}** or **{1}**", finBL.FormatCurrency(MinimumPaymentValue, True), finBL.FormatPercentage(MinimumPaymentPercent / 100, 4)))
            ElseIf MinimumPaymentValue <> 0 Then
              .AddCaptionCurrency("Value:", MinimumPaymentValue, True)
            ElseIf MinimumPaymentPercent <> 0 Then
              .AddCaptionPercentage("Percent:", MinimumPaymentPercent / 100, 4, True)
            End If

          Case isefinAccountMinimumPaymentBasis.Higher
            .AddCaptionWiki("Value:", String.Format("**{0}** or **{1}**", finBL.FormatCurrency(MinimumPaymentValue, True), finBL.FormatPercentage(MinimumPaymentPercent / 100, 4)))

          Case isefinAccountMinimumPaymentBasis.Instalment
            .AddCaptionDate("End Date:", MinimumPaymentInstalmentEndDate)
            If MinimumPaymentInstalmentResidualValue <> 0 Then
              .AddCaptionCurrency("Residual:", MinimumPaymentInstalmentResidualValue, True)
            End If

          Case isefinAccountMinimumPaymentBasis.InterestAndFeesBalance, isefinAccountMinimumPaymentBasis.InterestBalance

          Case isefinAccountMinimumPaymentBasis.InterestAndFeesOnly, isefinAccountMinimumPaymentBasis.InterestOnly

          Case isefinAccountMinimumPaymentBasis.None

          Case isefinAccountMinimumPaymentBasis.OngoingSetValue
            .AddCaptionCurrency("Value:", MinimumPaymentValue, True)

          Case isefinAccountMinimumPaymentBasis.PercentOfBalance
            .AddCaptionPercentage("Percent:", MinimumPaymentPercent / 100, 4, True)

          Case isefinAccountMinimumPaymentBasis.SetValue
            .AddCaptionCurrency("Value:", MinimumPaymentValue, True)
        End Select

        ' Due days
        .AddCaptionInteger("Due days:", MinimumPaymentDueDaysResolved)
        If MinimumPaymentDueDaysOverride Then
          Warnings &= "{{info|Due days overrides the Account Type setting.}}"
        End If

        ' Hold
        If accountCalc.IsCalcVersionOpening Then
          Select Case accountCalc.MinimumPaymentHoldToPeriod
            Case "None"
            Case "On Date"
              .AddCaptionDate("Hold To:", MinimumPaymentHoldToDate)
            Case Else
              .AddCaptionText("Hold Period:", String.Format("{0}, to {1}", finBL.Utilities.DateCycleGetDescription(False, accountCalc.MinimumPaymentHoldToPeriod), finBL.FormatDateLong(MinimumPaymentHoldToDate)))
          End Select
        Else
          If MinimumPaymentHoldToDate <> Nothing AndAlso MinimumPaymentHoldToDate >= dateAsAt Then
            .AddCaptionDate("Hold To:", MinimumPaymentHoldToDate)
          End If
        End If

        ' Paid by Direct Debit?
        If account.PaymentsByDirectDebit(dateAsAt) Then
          If MinimumPaymentDirectDebitFullBalance Then
            .AddCaptionText("Direct Debit:", "Full Balance")
          Else
            .AddCaptionText("Direct Debit:", "Minimum Balance")
          End If
        End If
      End With

      ' Warnings
      If accountCalc.IsCalcVersionFuture AndAlso FutureChange Then
        Warnings &= "{{Warning|Future Minimum Payment changes exist.}}"
      End If
      .TextAfter = Warnings

      ' Actions
      If includeActions Then
        With .Actions
          .AddFormAction("MinimumPaymentReview", "Review", finBL.CurrentUser.Permissions.Allow("Account.MinimumPayment.View")).ShowInWebInterfaces = True
          If (showScheduleAction OrElse showScheduleWithoutPaymentsAction) AndAlso (scheduleIndex >= 0 AndAlso scheduleIndex < account.CalculationVersions.Count) Then
            .AddFormAction("ShowSchedule", "Schedule", showScheduleAction, String.Format("index={0}", scheduleIndex)).ShowInWebInterfaces = True
            .AddFormAction("ShowSchedulePayments", "Schedule (omit Future Payments)", showScheduleWithoutPaymentsAction, String.Format("index={0}", scheduleIndex)).ShowInWebInterfaces = True
          End If
        End With
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Monitoring Summary.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="account">
  '''  The Account to summarise.
  ''' </param>
  ''' <param name="onlyIncludeIfMonitored">
  '''  Indicates whether to only include tables if Monitoring.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Status page and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>MainA</code><description>Monitor Category A details.</description></item>
  '''    <item><code>MainB</code><description>Monitor Category B details.</description></item>
  '''    <item><code>MainC</code><description>Monitor Category C details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_Monitoring(callerScriptInfo As ISScriptExecutionInfo,
                                                 account As finAccount,
                                        Optional onlyIncludeIfMonitored As Boolean = False,
                                        Optional includeActions As Boolean = True,
                                        Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables


    ' #################################################################
    ' Account_Monitoring
    '
    ' Version: 1.06 (04/01/2023)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.05  22/09/2017  ISS                  
    '    1.06  04/01/2023  ISS      J029951   Not applying Permissions
    ' #################################################################

    Dim CategoryAbc As String
    Dim DateAsAt As Date
    Dim Days As Long
    Dim Description As String
    Dim i As Integer
    Dim Include As Boolean
    Dim MonitorCategoryId As String
    Dim MonitorCategoryCancelAllowed As Boolean
    Dim MonitorCategoryEnteredDate As Date
    Dim MonitorCategoryUpdateAllowed As Boolean
    Dim MonitorCategoryUpdatedDate As Date
    Dim strTemp As String
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTableMainA As ISSummaryTable
    Dim SummaryTableMainB As ISSummaryTable
    Dim SummaryTableMainC As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMainA = finBL.CreateSummaryTable()
    SummaryTableMainB = finBL.CreateSummaryTable()
    SummaryTableMainC = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Date As At
    DateAsAt = finBL.TimeZoneFunctions.GetCurrentDatabaseDate()

    For i = 1 To 3
      ' Initialise
      Warnings = ""

      ' Get Monitoring Details
      Select Case i
        Case 1
          CategoryAbc = "A"
          Include = finBL.Settings.MonitorCategoryAUse AndAlso (account.MonitorCategoryAPk <> 0 OrElse Not onlyIncludeIfMonitored)
          Description = finBL.Settings.MonitorCategoryADescriptionResolved
          MonitorCategoryId = account.MonitorCategoryAId
          MonitorCategoryEnteredDate = account.MonitorCategoryAEnteredDate
          MonitorCategoryUpdatedDate = account.MonitorCategoryAUpdatedDate
          MonitorCategoryUpdateAllowed = finBL.CurrentUser.Permissions.Allow("Account.MonitorCategoryRevise") AndAlso finBL.CurrentUser.Permissions.Allow("Account.MonitorCategoryAUpdate")
          MonitorCategoryCancelAllowed = MonitorCategoryUpdateAllowed AndAlso finBL.CurrentUser.Permissions.Allow("Account.MonitorCategoryACancel") AndAlso account.MonitorCategoryAPk <> 0
          SummaryTableMain = SummaryTableMainA

        Case 2
          CategoryAbc = "B"
          Include = finBL.Settings.MonitorCategoryBUse AndAlso (account.MonitorCategoryBPk <> 0 OrElse Not onlyIncludeIfMonitored)
          Description = finBL.Settings.MonitorCategoryBDescriptionResolved
          MonitorCategoryId = account.MonitorCategoryBId
          MonitorCategoryEnteredDate = account.MonitorCategoryBEnteredDate
          MonitorCategoryUpdatedDate = account.MonitorCategoryBUpdatedDate
          MonitorCategoryUpdateAllowed = finBL.CurrentUser.Permissions.Allow("Account.MonitorCategoryRevise") AndAlso finBL.CurrentUser.Permissions.Allow("Account.MonitorCategoryBUpdate")
          MonitorCategoryCancelAllowed = MonitorCategoryUpdateAllowed AndAlso finBL.CurrentUser.Permissions.Allow("Account.MonitorCategoryBCancel") AndAlso account.MonitorCategoryBPk <> 0
          SummaryTableMain = SummaryTableMainB

        Case 3
          CategoryAbc = "C"
          Include = finBL.Settings.MonitorCategoryCUse AndAlso (account.MonitorCategoryCPk <> 0 OrElse Not onlyIncludeIfMonitored)
          Description = finBL.Settings.MonitorCategoryCDescriptionResolved
          MonitorCategoryId = account.MonitorCategoryCId
          MonitorCategoryEnteredDate = account.MonitorCategoryCEnteredDate
          MonitorCategoryUpdatedDate = account.MonitorCategoryCUpdatedDate
          MonitorCategoryUpdateAllowed = finBL.CurrentUser.Permissions.Allow("Account.MonitorCategoryRevise") AndAlso finBL.CurrentUser.Permissions.Allow("Account.MonitorCategoryCUpdate")
          MonitorCategoryCancelAllowed = MonitorCategoryUpdateAllowed AndAlso finBL.CurrentUser.Permissions.Allow("Account.MonitorCategoryCCancel") AndAlso account.MonitorCategoryCPk <> 0
          SummaryTableMain = SummaryTableMainC
      End Select

      ' Main A-C
      If Include Then
        With SummaryTableMain
          ' Initialise
          .TableClass = iseSummaryTableClass.Information
          .Caption = Description
          .Columns.AddText(20)
          .Columns.AddText()

          If Len(MonitorCategoryId) = 0 Then
            ' Not Monitored
            .TextAfter = "Not monitored."
          Else
            ' Monitored
            With .Rows
              .AddCaptionCodeDescription("Category:", MonitorCategoryId, finBL.MonitorCategories)

              ' Started
              Days = DateDiff(DateInterval.Day, MonitorCategoryEnteredDate.Date, DateAsAt)
              If Days = 0 Then
                strTemp = "Today"
              ElseIf Days = 1 Then
                strTemp = "**1** day ago"
              Else
                strTemp = String.Format("**{0}** days ago", Days)
              End If
              .AddCaptionDate("Started:", MonitorCategoryEnteredDate, strTemp)

              ' Moved to
              Days = DateDiff(DateInterval.Day, MonitorCategoryUpdatedDate.Date, DateAsAt)
              If Days = 0 Then
                strTemp = "Today"
              ElseIf Days = 1 Then
                strTemp = "**1** day ago"
              Else
                strTemp = String.Format("**{0}** days ago", Days)
              End If
              .AddCaptionDate(String.Format("Moved to '{0}':", MonitorCategoryId), MonitorCategoryUpdatedDate, strTemp)
            End With

            ' In Default?
            If finBL.MonitorCategories(MonitorCategoryId).TreatAsInDefault Then
              Warnings &= "{{warning|In Default.}}"
            End If

            ' Warnings
            .TextAfter = Warnings
          End If

          ' Actions
          If account.IsNew Then
            ' Unsaved Account, e.g., from an Account Application
          ElseIf includeActions Then
            With .Actions
              .AddFormAction("MonitorCategoryHistory" & CategoryAbc, "Review", finBL.CurrentUser.Permissions.Allow("Account.Form.Page.Status"))
              If MonitorCategoryUpdateAllowed Then .AddFormAction("MonitorCategoryUpdate" & CategoryAbc, "Revise", (Not finBL.Database.IsReadOnly)).ShowInWebInterfaces = True
              If MonitorCategoryCancelAllowed Then .AddFormAction("MonitorCategoryClear" & CategoryAbc, "Clear", (Not finBL.Database.IsReadOnly)).ShowInWebInterfaces = True
            End With
          End If
        End With
      End If
    Next

    ' Add Summary Tables
    If finBL.Settings.MonitorCategoryAUse Then SummaryTables.Add("MainA", SummaryTableMainA)
    If finBL.Settings.MonitorCategoryBUse Then SummaryTables.Add("MainB", SummaryTableMainB)
    If finBL.Settings.MonitorCategoryCUse Then SummaryTables.Add("MainC", SummaryTableMainC)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Payment Arrangements Summary.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="account">
  '''  The Account to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Payments page and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_PaymentArrangementsSummary(callerScriptInfo As ISScriptExecutionInfo,
                                                                 account As finAccount,
                                                        Optional includeActions As Boolean = True,
                                                        Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' Account_PaymentArrangementsSummary
    '
    ' Version 1.03 (21/03/2022)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.02  04/02/2021  ISS                  
    '    1.03  21/03/2022  ISS      J028467   Use finAccount.CanAddPaymentArrangment/Promise functions      
    ' #################################################################

    Dim AccountPayArrangement As finAccountPayArrangement
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim SummaryTables2 As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      .Columns.AddText(16).NoBreakChars = 16
      .Columns.AddText()

      If account.PaymentArrangements.Count = 0 Then
        ' No Payment Arrangements
        Warnings &= "{{info|No Payment Arrangements recorded.}}"
      Else
        With .Rows
          ' Details
          Select Case account.PaymentArrangements.Count
            Case 1
              .AddCaptionWiki("Details:", "**1** Payment Arrangement recorded")
            Case Else
              .AddCaptionWiki("Details:", String.Format("**{0}** Payment Arrangements recorded", account.PaymentArrangements.Count))
          End Select

          ' Current Arrangement
          AccountPayArrangement = account.PaymentArrangements(account.PaymentArrangements.Count - 1)
          If AccountPayArrangement.IsCurrent Then
            .AddSectionHeading2("Current Arrangement")

            ' Get Payment Arrangement Summary
            SummaryTables2 = Me.AccountPaymentArrangement_Summary(callerScriptInfo, AccountPayArrangement, True, includeActions)

            ' Append to this Table
            SummaryTableMain.Rows.AppendFromSummaryTables(SummaryTables2)

            ' Append Warnings
            If SummaryTables2 IsNot Nothing AndAlso SummaryTables2.Count <> 0 Then
              Warnings = SummaryTables2.ItemByIndex(0).TextAfter
            End If
          End If
        End With
      End If

      ' Warnings
      .TextAfter = Warnings

      ' Actions
      If includeActions Then
        With .Actions
          If account.PaymentArrangements.Count <> 0 AndAlso account.PaymentArrangements(account.PaymentArrangements.Count - 1).IsCurrent Then
            .AddHtmlShowFunction("PaymentArrangementViewCurrent", "View Current", "AccountPaymentArrangementSummary", String.Format("Payment Arrangement Summary for Account {0}, '{1}'", account.AccountId, account.Name), "AccountId=" & account.AccountId)
            .AddFormAction("PaymentArrangementCancel", "Cancel Payment Arrangement", account.PaymentArrangements(account.PaymentArrangements.Count - 1).CanCancel)
          End If
          .AddFormAction("PaymentArrangementAdd", "Make a Payment Arrangement", account.CanAddPaymentArrangement).ShowInWebInterfaces = True
          .AddFormAction("PaymentPromiseAdd", "Make a Payment Promise", account.CanAddPaymentPromise).ShowInWebInterfaces = True
        End With
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Payment Schedule (Version 1.01, Last updated 19/04/2016).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="account">
  '''  The Account to summarise.
  ''' </param>
  ''' <param name="payOverdues">
  '''  Indicates whether to show the Schedule given Overdue paid off today.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Payments page and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_PaymentSchedule(callerScriptInfo As ISScriptExecutionInfo,
                                                      account As finAccount,
                                                      payOverdues As Boolean,
                                             Optional includeActions As Boolean = True,
                                             Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim AccountCalc As finAccountCalc
    Dim AccountCalcSchedule As finAccountCalcSchedule
    Dim AccountCalcScheduleItem As finAccountCalcScheduleItem
    Dim Balance As Decimal
    Dim DateAsAt As Date
    Dim DirectDebits As Decimal
    Dim DueToday As Decimal
    Dim Include As Boolean
    Dim MinimumPaymentCount As Integer
    Dim MinimumPaymentDateTo As Date
    Dim Overdue As Decimal
    Dim OverdueDescription As String
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Date As At
    DateAsAt = finBL.TimeZoneFunctions.GetCurrentDatabaseDate()

    ' Get Required Information
    account.GetBalance(Balance)
    If (Not account.AccountType.ShowOverdue) AndAlso account.AccountType.ShowContractualOverdue Then
      OverdueDescription = "Contractual Overdue"
      account.GetBalanceOverdueContractual(Overdue, DateAsAt)
    Else
      OverdueDescription = "Overdue"
      account.GetBalanceOverdue(Overdue, DateAsAt)
    End If
    DueToday = account.Calculation.TotalNonDirectDebitPaymentsDueToday
    account.GetDirectDebitsAwaitingProcessing(0, DirectDebits, #12/31/9999#)
    If payOverdues Then
      If (Overdue - DirectDebits) > 0 Then
        ' Create Calculation object and calculate
        AccountCalc = finBL.CreateAccountCalc(account)
        With AccountCalc
          .LoadAccount()
          .SetModeTransactionEntry()
          .WhatIfs.AddPayment(account.AccountType.ElementLinks.ItemByElementLinkType(isefinAccountTypeElementLinkType.Payment).ElementPk, DateAsAt, "Payment", "Payment to clear " & OverdueDescription, (Overdue - DirectDebits), isefinAccountTransactionAllocationMethod.Automatic, 0, 0, 0, 0, 0, 0, 0)
          .CalculateExisting()
        End With

        AccountCalcSchedule = AccountCalc.Schedule
      Else
        ' Not Overdue, so just use current Schedule
        AccountCalcSchedule = account.Calculation.Schedule
      End If
    Else
      AccountCalcSchedule = account.Calculation.Schedule
    End If

    ' If not paying Overdues, show the overdue balance
    If Not payOverdues Then
      If Balance < 0 Then
        Warnings &= "{{Info|CREDIT Balance of " & finBL.FormatCurrency(-Balance, True) & ".}}"
      ElseIf Overdue > 0 Then
        If (Overdue - DueToday - DirectDebits) > 0 Then
          Warnings &= "{{Warning|" & OverdueDescription & " " & finBL.FormatCurrency(Overdue, True) & ".}}"
        End If
      ElseIf Overdue < 0 Then
        Warnings &= "{{Info|Prepaid " & finBL.FormatCurrency(-Overdue, True) & ".}}"
      End If
    End If

    ' Warning if NOT paid off at the end of the Calculation
    Select Case account.AccountClass
      Case isefinAccountClass.LoanFR, isefinAccountClass.LoanFT
        If AccountCalcSchedule.Count > 0 AndAlso AccountCalcSchedule(AccountCalcSchedule.Count - 1).Balance > account.Calculation.ResidualValue Then
          Warnings &= "{{Warning|Payments are insufficient to pay off the Account.}}"
        End If
    End Select

    ' Find date to list Minimum Payments to
    Select Case account.AccountClass
      Case isefinAccountClass.LoanRC
        MinimumPaymentCount = 3 ' Only show the next 3 Minimum Payments
        MinimumPaymentDateTo = DateAsAt
        For Each AccountCalcScheduleItem In AccountCalcSchedule
          If AccountCalcScheduleItem.IsExisting Then
          Else
            Select Case AccountCalcScheduleItem.ScheduleType
              Case isefinAccountCalcScheduleType.Payment, isefinAccountCalcScheduleType.PaymentAdditional, isefinAccountCalcScheduleType.PaymentOverridden, isefinAccountCalcScheduleType.PaymentPromise, isefinAccountCalcScheduleType.PaymentBalloon
                If AccountCalcScheduleItem.ScheduleSubType = isefinAccountCalcScheduleSubType.PaymentGrace Then
                ElseIf AccountCalcScheduleItem.Value < 0 OrElse AccountCalcScheduleItem.TransactionValue < 0 Then
                  ' Reset Minimum Payment Count
                  MinimumPaymentCount = 3
                End If
              Case isefinAccountCalcScheduleType.PaymentMinimum
                If MinimumPaymentCount <= 0 Then
                ElseIf AccountCalcScheduleItem.ScheduleSubType = isefinAccountCalcScheduleSubType.PaymentGrace Then
                ElseIf AccountCalcScheduleItem.Value < 0 OrElse AccountCalcScheduleItem.TransactionValue < 0 Then
                  MinimumPaymentDateTo = AccountCalcScheduleItem.Date
                  MinimumPaymentCount -= 1
                End If
              Case isefinAccountCalcScheduleType.WhatIf
                ' Reset Minimum Payment Count
                MinimumPaymentCount = 3
            End Select
          End If
        Next
    End Select

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .AutoStripe = True
      .Caption = ""

      ' Warnings (most shown at top on this summary)
      .TextBefore = Warnings
      Warnings = ""

      ' Columns
      With .Columns
        .AddDate("Date")
        .AddCode("Reference", 10) ' Code so it does not word break
        .AddText("Notes")
        .AddCurrency("Value")
      End With

      For Each AccountCalcScheduleItem In AccountCalcSchedule
        ' Include?
        If AccountCalcScheduleItem.IsExisting Then
          Include = False
        Else
          Select Case AccountCalcScheduleItem.ScheduleType
            Case isefinAccountCalcScheduleType.Payment, isefinAccountCalcScheduleType.PaymentAdditional, isefinAccountCalcScheduleType.PaymentBalloon, isefinAccountCalcScheduleType.PaymentOverridden, isefinAccountCalcScheduleType.PaymentPromise, isefinAccountCalcScheduleType.PaymentTransaction
              If AccountCalcScheduleItem.ScheduleSubType = isefinAccountCalcScheduleSubType.PaymentGrace Then
                Include = False
              ElseIf AccountCalcScheduleItem.Value < 0 OrElse AccountCalcScheduleItem.TransactionValue < 0 Then
                Include = True
              Else
                Include = False
              End If

            Case isefinAccountCalcScheduleType.PaymentMinimum
              If AccountCalcScheduleItem.Date > MinimumPaymentDateTo Then
                Include = False
              ElseIf AccountCalcScheduleItem.ScheduleSubType = isefinAccountCalcScheduleSubType.PaymentGrace Then
                Include = False
              ElseIf AccountCalcScheduleItem.Value < 0 OrElse AccountCalcScheduleItem.TransactionValue < 0 Then
                Include = True
              Else
                Include = False
              End If

            Case isefinAccountCalcScheduleType.WhatIf
              Include = True

            Case Else
              Include = False
          End Select
        End If

        ' Add Row
        If Include Then
          With .Rows.Add().Cells
            .AddDate(AccountCalcScheduleItem.Date)
            .AddText(AccountCalcScheduleItem.Reference)
            If AccountCalcScheduleItem.ScheduleType = isefinAccountCalcScheduleType.PaymentMinimum Then
              .AddWiki("!!Estimated payment!!")
            Else
              .AddText(AccountCalcScheduleItem.Notes)
            End If
            Select Case AccountCalcScheduleItem.ScheduleSubType
              Case isefinAccountCalcScheduleSubType.None, isefinAccountCalcScheduleSubType.PaymentAlternateSchedule, isefinAccountCalcScheduleSubType.PaymentStandardTransaction
                .AddCurrency(-AccountCalcScheduleItem.Value)
              Case Else
                .AddCurrency(-AccountCalcScheduleItem.TransactionValue)
            End Select
          End With
        End If
      Next

      ' Clear Table if no Payments listed
      If .Rows.Count = 1 Then
        .Rows.Clear()
        Warnings &= "{{info|No further payments listed.}}"
      Else
        ' Warning if NOT paid off at the end of the Calculation
        Select Case account.AccountClass
          Case isefinAccountClass.LoanFR, isefinAccountClass.LoanFT
            If AccountCalcSchedule.Count > 0 AndAlso AccountCalcSchedule(AccountCalcSchedule.Count - 1).Balance > account.Calculation.ResidualValue Then
              Warnings &= "{{Warning|Balance of " & finBL.FormatCurrency(AccountCalcSchedule(AccountCalcSchedule.Count - 1).Balance - account.Calculation.ResidualValue, True) & " remains outstanding.}}"
            End If
            If account.Calculation.ResidualValue <> 0 Then
              Warnings &= "{{Info|Residual Value of " & finBL.FormatCurrency(account.Calculation.ResidualValue, True) & ".}}"
            End If
        End Select
      End If

      ' Warnings
      .TextAfter = Warnings

      ' Actions
      If includeActions Then
        With .Actions
          '.Add("PaymentPromiseAdd", "Make a Payment Promise", Not finBL.Database.IsReadOnly AndAlso account.Status = isefinAccountStatus.Open AndAlso finBL.CurrentUser.Permissions.Allow("Account.PaymentPromiseAdd"))
        End With
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Payment Statistics (Version 1.02, Last updated 19/04/2016).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="account">
  '''  The Account to summarise.
  ''' </param>
  ''' <param name="lastReversedPaymentDaysMaximum">
  '''  The Maximum Days for warning since last Reversed Payment.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Payments page and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_PaymentStatistics(callerScriptInfo As ISScriptExecutionInfo,
                                                        account As finAccount,
                                               Optional lastReversedPaymentDaysMaximum As Integer = 120,
                                               Optional includeActions As Boolean = True,
                                               Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim DateAsAt As Date
    Dim Days As Integer
    Dim LastPaymentDate As Date
    Dim LastPaymentValue As Decimal
    Dim LastReversedPaymentDate As Date
    Dim LastReversedPaymentDateReversed As Date
    Dim LastReversedPaymentValue As Decimal
    Dim NextPaymentDate As Date
    Dim NextPaymentValue As Decimal
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Date As At
    DateAsAt = finBL.TimeZoneFunctions.GetCurrentDatabaseDate()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      .Columns.AddText(16).NoBreakChars = 16
      .Columns.AddText()

      With .Rows
        Select Case account.Status
          Case isefinAccountStatus.Open
            If account.TotalPayments = 0 Then
              Warnings &= "{{Info|No payment has been made on this Account yet.}}"
            Else
              ' Total Payments
              .AddCaptionCurrency("Total Payments:", account.TotalPayments, True)

              ' Last Payment
              account.GetLastPayment(LastPaymentDate, LastPaymentValue)
              .AddCaptionWiki("Last Payment:", String.Format("**{0}** --on-- **{1}**", finBL.FormatCurrency(LastPaymentValue, True), finBL.FormatDateLong(LastPaymentDate)))
            End If

            ' Next Payment
            account.GetNextPayment(NextPaymentDate, NextPaymentValue)
            If NextPaymentDate = Nothing Then
              Select Case account.AccountClass
                Case isefinAccountClass.LoanFR, isefinAccountClass.LoanFT
                  Warnings &= "{{Warning|No further payments listed for this Account.}}"
              End Select
            Else
              .AddCaptionWiki("Next Payment:", String.Format("**{0}** --on-- **{1}**", finBL.FormatCurrency(NextPaymentValue, True), finBL.FormatDateLong(NextPaymentDate)))
            End If

          Case isefinAccountStatus.Closed, isefinAccountStatus.ClosedPending
            If account.TotalPayments = 0 Then
              Warnings &= "{{Info|No payments were made on this Account.}}"
            Else
              ' Total Payments
              .AddCaptionCurrency("Total Payments:", account.TotalPayments, True)

              ' Last Payment
              account.GetLastPayment(LastPaymentDate, LastPaymentValue)
              .AddCaptionWiki("Last Payment:", String.Format("**{0}** --on-- **{1}**", finBL.FormatCurrency(LastPaymentValue, True), finBL.FormatDateLong(LastPaymentDate)))
            End If
        End Select
      End With

      ' Warnings
      account.GetLastReversedPayment(LastReversedPaymentDate, LastReversedPaymentValue, LastReversedPaymentDateReversed)
      If LastReversedPaymentDateReversed <> Nothing Then
        Days = CInt(DateDiff(DateInterval.Day, LastReversedPaymentDateReversed.Date, DateAsAt))
        If Days < lastReversedPaymentDaysMaximum OrElse LastReversedPaymentDateReversed > LastPaymentDate Then
          If LastReversedPaymentDate = Nothing Then
            Warnings &= "{{Warning|" & String.Format("Last Reversed Payment: **{0}**, reversed on **{1}**.", finBL.FormatCurrency(LastReversedPaymentValue, True), finBL.FormatDateLong(LastReversedPaymentDateReversed)) & "}}"
          Else
            Warnings &= "{{Warning|" & String.Format("Last Reversed Payment: **{0}** dated **{1}**, reversed on **{2}**.", finBL.FormatCurrency(LastReversedPaymentValue, True), finBL.FormatDateLong(LastReversedPaymentDate), finBL.FormatDateLong(LastReversedPaymentDateReversed)) & "}}"
          End If
        End If
      End If
      .TextAfter = Warnings

      ' Actions
      If includeActions Then
        With .Actions
        End With
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Overdue Aged Breakdown (Version 1.01, Last updated 07/07/2015).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="accountOverdues">
  '''  A finAccountOverdues object.
  ''' </param>
  ''' <param name="showFullBreakdown">
  '''  Indicates whether to show a Full Breakdown, i.e., all bands, even if no transactions fall within that band.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Status page and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_OverdueAgedBreakdown(callerScriptInfo As ISScriptExecutionInfo,
                                                           accountOverdues As finAccountOverdues,
                                                           showFullBreakdown As Boolean,
                                                  Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim AccountOverdue As finAccountOverdue
    Dim Breakdown(8) As Decimal
    Dim BreakdownDescription() As String
    Dim i As Integer
    Dim MaxLevel As Integer
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Define Breakdown Descriptions
    BreakdownDescription = New String() {"", "1-30 days", "31-60 days", "61-90 days", "91-120 days", "121-150 days", "151-180 days", "181+ days"}

    ' Calculate Breakdown
    For Each AccountOverdue In accountOverdues
      Breakdown(0) += AccountOverdue.ValueDue
      Select Case DateDiff(DateInterval.Day, AccountOverdue.Date, accountOverdues.DateAsAtResolved)
        Case 0 : Breakdown(8) += AccountOverdue.ValueDue
        Case Is <= 30 : Breakdown(1) += AccountOverdue.ValueDue
        Case Is <= 60 : Breakdown(2) += AccountOverdue.ValueDue
        Case Is <= 90 : Breakdown(3) += AccountOverdue.ValueDue
        Case Is <= 120 : Breakdown(4) += AccountOverdue.ValueDue
        Case Is <= 150 : Breakdown(5) += AccountOverdue.ValueDue
        Case Is <= 180 : Breakdown(6) += AccountOverdue.ValueDue
        Case Else : Breakdown(7) += AccountOverdue.ValueDue
      End Select
    Next

    ' Find the Maximum Breakdown level to display
    If showFullBreakdown Then
      MaxLevel = Breakdown.Length - 2
    Else
      MaxLevel = 1
      For i = 2 To Breakdown.Length - 2
        If Breakdown(i) <> 0 Then MaxLevel = i
      Next
    End If

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .AutoStripe = True
      .Caption = ""
      .Columns.AddText(18)
      .Columns.AddCurrency()

      ' Breakdown Rows
      For i = 1 To MaxLevel
        With .Rows.Add().Cells
          .AddCaption(BreakdownDescription(i))
          .AddCurrency(Breakdown(i))
        End With
      Next

      ' Total
      With .Rows.Add(iseSummaryTableRowClass.FooterBold).Cells
        .AddCaption("Total")
        .AddCurrency(Breakdown(0) - Breakdown(Breakdown.Length - 1), True)
      End With

      ' Due Today
      If Breakdown(Breakdown.Length - 1) <> 0 Then
        With .Rows.Add().Cells
          .AddCaption("Due today")
          .AddCurrency(Breakdown(Breakdown.Length - 1))
        End With

        With .Rows.Add(iseSummaryTableRowClass.FooterBold).Cells
          .AddCaption("Total")
          .AddCurrency(Breakdown(0), True)
        End With
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Overdue Transactions (Version 1.01, Last updated 30/09/2020).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="accountOverdues">
  '''  A finAccountOverdues object.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Status page and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_OverdueTransactions(callerScriptInfo As ISScriptExecutionInfo,
                                                          accountOverdues As finAccountOverdues,
                                                 Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim AccountOverdue As finAccountOverdue
    Dim ShowUnadjustedDateColumn As Boolean
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Find Columns to include
    ShowUnadjustedDateColumn = accountOverdues.HasDateAdjustments

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .AutoStripe = True
      .Caption = ""

      ' Columns (alignment for Column 2 may be adjusted later based on Account Status)
      With .Columns
        .AddDate("Date")
        If ShowUnadjustedDateColumn Then .AddDate("Unadjusted")
        .AddText("Type")
        .AddText("Reference")
        .AddText("Notes")
        .AddCurrency("Overdue")
        .AddCurrency("Original")
      End With

      For Each AccountOverdue In accountOverdues
        With .Rows.Add()
          ' Make 'Promise Due' row red
          If AccountOverdue.ScheduleType = isefinAccountCalcScheduleType.PaymentDuePromise Then
            .ForegroundColour = "red"
          End If

          With .Cells
            ' Date
            If AccountOverdue.Date = accountOverdues.DateAsAtResolved Then
              .AddText("Due today")
            Else
              .AddDate(AccountOverdue.Date)
            End If

            ' Unadjusted
            If ShowUnadjustedDateColumn Then
              If AccountOverdue.Date = AccountOverdue.DateUnadjusted Then
                .AddText("")
              Else
                .AddDate(AccountOverdue.DateUnadjusted)
              End If
            End If

            ' Type
            If AccountOverdue.ScheduleType = isefinAccountCalcScheduleType.Transaction Then
              Select Case AccountOverdue.TransactionSource
                Case isefinTransactionSource.AccountBalanceAdjustment
                  .AddText("Adjustment")
                Case Else
                  .AddText("")
              End Select
            Else
              .AddText(AccountOverdue.ScheduleTypeText).NoWrap = True
            End If

            ' Reference
            If AccountOverdue.Reference = AccountOverdue.ScheduleTypeText Then
              .AddText("")
            Else
              .AddText(AccountOverdue.Reference).NoWrap = True
            End If

            ' Notes
            If AccountOverdue.Notes = AccountOverdue.ScheduleTypeText Then
              .AddText("")
            Else
              .AddText(AccountOverdue.Notes)
            End If

            ' Overdue
            .AddCurrency(AccountOverdue.ValueDue)

            ' Original
            If AccountOverdue.ValueDue <> AccountOverdue.ValueDueOriginal Then
              .AddCurrency(AccountOverdue.ValueDueOriginal)
            Else
              .AddText("")
            End If
          End With
        End With
      Next

      ' Warnings
      .TextAfter = Warnings
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Restructure Changes Summary (Version 1.01, Last updated 08/06/2017).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="accountRestructure">
  '''  The Account Restructure object.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Restructure wizard.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Summary of Restructure details.</description></item>
  '''    <item><code>Maturity</code><description>Summary of Maturity details.</description></item>
  '''    <item><code>Interest</code><description>Summary of Interest details.</description></item>
  '''    <item><code>Payments</code><description>Summary of Payment details.</description></item>
  '''    <item><code>CreditLimits</code><description>Summary of Credit Limit details (if relevant).</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_Restructure_Changes(callerScriptInfo As ISScriptExecutionInfo,
                                                          accountRestructure As finAccountRestructure,
                                                 Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables


    Dim AccountCalc As finAccountCalc
    Dim AccountCalcPayment As finAccountCalcPayment
    Dim Balance As Decimal
    Dim BalloonPaymentDate As Date
    Dim BalloonPaymentValue As Decimal
    Dim DateCycle As finDateCycle
    Dim DateMaturity As Date
    Dim Days As Long
    Dim FutureChange1 As Boolean
    Dim FutureChange2 As Boolean
    Dim FutureChange3 As Boolean
    Dim strTemp1 As String
    Dim strTemp2 As String
    Dim SummaryTableCreditLimits As ISSummaryTable
    Dim SummaryTableInterest As ISSummaryTable
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTableMaturity As ISSummaryTable
    Dim SummaryTablePayments As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    If accountRestructure.CalculationNew.AccountType.CreditLimitCount <> 0 Then SummaryTableCreditLimits = finBL.CreateSummaryTable()
    SummaryTableInterest = finBL.CreateSummaryTable()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTableMaturity = finBL.CreateSummaryTable()
    SummaryTablePayments = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    If accountRestructure.CalculationNew.IsCalculationRequired Then
      ' Ignore
    Else
      ' Calculate
      AccountCalc = accountRestructure.CalculationNew
      AccountCalc.DateMaturityResolved(DateMaturity, True)
      AccountCalc.GetPaymentBalloon(BalloonPaymentDate, BalloonPaymentValue)
      If AccountCalc.Schedule.Count = 0 Then
        Balance = 0
      Else
        Balance = AccountCalc.Schedule(AccountCalc.Schedule.Count - 1).Balance
      End If

      ' Details
      With SummaryTableMain
        ' Initialise
        Warnings = ""
        .TableClass = iseSummaryTableClass.Information
        .Caption = "Details"
        .AutoStripe = True

        ' Columns
        With .Columns
          .AddText(17).NoBreakChars = 17
          .AddText(25, iseSummaryTableCellTextAlign.Right)
          .AddText()
        End With

        With .Rows
          .AddCaptionDate("Date Opened:", AccountCalc.OpeningDate)
          .AddCaptionDate("Restructured:", AccountCalc.DateRestructured)
          If Len(AccountCalc.RestructureType) <> 0 Then
            .AddCaptionText("Type:", AccountCalc.RestructureType)
          End If
        End With

        ' Warnings
        .TextAfter = Warnings
      End With

      ' Maturity
      With SummaryTableMaturity
        ' Initialise
        Warnings = ""
        .TableClass = iseSummaryTableClass.Information
        .Caption = "Maturity"
        .AutoStripe = True

        ' Columns
        With .Columns
          .AddText(17).NoBreakChars = 17
          .AddText(21, iseSummaryTableCellTextAlign.Right)
          .AddText()
        End With

        With .Rows
          If DateMaturity = Nothing Then
            With .AddCaptionText("Maturity Date:", "")
              .Cells.AddWiki("--!!**Payments Insufficient**!!--")
            End With
          Else
            If DateMaturity > AccountCalc.DateMaturity Then
              Days = DateDiff(DateInterval.Day, AccountCalc.DateMaturity, DateMaturity)
              With .AddCaptionDate("Maturity Date:", DateMaturity)
                .Cells.AddWiki(String.Format("--!!Extends Maturity by **{0}** day{1}!!--", Days, IIf(Days = 1, "", "s")))
              End With
            ElseIf DateMaturity < AccountCalc.DateMaturity Then
              Days = DateDiff(DateInterval.Day, DateMaturity, AccountCalc.DateMaturity)
              With .AddCaptionDate("Maturity Date:", DateMaturity)
                .Cells.AddWiki(String.Format("--++Shortens Maturity by **{0}** day{1}++--", Days, IIf(Days = 1, "", "s")))
              End With
            Else
              .AddCaptionDate("Maturity Date:", DateMaturity)
            End If

            ' Remaining Period
            DateCycle = finBL.Utilities.DateCycleGetDifference(accountRestructure.RestructureDate, DateMaturity, AccountCalc.PaymentCycle, Days)
            With .AddCaptionText("Remaining:", DateCycle.CycleDescription)
              If Days <> 0 Then .Cells.AddWiki(String.Format("--plus {0} day{1}--", Days, IIf(Days = 1, "", "s")))
            End With
          End If

          If AccountCalc.ResidualValue <> 0 Then
            If accountRestructure.CalculationCurrent.ResidualValue = 0 Then
              With .AddCaptionCurrency("Residual Value:", AccountCalc.ResidualValue, True)
                .Cells.AddWiki("--!!**Added**!!--")
              End With
            ElseIf accountRestructure.CalculationCurrent.ResidualValue = AccountCalc.ResidualValue Then
              .AddCaptionCurrency("Residual Value:", AccountCalc.ResidualValue, True)
            Else
              With .AddCaptionCurrency("Residual Value:", AccountCalc.ResidualValue, True)
                .Cells.AddWiki(String.Format("--!!Updated from **{0}**!!--", finBL.FormatCurrency(accountRestructure.CalculationCurrent.ResidualValue, True)))
              End With
            End If

            ' Warning
            If AccountCalc.ResidualValue <> Balance Then
              Warnings &= "{{Warning|Residual Value is greater than the remaining balance of " & finBL.FormatCurrency(Balance, True) & ".}}"
            End If
          ElseIf accountRestructure.CalculationCurrent.ResidualValue <> 0 Then
            With .AddCaptionCurrency("Residual Value:", AccountCalc.ResidualValue, True)
              .Cells.AddWiki(String.Format("--!!Removed, was **{0}**!!--", finBL.FormatCurrency(accountRestructure.CalculationCurrent.ResidualValue, True)))
            End With
          End If
        End With

        ' Warnings
        .TextAfter = Warnings
      End With

      ' Interest
      With SummaryTableInterest
        ' Initialise
        Warnings = ""
        .TableClass = iseSummaryTableClass.Information
        .Caption = "Interest"
        .AutoStripe = True

        ' Columns
        With .Columns
          .AddText(17).NoBreakChars = 17
          .AddText(21, iseSummaryTableCellTextAlign.Right)
          .AddText()
        End With

        With .Rows
          If accountRestructure.CalculationCurrent.InterestCycle = AccountCalc.InterestCycle Then
            .AddCaptionText("Charged:", AccountCalc.InterestCycleDescription)
          Else
            With .AddCaptionText("Charged:", AccountCalc.InterestCycleDescription)
              .Cells.AddWiki(String.Format("--!!Updated from **{0}**!!--", accountRestructure.CalculationCurrent.InterestCycleDescription))
            End With
          End If

          Select Case accountRestructure.CalculationCurrent.InterestType
            Case isefinAccountInterestType.InterestFree
              strTemp1 = "Interest Free"
            Case Else
              strTemp1 = finBL.FormatPercentage(accountRestructure.CalculationCurrent.InterestRate / 100, 4)
          End Select
          Select Case AccountCalc.InterestType
            Case isefinAccountInterestType.InterestFree
              strTemp2 = "Interest Free"
            Case Else
              strTemp2 = finBL.FormatPercentage(AccountCalc.InterestRate / 100, 4)
          End Select
          If strTemp1 = strTemp2 Then
            .AddCaptionText("Rate:", strTemp2)
          Else
            With .AddCaptionText("Rate:", strTemp2)
              .Cells.AddWiki(String.Format("--!!Updated from **{0}**!!--", strTemp1))
            End With
          End If

          ' Future change warnings?
          If accountRestructure.Account.GetDefaultInterestRate(accountRestructure.RestructureDate, 0, 0, "", FutureChange1) Then
            If FutureChange1 Then Warnings &= "{{Warning|Future Default Interest Rate changes will be cancelled.}}"
          End If
          If accountRestructure.Account.GetOtherInterestRate(accountRestructure.RestructureDate, 0, 0, "", FutureChange1) Then
            If FutureChange1 Then Warnings &= "{{Warning|Future Other Interest Rate changes will be cancelled.}}"
          End If
        End With

        ' Warnings
        .TextAfter = Warnings
      End With

      ' Payments
      With SummaryTablePayments
        ' Initialise
        Warnings = ""
        .TableClass = iseSummaryTableClass.Information
        .Caption = "Payments"
        .AutoStripe = True

        ' Columns
        With .Columns
          .AddText(17).NoBreakChars = 17
          .AddText(21, iseSummaryTableCellTextAlign.Right)
          .AddText()
        End With

        With .Rows
          If AccountCalc.PaymentRegular = 0 Then
            With .AddCaptionCurrency("Payment:", AccountCalc.PaymentRegular, True)
              .Cells.AddWiki("--!!**Nil**!!--")
            End With
          ElseIf AccountCalc.PaymentRegular > accountRestructure.CalculationCurrent.PaymentRegular Then
            With .AddCaptionCurrency("Payment:", AccountCalc.PaymentRegular, True)
              .Cells.AddWiki(String.Format("--!!Increased by **{0}**!!--", finBL.FormatCurrency(AccountCalc.PaymentRegular - accountRestructure.CalculationCurrent.PaymentRegular, True)))
            End With
          ElseIf AccountCalc.PaymentRegular < accountRestructure.CalculationCurrent.PaymentRegular Then
            With .AddCaptionCurrency("Payment:", AccountCalc.PaymentRegular, True)
              .Cells.AddWiki(String.Format("--!!Decreased by **{0}**!!--", finBL.FormatCurrency(accountRestructure.CalculationCurrent.PaymentRegular - AccountCalc.PaymentRegular, True)))
            End With
          Else
            .AddCaptionCurrency("Payment:", AccountCalc.PaymentRegular, True)
          End If

          If AccountCalc.PaymentBalloon <> 0 Then
            If AccountCalc.PaymentBalloon = BalloonPaymentValue Then
              strTemp1 = ""
            Else
              strTemp1 = String.Format(" Actual {0}", finBL.FormatCurrency(BalloonPaymentValue, True))
            End If

            If accountRestructure.CalculationCurrent.PaymentBalloon = 0 Then
              With .AddCaptionCurrency("Balloon Payment:", AccountCalc.PaymentBalloon, True)
                .Cells.AddWiki(String.Format("--!!**Added**!!{0}--", strTemp1))
              End With
            ElseIf accountRestructure.CalculationCurrent.PaymentBalloon = AccountCalc.PaymentBalloon Then
              .AddCaptionCurrency("Balloon Payment:", AccountCalc.PaymentBalloon, True)
            Else
              With .AddCaptionCurrency("Balloon Payment:", AccountCalc.PaymentBalloon, True)
                .Cells.AddWiki(String.Format("--!!Updated from **{0}**!!--", finBL.FormatCurrency(accountRestructure.CalculationCurrent.PaymentBalloon, True)))
              End With
            End If
          ElseIf accountRestructure.CalculationCurrent.PaymentBalloon <> 0 Then
            With .AddCaptionCurrency("Residual Value:", AccountCalc.ResidualValue, True)
              .Cells.AddWiki(String.Format("--!!Removed, was **{0}**!!--", finBL.FormatCurrency(accountRestructure.CalculationCurrent.PaymentBalloon, True)))
            End With
          End If

          If AccountCalc.PaymentFinalDate = Nothing Then
            With .AddCaptionText("Total Payments:", "")
              .Cells.AddWiki("--!!**Payments Insufficient**!!--")
            End With
          Else
            .AddCaptionCurrency("Total Payments:", AccountCalc.Schedule.TotalPayments)
          End If

          ' Ignored Overriding Payments
          For Each AccountCalcPayment In accountRestructure.CalculationNew.Payments
            If AccountCalcPayment.Ignored Then
              Warnings &= "{{Warning|One or more Overriding Payments were not included.}}"
              Exit For
            End If
          Next
        End With

        ' Warnings
        .TextAfter = Warnings
      End With

      ' Credit Limits
      If SummaryTableCreditLimits IsNot Nothing Then
        With SummaryTableCreditLimits
          ' Initialise
          Warnings = ""
          .TableClass = iseSummaryTableClass.Information
          .Caption = "Credit Limits"
          .AutoStripe = True

          ' Columns
          With .Columns
            .AddText(17).NoBreakChars = 17
            .AddText(21, iseSummaryTableCellTextAlign.Right)
            .AddText()
          End With

          With .Rows
            If AccountCalc.CreditLimit1 > accountRestructure.OriginalCreditLimit1 Then
              With .AddCaptionCurrency(AccountCalc.AccountType.CreditLimit1DescriptionResolved & ":", AccountCalc.CreditLimit1)
                .Cells.AddWiki(String.Format("--!!Increased by **{0}**!!--", finBL.FormatCurrency(AccountCalc.CreditLimit1 - accountRestructure.OriginalCreditLimit1, True)))
              End With
            ElseIf AccountCalc.CreditLimit1 < accountRestructure.OriginalCreditLimit1 Then
              With .AddCaptionCurrency(AccountCalc.AccountType.CreditLimit1DescriptionResolved & ":", AccountCalc.CreditLimit1)
                .Cells.AddWiki(String.Format("--!!Decreased by **{0}**!!--", finBL.FormatCurrency(accountRestructure.OriginalCreditLimit1 - AccountCalc.CreditLimit1, True)))
              End With
            Else
              .AddCaptionCurrency(AccountCalc.AccountType.CreditLimit1DescriptionResolved & ":", AccountCalc.CreditLimit1)
            End If

            If AccountCalc.AccountType.CreditLimitCount > 1 Then
              If AccountCalc.CreditLimit2 > accountRestructure.OriginalCreditLimit2 Then
                With .AddCaptionCurrency(AccountCalc.AccountType.CreditLimit2DescriptionResolved & ":", AccountCalc.CreditLimit2)
                  .Cells.AddWiki(String.Format("--!!Increased by **{0}**!!--", finBL.FormatCurrency(AccountCalc.CreditLimit2 - accountRestructure.OriginalCreditLimit2, True)))
                End With
              ElseIf AccountCalc.CreditLimit2 < accountRestructure.OriginalCreditLimit2 Then
                With .AddCaptionCurrency(AccountCalc.AccountType.CreditLimit2DescriptionResolved & ":", AccountCalc.CreditLimit2)
                  .Cells.AddWiki(String.Format("--!!Decreased by **{0}**!!--", finBL.FormatCurrency(accountRestructure.OriginalCreditLimit2 - AccountCalc.CreditLimit2, True)))
                End With
              Else
                .AddCaptionCurrency(AccountCalc.AccountType.CreditLimit2DescriptionResolved & ":", AccountCalc.CreditLimit2)
              End If
            End If

            If AccountCalc.AccountType.CreditLimitCount > 2 Then
              If AccountCalc.CreditLimit3 > accountRestructure.OriginalCreditLimit3 Then
                With .AddCaptionCurrency(AccountCalc.AccountType.CreditLimit3DescriptionResolved & ":", AccountCalc.CreditLimit3)
                  .Cells.AddWiki(String.Format("--!!Increased by **{0}**!!--", finBL.FormatCurrency(AccountCalc.CreditLimit3 - accountRestructure.OriginalCreditLimit3, True)))
                End With
              ElseIf AccountCalc.CreditLimit3 < accountRestructure.OriginalCreditLimit3 Then
                With .AddCaptionCurrency(AccountCalc.AccountType.CreditLimit3DescriptionResolved & ":", AccountCalc.CreditLimit3)
                  .Cells.AddWiki(String.Format("--!!Decreased by **{0}**!!--", finBL.FormatCurrency(accountRestructure.OriginalCreditLimit3 - AccountCalc.CreditLimit3, True)))
                End With
              Else
                .AddCaptionCurrency(AccountCalc.AccountType.CreditLimit3DescriptionResolved & ":", AccountCalc.CreditLimit3)
              End If
            End If

            ' Future change warnings?
            If accountRestructure.Account.GetCreditLimits(accountRestructure.RestructureDate, 0, 0, 0, "", FutureChange1, FutureChange2, FutureChange3) Then
              If FutureChange1 Then Warnings &= "{{Warning|Future " & AccountCalc.AccountType.CreditLimit1DescriptionResolved & " changes will be cancelled.}}"
              If FutureChange2 Then Warnings &= "{{Warning|Future " & AccountCalc.AccountType.CreditLimit2DescriptionResolved & " changes will be cancelled.}}"
              If FutureChange3 Then Warnings &= "{{Warning|Future " & AccountCalc.AccountType.CreditLimit3DescriptionResolved & " changes will be cancelled.}}"
            End If
          End With

          ' Warnings
          .TextAfter = Warnings
        End With
      End If

      ' Add Summary Tables
      SummaryTables.Add("Main", SummaryTableMain)
      SummaryTables.Add("Maturity", SummaryTableMaturity)
      SummaryTables.Add("Interest", SummaryTableInterest)
      SummaryTables.Add("Payments", SummaryTablePayments)
      If SummaryTableCreditLimits IsNot Nothing Then SummaryTables.Add("CreditLimits", SummaryTableCreditLimits)
    End If

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Schedule Allocations Summary.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="account">
  '''  The Account to summarise.
  ''' </param>
  ''' <param name="accountCalcSchedule">
  '''  The Account Schedule to summarise.
  ''' </param>
  ''' <param name="index">
  '''  The Schedule Item's index to use.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Schedule drilldown form.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Summary.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_ScheduleAllocations(callerScriptInfo As ISScriptExecutionInfo,
                                                          account As finAccount,
                                                          accountCalcSchedule As finAccountCalcSchedule,
                                                          index As Integer,
                                                 Optional includeActions As Boolean = True,
                                                 Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' Account_ScheduleAllocations
    '
    ' Version 1.02 (07/01/2022)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.01  31/03/2020  ISS                  
    '    1.02  07/01/2022  ISS      J028119   Allocations not showing when expected            
    ' #################################################################

    Dim AccountCalcScheduleItem As finAccountCalcScheduleItem
    Dim strTemp As String
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Information
    If accountCalcSchedule Is Nothing OrElse index < 0 OrElse index > accountCalcSchedule.Count Then
      AccountCalcScheduleItem = Nothing
    Else
      AccountCalcScheduleItem = accountCalcSchedule(index)
    End If

    ' Summary table
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .AutoStripe = True
      .Caption = ""

      ' Clear Warnings
      Warnings = ""

      If AccountCalcScheduleItem Is Nothing Then
      ElseIf AccountCalcScheduleItem.Value = 0 AndAlso (AccountCalcScheduleItem.HighCostLoanAdjustmentType = isefinAccountTransactionHCLAdjustmentType.NotApplicable) AndAlso (AccountCalcScheduleItem.ValueAllocatedFeeIB = 0 AndAlso AccountCalcScheduleItem.ValueAllocatedFeeNIB = 0 AndAlso AccountCalcScheduleItem.ValueAllocatedInterest = 0 AndAlso AccountCalcScheduleItem.ValueAllocatedPrincipalIB = 0 AndAlso AccountCalcScheduleItem.ValueAllocatedPrincipalNIB = 0) AndAlso AccountCalcScheduleItem.Overdue = 0 AndAlso AccountCalcScheduleItem.OverdueContractual = 0 Then
        .TextBefore = "{{info|Allocations are not applicable to this Transaction.}}"
      Else
        ' Columns
        With .Columns
          .AddText(" ")
          .AddCurrency("Transaction", 16)
          .AddCurrency("Balance", 18)
        End With

        With .Rows
          ' Value Allocations
          Select Case account.AccountClass
            Case isefinAccountClass.Deposit
              If AccountCalcScheduleItem.ValueAllocatedPrincipalNIB <> 0 OrElse AccountCalcScheduleItem.BalancePrincipalNIB <> 0 Then
                With .Add().Cells
                  .AddCaptionWiki("**Principal** --(Non Interest Bearing)--")
                  .AddCurrency(-AccountCalcScheduleItem.ValueAllocatedPrincipalNIB)
                  .AddCurrency(-AccountCalcScheduleItem.BalancePrincipalNIB)
                End With
              End If
              If AccountCalcScheduleItem.ValueAllocatedPrincipalIB <> 0 OrElse AccountCalcScheduleItem.BalancePrincipalIB <> 0 Then
                With .Add().Cells
                  .AddCaptionWiki("**Principal** --(Interest Bearing)--")
                  .AddCurrency(-AccountCalcScheduleItem.ValueAllocatedPrincipalIB)
                  .AddCurrency(-AccountCalcScheduleItem.BalancePrincipalIB)
                End With
              End If
              If AccountCalcScheduleItem.ValueAllocatedInterest <> 0 OrElse AccountCalcScheduleItem.BalanceInterest <> 0 Then
                With .Add().Cells
                  Select Case AccountCalcScheduleItem.WithholdingTaxResidentStatus
                    Case isefinAccountTransactionResidentStatus.ApprovedIssuerLevy
                      If AccountCalcScheduleItem.WithholdingTaxRate = 0 Then
                        strTemp = String.Format("Interest --AIL @ {0}--", finBL.FormatPercentage(AccountCalcScheduleItem.WithholdingTaxRate / 100, 4))
                      Else
                        strTemp = String.Format("Interest --{0} less {1} AIL {2}--", finBL.FormatCurrency(-AccountCalcScheduleItem.ValueAllocatedInterest - AccountCalcScheduleItem.WithholdingTaxValue, True), finBL.FormatPercentage(AccountCalcScheduleItem.WithholdingTaxRate / 100, 4), finBL.FormatCurrency(-AccountCalcScheduleItem.WithholdingTaxValue, True))
                      End If
                    Case isefinAccountTransactionResidentStatus.NonResident
                      If AccountCalcScheduleItem.WithholdingTaxRate = 0 Then
                        strTemp = String.Format("Interest --NRWT @ {0}--", finBL.FormatPercentage(AccountCalcScheduleItem.WithholdingTaxRate / 100, 4))
                      Else
                        strTemp = String.Format("Interest --{0} less {1} NRWT {2}--", finBL.FormatCurrency(-AccountCalcScheduleItem.ValueAllocatedInterest - AccountCalcScheduleItem.WithholdingTaxValue, True), finBL.FormatPercentage(AccountCalcScheduleItem.WithholdingTaxRate / 100, 4), finBL.FormatCurrency(-AccountCalcScheduleItem.WithholdingTaxValue, True))
                      End If
                    Case isefinAccountTransactionResidentStatus.Resident
                      If AccountCalcScheduleItem.WithholdingTaxRate = 0 Then
                        strTemp = String.Format("Interest --RWT @ {0}--", finBL.FormatPercentage(AccountCalcScheduleItem.WithholdingTaxRate / 100, 4))
                      Else
                        strTemp = String.Format("**Interest** --{0} less {1} RWT {2}--", finBL.FormatCurrency(-AccountCalcScheduleItem.ValueAllocatedInterest - AccountCalcScheduleItem.WithholdingTaxValue, True), finBL.FormatPercentage(AccountCalcScheduleItem.WithholdingTaxRate / 100, 4), finBL.FormatCurrency(-AccountCalcScheduleItem.WithholdingTaxValue, True))
                      End If
                    Case Else
                      strTemp = "**Interest**"
                  End Select
                  .AddCaptionWiki(strTemp)
                  .AddCurrency(-AccountCalcScheduleItem.ValueAllocatedInterest)
                  .AddCurrency(-AccountCalcScheduleItem.BalanceInterest)
                End With
              End If
              If AccountCalcScheduleItem.ValueAllocatedFeeNIB <> 0 OrElse AccountCalcScheduleItem.BalanceFeeNIB <> 0 Then
                With .Add().Cells
                  .AddCaptionWiki("**Fees** --(Non Interest Bearing)--")
                  .AddCurrency(-AccountCalcScheduleItem.ValueAllocatedFeeNIB)
                  .AddCurrency(-AccountCalcScheduleItem.BalanceFeeNIB)
                End With
              End If
              If AccountCalcScheduleItem.ValueAllocatedFeeIB <> 0 OrElse AccountCalcScheduleItem.BalanceFeeIB <> 0 Then
                With .Add().Cells
                  .AddCaptionWiki("**Fees** --(Interest Bearing)--")
                  .AddCurrency(-AccountCalcScheduleItem.ValueAllocatedFeeIB)
                  .AddCurrency(-AccountCalcScheduleItem.BalanceFeeIB)
                End With
              End If

              ' Value
              With .Add(iseSummaryTableRowClass.FooterBold).Cells
                .AddCaption("Total")
                .AddCurrency(-AccountCalcScheduleItem.Value)
                .AddCurrency(-AccountCalcScheduleItem.Balance)
              End With

            Case Else
              If AccountCalcScheduleItem.ValueAllocatedPrincipalNIB <> 0 OrElse AccountCalcScheduleItem.ValueAllocatedPrincipalIB <> 0 OrElse AccountCalcScheduleItem.ValueAllocatedInterest <> 0 OrElse AccountCalcScheduleItem.ValueAllocatedFeeNIB <> 0 OrElse AccountCalcScheduleItem.ValueAllocatedFeeIB <> 0 Then
                If AccountCalcScheduleItem.ValueAllocatedPrincipalNIB <> 0 OrElse AccountCalcScheduleItem.BalancePrincipalNIB <> 0 Then
                  With .Add().Cells
                    .AddCaptionWiki("**Principal** --(Non Interest Bearing)--")
                    .AddCurrency(AccountCalcScheduleItem.ValueAllocatedPrincipalNIB)
                    .AddCurrency(AccountCalcScheduleItem.BalancePrincipalNIB)
                  End With
                End If
                If AccountCalcScheduleItem.ValueAllocatedPrincipalIB <> 0 OrElse AccountCalcScheduleItem.BalancePrincipalIB <> 0 Then
                  With .Add().Cells
                    .AddCaptionWiki("**Principal** --(Interest Bearing)--")
                    .AddCurrency(AccountCalcScheduleItem.ValueAllocatedPrincipalIB)
                    .AddCurrency(AccountCalcScheduleItem.BalancePrincipalIB)
                  End With
                End If
                If AccountCalcScheduleItem.ValueAllocatedInterest <> 0 OrElse AccountCalcScheduleItem.BalanceInterest <> 0 Then
                  With .Add().Cells
                    .AddCaptionWiki("**Interest**")
                    .AddCurrency(AccountCalcScheduleItem.ValueAllocatedInterest)
                    .AddCurrency(AccountCalcScheduleItem.BalanceInterest)
                  End With
                End If
                If AccountCalcScheduleItem.ValueAllocatedFeeNIB <> 0 OrElse AccountCalcScheduleItem.BalanceFeeNIB <> 0 Then
                  With .Add().Cells
                    .AddCaptionWiki("**Fees** --(Non Interest Bearing)--")
                    .AddCurrency(AccountCalcScheduleItem.ValueAllocatedFeeNIB)
                    .AddCurrency(AccountCalcScheduleItem.BalanceFeeNIB)
                  End With
                End If
                If AccountCalcScheduleItem.ValueAllocatedFeeIB <> 0 OrElse AccountCalcScheduleItem.BalanceFeeIB <> 0 Then
                  With .Add().Cells
                    .AddCaptionWiki("**Fees** --(Interest Bearing)--")
                    .AddCurrency(AccountCalcScheduleItem.ValueAllocatedFeeIB)
                    .AddCurrency(AccountCalcScheduleItem.BalanceFeeIB)
                  End With
                End If
              End If

              ' Value
              With .Add(iseSummaryTableRowClass.FooterBold).Cells
                .AddCaption("Total")
                .AddCurrency(AccountCalcScheduleItem.Value)
                .AddCurrency(AccountCalcScheduleItem.Balance)
              End With

              ' Overdue Allocations
              If account.SupportsOverdue AndAlso account.Status <> isefinAccountStatus.Quote Then
                If account.AccountType.ShowOverdue Then
                  If AccountCalcScheduleItem.Overdue <> 0 OrElse AccountCalcScheduleItem.BalanceOverdue <> 0 Then
                    With .Add().Cells
                      .AddCaptionWiki("**Overdue**")
                      .AddCurrency(AccountCalcScheduleItem.Overdue)
                      .AddCurrency(AccountCalcScheduleItem.BalanceOverdue)
                    End With
                  End If
                End If
                If account.AccountType.ShowContractualOverdue Then
                  If AccountCalcScheduleItem.OverdueContractual <> 0 OrElse AccountCalcScheduleItem.BalanceOverdueContractual <> 0 Then
                    With .Add().Cells
                      .AddCaptionWiki("**Contractual Overdue**")
                      .AddCurrency(AccountCalcScheduleItem.OverdueContractual)
                      .AddCurrency(AccountCalcScheduleItem.BalanceOverdueContractual)
                    End With
                  End If
                End If
              End If

              ' Original Payment Value
              If AccountCalcScheduleItem.IsExisting AndAlso AccountCalcScheduleItem.ElementType = isefinElementType.PaymentReceived AndAlso AccountCalcScheduleItem.Value <> AccountCalcScheduleItem.TransactionValue Then
                With .Add(iseSummaryTableRowClass.NormalBold).Cells
                  .AddCaptionWiki("**Original Payment Value**")
                  .AddCurrency(AccountCalcScheduleItem.TransactionValue)
                  .AddText("")
                End With
              End If

              ' Original Value - before Consumer Regulation adjustment
              If AccountCalcScheduleItem.HighCostLoanAdjustmentType <> isefinAccountTransactionHCLAdjustmentType.NotApplicable Then
                If account.ConsumerRegulationType = isefinAccountConsumerRegulationType.NotApplicable Then
                  Warnings &= "{{info|" & String.Format("Value has been reduced from {0}.", finBL.FormatCurrency(AccountCalcScheduleItem.HighCostLoanValueOriginal, True)) & "}}"
                Else
                  Warnings &= "{{info|" & String.Format("Value has been reduced from {0} under '{1}' regulations.<br>Reason was '{2}'.", finBL.FormatCurrency(AccountCalcScheduleItem.HighCostLoanValueOriginal, True), account.ConsumerRegulationTypeText, AccountCalcScheduleItem.HighCostLoanAdjustmentTypeText) & "}}"
                End If
              End If
          End Select
        End With
      End If

      ' Warnings
      If AccountCalcScheduleItem IsNot Nothing Then
      End If
      .TextAfter = Warnings

      ' Actions
      If includeActions Then
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Summary", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Schedule Summary (Version 1.01, Last updated 31/03/2020).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="account">
  '''  The Account to summarise.
  ''' </param>
  ''' <param name="accountCalcSchedule">
  '''  The Account Calculation Schedule to summarise.
  ''' </param>
  ''' <param name="index">
  '''  The Schedule Item's index to use.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Schedule drilldown form.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Summary.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_ScheduleSummary(callerScriptInfo As ISScriptExecutionInfo,
                                                      account As finAccount,
                                                      accountCalcSchedule As finAccountCalcSchedule,
                                                      index As Integer,
                                             Optional includeActions As Boolean = True,
                                             Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim AccountCalcScheduleItem As finAccountCalcScheduleItem
    Dim strTemp As String
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Information
    If account Is Nothing OrElse index < 0 OrElse index > accountCalcSchedule.Count Then
      AccountCalcScheduleItem = Nothing
    Else
      AccountCalcScheduleItem = accountCalcSchedule(index)
    End If

    ' Summary table
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Columns.AddText(12)
      .Columns.AddText()

      With .Rows
        If AccountCalcScheduleItem IsNot Nothing Then
          ' General
          If AccountCalcScheduleItem.IsExisting Then
            .AddCaptionText("Status:", "Existing")
            If AccountCalcScheduleItem.TransactionPk = -1 Then
              .AddCaptionText("Id:", "Multiple")
            Else
              .AddCaptionInteger("Id:", AccountCalcScheduleItem.TransactionPk)
            End If
          ElseIf AccountCalcScheduleItem.ScheduleType = isefinAccountCalcScheduleType.OpeningRestructure Then
            .AddCaptionText("Status:", "Opening Restructure")
          Else
            .AddCaptionText("Status:", "Future Transaction")
          End If
          If AccountCalcScheduleItem.ElementPk <> 0 Then
            strTemp = AccountCalcScheduleItem.ElementTypeText
            If AccountCalcScheduleItem.ScheduleTypeText = AccountCalcScheduleItem.ElementTypeText Then
              If AccountCalcScheduleItem.ScheduleSubType <> isefinAccountCalcScheduleSubType.None Then
                strTemp &= String.Format(" ({0})", AccountCalcScheduleItem.ScheduleSubTypeText)
              End If
            ElseIf Len(AccountCalcScheduleItem.ScheduleTypeText) <> 0 Then
              If AccountCalcScheduleItem.ScheduleSubType = isefinAccountCalcScheduleSubType.None Then
                strTemp &= String.Format(" ({0})", AccountCalcScheduleItem.ScheduleTypeText)
              Else
                strTemp &= String.Format(" ({0}; {1})", AccountCalcScheduleItem.ScheduleTypeText, AccountCalcScheduleItem.ScheduleSubTypeText)
              End If
            End If
            .AddCaptionText("Type:", strTemp)
            .AddCaptionCodeDescription("Element:", AccountCalcScheduleItem.ElementId, AccountCalcScheduleItem.ElementDescription)
          End If
          strTemp = finBL.FormatDateLong(AccountCalcScheduleItem.Date)
          If AccountCalcScheduleItem.Date <> AccountCalcScheduleItem.DateFrom OrElse AccountCalcScheduleItem.Date <> AccountCalcScheduleItem.DateTo Then
            strTemp &= String.Format(" --(from {1} to {2})--", finBL.FormatDateLong(AccountCalcScheduleItem.Date), finBL.FormatDateLong(AccountCalcScheduleItem.DateFrom), finBL.FormatDateLong(AccountCalcScheduleItem.DateTo))
          End If
          If AccountCalcScheduleItem.DatePaymentGrace <> Nothing Then
            strTemp &= String.Format(" --(payment grace period until {0})--", finBL.FormatDateLong(AccountCalcScheduleItem.DatePaymentGrace))
          End If
          .AddCaptionWiki("Date:", strTemp)
          If Len(AccountCalcScheduleItem.Notes) <> 0 Then .AddCaptionText("Notes:", AccountCalcScheduleItem.Notes)
        End If
      End With

      ' Warnings
      Warnings = ""
      If AccountCalcScheduleItem IsNot Nothing Then
        ' Adjusted by Consumer Regulation
        If AccountCalcScheduleItem.HighCostLoanAdjustmentType <> isefinAccountTransactionHCLAdjustmentType.NotApplicable Then
          Select Case account.ConsumerRegulationType
            Case isefinAccountConsumerRegulationType.NotApplicable
              Warnings &= "{{warning|Value has been adjusted.}}"
            Case Else
              Warnings &= "{{warning|" & String.Format("Value has been reduced under '{0}' regulations.<br>Reason was '{1}'.", account.ConsumerRegulationTypeText, AccountCalcScheduleItem.HighCostLoanAdjustmentTypeText) & "}}"
          End Select
        End If

        ' Reversed Transaction
        If AccountCalcScheduleItem.TransactionReversePk <> 0 Then
          If AccountCalcScheduleItem.TransactionReversePk > AccountCalcScheduleItem.TransactionPk Then
            Warnings &= "{{warning|" & String.Format("Reversed by Transaction Id **{0}**.", AccountCalcScheduleItem.TransactionReversePk) & "}}"
          Else
            Warnings &= "{{warning|" & String.Format("Reversed Transaction Id **{0}**.", AccountCalcScheduleItem.TransactionReversePk) & "}}"
          End If
        End If

        ' Negative Payment Reversed
        If AccountCalcScheduleItem.TransactionNegativePaymentReversePk <> 0 Then
          If AccountCalcScheduleItem.TransactionNegativePaymentReversePk > AccountCalcScheduleItem.TransactionPk Then
            Warnings &= "{{warning|" & String.Format("Reversed by Negative Payment Transaction Id **{0}**.", AccountCalcScheduleItem.TransactionNegativePaymentReversePk) & "}}"
          Else
            Warnings &= "{{warning|" & String.Format("Negative Payment matched to Transaction Id **{0}**.", AccountCalcScheduleItem.TransactionNegativePaymentReversePk) & "}}"
          End If
        End If

        ' Restructure
        If AccountCalcScheduleItem.AccountCalculationPk <> 0 Then
          Warnings &= "{{info|Transaction is prior to current Account Restructure.}}"
        End If
      End If
      .TextAfter = Warnings

      ' Actions
      If includeActions Then
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Summary", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Standard Transaction Summary (Version 1.03, Last updated 15/08/2017).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="account">
  '''  The Account to summarise.
  ''' </param>
  ''' <param name="index">
  '''  The Standard Transaction index to use.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Payments page and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Summary.</description></item>
  '''    <item><code>Transfer</code><description>Transfer Account Summary.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_StandardTransaction(callerScriptInfo As ISScriptExecutionInfo,
                                                          account As finAccount,
                                                          index As Integer,
                                                 Optional includeActions As Boolean = True,
                                                 Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim AccountStdTran As finAccountStdTran
    Dim AccountTransfer As finAccount
    Dim DateNext As Date
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTableTransfer As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTableTransfer = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Information
    If account Is Nothing OrElse index < 0 OrElse index > account.StandardTransactions.Count Then
      AccountStdTran = Nothing
    Else
      AccountStdTran = account.StandardTransactions(index)

      ' Find Next Date (Nothing=Ceased)
      With AccountStdTran
        If .Cycle = "Opening" Then
          DateNext = Nothing
        ElseIf .DateStop <> Nothing Then
          If .DateNext > .DateStop Then
            DateNext = Nothing
          Else
            DateNext = .DateNext
          End If
        ElseIf .DateNext = #12/31/9999# Then
          DateNext = Nothing
        Else
          DateNext = .DateNext
        End If
      End With
    End If

    ' Summary table
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Columns.AddText(20)
      .Columns.AddText()

      With .Rows
        If AccountStdTran IsNot Nothing Then
          ' General
          .AddCaptionCodeDescription("Element:", AccountStdTran.ElementPk, finBL.Elements)
          If Len(AccountStdTran.Key) <> 0 Then .AddCaptionText("Key:", AccountStdTran.Key)
          .AddCaptionText("Frequency:", AccountStdTran.CycleDescription(account.Status))
          Select Case AccountStdTran.Cycle
            Case "Once"
              If DateNext <> Nothing Then .AddCaptionDate("Date:", DateNext)
              .AddCaptionText("Basis:", AccountStdTran.ValueBasisText)
            Case "Opening"
            Case Else
              .AddCaptionDate("Next Date:", DateNext)
              .AddCaptionDate("Stop Date:", AccountStdTran.DateStop)
              .AddCaptionText("Basis:", AccountStdTran.ValueBasisText)
          End Select
          If account.AccountClass = isefinAccountClass.Deposit AndAlso AccountStdTran.ElementType = isefinElementType.Transfer AndAlso AccountStdTran.Cycle = "Opening" Then
            ' Deposit Opening Transfer From
            .AddCaptionText("Value:", finBL.FormatCurrency(-AccountStdTran.Value, True))
          Else
            .AddCaptionText("Value:", AccountStdTran.ValueDescription)
          End If
          .AddCaptionText("Reference:", AccountStdTran.Reference)
          .AddCaptionText("Notes:", AccountStdTran.Notes)
        End If
      End With

      ' Warnings
      If AccountStdTran IsNot Nothing AndAlso AccountStdTran.Cycle <> "Opening" Then
        If DateNext = Nothing Then
          If AccountStdTran.Cycle = "Once" Then
            Warnings &= "{{info|Processing completed.}}"
          Else
            Warnings &= "{{info|Processing ceased.}}"
          End If
        ElseIf AccountStdTran.DateStop <> Nothing Then
          Warnings &= "{{info|Processing will cease on **" & finBL.FormatDate(AccountStdTran.DateStop, True) & "**.}}"
        End If
      End If
      .TextAfter = Warnings

      ' Actions
      If includeActions Then
      End If
    End With

    ' Transfer table
    With SummaryTableTransfer
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = "Transfer"
      .Columns.AddText(20)
      .Columns.AddText()

      Warnings = ""

      With .Rows
        If AccountStdTran IsNot Nothing AndAlso AccountStdTran.ElementType = isefinElementType.Transfer Then
          ' Load Account
          If AccountStdTran.TransferToAccountPk = 0 Then
            If account.AccountClass = isefinAccountClass.Deposit AndAlso AccountStdTran.ElementType = isefinElementType.Transfer AndAlso AccountStdTran.Cycle = "Opening" Then
              ' Deposit Opening Transfer From
              .AddCaptionText("Transfer From:", "Transfer from Account not defined")
            Else
              .AddCaptionText("Transfer To:", "Transfer to Account not defined")
            End If
          Else
            AccountTransfer = finBL.CreateAccount
            If AccountTransfer.LoadPk(AccountStdTran.TransferToAccountPk) Then
              If account.AccountClass = isefinAccountClass.Deposit AndAlso AccountStdTran.ElementType = isefinElementType.Transfer AndAlso AccountStdTran.Cycle = "Opening" Then
                ' Deposit Opening Transfer From
                With .AddCaptionText("Transfer From:", AccountTransfer.AccountId)
                  .Cells(1).HyperlinkSetFormShow("Accounts", AccountTransfer.AccountId)
                End With
              Else
                With .AddCaptionText("Transfer To:", AccountTransfer.AccountId)
                  .Cells(1).HyperlinkSetFormShow("Accounts", AccountTransfer.AccountId)
                End With
              End If
              .AddCaptionText("Name:", AccountTransfer.Name)
              .AddCaptionCodeDescription("Type:", AccountTransfer.AccountTypeId, finBL.AccountTypes)

              If AccountTransfer.Status <> isefinAccountStatus.Open Then
                Warnings &= "{{warning|Account's Status is '" & AccountTransfer.StatusText & "'.}}"
              End If
            Else
              .AddCaptionText("Transfer To:", AccountStdTran.TransferToAccountId)
              Warnings &= "{{info|Failed to load Transfer to Account.}}"
            End If
          End If
        End If
      End With

      ' Warnings
      .TextAfter = Warnings
    End With

    ' Add Summary Tables
    SummaryTables.Add("Summary", SummaryTableMain)
    If SummaryTableTransfer.HasData Then SummaryTables.Add("Transfer", SummaryTableTransfer)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Statement Summary.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="account">
  '''  The Account to summarise.
  ''' </param>
  ''' <param name="accountCalc">
  '''  The Account Calculation if not using the current Calculation.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Status page and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_Statements(callerScriptInfo As ISScriptExecutionInfo,
                                                 account As finAccount,
                                        Optional accountCalc As finAccountCalc = Nothing,
                                        Optional includeActions As Boolean = True,
                                        Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' Account_Statements
    '
    ' Version: 1.03 (04/01/2024)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.01  13/09/2017  ISS
    '    1.02  12/04/2022  ISS      J028575   Reverse Last Statement now supported in finCC
    '    1.03  04/01/2024  ISS      J032457   Updated Permission Key
    ' #################################################################

    Dim StatementCycle As String
    Dim StatementDateLast As Date
    Dim StatementDateNext As Date
    Dim StatementLog As finLogRO
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables

    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()
    If accountCalc Is Nothing Then accountCalc = account.Calculation

    ' Get Statement details
    If accountCalc.IsCalcVersionOpening Then
      With accountCalc
        If account.IsQuoteOrClosedQuote Then
          StatementCycle = .StatementCycleDescription
          StatementDateLast = Nothing
          StatementDateNext = .StatementDateNext
        Else
          StatementCycle = .OriginalStatementCycleDescription
          StatementDateLast = Nothing
          StatementDateNext = .OriginalStatementDateFirst
        End If
      End With
    Else
      With account.Calculation
        StatementCycle = .StatementCycleDescription
        StatementDateLast = .StatementDateLast
        StatementDateNext = .StatementDateNext
        If Not account.GetLastStatementLog(StatementLog) Then
          ' Ignore error
        End If
      End With
    End If

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      .Columns.AddText(10).NoBreakChars = 10
      .Columns.AddText()

      With .Rows
        .AddCaptionText("Frequency:", StatementCycle)
        If accountCalc.IsCalcVersionOpening Then
          Select Case StatementCycle
            Case "None", "On Demand"
            Case Else
              .AddCaptionDate("First Date:", StatementDateNext)
          End Select
        Else
          If StatementLog Is Nothing Then
            .AddCaptionDate("Last Date:", Nothing)
          Else
            .AddCaptionDate("Last Date:", StatementLog.LogDate)
          End If
          If account.Status = isefinAccountStatus.Open Then
            Select Case StatementCycle
              Case "None", "On Demand"
              Case Else
                .AddCaptionDate("Next Date:", StatementDateNext)
            End Select
          End If
        End If
      End With

      ' Warnings
      Select Case account.Status
        Case isefinAccountStatus.Quote, isefinAccountStatus.Open
          Select Case StatementCycle
            Case "None", "On Demand"
              Select Case account.AccountType.StatementCycle
                Case "None", "On Demand"
                Case Else
                  Warnings &= "{{Warning|No Statements will be sent for this account.}}"
              End Select
            Case Else
              If StatementDateNext = Nothing Then
                Warnings &= "{{Warning|No Statements will be sent as the Next Statement date is undefined.}}"
              End If
          End Select
      End Select
      .TextAfter = Warnings

      ' Actions
      If includeActions Then
        With .Actions
          .AddFormAction("StatementReview", "Review", finBL.CurrentUser.Permissions.Allow("Account.Statement.View") AndAlso account.Status = isefinAccountStatus.Open).ShowInWebInterfaces = True
          If StatementLog IsNot Nothing Then
            .AddFormShow("StatementViewLast", "View Last", "AccountLog", finBL.CurrentUser.Permissions.Allow("Account.Form.Page.Logs"), String.Format("id={0}", StatementLog.Pk)).ShowInWebInterfaces = True
          End If
          .AddFormAction("StatementReverse", "Reverse Last", account.CanReverseLastStatement()).ShowInWebInterfaces = True
        End With
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Financial Status Summary
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="account">
  '''  The Account to summarise.
  ''' </param>
  ''' <param name="includeAccountSummary">
  '''  Indicates whether to include a brief summary of the Account, e.g., Code, Name, Status, Borrowers.
  ''' </param>
  ''' <param name="includeMonitoringSummary">
  '''  Indicates whether to include a brief summary of Monitoring.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="compact">
  '''  Indicates whether to optimise for displaying in a compact area.
  ''' </param>
  ''' <param name="accountOverdues">
  '''  A finAccountOverdues object or Nothing. If Nothing then the overdues will be created and returned as a ByRef parameter.
  ''' </param>
  ''' <param name="accountOverduesC">
  '''  A finAccountOverdues object (representing Contractual Overdues) or Nothing. If Nothing then the overdues will be created and returned as a ByRef parameter.
  ''' </param>
  ''' <param name="lastReversedPaymentDaysMaximum">
  '''  The Maximum Days for warning since last Reversed Payment.
  ''' </param>
  ''' <param name="newBalanceAdjustment">
  '''  An Adjustment for the New Balance to display, e.g., if summarising via a Withdrawal wizard.
  ''' </param>
  ''' <param name="newBalanceSuffixWiki">
  '''  A simple Wiki suffix to apply to the 'New Balance' row. If this is blank, no 'New Balance' row will appear if the New Balance is zero.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Key and Status pages, Workflow Summary and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_FinancialStatus(callerScriptInfo As ISScriptExecutionInfo,
                                                      account As finAccount,
                                             Optional ByRef accountOverdues As finAccountOverdues = Nothing,
                                             Optional ByRef accountOverduesC As finAccountOverdues = Nothing,
                                             Optional lastReversedPaymentDaysMaximum As Integer = 120,
                                             Optional includeAccountSummary As Boolean = False,
                                             Optional includeMonitoringSummary As Boolean = False,
                                             Optional compact As Boolean = False,
                                             Optional newBalanceAdjustment As Decimal = 0,
                                             Optional newBalanceSuffixWiki As String = "",
                                             Optional includeActions As Boolean = True,
                                             Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' Account_FinancialStatus
    '
    ' Version 1.17 (08/05/2023)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.14  12/08/2020  ISS
    '    1.15  04/08/2022  ISS      J029268   Columns spacing not correct if Status is Quote
    '    1.16  19/04/2023  ISS      J030939   Closed Pending column alignment issue
    '    1.17  08/05/2023  ISS      J031024   Closed column alignment issue
    ' #################################################################

    Dim AccountClient As finAccountClient
    Dim AccountPayArrangement As finAccountPayArrangement
    Dim AccountPayArrangementPayment As finAccountPayArrangementPayment
    Dim AvailableCredit As Decimal
    Dim Balance As Decimal
    Dim BalanceRefinancePending As Decimal
    Dim CellClass As iseSummaryTableCellClass
    Dim CreditLimit As Decimal
    Dim DateAsAt As Date
    Dim dateTemp As Date
    Dim Days As Long
    Dim i As Integer
    Dim Icon As String
    Dim InterestRate As Double
    Dim InterestRatePremium As Double
    Dim InterestRateTableId As String
    Dim InterestRateTableIsTiered As Boolean
    Dim InterestRateTablePk As Integer
    Dim InterestType As isefinAccountInterestType
    Dim InvestmentPending As Decimal
    Dim InvestmentReceived As Decimal
    Dim InvestmentValue As Decimal
    Dim LastPaymentDate As Date
    Dim LastPaymentValue As Decimal
    Dim LastReversedPaymentDate As Date
    Dim LastReversedPaymentDateReversed As Date
    Dim LastReversedPaymentValue As Decimal
    Dim MaturityFeesIB As Decimal
    Dim MaturityFeesNIB As Decimal
    Dim MaturityInstruction As isefinAccountMaturityInstruction
    Dim MaturityInterest As Decimal
    Dim MaturityPaymentType As isefinAccountMaturityPaymentType
    Dim MaturityPayout As Decimal
    Dim MaturityPrincipalNIB As Decimal
    Dim MaturityPrincipalIB As Decimal
    Dim MaturityReinvestment As Decimal
    Dim MaturityValue As Decimal
    Dim NextPaymentDate As Date
    Dim NextPaymentValue As Decimal
    Dim Overdue As Decimal
    Dim OverdueToday As Decimal
    Dim OverdueContractual As Decimal
    Dim OverdueTodayContractual As Decimal
    Dim PromisesCountPending As Integer
    Dim PromisesCountRemaining As Integer
    Dim PromisesFinalDate As Date
    Dim PromisesLastStatus As isefinTransactionPromiseStatus
    Dim PromisesRemaining As Decimal
    Dim PromisesToday As Decimal
    Dim strTemp As String
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Tooltip As String
    Dim Warnings As String

    ' Get Date As At - weird function as ByRef accountOverdues and accountOverduesC could be passed in
    DateAsAt = finBL.TimeZoneFunctions.GetCurrentDatabaseDate()

    ' Initialise ByRef Parameters
    If account.Status = isefinAccountStatus.Open Then
      If accountOverdues Is Nothing AndAlso account.SupportsOverdue AndAlso account.AccountType.ShowOverdue Then
        ' Load Overdues
        accountOverdues = finBL.CreateAccountOverdues()
        accountOverdues.LoadFromAccount(account, False, DateAsAt)
      End If
      If accountOverduesC Is Nothing AndAlso account.SupportsOverdue AndAlso account.AccountType.ShowContractualOverdue Then
        ' Load Contractual Overdues
        accountOverduesC = finBL.CreateAccountOverdues()
        accountOverduesC.LoadFromAccount(account, True, DateAsAt)
      End If
    End If

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""

      ' Columns (alignment for Column 2 may be adjusted later based on Account Status)
      With .Columns
        .AddText(18).NoBreakChars = 18
        .AddText(16)
        .AddText()
      End With

      ' Alert Messages (only display for Payment Arrangements and Promises)
      Select Case callerScriptInfo.FormKey
        Case "AccountPaymentPromiseAdd", "AccountPaymentArrangementAdd", "AccountRestructure"
          account.GetAlertMessages(.TextBefore)
      End Select

      With .Rows
        ' ---------------
        ' Account Summary
        ' ---------------
        If includeAccountSummary Then
          ' General
          With .AddCaptionText("Code:", account.AccountId)
            .Cells(1).HyperlinkSetFormShow("Accounts", account.AccountId)
            .Cells.Add("")
          End With
          .AddCaptionText("Name:", account.Name, iseSummaryTableCellClass.Highlight1)
          .AddCaptionCodeDescription("Type:", account.AccountTypePk, finBL.AccountTypes)
          .AddCaptionText("Status:", account.StatusText)

          ' Clients (Owners and Guarantors)
          i = 0
          For Each AccountClient In account.Clients
            Select Case AccountClient.AccountRole.RoleType
              Case isefinAccountRoleType.Guarantor, isefinAccountRoleType.Owner
                ' Get details from Account  Role
                With AccountClient.AccountRole
                  If Len(.Icon) = 0 Then Icon = "Client" Else Icon = "AccountRole_" & AccountClient.AccountRole.Icon
                  Tooltip = .DescriptionShortResolved
                End With

                If i = 0 Then
                  With .AddCaptionWiki("Clients:", "{{icon|" & Icon & "|" & Tooltip & "}} " & AccountClient.ClientName)
                    .Cells(1).HyperlinkSetFormShow("Clients", AccountClient.ClientId)
                  End With
                Else
                  With .AddCaptionWiki("", "{{icon|" & Icon & "|" & Tooltip & "}} " & AccountClient.ClientName)
                    .Cells(1).HyperlinkSetFormShow("Clients", AccountClient.ClientId)
                  End With
                End If

                i += 1
            End Select
          Next
        End If

        ' ----------------
        ' Financial Status
        ' ----------------
        Select Case account.Status
          Case isefinAccountStatus.Closed
            ' Closed
            With .AddCaptionText("Balance:", "Closed", iseSummaryTableCellClass.Highlight1)
              .Cells(1).TextAlign = iseSummaryTableCellTextAlign.Left
            End With
            .AddCaptionDate("Closed:", account.DateClosed)
            With .AddCaptionText("Method:", account.CloseMethodText)
              If account.ClosedToAccountPk = 0 Then
                .Cells.AddText("")
              Else
                .Cells.AddWiki(String.Format("--to Account [[app://formshow?form=Accounts&id={0}|{1}]]--", finBL.UrlEncode(account.ClosedToAccountId), account.ClosedToAccountId))
              End If
            End With
            .AddCaptionText("Notes:", account.CloseNote)
            If account.DateMaturity <> Nothing Then
              .AddCaptionDate("Maturity Date:", account.DateMaturity)
            End If

          Case isefinAccountStatus.ClosedPending
            ' Closed Pending
            With .AddCaptionText("Balance:", "Closed (Pending)", iseSummaryTableCellClass.Highlight1)
              .Cells(1).TextAlign = iseSummaryTableCellTextAlign.Left
            End With
            If account.IsRefinancePending Then
              account.GetBalanceRefinancePending(BalanceRefinancePending)
              With .AddCaptionCurrency("Pre-Refinance:", BalanceRefinancePending, True)
                .Cells(1).CellClass = iseSummaryTableCellClass.Inactive
              End With
            End If
            .AddCaptionDate("Closed:", account.DateClosed)
            With .AddCaptionText("Method:", account.CloseMethodText)
              If account.ClosedToAccountPk = 0 Then
                .Cells.AddText("")
              Else
                .Cells.AddWiki(String.Format("--to Account [[app://formshow?form=Accounts&id={0}|{1}]]--", finBL.UrlEncode(account.ClosedToAccountId), account.ClosedToAccountId))
              End If
            End With
            .AddCaptionText("Notes:", account.CloseNote)
            If account.DateMaturity <> Nothing Then
              .AddCaptionDate("Maturity Date:", account.DateMaturity)
            End If

            ' Warnings
            If account.DateClosedPendingReview < DateAsAt Then
              Warnings &= "{{warning|" & String.Format("**Pending finalisation**. Review date of **{0}** has passed.", finBL.FormatDateLong(account.DateClosedPendingReview)) & "}}"
            Else
              Warnings &= "{{info|" & String.Format("**Pending finalisation**. For review on **{0}**.", finBL.FormatDateLong(account.DateClosedPendingReview)) & "}}"
            End If

          Case isefinAccountStatus.Open
            ' Open
            ' Tweak Column Alignment
            If includeAccountSummary OrElse includeMonitoringSummary Then
              ' Keep standard, left alignment
            Else
              SummaryTableMain.Columns(1).TextAlign = iseSummaryTableCellTextAlign.Right
            End If

            ' Balance
            If Len(newBalanceSuffixWiki) = 0 AndAlso newBalanceAdjustment = 0 Then
              CellClass = iseSummaryTableCellClass.Highlight1
            Else
              CellClass = iseSummaryTableCellClass.NormalBold
            End If
            account.GetBalance(Balance)
            Select Case account.AccountClass
              Case isefinAccountClass.Deposit
                If Balance < 0 Then
                  .AddCaptionCurrency("Balance:", -Balance, True, , CellClass)
                Else
                  With .AddCaptionCurrency("Balance:", -Balance, True, , CellClass)
                    .Cells.AddWiki("DEBIT Balance")
                  End With
                End If

              Case isefinAccountClass.Disbursement
                If Balance < 0 Then
                  With .AddCaptionCurrency("Balance:", Balance, True, , CellClass)
                    .Cells.AddWiki("CREDIT Balance")
                  End With
                Else
                  .AddCaptionCurrency("Balance:", Balance, True, , CellClass)
                End If

              Case Else
                If Balance < 0 Then
                  With .AddCaptionCurrency("Balance:", Balance, True, , CellClass)
                    .Cells.AddWiki("CREDIT Balance")
                  End With
                Else
                  ' Get Next Payment details
                  account.GetNextPayment(NextPaymentDate, NextPaymentValue)

                  If NextPaymentDate = Nothing Then
                    Select Case account.AccountClass
                      Case isefinAccountClass.LoanFR, isefinAccountClass.LoanFT
                        With .AddCaptionCurrency("Balance:", Balance, True, , CellClass)
                          .Cells.AddWiki("--!!No further payments listed!!--")
                        End With

                        ' Add a warning
                        Warnings &= "{{Warning|No further payments listed for this Account.}}"
                      Case Else
                        .AddCaptionCurrency("Balance:", Balance, True, , CellClass)
                    End Select
                  ElseIf NextPaymentDate = DateAsAt Then
                    With .AddCaptionCurrency("Balance:", Balance, True, , CellClass)
                      .Cells.AddWiki(String.Format("--Next Payment **{0}** due **today**--", finBL.FormatCurrency(NextPaymentValue, True)))
                    End With
                  Else
                    With .AddCaptionCurrency("Balance:", Balance, True, , CellClass)
                      .Cells.AddWiki(String.Format("--Next Payment **{0}** due **{1}**--", finBL.FormatCurrency(NextPaymentValue, True), finBL.FormatDateLong(NextPaymentDate)))
                    End With
                  End If
                End If
            End Select

            ' New Balance
            Select Case account.AccountClass
              Case isefinAccountClass.Deposit
                If Len(newBalanceSuffixWiki) <> 0 OrElse newBalanceAdjustment <> 0 Then
                  With .AddCaptionCurrency("New Balance:", -(Balance + newBalanceAdjustment), True, , iseSummaryTableCellClass.Highlight1)
                    .Cells.AddWiki("--" & newBalanceSuffixWiki & "--")
                  End With
                End If
              Case Else
                If Len(newBalanceSuffixWiki) <> 0 OrElse newBalanceAdjustment <> 0 Then
                  With .AddCaptionCurrency("New Balance:", Balance + newBalanceAdjustment, True, , iseSummaryTableCellClass.Highlight1)
                    .Cells.AddWiki("--" & newBalanceSuffixWiki & "--")
                  End With
                End If
            End Select

            ' Loan Advance
            If account.AccountType.ShowTotalAdvances Then
              With .AddCaptionCurrency("Total Advances:", account.TotalAdvances(False), True, , iseSummaryTableCellClass.Highlight2)
                .Cells.AddWiki("--Opened on " & finBL.FormatDateLong(account.DateOpened) & "--")
              End With
            End If

            ' Credit Limit
            If account.AccountType.CreditLimitCount > 0 Then
              account.GetAvailableCredit(DateAsAt, True, AvailableCredit, 0, 0, CreditLimit)

              With .AddCaptionCurrency("Credit Limit:", CreditLimit, True, , iseSummaryTableCellClass.Highlight2)
                If AvailableCredit - newBalanceAdjustment < 0 Then
                  .Cells.AddWiki("--!!**Credit Limit exceeded**!!--")
                Else
                  .Cells.AddWiki(String.Format("-- Available Credit **{0}** --", finBL.FormatCurrency(AvailableCredit - newBalanceAdjustment, True)))
                End If
              End With
            End If

            ' Overdues
            If account.SupportsOverdue Then
              ' Overdue
              If account.AccountType.ShowOverdue Then
                ' Get Overdues
                OverdueToday = accountOverdues.TotalOverdueToday
                Overdue = accountOverdues.TotalOverdue - OverdueToday

                If Overdue = 0 Then
                  .AddCaptionCurrency("Overdue:", 0, True, iseSummaryTableRowClass.Alt2, iseSummaryTableCellClass.Highlight2)
                ElseIf Overdue < 0 Then
                  With .AddCaptionCurrency("Overdue:", Overdue, True, iseSummaryTableRowClass.Alt2, iseSummaryTableCellClass.Highlight2)
                    .Cells(1).ForegroundColour = "green"
                    .Cells.AddWiki(String.Format("--Prepaid as at **{0}**--", finBL.FormatDateLong(accountOverdues.DateAsAtResolved)))
                  End With
                ElseIf accountOverdues.Count = 0 Then
                  With .AddCaptionCurrency("Overdue:", Overdue, True, iseSummaryTableRowClass.Alt2, iseSummaryTableCellClass.Highlight2)
                    .Cells(1).ForegroundColour = "red"
                    .Cells.AddWiki(String.Format("--as at **{0}**--", finBL.FormatDateLong(accountOverdues.DateAsAtResolved)))
                  End With
                Else
                  Days = DateDiff(DateInterval.Day, accountOverdues(0).Date, accountOverdues.DateAsAtResolved)
                  If Days = 1 Then strTemp = "day" Else strTemp = "days"
                  With .AddCaptionCurrency("Overdue:", Overdue, True, iseSummaryTableRowClass.Alt2, iseSummaryTableCellClass.Highlight2)
                    .Cells(1).ForegroundColour = "red"
                    .Cells.AddWiki(String.Format("--**{0}** {1} as at **{2}**--", Days, strTemp, finBL.FormatDateLong(accountOverdues.DateAsAtResolved)))
                  End With
                End If
                If OverdueToday > 0 Then
                  With .AddCaptionCurrency("plus Due today:", OverdueToday, True, iseSummaryTableRowClass.Alt2, iseSummaryTableCellClass.Highlight2)
                    If Overdue <> 0 Then
                      .Cells.AddWiki(String.Format("--Total to pay today **{0}**--", finBL.FormatCurrency(Overdue + OverdueToday, True)))
                    End If
                  End With
                End If

                ' Promises
                If account.PaymentArrangements.Count = 0 Then
                  PromisesRemaining = 0
                  PromisesToday = 0
                  PromisesFinalDate = Nothing
                Else
                  PromisesRemaining = account.PaymentArrangements(account.PaymentArrangements.Count - 1).Payments.TotalPromisesUnprocessed
                  PromisesToday = account.Transactions.TotalPromisesDueToday
                  PromisesFinalDate = account.PaymentArrangements(account.PaymentArrangements.Count - 1).Payments.PromisesFinalDate
                End If
                If PromisesRemaining <> 0 OrElse PromisesToday <> 0 Then
                  With .AddCaptionCurrency("Promises Remaining:", PromisesRemaining, True, iseSummaryTableRowClass.Alt2, iseSummaryTableCellClass.Highlight2)
                    If PromisesToday = 0 Then
                      .Cells.AddWiki(String.Format("--Net overdue **{0}**. Final Promise due **{1}**--", finBL.FormatCurrency(Overdue - PromisesRemaining, True), finBL.FormatDateLong(PromisesFinalDate)))
                    Else
                      .Cells.AddWiki(String.Format("--Due today **{0}**. Net overdue **{1}**. Final Promise due **{2}**--", finBL.FormatCurrency(PromisesToday, True), finBL.FormatCurrency(Overdue - PromisesRemaining, True), finBL.FormatDateLong(PromisesFinalDate)))
                    End If
                  End With
                End If
              End If

              ' Contractual Overdue
              If account.AccountType.ShowContractualOverdue Then
                ' Get Overdues
                OverdueTodayContractual = accountOverduesC.TotalOverdueToday
                OverdueContractual = accountOverduesC.TotalOverdue - OverdueTodayContractual

                If OverdueContractual = 0 Then
                  .AddCaptionCurrency("Contractual:", 0, True, iseSummaryTableRowClass.Alt2, iseSummaryTableCellClass.Highlight2)
                ElseIf OverdueContractual < 0 Then
                  With .AddCaptionCurrency("Contractual:", OverdueContractual, True, iseSummaryTableRowClass.Alt2, iseSummaryTableCellClass.Highlight2)
                    .Cells(1).ForegroundColour = "green"
                    .Cells.AddWiki(String.Format("--Contractual Prepaid as at **{0}**--", finBL.FormatDateLong(accountOverduesC.DateAsAtResolved)))
                  End With
                ElseIf accountOverduesC.Count = 0 Then
                  With .AddCaptionCurrency("Contractual:", OverdueContractual, True, iseSummaryTableRowClass.Alt2, iseSummaryTableCellClass.Highlight2)
                    .Cells(1).ForegroundColour = "red"
                    .Cells.AddWiki(String.Format("--as at **{0}**--", finBL.FormatDateLong(accountOverduesC.DateAsAtResolved)))
                  End With
                Else
                  Days = DateDiff(DateInterval.Day, accountOverduesC(0).Date, accountOverduesC.DateAsAtResolved)
                  If Days = 1 Then strTemp = "day" Else strTemp = "days"
                  With .AddCaptionCurrency("Contractual:", OverdueContractual, True, iseSummaryTableRowClass.Alt2, iseSummaryTableCellClass.Highlight2)
                    .Cells(1).ForegroundColour = "red"
                    .Cells.AddWiki(String.Format("--**{0}** {1} as at **{2}**--", Days, strTemp, finBL.FormatDateLong(accountOverduesC.DateAsAtResolved)))
                  End With
                End If
                If OverdueTodayContractual > 0 Then
                  With .AddCaptionCurrency("plus Due today:", OverdueTodayContractual, True, iseSummaryTableRowClass.Alt2, iseSummaryTableCellClass.Highlight2)
                    If Overdue <> 0 Then
                      .Cells.AddWiki(String.Format("--Total to pay today **{0}**--", finBL.FormatCurrency(OverdueContractual + OverdueTodayContractual, True)))
                    End If
                  End With
                End If
              ElseIf account.DateMaturity <> Nothing AndAlso DateAsAt > account.DateMaturity AndAlso Balance <> Overdue Then
                ' Include if past Maturity AND Balance (equals Contractual Overdue) differs from Overdue
                With .AddCaptionCurrency("Contractual:", Balance, True, iseSummaryTableRowClass.Alt2, iseSummaryTableCellClass.Highlight2)
                  .Cells(1).ForegroundColour = "red"
                  .Cells.AddWiki("--Full balance overdue as past Maturity--")
                End With
              End If

              ' Promises (for Contractual Overdue)
              If (Not account.AccountType.ShowOverdue) AndAlso account.AccountType.ShowContractualOverdue Then
                If account.PaymentArrangements.Count = 0 Then
                  PromisesRemaining = 0
                  PromisesToday = 0
                  PromisesFinalDate = Nothing
                Else
                  PromisesRemaining = account.PaymentArrangements(account.PaymentArrangements.Count - 1).Payments.TotalPromisesUnprocessed
                  PromisesToday = account.Transactions.TotalPromisesDueToday
                  PromisesFinalDate = account.PaymentArrangements(account.PaymentArrangements.Count - 1).Payments.PromisesFinalDate
                End If
                If PromisesRemaining <> 0 OrElse PromisesToday <> 0 Then
                  With .AddCaptionCurrency("Promises Remaining:", PromisesRemaining, True, iseSummaryTableRowClass.Alt2, iseSummaryTableCellClass.Highlight2)
                    If PromisesToday = 0 Then
                      .Cells.AddWiki(String.Format("--Net overdue **{0}**. Final Promise due **{1}**--", finBL.FormatCurrency(OverdueContractual - PromisesRemaining, True), finBL.FormatDateLong(PromisesFinalDate)))
                    Else
                      .Cells.AddWiki(String.Format("--Due today **{0}**. Net overdue **{1}**. Final Promise due **{2}**--", finBL.FormatCurrency(PromisesToday, True), finBL.FormatCurrency(OverdueContractual - PromisesRemaining, True), finBL.FormatDateLong(PromisesFinalDate)))
                    End If
                  End With
                End If
              End If
            End If

            ' Payments to Date
            Select Case account.AccountClass
              Case isefinAccountClass.LoanFR, isefinAccountClass.LoanFT, isefinAccountClass.LoanRC
                If account.TotalPayments = 0 Then
                  With .AddCaptionCurrency("Total Payments:", 0, True)
                    .Cells(1).ForegroundColour = "red"
                    .Cells.AddWiki("--No payment has been made on this Account yet--")
                  End With
                Else
                  ' Get Last Payment details
                  account.GetLastPayment(LastPaymentDate, LastPaymentValue)

                  With .AddCaptionCurrency("Total Payments:", account.TotalPayments, True)
                    .Cells.AddWiki(String.Format("--Last Payment **{0}** on **{1}**--", finBL.FormatCurrency(LastPaymentValue, True), finBL.FormatDateLong(LastPaymentDate)))
                  End With
                End If
            End Select

            ' Payment Arrangement
            If account.PaymentArrangements.Count <> 0 Then
              AccountPayArrangement = account.PaymentArrangements(account.PaymentArrangements.Count - 1)
              If AccountPayArrangement.IsCurrent Then
                ' Arrangement
                Select Case account.AccountClass
                  Case isefinAccountClass.LoanRC
                    If AccountPayArrangement.UseAltPaySchedule Then
                      strTemp = String.Format("{0} {1}", finBL.FormatCurrency(AccountPayArrangement.PaymentRegular, True), AccountPayArrangement.PaymentCycleDescription)
                    Else
                      strTemp = "Overriding payments only"
                    End If

                  Case Else
                    strTemp = String.Format("{0} {1}", finBL.FormatCurrency(AccountPayArrangement.PaymentRegular, True), AccountPayArrangement.PaymentCycleDescription)
                End Select
                With .AddCaptionDate("Arrangement:", AccountPayArrangement.ArrangementDate)
                  With .Cells.AddWiki(String.Format("--**{0}**--", strTemp))
                    .HyperlinkSetHtmlShowFunction("AccountPaymentArrangementSummary", String.Format("Payment Arrangement Summary for Account {0}, '{1}'", account.AccountId, account.Name), "AccountId=" & account.AccountId)
                  End With
                End With

                ' Promise
                If AccountPayArrangement.Payments.HasPromises Then
                  ' Initialise
                  PromisesCountPending = 0
                  PromisesCountRemaining = 0
                  PromisesLastStatus = isefinTransactionPromiseStatus.NotApplicable

                  For Each AccountPayArrangementPayment In AccountPayArrangement.Payments
                    If AccountPayArrangementPayment.PaymentType = isefinAccountCalcPaymentType.Promise Then
                      PromisesFinalDate = AccountPayArrangementPayment.Date

                      If AccountPayArrangementPayment.Processed Then
                        Select Case AccountPayArrangementPayment.PromiseStatus
                          Case isefinTransactionPromiseStatus.Pending
                            PromisesCountPending += 1
                          Case isefinTransactionPromiseStatus.Pass, isefinTransactionPromiseStatus.Fail, isefinTransactionPromiseStatus.Broken, isefinTransactionPromiseStatus.Cancelled
                            PromisesLastStatus = AccountPayArrangementPayment.PromiseStatus
                        End Select
                      Else
                        PromisesCountRemaining += 1
                      End If
                    End If
                  Next

                  If PromisesCountRemaining = 0 AndAlso PromisesCountPending = 0 Then
                    ' Completed and nothing pending
                    Select Case PromisesLastStatus
                      Case isefinTransactionPromiseStatus.Pass
                        'Warnings &= "{{info|Promise complete.}}"
                      Case isefinTransactionPromiseStatus.Fail
                        Warnings &= "{{warning|Promise FAILED.}}"
                      Case isefinTransactionPromiseStatus.Broken
                        Warnings &= "{{warning|Promise BROKEN.}}"
                      Case isefinTransactionPromiseStatus.Cancelled
                        Warnings &= "{{warning|Promise cancelled.}}"
                    End Select
                  Else
                    Select Case PromisesLastStatus
                      Case isefinTransactionPromiseStatus.Pass
                        Warnings &= "{{info|Last Promise passed.}}"
                      Case isefinTransactionPromiseStatus.Fail
                        Warnings &= "{{warning|Last Promise FAILED.}}"
                      Case isefinTransactionPromiseStatus.Broken
                        Warnings &= "{{warning|Last Promise BROKEN.}}"
                      Case isefinTransactionPromiseStatus.Cancelled
                        Warnings &= "{{warning|Last Promise cancelled.}}"
                    End Select

                    If PromisesCountPending <> 0 Then
                      Warnings &= "{{info|" & String.Format("{0} promises pending.", PromisesCountPending) & "}}"
                    End If
                  End If
                End If
              End If
            End If

            ' Last Reversed Payment Warning
            account.GetLastReversedPayment(LastReversedPaymentDate, LastReversedPaymentValue, LastReversedPaymentDateReversed)
            If LastReversedPaymentDateReversed <> Nothing Then
              Days = DateDiff(DateInterval.Day, LastReversedPaymentDateReversed.Date, DateAsAt)
              If Days < lastReversedPaymentDaysMaximum OrElse LastReversedPaymentDateReversed > LastPaymentDate Then
                If LastReversedPaymentDate = Nothing Then
                  Warnings &= "{{Warning|" & String.Format("Last Reversed Payment: **{0}**, reversed on **{1}**.", finBL.FormatCurrency(LastReversedPaymentValue, True), finBL.FormatDateLong(LastReversedPaymentDateReversed)) & "}}"
                Else
                  Warnings &= "{{Warning|" & String.Format("Last Reversed Payment: **{0}** dated **{1}**, reversed on **{2}**.", finBL.FormatCurrency(LastReversedPaymentValue, True), finBL.FormatDateLong(LastReversedPaymentDate), finBL.FormatDateLong(LastReversedPaymentDateReversed)) & "}}"
                End If
              End If
            End If

            ' Additional information for Deposit Accounts
            Select Case account.AccountClass
              Case isefinAccountClass.Deposit
                ' Get Information
                account.GetInvestmentDetails(InvestmentValue, InvestmentReceived, InvestmentPending)
                account.GetInterestRate(DateAsAt, InterestType, InterestRate, InterestRateTablePk, InterestRatePremium, "", False, Nothing, InterestRateTableIsTiered)

                ' Date Opened
                .AddCaptionDate("Date Opened:", account.DateOpened)

                ' Opening Investment
                With .AddCaptionCurrency("Investment:", InvestmentValue, True)
                  If InvestmentPending > 0 Then
                    .Cells.AddWiki(String.Format("Received **{0}**, !!Pending **{1}**!!", finBL.FormatCurrency(InvestmentReceived, True), finBL.FormatCurrency(InvestmentPending, True)))

                    Warnings &= "{{warning|Investment is pending.}}"
                  ElseIf InvestmentPending < 0 Then
                    .Cells.AddWiki(String.Format("Received **{0}**, Overpaid **{1}**!!", finBL.FormatCurrency(InvestmentReceived, True), finBL.FormatCurrency(-InvestmentPending, True)))

                    Warnings &= "{{warning|Investment is overpaid.}}"
                  End If
                End With

                ' Interest Rate
                Select Case InterestType
                  Case isefinAccountInterestType.FixedRate
                    With .AddCaptionPercentage("Interest Rate:", InterestRate / 100, 4, True)
                      .Cells.AddWiki("--Fixed--")
                    End With
                  Case isefinAccountInterestType.InterestFree
                    With .AddCaptionPercentage("Interest Rate:", InterestRate / 100, 4, True)
                      .Cells.AddWiki("--Interest Free--")
                    End With
                  Case isefinAccountInterestType.RateTable
                    If InterestRateTablePk = 0 Then InterestRateTablePk = account.AccountType.StandardRateTablePk

                    If InterestRateTablePk = 0 Then
                      strTemp = "Rate Table **invalid**"
                    Else
                      InterestRateTableId = finBL.RateTables.ItemByPk(InterestRateTablePk).RateTableId

                      If InterestRatePremium = 0 Then
                        strTemp = String.Format("**{0}**", InterestRateTableId)
                      ElseIf InterestRatePremium < 0 Then
                        strTemp = String.Format("**{0}** less **{1}**", InterestRateTableId, finBL.FormatPercentage(-InterestRatePremium / 100, 4))
                      Else
                        strTemp = String.Format("**{0}** plus **{1}**", InterestRateTableId, finBL.FormatPercentage(InterestRatePremium / 100, 4))
                      End If
                      If Not InterestRateTableIsTiered Then
                        strTemp &= String.Format(" --(net **{0}**)--", finBL.FormatPercentage(InterestRate / 100, 4))
                      End If
                    End If

                    With .AddCaptionPercentage("Interest Rate:", InterestRate / 100, 4, True)
                      .Cells.AddWiki("--" & strTemp & "--")
                    End With
                End Select
            End Select

            ' Maturity Date
            Select Case account.AccountClass
              Case isefinAccountClass.Deposit
                ' Term
                .AddCaptionText("Term:", account.Calculation.TermCycleDescription)

                ' Maturity
                If account.DateMaturity <> Nothing Then
                  ' Get Information
                  account.GetMaturityValues(MaturityInstruction, MaturityValue, MaturityReinvestment, MaturityPaymentType, MaturityPayout, MaturityPrincipalNIB, MaturityPrincipalIB, MaturityInterest, MaturityFeesNIB, MaturityFeesIB)

                  ' Maturity Date
                  With .AddCaptionDate("Maturity Date:", account.DateMaturity)
                    If account.DateMaturity < DateAsAt Then
                      .Cells(1).ForegroundColour = "red"
                      Days = DateDiff(DateInterval.Day, account.DateMaturity, DateAsAt)
                      If Days = 1 Then strTemp = "day" Else strTemp = "days"
                      .Cells.AddWiki(String.Format("--Past Maturity by **{0}** {1}--", Days, strTemp))
                    End If
                  End With

                  ' Maturity Value
                  If MaturityInstruction = isefinAccountMaturityInstruction.ToBeAdvised Then
                    If account.DateMaturity < DateAsAt Then
                      ' Passed Maturity
                      With .AddCaptionCurrency("Maturity Value:", -Balance, True)
                        .Cells.AddWiki(String.Format("--{0}--", finBL.Enums.isefinAccountMaturityInstruction_ToString(MaturityInstruction)))
                      End With
                    Else
                      With .AddCaptionCurrency("Maturity Value:", -(MaturityPrincipalNIB + MaturityPrincipalIB + MaturityInterest + MaturityFeesNIB + MaturityFeesIB), True)
                        .Cells.AddWiki(String.Format("--{0}--", finBL.Enums.isefinAccountMaturityInstruction_ToString(MaturityInstruction)))
                      End With
                    End If
                  Else
                    With .AddCaptionCurrency("Maturity Value:", MaturityReinvestment + MaturityPayout, True)
                      .Cells.AddWiki(String.Format("--{0}--", finBL.Enums.isefinAccountMaturityInstruction_ToString(MaturityInstruction)))
                    End With
                  End If
                End If

              Case isefinAccountClass.LoanFR, isefinAccountClass.LoanFT, isefinAccountClass.LoanRC
                If account.DateMaturity <> Nothing Then
                  With .AddCaptionDate("Maturity Date:", account.DateMaturity)
                    If account.DateMaturity < DateAsAt Then
                      .Cells(1).ForegroundColour = "red"
                      Days = DateDiff(DateInterval.Day, account.DateMaturity, DateAsAt)
                      If Days = 1 Then strTemp = "day" Else strTemp = "days"
                      .Cells.AddWiki(String.Format("--Past Maturity by **{0}** {1}--", Days, strTemp))
                    End If
                  End With
                End If
            End Select

            ' Residual Value
            If account.Calculation.ResidualValue <> 0 Then
              With .AddCaptionCurrency("Residual Value:", account.Calculation.ResidualValue, , , iseSummaryTableCellClass.Highlight2)
                If Not (account.Calculation.Schedule.Count = 0 OrElse account.Calculation.Schedule.Item(account.Calculation.Schedule.Count - 1).Balance >= account.Calculation.ResidualValue) Then
                  .Cells.AddWiki(String.Format("--!!Projected Residual Value **{0}**!!--", finBL.FormatCurrency(account.Calculation.Schedule.Item(account.Calculation.Schedule.Count - 1).Balance, True)))
                End If
              End With
            End If

            ' Projected Final Payment date
            Select Case account.AccountClass
              Case isefinAccountClass.LoanFR, isefinAccountClass.LoanFT
                dateTemp = account.Calculation.PaymentFinalDate

                If Balance < 0 Then
                  ' Credit Balance
                  With .AddCaptionDate("Projected Final Date:", Nothing)
                    .Cells.AddWiki("--**++Credit Balance++**--")
                  End With
                ElseIf dateTemp = Nothing Then
                  ' Insufficient Payment to pay off Loan
                  With .AddCaptionDate("Projected Final Date:", Nothing)
                    .Cells.AddWiki("--**!!Payments insufficient!!**--")
                  End With
                ElseIf account.Calculation.ResidualValue <> 0 AndAlso dateTemp < account.DateMaturity Then
                ElseIf dateTemp < account.DateMaturity Then
                  ' Prior to Maturity
                  Days = DateDiff(DateInterval.Day, dateTemp, account.DateMaturity)
                  If Days = 1 Then strTemp = "day" Else strTemp = "days"
                  With .AddCaptionDate("Projected Final Date:", dateTemp)
                    .Cells(1).ForegroundColour = "green"
                    .Cells.AddWiki(String.Format("--**{0}** {1} prior to Maturity--", Days, strTemp))
                  End With
                ElseIf dateTemp > account.DateMaturity Then
                  ' Past Maturity
                  Days = DateDiff(DateInterval.Day, account.DateMaturity, dateTemp)
                  If Days = 1 Then strTemp = "day" Else strTemp = "days"
                  With .AddCaptionDate("Projected Final Date:", dateTemp)
                    .Cells(1).ForegroundColour = "red"
                    .Cells.AddWiki(String.Format("--**{0}** {1} past Maturity--", Days, strTemp))
                  End With
                End If
            End Select

            ' In Default?
            strTemp = ""
            If account.MonitorCategoryAPk <> 0 AndAlso finBL.MonitorCategories.ItemByPk(account.MonitorCategoryAPk).TreatAsInDefault Then
              strTemp = finBL.Settings.MonitorCategoryADescriptionResolved
            End If
            If account.MonitorCategoryBPk <> 0 AndAlso finBL.MonitorCategories.ItemByPk(account.MonitorCategoryBPk).TreatAsInDefault Then
              If Len(strTemp) <> 0 Then strTemp &= ", "
              strTemp &= finBL.Settings.MonitorCategoryBDescriptionResolved
            End If
            If account.MonitorCategoryCPk <> 0 AndAlso finBL.MonitorCategories.ItemByPk(account.MonitorCategoryCPk).TreatAsInDefault Then
              If Len(strTemp) <> 0 Then strTemp &= ", "
              strTemp = finBL.Settings.MonitorCategoryCDescriptionResolved
            End If
            If Len(strTemp) <> 0 Then
              Warnings &= "{{warning|**In Default** (" & strTemp & ").}}"
            End If
        End Select

        ' ------------------
        ' Monitoring Summary
        ' ------------------
        If includeMonitoringSummary Then
          If finBL.Settings.MonitorCategoryAUse AndAlso account.MonitorCategoryAPk <> 0 Then
            .AddCaptionCodeDescription(finBL.Settings.MonitorCategoryADescriptionResolved & ":", account.MonitorCategoryAPk, finBL.MonitorCategories, , , , iseSummaryTableRowClass.Negative)
          End If
          If finBL.Settings.MonitorCategoryBUse AndAlso account.MonitorCategoryBPk <> 0 Then
            .AddCaptionCodeDescription(finBL.Settings.MonitorCategoryBDescriptionResolved & ":", account.MonitorCategoryBPk, finBL.MonitorCategories, , , , iseSummaryTableRowClass.Negative)
          End If
          If finBL.Settings.MonitorCategoryCUse AndAlso account.MonitorCategoryCPk <> 0 Then
            .AddCaptionCodeDescription(finBL.Settings.MonitorCategoryCDescriptionResolved & ":", account.MonitorCategoryCPk, finBL.MonitorCategories, , , , iseSummaryTableRowClass.Negative)
          End If
        End If
      End With

      ' Warnings
      .TextAfter = Warnings
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Summary.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="account">
  '''  The Account to summarise.
  ''' </param>
  ''' <param name="includeAccountIdHyperlink">
  '''  Indicates whether to include a hyperlink on the Account Id to show the Accounts form.
  ''' </param>
  ''' <param name="showClientAddress">
  '''  Indicates whether to show the Address of the Main Client.
  ''' </param>
  ''' <param name="bankReferenceLength">
  '''  The Bank Reference Length, if 0 will use Global Setting. Will left pad with zeros if necessary, 0 = no padding.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Account Key Details page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''    <item><code>Notes</code><description>Notes (if configured under Global Settings, General, Summary Pages).</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_Summary(callerScriptInfo As ISScriptExecutionInfo,
                                              account As finAccount,
                                     Optional includeAccountIdHyperlink As Boolean = True,
                                     Optional showClientAddress As Boolean = True,
                                     Optional bankReferenceLength As Integer = 0,
                                     Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' Account_Summary
    '
    ' Version: 1.16 (20/08/2024)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.12  12/08/2020  ISS                  
    '    1.13  29/06/2022  ISS      J028870   Source From Account link updated
    '    1.14  07/08/2023  ISS      J031733   Notes added if configured
    '          07/08/2023  ISS      J031731   Support hashtags in Notes
    '    1.15  26/09/2023  ISS      J032101   Refactored AddOn checks
    '          26/09/2023  ISS      J032108   Added hyperlink to Pool details
    '          27/09/2023  ISS      J031250   Added Pool details
    '    1.16  20/08/2024  ISS      J034115   Added Manager
    ' #################################################################

    Dim AccountAccountApp As finAccountAccountApp
    Dim AccountArchiveView As finAccountArchiveView
    Dim AddressDetails As ISAddressDetails
    Dim BalanceRefinancePending As Decimal
    Dim DateAsAt As Date
    Dim Notes As String
    Dim strTemp As String
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTableNotes As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Date As At
    DateAsAt = finBL.TimeZoneFunctions.GetCurrentDatabaseDate()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      .Columns.AddText(16).NoBreakChars = 10
      .Columns.AddText()

      ' Alert Message
      Select Case callerScriptInfo.FormKey
        Case "Accounts", "AccountCreditBureauDefault"
          account.GetAlertMessages(.TextBefore)

        Case Else
          If Len(account.AlertMessage) <> 0 Then .TextBefore = "{{alert|" & account.AlertMessage & "|True}}"
      End Select

      With .Rows
        ' General
        If Len(account.AccountId) = 0 AndAlso account.AccountApp IsNot Nothing Then
          ' Temporary Account from Account Application
          .AddCaptionText("Code:", "[New]")
        Else
          With .AddCaptionText("Code:", account.AccountId)
            If includeAccountIdHyperlink AndAlso Not account.IsNew Then
              .Cells(1).HyperlinkSetFormShow("Accounts", account.AccountId)
            End If
          End With
        End If
        If account.AccountType Is Nothing Then
          ' No Account Type, e.g., created from a partial Account Application
        ElseIf account.AccountType.ShowAccountIdWithCheckDigit AndAlso finBL.Settings.AccountCheckDigitMethod <> isefinCheckDigitMethod.NotUsed Then
          ' Resolve Length
          If bankReferenceLength = 0 Then bankReferenceLength = finBL.Settings.AccountCheckDigitLength

          strTemp = finBL.AccountFunctions.CheckDigitCalculateWithPrefix(account.AccountId, finBL.Settings.AccountCheckDigitMethod, finBL.Settings.AccountCheckDigitPrefix, bankReferenceLength)
          If Len(strTemp) <> 0 Then
            .AddCaptionText(finBL.SupportedCountries.CurrentSupportedCountry.Terminology(isefinCountryTerminology.BankCustomerReference, True) & ":", strTemp)
          End If
        End If
        If finBL.SettingsUser.AccountShowExternalId Then
          .AddCaptionText("External Id:", account.ExternalId)
        End If
        .AddCaptionText("Name:", account.Name, iseSummaryTableCellClass.Highlight1)

        ' Web Details
        If finBL.Settings.AddOns.WebAutomation Then
          ' Web Friendly Name
          If Len(account.WebFriendlyName) <> 0 Then
            .AddCaptionText("Friendly:", account.WebFriendlyName, iseSummaryTableCellClass.Highlight2)
          End If
        End If

        If showClientAddress AndAlso account.Clients.Count <> 0 AndAlso Not account.Clients.HasFilteredOutClients Then
          If account.Clients(0).Client.ContactAddresses.Count <> 0 Then
            AddressDetails = account.Clients(0).Client.ContactAddresses.GetPreviewAddressDetails()
            If AddressDetails IsNot Nothing AndAlso AddressDetails.HasValue Then
              .AddCaptionAddressDetailsPhysical("Address:", AddressDetails)
            End If
          End If
        End If
        .AddCaptionCodeDescription("Type:", account.AccountTypePk, finBL.AccountTypes)

        ' Branch etc        
        If finBL.SettingsUser.SummaryPagesShowBranchResolved AndAlso account.BranchPk <> 0 Then
          With .AddCaptionCodeDescription("Branch:", account.BranchPk, finBL.Branches).Cells(1)
            If finBL.Settings.AddOns.Entity Then
              .Value &= String.Format(" ({0})", account.Entity.Name)
            End If
          End With
        End If
        If finBL.SettingsUser.SummaryPagesShowDepartmentResolved AndAlso account.DepartmentPk <> 0 Then
          .AddCaptionCodeDescription("Department:", account.DepartmentPk, finBL.Departments)
        End If
        If finBL.SettingsUser.SummaryPagesShowManagerResolved AndAlso account.AccountManagerUserPk <> 0 Then
          .AddCaptionCodeDescription("Manager:", account.AccountManagerUserId, finBL.Users)
        End If
        If finBL.SettingsUser.SummaryPagesShowDealerResolved AndAlso account.DealerExternalPartyPk <> 0 Then
          With .AddCaptionCodeDescription("Dealer:", account.DealerExternalPartyPk, finBL.ExternalParties).Cells(1)
            If finBL.ExternalParties.ItemByPk(account.DealerExternalPartyPk).MasterExternalPartyPk <> 0 Then
              .Value &= String.Format(" ({0})", finBL.ExternalParties.ItemByPk(finBL.ExternalParties.ItemByPk(account.DealerExternalPartyPk).MasterExternalPartyPk).Name)
            End If
          End With
        End If
        If finBL.SettingsUser.SummaryPagesShowBrokerResolved AndAlso account.AccountTypePk <> 0 AndAlso account.BrokerExternalPartyPk <> 0 Then
          With .AddCaptionCodeDescription("Broker:", account.BrokerExternalPartyPk, finBL.ExternalParties).Cells(1)
            If finBL.ExternalParties.ItemByPk(account.BrokerExternalPartyPk).MasterExternalPartyPk <> 0 Then
              .Value &= String.Format(" ({0})", finBL.ExternalParties.ItemByPk(finBL.ExternalParties.ItemByPk(account.BrokerExternalPartyPk).MasterExternalPartyPk).Name)
            End If
          End With
        End If
        If finBL.SettingsUser.SummaryPagesShowBulkFunderResolved AndAlso account.BulkFunderExternalPartyPk <> 0 Then
          With .AddCaptionCodeDescription("Bulk Funder:", account.BulkFunderExternalPartyPk, finBL.ExternalParties).Cells(1)
            If finBL.ExternalParties.ItemByPk(account.BulkFunderExternalPartyPk).MasterExternalPartyPk <> 0 Then
              .Value &= String.Format(" ({0})", finBL.ExternalParties.ItemByPk(finBL.ExternalParties.ItemByPk(account.BulkFunderExternalPartyPk).MasterExternalPartyPk).Name)
            End If
          End With
        End If
        If finBL.SettingsUser.SummaryPagesShowPoolResolved AndAlso account.PoolPk <> 0 Then
          If finBL.HtmlWidgetUtilities.HasPermissionToViewFormKey("Pools", "") Then
            .AddCaptionCodeDescriptionWithFormShow("Pool:", account.PoolPk, finBL.Pools, "Pools")
          Else
            .AddCaptionCodeDescription("Pool:", account.PoolPk, finBL.Pools)
          End If
        End If

        ' Status
        If account.IsRefinancePending Then
          If account.GetBalanceRefinancePending(BalanceRefinancePending) Then
            strTemp = String.Format("Balance prior to Refinance {0}", finBL.FormatCurrency(BalanceRefinancePending, True))
          Else
            strTemp = ""
          End If
        Else
          strTemp = ""
        End If
        If Len(strTemp) = 0 Then
          .AddCaptionText("Status:", account.StatusText, iseSummaryTableCellClass.Highlight2)
        Else
          .AddCaptionWiki("Status:", "**" & account.StatusText & "**" & vbNewLine & "--" & strTemp & "--", iseSummaryTableCellClass.Highlight2)
        End If

        ' Source
        If account.CreatedFromAccountPk <> 0 Then
          If Len(account.CreatedFromAccountId) = 0 Then
            ' The Account may have been archived - so retrieve this
            AccountArchiveView = account.CreatedFromAccountArchive()

            If AccountArchiveView Is Nothing Then
              .AddCaptionWiki("Source:", String.Format("**{0}**", account.CreationMethodText))
            Else
              .AddCaptionWiki("Source:", String.Format("**{0}** --from Account [[app://formshow?form=AccountArchiveView&id={1}|{2}]]--", account.CreationMethodText, CStr(AccountArchiveView.Pk), AccountArchiveView.AccountId))
            End If
          Else
            .AddCaptionWiki("Source:", String.Format("**{0}** --from Account [[app://formshow?form=Accounts&id={1}|{2}]]--", account.CreationMethodText, finBL.UrlEncode(account.CreatedFromAccountId), account.CreatedFromAccountId))
          End If
        End If

        ' Created from Account Application
        If finBL.Settings.AddOns.AccountApplication Then
          For Each AccountAccountApp In account.AccountApps
            .AddCaptionCodeDescriptionWithFormShow("Application:", AccountAccountApp.AccountAppPk, finBL.AccountAppFunctions, "AccountApps")
          Next
        End If

        ' Status-specific
        Select Case account.Status
          Case isefinAccountStatus.Closed, isefinAccountStatus.ClosedPending
            ' Closed/ Closed Pending
            .AddSectionHeading2("Close Details")
            .AddCaptionDate("Closed:", account.DateClosed)
            If account.ClosedToAccountPk = 0 Then
              strTemp = ""
            Else
              strTemp = String.Format(" to Account [[app://formshow?form=Accounts&id={0}|{1}]]", finBL.UrlEncode(account.ClosedToAccountId), account.ClosedToAccountId)
            End If
            If Len(strTemp) = 0 Then
              .AddCaptionText("Method:", account.CloseMethodText)
            Else
              .AddCaptionWiki("Method:", String.Format("**{0}** --{1}--", account.CloseMethodText, strTemp))
            End If
            .AddCaptionText("Notes:", account.CloseNote)

            ' Warnings
            If account.Status = isefinAccountStatus.ClosedPending Then
              If account.DateClosedPendingReview < DateAsAt Then
                Warnings &= "{{warning|" & String.Format("**Pending finalisation**. Review date of **{0}** has passed.", finBL.FormatDateLong(account.DateClosedPendingReview)) & "}}"
              Else
                Warnings &= "{{info|" & String.Format("**Pending finalisation**. For review on **{0}**.", finBL.FormatDateLong(account.DateClosedPendingReview)) & "}}"
              End If
            End If

          Case isefinAccountStatus.Quote
            ' Quote
            .AddSectionHeading2("Quote Details")
            .AddCaptionDate("Date Quoted:", account.DateQuoted)
            .AddCaptionText("Quote Ready:", If(account.DateQuoteReady = Nothing, "", "{{tick}}"))
            .AddCaptionDate("Date Ready:", account.DateQuoteReady)
            .AddCaptionText("Notes:", account.QuoteNote)

          Case isefinAccountStatus.Declined, isefinAccountStatus.Unwanted
            ' Declined/ Unwanted
            .AddSectionHeading2(String.Format("{0} Details", account.StatusText))
            .AddCaptionDate(String.Format("{0}:", account.StatusText), account.DateClosed)
            .AddCaptionText("Notes:", account.CloseNote)
            .AddCaptionText("By:", account.CloseByWhom)
            If Len(account.CloseReason) <> 0 Then
              .AddCaptionText("Reason:", account.CloseReason)
            End If
        End Select
      End With

      ' Warnings
      .TextAfter = Warnings
    End With

    ' Notes
    If finBL.Settings.SummaryPagesShowNotes AndAlso Len(account.Notes) <> 0 Then
      SummaryTableNotes = finBL.CreateSummaryTable()

      ' Support hashtagging?
      Notes = account.Notes
      If finBL.Settings.QuickSearch2SupportHashtags Then
        Notes = finBL.Utilities.ParseHashTags(Notes)
      End If

      ' Main
      With SummaryTableNotes
        ' Initialise
        .TableClass = iseSummaryTableClass.Information
        .Caption = "Notes"
        .Columns.AddText()

        .Rows.AddText(Notes)
      End With
    End If

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)
    If SummaryTableNotes IsNot Nothing Then SummaryTables.Add("Notes", SummaryTableNotes)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Suspension Summary.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="account">
  '''  The Account to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Status page and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_Suspension(callerScriptInfo As ISScriptExecutionInfo,
                                                 account As finAccount,
                                        Optional includeActions As Boolean = True,
                                        Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' Account_Suspension
    '
    ' Version: 1.06 (29/07/2024)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.05  18/05/2017  ISS                  
    '    1.06  29/07/2024  ISS      J033979   Added reference to new finAccount.CanUpdateSuspensions() function
    ' #################################################################

    Dim DateAsAt As Date
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim SuspendActionText As String
    Dim SuspensionUpdateAllowed As Boolean
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Date As At
    DateAsAt = finBL.TimeZoneFunctions.GetCurrentDatabaseDate()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      .Columns.AddText()

      If account.IsSuspended Then
        ' Suspended
        .TextBefore = "The following are currently suspended:"
        SuspendActionText = "Review"

        With .Rows
          If account.SuspendInterest Then
            Select Case account.AccountClass
              Case isefinAccountClass.LoanFR, isefinAccountClass.LoanFT, isefinAccountClass.LoanRC
                .AddText("Interest + Default Interest & Fees", iseSummaryTableCellClass.NormalBold)
              Case Else
                .AddText("Interest", iseSummaryTableCellClass.NormalBold)
            End Select
          Else
            If account.SuspendDefaultInterest Then .AddText("Default Interest", iseSummaryTableCellClass.NormalBold)
            If account.SuspendDefaultFees Then
              If account.AccountType.OverLimitFeeChargeBasis = isefinOverLimitFeeChargeBasis.None Then
                .AddText("Default Fees", iseSummaryTableCellClass.NormalBold)
              Else
                .AddText("Default and Over Limit Fees", iseSummaryTableCellClass.NormalBold)
              End If
            End If
            If account.SuspendFacilityFee Then .AddText("Facility Fee", iseSummaryTableCellClass.NormalBold)
          End If
          If account.SuspendStandardTransactions Then .AddText("Standard Transactions", iseSummaryTableCellClass.NormalBold)
          If account.SuspendWithdrawals Then .AddText("Withdrawals", iseSummaryTableCellClass.NormalBold)
          If account.SuspendDocuments Then .AddText("Documents", iseSummaryTableCellClass.NormalBold)
          If account.SuspendOverdueRules Then .AddText("Overdue Rule Processing", iseSummaryTableCellClass.NormalBold)
          If account.SuspendCreditReporting Then .AddText("Comprehensive Credit Reporting", iseSummaryTableCellClass.NormalBold)
          If account.SuspendOther Then .AddText(finBL.Settings.AccountSuspendOtherCaptionResolved, iseSummaryTableCellClass.NormalBold)
        End With

        ' Warnings
        If account.SuspendDateReview.Date < DateAsAt Then
          Warnings &= "{{warning|Review was due on **" & finBL.FormatDateLong(account.SuspendDateReview) & "**.}}"
        ElseIf account.SuspendDateReview.Date = DateAsAt Then
          Warnings &= "{{info|Due for review **today**.}}"
        Else
          Warnings &= "{{info|Due for review on **" & finBL.FormatDateLong(account.SuspendDateReview) & "**.}}"
        End If
      Else
        ' Not Suspended
        Warnings &= "{{info|Not suspended.}}"
        SuspendActionText = "Suspend"
      End If

      ' Warnings
      .TextAfter = Warnings

      ' Actions
      If includeActions Then
        SuspensionUpdateAllowed = account.CanUpdateSuspensions()
        With .Actions
          .AddFormAction("SuspensionEdit", SuspendActionText, Not finBL.Database.IsReadOnly AndAlso SuspensionUpdateAllowed).ShowInWebInterfaces = True
          .AddFormAction("SuspensionClear", "Clear", Not finBL.Database.IsReadOnly AndAlso account.IsSuspended AndAlso (Not (account.SuspendInterest OrElse account.SuspendStandardTransactions)) AndAlso SuspensionUpdateAllowed).ShowInWebInterfaces = True
        End With
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Client Summary.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="client">
  '''  The Client to summarise.
  ''' </param>
  ''' <param name="includedContactMethodPks">
  '''  A list of Client Contact Methods included in the 'Contacts' table. This can be used to exclude these Contact Methods from other places on the Summary Page.
  ''' </param>
  ''' <param name="includeClientIdHyperlink">
  '''  Indicates whether to include a hyperlink on the Client Id to show the Clients form.
  ''' </param>
  ''' <param name="includeInvalidContactMethods">
  '''  Indicates whether to include invalid Phone Numbers and Email Addresses.
  ''' </param>
  ''' <param name="includeAkas">
  '''  Indicates whether to include the AKAs table.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  '''  <para>
  '''   The following parameters may be specified:
  '''   <list>
  '''   <item><code>SingleTable</code><description>Include all details in "Main" Summary Table.</description></item>
  '''   <item><code>ImageWidthPixels</code><description>If greater than 0 include Image as the width specified.</description></item>
  '''   </list>
  '''  </para>
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Client Key Details page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''    <item><code>Contacts</code><description>Contact details (optional if parameters "SingleTable"=False).</description></item>
  '''    <item><code>Akas</code><description>AKA details (optional).</description></item>
  '''    <item><code>Notes</code><description>Notes (if configured under Global Settings, General, Summary Pages).</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Client_Summary3(callerScriptInfo As ISScriptExecutionInfo,
                                              client As finClient,
                                              ByRef includedContactMethodPks As ISList,
                                     Optional includeClientIdHyperlink As Boolean = True,
                                     Optional includeInvalidContactMethods As Boolean = False,
                                     Optional includeAkas As Boolean = True,
                                     Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' Client_Summary3
    '
    ' Version: 1.07 (20/08/2024)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.00  15/03/2021  ISS      J027878   Created for C# compatibility    
    '    1.01  04/04/2021  ISS      J028554   Updated to use new GetFullName function
    '    1.02  05/04/2023  ISS      J030731   PEP Status
    '    1.03  20/04/2023  ISS      J030717   Add Image, Combined tables
    '    1.04  07/08/2023  ISS      J031733   Notes added if configured
    '          31/08/2023  ISS      J031731   Support hashtags in Notes
    '          26/09/2023  ISS      J032101   Refactored AddOn checks
    '    1.05  04/01/2024  ISS      J032692   SMS and Email now use "External Party" where appropriate
    '          04/01/2023  ISS      J032693   Show Mobile for Organisations
    '    1.06  08/02/2023  ISS      J032876   Show NZBN/ABN; Hide Legal Name if blank
    '    1.07  29/05/2024  ISS      J033540   Changed DOB formatting
    '          20/08/2024  ISS      J034115   Added Manager
    ' #################################################################

    Dim ClientAka As finClientAka
    Dim ClientContactMethod As finClientContactMethod
    Dim ClientContactMethodHome As finClientContactMethod
    Dim ClientContactMethodMobile As finClientContactMethod
    Dim ClientContactMethodWork As finClientContactMethod
    Dim ExternalParty As finExternalPartyRO
    Dim ExternalPartyId As String
    Dim ImageWidthPixels As Integer
    Dim Message As String
    Dim Notes As String
    Dim SingleTable As Boolean
    Dim strTemp As String
    Dim SummaryTableAkas As ISSummaryTable
    Dim SummaryTableContacts As ISSummaryTable
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTableNotes As ISSummaryTable
    Dim SummaryTables As ISSummaryTables

    ' Initialise ByRef Parameters
    includedContactMethodPks = New ISList()

    ' Get Constants

    ' Get Other Parameters
    If otherParameters Is Nothing Then
      SingleTable = False
      ImageWidthPixels = 0
    Else
      SingleTable = otherParameters.GetBoolean("SingleTable")
      ImageWidthPixels = otherParameters.GetInteger("ImageWidthPixels")
    End If

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    If SingleTable Then
      SummaryTableAkas = SummaryTableMain
      SummaryTableContacts = SummaryTableMain
      SummaryTableNotes = SummaryTableMain
    Else
      SummaryTableAkas = finBL.CreateSummaryTable()
      SummaryTableContacts = finBL.CreateSummaryTable()
      SummaryTableNotes = finBL.CreateSummaryTable()
    End If
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      .Columns.AddText(16)
      .Columns.AddText()

      ' Alert Message
      If Len(client.AlertMessage) <> 0 Then
        .TextBefore = "{{alert|" & client.AlertMessage & "|true}}"
      End If

      With .Rows
        ' General
        If Len(client.ClientId) = 0 AndAlso client.AccountAppApplicantPk <> 0 Then
          ' Temporary Client from Account Application
          .AddCaptionText("Code:", "[New]")
        Else
          With .AddCaptionText("Code:", client.ClientId)
            If includeClientIdHyperlink Then
              .Cells(1).HyperlinkSetFormShow("Clients", client.ClientId)
            End If
          End With
        End If
        If finBL.SettingsUser.ClientShowExternalId Then
          .AddCaptionText("External Id:", client.ExternalId)
        End If
        .AddCaptionText("Name:", client.Name, iseSummaryTableCellClass.Highlight1)
        .AddCaptionCodeDescription("Type:", client.ClientTypePk, finBL.ClientTypes)

        ' Branch etc
        If finBL.SettingsUser.SummaryPagesShowBranchResolved AndAlso client.BranchPk <> 0 Then
          With .AddCaptionCodeDescription("Branch:", client.BranchPk, finBL.Branches).Cells(1)
            If finBL.Settings.AddOns.Entity Then
              .Value &= String.Format(" ({0})", client.Entity.Name)
            End If
          End With
        End If
        If finBL.SettingsUser.SummaryPagesShowManagerResolved AndAlso client.ClientManagerUserPk <> 0 Then
          .AddCaptionCodeDescription("Manager:", client.ClientManagerUserId, finBL.Users)
        End If

        ' Individual/ Organisation
        If client.IsIndividual Then
          If client.DateOfBirth = Nothing Then
            strTemp = ""
          ElseIf client.IsIndividualDeceased Then
            strTemp = "!!Deceased!!"
          Else
            strTemp = finBL.Runtime.DateUtilities.AgeAsText(client.DateOfBirth, Nothing, True)
          End If
          .AddCaptionWiki("Date of Birth:", String.Format("**{0}** --{1}--", finBL.FormatDateLong(client.DateOfBirth), strTemp))
          .AddCaptionText("Gender:", client.GenderText)
          .AddCaptionText("Occupation:", client.Occupation)
        ElseIf client.IsSoleTrader Then
          .AddCaptionText("Occupation:", client.Occupation)
        Else
          .AddCaptionText("Contact:", client.GetFullName(False, True))
          If Len(client.LegalName) <> 0 Then
            .AddCaptionText("Legal Name:", client.LegalName)
          End If
          If Len(client.BusinessNumber) <> 0 Then
            strTemp = finBL.SupportedCountries.CurrentSupportedCountry.Terminology(isefinCountryTerminology.BusinessNumber, True)
            If Len(strTemp) = 0 Then strTemp = "Business No"
            .AddCaptionText(strTemp & ":", client.BusinessNumber)
          End If
        End If

        ' Status
        .AddCaptionText("Credit Rating:", client.CreditRating)
        Select Case client.Status
          Case isefinClientStatus.None : strTemp = ""
          Case Else : strTemp = "{{icon|ClientStatus" & client.Status.ToString() & "}}"
        End Select
        .AddCaptionText("Status:", String.Format("{0} {1}", client.StatusText, strTemp))

        If client.IsIndividual Then
          Select Case client.PepStatus
            Case isefinClientPepStatus.Unknown
              If client.PepStatusDate = Nothing Then
                .AddCaptionWiki("PEP Status:", "**Unknown**")
              Else
                .AddCaptionWiki("PEP Status:", String.Format("**Unknown** {0}", finBL.FormatDateLong(client.PepStatusDate)))
              End If

            Case isefinClientPepStatus.No
              If client.PepStatusDate = Nothing Then
                .AddCaptionWiki("PEP Status:", String.Format("++**{0}**++", client.PepStatusText))
              Else
                .AddCaptionWiki("PEP Status:", String.Format("++**{0}** --{1}--++", client.PepStatusText, finBL.FormatDateLong(client.PepStatusDate)))
              End If

            Case Else
              If client.PepStatusDate = Nothing Then
                .AddCaptionWiki("PEP Status:", String.Format("!!**{0}**!!", client.PepStatusText))
              Else
                .AddCaptionWiki("PEP Status:", String.Format("!!**{0}** --{1}--!!", client.PepStatusText, finBL.FormatDateLong(client.PepStatusDate)))
              End If

          End Select
        End If
      End With

      ' Special Type
      strTemp = ""
      Select Case client.SpecialType
        Case isefinClientSpecialType.Branch
          If callerScriptInfo.FormKey = "Branches" Then
            ' Ignore on Branch form
          Else
            strTemp = String.Format("This is a special Client linked to Branch **[[app://FormShow?form=Branches&id={0}|{1}]]**, {2}.", finBL.UrlEncode(client.ParentBranch.BranchId), client.ParentBranch.BranchId, client.ParentBranch.Name)
          End If

        Case isefinClientSpecialType.ExternalParty
          If finBL.Settings.AddOns.ExternalParty Then
            ExternalParty = client.ParentExternalPartyRO

            If ExternalParty IsNot Nothing Then
              ExternalPartyId = ExternalParty.ExternalPartyId
              strTemp = String.Format("This is a special Client linked to {0} **[[app://FormShow?form=ExternalParties&id={1}|{2}]]**, {3}.", ExternalParty.ExternalPartyTypeText, finBL.UrlEncode(ExternalPartyId), ExternalPartyId, ExternalParty.Name)
            End If
          End If
      End Select
      If Len(strTemp) <> 0 Then
        .TextAfter = "{{info|" & strTemp & "}}"
      End If

      ' Add Client Image
      If finBL.DocumentManager.IsAvailableResolved AndAlso ImageWidthPixels > 0 Then
        If Len(client.ImageFileName) <> 0 Then
          ' Client Image or video
          .TextRight = "{{ClientImage ClientId='" & client.ClientId & "' width='" & CStr(ImageWidthPixels) & "'}}"
        ElseIf client.AccountAppApplicant IsNot Nothing AndAlso Len(client.AccountAppApplicant.ImageFileName) <> 0 Then
          ' Applicant Image
          .TextRight = "{{DocumentManagerImage width='" & CStr(ImageWidthPixels) & "' fileName='" & client.AccountAppApplicant.ImageFileNameResolved & "'}}"
        End If
      End If
    End With

    ' Contact Details
    With SummaryTableContacts
      If SingleTable Then
        ' Add Heading
        .Rows.AddSectionHeading3("Contact Details")
      Else
        ' Initialise Table
        .TableClass = iseSummaryTableClass.Information
        .Caption = "Contact Details"
        .Columns.AddText(16)
        .Columns.AddText()
      End If

      With SummaryTableContacts.Rows
        ClientContactMethodMobile = client.ContactMethods.GetCurrentPhone(, , , , iseTriState.True,, includeInvalidContactMethods)

        If client.IsIndividual Then
          ' Get Contact Methods
          ClientContactMethodHome = client.ContactMethods.GetCurrentPhone(, , , iseTriState.True,,, includeInvalidContactMethods)
          ClientContactMethodWork = client.ContactMethods.GetCurrentPhone(, , , , , iseTriState.True, includeInvalidContactMethods)

          ' Home
          If ClientContactMethodHome.IsNew Then
            ' Not found so try any phone number
            ClientContactMethod = client.ContactMethods.GetCurrentPhone()

            includedContactMethodPks.Add(CStr(ClientContactMethod.Pk))
            If ClientContactMethod.Value = ClientContactMethodWork.Value OrElse ClientContactMethod.Value = ClientContactMethodMobile.Value Then
              ' Ignore since it is the same as the Work or Mobile number
              .AddCaptionText("Home:", "")
            Else
              .AddCaptionTextPhoneNumber("Phone:", ClientContactMethod.Value, , client.ClientId, CStr(ClientContactMethod.Pk), ClientContactMethod.Notes)
            End If
          Else
            includedContactMethodPks.Add(CStr(ClientContactMethodHome.Pk))
            With .AddCaptionTextPhoneNumber("Home:", ClientContactMethodHome.Value, , client.ClientId, CStr(ClientContactMethodWork.Pk), ClientContactMethodHome.Notes)
              If Not finBL.Runtime.Validation.IsValidPhoneNumber(ClientContactMethodHome.Value, Message, True) Then
                .Cells.Add("{{warning|" & Message & "}}", iseSummaryTableCellClass.SmallBold)
              End If
            End With
          End If

          ' Work
          includedContactMethodPks.Add(CStr(ClientContactMethodWork.Pk))
          With .AddCaptionTextPhoneNumber("Work:", ClientContactMethodWork.Value, , client.ClientId, CStr(ClientContactMethodWork.Pk), ClientContactMethodWork.Notes)
            If Not finBL.Runtime.Validation.IsValidPhoneNumber(ClientContactMethodWork.Value, Message, True) Then
              .Cells.Add("{{warning|" & Message & "}}", iseSummaryTableCellClass.SmallBold)
            End If
          End With

          ' Mobile
          includedContactMethodPks.Add(CStr(ClientContactMethodMobile.Pk))
          With .AddCaptionTextPhoneNumber("Mobile:", ClientContactMethodMobile.Value, , client.ClientId, CStr(ClientContactMethodMobile.Pk), ClientContactMethodMobile.Notes)
            If Not finBL.Runtime.Validation.IsValidPhoneNumber(ClientContactMethodMobile.Value, Message, True) Then
              .Cells.Add("{{warning|" & Message & "}}", iseSummaryTableCellClass.SmallBold)
            End If
          End With
        Else
          ' Phone
          ClientContactMethod = client.ContactMethods.GetCurrentPhone(,,,,,, includeInvalidContactMethods)
          includedContactMethodPks.Add(CStr(ClientContactMethod.Pk))
          With .AddCaptionTextPhoneNumber("Phone:", ClientContactMethod.Value, , client.ClientId, CStr(ClientContactMethod.Pk), ClientContactMethod.Notes,,, ExternalPartyId)
            If Not finBL.Runtime.Validation.IsValidPhoneNumber(ClientContactMethod.Value, Message, True) Then
              .Cells.Add("{{warning|" & Message & "}}", iseSummaryTableCellClass.SmallBold)
            End If
          End With

          ' Mobile
          If ClientContactMethodMobile.Pk = 0 OrElse ClientContactMethodMobile.Pk = ClientContactMethod.Pk Then
            ' Ignore since it is the same as the above Phone number
          Else
            includedContactMethodPks.Add(CStr(ClientContactMethodMobile.Pk))
            With .AddCaptionTextPhoneNumber("Mobile:", ClientContactMethodMobile.Value, , client.ClientId, CStr(ClientContactMethodMobile.Pk), ClientContactMethodMobile.Notes,,, ExternalPartyId)
              If Not finBL.Runtime.Validation.IsValidPhoneNumber(ClientContactMethodMobile.Value, Message, True) Then
                .Cells.Add("{{warning|" & Message & "}}", iseSummaryTableCellClass.SmallBold)
              End If
            End With
          End If


          ' Web Site
          ClientContactMethod = client.ContactMethods.GetCurrentWebsite()
          includedContactMethodPks.Add(CStr(ClientContactMethod.Pk))
          .AddCaptionTextWebsiteUrl("Website:", ClientContactMethod.Value, , client.ClientId, CStr(ClientContactMethod.Pk), ClientContactMethod.Notes)
        End If

        ' Email
        ClientContactMethod = client.ContactMethods.GetCurrentEmail(,,,,,, includeInvalidContactMethods)
        includedContactMethodPks.Add(CStr(ClientContactMethod.Pk))
        With .AddCaptionTextEmailAddress("Email:", ClientContactMethod.Value, , client.ClientId, CStr(ClientContactMethod.Pk), ClientContactMethod.Notes,,, ExternalPartyId)
          If Not finBL.Runtime.Validation.IsValidEmailAddress(ClientContactMethod.Value, Message, True) Then
            .Cells.Add("{{warning|" & Message & "}}", iseSummaryTableCellClass.SmallBold)
          End If
        End With
      End With
    End With

    If includeAkas AndAlso client.Akas.Count <> 0 Then
      With SummaryTableAkas
        If SingleTable Then
          With .Rows
            ' Add Heading
            .AddSectionHeading3("Also Known As")

            For Each ClientAka In client.Akas
              If client.IsOrganisation Then
                .AddText(ClientAka.Name).Cells(0).ColSpan = 2
              Else
                .AddText(finBL.Runtime.TextUtilities.ListSeparate(" ", ClientAka.Title, ClientAka.FirstName, ClientAka.MiddleNames, ClientAka.LastName)).Cells(0).ColSpan = 2
              End If
            Next
          End With
        Else
          ' Initialise Table
          .TableClass = iseSummaryTableClass.Information
          .Caption = "Also Known As"
          .Columns.AddText()

          With .Rows
            For Each ClientAka In client.Akas
              If client.IsOrganisation Then
                .AddText(ClientAka.Name)
              Else
                .AddText(finBL.Runtime.TextUtilities.ListSeparate(" ", ClientAka.Title, ClientAka.FirstName, ClientAka.MiddleNames, ClientAka.LastName))
              End If
            Next
          End With
        End If
      End With
    End If

    ' Notes
    If finBL.Settings.SummaryPagesShowNotes AndAlso Len(client.Notes) <> 0 Then
      ' Support hashtagging?
      Notes = client.Notes
      If finBL.Settings.QuickSearch2SupportHashtags Then
        Notes = finBL.Utilities.ParseHashTags(Notes)
      End If

      ' Main
      With SummaryTableNotes
        If SingleTable Then
          ' Add Heading
          .Rows.AddSectionHeading3("Notes")
        Else
          ' Initialise Table
          .TableClass = iseSummaryTableClass.Information
          .Caption = "Notes"
          .Columns.AddText()
        End If

        .Rows.AddText(Notes)
      End With
    Else
      SummaryTableNotes = Nothing
    End If

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)
    If Not SingleTable Then
      SummaryTables.Add("Contacts", SummaryTableContacts)
      If includeAkas Then SummaryTables.Add("Akas", SummaryTableAkas)
      If SummaryTableNotes IsNot Nothing Then SummaryTables.Add("Notes", SummaryTableNotes)
    End If

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Client Summary for a Filtered Out Client (Version 1.0, Last updated 29/07/2013).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="client">
  '''  The Client to summarise.
  ''' </param>
  ''' <param name="includeClientIdHyperlink">
  '''  Indicates whether to include a hyperlink on the Client Id to show the Clients form.
  ''' </param>
  ''' <param name="includedContactMethodPks">
  '''  A list of Client Contact Methods included in this summary that can be used to exclude from other places on the Summary Page.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Client Key Details page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Client_SummaryFilteredOut(callerScriptInfo As ISScriptExecutionInfo,
                                                        client As finClient,
                                                        includeClientIdHyperlink As Boolean,
                                               Optional ByRef includedContactMethodPks As ISList = Nothing,
                                               Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables

    ' Initialise ByRef Parameters
    includedContactMethodPks = New ISList()

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      .Columns.AddText(16)
      .Columns.AddText()

      ' Alert Message
      If Len(client.AlertMessage) <> 0 Then
        .TextBefore = "{{alert|" & client.AlertMessage & "|true}}"
      End If

      With .Rows
        ' General
        With .AddCaptionText("Code:", client.ClientId)
          If includeClientIdHyperlink Then
            .Cells(1).HyperlinkSetFormShow("Clients", client.ClientId)
          End If
        End With
        If finBL.SettingsUser.ClientShowExternalId Then
          .AddCaptionText("External Id:", client.ExternalId)
        End If
        .AddCaptionText("Name:", client.Name, iseSummaryTableCellClass.Highlight1)
        .AddCaptionCodeDescription("Type:", client.ClientTypePk, finBL.ClientTypes)
      End With

      ' Filtered Out Warning
      .TextAfter = "{{warning|You do not have permission to view this Client.}}"
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Client Tax Certificates (Version 1.01, Last updated 15/01/2020).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="client">
  '''  The Client to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Payments page and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Client_TaxCertificates(callerScriptInfo As ISScriptExecutionInfo,
                                                     client As finClient,
                                            Optional includeActions As Boolean = True,
                                            Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim ClientTaxCertificate As finClientTaxCertificate
    Dim LastYear As Integer
    Dim RowAlt As iseSummaryTableRowClass
    Dim ShowNonGrouped As Boolean
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants
    ShowNonGrouped = False

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()
    RowAlt = iseSummaryTableRowClass.Alt2

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .AutoStripe = False
      .Caption = ""

      If client.TaxCertificates.Count = 0 Then
        ' No Tax Certificates
        Warnings &= "{{info|No Tax Certificates generated.}}"
      Else
        ' Columns
        With .Columns
          .AddText("Certificate")
          .AddDate("Date")
          .AddText("Type")
          If ShowNonGrouped Then .AddText("Avg Rate", 8, iseSummaryTableCellTextAlign.Right).NoBreakChars = 8
          .AddCurrency("Gross", 12)
          .AddCurrency("W/Tax", 12)
          .AddCurrency("Net", 12)
        End With

        With .Rows
          For Each ClientTaxCertificate In client.TaxCertificates
            If ShowNonGrouped OrElse ClientTaxCertificate.GroupTaxCertificatePk = 0 Then
              ' Stripe when Year changes
              If Year(ClientTaxCertificate.Date) <> LastYear Then
                LastYear = Year(ClientTaxCertificate.Date)
                If RowAlt = iseSummaryTableRowClass.Alt1 Then
                  RowAlt = iseSummaryTableRowClass.Alt2
                Else
                  RowAlt = iseSummaryTableRowClass.Alt1
                End If
              End If

              ' Add Group Row
              With .Add(RowAlt).Cells
                With .AddText(ClientTaxCertificate.CertificateNumber)
                  If ClientTaxCertificate.ClientLogPk <> 0 Then
                    ' Show Tax Certificate Log
                    .HyperlinkSetFormShow("ClientLog", CStr(ClientTaxCertificate.ClientLogPk))
                  End If
                End With
                .AddDate(ClientTaxCertificate.Date)
                .AddText(ClientTaxCertificate.TaxCertificateTypeText)
                If ShowNonGrouped Then
                  .AddText(finBL.FormatPercentage(ClientTaxCertificate.AverageWTaxRate / 100, 4))
                  .AddCurrency(ClientTaxCertificate.TotalGross)
                  .AddCurrency(ClientTaxCertificate.TotalWithholdingTax)
                  .AddCurrency(ClientTaxCertificate.TotalNet)
                Else
                  .AddCurrency(ClientTaxCertificate.GroupTotalGross)
                  .AddCurrency(ClientTaxCertificate.GroupTotalWithholdingTax)
                  .AddCurrency(ClientTaxCertificate.GroupTotalNet)
                End If
              End With
            End If
          Next
        End With
      End If

      ' Warnings
      .TextAfter = Warnings

      ' Actions
      If includeActions Then
        With .Actions
        End With
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Application Account Summary (Version 1.03, Last updated 7/06/2017).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="accountApp">
  '''  The Account Application.
  ''' </param>
  ''' <param name="accountAppCalculation">
  '''  The Calculation that was used to create the Account.
  ''' </param>
  ''' <param name="account">
  '''  The Account to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Account Applications form, Account page. May preview either the Account that will be created or the actual Account that was created.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function AccountApp_AccountSummary(callerScriptInfo As ISScriptExecutionInfo,
                                                        accountApp As finAccountApp,
                                                        accountAppCalculation As finAccountAppCalculation,
                                                        account As finAccount,
                                               Optional includeActions As Boolean = True,
                                               Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim strTemp As String
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim WarningMessage As String
    Dim WarningSeverity As isefinAccountWarningSeverity
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Validate Account
    If account.IsNew Then
      ' Validate
      If accountApp.AccountAppType Is Nothing Then
        ' Not initialised
      ElseIf Not accountApp.AccountAppType.ValidateAccount(accountApp, accountAppCalculation, account, WarningSeverity, WarningMessage) Then
        WarningSeverity = isefinAccountWarningSeverity.Fail
        WarningMessage = finBL.Error.Message(True)
      End If
    Else
      ' Real Account so do nothing
    End If

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      .Columns.AddText(16).NoBreakChars = 10
      .Columns.AddText()

      ' Preview New Account link
      If includeActions AndAlso Not accountApp.IsClosed AndAlso Not accountApp.IsNew AndAlso Not accountAppCalculation.IsNew Then
        If callerScriptInfo.FormKey = "AccountApps" AndAlso callerScriptInfo.FormRecordMode = iseFormRecordMode.Edit Then
          ' Use Form Action is editing Account Application, i.e., may have unsaved information
          .TextBefore &= "{{button icon='Verify' caption='View Account that will be generated' hyperlink='app://formaction?action=ShowTempAccount'}}"
        Else
          ' Use Application Shortcut
          strTemp = "{AccountAppCalculation|" & accountApp.AccountAppId & "|" & accountAppCalculation.Pk & "}"
          .TextBefore &= "{{button icon='Verify' caption='View Account that will be generated' hyperlink='app://formshow?form=Accounts&id=" & finBL.UrlEncode(strTemp) & "'}}"
        End If
      End If

      ' Validation Message
      If Len(WarningMessage) <> 0 Then
        Select Case WarningSeverity
          Case isefinAccountWarningSeverity.Alert
            .TextBefore &= "{{warning|" & WarningMessage & "|true}}"
          Case isefinAccountWarningSeverity.Fail
            .TextBefore &= "{{alert|" & WarningMessage & "|true}}"
          Case isefinAccountWarningSeverity.Information
            .TextBefore &= "{{info|" & WarningMessage & "|true}}"
        End Select
      End If

      ' Alert Message
      If Len(account.AlertMessage) <> 0 Then
        .TextBefore &= "{{alert|" & account.AlertMessage & "|true}}"
      End If

      With .Rows
        ' General
        If account.IsNew Then
          ' New Account
          .AddCaptionText("Code:", "[New]")
        Else
          ' Open Actual Account
          With .AddCaptionText("Code:", account.AccountId)
            .Cells(1).HyperlinkSetFormShow("Accounts", account.AccountId)
          End With
        End If
        .AddCaptionText("Name:", account.Name)

        ' Account Type
        If account.AccountTypePk <> 0 Then
          '.AddCaptionCodeDescription("Product Type:", account.ProductTypeId, finBL.ProductTypes)
          .AddCaptionCodeDescription("Account Type:", account.AccountTypePk, finBL.AccountTypes)
          If finBL.Settings.AddOns.Promotions AndAlso account.AccountTypePromotionPk <> 0 Then
            .AddCaptionCodeDescription("Promotion:", account.AccountTypePromotionId, account.AccountTypePromotionDescription)
          End If
        End If

        ' Account Manager
        If account.AccountManagerUserPk <> 0 Then
          .AddCaptionCodeDescription("Manager:", account.AccountManagerUserPk, finBL.Users)
        End If

        ' Status-specific
        Select Case account.Status
          Case isefinAccountStatus.Quote
            ' Quote
            If account.DateQuoted <> Nothing OrElse account.DateQuoteReady <> Nothing OrElse account.DateQuoteReady <> Nothing OrElse account.QuoteNote <> Nothing Then
              .AddSectionHeading2("Quote Details")
              If account.DateQuoted <> Nothing Then
                .AddCaptionDate("Date Quoted:", account.DateQuoted)
              End If
              'If account.DateQuoteReady <> Nothing Then
              '  .AddCaptionText("Quote Ready:", If(account.DateQuoteReady = Nothing, "", "{{tick}}"))
              'End If
              'If account.DateQuoteReady <> Nothing Then
              '  .AddCaptionDate("Date Ready:", account.DateQuoteReady)
              'End If
              'If Len(account.QuoteNote) <> 0 Then
              '  .AddCaptionText("Notes:", account.QuoteNote)
              'End If
            End If
        End Select

        ' Other Details
        .AddSectionHeading2("Other Details")
        If Len(account.Purpose) <> 0 Then
          .AddCaptionText("Purpose:", account.Purpose)
        End If
        If Len(account.Source) <> 0 Then
          .AddCaptionText("Source:", account.Source)
        End If
        If Len(account.Region) <> 0 Then
          .AddCaptionText("Region:", account.Region)
        End If

        ' Branch etc (don't use User-based Summary Page options like Account does since this is more or a representation of the Accounts form)
        If finBL.Settings.AddOns.Branch AndAlso account.BranchPk <> 0 Then
          With .AddCaptionCodeDescription("Branch:", account.BranchPk, finBL.Branches).Cells(1)
            If finBL.Settings.AddOns.Entity Then
              .Value &= String.Format(" ({0})", account.Entity.Name)
            End If
          End With
        End If
        If account.DepartmentPk <> 0 Then
          .AddCaptionCodeDescription("Department:", account.DepartmentPk, finBL.Departments)
        End If
        If finBL.Settings.AddOns.ExternalPartyDealers AndAlso account.DealerExternalPartyPk <> 0 Then
          With .AddCaptionCodeDescription("Dealer:", account.DealerExternalPartyPk, finBL.ExternalParties).Cells(1)
            If finBL.ExternalParties.ItemByPk(account.DealerExternalPartyPk).MasterExternalPartyPk <> 0 Then
              .Value &= String.Format(" ({0})", finBL.ExternalParties.ItemByPk(finBL.ExternalParties.ItemByPk(account.DealerExternalPartyPk).MasterExternalPartyPk).Name)
            End If
          End With
          If account.DealerExternalPartyEmployeePk <> 0 Then
            .AddCaptionCodeDescription("Employee:", account.DealerExternalPartyEmployeeClientEmploymentId, account.DealerExternalPartyEmployeeName)
          End If
        End If
        If account.AccountTypePk <> 0 AndAlso finBL.Settings.AddOns.ExternalPartyBrokers Then
          With .AddCaptionCodeDescription("Broker:", account.BrokerExternalPartyPk, finBL.ExternalParties).Cells(1)
            If account.BrokerExternalPartyPk <> 0 AndAlso finBL.ExternalParties.ItemByPk(account.BrokerExternalPartyPk).MasterExternalPartyPk <> 0 Then
              .Value &= String.Format(" ({0})", finBL.ExternalParties.ItemByPk(finBL.ExternalParties.ItemByPk(account.BrokerExternalPartyPk).MasterExternalPartyPk).Name)
            End If
          End With
          If account.BrokerExternalPartyEmployeePk <> 0 Then
            .AddCaptionCodeDescription("Employee:", account.BrokerExternalPartyEmployeeClientEmploymentId, account.BrokerExternalPartyEmployeeName)
          End If
        End If

        ' Insurance
        If account.AccountTypePk <> 0 AndAlso account.AccountType.IncludeAccountLevelInsurance AndAlso finBL.Settings.AddOns.ExternalPartyInsurers Then
          .AddSectionHeading2("Insurance details")
          .AddCaptionCodeDescription("Insurer:", account.InsuranceInsurerExternalPartyPk, finBL.ExternalParties)
          If Len(account.InsurancePolicyType) <> 0 Then
            .AddCaptionText("Policy Type:", account.InsurancePolicyType)
          End If
          If Len(account.InsurancePolicyNumber) <> 0 Then
            .AddCaptionText("Policy Number:", account.InsurancePolicyNumber)
          End If
        End If
      End With

      ' Warnings
      .TextAfter = Warnings
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Application Applicant Summary (Version 1.02, Last updated 16/12/2015).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="accountAppApplicant">
  '''  The Account Application Applicant.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Account Applications form, Applicants page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function AccountApp_ApplicantSummary(callerScriptInfo As ISScriptExecutionInfo,
                                                          accountAppApplicant As finAccountAppApplicant,
                                                 Optional includeActions As Boolean = True,
                                                 Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim strTemp As String
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      .Columns.AddText(16).NoBreakChars = 10
      .Columns.AddText()

      ' Preview New/ Updated Client link
      If includeActions AndAlso Not accountAppApplicant.AccountApp.IsClosed AndAlso Not accountAppApplicant.IsNew Then
        If callerScriptInfo.FormKey = "AccountApps" AndAlso callerScriptInfo.FormRecordMode = iseFormRecordMode.Edit Then
          ' Use Form Action is editing Account Application, i.e., may have unsaved information
          strTemp = "app://formaction?action=ShowTempClient"
        Else
          ' Use Application Shortcut
          strTemp = "app://formshow?form=Clients&id=" & finBL.UrlEncode("{AccountAppApplicant|" & accountAppApplicant.AccountApp.AccountAppId & "|" & accountAppApplicant.Pk & "}")
        End If

        If accountAppApplicant.ClientPk = 0 Then
          ' New Client
          .TextBefore &= "{{button icon='Verify' caption='View new Client that will be generated' hyperlink='" & strTemp & "'}}"
        ElseIf accountAppApplicant.UpdateClient Then
          ' Update existing Client
          .TextBefore &= "{{button icon='Verify' caption='View existing Client from Applicant' hyperlink='" & strTemp & "'}}"
        End If
      End If

      ' Used?
      If Not accountAppApplicant.Used Then
        .TextBefore &= "{{warning|Unused Applicant will not be included on Account or create/update a Client record.|true}}"
      End If

      With .Rows
        ' General
        .AddCaptionText("Name:", accountAppApplicant.Name, iseSummaryTableCellClass.Highlight1)

        If accountAppApplicant.AccountRoleResolvedPk = 0 Then
          strTemp = "!!Not defined!!"
        Else
          With finBL.AccountRoles.ItemByPk(accountAppApplicant.AccountRoleResolvedPk)
            strTemp = String.Format("**{0}**, {1}", .AccountRoleId, .Description)
          End With
        End If
        If accountAppApplicant.AccountRoleJointResolved Then
          strTemp &= " --(Joint Applicant)--"
        End If
        .AddCaptionWiki("Account Role:", strTemp)

        If accountAppApplicant.ClientTypePk <> 0 Then
          .AddCaptionCodeDescription("Client Type:", accountAppApplicant.ClientTypePk, finBL.ClientTypes)
        End If
        If accountAppApplicant.ClientGroupPk <> 0 Then
          .AddCaptionCodeDescription("Client Group:", accountAppApplicant.ClientGroupPk, finBL.ClientGroups)
        End If

        ' Client
        If accountAppApplicant.ClientPk <> 0 OrElse accountAppApplicant.CreatedClientPk <> 0 Then
          .AddSectionHeading2("Client Details")
          If accountAppApplicant.ClientPk <> 0 Then
            .AddCaptionCodeDescription("Client:", accountAppApplicant.ClientPk, finBL.ClientFunctions)
          End If
          If accountAppApplicant.CreatedClientPk <> 0 Then
            .AddCaptionCodeDescription("Created Client:", accountAppApplicant.CreatedClientPk, finBL.ClientFunctions)
          End If
        End If

        ' Notes
        If Len(accountAppApplicant.Notes) <> 0 Then
          .AddSectionHeading2("Notes")
          .AddText(accountAppApplicant.Notes)
        End If
      End With

      ' Warnings
      If Not accountAppApplicant.AccountApp.IsClosed AndAlso accountAppApplicant.UpdateClient Then
        ' Warnings
        If accountAppApplicant.LoadedFromClientPk <> 0 AndAlso accountAppApplicant.ClientPk = 0 Then
          Warnings &= "{{info|Loaded from Client '" & accountAppApplicant.LoadedFromClientId & "' but this Client will not be updated.}}"
        ElseIf accountAppApplicant.LoadedFromClientPk = 0 AndAlso accountAppApplicant.ClientPk <> 0 Then
          If accountAppApplicant.CreatedClientPk = accountAppApplicant.ClientPk Then
            ' This Client has been created from this Applicant (manually from the Account Application Applicant wizard)
          Else
            Warnings &= "{{warning|Client '" & accountAppApplicant.ClientId & "' will be updated but this Applicant has not been pre-loaded from a Client.}}"
          End If
        ElseIf accountAppApplicant.LoadedFromClientPk <> 0 AndAlso accountAppApplicant.ClientPk <> 0 AndAlso accountAppApplicant.LoadedFromClientPk <> accountAppApplicant.ClientPk Then
          Warnings &= "{{warning|Applicant was pre-loaded from Client '" & accountAppApplicant.LoadedFromClientId & "' but is configured to update Client '" & accountAppApplicant.ClientId & "'.|True}}"
        End If
      ElseIf Not accountAppApplicant.AccountApp.IsClosed AndAlso accountAppApplicant.LoadedFromClientPk <> 0 Then
        Warnings &= "{{info|Loaded from Client '" & accountAppApplicant.LoadedFromClientId & "' but this Client will not be updated.}}"
      ElseIf Not accountAppApplicant.AccountApp.IsClosed AndAlso accountAppApplicant.ClientPk <> 0 Then
        Warnings &= "{{info|Linked to existing Client but this Client will not be updated.}}"
      End If
      If accountAppApplicant.AccountRolePk <> 0 AndAlso accountAppApplicant.AccountRolePk <> accountAppApplicant.AccountRoleResolvedPk Then
        Warnings &= "{{info|Account Role updated.}}"
      End If
      If accountAppApplicant.AccountRoleJoint <> accountAppApplicant.AccountRoleJointResolved Then
        Warnings &= "{{info|Joint Applicant updated.}}"
      End If
      .TextAfter = Warnings

      ' Actions
      If includeActions Then

      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Application Applicant Enquiries and Decisions (Version 1.03, Last updated 24/09/2018).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="accountAppApplicant">
  '''  The Account Application Applicant.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Account Applications form, Applicants page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Enquiries</code><description>Enquiry details.</description></item>
  '''    <item><code>Decisions</code><description>Decision details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function AccountApp_ApplicantEnquiriesAndDecisions(callerScriptInfo As ISScriptExecutionInfo,
                                                                        accountAppApplicant As finAccountAppApplicant,
                                                               Optional includeActions As Boolean = True,
                                                               Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim DecisionOutcome As finDecisionOutcome
    Dim Description As String
    Dim i As Integer
    Dim Icon As String
    Dim Include As Boolean
    Dim Log As finLogRO
    Dim PageName As String
    Dim SummaryTableDecisions As ISSummaryTable
    Dim SummaryTableEnquiries As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableDecisions = finBL.CreateSummaryTable()
    SummaryTableEnquiries = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Enquiries
    Warnings = ""
    With SummaryTableEnquiries
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .Caption = "Enquiries"
      .AutoStripe = True
      .MaxDisplayRows = 10

      ' Columns
      With .Columns
        .AddCode(" ", 1) ' Icon
        .AddDate("Date")
        .AddText("Description")
      End With

      For i = accountAppApplicant.AccountApp.Logs.Count - 1 To 0 Step -1
        Log = accountAppApplicant.AccountApp.Logs(i)

        ' Include?
        Select Case Log.LogClass
          Case isefinLogClass.AccountApp
            Include = (Log.SubSourcePk = accountAppApplicant.Pk)
          Case isefinLogClass.Client
            Include = (Log.SourcePk = accountAppApplicant.ClientPk)
        End Select
        If Include Then
          Include = False
          If Log.ServiceLogPk <> 0 Then
            Select Case UCase(Log.ServiceLog.ServiceType)
              Case "CREDITBUREAU"
                ' Credit Bureau
                Select Case UCase(Log.ServiceLog.ProductClass)
                  Case "BANKACCOUNTENQUIRY"
                    ' Bank Account Enquiry
                    Include = True
                    Icon = "BankAccountEnquiry"
                    PageName = "Bank Account Enquiry"
                    Description = Replace(Log.Subject, "BankAccountEnquiry.", "")

                  Case "CREDITENQUIRY"
                    ' Credit Enquiry
                    Include = True
                    Icon = "CreditEnquiry"
                    PageName = "Credit Enquiry"
                    Description = Replace(Log.Subject, "CreditBureau.", "")
                End Select

              Case "SECURITYENQUIRY"
                ' Security Enquiry
                Include = True
                Icon = "SecurityEnquiry"
                PageName = "Security Enquiry"
                Description = Log.Subject

              Case "SECURITYREGISTER"
                ' Security Register
                Select Case UCase(Log.ServiceLog.ServiceId & "." & Log.ServiceLog.ProductId)
                  Case "PPSRB2G.AU.SEARCHREGISTRATION"
                    ' PPSR (Australia)
                    Include = True
                    Icon = "LOGO_PPSR_AU"
                    PageName = "PPSR*"
                    Description = Log.Subject

                  Case "PPSRG2B.NZ.PPSR_SEARCH", "PPSRNZ.SEARCH"
                    ' PPSR (New Zealand)
                    Include = True
                    Icon = "LOGO_PPSR_NZ"
                    PageName = "PPSR*"
                    Description = Log.Subject
                End Select

              Case "SMS"
                ' Ignore
            End Select
          End If
        End If

        ' Add
        If Include Then
          With .Rows.Add()
            ' To Action?
            If Log.ActionDate <> Nothing AndAlso Log.ActionCompleteDate = Nothing Then
              .RowClass = iseSummaryTableRowClass.NormalBold
            End If

            ' Hide links to duplicate Service Logs
            .Visible = Not Log.DuplicateServiceLink

            With .Cells
              .AddText("{{Icon|" & Icon & "|" & Log.LogSourceText & "}}")
              .AddDate(Log.LogDate)
              With .AddText(Description)
                ' Hyperlink (Log Source Text just happens to match the page name on the Log forms)
                Select Case Log.LogClass
                  Case isefinLogClass.AccountApp
                    .HyperlinkSetFormShow("AccountAppLog", CStr(Log.Pk), PageName)
                  Case isefinLogClass.Client
                    .HyperlinkSetFormShow("ClientLog", CStr(Log.Pk), PageName)
                End Select
              End With
            End With
          End With
        End If
      Next

      ' Warnings
      .TextAfter = Warnings
    End With

    ' Decisions
    Warnings = ""
    With SummaryTableDecisions
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .Caption = "Decisions"
      .AutoStripe = True
      .MaxDisplayRows = 10

      ' Columns
      With .Columns
        .AddCode(" ", 1) ' Icon
        .AddDate("Date")
        .AddText("Description")
      End With

      For i = accountAppApplicant.AccountApp.Logs.Count - 1 To 0 Step -1
        Log = accountAppApplicant.AccountApp.Logs(i)

        ' Include?
        Select Case Log.LogClass
          Case isefinLogClass.AccountApp
            Include = (Log.SubSourcePk = accountAppApplicant.Pk)
          Case isefinLogClass.Client
            Include = (Log.SourcePk = accountAppApplicant.ClientPk)
        End Select
        If Include Then
          If Log.ExtendedType = isefinLogExtendedType.DecisionOutcome Then
            Include = True
            PageName = "Decision Outcome"
            Description = Log.Subject
            If Log.GetDecisionOutcomeFromExtendedData(DecisionOutcome) Then
              Select Case DecisionOutcome.OutcomeStatus
                Case isefinDecisionOutcomeStatus.Fail
                  Icon = "Outcome_Failed"
                  If Len(DecisionOutcome.OutcomeMessage) <> 0 Then Description &= vbNewLine & "!!--" & DecisionOutcome.OutcomeMessage & "--!!"
                Case isefinDecisionOutcomeStatus.None
                  Icon = "Blank"
                Case isefinDecisionOutcomeStatus.Pass
                  Icon = "Outcome_Success"
                  If Len(DecisionOutcome.OutcomeMessage) <> 0 Then Description &= vbNewLine & "++--" & DecisionOutcome.OutcomeMessage & "--++"
                Case isefinDecisionOutcomeStatus.Refer
                  Icon = "Outcome_Neutral"
                  If Len(DecisionOutcome.OutcomeMessage) <> 0 Then Description &= vbNewLine & "--" & DecisionOutcome.OutcomeMessage & "--"
              End Select
            Else
              ' Ignore Error
              Icon = "Blank"
            End If
          Else
            Include = False
          End If
        End If

        ' Add
        If Include Then
          With .Rows.Add()
            ' To Action?
            If Log.ActionDate <> Nothing AndAlso Log.ActionCompleteDate = Nothing Then
              .RowClass = iseSummaryTableRowClass.NormalBold
            End If

            With .Cells
              .AddText("{{Icon|" & Icon & "}}")
              .AddDate(Log.LogDate)
              With .AddWiki(Description)
                ' Hyperlink (Log Source Text just happens to match the page name on the Log forms)
                Select Case Log.LogClass
                  Case isefinLogClass.AccountApp
                    .HyperlinkSetFormShow("AccountAppLog", CStr(Log.Pk), PageName)
                  Case isefinLogClass.Client
                    .HyperlinkSetFormShow("ClientLog", CStr(Log.Pk), PageName)
                End Select
              End With
            End With
          End With
        End If
      Next

      ' Warnings
      .TextAfter = Warnings
    End With

    ' Add Summary Tables
    SummaryTables.Add("Enquiries", SummaryTableEnquiries)
    SummaryTables.Add("Decisions", SummaryTableDecisions)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Application Applicant Logs Summary (Version 1.00, Last updated 12/03/2015).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="accountAppApplicant">
  '''  The Applicant to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Workflow Key Details page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function AccountApp_ApplicantLogs(callerScriptInfo As ISScriptExecutionInfo,
                                                       accountAppApplicant As finAccountAppApplicant,
                                              Optional maxDisplayRows As Integer = 20,
                                              Optional includeActions As Boolean = True,
                                              Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim Action As String
    Dim Log As finLogRO
    Dim Logs As List(Of finLogRO)
    Dim LogClassesList As ISList
    Dim i As Integer
    Dim ShowAction As Boolean
    Dim ShowLogClass As Boolean
    Dim ShowPublish As Boolean
    Dim ShowSeverity As Boolean
    Dim strTemp As String
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()
    Logs = New List(Of finLogRO)

    ' Determine Logs and Columns to include
    ShowAction = False
    ShowPublish = False
    ShowSeverity = False
    LogClassesList = New ISList()
    For Each Log In accountAppApplicant.AccountApp.Logs
      ' Include?
      If (Log.LogSubClass = isefinLogSubClass.AccountAppApplicant AndAlso Log.SubSourcePk = accountAppApplicant.Pk) OrElse
         (Log.LogClass = isefinLogClass.Client AndAlso Log.SourcePk = accountAppApplicant.ClientPk) Then
        ' Add to List
        Logs.Add(Log)

        ' Determine Columns
        If Log.ActionDate <> Nothing AndAlso Log.ActionCompleteDate = Nothing Then ShowAction = True
        If Log.PublishStatus <> isefinLogPublishStatus.None Then ShowPublish = True
        If Log.LogSeverityPk <> 0 Then ShowSeverity = True
        LogClassesList.Add(Log.LogClass.ToString(), True)
      End If
    Next
    ShowLogClass = LogClassesList.Count > 1

    ' Main
    With SummaryTableMain
      If Logs.Count = 0 Then
        .TextBefore = "{{info|No linked logs.}}"
      Else
        ' Initialise
        .TableClass = iseSummaryTableClass.TabularData
        .Caption = ""
        .AutoStripe = True
        .MaxDisplayRows = maxDisplayRows
        .ShowHiddenRowsCaption = "Show More Logs"

        ' Columns
        With .Columns
          If ShowLogClass Then .AddBoolean(" ")
          If ShowSeverity Then .AddBoolean(" ")
          .AddDate("Date")
          .AddText("Subject")
          If ShowAction Then .AddText("Action", 10)
          If ShowPublish Then .AddCode("Publish", 10)
        End With

        With .Rows
          ' Reverse order so latest are at the top
          For i = Logs.Count - 1 To 0 Step -1
            ' Initialise
            Log = Logs(i)

            With .Add()
              ' Incomplete
              If Log.IsIncomplete OrElse Log.IsAwaitingPublish Then
                .RowClass = iseSummaryTableRowClass.NormalBold
              End If

              ' Hide if not issued
              If Log.PublishStatus = isefinLogPublishStatus.NotIssued Then
                .Visible = False
              End If

              ' Hide if duplicate Service Log (e.g., a Client Log recording a Credit Enquiry when an Applicant Log exists too)
              If Log.DuplicateServiceLink Then
                .Visible = False
              End If

              With .Cells
                If ShowLogClass Then
                  Select Case Log.LogClass
                    Case isefinLogClass.Account : strTemp = "Account"
                    Case isefinLogClass.AccountApp : strTemp = "AccountApp"
                    Case isefinLogClass.Client : strTemp = "Client"
                    Case isefinLogClass.SecurityStmt : strTemp = "SecurityStmt"
                    Case isefinLogClass.SecurityStmtItem : strTemp = "SecurityType"
                    Case isefinLogClass.User : strTemp = "User"
                    Case Else : strTemp = "Blank"
                  End Select
                  .AddText("{{icon|" & strTemp & "|" & Log.LogClassText & "}}")
                End If

                If ShowSeverity Then
                  If Log.LogSeverityPk = 0 Then
                    .AddText("")
                  ElseIf Log.ActionDate <> Nothing AndAlso Log.ActionCompleteDate = Nothing Then
                    .AddText("{{colourblock|" & Log.LogSeverity.OpenColourBackground & "|" & Log.LogSeverity.LogSeverityId & ", " & Log.LogSeverity.Description & "}}")
                  Else
                    .AddText("{{colourblock|" & Log.LogSeverity.CompleteColourBackground & "|" & Log.LogSeverity.LogSeverityId & ", " & Log.LogSeverity.Description & "}}")
                  End If
                End If

                .AddDate(Log.LogDate)

                ' Make Subject splitable (auto-generated subjects such as Credit Enquiries have no spaces and therefore force columns too wide)
                strTemp = Log.Subject
                If Len(strTemp) > 20 Then
                  If InStr(strTemp, ".") <> 0 Then
                    strTemp = Replace(strTemp, ".", ". ")
                  End If
                End If
                With .AddText(strTemp)
                  .HyperlinkSetFormShow(Log.LogFormKey, CStr(Log.Pk))
                End With

                If ShowAction Then
                  If Log.ActionDate = Nothing Then
                    Action = ""
                  ElseIf Log.ActionCompleteDate = Nothing Then
                    Action = finBL.FormatDateForGrid(Log.ActionDate)
                  Else
                    Action = "Complete"
                  End If
                  .AddText(Action)
                End If
                If ShowPublish Then
                  If Log.PublishStatus = isefinLogPublishStatus.None Then
                    .AddText("")
                  Else
                    .AddText(Log.PublishStatusText)
                  End If
                End If
              End With
            End With
          Next
        End With

        ' Warnings
        .TextAfter = Warnings

        ' Actions
        If includeActions Then
          With .Actions
          End With
        End If
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Application Collateral Items (Version 1.01, Last updated 20/06/2017).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="accountApp">
  '''  The Account Application to summarise.
  ''' </param>
  ''' <param name="includeUnused">
  '''  Indicates whether to include 'Unused' items.
  ''' </param>
  ''' <param name="showReference">
  '''  Indicates whether to include a 'Reference' column.
  ''' </param>
  ''' <param name="showTradeIn">
  '''  Indicates whether to include a 'Trade In' column.
  ''' </param>
  ''' <param name="showDefunct">
  '''  Indicates whether to include a 'Defunct' column.
  ''' </param>
  ''' <param name="includeTradeIns">
  '''  Indicates whether to Include Trade In Items.
  ''' </param>
  ''' <param name="includeDefunct">
  '''  Indicates whether to Include Defunct Items.
  ''' </param>
  ''' <param name="includeRegisterStatusNa">
  '''  Indicates whether to Include Items with a Register Status of 'Not Applicable'.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="maxDisplayRows">
  '''  The Maximum number of Rows to Display in the table before a 'Show Hidden' link is displayed.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Security Statement Key Details pages and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function AccountApp_CollateralItems(callerScriptInfo As ISScriptExecutionInfo,
                                                         accountApp As finAccountApp,
                                                Optional includeUnused As Boolean = False,
                                                Optional showReference As Boolean = True,
                                                Optional showTradeIn As Boolean = False,
                                                Optional showDefunct As Boolean = False,
                                                Optional includeTradeIns As Boolean = True,
                                                Optional includeDefunct As Boolean = False,
                                                Optional includeRegisterStatusNa As Boolean = False,
                                                Optional maxDisplayRows As Integer = 20,
                                                Optional includeActions As Boolean = True,
                                                Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim AccountAppCollateralItem As finAccountAppCollateralItem
    Dim Include As Boolean
    Dim Index As Integer
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .Caption = ""
      .AutoStripe = True
      .MaxDisplayRows = maxDisplayRows
      .ShowHiddenRowsCaption = "Show More Collateral Items"

      ' Columns
      If accountApp.CollateralItems.Count = 0 Then
        .TextBefore = "{{info|No Collateral Items listed for this Account Application.}}"
      ElseIf Not includeUnused AndAlso accountApp.CollateralItems.CountUsed = 0 Then
        .TextBefore = "{{info|No 'Used' Collateral Items listed for this Account Application.}}"
      ElseIf Not includeDefunct AndAlso Not includeTradeIns AndAlso accountApp.CollateralItems.HasOnlyDefunctAndTradeIns Then
        .TextBefore = "{{info|Only Trade-In or Defunct Collateral Items listed for this Account Application.}}"
      Else
        With .Columns
          .AddInteger("#", 1)
          .AddCode(" ", 1).TextAlign = iseSummaryTableCellTextAlign.Center  ' Icon
          .AddCode("Type", 5)
          If showReference Then .AddText("Reference", 10)
          If showTradeIn Then .AddBoolean("Trade-In").NoBreakChars = 10
          If showDefunct Then .AddBoolean("Defunct")
          If finBL.Settings.SecurityStmtInsuranceBrokerTerminology Then
            .AddText("Policy No", 10).NoBreakChars = 20
            .AddText("Description")
            .AddCurrency("Cover")
            .AddCurrency("Premium")
          Else
            .AddText("Serial No", 10).NoBreakChars = 20
            .AddText("Description")
            .AddCurrency("Value")
            .AddCurrency("Security Value").NoBreakChars = 20
          End If
        End With

        With .Rows
          Index = 0
          For Each AccountAppCollateralItem In accountApp.CollateralItems
            ' Index
            Index += 1

            ' Include?
            'If AccountAppCollateralItem.RegisterStatus = iseSecurityStmtRegisterStatus.NotApplicable AndAlso Not includeRegisterStatusNa Then
            '  Include = False
            If AccountAppCollateralItem.TradeIn AndAlso Not includeTradeIns Then
              Include = False
            ElseIf AccountAppCollateralItem.Defunct AndAlso Not includeDefunct Then
              Include = False
            Else
              Include = True
            End If

            ' Add Row
            If Include Then
              With .Add()
                ' Unused?
                If Not AccountAppCollateralItem.Used Then
                  .ForegroundColour = "gray"
                End If

                With .Cells
                  .AddInteger(Index)
                  If AccountAppCollateralItem.SecurityType Is Nothing OrElse Len(AccountAppCollateralItem.SecurityType.Icon) = 0 Then
                    .AddText("")
                  Else
                    .AddText("{{icon|SecurityType_" & AccountAppCollateralItem.SecurityType.Icon & "}}")
                  End If
                  If AccountAppCollateralItem.SecurityType Is Nothing Then
                    .AddText("")
                  Else
                    .AddText(AccountAppCollateralItem.SecurityType.DescriptionShortResolved)
                  End If
                  If showReference Then
                    .AddText(AccountAppCollateralItem.Reference)
                  End If
                  If showTradeIn Then
                    .AddTick(AccountAppCollateralItem.TradeIn, , True)
                  End If
                  If showDefunct Then
                    .AddTick(AccountAppCollateralItem.Defunct, , True)
                  End If
                  .AddText(AccountAppCollateralItem.SerialNumberResolved)
                  With .AddText(AccountAppCollateralItem.DescriptionResolved)
                    ' Edit Collateral Item
                    If Not finBL.Database.IsReadOnly AndAlso accountApp.AccountAppType IsNot Nothing AndAlso accountApp.AccountAppType.DataEntryCollateralHtmlWidgetScriptPk <> 0 AndAlso Not accountApp.IsClosed Then
                      .HyperlinkSetApplicationShortcutUrl(accountApp.AccountAppType.GetApplicationShortcutUrlHtmlWidgetCollateralItem(accountApp.Pk, AccountAppCollateralItem.Pk, False))
                    End If
                  End With
                  'If finBL.Settings.SecurityStmtInsuranceBrokerTerminology Then
                  '  .AddCurrency(AccountAppCollateralItem.InsuranceSumInsured)
                  '  .AddCurrency(AccountAppCollateralItem.InsurancePremium)
                  'Else
                  .AddCurrency(AccountAppCollateralItem.Value)
                  .AddCurrency(AccountAppCollateralItem.SecurityValue)
                  'End If
                End With
              End With
            End If
          Next
        End With
      End If

      ' Warnings
      .TextAfter = Warnings

      ' Actions
      If includeActions Then
        With .Actions
          ' Add Collateral Item
          If Not finBL.Database.IsReadOnly AndAlso accountApp.AccountAppType IsNot Nothing AndAlso accountApp.AccountAppType.DataEntryCollateralHtmlWidgetScriptPk <> 0 AndAlso accountApp.AccountAppType.AllowAdditionalCollateral AndAlso Not accountApp.IsClosed Then
            .AddApplicationShortcutUrl("ItemAdd", "Add Collateral", accountApp.AccountAppType.GetApplicationShortcutUrlHtmlWidgetCollateralItem(accountApp.Pk, -1, False), callerScriptInfo.FormRecordMode = iseFormRecordMode.Loaded).ShowInWebInterfaces = True
          End If
        End With
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Application Collateral Item Enquiries.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="accountAppCollateralItem">
  '''  The Collateral Item to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Security Statement Key Details page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function AccountApp_CollateralItemEnquiries(callerScriptInfo As ISScriptExecutionInfo,
                                                                 accountAppCollateralItem As finAccountAppCollateralItem,
                                                        Optional includeActions As Boolean = True,
                                                        Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' AccountApp_CollateralItemEnquiries
    '
    ' Version: 1.02 (11/11/2024)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.00  25/05/2016  ISS                Created
    '    1.01  14/06/2024  ISS      J033547   Reversed order of items so most recent are displayed first
    '    1.02  11/11/2024  ISS      J034681   Show the Summary Page Report instead of the Service Log
    ' #################################################################

    Dim DifferencesUpdate As Boolean
    Dim DifferencesView As Boolean
    Dim i As Integer
    Dim j As Integer
    Dim ServiceLog As ISServiceLog
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Show Differences?
    Select Case callerScriptInfo.FormKey
      Case "AccountApps"
        DifferencesView = True
        DifferencesUpdate = callerScriptInfo.FormRecordMode = iseFormRecordMode.Add OrElse callerScriptInfo.FormRecordMode = iseFormRecordMode.Edit
      Case Else
        DifferencesView = False
    End Select

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .Caption = ""
      .AutoStripe = True

      If accountAppCollateralItem.SecurityEnquiries.Count = 0 Then
        .TextBefore = "{{info|No Security Enquiries found.}}"
      Else
        ' Columns
        With .Columns
          .AddDateTime("Created")
          .AddText("User")
          .AddText("Service")
          .AddText("Product")
          If DifferencesView Then .AddText("Differences")
        End With

        With .Rows
          For i = accountAppCollateralItem.SecurityEnquiries.Count - 1 To 0 Step -1
            ServiceLog = accountAppCollateralItem.SecurityEnquiries(i)

            With .Add()
              ' Only show last Enquiry for each Service/ Product
              For j = i + 1 To accountAppCollateralItem.SecurityEnquiries.Count - 1
                If ServiceLog.ServiceId = accountAppCollateralItem.SecurityEnquiries(j).ServiceId AndAlso ServiceLog.ProductId = accountAppCollateralItem.SecurityEnquiries(j).ProductId AndAlso ServiceLog.ProductOptions = accountAppCollateralItem.SecurityEnquiries(j).ProductOptions Then
                  .Visible = False
                  Exit For
                End If
              Next

              With .Cells
                .AddDateTime(ServiceLog.CreatedDate)
                .AddText(finBL.Users.ItemByPkSafe(ServiceLog.CreatedUserPk).UserIdResolved)
                .AddText(ServiceLog.ServiceId)
                With .AddText(ServiceLog.ProductId & If(Len(ServiceLog.ProductOptions) = 0, "", " (" & ServiceLog.ProductOptions & ")"))
                  .HyperlinkSetHtmlShowFunction("ServiceReport", "Security Enquiry", "serviceLogPk=" & ServiceLog.Pk)
                  .Tooltip = ServiceLog.ProductOptionsTooltip
                End With
                If DifferencesView Then
                  Select Case UCase(ServiceLog.ServiceId) & "." & UCase(ServiceLog.ProductId)
                    Case "CENTRIXNZ.CONFIRM OWNER"
                    Case Else
                      With .AddText(If(DifferencesUpdate, "Update", "View"))
                        .HyperlinkSetFormAction("SecurityEnquiryDifference", "ServiceLogPk=" & CStr(ServiceLog.Pk))
                      End With
                  End Select
                End If
              End With
            End With
          Next
        End With
      End If

      ' Warnings
      .TextAfter = Warnings

      ' Actions
      If includeActions Then
        With .Actions
        End With
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Application Collateral Item Logs Summary (Version 1.00, Last updated 12/03/2015).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="accountAppCollateralItem">
  '''  The Collateral Item to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Workflow Key Details page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function AccountApp_CollateralItemLogs(callerScriptInfo As ISScriptExecutionInfo,
                                                            accountAppCollateralItem As finAccountAppCollateralItem,
                                                   Optional maxDisplayRows As Integer = 20,
                                                   Optional includeActions As Boolean = True,
                                                   Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim Action As String
    Dim Log As finLogRO
    Dim Logs As List(Of finLogRO)
    Dim LogClassesList As ISList
    Dim i As Integer
    Dim ShowAction As Boolean
    Dim ShowLogClass As Boolean
    Dim ShowPublish As Boolean
    Dim ShowSeverity As Boolean
    Dim strTemp As String
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()
    Logs = New List(Of finLogRO)

    ' Determine Logs and Columns to include
    ShowAction = False
    ShowPublish = False
    ShowSeverity = False
    LogClassesList = New ISList()
    For Each Log In accountAppCollateralItem.AccountApp.Logs
      ' Include?
      If Log.LogSubClass = isefinLogSubClass.AccountAppCollateralItem AndAlso Log.SubSourcePk = accountAppCollateralItem.Pk Then
        ' Add to List
        Logs.Add(Log)

        ' Determine Columns
        If Log.ActionDate <> Nothing AndAlso Log.ActionCompleteDate = Nothing Then ShowAction = True
        If Log.PublishStatus <> isefinLogPublishStatus.None Then ShowPublish = True
        If Log.LogSeverityPk <> 0 Then ShowSeverity = True
        LogClassesList.Add(Log.LogClass.ToString(), True)
      End If
    Next
    ShowLogClass = LogClassesList.Count > 1

    ' Main
    With SummaryTableMain
      If Logs.Count = 0 Then
        .TextBefore = "{{info|No linked logs.}}"
      Else
        ' Initialise
        .TableClass = iseSummaryTableClass.TabularData
        .Caption = ""
        .AutoStripe = True
        .MaxDisplayRows = maxDisplayRows
        .ShowHiddenRowsCaption = "Show More Logs"

        ' Columns
        With .Columns
          If ShowLogClass Then .AddBoolean(" ")
          If ShowSeverity Then .AddBoolean(" ")
          .AddDate("Date")
          .AddText("Subject")
          If ShowAction Then .AddText("Action", 10)
          If ShowPublish Then .AddCode("Publish", 10)
        End With

        With .Rows
          ' Reverse order so latest are at the top
          For i = Logs.Count - 1 To 0 Step -1
            ' Initialise
            Log = Logs(i)

            With .Add()
              ' Incomplete
              If Log.IsIncomplete OrElse Log.IsAwaitingPublish Then
                .RowClass = iseSummaryTableRowClass.NormalBold
              End If

              ' Hide if not issued
              If Log.PublishStatus = isefinLogPublishStatus.NotIssued Then
                .Visible = False
              End If

              ' Hide if duplicate Service Log (probably not applicable to Collateral Item Logs but added for consistency)
              If Log.DuplicateServiceLink Then
                .Visible = False
              End If

              With .Cells
                If ShowLogClass Then
                  Select Case Log.LogClass
                    Case isefinLogClass.Account : strTemp = "Account"
                    Case isefinLogClass.AccountApp : strTemp = "AccountApp"
                    Case isefinLogClass.Client : strTemp = "Client"
                    Case isefinLogClass.SecurityStmt : strTemp = "SecurityStmt"
                    Case isefinLogClass.SecurityStmtItem : strTemp = "SecurityType"
                    Case isefinLogClass.User : strTemp = "User"
                    Case Else : strTemp = "Blank"
                  End Select
                  .AddText("{{icon|" & strTemp & "|" & Log.LogClassText & "}}")
                End If

                If ShowSeverity Then
                  If Log.LogSeverityPk = 0 Then
                    .AddText("")
                  ElseIf Log.ActionDate <> Nothing AndAlso Log.ActionCompleteDate = Nothing Then
                    .AddText("{{colourblock|" & Log.LogSeverity.OpenColourBackground & "|" & Log.LogSeverity.LogSeverityId & ", " & Log.LogSeverity.Description & "}}")
                  Else
                    .AddText("{{colourblock|" & Log.LogSeverity.CompleteColourBackground & "|" & Log.LogSeverity.LogSeverityId & ", " & Log.LogSeverity.Description & "}}")
                  End If
                End If

                .AddDate(Log.LogDate)

                ' Make Subject splitable (auto-generated subjects such as Credit Enquiries have no spaces and therefore force columns too wide)
                strTemp = Log.Subject
                If Len(strTemp) > 20 Then
                  If InStr(strTemp, ".") <> 0 Then
                    strTemp = Replace(strTemp, ".", ". ")
                  End If
                End If
                With .AddText(strTemp)
                  .HyperlinkSetFormShow(Log.LogFormKey, CStr(Log.Pk))
                End With

                If ShowAction Then
                  If Log.ActionDate = Nothing Then
                    Action = ""
                  ElseIf Log.ActionCompleteDate = Nothing Then
                    Action = finBL.FormatDateForGrid(Log.ActionDate)
                  Else
                    Action = "Complete"
                  End If
                  .AddText(Action)
                End If
                If ShowPublish Then
                  If Log.PublishStatus = isefinLogPublishStatus.None Then
                    .AddText("")
                  Else
                    .AddText(Log.PublishStatusText)
                  End If
                End If
              End With
            End With
          Next
        End With

        ' Warnings
        .TextAfter = Warnings

        ' Actions
        If includeActions Then
          With .Actions
          End With
        End If
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Application Collateral Item Summary.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="accountAppCollateralItem">
  '''  The Account Application Collateral Item.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Account Applications form, Collateral page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function AccountApp_CollateralItemSummary(callerScriptInfo As ISScriptExecutionInfo,
                                                               accountAppCollateralItem As finAccountAppCollateralItem,
                                                      Optional includeActions As Boolean = True,
                                                      Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' AccountApp_CollateralItemSummary
    '
    ' Version: 1.01 (15/06/2022)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.00  26/11/2013  ISS                Created
    '    1.01  15/06/2022  ISS      J028230   Option to view Security Item now supplies Account App Id
    ' #################################################################

    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      .Columns.AddText(20)
      .Columns.AddText()

      ' Preview New Security Statement link (cannot preview if not used since it will not be included in the Security Statement)
      If finBL.Settings.AddOns.SecurityRegister AndAlso includeActions AndAlso Not accountAppCollateralItem.AccountApp.IsClosed AndAlso accountAppCollateralItem.Used Then
        .TextBefore &= "{{button icon='Verify' caption='View new Security Item that will be generated' hyperlink='app://formaction?action=ShowTempSecurityItem&accountAppId=" & finBL.UrlEncode(accountAppCollateralItem.AccountApp.AccountAppId) & "&index=" & CStr(accountAppCollateralItem.Index) & "'}}"
      End If

      ' Used?
      If finBL.Settings.AddOns.SecurityRegister AndAlso Not accountAppCollateralItem.Used Then
        .TextBefore &= "{{warning|Collateral Item is not used and will not be included on the Security Statement.|true}}"
      End If

      With .Rows
        ' General
        .AddCaptionText("Description:", accountAppCollateralItem.DescriptionResolved, iseSummaryTableCellClass.Highlight1)
        If accountAppCollateralItem.SecurityTypePk <> 0 Then
          .AddCaptionCodeDescription("Security Type:", accountAppCollateralItem.SecurityTypePk, finBL.SecurityTypes)
        End If

        ' Notes
        If Len(accountAppCollateralItem.Notes) <> 0 Then
          .AddSectionHeading2("Notes")
          .AddText(accountAppCollateralItem.Notes)
        End If
      End With

      ' Warnings
      .TextAfter = Warnings

      ' Actions
      If includeActions Then

      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Application Collateral Item User Defined details (Version 1.00, Last updated 03/11/2020).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="accountAppCollateralItem">
  '''  The Collateral Item to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  Public Overridable Function AccountApp_CollateralItemUserDefined(callerScriptInfo As ISScriptExecutionInfo,
                                                                   accountAppCollateralItem As finAccountAppCollateralItem,
                                                          Optional includeActions As Boolean = True,
                                                          Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim Parameters As ISParameters
    Dim ParameterSetPk As Integer
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables

    If accountAppCollateralItem.SecurityTypePk <> 0 Then
      ParameterSetPk = accountAppCollateralItem.SecurityType.UserDefinedParameterSetPk
    End If

    Parameters = finBL.SecurityStmtFunctions.CreateUserDefinedParametersSecurityItem(ParameterSetPk)
    Parameters.UpdateFromKeyValueList(accountAppCollateralItem.UserData)

    If ParameterSetPk = 0 AndAlso Not finBL.Settings.HasSecurityStmtItemUser Then
      SummaryTables = finBL.CreateSummaryTables()
      SummaryTableMain = finBL.CreateSummaryTable()
      SummaryTables.Add("Main", SummaryTableMain)
    Else
      SummaryTables = finBL.Utilities.ParametersToSummaryTables(Parameters)
    End If

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Application Application Details Summary (Version 1.0, Last updated 26/5/2014).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="accountApp">
  '''  The Account Application.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Account Applications form, Account page. May preview either the Account that will be created or the actual Account that was created.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function AccountApp_DetailSummaryApplication(callerScriptInfo As ISScriptExecutionInfo,
                                                                  accountApp As finAccountApp,
                                                         Optional includeActions As Boolean = True,
                                                         Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim strTemp As String
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      .Columns.AddText(16).NoBreakChars = 10
      .Columns.AddText()

      With .Rows
        ' Financial
        .AddSectionHeading2("Financial")
        If accountApp.PreferredAccountTypePk <> 0 Then
          .AddCaptionCodeDescription("Account Type:", accountApp.PreferredAccountTypePk, finBL.AccountTypes)
          If finBL.Settings.AddOns.Promotions AndAlso Len(accountApp.PreferredAccountTypePromotionId) <> 0 Then
            If accountApp.PreferredAccountType IsNot Nothing AndAlso accountApp.PreferredAccountType.Promotions.ExistsPk(accountApp.PreferredAccountTypePromotionPk) Then
              .AddCaptionCodeDescription("Promotion:", accountApp.PreferredAccountTypePromotionId, accountApp.PreferredAccountType.Promotions.ItemByPk(accountApp.PreferredAccountTypePromotionPk).Description)
            Else
              ' Invalid promotion
            End If
          End If
        End If
        If accountApp.PreferredLoanAmount <> 0 Then
          .AddCaptionCurrency("Preferred Amount:", accountApp.PreferredLoanAmount, True)
        End If
        If Len(accountApp.PreferredTerm) <> 0 Then
          .AddCaptionText("Preferred Term:", accountApp.PreferredTerm)
        End If
        If accountApp.PreferredNumberOfPayments <> 0 OrElse Len(accountApp.PreferredPaymentFrequency) <> 0 Then
          If accountApp.PreferredNumberOfPayments = 0 Then
            strTemp = ""
          Else
            strTemp = CStr(accountApp.PreferredNumberOfPayments) & " "
          End If
          strTemp &= accountApp.PreferredPaymentFrequency

          .AddCaptionText("Preferred Payments:", strTemp)
        End If

        With .Add(iseSummaryTableRowClass.Normal).Cells.Add()
          .Value = "{{info|Captured details are **preferred** details and may differ from those on the **Quotes** page or those used to generate the final Account.}}"
        End With

        ' Other Details
        If Len(accountApp.Purpose) <> 0 OrElse
           Len(accountApp.Source) <> 0 OrElse
           Len(accountApp.Region) <> 0 Then
          .AddSectionHeading2("Other Details")
          If Len(accountApp.Purpose) <> 0 Then
            .AddCaptionText("Purpose:", accountApp.Purpose)
          End If
          If Len(accountApp.Source) <> 0 Then
            .AddCaptionText("Source:", accountApp.Source)
          End If
          If Len(accountApp.Region) <> 0 Then
            .AddCaptionText("Region:", accountApp.Region)
          End If
        End If

        '' Account Type
        'If account.AccountTypePk <> 0 Then
        '  '.AddCaptionCodeDescription("Product Type:", account.ProductTypeId, finBL.ProductTypes)
        '  .AddCaptionCodeDescription("Account Type:", account.AccountTypePk, finBL.AccountTypes)
        '  If finBL.Settings.AddOns.Promotions AndAlso account.AccountTypePromotionPk <> 0 Then
        '    .AddCaptionCodeDescription("Promotion:", account.AccountTypePromotionId, account.AccountTypePromotionDescription)
        '  End If
        'End If

        '' Account Manager
        'If account.AccountManagerUserPk <> 0 Then
        '  .AddCaptionCodeDescription("Manager:", account.AccountManagerUserPk, finBL.Users)
        'End If

        '' Status-specific
        'Select Case account.Status
        '  Case isefinAccountStatus.Quote
        '    ' Quote
        '    If account.DateQuoted <> Nothing OrElse account.DateQuoteReady <> Nothing OrElse account.DateQuoteReady <> Nothing OrElse account.QuoteNote <> Nothing Then
        '      .AddSectionHeading2("Quote Details")
        '      If account.DateQuoted <> Nothing Then
        '        .AddCaptionDate("Date Quoted:", account.DateQuoted)
        '      End If
        '      'If account.DateQuoteReady <> Nothing Then
        '      '  .AddCaptionText("Quote Ready:", If(account.DateQuoteReady = Nothing, "", "{{tick}}"))
        '      'End If
        '      'If account.DateQuoteReady <> Nothing Then
        '      '  .AddCaptionDate("Date Ready:", account.DateQuoteReady)
        '      'End If
        '      'If Len(account.QuoteNote) <> 0 Then
        '      '  .AddCaptionText("Notes:", account.QuoteNote)
        '      'End If
        '    End If
        'End Select

        '' Other Details
        '.AddSectionHeading2("Other Details")
        'If Len(account.Purpose) <> 0 Then
        '  .AddCaptionText("Purpose:", account.Purpose)
        'End If
        'If Len(account.Source) <> 0 Then
        '  .AddCaptionText("Source:", account.Source)
        'End If
        'If Len(account.Region) <> 0 Then
        '  .AddCaptionText("Region:", account.Region)
        'End If

        'If finBL.Settings.AddOns.Branch Then
        '  .AddCaptionCodeDescription("Branch:", account.BranchPk, finBL.Branches)
        'End If
        'If account.DepartmentPk <> 0 Then
        '  .AddCaptionCodeDescription("Department:", account.DepartmentPk, finBL.Departments)
        'End If

        'If finBL.Settings.AddOns.ExternalPartyDealers AndAlso account.DealerExternalPartyPk <> 0 Then
        '  .AddCaptionCodeDescription("Dealer:", account.DealerExternalPartyPk, finBL.ExternalParties)
        '  If account.DealerExternalPartyEmployeePk <> 0 Then
        '    .AddCaptionCodeDescription("Employee:", account.DealerExternalPartyEmployeeClientEmploymentId, account.DealerExternalPartyEmployeeName)
        '  End If
        'End If

        'If account.AccountTypePk <> 0 AndAlso account.AccountType.ShowBrokerInformation AndAlso finBL.Settings.AddOns.ExternalPartyBrokers Then
        '  .AddCaptionCodeDescription("Broker:", account.BrokerExternalPartyPk, finBL.ExternalParties)
        '  If account.BrokerExternalPartyEmployeePk <> 0 Then
        '    .AddCaptionCodeDescription("Employee:", account.BrokerExternalPartyEmployeeClientEmploymentId, account.BrokerExternalPartyEmployeeName)
        '  End If
        'End If

        '' Insurance
        'If account.AccountTypePk <> 0 AndAlso account.AccountType.IncludeAccountLevelInsurance AndAlso finBL.Settings.AddOns.ExternalPartyInsurers Then
        '  .AddSectionHeading2("Insurance details")
        '  .AddCaptionCodeDescription("Insurer:", account.InsuranceInsurerExternalPartyPk, finBL.ExternalParties)
        '  If Len(account.InsurancePolicyType) <> 0 Then
        '    .AddCaptionText("Policy Type:", account.InsurancePolicyType)
        '  End If
        '  If Len(account.InsurancePolicyNumber) <> 0 Then
        '    .AddCaptionText("Policy Number:", account.InsurancePolicyNumber)
        '  End If
        'End If
      End With

      ' Warnings
      .TextAfter = Warnings
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Application Applicant Details Summary (Version 1.01, Last updated 3/12/2014).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="accountAppApplicant">
  '''  The Applicant.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Account Applications form, Account page. May preview either the Account that will be created or the actual Account that was created.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''    <item><code>ContactMethods</code><description>Contact Method details.</description></item>
  '''    <item><code>ContactAddresses</code><description>Contact Address details.</description></item>
  '''    <item><code>Identification</code><description>Identification details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function AccountApp_DetailSummaryApplicant(callerScriptInfo As ISScriptExecutionInfo,
                                                                accountAppApplicant As finAccountAppApplicant,
                                                       Optional includeActions As Boolean = True,
                                                       Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim SummaryTableContactAddresses As ISSummaryTable
    Dim SummaryTableContactMethods As ISSummaryTable
    Dim SummaryTableIdentification As ISSummaryTable
    Dim SummaryTableMain As ISSummaryTable
    Dim strTemp As String
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableContactAddresses = finBL.CreateSummaryTable()
    SummaryTableContactMethods = finBL.CreateSummaryTable()
    SummaryTableIdentification = finBL.CreateSummaryTable()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      .Columns.AddText(16).NoBreakChars = 10
      .Columns.AddText()

      With .Rows
        ' Name
        If accountAppApplicant.IsOrganisation Then
          .AddCaptionText("Name:", accountAppApplicant.Name, iseSummaryTableCellClass.Highlight1)
        Else
          .AddCaptionText("Name:", finBL.Runtime.TextUtilities.ListSeparate(" ", accountAppApplicant.Title, accountAppApplicant.FirstName, accountAppApplicant.MiddleNames, accountAppApplicant.LastName), iseSummaryTableCellClass.Highlight1)
        End If

        ' General
        .AddCaptionCodeDescription("Client Type:", accountAppApplicant.ClientTypeResolvedPk, finBL.ClientTypes).RowClass = iseSummaryTableRowClass.Alt2
        .AddCaptionCodeDescription("Client Group:", accountAppApplicant.ClientGroupResolvedPk, finBL.ClientGroups).RowClass = iseSummaryTableRowClass.Alt2
        .AddCaptionCodeDescription("Role:", accountAppApplicant.AccountRoleResolvedPk, finBL.AccountRoles).RowClass = iseSummaryTableRowClass.Alt2
        If accountAppApplicant.ClientPk <> 0 Then
          .AddCaptionCodeDescription("Existing Client:", accountAppApplicant.ClientPk, finBL.ClientFunctions).RowClass = iseSummaryTableRowClass.Alt2
        End If
        If accountAppApplicant.LoadedFromClientPk <> 0 AndAlso accountAppApplicant.ClientPk <> accountAppApplicant.LoadedFromClientPk Then
          .AddCaptionCodeDescription("Loaded From:", accountAppApplicant.LoadedFromClientPk, finBL.ClientFunctions).RowClass = iseSummaryTableRowClass.Alt2
        End If
        If accountAppApplicant.CreatedClientPk <> 0 Then
          .AddCaptionCodeDescription("Created Client:", accountAppApplicant.CreatedClientPk, finBL.ClientFunctions).RowClass = iseSummaryTableRowClass.Alt2
        End If

        ' Individual/ Organisation Details
        If accountAppApplicant.IsIndividual OrElse accountAppApplicant.IsSoleTrader Then
          ' Individual
          If Len(accountAppApplicant.IndividualNumber) <> 0 Then
            strTemp = finBL.SupportedCountries.CurrentSupportedCountry.Terminology(isefinCountryTerminology.IndividualNumber)
            If Len(strTemp) = 0 Then strTemp = "Individual No"
            .AddCaptionText(strTemp & ":", accountAppApplicant.IndividualNumber)
          End If
          If Len(accountAppApplicant.TaxNumber) <> 0 Then
            strTemp = finBL.SupportedCountries.CurrentSupportedCountry.Terminology(isefinCountryTerminology.TaxNumberIndividual)
            If Len(strTemp) = 0 Then strTemp = "Tax Number"
            .AddCaptionText(strTemp & ":", accountAppApplicant.TaxNumber)
          End If
          If Len(accountAppApplicant.GstNumber) <> 0 Then
            strTemp = finBL.SupportedCountries.CurrentSupportedCountry.Terminology(isefinCountryTerminology.GSTNumberIndividual)
            If Len(strTemp) = 0 Then strTemp = "GST Number"
            .AddCaptionText(strTemp & ":", accountAppApplicant.GstNumber)
          End If
          If accountAppApplicant.DateOfBirth <> Nothing Then
            strTemp = String.Format("{0} old as at {1}", finBL.Runtime.DateUtilities.AgeAsText(accountAppApplicant.DateOfBirth, accountAppApplicant.AccountApp.DateQuoted), finBL.FormatDateLong(accountAppApplicant.AccountApp.DateQuoted))
            .AddCaptionWiki("Date of Birth:", String.Format("**{0}** --{1}--", finBL.FormatDateLong(accountAppApplicant.DateOfBirth), strTemp))
          End If
          If accountAppApplicant.Gender <> isefinGender.Unknown Then
            .AddCaptionText("Gender:", accountAppApplicant.GenderText)
          End If
          If Len(accountAppApplicant.MaritalStatus) <> 0 Then
            .AddCaptionText("Marital Status:", accountAppApplicant.MaritalStatus)
          End If
          If Len(accountAppApplicant.Dependants) <> 0 Then
            .AddCaptionText("Dependants:", accountAppApplicant.Dependants)
          End If
          If Len(accountAppApplicant.Occupation) <> 0 Then
            .AddCaptionText("Occupation:", accountAppApplicant.Occupation)
          End If
          If Len(accountAppApplicant.ResidentialStatus) <> 0 Then
            .AddCaptionText("Residential:", accountAppApplicant.ResidentialStatus)
          End If
          If Len(accountAppApplicant.ResidencyStatus) <> 0 Then
            .AddCaptionText("Residency:", accountAppApplicant.ResidencyStatus)
          End If
          If Len(accountAppApplicant.IndustryCode) <> 0 Then
            .AddCaptionText("Industry Code:", accountAppApplicant.IndustryCode)
          End If
          If Len(accountAppApplicant.Salutation) <> 0 Then
            .AddCaptionText("Salutation:", accountAppApplicant.Salutation)
          End If
          If Len(accountAppApplicant.AddresseeName) <> 0 Then
            .AddCaptionText("Addressee:", accountAppApplicant.AddresseeName)
          End If
        Else
          If Len(accountAppApplicant.LegalName) <> 0 AndAlso accountAppApplicant.LegalName <> accountAppApplicant.Name Then
            .AddCaptionText("Legal Name:", accountAppApplicant.LegalName)
          End If
          If Len(accountAppApplicant.BusinessNumber) <> 0 Then
            strTemp = finBL.SupportedCountries.CurrentSupportedCountry.Terminology(isefinCountryTerminology.BusinessNumber, True)
            If Len(strTemp) = 0 Then strTemp = "Business No"
            .AddCaptionText(strTemp & ":", accountAppApplicant.BusinessNumber)
          End If
          If Len(accountAppApplicant.TaxNumber) <> 0 Then
            strTemp = finBL.SupportedCountries.CurrentSupportedCountry.Terminology(isefinCountryTerminology.TaxNumberOrganisation, True)
            If Len(strTemp) = 0 Then strTemp = "Tax Number"
            .AddCaptionText(strTemp & ":", accountAppApplicant.TaxNumber)
          End If
          If Len(accountAppApplicant.GstNumber) <> 0 Then
            strTemp = finBL.SupportedCountries.CurrentSupportedCountry.Terminology(isefinCountryTerminology.GSTNumberOrganisation, True)
            If Len(strTemp) = 0 Then strTemp = "GST Number"
            .AddCaptionText(strTemp & ":", accountAppApplicant.GstNumber)
          End If
          If Len(accountAppApplicant.OrganisationNumber) <> 0 Then
            strTemp = finBL.SupportedCountries.CurrentSupportedCountry.Terminology(isefinCountryTerminology.CompanyNumber, True)
            If Len(strTemp) = 0 Then strTemp = "Company No"
            .AddCaptionText(strTemp & ":", accountAppApplicant.OrganisationNumber)
          End If
          If accountAppApplicant.CommencementDate <> Nothing Then
            .AddCaptionDate("Commenced:", accountAppApplicant.CommencementDate)
          End If
          If Len(accountAppApplicant.IndustryCode) <> 0 Then
            .AddCaptionText("Industry Code:", accountAppApplicant.IndustryCode)
          End If

          ' Person Acting/ Personal Details
          If accountAppApplicant.IsSoleTrader Then
            .AddSectionHeading2("Personal details")
          Else
            .AddSectionHeading2("Person Acting")
          End If
          .AddCaptionText("Name:", finBL.Runtime.TextUtilities.ListSeparate(" ", accountAppApplicant.Title, accountAppApplicant.FirstName, accountAppApplicant.MiddleNames, accountAppApplicant.LastName))
          If accountAppApplicant.DateOfBirth <> Nothing Then
            strTemp = String.Format("{0} old as at {1}", finBL.Runtime.DateUtilities.AgeAsText(accountAppApplicant.DateOfBirth, accountAppApplicant.AccountApp.DateQuoted), finBL.FormatDateLong(accountAppApplicant.AccountApp.DateQuoted))
            .AddCaptionWiki("Date of Birth:", String.Format("**{0}** --{1}--", finBL.FormatDateLong(accountAppApplicant.DateOfBirth), strTemp))
          End If
          If accountAppApplicant.Gender <> isefinGender.Unknown Then
            .AddCaptionText("Gender:", accountAppApplicant.GenderText)
          End If
          If Len(accountAppApplicant.MaritalStatus) <> 0 Then
            .AddCaptionText("Marital Status:", accountAppApplicant.MaritalStatus)
          End If
          If Len(accountAppApplicant.Occupation) <> 0 Then
            .AddCaptionText("Occupation:", accountAppApplicant.Occupation)
          End If
          If Len(accountAppApplicant.JobTitle) <> 0 Then
            .AddCaptionText("Job Title:", accountAppApplicant.JobTitle)
          End If
        End If
      End With

      ' Warnings
      If Not accountAppApplicant.Used Then
        Warnings &= "{{warning|Not used.}}"
      End If
      .TextAfter = Warnings
    End With

    ' Contact Methods
    With SummaryTableContactMethods
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = "Contact Methods"
      .Columns.AddText(16).NoBreakChars = 10
      .Columns.AddText()

      With .Rows
        If Len(accountAppApplicant.ContactPhone) <> 0 Then
          With .AddCaptionText("Phone:", accountAppApplicant.ContactPhone)
            .Cells(1).HyperlinkSetPhoneNumber(accountAppApplicant.ContactPhone)
          End With
        End If
        If Len(accountAppApplicant.ContactPhoneWork) <> 0 Then
          With .AddCaptionText("Phone (Work):", accountAppApplicant.ContactPhoneWork)
            .Cells(1).HyperlinkSetPhoneNumber(accountAppApplicant.ContactPhoneWork)
          End With
        End If
        If Len(accountAppApplicant.ContactMobile) <> 0 Then
          With .AddCaptionText("Mobile:", accountAppApplicant.ContactMobile)
            .Cells(1).HyperlinkSetPhoneNumber(accountAppApplicant.ContactMobile)
          End With
        End If
        If Len(accountAppApplicant.ContactEmail) <> 0 Then
          With .AddCaptionText("Email:", accountAppApplicant.ContactEmail)
            .Cells(1).HyperlinkSetEmailAddress(accountAppApplicant.ContactEmail)
          End With
        End If
        If Len(accountAppApplicant.ContactFacsimile) <> 0 Then
          .AddCaptionText("Facsimile:", accountAppApplicant.ContactFacsimile)
        End If
      End With
    End With

    ' Contact Addresses
    With SummaryTableContactAddresses
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = "Address"
      .Columns.AddText(16).NoBreakChars = 10
      .Columns.AddText()

      With .Rows
        If accountAppApplicant.AddressPostal.HasValue AndAlso accountAppApplicant.AddressPhysicalIsPostal Then
          .AddCaptionAddressDetailsPostal("Address:", accountAppApplicant.AddressPostal)
        Else
          If accountAppApplicant.AddressPostal.HasValue Then
            .AddCaptionAddressDetailsPostal("Postal:", accountAppApplicant.AddressPostal)
          End If
          If accountAppApplicant.AddressPhysical.HasValue Then
            .AddCaptionAddressDetailsPostal("Physical:", accountAppApplicant.AddressPhysical)
          End If
        End If
      End With
    End With

    ' Identification
    With SummaryTableIdentification
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = "Identification"
      .Columns.AddText(16).NoBreakChars = 10
      .Columns.AddText()

      With .Rows
        ' Identification
        If Len(accountAppApplicant.DriversLicenceNumber) <> 0 Then
          .AddCaptionText("Drivers Licence:", accountAppApplicant.DriversLicenceNumber)
          If Len(accountAppApplicant.DriversLicenceIssuer) <> 0 Then
            .AddCaptionText("Issuer:", accountAppApplicant.DriversLicenceIssuer)
          End If
          If accountAppApplicant.DriversLicenceExpiryDate <> Nothing Then
            .AddCaptionDate("Expiry Date:", accountAppApplicant.DriversLicenceExpiryDate)
          End If
        End If

        If Len(accountAppApplicant.PassportNumber) <> 0 Then
          .AddCaptionText("Passport No:", accountAppApplicant.PassportNumber)
          If Len(accountAppApplicant.PassportIssuer) <> 0 Then
            .AddCaptionText("Issuer:", accountAppApplicant.PassportIssuer)
          End If
          If accountAppApplicant.PassportExpiryDate <> Nothing Then
            .AddCaptionDate("Expiry Date:", accountAppApplicant.PassportExpiryDate)
          End If
        End If
      End With
    End With

    ' Add Summary Tables (always add regardless of whether they contain any rows)
    SummaryTables.Add("Main", SummaryTableMain)
    SummaryTables.Add("ContactMethods", SummaryTableContactMethods)
    SummaryTables.Add("ContactAddresses", SummaryTableContactAddresses)
    SummaryTables.Add("Identification", SummaryTableIdentification)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Application Collateral Items Summary (Version 1.01, Last updated 06/03/2015).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="accountApp">
  '''  The Account Application.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Account Applications form, Data Capture page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function AccountApp_DetailSummaryCollateralItems(callerScriptInfo As ISScriptExecutionInfo,
                                                                      accountApp As finAccountApp,
                                                             Optional includeActions As Boolean = True,
                                                             Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Return Me.AccountApp_CollateralItems(callerScriptInfo, accountApp, False, , , , , , , , includeActions)

  End Function

  ''' <summary>
  '''  Account Application History Item Summary (Version 2.01, Last updated 19/04/2016).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="accountAppHistoryItem">
  '''  The Account Application History Item.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Application History page and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Summary.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function AccountApp_HistoryItemSummary(callerScriptInfo As ISScriptExecutionInfo,
                                                            accountAppHistoryItem As finAccountAppHistoryItem,
                                                   Optional includeActions As Boolean = True,
                                                   Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim AccountApp As finAccountApp
    Dim DateAsAt As Date
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Date As At
    DateAsAt = finBL.TimeZoneFunctions.GetCurrentDatabaseDate()

    ' Cache Account Application 
    AccountApp = accountAppHistoryItem.AccountApp

    ' Summary table
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Columns.AddText(16).NoBreakChars = 16
      .Columns.AddText()

      If accountAppHistoryItem IsNot Nothing Then
        With .Rows
          ' General
          If accountAppHistoryItem.HistoryType = isefinAccountAppHistoryType.MonitorCategoryChange AndAlso Len(accountAppHistoryItem.MonitorCategoryId) = 0 Then
            With .AddCaptionText("Description:", "Monitor Category Cleared", iseSummaryTableCellClass.Highlight1)
              .Cells(1).Tooltip = String.Format("Primary Key: {0}", accountAppHistoryItem.Pk)
            End With
          Else
            With .AddCaptionText("Description:", accountAppHistoryItem.HistoryTypeText, iseSummaryTableCellClass.Highlight1)
              .Cells(1).Tooltip = String.Format("Primary Key: {0}", accountAppHistoryItem.Pk)
            End With
          End If
          .AddCaptionWiki("Created:", finBL.Utilities.GetUserAndDateWikiText("", accountAppHistoryItem.CreatedUserPk, accountAppHistoryItem.CreatedDate))
          If accountAppHistoryItem.CreatedUserPk <> accountAppHistoryItem.UpdatedUserPk OrElse accountAppHistoryItem.CreatedUtcDate <> accountAppHistoryItem.UpdatedUtcDate Then
            .AddCaptionWiki("Last Updated:", finBL.Utilities.GetUserAndDateWikiText("", accountAppHistoryItem.UpdatedUserPk, accountAppHistoryItem.UpdatedDate))
          End If

          ' Details
          .AddSectionHeading2("Details")
          .AddCaptionDate("Date:", accountAppHistoryItem.Date)
          If Len(accountAppHistoryItem.Reference) <> 0 Then
            .AddCaptionText("Reference:", accountAppHistoryItem.Reference)
          End If

          ' History Type Specific
          Select Case accountAppHistoryItem.HistoryType
            Case isefinAccountAppHistoryType.MonitorCategoryChange
              ' Monitor Category Change
              If Len(accountAppHistoryItem.MonitorCategoryId) = 0 Then
                .AddCaptionText("Cleared from:", accountAppHistoryItem.AccountMonitorCategoryText)
              Else
                .AddCaptionCodeDescription("Moved into:", accountAppHistoryItem.MonitorCategoryId, accountAppHistoryItem.AccountMonitorCategoryText)
              End If

            Case Else
              Warnings &= "{{warning|History type '**" & accountAppHistoryItem.HistoryTypeText & "**' is not yet implemented.}}"
          End Select

          ' Notes
          If Len(accountAppHistoryItem.Notes) <> 0 Then
            .AddSectionHeading2("Notes")
            .AddText(accountAppHistoryItem.Notes)
          End If
        End With

        ' Warnings
        Select Case accountAppHistoryItem.Status
          Case isefinAccountAppHistoryStatus.Cancelled
            Warnings &= "{{warning|This " & accountAppHistoryItem.HistoryTypeText & " was " & finBL.Utilities.GetUserAndDateWikiText("cancelled", accountAppHistoryItem.UpdatedUserPk, accountAppHistoryItem.UpdatedDate) & ".}}"

          Case isefinAccountAppHistoryStatus.Complete
            Select Case accountAppHistoryItem.HistoryType
            End Select

          Case isefinAccountAppHistoryStatus.Pending
            Warnings &= "{{warning|This " & accountAppHistoryItem.HistoryTypeText & " is still outstanding.}}"
        End Select
        .TextAfter = Warnings

        ' Actions
        If includeActions Then
          With .Actions
          End With
        End If
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Summary", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Application Monitoring Summary.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="accountApp">
  '''  The Account Application to summarise.
  ''' </param>
  ''' <param name="onlyIncludeIfMonitored">
  '''  Indicates whether to only include tables if Monitoring.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Status page and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>MainA</code><description>Monitor Category A details.</description></item>
  '''    <item><code>MainB</code><description>Monitor Category B details.</description></item>
  '''    <item><code>MainC</code><description>Monitor Category C details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function AccountApp_Monitoring(callerScriptInfo As ISScriptExecutionInfo,
                                                    accountApp As finAccountApp,
                                           Optional onlyIncludeIfMonitored As Boolean = False,
                                           Optional includeActions As Boolean = True,
                                           Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' AccountApp_Monitoring
    '
    ' Version: 1.02 (27/03/2023)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.01  19/04/2016  ISS                  
    '    1.02  27/03/2023  ISS      J030571   Not applying Permissions
    ' #################################################################

    Dim CategoryAbc As String
    Dim DateAsAt As Date
    Dim Days As Long
    Dim Description As String
    Dim i As Integer
    Dim Include As Boolean
    Dim MonitorCategoryId As String
    Dim MonitorCategoryCancelAllowed As Boolean
    Dim MonitorCategoryEnteredDate As Date
    Dim MonitorCategoryUpdateAllowed As Boolean
    Dim MonitorCategoryUpdatedDate As Date
    Dim strTemp As String
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTableMainA As ISSummaryTable
    Dim SummaryTableMainB As ISSummaryTable
    Dim SummaryTableMainC As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMainA = finBL.CreateSummaryTable()
    SummaryTableMainB = finBL.CreateSummaryTable()
    SummaryTableMainC = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Date As At
    DateAsAt = finBL.TimeZoneFunctions.GetCurrentDatabaseDate()

    For i = 1 To 3
      ' Initialise
      Warnings = ""

      ' Get Monitoring Details
      Select Case i
        Case 1
          CategoryAbc = "A"
          Include = finBL.Settings.MonitorCategoryAUseAccountApp AndAlso (accountApp.MonitorCategoryAPk <> 0 OrElse Not onlyIncludeIfMonitored)
          Description = finBL.Settings.MonitorCategoryADescriptionResolved
          MonitorCategoryId = accountApp.MonitorCategoryAId
          MonitorCategoryEnteredDate = accountApp.MonitorCategoryAEnteredDate
          MonitorCategoryUpdatedDate = accountApp.MonitorCategoryAUpdatedDate
          MonitorCategoryUpdateAllowed = finBL.CurrentUser.Permissions.Allow("AccountApp.MonitorCategoryRevise") AndAlso finBL.CurrentUser.Permissions.Allow("AccountApp.MonitorCategoryAUpdate")
          MonitorCategoryCancelAllowed = MonitorCategoryUpdateAllowed AndAlso finBL.CurrentUser.Permissions.Allow("AccountApp.MonitorCategoryACancel") AndAlso accountApp.MonitorCategoryAPk <> 0
          SummaryTableMain = SummaryTableMainA

        Case 2
          CategoryAbc = "B"
          Include = finBL.Settings.MonitorCategoryBUseAccountApp AndAlso (accountApp.MonitorCategoryBPk <> 0 OrElse Not onlyIncludeIfMonitored)
          Description = finBL.Settings.MonitorCategoryBDescriptionResolved
          MonitorCategoryId = accountApp.MonitorCategoryBId
          MonitorCategoryEnteredDate = accountApp.MonitorCategoryBEnteredDate
          MonitorCategoryUpdatedDate = accountApp.MonitorCategoryBUpdatedDate
          MonitorCategoryUpdateAllowed = finBL.CurrentUser.Permissions.Allow("AccountApp.MonitorCategoryRevise") AndAlso finBL.CurrentUser.Permissions.Allow("AccountApp.MonitorCategoryBUpdate")
          MonitorCategoryCancelAllowed = MonitorCategoryUpdateAllowed AndAlso finBL.CurrentUser.Permissions.Allow("AccountApp.MonitorCategoryBCancel") AndAlso accountApp.MonitorCategoryBPk <> 0
          SummaryTableMain = SummaryTableMainB

        Case 3
          CategoryAbc = "C"
          Include = finBL.Settings.MonitorCategoryCUseAccountApp AndAlso (accountApp.MonitorCategoryCPk <> 0 OrElse Not onlyIncludeIfMonitored)
          Description = finBL.Settings.MonitorCategoryCDescriptionResolved
          MonitorCategoryId = accountApp.MonitorCategoryCId
          MonitorCategoryEnteredDate = accountApp.MonitorCategoryCEnteredDate
          MonitorCategoryUpdatedDate = accountApp.MonitorCategoryCUpdatedDate
          MonitorCategoryUpdateAllowed = finBL.CurrentUser.Permissions.Allow("AccountApp.MonitorCategoryRevise") AndAlso finBL.CurrentUser.Permissions.Allow("AccountApp.MonitorCategoryCUpdate")
          MonitorCategoryCancelAllowed = MonitorCategoryUpdateAllowed AndAlso finBL.CurrentUser.Permissions.Allow("AccountApp.MonitorCategoryCCancel") AndAlso accountApp.MonitorCategoryCPk <> 0
          SummaryTableMain = SummaryTableMainC
      End Select

      ' Main A-C
      If Include Then
        With SummaryTableMain
          ' Initialise
          .TableClass = iseSummaryTableClass.Information
          .Caption = Description
          .Columns.AddText(20)
          .Columns.AddText()

          If Len(MonitorCategoryId) = 0 Then
            ' Not Monitored
            .TextAfter = "Not monitored."
          Else
            ' Monitored
            With .Rows
              .AddCaptionCodeDescription("Category:", MonitorCategoryId, finBL.MonitorCategories)

              ' Started
              Days = DateDiff(DateInterval.Day, MonitorCategoryEnteredDate.Date, DateAsAt)
              If Days = 0 Then
                strTemp = "Today"
              ElseIf Days = 1 Then
                strTemp = "**1** day ago"
              Else
                strTemp = String.Format("**{0}** days ago", Days)
              End If
              .AddCaptionDate("Started:", MonitorCategoryEnteredDate, strTemp)

              ' Moved to
              Days = DateDiff(DateInterval.Day, MonitorCategoryUpdatedDate.Date, DateAsAt)
              If Days = 0 Then
                strTemp = "Today"
              ElseIf Days = 1 Then
                strTemp = "**1** day ago"
              Else
                strTemp = String.Format("**{0}** days ago", Days)
              End If
              .AddCaptionDate(String.Format("Moved to '{0}':", MonitorCategoryId), MonitorCategoryUpdatedDate, strTemp)
            End With

            ' Warnings
            .TextAfter = Warnings
          End If

          ' Actions
          If accountApp.IsNew Then
            ' Unsaved Account Application
          ElseIf includeActions Then
            With .Actions
              .AddFormAction("MonitorCategoryHistory" & CategoryAbc, "Review", finBL.CurrentUser.Permissions.Allow("AccountApp.Form.Page.Status"))
              If MonitorCategoryUpdateAllowed Then .AddFormAction("MonitorCategoryUpdate" & CategoryAbc, "Revise", (Not finBL.Database.IsReadOnly)).ShowInWebInterfaces = True
              If MonitorCategoryCancelAllowed Then .AddFormAction("MonitorCategoryClear" & CategoryAbc, "Clear", (Not finBL.Database.IsReadOnly)).ShowInWebInterfaces = True
            End With
          End If
        End With
      End If
    Next

    ' Add Summary Tables
    If finBL.Settings.MonitorCategoryAUseAccountApp Then SummaryTables.Add("MainA", SummaryTableMainA)
    If finBL.Settings.MonitorCategoryBUseAccountApp Then SummaryTables.Add("MainB", SummaryTableMainB)
    If finBL.Settings.MonitorCategoryCUseAccountApp Then SummaryTables.Add("MainC", SummaryTableMainC)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Application Summary (Version 1.03, Last updated 3/03/2016).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="accountApp">
  '''  The Account Application to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Account Application Key Details page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function AccountApp_StatusSummary(callerScriptInfo As ISScriptExecutionInfo,
                                                       accountApp As finAccountApp,
                                              Optional includeActions As Boolean = True,
                                              Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim AccountAppAccount As finAccountAppAccount
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      .Columns.AddText(12).MaxDisplayChars = 16
      .Columns.AddText()

      With .Rows
        ' Status
        If Len(accountApp.StatusSub) = 0 Then
          .AddCaptionText("Status:", accountApp.StatusText, iseSummaryTableCellClass.Highlight2)
        Else
          .AddCaptionWiki("Status:", "**" & accountApp.StatusText & "**" & " --(" & accountApp.StatusSub & ")--", iseSummaryTableCellClass.Highlight2)
        End If

        Select Case accountApp.Status
          Case isefinAccountAppStatus.Accepted
            ' Accepted
            .AddSectionHeading2("Accepted Details")
            .AddCaptionDate("Accepted:", accountApp.DateClosed)
            For Each AccountAppAccount In accountApp.Accounts
              .AddCaptionCodeDescriptionWithFormShow("Account:", AccountAppAccount.AccountPk, finBL.AccountFunctions, "Accounts")
            Next
            If Len(accountApp.CloseByWhom) <> 0 Then .AddCaptionText("By:", accountApp.CloseByWhom)
            If Len(accountApp.CloseNote) <> 0 Then .AddCaptionText("Notes:", accountApp.CloseNote)
            If Len(accountApp.CloseReason) <> 0 Then .AddCaptionText("Reason:", accountApp.CloseReason)

          Case isefinAccountAppStatus.Declined, isefinAccountAppStatus.Unwanted
            ' Declined/ Unwanted
            .AddSectionHeading2(accountApp.StatusText & " Details")
            .AddCaptionDate("Date:", accountApp.DateClosed)
            .AddCaptionText("By:", accountApp.CloseByWhom)
            If Len(accountApp.CloseNote) <> 0 Then .AddCaptionText("Notes:", accountApp.CloseNote)
            If Len(accountApp.CloseReason) <> 0 Then .AddCaptionText("Reason:", accountApp.CloseReason)
        End Select
      End With

      ' Warnings
      .TextAfter = Warnings
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Application Summary.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="accountApp">
  '''  The Account Application to summarise.
  ''' </param>
  ''' <param name="includeAccountAppIdHyperlink">
  '''  Indicates whether to include a hyperlink on the Account Application Id to show the Account Applications form.
  ''' </param>
  ''' <param name="showApplicantAddress">
  '''  Indicates whether to show the Address of the Main Applicant.
  ''' </param>
  ''' <param name="includeMonitoringSummary">
  '''  Indicates whether to include a brief summary of Monitoring.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="compact">
  '''  Indicates whether to optimise for displaying in a compact area.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Account Application Key Details page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''    <item><code>Notes</code><description>Notes (if configured under Global Settings, General, Summary Pages).</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function AccountApp_Summary(callerScriptInfo As ISScriptExecutionInfo,
                                                 accountApp As finAccountApp,
                                        Optional includeAccountAppIdHyperlink As Boolean = True,
                                        Optional showApplicantAddress As Boolean = True,
                                        Optional includeMonitoringSummary As Boolean = False,
                                        Optional compact As Boolean = False,
                                        Optional includeActions As Boolean = True,
                                        Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' AccountApp_Summary
    '
    ' Version: 1.08 (20/08/2024)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.06  04/03/2020  ISS                  
    '    1.07  07/08/2023  ISS      J031733   Notes added if configured
    '          07/08/2023  ISS      J031731   Support hashtags in Notes
    '          26/09/2023  ISS      J032101   Refactored AddOn checks
    '    1.08  20/08/2024  ISS      J034115   Added Manager
    ' #################################################################

    Dim AccountAppAccount As finAccountAppAccount
    Dim AddressDetails As ISAddressDetails
    Dim Notes As String
    Dim strTemp As String
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTableNotes As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      .Columns.AddText(16)
      .Columns.AddText()

      With .Rows
        ' General
        With .AddCaptionText("Code:", accountApp.AccountAppId)
          If includeAccountAppIdHyperlink AndAlso Not accountApp.IsNew Then
            .Cells(1).HyperlinkSetFormShow("AccountApps", accountApp.AccountAppId)
          End If
        End With
        If finBL.SettingsUser.AccountAppShowExternalId Then
          .AddCaptionText("External Id:", accountApp.ExternalId)
        End If
        .AddCaptionText("Name:", accountApp.Name, iseSummaryTableCellClass.Highlight1)

        ' Web Details
        If finBL.Settings.AddOns.WebAutomation Then
          ' Web Friendly Name
          If Len(accountApp.WebFriendlyName) <> 0 Then
            .AddCaptionText("Friendly:", accountApp.WebFriendlyName, iseSummaryTableCellClass.Highlight2)
          End If
        End If

        If showApplicantAddress AndAlso accountApp.Applicants.Count <> 0 Then
          AddressDetails = accountApp.Applicants(0).AddressPostal
          If AddressDetails.HasValue Then
            .AddCaptionAddressDetailsPhysical("Address:", AddressDetails)
          End If
        End If
        .AddCaptionCodeDescription("Type:", accountApp.AccountAppTypePk, finBL.AccountAppTypes)

        ' Branch etc
        If finBL.SettingsUser.SummaryPagesShowBranchResolved AndAlso accountApp.BranchPk <> 0 Then
          With .AddCaptionCodeDescription("Branch:", accountApp.BranchPk, finBL.Branches).Cells(1)
            If finBL.Settings.AddOns.Entity Then
              .Value &= String.Format(" ({0})", accountApp.Entity.Name)
            End If
          End With
        End If
        If finBL.SettingsUser.SummaryPagesShowDepartmentResolved AndAlso accountApp.DepartmentPk <> 0 Then
          .AddCaptionCodeDescription("Department:", accountApp.DepartmentPk, finBL.Departments)
        End If
        If finBL.SettingsUser.SummaryPagesShowManagerResolved AndAlso accountApp.AccountManagerUserPk <> 0 Then
          .AddCaptionCodeDescription("Manager:", accountApp.AccountManagerUserId, finBL.Users)
        End If
        If finBL.SettingsUser.SummaryPagesShowDealerResolved AndAlso accountApp.DealerExternalPartyPk <> 0 Then
          With .AddCaptionCodeDescription("Dealer:", accountApp.DealerExternalPartyPk, finBL.ExternalParties).Cells(1)
            If finBL.ExternalParties.ItemByPk(accountApp.DealerExternalPartyPk).MasterExternalPartyPk <> 0 Then
              .Value &= String.Format(" ({0})", finBL.ExternalParties.ItemByPk(finBL.ExternalParties.ItemByPk(accountApp.DealerExternalPartyPk).MasterExternalPartyPk).Name)
            End If
          End With
        End If
        If finBL.SettingsUser.SummaryPagesShowBrokerResolved AndAlso accountApp.BrokerExternalPartyPk <> 0 Then
          With .AddCaptionCodeDescription("Broker:", accountApp.BrokerExternalPartyPk, finBL.ExternalParties).Cells(1)
            If finBL.ExternalParties.ItemByPk(accountApp.BrokerExternalPartyPk).MasterExternalPartyPk <> 0 Then
              .Value &= String.Format(" ({0})", finBL.ExternalParties.ItemByPk(finBL.ExternalParties.ItemByPk(accountApp.BrokerExternalPartyPk).MasterExternalPartyPk).Name)
            End If
          End With
        End If
        If finBL.SettingsUser.SummaryPagesShowBulkFunderResolved AndAlso accountApp.BulkFunderExternalPartyPk <> 0 Then
          With .AddCaptionCodeDescription("Bulk Funder:", accountApp.BulkFunderExternalPartyPk, finBL.ExternalParties).Cells(1)
            If finBL.ExternalParties.ItemByPk(accountApp.BulkFunderExternalPartyPk).MasterExternalPartyPk <> 0 Then
              .Value &= String.Format(" ({0})", finBL.ExternalParties.ItemByPk(finBL.ExternalParties.ItemByPk(accountApp.BulkFunderExternalPartyPk).MasterExternalPartyPk).Name)
            End If
          End With
        End If

        ' Status
        If Len(accountApp.StatusSub) = 0 Then
          .AddCaptionText("Status:", accountApp.StatusText, iseSummaryTableCellClass.Highlight2)
        Else
          .AddCaptionWiki("Status:", "**" & accountApp.StatusText & "**" & " --(" & accountApp.StatusSub & ")--", iseSummaryTableCellClass.Highlight2)
        End If

        ' Flag
        If Len(accountApp.FlagColour) <> 0 OrElse Len(accountApp.FlagNotes) <> 0 Then
          ' Flag Icon
          If Len(accountApp.FlagColour) = 0 Then
            strTemp = ""
          Else
            strTemp = "{{Flag|" & accountApp.FlagColour & "|" & accountApp.FlagColour & "}} "
          End If

          ' Flag Notes
          If Len(accountApp.FlagNotes) = 0 Then
            ' No Notes
          ElseIf InStr(accountApp.FlagNotes, vbNewLine) <> 0 Then
            ' Multi-Line Notes
            strTemp &= " {{popupNote|" & accountApp.FlagNotes & "}}"
          Else
            ' Single Line Notes
            strTemp &= " " & accountApp.FlagNotes
          End If

          .AddCaptionText("Flag:", strTemp)
        End If

        Select Case accountApp.Status
          Case isefinAccountAppStatus.Accepted
            ' Accepted
            .AddSectionHeading2("Accepted Details")
            .AddCaptionDate("Accepted:", accountApp.DateClosed)
            For Each AccountAppAccount In accountApp.Accounts
              If AccountAppAccount.AccountStatus = isefinAccountStatus.Open Then
                .AddCaptionCodeDescriptionWithFormShow("Account:", AccountAppAccount.AccountPk, finBL.AccountFunctions, "Accounts")
              Else
                With .AddCaptionCodeDescriptionWithFormShow("Account:", AccountAppAccount.AccountPk, finBL.AccountFunctions, "Accounts")
                  .Cells(1).Value &= String.Format(" (**{0}**)", AccountAppAccount.AccountStatusText)
                End With
              End If
            Next
            If Len(accountApp.CloseByWhom) <> 0 Then .AddCaptionText("By:", accountApp.CloseByWhom)
            If Len(accountApp.CloseNote) <> 0 Then .AddCaptionText("Notes:", accountApp.CloseNote)
            If Len(accountApp.CloseReason) <> 0 Then .AddCaptionText("Reason:", accountApp.CloseReason)

          Case isefinAccountAppStatus.Declined, isefinAccountAppStatus.Unwanted
            ' Declined/ Unwanted
            .AddSectionHeading2(accountApp.StatusText & " Details")
            .AddCaptionDate("Date:", accountApp.DateClosed)
            .AddCaptionText("By:", accountApp.CloseByWhom)
            If Len(accountApp.CloseNote) <> 0 Then .AddCaptionText("Notes:", accountApp.CloseNote)
            If Len(accountApp.CloseReason) <> 0 Then .AddCaptionText("Reason:", accountApp.CloseReason)
        End Select

        ' ------------------
        ' Monitoring Summary
        ' ------------------
        If includeMonitoringSummary Then
          If finBL.Settings.MonitorCategoryAUseAccountApp AndAlso accountApp.MonitorCategoryAPk <> 0 Then
            .AddCaptionCodeDescription(finBL.Settings.MonitorCategoryADescriptionResolved & ":", accountApp.MonitorCategoryAPk, finBL.MonitorCategories, , , , iseSummaryTableRowClass.Negative)
          End If
          If finBL.Settings.MonitorCategoryBUseAccountApp AndAlso accountApp.MonitorCategoryBPk <> 0 Then
            .AddCaptionCodeDescription(finBL.Settings.MonitorCategoryBDescriptionResolved & ":", accountApp.MonitorCategoryBPk, finBL.MonitorCategories, , , , iseSummaryTableRowClass.Negative)
          End If
          If finBL.Settings.MonitorCategoryCUseAccountApp AndAlso accountApp.MonitorCategoryCPk <> 0 Then
            .AddCaptionCodeDescription(finBL.Settings.MonitorCategoryCDescriptionResolved & ":", accountApp.MonitorCategoryCPk, finBL.MonitorCategories, , , , iseSummaryTableRowClass.Negative)
          End If
        End If
      End With

      ' Warnings
      .TextAfter = Warnings
    End With

    ' Notes
    If finBL.Settings.SummaryPagesShowNotes AndAlso Len(accountApp.Notes) <> 0 Then
      SummaryTableNotes = finBL.CreateSummaryTable()

      ' Support hashtagging?
      Notes = accountApp.Notes
      If finBL.Settings.QuickSearch2SupportHashtags Then
        Notes = finBL.Utilities.ParseHashTags(Notes)
      End If

      ' Main
      With SummaryTableNotes
        ' Initialise
        .TableClass = iseSummaryTableClass.Information
        .Caption = "Notes"
        .Columns.AddText()

        .Rows.AddText(Notes)
      End With
    End If

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)
    If SummaryTableNotes IsNot Nothing Then SummaryTables.Add("Notes", SummaryTableNotes)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Application Applicants Summary (Version 1.02, Last updated 20/06/2017).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="accountApp">
  '''  The Account Application to summarise.
  ''' </param>
  ''' <param name="includeUnused">
  '''  Indicates whether to include 'Unused' Applicants.
  ''' </param>
  ''' <param name="showCity">
  '''  Indicates whether to include an 'Address' column containing the City with the full address shown in a popup.
  ''' </param>
  ''' <param name="showFullAddress">
  '''  Indicates whether to include an 'Address' column containing the full address (physical if available, if not, postal).
  ''' </param>
  ''' <param name="showContactMethods">
  '''  Indicates whether to include columns detailing the Applicant's Contact Methods.
  ''' </param>
  ''' <param name="showDateOfBirth">
  '''  Indicates whether to show the Applicant's Date of Birth.
  ''' </param>
  ''' <param name="includeRoleOwner">
  '''  Indicates whether to include Owners.
  ''' </param>
  ''' <param name="includeRoleGuarantor">
  '''  Indicates whether to include Guarantors.
  ''' </param>
  ''' <param name="includeRoleOther">
  '''  Indicates whether to include 'Other' Account Roles.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="maxDisplayRows">
  '''  The Maximum number of Rows to Display in the table before a 'Show Hidden' link is displayed.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Application Key Details page and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function AccountApp_Applicants(callerScriptInfo As ISScriptExecutionInfo,
                                                    accountApp As finAccountApp,
                                           Optional includeUnused As Boolean = False,
                                           Optional showCity As Boolean = True,
                                           Optional showFullAddress As Boolean = False,
                                           Optional showContactMethods As Boolean = False,
                                           Optional showDateOfBirth As Boolean = False,
                                           Optional includeRoleOwner As Boolean = True,
                                           Optional includeRoleGuarantor As Boolean = True,
                                           Optional includeRoleOther As Boolean = True,
                                           Optional maxDisplayRows As Integer = 20,
                                           Optional includeActions As Boolean = True,
                                           Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim AccountAppApplicant As finAccountAppApplicant
    Dim AddressDetails As ISAddressDetails
    'Dim ApplicationShortcut As ISApplicationShortcut
    Dim City As String
    Dim ContactMethodDescripitons As String
    Dim ContactMethodValues As String
    Dim Include As Boolean
    Dim strTemp As String
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Validate

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .Caption = ""
      .AutoStripe = True
      .MaxDisplayRows = maxDisplayRows
      .ShowHiddenRowsCaption = "Show More Applicants"

      ' Columns
      With .Columns
        .AddCode("Client", finBL.ClientFunctions.GetLongestCode())
        .AddText("Name")
        If showFullAddress Then
          .AddText("Address", 30).NoBreakChars = 30
        ElseIf showCity Then
          .AddText("Address", 15).NoBreakChars = 15
        End If
        If showContactMethods Then
          With .AddText("Contact", 10)
            .NoBreakChars = 30
            If showFullAddress OrElse showCity Then
              .HideRule = iseSummaryTableColumnHideRule.DocumentWidthLessThan800px
            Else
              .HideRule = iseSummaryTableColumnHideRule.DocumentWidthLessThan640px
            End If
          End With
          With .AddText(" ")
            .NoBreakChars = 30
            If showFullAddress OrElse showCity Then
              .HideRule = iseSummaryTableColumnHideRule.DocumentWidthLessThan800px
            Else
              .HideRule = iseSummaryTableColumnHideRule.DocumentWidthLessThan640px
            End If
          End With
        End If
        .AddText("Role", 10).NoBreakChars = 15
        If showDateOfBirth Then .AddDate("DOB")
      End With

      With .Rows
        For Each AccountAppApplicant In accountApp.Applicants
          ' Include?
          Select Case AccountAppApplicant.AccountRoleType
            Case isefinAccountRoleType.Guarantor : Include = includeRoleGuarantor
            Case isefinAccountRoleType.Other : Include = includeRoleOther
            Case isefinAccountRoleType.Owner : Include = includeRoleOwner
            Case Else : Include = True
          End Select
          If Include Then
            If Not includeUnused AndAlso Not AccountAppApplicant.Used Then Include = False
          End If

          If Include Then
            ' Add Row
            With .Add()
              ' Unused?
              If Not AccountAppApplicant.Used Then
                .ForegroundColour = "gray"
              End If

              With .Cells()
                With .AddText(AccountAppApplicant.ClientId)
                  If AccountAppApplicant.ClientPk <> 0 Then
                    .HyperlinkSetFormShow("Clients", AccountAppApplicant.ClientId)
                  End If
                End With
                With .AddText(AccountAppApplicant.Name)
                  ' Edit Applicant
                  If Not finBL.Database.IsReadOnly AndAlso accountApp.AccountAppType IsNot Nothing AndAlso accountApp.AccountAppType.DataEntryApplicantHtmlWidgetScriptPk <> 0 AndAlso Not accountApp.IsClosed Then
                    .HyperlinkSetApplicationShortcutUrl(accountApp.AccountAppType.GetApplicationShortcutUrlHtmlWidgetApplicant(accountApp.Pk, AccountAppApplicant.Pk, False))
                  End If
                End With

                ' Address/ City
                If showCity OrElse showFullAddress Then
                  ' Get Address
                  AddressDetails = AccountAppApplicant.AddressPhysical
                  If Not AddressDetails.HasValue Then AddressDetails = AccountAppApplicant.AddressPostal

                  If AddressDetails.HasValue Then
                    If showFullAddress Then
                      ' Full Address
                      .AddAddressDetailsPhysical(AddressDetails)
                    Else
                      ' City (plus full Address popup)
                      Select Case finBL.CountryCode
                        Case "AU"
                          ' Suburb is generally used in Australia
                          City = AddressDetails.Suburb
                          If Len(City) = 0 Then City = AddressDetails.City
                        Case Else
                          ' If not City then list Suburb
                          City = AddressDetails.City
                          If Len(City) = 0 Then City = AddressDetails.Suburb
                      End Select

                      With .AddText(City)
                        If AddressDetails.HasValue Then
                          .TooltipSetPopupNote(finBL.Addressing.FormatAddressFromAddressDetails(AddressDetails, , True))
                        End If
                      End With
                    End If
                  Else
                    .AddText("")
                  End If
                End If

                If showContactMethods Then
                  ' Contact Methods
                  ContactMethodDescripitons = ""
                  ContactMethodValues = ""

                  If Len(AccountAppApplicant.ContactPhone) <> 0 Then
                    If Len(ContactMethodDescripitons) <> 0 Then
                      ContactMethodDescripitons &= vbNewLine
                      ContactMethodValues &= vbNewLine
                    End If
                    ContactMethodDescripitons &= "Phone:"
                    ContactMethodValues &= String.Format("[[app://contact?accountAppId={0}&accountAppApplicantPk={1}&phoneNumber={2}&phoneSms=false|{3}]]", finBL.UrlEncode(accountApp.AccountAppId), AccountAppApplicant.Pk, finBL.UrlEncode(AccountAppApplicant.ContactPhone), AccountAppApplicant.ContactPhone)
                  End If

                  If Len(AccountAppApplicant.ContactPhoneWork) <> 0 Then
                    If Len(ContactMethodDescripitons) <> 0 Then
                      ContactMethodDescripitons &= vbNewLine
                      ContactMethodValues &= vbNewLine
                    End If
                    ContactMethodDescripitons &= "Work:"
                    ContactMethodValues &= String.Format("[[app://contact?accountAppId={0}&accountAppApplicantPk={1}&phoneNumber={2}&phoneSms=false|{3}]]", finBL.UrlEncode(accountApp.AccountAppId), AccountAppApplicant.Pk, finBL.UrlEncode(AccountAppApplicant.ContactPhoneWork), AccountAppApplicant.ContactPhoneWork)
                  End If

                  If Len(AccountAppApplicant.ContactMobile) <> 0 Then
                    If Len(ContactMethodDescripitons) <> 0 Then
                      ContactMethodDescripitons &= vbNewLine
                      ContactMethodValues &= vbNewLine
                    End If
                    ContactMethodDescripitons &= "Mobile:"
                    ContactMethodValues &= String.Format("[[app://contact?accountAppId={0}&accountAppApplicantPk={1}&phoneNumber={2}&phoneSms=true|{3}]]", finBL.UrlEncode(accountApp.AccountAppId), AccountAppApplicant.Pk, finBL.UrlEncode(AccountAppApplicant.ContactMobile), AccountAppApplicant.ContactMobile)
                  End If

                  If Len(AccountAppApplicant.ContactEmail) <> 0 Then
                    If Len(ContactMethodDescripitons) <> 0 Then
                      ContactMethodDescripitons &= vbNewLine
                      ContactMethodValues &= vbNewLine
                    End If
                    ContactMethodDescripitons &= "Email:"
                    ContactMethodValues &= String.Format("[[app://contact?accountAppId={0}&accountAppApplicantPk={1}&emailAddress={2}|{3}]]", finBL.UrlEncode(accountApp.AccountAppId), AccountAppApplicant.Pk, finBL.UrlEncode(AccountAppApplicant.ContactEmail), AccountAppApplicant.ContactEmail)
                  End If

                  .AddWiki(ContactMethodDescripitons) ' Added as Wiki so HTML templates are not destroyed
                  .AddWiki(ContactMethodValues)       ' Added as Wiki to enable contact hyperlinks
                End If

                ' Account Role
                If AccountAppApplicant.AccountRoleResolvedPk = 0 Then
                  strTemp = "!!Not defined!!"
                Else
                  With finBL.AccountRoles.ItemByPk(AccountAppApplicant.AccountRoleResolvedPk)
                    strTemp = .DescriptionShortResolved
                  End With
                End If
                If AccountAppApplicant.AccountRoleJointResolved Then
                  strTemp &= " --(Joint)--"
                End If
                .AddWiki(strTemp)

                ' Date of Birth
                If showDateOfBirth Then
                  .AddDate(AccountAppApplicant.DateOfBirth)
                End If
              End With
            End With
          End If
        Next
      End With

      ' Warnings
      .TextAfter = Warnings

      ' Actions
      If includeActions Then
        With .Actions
          ' Add Applicant
          If Not finBL.Database.IsReadOnly AndAlso accountApp.AccountAppType IsNot Nothing AndAlso accountApp.AccountAppType.DataEntryApplicantHtmlWidgetScriptPk <> 0 AndAlso accountApp.AccountAppType.AllowAdditionalApplicants AndAlso Not accountApp.IsClosed Then
            .AddApplicationShortcutUrl("ItemAdd", "Add Applicant", accountApp.AccountAppType.GetApplicationShortcutUrlHtmlWidgetApplicant(accountApp.Pk, -1, False), callerScriptInfo.FormRecordMode = iseFormRecordMode.Loaded).ShowInWebInterfaces = True
          End If
        End With
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Application Workflows Summary.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="accountApp">
  '''  The Account Application to summarise.
  ''' </param>
  ''' <param name="includeComplete">
  '''  Indicates whether to include Complete (non-cancelled) Workflows.
  ''' </param>
  ''' <param name="includeIncomplete">
  '''  Indicates whether to include Incomplete Workflows.
  ''' </param>
  ''' <param name="includeCancelled">
  '''  Indicates whether to include Cancelled Workflows.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="maxDisplayRows">
  '''  The Maximum number of Rows to Display in the table before a 'Show Hidden' link is displayed.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Status and Key Details pages and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function AccountApp_Workflows(callerScriptInfo As ISScriptExecutionInfo,
                                                   accountApp As finAccountApp,
                                                   includeComplete As Boolean,
                                                   includeIncomplete As Boolean,
                                                   includeCancelled As Boolean,
                                          Optional maxDisplayRows As Integer = 20,
                                          Optional includeActions As Boolean = True,
                                          Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' AccountApp_Workflows
    '
    ' Version: 1.03 (23/08/2023)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.02  19/04/2016
    '    1.03  23/08/2023  ISS      J031278   Remove "Locate in Task Manager" link
    ' #################################################################

    Dim AccountAppWorkflow As finAccountAppWorkflow
    Dim DateAsAt As Date
    Dim Include As Boolean
    Dim ShowLocateInTaskManager As Boolean
    Dim StatusIcon As String
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim TooltipText As String
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Date As At
    DateAsAt = finBL.TimeZoneFunctions.GetCurrentDatabaseDate()

    ' Determine Columns to include
    Select Case callerScriptInfo.Target
      Case iseSummaryPageTarget.Form
        If finBL.Settings.UseTaskManager1Resolved Then
          ShowLocateInTaskManager = (accountApp.Workflows.CountInTaskManager <> 0) AndAlso Not finBL.IsRunningFromWeb() AndAlso finBL.CurrentUser.Permissions.Allow("Menu.Process.TaskManager")
        End If
    End Select

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .Caption = ""
      .AutoStripe = True
      .MaxDisplayRows = maxDisplayRows
      .ShowHiddenRowsCaption = "Show More Workflows"

      If accountApp.Workflows.Count = 0 Then
        ' No Workflows
        .TextAfter = "{{info|No Workflows.}}"
      Else
        ' Columns
        With .Columns
          .AddText(" ", 1, iseSummaryTableCellTextAlign.Center) ' Flag Colour
          .AddText(" ", 1, iseSummaryTableCellTextAlign.Center) ' Status Icon
          .AddDate("Opened")
          .AddCode("Workflow", finBL.WorkflowFunctions.GetLongestCode())
          If ShowLocateInTaskManager Then
            With .AddText(" ", 1, iseSummaryTableCellTextAlign.Center) ' Locate in Task Manager Icon
              .HideRule = iseSummaryTableColumnHideRule.DocumentWidthLessThan800px
            End With
          End If
          .AddText("Description").HideRule = iseSummaryTableColumnHideRule.DocumentWidthLessThan640px
          .AddText("Current Item").HideRule = iseSummaryTableColumnHideRule.DocumentWidthLessThan800px
          .AddCode("Allocated", finBL.Users.GetLongestCode())
        End With

        With .Rows
          For Each AccountAppWorkflow In accountApp.Workflows
            ' Include?
            Select Case AccountAppWorkflow.Status
              Case isefinWorkflowStatus.Closed
                If AccountAppWorkflow.ClosedType = isefinWorkflowClosedType.Cancelled Then
                  Include = includeCancelled
                Else
                  Include = includeComplete
                End If
              Case Else
                Include = includeIncomplete
            End Select

            If Include Then
              ' Status Icon (not the real Status but something to bring this item to the User's attention)
              StatusIcon = "Blank"
              TooltipText = ""
              If AccountAppWorkflow.Status = isefinWorkflowStatus.Closed Then
                If AccountAppWorkflow.ClosedType = isefinWorkflowClosedType.Cancelled Then
                  StatusIcon = "WorkflowStatus_Cancelled"
                  TooltipText = "Cancelled"
                Else
                  StatusIcon = "WorkflowStatus_Closed"
                  TooltipText = "Closed"
                End If
              Else
                Select Case AccountAppWorkflow.Status
                  Case isefinWorkflowStatus.OnHold
                    StatusIcon = "Hold"
                    TooltipText = "On Hold"
                  Case isefinWorkflowStatus.Pending
                    StatusIcon = "WorkflowPending"
                    TooltipText = "Pending"
                  Case isefinWorkflowStatus.Open
                    If AccountAppWorkflow.RecallImmediate OrElse (AccountAppWorkflow.RecallDate <> Nothing AndAlso AccountAppWorkflow.RecallDate < DateAsAt) Then
                      StatusIcon = "Review"
                      If AccountAppWorkflow.RecallImmediate Then
                        TooltipText = "Immediate Recall"
                      Else
                        TooltipText = String.Format("Recall due to Recall Date of {0} reached", finBL.FormatDate(AccountAppWorkflow.RecallDate, True))
                      End If
                    ElseIf Not AccountAppWorkflow.RecallImmediate AndAlso AccountAppWorkflow.RecallDate <> Nothing AndAlso AccountAppWorkflow.RecallDate > DateAsAt Then
                      StatusIcon = "Hourglass"
                      TooltipText = "Waiting for Recall Date to be reached"
                    End If
                End Select
              End If

              ' Add Row
              With .Add()
                ' Cancelled?
                If AccountAppWorkflow.Status = isefinWorkflowStatus.Closed Then
                  If AccountAppWorkflow.ClosedType = isefinWorkflowClosedType.Cancelled Then
                    .RowClass = iseSummaryTableRowClass.Inactive
                  Else
                    .ForegroundColour = "gray"
                  End If
                  .Visible = False
                End If

                With .Cells
                  If Len(AccountAppWorkflow.FlagColour) = 0 Then
                    .AddText("")
                  Else
                    .AddText("{{flag|" & AccountAppWorkflow.FlagColour & "}}").Tooltip = AccountAppWorkflow.FlagColour
                  End If
                  If Len(StatusIcon) = 0 Then
                    .AddText("")
                  Else
                    .AddText("{{icon|" & StatusIcon & "}}").Tooltip = TooltipText
                  End If
                  .AddDate(AccountAppWorkflow.OpenedDate)
                  With .AddText(AccountAppWorkflow.WorkflowId)
                    .HyperlinkSetFormShow("Workflows", AccountAppWorkflow.WorkflowId)
                  End With
                  If ShowLocateInTaskManager Then
                    If AccountAppWorkflow.IsInTaskManager() Then
                      With .AddText("{{icon|Task_Locate|Locate in Task Manager}}")
                        .HyperlinkSetFormAction("LocateWorkflow", "workflowId=" & finBL.UrlEncode(AccountAppWorkflow.WorkflowId), "TaskManager", True, True)
                      End With
                    Else
                      .AddText("")
                    End If
                  End If
                  .AddText(AccountAppWorkflow.Description)
                  If AccountAppWorkflow.Workflow.GetCurrentItem() Is Nothing Then
                    .AddText("")
                  Else
                    .AddText(AccountAppWorkflow.Workflow.GetCurrentItem().Description)
                  End If
                  .AddText(AccountAppWorkflow.AllocatedUserId)
                End With
              End With
            End If
          Next
        End With

        ' Warnings
        .TextAfter = Warnings

        ' Actions
        If includeActions Then
          With .Actions
          End With
        End If
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Application Type Summary (Version 1.0, Last updated 22/08/2013).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="accountAppType">
  '''  The Account Application Type to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Key Details Page when viewed from the Account Type Applications form.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function AccountAppType_Summary(callerScriptInfo As ISScriptExecutionInfo,
                                                     accountAppType As finAccountAppType,
                                            Optional includeActions As Boolean = True,
                                            Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      .Columns.AddText(16)
      .Columns.AddText()

      With .Rows
        ' General
        .AddCaptionText("Code:", accountAppType.AccountAppTypeId)
        .AddCaptionText("Description:", accountAppType.Description, iseSummaryTableCellClass.Highlight1)
        .AddCaptionText("Version:", Format(accountAppType.Version, "0.00"))
      End With
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Archive View Summary (Version 1.01, Last updated 14/04/2021).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="accountArchiveView">
  '''  Account Details for Account Archive View to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Client Accounts page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Summary.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function AccountArchiveView_Summary(callerScriptInfo As ISScriptExecutionInfo,
                                                         accountArchiveView As finAccountArchiveView,
                                                Optional includeActions As Boolean = True,
                                                Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim CreatedUser As finUserRO
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables

    Dim Warnings As String

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    CreatedUser = finBL.Users.ItemByPkSafe(accountArchiveView.CreatedUserPk)
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      .Columns.AddText(12).NoBreakChars = 20
      .Columns.AddText()

      With .Rows
        ' General
        .AddCaptionText("Type:", accountArchiveView.ArchiveTypeText)
        Select Case accountArchiveView.ArchiveType
          Case isefinAccountArchiveType.Closed
            .AddCaptionDate("Closed:", accountArchiveView.DateClosed)
            If Len(accountArchiveView.ClosedToAccountId) <> 0 Then
              .AddCaptionWiki("Method:", String.Format("**{0}**-- to Account [[{1}{2}|{2}]] --", accountArchiveView.CloseMethodText, "app://formshow?form=Accounts&id=", accountArchiveView.ClosedToAccountId))
            ElseIf Len(accountArchiveView.ClosedToArchiveId) <> 0 Then
              .AddCaptionWiki("Method:", String.Format("**{0}**-- to Archived Account [[{1}{2}|{2}]]--", accountArchiveView.CloseMethodText, "app://formshow?form=AccountArchiveView&id=AccountId=", accountArchiveView.ClosedToArchiveId))
            Else
              .AddCaptionText("Method:", accountArchiveView.CloseMethodText)
            End If
        End Select
        If Len(accountArchiveView.ArchiveByWhom) <> 0 Then
          If accountArchiveView.ArchiveByWhom = CreatedUser.UserId AndAlso accountArchiveView.ArchiveDate.Date = accountArchiveView.CreatedDate.Date Then
            ' Ignore
          Else
            .AddCaptionText("By Whom:", String.Format("{0} on {1}", accountArchiveView.ArchiveByWhom, accountArchiveView.ArchiveDate))
          End If
        End If
        If Len(accountArchiveView.ArchiveNote) <> 0 Then .AddCaptionText("Notes:", accountArchiveView.ArchiveNote)
        .AddCaptionText("Reason:", accountArchiveView.ArchiveReason)

        ' Archived Date and Time
        If accountArchiveView.CreatedDate.TimeOfDay = Nothing Then
          .AddCaptionText("Archived:", String.Format("{0} on {1}.", CreatedUser.UserId, finBL.FormatDateLong(accountArchiveView.CreatedDate)))
        Else
          .AddCaptionText("Archived:", String.Format("{0} on {1} at {2}.", CreatedUser.UserId, finBL.FormatDateLong(accountArchiveView.CreatedDate), finBL.FormatDateTimeLong(accountArchiveView.CreatedDate, True)))
        End If
      End With

      ' Warnings
      .TextAfter = Warnings
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Archive View Account Details (Version 1.02, Last updated 20/03/2020).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="accountArchiveView">
  '''  Account Details for Account Archive View to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Client Accounts page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Summary.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function AccountArchiveView_AccountDetails(callerScriptInfo As ISScriptExecutionInfo,
                                                                accountArchiveView As finAccountArchiveView,
                                                       Optional includeActions As Boolean = True,
                                                       Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim AccountAppId As String
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      .Columns.AddText(12).NoBreakChars = 20
      .Columns.AddText()

      With .Rows
        ' Account Details
        .AddCaptionCodeDescription("Account:", accountArchiveView.AccountId, accountArchiveView.Name)
        For Each AccountAppId In accountArchiveView.AccountAppIds
          .AddCaptionText("Application:", AccountAppId)
        Next
        If Len(accountArchiveView.ExternalId) <> 0 Then
          .AddCaptionText("External Id:", accountArchiveView.ExternalId)
        End If
        .AddCaptionText("Class:", accountArchiveView.AccountClassText)
        If accountArchiveView.AccountType Is Nothing Then
          .AddCaptionText("Type:", accountArchiveView.AccountTypeId)
        Else
          .AddCaptionCodeDescription("Type:", accountArchiveView.AccountTypePk, finBL.AccountTypes)
        End If
        If Len(accountArchiveView.AccountTypePromotionId) <> 0 Then
          If accountArchiveView.AccountType Is Nothing OrElse Not accountArchiveView.AccountType.Promotions.Exists(accountArchiveView.AccountTypePromotionId) Then
            .AddCaptionText("Promotion:", accountArchiveView.AccountTypePromotionId)
          Else
            .AddCaptionCodeDescription("Promotion:", accountArchiveView.AccountTypePromotionId, accountArchiveView.AccountType.Promotions(accountArchiveView.AccountTypePromotionId).Description)
          End If
        End If
        If accountArchiveView.ConsumerRegulationType <> isefinAccountConsumerRegulationType.NotApplicable Then
          .AddCaptionText("Consumer Regulation:", accountArchiveView.ConsumerRegulationTypeText)
        End If
        If accountArchiveView.CreationMethod <> isefinAccountCreationMethod.New Then
          .AddCaptionText("Method:", accountArchiveView.CreationMethodText)
        End If
        If finBL.Settings.AddOns.Branch AndAlso Len(accountArchiveView.BranchId) <> 0 Then
          .AddCaptionCodeDescription("Branch:", accountArchiveView.BranchId, finBL.Branches)
        End If
        If Len(accountArchiveView.DepartmentId) <> 0 Then
          .AddCaptionCodeDescription("Department:", accountArchiveView.DepartmentId, finBL.Departments)
        End If
        If finBL.Settings.AddOns.ExternalPartyDealers AndAlso Len(accountArchiveView.DealerExternalPartyId) <> 0 Then
          .AddCaptionCodeDescription("Dealer:", accountArchiveView.DealerExternalPartyId, finBL.ExternalParties)
          If Len(accountArchiveView.DealerExternalPartyEmployeeName) <> 0 Then .AddCaptionText("", accountArchiveView.DealerExternalPartyEmployeeName)
        End If
        If finBL.Settings.AddOns.ExternalPartyBrokers AndAlso Len(accountArchiveView.BrokerExternalPartyId) <> 0 Then
          .AddCaptionCodeDescription("Broker:", accountArchiveView.BrokerExternalPartyId, finBL.ExternalParties)
          If Len(accountArchiveView.BrokerExternalPartyEmployeeName) <> 0 Then .AddCaptionText("", accountArchiveView.BrokerExternalPartyEmployeeName)
        End If
        If finBL.Settings.AddOns.Securitisation AndAlso Len(accountArchiveView.BulkFunderExternalPartyId) <> 0 Then
          .AddCaptionCodeDescription("Bulk Funder:", accountArchiveView.BulkFunderExternalPartyId, finBL.ExternalParties)
        End If
        If Len(accountArchiveView.Purpose) <> 0 Then
          .AddCaptionText("Purpose:", accountArchiveView.Purpose)
        End If
        If Len(accountArchiveView.Source) <> 0 Then
          .AddCaptionText("Source:", accountArchiveView.Source)
        End If
        If Len(accountArchiveView.Region) <> 0 Then
          .AddCaptionText("Region:", accountArchiveView.Region)
        End If
      End With

      ' Warnings
      .TextAfter = Warnings
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Client Summary (Version 1.0, Last updated 22/08/2013).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="accountClient">
  '''  The Account Client to summarise.
  ''' </param>
  ''' <param name="productTypeId">
  '''  The Product Type to determine what to display (only used for new Accounts that do not have an Account Id set).
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Client Key Details Page when viewed from the Accounts form, Clients page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function AccountClient_Summary(callerScriptInfo As ISScriptExecutionInfo,
                                                    accountClient As finAccountClient,
                                           Optional productTypeId As String = "",
                                           Optional includeActions As Boolean = True,
                                           Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim ShowInsuranceDetails As Boolean
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()
    If Len(productTypeId) = 0 AndAlso accountClient.Account.AccountType IsNot Nothing Then productTypeId = accountClient.Account.AccountType.ProductTypeId

    ' Show Insurance Details?
    If finBL.AccountRoles.Exists(accountClient.AccountRoleId) Then
      If finBL.AccountRoles(accountClient.AccountRoleId).RecordInsuranceDetails Then
        If finBL.ProductTypes.Exists(productTypeId) Then
          ShowInsuranceDetails = finBL.ProductTypes(productTypeId).IncludeClientLevelInsurance
        Else
          ' Should never get here
          ShowInsuranceDetails = False
        End If
      Else
        ShowInsuranceDetails = False
      End If
    Else
      ShowInsuranceDetails = False
    End If

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      .Columns.AddText(10).NoBreakChars = 10
      .Columns.AddText()

      With .Rows
        ' General
        If accountClient.RoleJoint Then
          With .AddCaptionCodeDescription("Role:", accountClient.AccountRoleId, finBL.AccountRoles)
            .Cells(1).Value &= " --(Joint)--"
          End With
        Else
          .AddCaptionCodeDescription("Role:", accountClient.AccountRoleId, finBL.AccountRoles)
        End If

        ' Options
        If accountClient.Parent.IndexOf(accountClient) = 0 Then
          ' Not applicable to Main Client
        Else
          .AddSectionHeading2("Options")
          .AddCaptionTick("Hide:", accountClient.AccountHidden)
          .AddCaptionTick("Signatory:", accountClient.AccountSignatory)
          If finBL.AccountRoles.Exists(accountClient.AccountRoleId) AndAlso finBL.AccountRoles(accountClient.AccountRoleId).UsePrivacyConsent Then
            .AddCaptionTick("Privacy:", accountClient.PrivacyConsent)
          End If
          If finBL.Settings.AddOns.SecurityRegister Then
            .AddCaptionTick("Security:", accountClient.SecurityParty)
          End If
        End If

        ' Insurance
        If ShowInsuranceDetails Then
          .AddSectionHeading2("Insurance")
          If finBL.Settings.AddOns.ExternalPartyInsurers Then
            .AddCaptionCodeDescription("Insurer:", accountClient.InsuranceInsurerExternalPartyId, finBL.ExternalParties)
          End If
          .AddCaptionText("Policy Type:", accountClient.InsurancePolicyType)
          .AddCaptionText("Policy Number:", accountClient.InsurancePolicyNumber)
        End If

        ' Notes
        If Len(accountClient.Notes) <> 0 Then
          .AddSectionHeading2("Notes")
          .AddText(accountClient.Notes)
        End If
      End With
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Close Summary (Version 1.03, Last updated 09/03/2020).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="accountClose">
  '''  The Account Close object to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Close wizard.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function AccountClose_Summary(callerScriptInfo As ISScriptExecutionInfo,
                                                   accountClose As finAccountClose,
                                          Optional includeActions As Boolean = True,
                                          Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim AccountCalc As finAccountCalc
    Dim AccountTransaction As finAccountTransaction
    Dim PendingWithdrawals As Decimal
    Dim SummaryTable As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim UnclearedFunds As Decimal
    Dim Warnings As String

    ' Initialise
    SummaryTables = finBL.CreateSummaryTables()

    ' Cache Account Calculation
    AccountCalc = accountClose.Account.Calculation

    ' Get Values
    accountClose.Account.GetPendingWithdrawals(PendingWithdrawals)
    accountClose.Account.GetUnclearedFunds2(UnclearedFunds)

    SummaryTable = SummaryTables.CreateSummaryTableInformation("", "Main")
    With SummaryTable
      ' Alert Messages
      accountClose.Account.GetAlertMessages(.TextBefore)

      ' Type
      .AddRowCaptionCodeDescription("Type:", accountClose.Account.AccountTypeId, finBL.AccountTypes)

      ' Account Class
      Select Case AccountCalc.AccountClass
        ' NOTE: AddRowCaptionX methods exclude rows by default if a value is zero. Set alwaysInclude = True to always include rows
        Case isefinAccountClass.Deposit
          .AddRowCaptionDate("Date Opened:", AccountCalc.OpeningDate)
          .AddRowCaptionText("Term:", AccountCalc.TermCycleDescription)
          If AccountCalc.DateMaturity <> Nothing Then
            .AddRowCaptionDate("Maturity:", AccountCalc.DateMaturity)
          End If

          ' Warnings
          Select Case AccountCalc.TermCycle
            Case "On Call"
            Case Else
              Warnings &= "{{warning|This is a Fixed Term Deposit.}}"
          End Select

        Case isefinAccountClass.Disbursement
          .AddRowCaptionDate("Date Opened:", AccountCalc.OpeningDate)

        Case isefinAccountClass.LoanFR, isefinAccountClass.LoanFT
          .AddRowCaptionDate("Date Opened:", AccountCalc.OpeningDate)
          If AccountCalc.IsRestructured Then
            .AddRowCaptionText("Original Term:", AccountCalc.TermCycleDescription)
            .AddRowCaptionDate("Original Maturity:", accountClose.Account.CalculationVersions(0).DateMaturity)
            .AddRowCaptionDate("Current Maturity:", AccountCalc.DateMaturity)
          ElseIf AccountCalc.OriginalDateMaturity <> AccountCalc.DateMaturity Then
            .AddRowCaptionText("Original Term:", AccountCalc.TermCycleDescription)
            .AddRowCaptionDate("Original Maturity:", AccountCalc.OriginalDateMaturity)
            .AddRowCaptionDate("Current Maturity:", AccountCalc.DateMaturity)
          Else
            .AddRowCaptionText("Term:", AccountCalc.TermCycleDescription)
            .AddRowCaptionDate("Maturity:", AccountCalc.DateMaturity)
          End If
          If AccountCalc.ResidualValue <> 0 Then
            .AddRowCaptionCurrency("Residual:", AccountCalc.ResidualValue)
          End If

        Case isefinAccountClass.LoanRC
          .AddRowCaptionDate("Date Opened:", AccountCalc.OpeningDate)
      End Select

      ' Pending Withdrawals
      If PendingWithdrawals <> 0 Then
        Warnings &= "{{warning|Pending withdrawals of " & finBL.FormatCurrency(PendingWithdrawals, True) & " exist.}}"
      End If

      ' Uncleared Funds
      If UnclearedFunds <> 0 Then
        Warnings &= "{{warning|Funds of " & finBL.FormatCurrency(UnclearedFunds, True) & " not yet cleared.}}"
      End If

      ' Post Dated Transactions?
      If accountClose.CloseDate <> Nothing Then
        For Each AccountTransaction In accountClose.Account.Transactions
          If AccountTransaction.Date > accountClose.CloseDate Then
            If AccountTransaction.ReversePk = 0 OrElse AccountTransaction.ElementType = isefinElementType.PaymentReceived Then
              Warnings &= "{{Warning|Transactions are dated after the date the Account will be closed.}}"
              Exit For
            End If
          End If
        Next
      End If

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

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Close Financial Summary.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="accountClose">
  '''  The Account Close object to summarise.
  ''' </param>
  ''' <param name="showOriginalValues">
  '''  Show a column with the Original Values calculated.
  ''' </param>
  ''' <param name="showPostScriptValues">
  '''  Show a column with Values after the Post Script has been run.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Close wizard and Account Close Log form.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function AccountClose_FinancialSummary(callerScriptInfo As ISScriptExecutionInfo,
                                                            accountClose As finAccountClose,
                                                   Optional showOriginalValues As Boolean = True,
                                                   Optional showPostScriptValues As Boolean = False,
                                                   Optional includeActions As Boolean = True,
                                                   Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' AccountClose_FinancialSummary
    '
    ' Version: 1.02 (24/07/2024)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.01  05/04/2020
    '    1.02  24/07/2024  ISS      J032515   Updated to use Other Interest description
    ' #################################################################

    Dim BalanceActual As Decimal
    Dim BalanceOriginal As Decimal
    Dim BalancePostScript As Decimal
    Dim Message As String
    Dim SummaryTable As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise
    SummaryTables = finBL.CreateSummaryTables()

    SummaryTable = finBL.CreateSummaryTable()
    With SummaryTable
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .Caption = ""
      .AutoStripe = True

      ' Columns
      With .Columns
        If showOriginalValues OrElse showPostScriptValues Then
          .AddText(" ")
          If showOriginalValues Then .AddCurrency("Original", 16).NoBreakChars = 30
          If showPostScriptValues Then .AddCurrency("Post Script", 16).NoBreakChars = 30
          .AddCurrency("Actual", 16).NoBreakChars = 30
        Else
          .AddText("")
          .AddCurrency("", 16).NoBreakChars = 30
        End If
      End With

      ' Initialise Balances
      BalanceActual = accountClose.BalanceCurrent
      BalanceOriginal = accountClose.BalanceCurrent
      BalancePostScript = accountClose.BalanceCurrent

      ' Rows
      With .Rows
        Select Case accountClose.Account.AccountClass
          Case isefinAccountClass.Deposit
            ' Balance
            With .Add(iseSummaryTableRowClass.Footer).Cells
              .AddText("Current Balance").CellClass = iseSummaryTableCellClass.CaptionBold
              If showOriginalValues Then .AddCurrency(-BalanceOriginal, True)
              If showPostScriptValues Then .AddCurrency(-BalancePostScript, True)
              .AddCurrency(-BalanceActual, True).CellClass = iseSummaryTableCellClass.CaptionBold
            End With

            If accountClose.Summary.TotalCredits <> 0 OrElse accountClose.Summary.TotalCreditsOriginal <> 0 Then
              With .Add().Cells
                If accountClose.Summary.TotalCredits < 0 Then
                  .AddText("  less Credits")
                  If showOriginalValues Then .AddCurrency(-accountClose.Summary.TotalCreditsOriginal)
                  If showPostScriptValues Then .AddCurrency(-accountClose.Summary.TotalCreditsPostScript)
                  .AddCurrency(-accountClose.Summary.TotalCredits)
                Else
                  .AddText("    plus Credits")
                  If showOriginalValues Then .AddCurrency(accountClose.Summary.TotalCreditsOriginal)
                  If showPostScriptValues Then .AddCurrency(accountClose.Summary.TotalCreditsPostScript)
                  .AddCurrency(accountClose.Summary.TotalCredits)
                End If
              End With

              BalanceActual -= accountClose.Summary.TotalCredits
              BalanceOriginal -= accountClose.Summary.TotalCreditsOriginal
              BalancePostScript -= accountClose.Summary.TotalCreditsPostScript
            End If

            If accountClose.AccruedInterestResolved <> 0 OrElse accountClose.AccruedInterestOriginal <> 0 Then
              With .Add().Cells
                If accountClose.AccruedInterestResolved < 0 Then
                  .AddText("    plus Accrued Interest")
                  If showOriginalValues Then .AddCurrency(-accountClose.AccruedInterestOriginal)
                  If showPostScriptValues Then .AddCurrency(-accountClose.AccruedInterestPostScript)
                  .AddCurrency(-accountClose.AccruedInterestResolved)
                Else
                  .AddText("    less Accrued Interest")
                  If showOriginalValues Then .AddCurrency(accountClose.AccruedInterestOriginal)
                  If showPostScriptValues Then .AddCurrency(accountClose.AccruedInterestPostScript)
                  .AddCurrency(accountClose.AccruedInterestResolved)
                End If
              End With

              BalanceActual += accountClose.AccruedInterestResolved
              BalanceOriginal += accountClose.AccruedInterestOriginal
              BalancePostScript += accountClose.AccruedInterestPostScript
            End If

            If accountClose.WithholdingTaxValueResolved <> 0 OrElse accountClose.WithholdingTaxValueOriginal <> 0 Then
              With .Add().Cells
                If accountClose.WithholdingTaxValueResolved < 0 Then
                  .AddText(String.Format("    less Withholding Tax ({0} @ {1})", accountClose.WithholdingTaxResidentStatusShortText, finBL.FormatPercentage(accountClose.WithholdingTaxRate / 100, 4)))
                  If showOriginalValues Then .AddCurrency(-accountClose.WithholdingTaxValueOriginal)
                  If showPostScriptValues Then .AddCurrency(-accountClose.WithholdingTaxValuePostScript)
                  .AddCurrency(-accountClose.WithholdingTaxValueResolved)
                Else
                  .AddText("    plus Withholding Tax")
                  If showOriginalValues Then .AddCurrency(accountClose.WithholdingTaxValueOriginal)
                  If showPostScriptValues Then .AddCurrency(accountClose.WithholdingTaxValuePostScript)
                  .AddCurrency(accountClose.WithholdingTaxValueResolved)
                End If
              End With

              BalanceActual -= accountClose.WithholdingTaxValueResolved
              BalanceOriginal -= accountClose.WithholdingTaxValueOriginal
              BalancePostScript -= accountClose.WithholdingTaxValuePostScript
            End If

            If accountClose.AccruedOtherInterestResolved <> 0 OrElse accountClose.AccruedOtherInterestOriginal <> 0 Then
              With .Add().Cells
                If accountClose.AccruedOtherInterestResolved < 0 Then
                  .AddText("    plus Accrued " & accountClose.Account.AccountType.OtherInterestDescriptionResolved)
                  If showOriginalValues Then .AddCurrency(-accountClose.AccruedOtherInterestOriginal)
                  If showPostScriptValues Then .AddCurrency(-accountClose.AccruedOtherInterestPostScript)
                  .AddCurrency(-accountClose.AccruedOtherInterestResolved)
                Else
                  .AddText("    less Accrued " & accountClose.Account.AccountType.OtherInterestDescriptionResolved)
                  If showOriginalValues Then .AddCurrency(accountClose.AccruedOtherInterestOriginal)
                  If showPostScriptValues Then .AddCurrency(accountClose.AccruedOtherInterestPostScript)
                  .AddCurrency(accountClose.AccruedOtherInterestResolved)
                End If
              End With

              BalanceActual += accountClose.AccruedOtherInterestResolved
              BalanceOriginal += accountClose.AccruedOtherInterestOriginal
              BalancePostScript += accountClose.AccruedOtherInterestPostScript
            End If

            If accountClose.UnpostedStandardTransactionsResolved <> 0 OrElse accountClose.UnpostedStandardTransactions <> 0 Then
              With .Add().Cells
                If accountClose.UnpostedStandardTransactionsResolved < 0 Then
                  .AddText("    plus Standard Transactions not yet posted")
                  If showOriginalValues Then .AddCurrency(-accountClose.UnpostedStandardTransactions)
                  If showPostScriptValues Then .AddCurrency(-accountClose.UnpostedStandardTransactions)
                  .AddCurrency(-accountClose.UnpostedStandardTransactionsResolved)
                Else
                  .AddText("    less Standard Transactions not yet posted")
                  If showOriginalValues Then .AddCurrency(accountClose.UnpostedStandardTransactions)
                  If showPostScriptValues Then .AddCurrency(accountClose.UnpostedStandardTransactions)
                  .AddCurrency(accountClose.UnpostedStandardTransactionsResolved)
                End If
              End With

              BalanceActual += accountClose.UnpostedStandardTransactionsResolved
              BalanceOriginal += accountClose.UnpostedStandardTransactions
              BalancePostScript += accountClose.UnpostedStandardTransactions
            End If

            With .Add(iseSummaryTableRowClass.Footer).Cells
              .AddText("Net Balance").CellClass = iseSummaryTableCellClass.CaptionBold
              If showOriginalValues Then .AddCurrency(-BalanceOriginal, True)
              If showPostScriptValues Then .AddCurrency(-BalancePostScript, True)
              .AddCurrency(-BalanceActual, True).CellClass = iseSummaryTableCellClass.CaptionBold
            End With

            If accountClose.FeeValueResolved <> 0 OrElse accountClose.FeeValueOriginal <> 0 Then
              With .Add().Cells
                If accountClose.FeeValueResolved < 0 Then
                  .AddText("    plus Fee")
                  If showOriginalValues Then .AddCurrency(-accountClose.FeeValueOriginal)
                  If showPostScriptValues Then .AddCurrency(-accountClose.FeeValuePostScript)
                  .AddCurrency(-accountClose.FeeValueResolved)
                Else
                  .AddText("    less Fee")
                  If showOriginalValues Then .AddCurrency(accountClose.FeeValueOriginal)
                  If showPostScriptValues Then .AddCurrency(accountClose.FeeValuePostScript)
                  .AddCurrency(accountClose.FeeValueResolved)
                End If
              End With

              BalanceActual += accountClose.FeeValueResolved
              BalanceOriginal += accountClose.FeeValueOriginal
              BalancePostScript += accountClose.FeeValuePostScript
            End If

            If accountClose.Other1ValueResolved <> 0 OrElse accountClose.Other1ValuePostScript <> 0 Then
              With .Add().Cells
                If accountClose.Other1ValueResolved < 0 Then
                  .AddText("    plus " & accountClose.Other1Description)
                  If showOriginalValues Then .AddText("")
                  If showPostScriptValues Then .AddCurrency(-accountClose.Other1ValuePostScript)
                  .AddCurrency(-accountClose.Other1ValueResolved)
                Else
                  .AddText(String.Format("    less " & accountClose.Other1Description))
                  If showOriginalValues Then .AddText("")
                  If showPostScriptValues Then .AddCurrency(-accountClose.Other1ValuePostScript)
                  .AddCurrency(accountClose.Other1ValueResolved)
                End If
              End With

              BalanceActual += accountClose.Other1ValueResolved
              BalancePostScript += accountClose.Other1ValuePostScript
            End If

            If accountClose.Other2ValueResolved <> 0 OrElse accountClose.Other2ValuePostScript <> 0 Then
              With .Add().Cells
                If accountClose.Other2ValueResolved < 0 Then
                  .AddText("    plus " & accountClose.Other2Description)
                  If showOriginalValues Then .AddText("")
                  If showPostScriptValues Then .AddCurrency(-accountClose.Other2ValuePostScript)
                  .AddCurrency(-accountClose.Other2ValueResolved)
                Else
                  .AddText("    less " & accountClose.Other2Description)
                  If showOriginalValues Then .AddText("")
                  If showPostScriptValues Then .AddCurrency(accountClose.Other2ValuePostScript)
                  .AddCurrency(accountClose.Other2ValueResolved)
                End If
              End With

              BalanceActual += accountClose.Other2ValueResolved
              BalancePostScript += accountClose.Other2ValuePostScript
            End If

            If accountClose.AdjustmentValueResolved <> 0 Then
              With .Add().Cells
                If accountClose.AdjustmentValueResolved < 0 Then
                  .AddText("    plus Adjustment")
                  If showOriginalValues Then .AddCurrency(0)
                  If showPostScriptValues Then .AddCurrency(0)
                  .AddCurrency(-accountClose.AdjustmentValueResolved)
                Else
                  .AddText("    less Adjustment")
                  If showOriginalValues Then .AddCurrency(0)
                  If showPostScriptValues Then .AddCurrency(0)
                  .AddCurrency(accountClose.AdjustmentValueResolved)
                End If
              End With

              BalanceActual += accountClose.AdjustmentValueResolved
            End If

            If accountClose.PaymentFeeValueResolved <> 0 Then
              With .Add().Cells
                If accountClose.PaymentFeeValueResolved < 0 Then
                  If BalanceActual > 0 Then
                    .AddText("    plus Payment Fee")
                  Else
                    .AddText("    plus Withdrawal Fee")
                  End If
                  If showOriginalValues Then .AddCurrency(0)
                  If showPostScriptValues Then .AddCurrency(0)
                  .AddCurrency(-accountClose.PaymentFeeValueResolved)
                Else
                  If BalanceActual > 0 Then
                    .AddText("    less Payment Fee")
                  Else
                    .AddText("    less Withdrawal Fee")
                  End If
                  If showOriginalValues Then .AddCurrency(0)
                  If showPostScriptValues Then .AddCurrency(0)
                  .AddCurrency(accountClose.PaymentFeeValueResolved)
                End If
              End With

              BalanceActual += accountClose.PaymentFeeValueResolved
            End If

            With .Add(iseSummaryTableRowClass.Footer).Cells
              .AddText("BALANCE DUE").CellClass = iseSummaryTableCellClass.CaptionBold
              If showOriginalValues Then .AddCurrency(-BalanceOriginal, True)
              If showPostScriptValues Then .AddCurrency(-BalancePostScript, True)
              .AddCurrency(-BalanceActual, True).CellClass = iseSummaryTableCellClass.CaptionBold
            End With

          Case Else
            ' Balance
            With .Add(iseSummaryTableRowClass.Footer).Cells
              .AddText("Current Balance").CellClass = iseSummaryTableCellClass.CaptionBold
              If showOriginalValues Then .AddCurrency(BalanceOriginal, True)
              If showPostScriptValues Then .AddCurrency(BalancePostScript, True)
              .AddCurrency(BalanceActual, True).CellClass = iseSummaryTableCellClass.CaptionBold
            End With

            If accountClose.FuturePayments <> 0 Then
              With .Add(iseSummaryTableRowClass.NormalBold).Cells
                .AddText("    less expected Future Payments").ForegroundColour = "Green"
                If showOriginalValues Then .AddCurrency(accountClose.FuturePayments).ForegroundColour = "Green"
                If showPostScriptValues Then .AddCurrency(accountClose.FuturePayments).ForegroundColour = "Green"
                .AddCurrency(accountClose.FuturePayments).ForegroundColour = "Green"
              End With

              BalanceActual -= accountClose.FuturePayments
              BalanceOriginal -= accountClose.FuturePayments
              BalancePostScript -= accountClose.FuturePayments
            End If

            If accountClose.Summary.TotalCredits <> 0 OrElse accountClose.Summary.TotalCreditsOriginal <> 0 Then
              With .Add().Cells
                If accountClose.Summary.TotalCredits < 0 Then
                  .AddText("    plus Credits")
                  If showOriginalValues Then .AddCurrency(-accountClose.Summary.TotalCreditsOriginal)
                  If showPostScriptValues Then .AddCurrency(-accountClose.Summary.TotalCreditsPostScript)
                  .AddCurrency(-accountClose.Summary.TotalCredits)
                Else
                  .AddText("    less Credits")
                  If showOriginalValues Then .AddCurrency(accountClose.Summary.TotalCreditsOriginal)
                  If showPostScriptValues Then .AddCurrency(accountClose.Summary.TotalCreditsPostScript)
                  .AddCurrency(accountClose.Summary.TotalCredits)
                End If
              End With

              BalanceActual -= accountClose.Summary.TotalCredits
              BalanceOriginal -= accountClose.Summary.TotalCreditsOriginal
              BalancePostScript -= accountClose.Summary.TotalCreditsPostScript
            End If

            If accountClose.AccruedInterestResolved <> 0 OrElse accountClose.AccruedInterestOriginal <> 0 Then
              With .Add().Cells
                If accountClose.AccruedInterestResolved < 0 OrElse (accountClose.AccruedInterestResolved = 0 AndAlso accountClose.AccruedInterestOriginal < 0) Then
                  .AddText("    less Accrued Interest")
                  If showOriginalValues Then .AddCurrency(-accountClose.AccruedInterestOriginal)
                  If showPostScriptValues Then .AddCurrency(-accountClose.AccruedInterestPostScript)
                  .AddCurrency(-accountClose.AccruedInterestResolved)
                Else
                  .AddText("    plus Accrued Interest")
                  If showOriginalValues Then .AddCurrency(accountClose.AccruedInterestOriginal)
                  If showPostScriptValues Then .AddCurrency(accountClose.AccruedInterestPostScript)
                  .AddCurrency(accountClose.AccruedInterestResolved)
                End If
              End With

              BalanceActual += accountClose.AccruedInterestResolved
              BalanceOriginal += accountClose.AccruedInterestOriginal
              BalancePostScript += accountClose.AccruedInterestPostScript
            End If

            If accountClose.AccruedDefaultInterestResolved <> 0 OrElse accountClose.AccruedDefaultInterestOriginal <> 0 Then
              With .Add().Cells
                If accountClose.AccruedDefaultInterestResolved < 0 Then
                  .AddText("    less Accrued Default Interest")
                  If showOriginalValues Then .AddCurrency(-accountClose.AccruedDefaultInterestOriginal)
                  If showPostScriptValues Then .AddCurrency(-accountClose.AccruedDefaultInterestPostScript)
                  .AddCurrency(-accountClose.AccruedDefaultInterestResolved)
                Else
                  .AddText("    plus Accrued Default Interest")
                  If showOriginalValues Then .AddCurrency(accountClose.AccruedDefaultInterestOriginal)
                  If showPostScriptValues Then .AddCurrency(accountClose.AccruedDefaultInterestPostScript)
                  .AddCurrency(accountClose.AccruedDefaultInterestResolved)
                End If
              End With

              BalanceActual += accountClose.AccruedDefaultInterestResolved
              BalanceOriginal += accountClose.AccruedDefaultInterestOriginal
              BalancePostScript += accountClose.AccruedDefaultInterestPostScript
            End If

            If accountClose.AccruedOtherInterestResolved <> 0 OrElse accountClose.AccruedOtherInterestOriginal <> 0 Then
              With .Add().Cells
                If accountClose.AccruedOtherInterestResolved < 0 Then
                  .AddText("    less Accrued " & accountClose.Account.AccountType.OtherInterestDescriptionResolved)
                  If showOriginalValues Then .AddCurrency(-accountClose.AccruedOtherInterestOriginal)
                  If showPostScriptValues Then .AddCurrency(-accountClose.AccruedOtherInterestPostScript)
                  .AddCurrency(-accountClose.AccruedOtherInterestResolved)
                Else
                  .AddText("    plus Accrued " & accountClose.Account.AccountType.OtherInterestDescriptionResolved)
                  If showOriginalValues Then .AddCurrency(accountClose.AccruedOtherInterestOriginal)
                  If showPostScriptValues Then .AddCurrency(accountClose.AccruedOtherInterestPostScript)
                  .AddCurrency(accountClose.AccruedOtherInterestResolved)
                End If
              End With

              BalanceActual += accountClose.AccruedOtherInterestResolved
              BalanceOriginal += accountClose.AccruedOtherInterestOriginal
              BalancePostScript += accountClose.AccruedOtherInterestPostScript
            End If

            If accountClose.UnpostedDefaultFeesResolved <> 0 OrElse accountClose.UnpostedDefaultFeesOriginal <> 0 Then
              With .Add().Cells
                If accountClose.UnpostedDefaultFeesResolved < 0 Then
                  .AddText("    less Default Fees not yet posted")
                  If showOriginalValues Then .AddCurrency(-accountClose.UnpostedDefaultFeesOriginal)
                  If showPostScriptValues Then .AddCurrency(-accountClose.UnpostedDefaultFeesPostScript)
                  .AddCurrency(-accountClose.UnpostedDefaultFeesResolved)
                Else
                  .AddText("    plus Default Fees not yet posted")
                  If showOriginalValues Then .AddCurrency(accountClose.UnpostedDefaultFeesOriginal)
                  If showPostScriptValues Then .AddCurrency(accountClose.UnpostedDefaultFeesPostScript)
                  .AddCurrency(accountClose.UnpostedDefaultFeesResolved)
                End If
              End With

              BalanceActual += accountClose.UnpostedDefaultFeesResolved
              BalanceOriginal += accountClose.UnpostedDefaultFeesOriginal
              BalancePostScript += accountClose.UnpostedDefaultFeesPostScript
            End If

            If accountClose.UnpostedOverLimitFeesResolved <> 0 OrElse accountClose.UnpostedOverLimitFeesOriginal <> 0 Then
              With .Add().Cells
                If accountClose.UnpostedOverLimitFeesResolved < 0 Then
                  .AddText("    less Over Limit Fees not yet posted")
                  If showOriginalValues Then .AddCurrency(-accountClose.UnpostedOverLimitFeesOriginal)
                  If showPostScriptValues Then .AddCurrency(-accountClose.UnpostedOverLimitFeesPostScript)
                  .AddCurrency(-accountClose.UnpostedOverLimitFeesResolved)
                Else
                  .AddText("    plus Over Limit Fees not yet posted")
                  If showOriginalValues Then .AddCurrency(accountClose.UnpostedOverLimitFeesOriginal)
                  If showPostScriptValues Then .AddCurrency(accountClose.UnpostedOverLimitFeesPostScript)
                  .AddCurrency(accountClose.UnpostedOverLimitFeesResolved)
                End If
              End With

              BalanceActual += accountClose.UnpostedOverLimitFeesResolved
              BalanceOriginal += accountClose.UnpostedOverLimitFeesOriginal
              BalancePostScript += accountClose.UnpostedOverLimitFeesPostScript
            End If

            If accountClose.UnpostedFacilityFeesResolved <> 0 OrElse accountClose.UnpostedFacilityFeesOriginal <> 0 Then
              With .Add().Cells
                If accountClose.UnpostedFacilityFeesResolved < 0 Then
                  .AddText("    less Facility Fees not yet posted")
                  If showOriginalValues Then .AddCurrency(-accountClose.UnpostedFacilityFeesOriginal)
                  If showPostScriptValues Then .AddCurrency(-accountClose.UnpostedFacilityFeesPostScript)
                  .AddCurrency(-accountClose.UnpostedFacilityFeesResolved)
                Else
                  .AddText("    plus Facility Fees not yet posted")
                  If showOriginalValues Then .AddCurrency(accountClose.UnpostedFacilityFeesOriginal)
                  If showPostScriptValues Then .AddCurrency(accountClose.UnpostedFacilityFeesPostScript)
                  .AddCurrency(accountClose.UnpostedFacilityFeesResolved)
                End If
              End With

              BalanceActual += accountClose.UnpostedFacilityFeesResolved
              BalanceOriginal += accountClose.UnpostedFacilityFeesOriginal
              BalancePostScript += accountClose.UnpostedFacilityFeesPostScript
            End If

            If accountClose.UnpostedStandardTransactionsResolved <> 0 OrElse accountClose.UnpostedStandardTransactions <> 0 Then
              With .Add().Cells
                If accountClose.UnpostedStandardTransactionsResolved < 0 Then
                  .AddText("    less Standard Transactions not yet posted")
                  If showOriginalValues Then .AddCurrency(-accountClose.UnpostedStandardTransactions)
                  If showPostScriptValues Then .AddCurrency(-accountClose.UnpostedStandardTransactions)
                  .AddCurrency(-accountClose.UnpostedStandardTransactionsResolved)
                Else
                  .AddText("    plus Standard Transactions not yet posted")
                  If showOriginalValues Then .AddCurrency(accountClose.UnpostedStandardTransactions)
                  If showPostScriptValues Then .AddCurrency(accountClose.UnpostedStandardTransactions)
                  .AddCurrency(accountClose.UnpostedStandardTransactionsResolved)
                End If
              End With

              BalanceActual += accountClose.UnpostedStandardTransactionsResolved
              BalanceOriginal += accountClose.UnpostedStandardTransactions
              BalancePostScript += accountClose.UnpostedStandardTransactions
            End If

            With .Add(iseSummaryTableRowClass.Footer).Cells
              .AddText("Net Balance").CellClass = iseSummaryTableCellClass.CaptionBold
              If showOriginalValues Then .AddCurrency(BalanceOriginal, True)
              If showPostScriptValues Then .AddCurrency(BalancePostScript, True)
              .AddCurrency(BalanceActual, True).CellClass = iseSummaryTableCellClass.CaptionBold
            End With

            If accountClose.LossValueResolved <> 0 OrElse accountClose.LossValueOriginal <> 0 Then
              With .Add().Cells
                If accountClose.LossValueResolved < 0 Then
                  .AddText("    less Loss")
                  If showOriginalValues Then .AddCurrency(-accountClose.LossValueOriginal)
                  If showPostScriptValues Then .AddCurrency(-accountClose.LossValuePostScript)
                  .AddCurrency(-accountClose.LossValueResolved)
                Else
                  .AddText("    plus Loss")
                  If showOriginalValues Then .AddCurrency(accountClose.LossValueOriginal)
                  If showPostScriptValues Then .AddCurrency(accountClose.LossValuePostScript)
                  .AddCurrency(accountClose.LossValueResolved)
                End If
              End With

              BalanceActual += accountClose.LossValueResolved
              BalanceOriginal += accountClose.LossValueOriginal
              BalancePostScript += accountClose.LossValuePostScript
            End If

            If accountClose.FeeValueResolved <> 0 OrElse accountClose.FeeValueOriginal <> 0 Then
              With .Add().Cells
                If accountClose.FeeValueResolved < 0 Then
                  .AddText("    less Fee")
                  If showOriginalValues Then .AddCurrency(-accountClose.FeeValueOriginal)
                  If showPostScriptValues Then .AddCurrency(-accountClose.FeeValuePostScript)
                  .AddCurrency(-accountClose.FeeValueResolved)
                Else
                  .AddText("    plus Fee")
                  If showOriginalValues Then .AddCurrency(accountClose.FeeValueOriginal)
                  If showPostScriptValues Then .AddCurrency(accountClose.FeeValuePostScript)
                  .AddCurrency(accountClose.FeeValueResolved)
                End If
              End With

              BalanceActual += accountClose.FeeValueResolved
              BalanceOriginal += accountClose.FeeValueOriginal
              BalancePostScript += accountClose.FeeValuePostScript
            End If

            If accountClose.Other1ValueResolved <> 0 OrElse accountClose.Other1ValuePostScript <> 0 Then
              With .Add().Cells
                If accountClose.Other1ValueResolved < 0 OrElse (accountClose.Other1ValueResolved = 0 AndAlso accountClose.Other1ValuePostScript < 0) Then
                  .AddText("    less " & accountClose.Other1Description)
                  If showOriginalValues Then .AddText("")
                  If showPostScriptValues Then .AddCurrency(-accountClose.Other1ValuePostScript)
                  .AddCurrency(-accountClose.Other1ValueResolved)
                Else
                  .AddText("    plus " & accountClose.Other1Description)
                  If showOriginalValues Then .AddText("")
                  If showPostScriptValues Then .AddCurrency(accountClose.Other1ValuePostScript)
                  .AddCurrency(accountClose.Other1ValueResolved)
                End If
              End With

              BalanceActual += accountClose.Other1ValueResolved
              BalancePostScript += accountClose.Other1ValuePostScript
            End If

            If accountClose.Other2ValueResolved <> 0 OrElse accountClose.Other2ValuePostScript <> 0 Then
              With .Add().Cells
                If accountClose.Other2ValueResolved < 0 OrElse (accountClose.Other2ValueResolved = 0 AndAlso accountClose.Other2ValuePostScript < 0) Then
                  .AddText("    less " & accountClose.Other2Description)
                  If showOriginalValues Then .AddText("")
                  If showPostScriptValues Then .AddCurrency(-accountClose.Other2ValuePostScript)
                  .AddCurrency(-accountClose.Other2ValueResolved)
                Else
                  .AddText("    plus " & accountClose.Other2Description)
                  If showOriginalValues Then .AddText("")
                  If showPostScriptValues Then .AddCurrency(accountClose.Other2ValuePostScript)
                  .AddCurrency(accountClose.Other2ValueResolved)
                End If
              End With

              BalanceActual += accountClose.Other2ValueResolved
              BalancePostScript += accountClose.Other2ValuePostScript
            End If

            If accountClose.AdjustmentValueResolved <> 0 Then
              With .Add().Cells
                If accountClose.AdjustmentValueResolved < 0 Then
                  .AddText("    less Adjustment")
                  If showOriginalValues Then .AddCurrency(0)
                  If showPostScriptValues Then .AddCurrency(0)
                  .AddCurrency(-accountClose.AdjustmentValueResolved)
                Else
                  .AddText("    plus Adjustment")
                  If showOriginalValues Then .AddCurrency(0)
                  If showPostScriptValues Then .AddCurrency(0)
                  .AddCurrency(accountClose.AdjustmentValueResolved)
                End If
              End With

              BalanceActual += accountClose.AdjustmentValueResolved
            End If

            If accountClose.ResidualValueResolved <> 0 OrElse accountClose.ResidualValueOriginal <> 0 Then
              With .Add().Cells
                .AddText("    less Residual Credit")
                If showOriginalValues Then .AddCurrency(-accountClose.ResidualValueOriginal)
                If showPostScriptValues Then .AddCurrency(-accountClose.ResidualValuePostScript)
                .AddCurrency(-accountClose.ResidualValueResolved)
              End With

              BalanceActual -= accountClose.ResidualValueResolved
              BalanceOriginal -= accountClose.ResidualValueOriginal
              BalancePostScript += accountClose.ResidualValuePostScript
            End If

            If accountClose.PaymentFeeValueResolved <> 0 Then
              With .Add().Cells
                If accountClose.PaymentFeeValueResolved < 0 Then
                  If BalanceActual > 0 Then
                    .AddText("    less Payment Fee")
                  Else
                    .AddText("    less Withdrawal Fee")
                  End If
                  If showOriginalValues Then .AddCurrency(0)
                  If showPostScriptValues Then .AddCurrency(0)
                  .AddCurrency(-accountClose.PaymentFeeValueResolved)
                Else
                  If BalanceActual > 0 Then
                    .AddText("    plus Payment Fee")
                  Else
                    .AddText("    plus Withdrawal Fee")
                  End If
                  If showOriginalValues Then .AddCurrency(0)
                  If showPostScriptValues Then .AddCurrency(0)
                  .AddCurrency(accountClose.PaymentFeeValueResolved)
                End If
              End With

              BalanceActual += accountClose.PaymentFeeValueResolved
            End If

            With .Add(iseSummaryTableRowClass.Footer).Cells
              .AddText("BALANCE DUE").CellClass = iseSummaryTableCellClass.CaptionBold
              If showOriginalValues Then .AddCurrency(BalanceOriginal, True)
              If showPostScriptValues Then .AddCurrency(BalancePostScript, True)
              .AddCurrency(BalanceActual, True).CellClass = iseSummaryTableCellClass.CaptionBold
            End With
        End Select
      End With

      ' Warnings
      If Not accountClose.CanCommitConsumerRegulationType(Message, True) Then
        Warnings &= "{{Warning|" & Message & "|True}}"
      End If
      If Len(accountClose.LossMessageError) <> 0 Then
        Warnings &= "{{warning|" & accountClose.LossMessageError & "}}"
      End If
      If accountClose.AccruedInterestSuspended OrElse accountClose.AccruedDefaultInterestSuspended OrElse accountClose.UnpostedDefaultFeesSuspended OrElse accountClose.UnpostedFacilityFeesSuspended Then
        If accountClose.AccruedInterestSuspended Then
          Warnings &= "{{warning|Interest (including Default Interest and Fees) is suspended.}}"
        Else
          If accountClose.AccruedDefaultInterestSuspended Then Warnings &= "{{warning|Default Interest is suspended.}}"
          If accountClose.UnpostedDefaultFeesSuspended Then Warnings &= "{{warning|Default Fees are suspended.}}"
          If accountClose.UnpostedFacilityFeesSuspended Then Warnings &= "{{warning|Facility Fee is suspended.}}"
        End If
      End If
      If Len(accountClose.LossMessageInformation) <> 0 Then
        Warnings &= "{{info|" & accountClose.LossMessageInformation & "}}"
      End If

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

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Close Summary Credits(Version 1.01, Last updated 20/09/2016).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="accountClose">
  '''  The Account Close object to summarise.
  ''' </param>
  ''' <param name="accountCloseSummaryItem">
  '''  The Account Close Summary Item object to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Close wizard.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function AccountClose_SummaryCredits(callerScriptInfo As ISScriptExecutionInfo,
                                                          accountClose As finAccountClose,
                                                          accountCloseSummaryItem As finAccountCloseSummaryItem,
                                                 Optional includeActions As Boolean = True,
                                                 Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

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

    ' Initialise
    SummaryTables = finBL.CreateSummaryTables()

    SummaryTable = SummaryTables.CreateSummaryTableInformation("", "Main")
    With SummaryTable
      If accountCloseSummaryItem.IsTotalItem Then
        Warnings &= "{{info|Total Item.}}"
      Else
        ' General
        .AddRowCaptionCodeDescription("Element:", accountCloseSummaryItem.ElementId, finBL.Elements)
        If accountCloseSummaryItem.Count = 1 Then
          .AddRowCaptionDate("Date:", accountCloseSummaryItem.FirstTransactionDate)
        End If

        Select Case accountClose.Account.AccountClass
          Case isefinAccountClass.Deposit
            .AddRowCaptionCurrency("Value:", -accountCloseSummaryItem.Value, True)
            If accountCloseSummaryItem.CreditAllowEntry Then
              If accountCloseSummaryItem.CreditElementPk = 0 Then
                .AddRowCaptionCodeDescription("Credit Element:", accountCloseSummaryItem.ElementId, finBL.Elements)
              Else
                .AddRowCaptionCodeDescription("Credit Element:", accountCloseSummaryItem.CreditElementId, finBL.Elements)
              End If
              .AddRowCaptionText("Method:", accountCloseSummaryItem.CreditCalculationDescription)
              .AddRowCaptionText("Method Notes:", accountCloseSummaryItem.CreditCalculationNotes)
              If accountCloseSummaryItem.Credit <> accountCloseSummaryItem.CreditOriginal Then
                .AddRowCaptionCurrency("Original Credit:", -accountCloseSummaryItem.CreditOriginal)
              End If
              .AddRowCaptionText("Credit Notes:", accountCloseSummaryItem.CreditNotes)
              .AddRowCaptionCurrency("Credit:", -accountCloseSummaryItem.Credit, True)
              .AddRowCaptionText("Trans Notes:", accountCloseSummaryItem.TransactionNotes)
            End If

          Case Else
            .AddRowCaptionCurrency("Value:", accountCloseSummaryItem.Value, True)
            If accountCloseSummaryItem.CreditAllowEntry Then
              If accountCloseSummaryItem.CreditElementPk = 0 Then
                .AddRowCaptionCodeDescription("Credit Element:", accountCloseSummaryItem.ElementId, finBL.Elements)
              Else
                .AddRowCaptionCodeDescription("Credit Element:", accountCloseSummaryItem.CreditElementId, finBL.Elements)
              End If
              .AddRowCaptionText("Method:", accountCloseSummaryItem.CreditCalculationDescription)
              .AddRowCaptionText("Method Notes:", accountCloseSummaryItem.CreditCalculationNotes)
              If accountCloseSummaryItem.Credit <> accountCloseSummaryItem.CreditOriginal Then
                .AddRowCaptionCurrency("Original Credit:", accountCloseSummaryItem.CreditOriginal)
              End If
              .AddRowCaptionText("Credit Notes:", accountCloseSummaryItem.CreditNotes)
              .AddRowCaptionCurrency("Credit:", accountCloseSummaryItem.Credit, True)
              .AddRowCaptionText("Trans Notes:", accountCloseSummaryItem.TransactionNotes)
            End If
        End Select
      End If

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

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Close Log Summary (Version 1.02, Last updated 10/05/2021).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="accountLog">
  '''  The Account Close Log to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Close Log form.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''    <item><code>Close Notes</code><description>Close notes.</description></item>
  '''    <item><code>Transaction Notes</code><description>Transaction notes.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function AccountCloseLog_Summary(callerScriptInfo As ISScriptExecutionInfo,
                                                      accountLog As finAccountLog,
                                             Optional includeActions As Boolean = True,
                                             Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim AccountClose As finAccountClose
    Dim SummaryTable As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise
    SummaryTables = finBL.CreateSummaryTables()

    SummaryTable = SummaryTables.CreateSummaryTableInformation("", "StatusSummary")
    With SummaryTable
      ' Get Account Close
      If accountLog.GetAccountCloseObjectFromExtendedData(AccountClose) Then
        Select Case AccountClose.CloseMethod
          Case isefinAccountCloseMethod.BadDebtWriteOff
            .AddRowCaptionText("Method:", "Written Off (as a Bad Debt)")
          Case isefinAccountCloseMethod.Cancelled
            .AddRowCaptionText("Method:", "Cancelled")
          Case isefinAccountCloseMethod.EarlyRedemption
            .AddRowCaptionText("Method:", "Early Redemption")
          Case isefinAccountCloseMethod.EarlySettlement
            .AddRowCaptionText("Method:", "Early Settlement")
          Case isefinAccountCloseMethod.Refinanced
            If Len(AccountClose.RefinancedAccountId) = 0 Then
              .AddRowCaptionText("Method:", "Refinanced")
            Else
              With .Rows.AddCaptionText("Refinanced to ", AccountClose.RefinancedAccountId)
                .Cells(1).HyperlinkSetFormShow("Accounts", AccountClose.RefinancedAccountId)
              End With
            End If
          Case isefinAccountCloseMethod.WrittenOff
            .AddRowCaptionText("Method:", "Written Off")
          Case isefinAccountCloseMethod.Closed
            .AddRowCaptionText("Method:", "Closed")
          Case Else
            .AddRowCaptionText("Method:", "")
        End Select
        .AddRowCaptionDate("Closed:", AccountClose.CloseDate)
        If AccountClose.ClosePending Then
          .AddRowCaptionText("Status:", "Closed Pending")
          .AddRowCaptionDate("Review:", AccountClose.ClosePendingReviewDate)
        End If
        .AddRowCaptionText("Notes:", AccountClose.CloseNote)

        ' Transaction
        .Rows.AddSectionHeading2("Transaction")
        Select Case AccountClose.Account.AccountClass
          Case isefinAccountClass.Deposit
            .AddRowCaptionCurrency("Value:", -AccountClose.PaymentValueResolved, True)
          Case Else
            .AddRowCaptionCurrency("Value:", AccountClose.PaymentValueResolved, True)
        End Select
        If AccountClose.TransactionTypePk <> 0 Then
          .AddRowCaptionCodeDescription("Transaction Type:", AccountClose.TransactionTypeId, AccountClose.TransactionTypeDescription)
          .AddRowCaptionText("Reference:", AccountClose.TransactionReference)
          .AddRowCaptionText("Notes:", AccountClose.TransactionNotes)
        End If
        .AddRowCaptionCodeDescription("Pay Method:", AccountClose.BankingDetails.PaymentMethodId, AccountClose.BankingDetails.PaymentMethodDescription)

        ' Warnings
        If AccountClose.IsQuotation Then
          Warnings &= "{{info|DRAFT}}"
        End If
        If AccountClose.PrintSummary Then
          Warnings &= "{{info|A summary was printed.}}"
        End If
        .TextAfter = Warnings

        ' Actions
        If includeActions Then
          With .Actions
            If Not accountLog.IsNew AndAlso AccountClose.SupportsPrintSummary Then
              .AddApplicationShortcutUrl("Print", "Print Closing Summary", "Document?id=" & finBL.UrlEncode(AccountClose.Account.AccountType.ClosingSummaryDocumentId) & "&logPk=" & accountLog.Pk).ShowInWebInterfaces = True
            End If
          End With
        End If
      Else
        .TextBefore = "{{error|" & finBL.Error.Message(True) & "}}"
      End If
    End With
    SummaryTables.Add("Main", SummaryTable)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Interest Payout Summary (Version 1.02, Last updated 13/05/2021).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="accountInterestPayout">
  '''  The Account Interest Payout Item to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used on the Process Interest Payouts wizard.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''    <item><code>Payment</code><description>Payment details.</description></item>
  '''    <item><code>CombinedPayment</code><description>Combined Payment details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function AccountInterestPayout_Summary(callerScriptInfo As ISScriptExecutionInfo,
                                                            accountInterestPayout As finAccountInterestPayout,
                                                   Optional includeActions As Boolean = True,
                                                   Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim CombinedAccountInterestPayout As finAccountInterestPayout
    Dim CombinedCount As Integer
    Dim CombinedValue As Decimal
    Dim SummaryTableCombinedPayment As ISSummaryTable
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTablePayment As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTablePayment = finBL.CreateSummaryTable()
    SummaryTableCombinedPayment = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""

      ' Columns
      .Columns.AddText(16).NoBreakChars = 16
      .Columns.AddText()

      ' Clear Warnings
      Warnings = ""

      With .Rows
        ' General
        With .AddCaptionText("Account:", accountInterestPayout.AccountId)
          .Cells(1).HyperlinkSetFormShow("Accounts", accountInterestPayout.AccountId)
        End With
        .AddCaptionText("Name:", accountInterestPayout.AccountName)
      End With

      ' Warnings
      .TextAfter = Warnings
    End With

    ' Payment
    With SummaryTablePayment
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = "Payment"

      ' Columns
      .Columns.AddText(16).NoBreakChars = 16
      .Columns.AddText()

      ' Clear Warnings
      Warnings = ""

      With .Rows
        If accountInterestPayout.BalanceInterest <> accountInterestPayout.Payout Then
          .AddCaptionCurrency("Interest Balance:", accountInterestPayout.BalanceInterest, True)
        End If
        .AddCaptionCurrency("Payout:", accountInterestPayout.Payout, True)
      End With

      ' Warning Messages
      With accountInterestPayout
        ' Invalid?
        If Len(.InvalidMessage) <> 0 Then
          If .Processed Then
            Warnings &= "{{info|" & .InvalidMessage & "}}"
          ElseIf .IsExportable Then
            Warnings &= "{{warning|" & .InvalidMessage & "}}"
          Else
            Warnings &= "{{warning|" & .InvalidMessage & "}}"
            Warnings &= "{{warning|CANNOT EXPORT PAYMENT.|True}}"
          End If
        End If
      End With

      ' Warnings
      .TextAfter = Warnings
    End With

    ' Combined Payment
    With SummaryTableCombinedPayment
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = "Combined Payment"

      ' Columns
      .Columns.AddText(16).NoBreakChars = 16
      .Columns.AddText()

      ' Clear Warnings
      Warnings = ""

      If accountInterestPayout.IsExportable AndAlso accountInterestPayout.Include AndAlso accountInterestPayout.Combine Then
        ' Get Values
        CombinedCount = 0
        CombinedValue = 0
        For Each CombinedAccountInterestPayout In accountInterestPayout.Parent
          ' Must be including and combining
          If CombinedAccountInterestPayout.IsExportable AndAlso CombinedAccountInterestPayout.Include AndAlso CombinedAccountInterestPayout.Combine Then
            ' Must be for the same Client and Banking Details
            If accountInterestPayout.ClientPk = CombinedAccountInterestPayout.ClientPk AndAlso accountInterestPayout.BankingDetails.CompareTo(CombinedAccountInterestPayout.BankingDetails) Then
              CombinedCount += 1
              CombinedValue += CombinedAccountInterestPayout.Payout
            End If
          End If
        Next

        With .Rows
          ' Combined Payment
          If CombinedCount > 1 Then
            .AddCaptionCodeDescriptionWithFormShow("Main Client:", accountInterestPayout.ClientId, accountInterestPayout.ClientName, "Clients")
            .AddCaptionCurrency("Value:", CombinedValue, True)

            ' Warning Messages
            Warnings &= "{{info|" & CStr(CombinedCount) & " payments combined.}}"
          End If
        End With
      End If

      ' Warnings
      .TextAfter = Warnings
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)
    If SummaryTablePayment.HasData Then SummaryTables.Add("Payment", SummaryTablePayment)
    If SummaryTableCombinedPayment.HasData Then SummaryTables.Add("CombinedPayment", SummaryTableCombinedPayment)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Payment Summary (Version 1.05, Last updated 10/05/2021).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="accountPayment">
  '''  The Account Payment object to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Payment wizard.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''    <item><code>Investment</code><description>Deposit Account Investment details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function AccountPayment_Summary(callerScriptInfo As ISScriptExecutionInfo,
                                                     accountPayment As finAccountPayment,
                                            Optional includeActions As Boolean = True,
                                            Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim Account As finAccount
    Dim Balance As Decimal
    Dim BalanceOverdue As Decimal
    Dim BalanceOverdueContractual As Decimal
    Dim DirectDebitValue As Decimal
    Dim InvestmentPending As Decimal
    Dim InvestmentReceived As Decimal
    Dim InvestmentValue As Decimal
    Dim IsBalanceOverdue As Boolean
    Dim IsBalanceOverdueContractual As Boolean
    Dim ShowOverdue As Boolean
    Dim ShowOverdueContractual As Boolean
    Dim SummaryTable As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Information
    Account = accountPayment.Account
    With Account
      ' Get Balance
      .GetBalance(Balance)

      ' Get Direct Debits Awaiting Processing
      If .SupportsPayments Then
        .GetDirectDebitsAwaitingProcessing(0, DirectDebitValue, #12/31/9999#)
      Else
        DirectDebitValue = 0
      End If

      ' Overdue Details
      If .SupportsOverdue Then
        ShowOverdue = .AccountType.ShowOverdue
        ShowOverdueContractual = .AccountType.ShowContractualOverdue

        If ShowOverdue Then .GetBalanceOverdue(BalanceOverdue, accountPayment.PaymentDate)
        If ShowOverdueContractual Then .GetBalanceOverdueContractual(BalanceOverdueContractual, accountPayment.PaymentDate)

        ' Set Flags
        IsBalanceOverdue = (BalanceOverdue > 0)
        IsBalanceOverdueContractual = (BalanceOverdueContractual > 0)
      Else
        ShowOverdue = False
        ShowOverdueContractual = False
        IsBalanceOverdue = False
        IsBalanceOverdueContractual = False
      End If

      ' Investment Details
      If accountPayment.TransactionType IsNot Nothing AndAlso accountPayment.TransactionType.ElementType = isefinElementType.Investment Then
        .GetInvestmentDetails(InvestmentValue, InvestmentReceived, InvestmentPending)

        ' Deduct this Investment
        InvestmentPending -= accountPayment.PaymentValue
      End If
    End With

    ' Main
    SummaryTable = SummaryTables.CreateSummaryTableTabular("", "Main")
    With SummaryTable
      ' Columns
      With .Columns
        .AddText(" ", 30).NoBreakChars = 30
        .AddCurrency("Balance", 20)
        If ShowOverdue Then .AddCurrency("Overdue", 20)
        If ShowOverdueContractual Then .AddCurrency("Contractual", 20)
      End With

      ' Alert Messages
      Account.GetAlertMessages(.TextBefore)

      ' Rows
      With .Rows
        Select Case Account.AccountClass
          Case isefinAccountClass.Deposit
            ' Balance
            With .Add(iseSummaryTableRowClass.FooterBold).Cells
              .AddCaption("Current Balance")
              .AddCurrency(-Balance)
            End With

            ' Plus Investment
            With .Add().Cells
              .AddCaption("plus Investment")
              .AddCurrency(accountPayment.PaymentValue)
            End With

            ' Adjust Balances
            Balance -= accountPayment.PaymentValue

            ' Plus Payment Fee
            If accountPayment.PaymentFeeValueResolved <> 0 Then
              If accountPayment.BankingDetails.PaymentMethod.IsDirectDebit Then
                ' Direct Debits will be paid immediately, so won't increase Balance or Overdue
              Else
                With .Add().Cells
                  .AddCaption("less Payment Fee")
                  .AddCurrency(accountPayment.PaymentFeeValueResolved)
                End With

                ' Adjust Balances
                Balance += accountPayment.PaymentFeeValueResolved
              End If
            End If

            ' Balance After Investment
            With .Add(iseSummaryTableRowClass.FooterBold).Cells
              .AddCaption("New Balance")
              .AddCurrency(-Balance, True)
            End With

          Case Else
            ' Balance
            With .Add(iseSummaryTableRowClass.FooterBold).Cells
              .AddCaption("Current Balance")
              .AddCurrency(Balance)
              If ShowOverdue Then .AddCurrency(BalanceOverdue)
              If ShowOverdueContractual Then .AddCurrency(BalanceOverdueContractual)
            End With

            ' Less Payment
            With .Add().Cells
              .AddCaption("less Payment")
              .AddCurrency(accountPayment.PaymentValue)
              If ShowOverdue Then
                If IsBalanceOverdue Then
                  .AddCurrency(accountPayment.PaymentValue)
                Else
                  .AddCurrency(0)
                End If
              End If
              If ShowOverdueContractual Then
                If IsBalanceOverdueContractual Then
                  .AddCurrency(accountPayment.PaymentValue)
                Else
                  .AddCurrency(0)
                End If
              End If
            End With

            ' Adjust Balances
            Balance -= accountPayment.PaymentValue
            If IsBalanceOverdue Then BalanceOverdue -= accountPayment.PaymentValue
            If IsBalanceOverdueContractual Then BalanceOverdueContractual -= accountPayment.PaymentValue

            ' Plus Payment Fee
            If accountPayment.PaymentFeeValueResolved <> 0 Then
              If accountPayment.BankingDetails.PaymentMethod.IsDirectDebit Then
                ' Direct Debits will be paid immediately, so won't increase Balance or Overdue
              Else
                With .Add().Cells
                  .AddCaption("plus Payment Fee")
                  .AddCurrency(accountPayment.PaymentFeeValueResolved)
                  If ShowOverdue Then
                    If IsBalanceOverdue AndAlso finBL.Elements.ItemByPk(accountPayment.PaymentFeeElementPk).DueImmediately Then
                      .AddCurrency(accountPayment.PaymentFeeValueResolved)
                      BalanceOverdue += accountPayment.PaymentFeeValueResolved
                    Else
                      .AddCurrency(0)
                    End If
                  End If
                  If ShowOverdueContractual AndAlso finBL.Elements.ItemByPk(accountPayment.PaymentFeeElementPk).DueImmediately Then
                    If IsBalanceOverdueContractual Then
                      .AddCurrency(accountPayment.PaymentFeeValueResolved)
                      BalanceOverdueContractual += accountPayment.PaymentFeeValueResolved
                    Else
                      .AddCurrency(0)
                    End If
                  End If
                End With

                ' Adjust Balances
                Balance += accountPayment.PaymentFeeValueResolved
              End If
            End If

            ' Balance After Payment
            With .Add(iseSummaryTableRowClass.FooterBold).Cells
              .AddCaption("New Balance")
              .AddCurrency(Balance, True)
              If ShowOverdue Then .AddCurrency(BalanceOverdue, True)
              If ShowOverdueContractual Then .AddCurrency(BalanceOverdueContractual, True)
            End With
        End Select
      End With

      ' Warnings
      Warnings = ""
      If ShowOverdue AndAlso (Not IsBalanceOverdue) Then
        Warnings &= "{{info|Account is NOT currently Overdue.}}"
      End If
      If ShowOverdueContractual AndAlso (Not IsBalanceOverdueContractual) Then
        Warnings &= "{{info|Account is NOT currently Contractually Overdue.}}"
      End If
      If DirectDebitValue <> 0 Then
        Warnings &= "{{info|Account has Direct Debits of " & finBL.FormatCurrency(DirectDebitValue, True) & " awaiting processing.}}"
      End If
      If accountPayment.PaymentFeeCharge AndAlso accountPayment.PaymentFeeValue <> accountPayment.PaymentFeeValueResolved Then
        Warnings &= "{{warning|" & String.Format("Payment Fee has been reduced from {0} to {1}.", finBL.FormatCurrency(accountPayment.PaymentFeeValue, True), finBL.FormatCurrency(accountPayment.PaymentFeeValueResolved, True)) & "}}"
      End If
      .TextAfter = Warnings
    End With
    SummaryTables.Add("Main", SummaryTable)

    ' Investment
    If Account.AccountClass = isefinAccountClass.Deposit AndAlso accountPayment.TransactionType IsNot Nothing AndAlso accountPayment.TransactionType.ElementType = isefinElementType.Investment Then
      SummaryTable = SummaryTables.CreateSummaryTableTabular("Investment Details", "Investment")
      With SummaryTable
        ' Columns
        With .Columns
          .AddText(30).NoBreakChars = 30
          .AddCurrency(20)
        End With

        ' Rows
        With .Rows
          .AddCaptionCurrency("Investment:", InvestmentValue, True, iseSummaryTableRowClass.FooterBold)
          .AddCaptionCurrency("less Received:", InvestmentReceived,,, iseSummaryTableCellClass.Normal)
          .AddCaptionCurrency("less Investment:", accountPayment.PaymentValue,,, iseSummaryTableCellClass.Normal)
          .AddCaptionCurrency("Balance Remaining:", InvestmentPending, True, iseSummaryTableRowClass.FooterBold, If(InvestmentPending = 0, iseSummaryTableCellClass.NormalBold, iseSummaryTableCellClass.WarningBold))
        End With

        ' Warnings
        Warnings = ""
        If Account.CreationMethod = isefinAccountCreationMethod.Reinvested Then
          Warnings &= "{{info|Deposit was created from a Reinvestment.}}"
        End If
        If InvestmentPending > 0 Then
          Warnings &= "{{warning|Investment is underpaid.|True}}"
        ElseIf InvestmentPending < 0 Then
          Warnings &= "{{warning|Investment is overpaid.|True}}"
        End If
        .TextAfter = Warnings
      End With
      SummaryTables.Add("Investment", SummaryTable)
    End If

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Payment Arrangement Summary.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="accountPayArrangement">
  '''  The Account Payment Arrangement object to summarise.
  ''' </param>
  ''' <param name="shortSummary">
  '''  Indicate whether this is a 'Short Summary' which excludes details such as Status and Created/ Updated information.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used on the Accounts form, Payments page, Payment Arrangements tab.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function AccountPaymentArrangement_Summary(callerScriptInfo As ISScriptExecutionInfo,
                                                                accountPayArrangement As finAccountPayArrangement,
                                                       Optional shortSummary As Boolean = False,
                                                       Optional includeActions As Boolean = True,
                                                       Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' AccountPaymentArrangement_Summary
    '
    ' Version 1.05, Last updated 08/02/2024
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.02  04/02/2021  ISS                  
    '    1.03  23/08/2021  ISS      J027251   Added additional information for NZ CCCFA
    '    1.04  02/09/2021  ISS      J027267   Added 'Rate of Charge' for NZ HCCCC
    '    1.05  08/02/2024  ISS      J032792   Added Regular missed Payment until date
    ' #################################################################

    Dim Account As finAccount
    Dim AccountCalcOriginal As finAccountCalc
    Dim AccountCalcScheduleItem As finAccountCalcScheduleItem
    Dim AccountPayArrangementPayment As finAccountPayArrangementPayment
    Dim OriginalTotalCostOfBorrowing As Decimal
    Dim OriginalTotalFees As Decimal
    Dim OriginalTotalInterest As Decimal
    Dim OriginalTotalPayments As Decimal
    Dim PromisesCount As Integer
    Dim PromisesCountPending As Integer
    Dim PromisesCountRemaining As Integer
    Dim PromisesFinalDate As Date
    Dim PromisesLastStatus As isefinTransactionPromiseStatus
    Dim strTemp As String
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Get Constants

    ' Initialise
    Account = accountPayArrangement.Account
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      .Columns.AddText(16).NoBreakChars = 16
      .Columns.AddText()

      With .Rows
        ' General
        .AddCaptionDate("Dated:", accountPayArrangement.ArrangementDate)
        If shortSummary Then
          ' Short Summary is probably coming from somewhere where we already know the Status, e.g., when displaying the Current Payment Arrangement details
        Else
          If accountPayArrangement.IsCurrent Then
            .AddCaptionWiki("Status:", "**++Current++**")
          Else
            .AddCaptionWiki("Status:", "**!!Not Current!!**")
          End If
        End If
        If Not shortSummary Then
          .AddCaptionText("Source:", accountPayArrangement.SourceText)
        End If
        If Len(accountPayArrangement.ArrangementType) <> 0 Then
          .AddCaptionText("Type:", accountPayArrangement.ArrangementType)
        End If
        .AddCaptionText("By:", accountPayArrangement.ArrangementByWhom)
        If Len(accountPayArrangement.ArrangementReason) <> 0 Then
          .AddCaptionText("Reason:", accountPayArrangement.ArrangementReason)
        End If
        If Len(accountPayArrangement.UserStatus) <> 0 Then
          .AddCaptionText("User Status:", accountPayArrangement.UserStatus)
        End If
        Select Case Account.AccountClass
          Case isefinAccountClass.LoanRC
            If accountPayArrangement.UseAltPaySchedule Then
              strTemp = String.Format("{0} {1}", finBL.FormatCurrency(accountPayArrangement.PaymentRegular, True), accountPayArrangement.PaymentCycleDescription)
            Else
              strTemp = "Overriding payments only"
            End If

          Case Else
            strTemp = String.Format("{0} {1}", finBL.FormatCurrency(accountPayArrangement.PaymentRegular, True), accountPayArrangement.PaymentCycleDescription)
        End Select
        .AddCaptionText("Payments:", strTemp)

        If accountPayArrangement.PaymentFirstDate <> Nothing Then
          .AddCaptionDate("First Payment Due:", accountPayArrangement.PaymentFirstDate)
        End If

        ' Variations
        Select Case Account.AccountClass
          Case isefinAccountClass.LoanFR, isefinAccountClass.LoanFT
            If accountPayArrangement.PaymentRegularMissUntilDate <> Nothing Then
              .AddCaptionDate("Regular missed until:", accountPayArrangement.PaymentRegularMissUntilDate, "Regular Payments will still add to the Overdue balance")
            End If

            If accountPayArrangement.PaymentFinalDate = Nothing Then
              ' Payments insufficient
              .AddCaptionDate("Final Payment:", Nothing)
              .AddCaptionWiki("Total Payments:", "**!!Payments are insufficient to pay off the Loan!!**")
            Else
              ' Get Original Totals
              Account.CalculationVersions.GetOpeningCalculation(0, AccountCalcOriginal)
              OriginalTotalCostOfBorrowing = 0
              OriginalTotalFees = 0
              OriginalTotalInterest = 0
              OriginalTotalPayments = 0
              For Each AccountCalcScheduleItem In AccountCalcOriginal.Schedule
                Select Case AccountCalcScheduleItem.ElementType
                  Case isefinElementType.Cost, isefinElementType.Journal
                    OriginalTotalCostOfBorrowing += AccountCalcScheduleItem.Value
                  Case isefinElementType.Fee
                    OriginalTotalCostOfBorrowing += AccountCalcScheduleItem.Value
                    OriginalTotalFees += AccountCalcScheduleItem.Value
                  Case isefinElementType.Interest, isefinElementType.InterestDefault
                    OriginalTotalCostOfBorrowing += AccountCalcScheduleItem.Value
                    OriginalTotalInterest += AccountCalcScheduleItem.Value
                  Case isefinElementType.PaymentReceived
                    OriginalTotalPayments -= AccountCalcScheduleItem.Value
                End Select
              Next

              ' Final Payment Date
              If AccountCalcOriginal.PaymentFinalDate = Nothing OrElse accountPayArrangement.PaymentFinalDate = AccountCalcOriginal.PaymentFinalDate Then
                .AddCaptionDate("Final Payment:", accountPayArrangement.PaymentFinalDate)
              ElseIf AccountCalcOriginal.PaymentFinalDate > accountPayArrangement.PaymentFinalDate Then
                .AddCaptionDate("Final Payment:", accountPayArrangement.PaymentFinalDate, String.Format("++Original Contract {0} (decrease of {1} days)++", finBL.FormatDateLong(AccountCalcOriginal.PaymentFinalDate), DateDiff(DateInterval.Day, accountPayArrangement.PaymentFinalDate, AccountCalcOriginal.PaymentFinalDate)))
              Else
                .AddCaptionDate("Final Payment:", accountPayArrangement.PaymentFinalDate, String.Format("!!Original Contract {0} (increase of {1} days)!!", finBL.FormatDateLong(AccountCalcOriginal.PaymentFinalDate), DateDiff(DateInterval.Day, AccountCalcOriginal.PaymentFinalDate, accountPayArrangement.PaymentFinalDate)))
              End If

              ' Total Payments
              If accountPayArrangement.TotalPayments <> 0 Then
                If OriginalTotalPayments = 0 OrElse accountPayArrangement.TotalPayments = OriginalTotalPayments Then
                  .AddCaptionCurrency("Total Payments:", accountPayArrangement.TotalPayments, True)
                ElseIf OriginalTotalPayments > accountPayArrangement.TotalPayments Then
                  .AddCaptionCurrency("Total Payments:", accountPayArrangement.TotalPayments, String.Format("++Original Contract {0} (decrease of {1})++", finBL.FormatCurrency(OriginalTotalPayments, True), finBL.FormatCurrency(OriginalTotalPayments - accountPayArrangement.TotalPayments, True)), True)
                Else
                  .AddCaptionCurrency("Total Payments:", accountPayArrangement.TotalPayments, String.Format("!!Original Contract {0} (increase of {1})!!", finBL.FormatCurrency(OriginalTotalPayments, True), finBL.FormatCurrency(accountPayArrangement.TotalPayments - OriginalTotalPayments, True)), True)
                End If
                If accountPayArrangement.TotalPaymentsToDate <> 0 Then
                  If OriginalTotalPayments = 0 OrElse accountPayArrangement.TotalPayments = OriginalTotalPayments Then
                    .AddCaptionCurrency("Remaining Payments:", accountPayArrangement.TotalPayments - accountPayArrangement.TotalPaymentsToDate, True)
                  ElseIf OriginalTotalPayments > accountPayArrangement.TotalPayments Then
                    .AddCaptionCurrency("Remaining Payments:", accountPayArrangement.TotalPayments - accountPayArrangement.TotalPaymentsToDate, String.Format("++Original Contract {0}++", finBL.FormatCurrency(OriginalTotalPayments - accountPayArrangement.TotalPaymentsToDate, True)), True)
                  Else
                    .AddCaptionCurrency("Remaining Payments:", accountPayArrangement.TotalPayments - accountPayArrangement.TotalPaymentsToDate, String.Format("!!Original Contract {0}!!", finBL.FormatCurrency(OriginalTotalPayments - accountPayArrangement.TotalPaymentsToDate, True)), True)
                  End If
                End If
              End If

              ' Total Interest, Fees and Cost of Borrowing
              If accountPayArrangement.TotalInterest <> 0 Then
                If OriginalTotalInterest = 0 OrElse accountPayArrangement.TotalInterest = OriginalTotalInterest Then
                  .AddCaptionCurrency("Total Interest:", accountPayArrangement.TotalInterest, True)
                ElseIf OriginalTotalInterest > accountPayArrangement.TotalInterest Then
                  .AddCaptionCurrency("Total Interest:", accountPayArrangement.TotalInterest, String.Format("++Original Contract {0} (decrease of {1})++", finBL.FormatCurrency(OriginalTotalInterest, True), finBL.FormatCurrency(OriginalTotalInterest - accountPayArrangement.TotalInterest, True)), True)
                Else
                  .AddCaptionCurrency("Total Interest:", accountPayArrangement.TotalInterest, String.Format("!!Original Contract {0} (increase of {1})!!", finBL.FormatCurrency(OriginalTotalInterest, True), finBL.FormatCurrency(accountPayArrangement.TotalInterest - OriginalTotalInterest, True)), True)
                End If
              End If
              If accountPayArrangement.TotalFees <> 0 Then
                If OriginalTotalFees = 0 OrElse accountPayArrangement.TotalFees = OriginalTotalFees Then
                  .AddCaptionCurrency("Total Fees:", accountPayArrangement.TotalFees, True)
                ElseIf OriginalTotalFees > accountPayArrangement.TotalFees Then
                  .AddCaptionCurrency("Total Fees:", accountPayArrangement.TotalFees, String.Format("++Original Contract {0} (decrease of {1})++", finBL.FormatCurrency(OriginalTotalFees, True), finBL.FormatCurrency(OriginalTotalFees - accountPayArrangement.TotalFees, True)), True)
                Else
                  .AddCaptionCurrency("Total Fees:", accountPayArrangement.TotalFees, String.Format("!!Original Contract {0} (increase of {1})!!", finBL.FormatCurrency(OriginalTotalFees, True), finBL.FormatCurrency(accountPayArrangement.TotalFees - OriginalTotalFees, True)), True)
                End If
              End If
              If accountPayArrangement.TotalCostOfBorrowing <> 0 Then
                If OriginalTotalCostOfBorrowing = 0 OrElse accountPayArrangement.TotalCostOfBorrowing = OriginalTotalCostOfBorrowing Then
                  .AddCaptionCurrency("Total Cost of Borrowing:", accountPayArrangement.TotalCostOfBorrowing, True)
                ElseIf OriginalTotalCostOfBorrowing > accountPayArrangement.TotalCostOfBorrowing Then
                  .AddCaptionCurrency("Total Cost of Borrowing:", accountPayArrangement.TotalCostOfBorrowing, String.Format("++Original Contract {0} (decrease of {1})++", finBL.FormatCurrency(OriginalTotalCostOfBorrowing, True), finBL.FormatCurrency(OriginalTotalCostOfBorrowing - accountPayArrangement.TotalCostOfBorrowing, True)), True)
                Else
                  .AddCaptionCurrency("Total Cost of Borrowing:", accountPayArrangement.TotalCostOfBorrowing, String.Format("!!Original Contract {0} (increase of {1})!!", finBL.FormatCurrency(OriginalTotalCostOfBorrowing, True), finBL.FormatCurrency(accountPayArrangement.TotalCostOfBorrowing - OriginalTotalCostOfBorrowing, True)), True)
                End If
              End If

              ' Comparison Rate
              Select Case accountPayArrangement.Account.ConsumerRegulationType
                Case isefinAccountConsumerRegulationType.NZ_HighCostConsumerCreditContract
                  If accountPayArrangement.ComparisonRateType = isefinAccountCalcComparisonRateType.NewZealandRateOfCharge Then
                    If Len(accountPayArrangement.ComparisonRateError) = 0 Then
                      If accountPayArrangement.ComparisonRate < 0 Then
                        .AddCaptionWiki("Rate of Charge:", "**!!Error!!**")
                      ElseIf accountPayArrangement.ComparisonRate > accountPayArrangement.ComparisonRateMaximum Then
                        .AddCaptionPercentage("Rate of Charge:", accountPayArrangement.ComparisonRate / 100, 8, True, String.Format("**!!Exceeds Maximum {0}!!**", finBL.FormatPercentage(accountPayArrangement.ComparisonRateMaximum / 100, 4)))
                      Else
                        .AddCaptionPercentage("Rate of Charge:", accountPayArrangement.ComparisonRate / 100, 8, True)
                      End If
                    Else
                      .AddCaptionWiki("Rate of Charge:", "**!!accountPayArrangement.ComparisonRateError!!**")
                    End If
                  End If
              End Select
            End If
        End Select

        ' Promise
        If accountPayArrangement.Payments.HasPromises Then
          ' Initialise
          PromisesCount = 0
          PromisesCountPending = 0
          PromisesCountRemaining = 0
          PromisesLastStatus = isefinTransactionPromiseStatus.NotApplicable
          PromisesFinalDate = Nothing

          For Each AccountPayArrangementPayment In accountPayArrangement.Payments
            If AccountPayArrangementPayment.PaymentType = isefinAccountCalcPaymentType.Promise Then
              PromisesCount += 1
              PromisesFinalDate = AccountPayArrangementPayment.Date

              If AccountPayArrangementPayment.Processed Then
                Select Case AccountPayArrangementPayment.PromiseStatus
                  Case isefinTransactionPromiseStatus.Pending
                    PromisesCountPending += 1
                  Case isefinTransactionPromiseStatus.Pass, isefinTransactionPromiseStatus.Fail, isefinTransactionPromiseStatus.Broken, isefinTransactionPromiseStatus.Cancelled
                    PromisesLastStatus = AccountPayArrangementPayment.PromiseStatus
                End Select
              Else
                PromisesCountRemaining += 1
              End If
            End If
          Next

          If PromisesCountRemaining = 0 Then
            strTemp = String.Format("Promise complete. Final Promise was on {0}.", finBL.FormatDateLong(PromisesFinalDate))
          Else
            strTemp = String.Format("Promises remaining. Final Promise due on {0}.", finBL.FormatDateLong(PromisesFinalDate))
          End If
          .AddCaptionText("Promises:", strTemp)

          If PromisesCountRemaining = 0 AndAlso PromisesCountPending = 0 Then
            ' Completed and nothing pending
            Select Case PromisesLastStatus
              Case isefinTransactionPromiseStatus.Pass
                'Warnings &= "{{info|Promise complete.}}"
              Case isefinTransactionPromiseStatus.Fail
                Warnings &= "{{warning|Promise FAILED.}}"
              Case isefinTransactionPromiseStatus.Broken
                Warnings &= "{{warning|Promise BROKEN.}}"
              Case isefinTransactionPromiseStatus.Cancelled
                Warnings &= "{{warning|Promise cancelled.}}"
            End Select
          Else
            Select Case PromisesLastStatus
              Case isefinTransactionPromiseStatus.Pass
                Warnings &= "{{info|Last Promise passed.}}"
              Case isefinTransactionPromiseStatus.Fail
                Warnings &= "{{warning|Last Promise FAILED.}}"
              Case isefinTransactionPromiseStatus.Broken
                Warnings &= "{{warning|Last Promise BROKEN.}}"
              Case isefinTransactionPromiseStatus.Cancelled
                Warnings &= "{{warning|Last Promise cancelled.}}"
            End Select

            If PromisesCountPending <> 0 Then
              Warnings &= "{{info|" & String.Format("{0} promises pending.", PromisesCountPending) & "}}"
            End If
          End If
        End If

        If Not shortSummary Then
          If accountPayArrangement.WorkflowPk <> 0 AndAlso finBL.Settings.AddOns.Workflow Then
            .AddCaptionCodeDescriptionWithFormShow("Workflow:", accountPayArrangement.WorkflowPk, finBL.WorkflowFunctions, "Workflows")
          End If
          .AddCaptionWiki("Created:", finBL.Utilities.GetUserAndDateWikiText("", accountPayArrangement.CreatedUserPk, accountPayArrangement.CreatedDate))
          .AddCaptionWiki("Updated:", finBL.Utilities.GetUserAndDateWikiText("", accountPayArrangement.UpdatedUserPk, accountPayArrangement.UpdatedDate))
        End If
      End With

      ' Warnings
      If Account.SupportsOverdue Then
        If Account.AccountType.ShowOverdue Then
          If accountPayArrangement.BalanceOverdue <> 0 OrElse accountPayArrangement.BalanceOverdueToday <> 0 Then
            If accountPayArrangement.BalanceOverdueToday = 0 Then
              strTemp = String.Format("Overdue Balance when Arrangement made was {0}.", finBL.FormatCurrency(accountPayArrangement.BalanceOverdue, True))
            Else
              strTemp = String.Format("Overdue Balance when Arrangement made was {0}, plus {1} due on the date of the Arrangement.", finBL.FormatCurrency(accountPayArrangement.BalanceOverdue, True), finBL.FormatCurrency(accountPayArrangement.BalanceOverdueToday, True))
            End If
            Warnings &= "{{info|" & strTemp & "}}"
          End If
        End If
        If Account.AccountType.ShowContractualOverdue Then
          If accountPayArrangement.BalanceOverdueContractual <> 0 OrElse accountPayArrangement.BalanceOverdueContractualToday <> 0 Then
            If accountPayArrangement.BalanceOverdueContractualToday = 0 Then
              strTemp = String.Format("Contractual Overdue Balance when Arrangement made was {0}.", finBL.FormatCurrency(accountPayArrangement.BalanceOverdueContractual, True))
            Else
              strTemp = String.Format("Contractual Overdue Balance when Arrangement made was {0}, plus {1} due on the date of the Arrangement.", finBL.FormatCurrency(accountPayArrangement.BalanceOverdueContractual, True), finBL.FormatCurrency(accountPayArrangement.BalanceOverdueContractualToday, True))
            End If
            Warnings &= "{{info|" & strTemp & "}}"
          End If
        End If
      End If
      .TextAfter = Warnings
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Payment Arrangement Overriding Payments Summary.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="accountPayArrangement">
  '''  The Account Payment Arrangement object to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used on the Accounts form, Payments page, Payment Arrangements tab.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function AccountPaymentArrangement_OverridingPayments(callerScriptInfo As ISScriptExecutionInfo,
                                                                           accountPayArrangement As finAccountPayArrangement,
                                                                  Optional includeActions As Boolean = True,
                                                                  Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' AccountPaymentArrangement_OverridingPayments
    '
    ' Version 1.01, Last updated 29/04/2024
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.00  05/09/2013  ISS
    '    1.01  29/04/2024  ISS      J033341   'Processed' column for open-ended Date Ranges are now greyed out as not-applicable.
    ' #################################################################

    Dim AccountPaymentArrangementPayment As finAccountPayArrangementPayment
    Dim HasManualPayment As Boolean
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Determine Columns to include
    HasManualPayment = (accountPayArrangement.Payments.CountManualPayments <> 0)

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .AutoStripe = True
      .Caption = ""

      If accountPayArrangement.Payments.Count = 0 Then
        .TextAfter = "{{info|No Overriding Payments.}}"
      Else
        ' Columns
        With .Columns
          .AddText("Type", 8).NoBreakChars = 10
          .AddDate("Date")
          .AddCurrency("Value")
          If HasManualPayment Then
            .AddBoolean("Manual")
          End If
          .AddBoolean("Processed")
          .AddText("Notes")
        End With

        ' Payments
        For Each AccountPaymentArrangementPayment In accountPayArrangement.Payments
          With .Rows.Add().Cells
            ' Type
            .AddText(AccountPaymentArrangementPayment.PaymentTypeText)

            ' Date
            If Len(AccountPaymentArrangementPayment.DateRange) = 0 Then
              .AddDate(AccountPaymentArrangementPayment.Date)
            Else
              .AddText(AccountPaymentArrangementPayment.DateRangeDescription)
            End If

            ' Value
            If AccountPaymentArrangementPayment.ValueType = isefinAccountCalcPaymentValueType.SetValue Then
              .AddCurrency(AccountPaymentArrangementPayment.Value)
            Else
              .AddText(AccountPaymentArrangementPayment.ValueText)
            End If

            ' Manual
            If HasManualPayment Then
              .AddTick(AccountPaymentArrangementPayment.ManualPayment).Tooltip = "Manual Payment"
            End If

            ' Processed
            If AccountPaymentArrangementPayment.Processed Then
              If AccountPaymentArrangementPayment.PaymentType = isefinAccountCalcPaymentType.Promise Then
                .AddText("{{colourblock|" & AccountPaymentArrangementPayment.PromiseStatusColour & "}}").Tooltip = AccountPaymentArrangementPayment.PromiseStatusText
              Else
                .AddTick(True).Tooltip = "Processed"
              End If
            ElseIf AccountPaymentArrangementPayment.IsRangeOpenEnded() Then
              .AddText("").BackgroundColour = "#ededed"
            Else
              .AddText("")
            End If

            ' Notes
            .AddText(AccountPaymentArrangementPayment.Notes)
          End With
        Next
      End If

      ' Warnings
      If accountPayArrangement.IsCurrent AndAlso accountPayArrangement.Payments.HasUnprocessedPayments() Then
        Warnings &= "{{Info|Overriding Payments still to be processed.}}"
      End If
      .TextAfter = Warnings
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Securitisation Summary (Version 1.0, Last updated 23/08/2013).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="accountSecuritisation">
  '''  The Account Securitisation to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Accounts form, Securitisations page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function AccountSecuritisation_Summary(callerScriptInfo As ISScriptExecutionInfo,
                                                            accountSecuritisation As finAccountSecuritisation,
                                                   Optional includeActions As Boolean = True,
                                                   Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim strTemp As String
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      .Columns.AddText(12).NoBreakChars = 15
      .Columns.AddText()

      With .Rows
        ' General
        With .AddCaptionCodeDescription("Bulk Funder:", accountSecuritisation.ExternalPartyPk, finBL.ExternalParties)
          .Cells(1).CellClass = iseSummaryTableCellClass.Highlight1
          .Cells(1).HyperlinkSetFormShow("ExternalParties", accountSecuritisation.ExternalPartyId)
        End With
        .AddCaptionText("Status:", accountSecuritisation.StatusText)

        ' Sale and Transfer
        If accountSecuritisation.DiscountedDate <> Nothing Then
          .AddSectionHeading2("Securitisation Details")

          .AddCaptionDate("Sale Date:", accountSecuritisation.DiscountedDate)
          If Len(accountSecuritisation.SecuritisationType) <> 0 Then
            .AddCaptionText("Securitisation Type:", accountSecuritisation.SecuritisationType)
          End If

          If Len(accountSecuritisation.DiscountedBasis) <> 0 Then
            .AddCaptionText("Basis:", accountSecuritisation.DiscountedBasis & "  " & finBL.FormatPercentage(accountSecuritisation.DiscountedRate / 100, 4))
          ElseIf accountSecuritisation.DiscountedRate <> 0 Then
            .AddCaptionPercentage("Rate:", accountSecuritisation.DiscountedRate / 100, 4)
          End If

          If accountSecuritisation.DiscountedValue <> 0 Then
            .AddCaptionCurrency("Value:", accountSecuritisation.DiscountedValue, True)
          End If
          If accountSecuritisation.DiscountedElementPk <> 0 Then
            .AddCaptionCodeDescription("Discounted Element:", accountSecuritisation.DiscountedElementPk, finBL.Elements)
          End If

          If accountSecuritisation.Repayments.Count = 0 Then
            strTemp = ""
          Else
            strTemp = "--(**" & Format(accountSecuritisation.Repayments.Count, "####0") & "** Repayments)--"
          End If
          If Len(accountSecuritisation.RepaymentBasis) <> 0 OrElse Len(strTemp) > 0 Then
            .AddCaptionWiki("Repayment Basis:", String.Format("**{0}** {1}", accountSecuritisation.RepaymentBasis, strTemp))
          End If
          If accountSecuritisation.RepaymentValue <> 0 Then
            .AddCaptionCurrency("Total Expected Repayments:", accountSecuritisation.RepaymentValue, True)
          End If
        End If

        ' Buyback and Transfer
        If accountSecuritisation.BuybackDate <> Nothing Then
          If accountSecuritisation.Status = isefinSecuritisationStatus.Transferred Then
            strTemp = "Transfer"
          Else
            strTemp = "Buyback"
          End If
          .AddSectionHeading2(String.Format("{0} Details", strTemp))

          .AddCaptionDate("Date:", accountSecuritisation.BuybackDate)

          If accountSecuritisation.BuybackInterest = 0 Then
            .AddCaptionCurrency(String.Format("{0} Value:", strTemp), accountSecuritisation.BuybackValue, True)
          Else
            .AddCaptionCurrency(String.Format("{0} Principal:", strTemp), accountSecuritisation.BuybackValue - accountSecuritisation.BuybackInterest, True)
            .AddCaptionCurrency(String.Format("Plus {0} Interest:", strTemp), accountSecuritisation.BuybackInterest, True)
          End If
          If accountSecuritisation.BuybackRebate <> 0 Then
            .AddCaptionCurrency(String.Format("Less {0} Rebate:", strTemp), accountSecuritisation.BuybackRebate, True)
            .AddCaptionCurrency(String.Format("{0} Repayment:", strTemp), accountSecuritisation.BuybackValue - accountSecuritisation.BuybackRebate, True)
          End If
        End If

        ' Notes
        If Len(accountSecuritisation.Notes) <> 0 Then
          .AddSectionHeading2("Notes")
          .AddText(accountSecuritisation.Notes)
        End If
      End With

      ' Warnings
      .TextAfter = Warnings
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Securitisation Repayments Summary (Version 1.0, Last updated 23/08/2013).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="accountSecuritisation">
  '''  The Account Securitisation to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Accounts form, Securitisation page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function AccountSecuritisation_Repayments(callerScriptInfo As ISScriptExecutionInfo,
                                                               accountSecuritisation As finAccountSecuritisation,
                                                      Optional includeActions As Boolean = True,
                                                      Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim AccountSecuritisationRepayment As finAccountSecuritisationRepayment
    Dim i As Integer
    Dim IncludeInterest As Boolean
    Dim PaidTotal As Boolean
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim TotalValue As Decimal
    Dim TotalInterest As Decimal
    Dim TotalPaid As Decimal
    Dim TotalPaidInterest As Decimal
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Find Columns to include
    For Each AccountSecuritisationRepayment In accountSecuritisation.Repayments
      If AccountSecuritisationRepayment.Interest <> 0 Then
        IncludeInterest = True
        Exit For
      End If
    Next

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .AutoStripe = True
      .Caption = ""

      ' Columns
      With .Columns
        .AddInteger("#", 1)
        .AddDate("Date")
        .AddBoolean("Paid")
        .AddCurrency("Value", 10)
        If IncludeInterest Then .AddCurrency("Interest", 10)
      End With

      ' Repayments
      i = 0
      TotalValue = 0
      TotalInterest = 0
      TotalPaid = 0
      TotalPaidInterest = 0
      PaidTotal = False
      For Each AccountSecuritisationRepayment In accountSecuritisation.Repayments
        i += 1

        ' Paid Total Row
        If Not AccountSecuritisationRepayment.Processed AndAlso Not PaidTotal Then
          If TotalPaid <> 0 Or TotalPaidInterest <> 0 Then
            With .Rows.Add(iseSummaryTableRowClass.FooterBold).Cells
              With .AddText("Total Paid")
                .ColSpan = 3
                .TextAlign = iseSummaryTableCellTextAlign.Left
              End With
              .AddCurrency(TotalPaid, True)
              If IncludeInterest Then
                .AddCurrency(TotalPaidInterest, True)
              End If
            End With
          End If
          PaidTotal = True
        End If

        ' Repayment
        With .Rows.Add().Cells
          .AddInteger(i)
          .AddDate(AccountSecuritisationRepayment.Date)
          .AddTick(AccountSecuritisationRepayment.Processed)
          .AddCurrency(AccountSecuritisationRepayment.Value)
          If IncludeInterest Then
            .AddCurrency(AccountSecuritisationRepayment.Interest)
          End If
        End With

        ' Track Totals
        If AccountSecuritisationRepayment.Processed Then
          TotalPaid += AccountSecuritisationRepayment.Value
          TotalPaidInterest += AccountSecuritisationRepayment.Interest
        Else
          TotalValue += AccountSecuritisationRepayment.Value
          TotalInterest += AccountSecuritisationRepayment.Interest
        End If
      Next

      ' Totals
      If i <> 0 Then
        ' Paid Total Row
        If Not PaidTotal Then
          If Not TotalPaid <> 0 OrElse TotalPaidInterest <> 0 Then
            With .Rows.Add(iseSummaryTableRowClass.FooterBold).Cells
              With .AddText("Total Paid")
                .ColSpan = 3
                .TextAlign = iseSummaryTableCellTextAlign.Left
              End With
              .AddCurrency(TotalPaid, True)
              If IncludeInterest Then
                .AddCurrency(TotalPaidInterest, True)
              End If
            End With
          End If
          PaidTotal = True
        End If

        ' Less Rebate Rows
        If accountSecuritisation.BuybackRebate <> 0 Then
          With .Rows.Add(iseSummaryTableRowClass.FooterBold).Cells
            With .AddText("Less Rebate")
              .ColSpan = 3
              .TextAlign = iseSummaryTableCellTextAlign.Left
            End With
            .AddCurrency(accountSecuritisation.BuybackRebate, True)
            If IncludeInterest Then
              .AddText("")
            End If
          End With
          With .Rows.Add(iseSummaryTableRowClass.FooterBold).Cells
            With .AddText("Net Repayments")
              .ColSpan = 3
              .TextAlign = iseSummaryTableCellTextAlign.Left
            End With
            .AddCurrency(TotalPaid - accountSecuritisation.BuybackRebate, True)
            If IncludeInterest Then
              .AddText("")
            End If
          End With
        End If

        ' Total Remaining Row
        If TotalValue <> 0 OrElse TotalInterest <> 0 Then
          With .Rows.Add(iseSummaryTableRowClass.FooterBold).Cells
            With .AddText("Total Remaining")
              .ColSpan = 3
              .TextAlign = iseSummaryTableCellTextAlign.Left
            End With
            .AddCurrency(TotalValue, True)
            If IncludeInterest Then
              .AddCurrency(TotalInterest, True)
            End If
          End With
        End If
      End If

      ' Warnings
      .TextAfter = Warnings
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Securitisation Activation Repayments Summary (Version 1.0, Last updated 26/08/2013).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="accountSecuritisationActivation">
  '''  The Account Securitisation Activation to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Securitisation Activation wizard.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function AccountSecuritisationActivation_Repayments(callerScriptInfo As ISScriptExecutionInfo,
                                                                         accountSecuritisationActivation As finAccountSecuritisationActivation,
                                                                Optional includeActions As Boolean = True,
                                                                Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim AccountSecuritisationRepayment As finAccountSecuritisationRepayment
    Dim i As Integer
    Dim IncludeInterest As Boolean
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim TotalValue As Decimal
    Dim TotalInterest As Decimal
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Find Columns to include
    For Each AccountSecuritisationRepayment In accountSecuritisationActivation.Repayments
      If AccountSecuritisationRepayment.Interest <> 0 Then
        IncludeInterest = True
        Exit For
      End If
    Next

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .AutoStripe = True
      .Caption = ""

      ' Columns
      With .Columns
        .AddInteger("#", 1)
        .AddDate("Date")
        .AddCurrency("Value", 10)
        If IncludeInterest Then .AddCurrency("Interest", 10)
      End With

      ' Repayments
      i = 0
      TotalValue = 0
      TotalInterest = 0
      For Each AccountSecuritisationRepayment In accountSecuritisationActivation.Repayments
        i += 1

        With .Rows.Add().Cells
          .AddInteger(i)
          .AddDate(AccountSecuritisationRepayment.Date)
          .AddCurrency(AccountSecuritisationRepayment.Value)
          If IncludeInterest Then
            .AddCurrency(AccountSecuritisationRepayment.Interest)
          End If
        End With

        ' Track Totals
        TotalValue += AccountSecuritisationRepayment.Value
        TotalInterest += AccountSecuritisationRepayment.Interest
      Next

      ' Totals
      If i <> 0 Then
        With .Rows.Add(iseSummaryTableRowClass.FooterBold).Cells
          .AddText("")
          .AddText("")
          .AddCurrency(TotalValue, True)
          If IncludeInterest Then
            .AddCurrency(TotalInterest, True)
          End If
        End With
      End If

      ' Warnings
      .TextAfter = Warnings
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Securitisation Activation Summary (Version 1.0, Last updated 23/08/2013).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="accountSecuritisationActivation">
  '''  The Account Securitisation Activation to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Securitisation Activation wizard.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function AccountSecuritisationActivation_Summary(callerScriptInfo As ISScriptExecutionInfo,
                                                                      accountSecuritisationActivation As finAccountSecuritisationActivation,
                                                             Optional includeActions As Boolean = True,
                                                             Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim strTemp As String
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      .Columns.AddText(12).NoBreakChars = 15
      .Columns.AddText()

      With .Rows
        ' General
        With .AddCaptionText("Account:", accountSecuritisationActivation.AccountId)
          .Cells(1).HyperlinkSetFormShow("Accounts", accountSecuritisationActivation.AccountId)
        End With
        .AddCaptionText("Name:", accountSecuritisationActivation.AccountName, iseSummaryTableCellClass.Highlight1)
        .AddCaptionText("Status:", accountSecuritisationActivation.StatusText, iseSummaryTableCellClass.Highlight2)

        ' Sale and Transfer
        If accountSecuritisationActivation.IsSale OrElse accountSecuritisationActivation.IsTransfer Then
          .AddSectionHeading2("Securitisation Details")

          .AddCaptionDate("Sale Date:", accountSecuritisationActivation.DiscountedDate)
          If Len(accountSecuritisationActivation.SecuritisationType) <> 0 Then
            .AddCaptionText("Securitisation Type:", accountSecuritisationActivation.SecuritisationType)
          End If

          If Len(accountSecuritisationActivation.DiscountedBasis) <> 0 Then
            .AddCaptionText("Basis:", accountSecuritisationActivation.DiscountedBasis & "  " & finBL.FormatPercentage(accountSecuritisationActivation.DiscountedRate / 100, 4))
          ElseIf accountSecuritisationActivation.DiscountedRate <> 0 Then
            .AddCaptionPercentage("Rate:", accountSecuritisationActivation.DiscountedRate / 100, 4)
          End If

          If accountSecuritisationActivation.DiscountedValue <> 0 Then
            .AddCaptionCurrency("Value:", accountSecuritisationActivation.DiscountedValue, True)
          End If
          If accountSecuritisationActivation.DiscountedElementPk <> 0 Then
            .AddCaptionCodeDescription("Discounted Element:", accountSecuritisationActivation.DiscountedElementPk, finBL.Elements)
          End If

          If accountSecuritisationActivation.Repayments.Count = 0 Then
            strTemp = ""
          Else
            strTemp = "--(**" & Format(accountSecuritisationActivation.Repayments.Count, "####0") & "** Repayments)--"
          End If
          If Len(accountSecuritisationActivation.RepaymentBasis) <> 0 OrElse Len(strTemp) > 0 Then
            .AddCaptionWiki("Repayment Basis:", String.Format("**{0}** {1}", accountSecuritisationActivation.RepaymentBasis, strTemp))
          End If
          If accountSecuritisationActivation.RepaymentValue <> 0 Then
            .AddCaptionCurrency("Repayment Value:", accountSecuritisationActivation.RepaymentValue, True)
          End If
        End If

        ' Buyback and Transfer
        If accountSecuritisationActivation.IsBuyback OrElse accountSecuritisationActivation.IsTransfer Then
          .AddSectionHeading2("Buyback Details")

          .AddCaptionCurrency("Buyback Value:", accountSecuritisationActivation.BuybackValue, True)
          If accountSecuritisationActivation.BuybackRebateElementPk <> 0 Then
            .AddCaptionCodeDescription("Buyback Element:", accountSecuritisationActivation.BuybackRebateElementPk, finBL.Elements)
          End If
          If accountSecuritisationActivation.BuybackInterest <> 0 Then
            .AddCaptionCurrency("Buyback Interest:", accountSecuritisationActivation.BuybackInterest, True)
          End If
          If accountSecuritisationActivation.BuybackRebate <> 0 Then
            .AddCaptionCurrency("Buyback Rebate:", accountSecuritisationActivation.BuybackRebate, True)
          End If
          If accountSecuritisationActivation.BuybackRebateElementPk <> 0 Then
            .AddCaptionCodeDescription("Rebate Element:", accountSecuritisationActivation.BuybackRebateElementPk, finBL.Elements)
          End If
        End If

        ' Notes
        If Len(accountSecuritisationActivation.Notes) <> 0 Then
          .AddSectionHeading2("Notes")
          .AddText(accountSecuritisationActivation.Notes)
        End If
      End With

      ' Warnings
      If accountSecuritisationActivation.Pk <> 0 Then
        Warnings &= "{{info|This is an existing record " & finBL.Utilities.GetUserAndDateWikiText("created", accountSecuritisationActivation.CreatedUserPk, accountSecuritisationActivation.CreatedDate) & "}}"
      End If
      If Len(accountSecuritisationActivation.InvalidMessageResolved) <> 0 Then
        Warnings &= "{{warning|" & accountSecuritisationActivation.InvalidMessageResolved & "}}"
      End If
      .TextAfter = Warnings
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Securitisation Allocation Summary.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="accountSecuritisationAllocation">
  '''  The Account Securitisation Allocation to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Securitisation Allocation wizard.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function AccountSecuritisationAllocation_Summary(callerScriptInfo As ISScriptExecutionInfo,
                                                                      accountSecuritisationAllocation As finAccountSecuritisationAllocation,
                                                             Optional includeActions As Boolean = True,
                                                             Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' AccountSecuritisationAllocation_Summary
    '
    ' Version: 1.01 (30/09/2021)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.00  23/08/2013  ISS                Created
    '    1.01  14/09/2021  ISS      J020367   Added support for Allocations HTML Widget
    '          30/09/2021  ISS      J027480   Added "Other Details" section
    ' #################################################################

    Dim AccountSecuritisationAllocations As finAccountSecuritisationAllocations
    Dim strTemp As String
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Parent Collection
    AccountSecuritisationAllocations = accountSecuritisationAllocation.Parent

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      .Columns.AddText(12).NoBreakChars = 15
      .Columns.AddText()

      With .Rows
        ' General
        With .AddCaptionText("Account:", accountSecuritisationAllocation.AccountId)
          .Cells(1).HyperlinkSetFormShow("Accounts", accountSecuritisationAllocation.AccountId)
        End With
        .AddCaptionText("Name:", accountSecuritisationAllocation.AccountName, iseSummaryTableCellClass.Highlight1)

        ' Only display Status if finPOWER Connect form to prevent HTML Widget requiring a call back when updating the Status on the grid
        If callerScriptInfo.Target = iseSummaryPageTarget.Form Then
          .AddCaptionText("Status:", accountSecuritisationAllocation.StatusText, iseSummaryTableCellClass.Highlight2)
        End If

        ' Sale and Transfer
        If AccountSecuritisationAllocations.IsSale OrElse AccountSecuritisationAllocations.IsTransfer Then
          .AddSectionHeading2("Securitisation Details")

          .AddCaptionDate("Sale Date:", accountSecuritisationAllocation.DiscountedDate)
          If Len(accountSecuritisationAllocation.SecuritisationType) <> 0 Then
            .AddCaptionText("Securitisation Type:", accountSecuritisationAllocation.SecuritisationType)
          End If

          If Len(accountSecuritisationAllocation.DiscountedBasis) <> 0 Then
            .AddCaptionText("Basis:", accountSecuritisationAllocation.DiscountedBasis & "  " & finBL.FormatPercentage(accountSecuritisationAllocation.DiscountedRate / 100, 4))
          ElseIf accountSecuritisationAllocation.DiscountedRate <> 0 Then
            .AddCaptionPercentage("Rate:", accountSecuritisationAllocation.DiscountedRate / 100, 4)
          End If

          If accountSecuritisationAllocation.DiscountedValue <> 0 Then
            .AddCaptionCurrency("Value:", accountSecuritisationAllocation.DiscountedValue, True)
          End If
          If accountSecuritisationAllocation.DiscountedElementPk <> 0 Then
            .AddCaptionCodeDescription("Discounted Element:", accountSecuritisationAllocation.DiscountedElementPk, finBL.Elements)
          End If

          If accountSecuritisationAllocation.Repayments.Count = 0 Then
            strTemp = ""
          Else
            strTemp = "--(**" & Format(accountSecuritisationAllocation.Repayments.Count, "####0") & "** Repayments)--"
          End If
          If Len(accountSecuritisationAllocation.RepaymentBasis) <> 0 OrElse Len(strTemp) > 0 Then
            .AddCaptionWiki("Repayment Basis:", String.Format("**{0}** {1}", accountSecuritisationAllocation.RepaymentBasis, strTemp))
          End If
          If accountSecuritisationAllocation.RepaymentValue <> 0 Then
            .AddCaptionCurrency("Repayment Value:", accountSecuritisationAllocation.RepaymentValue, True)
          End If
        End If

        ' Buyback and Transfer
        If AccountSecuritisationAllocations.IsBuyback OrElse AccountSecuritisationAllocations.IsTransfer Then
          .AddSectionHeading2("Buyback Details")

          .AddCaptionCurrency("Buyback Value:", accountSecuritisationAllocation.BuybackValue, True)
          If accountSecuritisationAllocation.BuybackRebateElementPk <> 0 Then
            .AddCaptionCodeDescription("Buyback Element:", accountSecuritisationAllocation.BuybackRebateElementPk, finBL.Elements)
          End If
          If accountSecuritisationAllocation.BuybackInterest <> 0 Then
            .AddCaptionCurrency("Buyback Interest:", accountSecuritisationAllocation.BuybackInterest, True)
          End If
          If accountSecuritisationAllocation.BuybackRebate <> 0 Then
            .AddCaptionCurrency("Buyback Rebate:", accountSecuritisationAllocation.BuybackRebate, True)
          End If
          If accountSecuritisationAllocation.BuybackRebateElementPk <> 0 Then
            .AddCaptionCodeDescription("Rebate Element:", accountSecuritisationAllocation.BuybackRebateElementPk, finBL.Elements)
          End If
        End If

        ' Notes
        If Len(accountSecuritisationAllocation.Notes) <> 0 Then
          .AddSectionHeading2("Notes")
          .AddText(accountSecuritisationAllocation.Notes)
        End If

        ' Custom Columns
        If accountSecuritisationAllocation.CustomDisplayColumnsUsed Then
          .AddSectionHeading2("Other Details")
          If Len(accountSecuritisationAllocation.CustomDisplayColumn1) <> 0 Then
            .AddCaptionText(finBL.Settings.AccountSecuritisationCustomDisplayColumn1HeadingResolved & ":", accountSecuritisationAllocation.CustomDisplayColumn1)
          End If
          If Len(accountSecuritisationAllocation.CustomDisplayColumn2) <> 0 Then
            .AddCaptionText(finBL.Settings.AccountSecuritisationCustomDisplayColumn2HeadingResolved & ":", accountSecuritisationAllocation.CustomDisplayColumn2)
          End If
          If Len(accountSecuritisationAllocation.CustomDisplayColumn3) <> 0 Then
            .AddCaptionText(finBL.Settings.AccountSecuritisationCustomDisplayColumn3HeadingResolved & ":", accountSecuritisationAllocation.CustomDisplayColumn3)
          End If
          If Len(accountSecuritisationAllocation.CustomDisplayColumn4) <> 0 Then
            .AddCaptionText(finBL.Settings.AccountSecuritisationCustomDisplayColumn4HeadingResolved & ":", accountSecuritisationAllocation.CustomDisplayColumn4)
          End If
        End If
      End With

      ' Warnings
      If accountSecuritisationAllocation.Pk <> 0 Then
        Warnings &= "{{info|This is an existing record " & finBL.Utilities.GetUserAndDateWikiText("created", accountSecuritisationAllocation.CreatedUserPk, accountSecuritisationAllocation.CreatedDate) & "}}"
      End If
      If Len(accountSecuritisationAllocation.InvalidMessageResolved) <> 0 Then
        Warnings &= "{{warning|" & accountSecuritisationAllocation.InvalidMessageResolved & "}}"
      End If
      .TextAfter = Warnings
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Securitisation Repayments Process Item Summary (Version 1.0, Last updated 26/08/2013).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="accountSecuritisationRepaymentsProcessItem">
  '''  The Account Securitisation Repayments Process Item to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Accounts form, Securitisations page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function AccountSecuritisationRepaymentsProcessItem_Summary(callerScriptInfo As ISScriptExecutionInfo,
                                                                                 accountSecuritisationRepaymentsProcessItem As finAccountSecuritisationRepaymentsProcessItem,
                                                                        Optional includeActions As Boolean = True,
                                                                        Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      .Columns.AddText(12).NoBreakChars = 15
      .Columns.AddText()

      With .Rows
        ' General
        With .AddCaptionCodeDescription("Bulk Funder:", accountSecuritisationRepaymentsProcessItem.ExternalPartyPk, finBL.ExternalParties)
          .Cells(1).CellClass = iseSummaryTableCellClass.Highlight1
          .Cells(1).HyperlinkSetFormShow("ExternalParties", accountSecuritisationRepaymentsProcessItem.ExternalPartyId)
        End With
        .AddCaptionDate("Date:", accountSecuritisationRepaymentsProcessItem.RepaymentDate)
        If accountSecuritisationRepaymentsProcessItem.Status <> isefinSecuritisationRepaymentProcessItemStatus.None Then
          .AddCaptionText("Status:", accountSecuritisationRepaymentsProcessItem.StatusText)
        End If
        .AddCaptionCurrency("Value:", accountSecuritisationRepaymentsProcessItem.RepaymentValue, , , iseSummaryTableCellClass.Highlight2)
        If accountSecuritisationRepaymentsProcessItem.RepaymentInterest <> 0 Then
          .AddCaptionCurrency("Interest:", accountSecuritisationRepaymentsProcessItem.RepaymentInterest)
        End If
        If accountSecuritisationRepaymentsProcessItem.Rebate <> 0 Then
          .AddCaptionCurrency("Rebate:", accountSecuritisationRepaymentsProcessItem.Rebate)
        End If
        With .AddCaptionText("Account:", accountSecuritisationRepaymentsProcessItem.AccountId)
          .Cells(1).HyperlinkSetFormShow("Accounts", accountSecuritisationRepaymentsProcessItem.AccountId)
        End With
        .AddCaptionText("Name:", accountSecuritisationRepaymentsProcessItem.AccountName)
        .AddCaptionText("Account Status:", accountSecuritisationRepaymentsProcessItem.AccountStatusText)
      End With

      ' Warnings
      If accountSecuritisationRepaymentsProcessItem.IsNew Then
        Warnings &= "{{info|New repayment record.}}"
      End If
      If Not accountSecuritisationRepaymentsProcessItem.CreateTransaction Then
        Warnings &= "{{info|No Transaction record will be created for this repayment.}}"
      End If
      .TextAfter = Warnings
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Securitisation Allocation Repayments Summary (Version 1.0, Last updated 23/08/2013).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="accountSecuritisationAllocation">
  '''  The Account Securitisation Allocation to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Securitisation Allocation wizard.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function AccountSecuritisationAllocation_Repayments(callerScriptInfo As ISScriptExecutionInfo,
                                                                         accountSecuritisationAllocation As finAccountSecuritisationAllocation,
                                                                Optional includeActions As Boolean = True,
                                                                Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim AccountSecuritisationAllocationRepayment As finAccountSecuritisationAllocationRepayment
    Dim i As Integer
    Dim IncludeInterest As Boolean
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim TotalValue As Decimal
    Dim TotalInterest As Decimal
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Find Columns to include
    For Each AccountSecuritisationAllocationRepayment In accountSecuritisationAllocation.Repayments
      If AccountSecuritisationAllocationRepayment.Interest <> 0 Then
        IncludeInterest = True
        Exit For
      End If
    Next

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .AutoStripe = True
      .Caption = ""

      ' Columns
      With .Columns
        .AddInteger("#", 1)
        .AddDate("Date")
        .AddCurrency("Value", 10)
        If IncludeInterest Then .AddCurrency("Interest", 10)
      End With

      ' Repayments
      i = 0
      TotalValue = 0
      TotalInterest = 0
      For Each AccountSecuritisationAllocationRepayment In accountSecuritisationAllocation.Repayments
        i += 1

        With .Rows.Add().Cells
          .AddInteger(i)
          .AddDate(AccountSecuritisationAllocationRepayment.Date)
          .AddCurrency(AccountSecuritisationAllocationRepayment.Value)
          If IncludeInterest Then
            .AddCurrency(AccountSecuritisationAllocationRepayment.Interest)
          End If
        End With

        ' Track Totals
        TotalValue += AccountSecuritisationAllocationRepayment.Value
        TotalInterest += AccountSecuritisationAllocationRepayment.Interest
      Next

      ' Totals
      If i <> 0 Then
        With .Rows.Add(iseSummaryTableRowClass.FooterBold).Cells
          .AddText("")
          .AddText("")
          .AddCurrency(TotalValue, True)
          If IncludeInterest Then
            .AddCurrency(TotalInterest, True)
          End If
        End With
      End If

      ' Warnings
      .TextAfter = Warnings
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Transfer Summary (Version 1.01, Last updated 09/03/2020).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="accountTransfer">
  '''  The Account Transfer object to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Transfer wizard, Transfer page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function AccountTransfer_Summary(callerScriptInfo As ISScriptExecutionInfo,
                                                      accountTransfer As finAccountTransfer,
                                             Optional includeActions As Boolean = True,
                                             Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim BalanceFrom As Decimal
    Dim BalanceOverdue As Decimal
    Dim BalanceOverdueContractual As Decimal
    Dim BalanceTo As Decimal
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    Dim SummaryTableFrom As ISSummaryTable
    Dim SummaryTableTo As ISSummaryTable

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()
    SummaryTableFrom = finBL.CreateSummaryTable()
    SummaryTableTo = finBL.CreateSummaryTable()

    ' Just in case 
    If accountTransfer.FromAccount.IsNew Then Return SummaryTables

    ' From / To Accounts
    With accountTransfer.FromAccount
      ' Alert Messages
      .GetAlertMessages(SummaryTableFrom.TextAfter)

      ' Get Balance
      .GetBalance(BalanceFrom)

      ' Overdue Details
      If .SupportsOverdue Then
        If .AccountType.ShowOverdue Then
          .GetBalanceOverdue(BalanceOverdue, accountTransfer.TransferDate)
        End If
        If .AccountType.ShowContractualOverdue Then
          .GetBalanceOverdueContractual(BalanceOverdueContractual, accountTransfer.TransferDate)
        End If
      End If
    End With
    With accountTransfer.ToAccount
      ' Alert Messages
      .GetAlertMessages(SummaryTableTo.TextAfter)

      ' Get Balance
      .GetBalance(BalanceTo)
    End With

    ' Alert Summary Tables
    If Len(SummaryTableFrom.TextAfter) <> 0 Then SummaryTableFrom.Rows.AddSectionHeading2("From Account Alert(s)")
    If Len(SummaryTableTo.TextAfter) <> 0 Then SummaryTableTo.Rows.AddSectionHeading2("To Account Alert(s)")

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .AutoStripe = True
      .Caption = ""

      ' Columns
      With .Columns
        .AddText(" ", 20).NoBreakChars = 20
        .AddCurrency("Withdrawal from " & accountTransfer.FromAccount.AccountId, 30)
        .AddCurrency("Credit to " & accountTransfer.ToAccount.AccountId, 30)
      End With

      With .Rows
        ' Balance
        With .Add(iseSummaryTableRowClass.FooterBold).Cells
          .AddText("Current Balance")
          .AddCurrency(BalanceFrom)
          .AddCurrency(BalanceTo)
        End With

        ' Plus Transfer
        With .Add().Cells
          .AddText("Transfer")
          .AddCurrency(accountTransfer.TransferValueResolved)
          .AddCurrency(-accountTransfer.TransferValueResolved)
        End With

        ' Plus Fee
        If accountTransfer.FeeValueResolved <> 0 Then
          With .Add().Cells
            .AddText("plus Fee")
            .AddCurrency(accountTransfer.FeeValueResolved)
            .AddText("N/A")
          End With
        End If

        ' Balance After Transfer
        With .Add(iseSummaryTableRowClass.FooterBold).Cells
          .AddText("Balance after Transfer")
          .AddCurrency(BalanceFrom + accountTransfer.TransferValueResolved + accountTransfer.FeeValueResolved, True)
          .AddCurrency(BalanceTo - accountTransfer.TransferValueResolved, True)
        End With
      End With

      ' Warnings
      If BalanceOverdue > 0 Then
        Warnings &= "{{warning|Account is currently Overdue.}}"
      End If
      If BalanceOverdueContractual > 0 Then
        Warnings &= "{{warning|Account is currently Contractually Overdue.}}"
      End If
      .TextAfter = Warnings
    End With

    ' Add Summary Tables
    SummaryTables.Add("AlertsFrom", SummaryTableFrom)
    SummaryTables.Add("AlertsTo", SummaryTableTo)
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Withdrawal Payment Arrangement Options Summary.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="accountWithdrawal">
  '''  The Account Withdrawal object to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="withdrawalCaption">
  '''  The Withdrawal caption, e.g., Withdrawal, Refund etc.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Withdrawal wizard, Withdrawal page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function AccountWithdrawal_PaymentArrangementOptions(callerScriptInfo As ISScriptExecutionInfo,
                                                                          accountWithdrawal As finAccountWithdrawal,
                                                                 Optional withdrawalCaption As String = "Withdrawal",
                                                                 Optional includeActions As Boolean = True,
                                                                 Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' AccountWithdrawal_PaymentArrangementOptions
    '
    ' Version: 1.02 (29/03/2022)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.01  03/05/2016  ISS      
    '    1.02  29/03/2022  ISS      J028520   Added support for AdjustRegularPaymentMaturity Enumeration
    ' #################################################################

    Dim Account As finAccount
    Dim AccountPayArrangementAdd As finAccountPayArrangementAdd
    Dim Days As Integer
    Dim PaymentFinalDate As Date
    Dim PaymentFinalRegular As Decimal
    Dim PaymentRegular As Decimal
    Dim NewPaymentFinalDate As Date
    Dim NewPaymentFinalRegular As Decimal
    Dim NewPaymentRegular As Decimal
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTableRowClass As iseSummaryTableRowClass
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()
    Account = accountWithdrawal.Account
    AccountPayArrangementAdd = finBL.CreateAccountPayArrangementAdd()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .AutoStripe = True
      .Caption = ""

      ' Columns
      With .Columns
        .AddText(" ", 20).NoBreakChars = 40
        .AddCurrency("Regular", 12)
        .AddCurrency("+Value")
        .AddCurrency("Final", 12)
        .AddDate("Final Date")
        .AddInteger("+Days", 10)
      End With

      With .Rows
        ' Pre-Withdrawal
        With Account
          PaymentRegular = .Calculation.PaymentRegular
          .Calculation.GetPaymentRegularFinal(Nothing, PaymentFinalRegular, False)
          PaymentFinalDate = .Calculation.PaymentFinalDate
        End With
        With .Add(iseSummaryTableRowClass.Normal).Cells
          .AddText("Pre-" & withdrawalCaption)
          .AddCurrency(PaymentRegular, True)
          .AddText("")
          .AddCurrency(PaymentFinalRegular, True)
          .AddDate(PaymentFinalDate)
          .AddText("")
        End With

        ' Hold Current Regular Payment
        ' Get Values
        With accountWithdrawal
          NewPaymentRegular = .Calculation.PaymentRegular
          NewPaymentFinalDate = .Calculation.PaymentFinalDate
          .Calculation.GetPaymentRegularFinal(Nothing, NewPaymentFinalRegular, False)
        End With

        If accountWithdrawal.RegularPaymentAdjustmentType = isefinAccountWithdrawalRegularPaymentAdjustmentType.None Then
          SummaryTableRowClass = iseSummaryTableRowClass.FooterBold
        Else
          SummaryTableRowClass = iseSummaryTableRowClass.Normal
        End If
        With .Add(SummaryTableRowClass).Cells
          .AddText("1. Hold Current Payment")
          .AddCurrency(NewPaymentRegular, True)
          .AddCurrency(NewPaymentRegular - PaymentRegular, True)
          .AddCurrency(NewPaymentFinalRegular, True)
          .AddDate(NewPaymentFinalDate)
          If PaymentFinalDate = Nothing OrElse NewPaymentFinalDate = Nothing Then
            Days = 0
          Else
            Days = CInt(DateDiff(DateInterval.Day, PaymentFinalDate, NewPaymentFinalDate))
          End If
          If Days = 0 Then .AddText("") Else .AddInteger(Days)
        End With

        ' Hold Final Payment Date
        If Account.Calculation.PaymentFinalDate <> Nothing Then
          ' Get Values
          NewPaymentRegular = 0
          With AccountPayArrangementAdd
            If .AccountLoadPk(accountWithdrawal.Account.Pk) Then
              .AddWithdrawal(accountWithdrawal)
              .Calculation.PaymentFinalDateHold = True
              If accountWithdrawal.Account.Calculation.PaymentFinalDate < accountWithdrawal.Account.Calculation.DateMaturity Then
                .Calculation.PaymentFinalDateHoldDate = accountWithdrawal.Account.Calculation.DateMaturity
              Else
                .Calculation.PaymentFinalDateHoldDate = accountWithdrawal.Account.Calculation.PaymentFinalDate
              End If

              If .Calculate Then
                NewPaymentRegular = .Calculation.PaymentRegular
                .Calculation.GetPaymentRegularFinal(Nothing, NewPaymentFinalRegular, False)
                NewPaymentFinalDate = .Calculation.PaymentFinalDate
              End If
            End If
          End With

          If accountWithdrawal.RegularPaymentAdjustmentType = isefinAccountWithdrawalRegularPaymentAdjustmentType.AdjustRegularPayment Then
            SummaryTableRowClass = iseSummaryTableRowClass.FooterBold
          Else
            SummaryTableRowClass = iseSummaryTableRowClass.Normal
          End If

          With .Add(SummaryTableRowClass).Cells
            .AddText("2. Maintain Final Date")
            If NewPaymentRegular = 0 OrElse NewPaymentFinalDate = Nothing Then
              With .AddText("Failed to Calculate")
                .CellClass = iseSummaryTableCellClass.Warning
                .TextAlign = iseSummaryTableCellTextAlign.Left
              End With
            Else
              .AddCurrency(NewPaymentRegular, True)
              .AddCurrency(NewPaymentRegular - PaymentRegular, True)
              .AddCurrency(NewPaymentFinalRegular, True)
              .AddDate(NewPaymentFinalDate)
              If PaymentFinalDate = Nothing OrElse NewPaymentFinalDate = Nothing Then
                Days = 0
              Else
                Days = CInt(DateDiff(DateInterval.Day, PaymentFinalDate, NewPaymentFinalDate))
              End If
              If Days = 0 Then .AddText("") Else .AddInteger(Days)
            End If
          End With
        End If

        ' Hold Maturity Date
        If accountWithdrawal.IsAdjustRegularPaymentMaturityAvailable() Then
          ' Get Values
          NewPaymentRegular = 0
          With AccountPayArrangementAdd
            If .AccountLoadPk(accountWithdrawal.Account.Pk) Then
              .AddWithdrawal(accountWithdrawal)
              .Calculation.PaymentFinalDateHold = True
              .Calculation.PaymentFinalDateHoldDate = accountWithdrawal.Account.Calculation.DateMaturity

              If .Calculate() Then
                NewPaymentRegular = .Calculation.PaymentRegular
                .Calculation.GetPaymentRegularFinal(Nothing, NewPaymentFinalRegular, False)
                NewPaymentFinalDate = .Calculation.DateMaturity
              End If
            End If
          End With

          If accountWithdrawal.RegularPaymentAdjustmentType = isefinAccountWithdrawalRegularPaymentAdjustmentType.AdjustRegularPaymentMaturity Then
            SummaryTableRowClass = iseSummaryTableRowClass.FooterBold
          Else
            SummaryTableRowClass = iseSummaryTableRowClass.Normal
          End If

          With .Add(SummaryTableRowClass).Cells
            .AddText("3. Maintain Maturity Date")
            If NewPaymentRegular = 0 OrElse NewPaymentFinalDate = Nothing Then
              With .AddText("Failed to Calculate")
                .CellClass = iseSummaryTableCellClass.Warning
                .TextAlign = iseSummaryTableCellTextAlign.Left
              End With
            Else
              .AddCurrency(NewPaymentRegular, True)
              .AddCurrency(NewPaymentRegular - PaymentRegular, True)
              .AddCurrency(NewPaymentFinalRegular, True)
              .AddDate(NewPaymentFinalDate)
              If PaymentFinalDate = Nothing OrElse NewPaymentFinalDate = Nothing Then
                Days = 0
              Else
                Days = CInt(DateDiff(DateInterval.Day, PaymentFinalDate, NewPaymentFinalDate))
              End If
              If Days = 0 Then .AddText("") Else .AddInteger(Days)
            End If
          End With
        End If

        ' Overriding Regular Payment
        If accountWithdrawal.RegularPaymentNew > 0 Then
          ' Get Values
          NewPaymentRegular = 0
          With AccountPayArrangementAdd
            If .AccountLoadPk(accountWithdrawal.Account.Pk) Then
              .AddWithdrawal(accountWithdrawal)
              .Calculation.PaymentRegularOverride = accountWithdrawal.RegularPaymentNew

              If .Calculate Then
                NewPaymentRegular = .Calculation.PaymentRegular
                .Calculation.GetPaymentRegularFinal(Nothing, NewPaymentFinalRegular, False)
                NewPaymentFinalDate = .Calculation.PaymentFinalDate
              End If
            End If
          End With

          If accountWithdrawal.RegularPaymentAdjustmentType = isefinAccountWithdrawalRegularPaymentAdjustmentType.OverrideRegularPayment Then
            SummaryTableRowClass = iseSummaryTableRowClass.FooterBold
          Else
            SummaryTableRowClass = iseSummaryTableRowClass.Normal
          End If
          With .Add(SummaryTableRowClass).Cells
            .AddText("4. Override Payment")
            If NewPaymentRegular = 0 OrElse NewPaymentFinalDate = Nothing Then
              With .AddText("Failed to Calculate")
                .CellClass = iseSummaryTableCellClass.Warning
                .TextAlign = iseSummaryTableCellTextAlign.Left
              End With
            Else
              .AddCurrency(NewPaymentRegular, True)
              .AddCurrency(NewPaymentRegular - PaymentRegular, True)
              .AddCurrency(NewPaymentFinalRegular, True)
              .AddDate(NewPaymentFinalDate)
              If PaymentFinalDate = Nothing OrElse NewPaymentFinalDate = Nothing Then
                Days = 0
              Else
                Days = CInt(DateDiff(DateInterval.Day, PaymentFinalDate, NewPaymentFinalDate))
              End If
              If Days = 0 Then .AddText("") Else .AddInteger(Days)
            End If
          End With
        End If
      End With

      ' Warnings
      If Not accountWithdrawal.RegularPaymentOverdueHold Then Warnings &= "{{info|Overdue will be cleared.}}"

      .TextAfter = Warnings
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Withdrawal Summary (Version 1.04, Last updated 16/12/2020).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="accountWithdrawal">
  '''  The Account Withdrawal object to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="withdrawalCaption">
  '''  The Withdrawal caption, e.g., Withdrawal, Refund etc.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Withdrawal wizard, Withdrawal page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function AccountWithdrawal_Summary(callerScriptInfo As ISScriptExecutionInfo,
                                                        accountWithdrawal As finAccountWithdrawal,
                                               Optional withdrawalCaption As String = "Withdrawal",
                                               Optional includeActions As Boolean = True,
                                               Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim Account As finAccount
    Dim Balance As Decimal
    Dim BalanceOverdue As Decimal
    Dim BalanceOverdueContractual As Decimal
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()
    Account = accountWithdrawal.Account

    ' Just in case 
    If Account.IsNew Then Return SummaryTables

    With Account
      ' Get Balance
      .GetBalance(Balance)

      ' Overdue Details
      If .SupportsOverdue Then
        If .AccountType.ShowOverdue Then
          .GetBalanceOverdue(BalanceOverdue, accountWithdrawal.WithdrawalDate)
        End If
        If .AccountType.ShowContractualOverdue Then
          .GetBalanceOverdueContractual(BalanceOverdueContractual, accountWithdrawal.WithdrawalDate)
        End If
      End If
    End With

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .AutoStripe = True
      .Caption = ""

      ' Columns
      With .Columns
        .AddText(" ", 20).NoBreakChars = 20
        .AddCurrency("Balance", 20)
      End With

      ' Alert Messages
      Account.GetAlertMessages(.TextBefore)

      With .Rows
        Select Case Account.AccountClass
          Case isefinAccountClass.Deposit
            ' Balance
            With .Add(iseSummaryTableRowClass.FooterBold).Cells
              .AddText("Current Balance")
              .AddCurrency(-Balance)
            End With

            ' Less Withdrawal
            With .Add().Cells
              .AddText("less " & withdrawalCaption)
              .AddCurrency(accountWithdrawal.WithdrawalValueResolved)
            End With

            ' Plus Fee
            If accountWithdrawal.FeeValueResolved <> 0 Then
              With .Add().Cells
                .AddText("less Fee")
                .AddCurrency(accountWithdrawal.FeeValueResolved)
              End With
            End If

            ' Plus Payment Fee
            If accountWithdrawal.PaymentFeeValueResolved <> 0 Then
              With .Add().Cells
                .AddText("less Payment Fee")
                .AddCurrency(accountWithdrawal.PaymentFeeValueResolved)
              End With
            End If

            ' Balance After Withdrawal
            With .Add(iseSummaryTableRowClass.FooterBold).Cells
              .AddText("Balance after " & withdrawalCaption)
              .AddCurrency(-(Balance + accountWithdrawal.WithdrawalValueResolved + accountWithdrawal.FeeValueResolved + accountWithdrawal.PaymentFeeValueResolved), True)
            End With

          Case Else
            ' Balance
            With .Add(iseSummaryTableRowClass.FooterBold).Cells
              .AddText("Current Balance")
              .AddCurrency(Balance)
            End With

            ' Plus Withdrawal
            With .Add().Cells
              .AddText("plus " & withdrawalCaption)
              .AddCurrency(accountWithdrawal.WithdrawalValueResolved)
            End With

            ' Plus Fee
            If accountWithdrawal.FeeValueResolved <> 0 Then
              With .Add().Cells
                .AddText("plus Fee")
                .AddCurrency(accountWithdrawal.FeeValueResolved)
              End With
            End If

            ' Plus Payment Fee
            If accountWithdrawal.PaymentFeeValueResolved <> 0 Then
              With .Add().Cells
                .AddText("plus Payment Fee")
                .AddCurrency(accountWithdrawal.PaymentFeeValueResolved)
              End With
            End If

            ' Balance After Withdrawal
            With .Add(iseSummaryTableRowClass.FooterBold).Cells
              .AddText("Balance after " & withdrawalCaption)
              .AddCurrency(Balance + accountWithdrawal.WithdrawalValueResolved + accountWithdrawal.FeeValueResolved + accountWithdrawal.PaymentFeeValueResolved, True)
            End With
        End Select
      End With

      ' Warnings
      If Account.SupportsOverdue Then
        If BalanceOverdue > 0 Then Warnings &= "{{warning|Account is currently Overdue.}}"
        If BalanceOverdueContractual > 0 Then Warnings &= "{{warning|Account is currently Contractually Overdue.}}"
      End If
      .TextAfter = Warnings
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Bank Account Suspense Item Summary (Version 1.01, Last updated 12/05/2021).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="bankAccountSuspenseItem">
  '''  Bank Account Suspense Item to display.
  ''' </param>
  ''' <param name="includeWarnings">
  '''  Indicates whether to include Warnings with the Summary Tables.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Suspense Items wizard and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function BankAccountSuspenseItem_Summary(callerScriptInfo As ISScriptExecutionInfo,
                                                              bankAccountSuspenseItem As finBankAccountSuspenseItem,
                                                     Optional includeWarnings As Boolean = True,
                                                     Optional includeActions As Boolean = True,
                                                     Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    With SummaryTableMain
      .TableClass = iseSummaryTableClass.Information
      .WidthHtml = "100%"
      .AutoStripe = True
      .Columns.AddText(12).NoBreakChars = 20

      With .Rows
        .AddCaptionDate("Date:", bankAccountSuspenseItem.Date)
        .AddCaptionText("Reference:", bankAccountSuspenseItem.Reference)
        .AddCaptionCurrency("Value:", bankAccountSuspenseItem.Value, True)
        If bankAccountSuspenseItem.BankingDetails.PaymentMethod IsNot Nothing Then
          .AddCaptionCodeDescription("Pay Method:", bankAccountSuspenseItem.BankingDetails.PaymentMethodId, finBL.PaymentMethods)
        End If
        .AddCaptionWiki("Created:", finBL.Utilities.GetUserAndDateWikiText("", bankAccountSuspenseItem.CreatedUserPk, bankAccountSuspenseItem.CreatedDate))
      End With

      ' Warnings
      If includeWarnings Then
        If bankAccountSuspenseItem.GlExportPk <> 0 Then Warnings &= "{{info|Item has been transferred to General Ledger.}}"
        If bankAccountSuspenseItem.Deleted Then Warnings &= "{{warning|Item has been flagged as 'Deleted'.}}"
        .TextAfter = Warnings
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Bank Account Suspense Item Imported Transaction (Version 1.00, Last updated 7/04/2020).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="bankAccountSuspenseItem">
  '''  Bank Account Suspense Item to display.
  ''' </param>
  ''' <param name="includeWarnings">
  '''  Indicates whether to include Warnings with the Summary Tables.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Suspense Items wizard and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function BankAccountSuspenseItem_ImportedTransaction(callerScriptInfo As ISScriptExecutionInfo,
                                                                          bankAccountSuspenseItem As finBankAccountSuspenseItem,
                                                                 Optional includeWarnings As Boolean = True,
                                                                 Optional includeActions As Boolean = True,
                                                                 Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim AlwaysInclude As Boolean
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    AlwaysInclude = (finBL.CountryCode = "NZ")
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    With SummaryTableMain
      .WidthHtml = "100%"
      .AutoStripe = True
      .Columns.AddText(12).NoBreakChars = 20

      .AddRowCaptionText("Particulars:", finBL.HtmlEncode(bankAccountSuspenseItem.ImportedParticulars), AlwaysInclude)
      .AddRowCaptionText("Code:", finBL.HtmlEncode(bankAccountSuspenseItem.ImportedCode), AlwaysInclude)
      .AddRowCaptionText("Reference:", finBL.HtmlEncode(bankAccountSuspenseItem.ImportedReference), AlwaysInclude)

      .AddRowCaptionText("Dishonour Reason:", finBL.HtmlEncode(bankAccountSuspenseItem.ImportedDishonourReason))
      .AddRowCaptionText("OP Name:", finBL.HtmlEncode(bankAccountSuspenseItem.ImportedOtherPartyName))
      If Len(bankAccountSuspenseItem.ImportedOtherPartyBankAccountSortCode) <> 0 AndAlso finBL.CurrentUser.Permissions.Allow("Banking.ShowAccountDetails") Then
        .AddRowCaptionText(String.Format("OP {0}:", finBL.HtmlEncode(finBL.CurrentCountry.Terminology(isefinCountryTerminology.BankSortCode))), finBL.HtmlEncode(bankAccountSuspenseItem.ImportedOtherPartyBankAccountSortCodeForDisplay))
      End If
      If Len(bankAccountSuspenseItem.ImportedOtherPartyBankAccountNumber) <> 0 AndAlso finBL.CurrentUser.Permissions.Allow("Banking.ShowAccountDetails") Then
        .AddRowCaptionText("OP Account No:", finBL.HtmlEncode(bankAccountSuspenseItem.ImportedOtherPartyBankAccountNumberForDisplay))
      End If
      If Len(bankAccountSuspenseItem.ImportedSource) <> 0 Then
        If Len(bankAccountSuspenseItem.ImportedSourceDescription) = 0 Then
          .AddRowCaptionText("Source:", finBL.HtmlEncode(bankAccountSuspenseItem.ImportedSource))
        Else
          .AddRowCaptionCodeDescription("Source:", bankAccountSuspenseItem.ImportedSource, bankAccountSuspenseItem.ImportedSourceDescription)
        End If
      End If
      .AddRowCaptionText("Trans Code:", finBL.HtmlEncode(bankAccountSuspenseItem.ImportedTransactionCode))
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Banking Details Summary for Accounts (Version 1.04, Last updated 28/07/2015).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="bankingDetails">
  '''  Banking Details to display.
  ''' </param>
  ''' <param name="account">
  '''  Optionally the Account to substitute special tags from.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Payments page and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function BankingDetails_Summary(callerScriptInfo As ISScriptExecutionInfo,
                                                     bankingDetails As finBankingDetails,
                                            Optional account As finAccount = Nothing,
                                            Optional includeActions As Boolean = True,
                                            Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Return Me.BankingDetails_Summary2(callerScriptInfo, bankingDetails, account, Nothing, True, includeActions, otherParameters)

  End Function

  ''' <summary>
  '''  Banking Details Summary for Accounts.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="bankingDetails">
  '''  Banking Details to display.
  ''' </param>
  ''' <param name="account">
  '''  Optionally the Account to substitute special tags from.
  ''' </param>
  ''' <param name="dateAsAt">
  '''  The date to include Expiry Date warnings. If Nothing the current Date will be used.
  ''' </param>
  ''' <param name="includeWarnings">
  '''  Indicates whether to include Warnings with the Summary Tables.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Payments page and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function BankingDetails_Summary2(callerScriptInfo As ISScriptExecutionInfo,
                                                      bankingDetails As finBankingDetails,
                                             Optional account As finAccount = Nothing,
                                             Optional dateAsAt As Date = Nothing,
                                             Optional includeWarnings As Boolean = True,
                                             Optional includeActions As Boolean = True,
                                             Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' BankingDetails_Summary2
    '
    ' Version: 2.09 (01/07/2024)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    2.05  04/05/2021  ISS                  
    '    2.06  06/09/2021  ISS      J027325   Rebrand Split to Zepto
    '    2.07  26/10/2022  ISS      J029865   Add Zepto NZ
    '    2.08  20/02/2024  ISS      J032155   Add PayTo 
    '    2.09  01/07/2024  ISS      J032289   Add Monoova
    ' #################################################################

    Dim BankDetails As String
    Dim BankingDetailsMasked As finBankingDetails
    Dim Caption As String
    Dim CashRegisterId As String
    Dim Code As String
    Dim CodeResolved As String
    Dim ExpiryCheckDate As Date
    Dim Particulars As String
    Dim ParticularsResolved As String
    Dim PaymentMethod As finPaymentMethodRO
    Dim Reference As String
    Dim ReferenceResolved As String
    Dim strTemp As String
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Date As At
    ExpiryCheckDate = dateAsAt ' Hack so this is more logical, remember we can't change the function signature and rename the parameter
    dateAsAt = finBL.TimeZoneFunctions.GetCurrentDatabaseDate()

    If bankingDetails Is Nothing Then
      PaymentMethod = Nothing
    Else
      PaymentMethod = bankingDetails.PaymentMethod
    End If
    If PaymentMethod Is Nothing Then
      BankingDetailsMasked = Nothing
    Else
      BankingDetailsMasked = bankingDetails.CloneForDisplay
    End If
    CashRegisterId = otherParameters.GetString("CashRegisterId")

    ' Validate Expiry Check Date
    If ExpiryCheckDate = Nothing Then
      ExpiryCheckDate = dateAsAt
    Else
      ExpiryCheckDate = ExpiryCheckDate.Date
    End If

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      .Columns.AddText(16).NoBreakChars = 16
      .Columns.AddText()

      If PaymentMethod Is Nothing Then
        ' No Details
        Warnings &= "{{info|Payment details have not been entered.}}"
      ElseIf Not finBL.CurrentUser.Permissions.Allow("Banking.ShowAccountDetails") Then
        ' No Permission to view
        With .Rows
          .AddCaptionCodeDescription("Pay Method: ", PaymentMethod.PaymentMethodId, PaymentMethod.Description)
        End With
      Else
        With .Rows
          ' General
          .AddCaptionCodeDescription("Pay Method:", PaymentMethod.PaymentMethodId, PaymentMethod.Description)

          ' Optional Cash Register
          If Len(CashRegisterId) <> 0 Then
            If finBL.CashRegisters.Exists(CashRegisterId) Then
              .AddCaptionCodeDescription("Cash Register:", CashRegisterId, finBL.CashRegisters(CashRegisterId).Description)
            Else
              .AddCaptionText("Cash Register:", CashRegisterId)
            End If
          End If

          ' Type-Specific
          Select Case PaymentMethod.PaymentTypeCategory
            Case isefinPaymentTypeCategory.Bank
              ' ----
              ' Bank
              ' ----
              ' Find Bank/ Branch information
              If finBL.SupportedCountries.CurrentSupportedCountry.ValidateBankBranch(BankingDetailsMasked, "") Then
                With BankingDetailsMasked
                  If Len(.BankName) = 0 Then
                    BankDetails = finBL.Runtime.TextUtilities.ListSeparate(", ", .BankNameShort, .BankBranchName)
                  Else
                    BankDetails = finBL.Runtime.TextUtilities.ListSeparate(", ", .BankName & " (" & .BankNameShort & ")", .BankBranchName)
                  End If
                End With
              Else
                BankDetails = ""
              End If

              ' Bank Sort Code and Account Number
              If finBL.CurrentCountry.SupportsBankSortCode Then
                .AddCaptionText(finBL.CurrentCountry.Terminology(isefinCountryTerminology.BankSortCode, True) & ":", BankingDetailsMasked.AccountSortCode)
                If Len(BankDetails) <> 0 Then .AddCaptionText("", BankDetails)
                .AddCaptionText("Account No:", BankingDetailsMasked.AccountNumber)
              Else
                .AddCaptionText("Account No:", BankingDetailsMasked.AccountNumber)
                If Len(BankDetails) <> 0 Then .AddCaptionText("", BankDetails)
              End If

              ' Account Name
              .AddCaptionText("Name:", BankingDetailsMasked.AccountName)

              ' Country-Specific
              Select Case finBL.CountryCode
                Case "NZ"
                  ' Split Reference into Particulars, Code and Reference and Resolve
                  BankingDetailsMasked.Reference_SplitNZ(Particulars, Code, Reference)
                  BankingDetailsMasked.ReferenceResolved_SplitNZ(account, ParticularsResolved, CodeResolved, ReferenceResolved)

                  With .AddCaptionWiki("Particulars:", "**" & Particulars & "**")
                    If Particulars <> ParticularsResolved Then .Cells(1).Value &= String.Format(" --resolves to-- **{0}**", ParticularsResolved)
                  End With
                  With .AddCaptionWiki("Code:", "**" & Code & "**")
                    If Code <> CodeResolved Then .Cells(1).Value &= String.Format(" --resolves to-- **{0}**", CodeResolved)
                  End With
                  With .AddCaptionWiki("Reference:", "**" & Reference & "**")
                    If Reference <> ReferenceResolved Then .Cells(1).Value &= String.Format(" --resolves to-- **{0}**", ReferenceResolved)
                  End With

                Case Else
                  ' Resolve Reference
                  ReferenceResolved = BankingDetailsMasked.ReferenceResolved(account)

                  With .AddCaptionWiki("Reference:", "**" & BankingDetailsMasked.Reference & "**")
                    If BankingDetailsMasked.Reference <> ReferenceResolved Then .Cells(1).Value &= String.Format(" --resolves to-- **{0}**", ReferenceResolved)
                  End With
              End Select

              ' Warnings
              If Not bankingDetails.IsValid(True, False) Then
                Warnings &= "{{Warning|" & finBL.Error.Message(True, True) & "}}"
              End If

            Case isefinPaymentTypeCategory.Cheque
              ' ------
              ' Cheque
              ' ------
              If bankingDetails.PaymentFlowDirection = isefinPaymentMethodPaymentFlowDirection.Incoming Then
                ' Find Bank/ Branch information
                If Len(BankingDetailsMasked.AccountSortCode) <> 0 OrElse Len(BankingDetailsMasked.BankNameShort) <> 0 OrElse Len(BankingDetailsMasked.BankBranchName) <> 0 Then
                  If Len(BankingDetailsMasked.AccountSortCode) = 0 Then
                    Caption = "Bank/Branch"
                    strTemp = ""
                  Else
                    Caption = finBL.SupportedCountries.CurrentSupportedCountry.Terminology(isefinCountryTerminology.BankSortCode)
                    strTemp = BankingDetailsMasked.AccountSortCode
                    If Len(BankingDetailsMasked.BankNameShort) <> 0 OrElse Len(BankingDetailsMasked.BankBranchName) <> 0 Then If Len(strTemp) <> 0 Then strTemp &= "; "
                  End If
                  If Len(BankingDetailsMasked.BankNameShort) <> 0 Then
                    strTemp &= BankingDetailsMasked.BankNameShort
                    If Len(BankingDetailsMasked.BankBranchName) <> 0 Then strTemp &= ", "
                  End If
                  If Len(BankingDetailsMasked.BankBranchName) <> 0 Then
                    strTemp &= BankingDetailsMasked.BankBranchName
                  End If
                Else
                  Caption = "Bank/Branch"
                End If

                .AddCaptionText("Drawer:", BankingDetailsMasked.AccountName)
                .AddCaptionText(Caption & ":", strTemp)
              Else
                .AddCaptionText("Payee:", BankingDetailsMasked.AccountName)
                If Len(BankingDetailsMasked.Reference) <> 0 Then
                  .AddCaptionText(String.Format("{0} No:", finBL.CurrentCountry.Terminology(isefinCountryTerminology.Cheque)), BankingDetailsMasked.Reference)
                End If
              End If

            Case isefinPaymentTypeCategory.CreditCard, isefinPaymentTypeCategory.PosCard
              ' ----------------
              ' Credit/ POS Card
              ' ----------------
              ' Resolve Reference
              ReferenceResolved = BankingDetailsMasked.ReferenceResolved(account)

              .AddCaptionText("Card Type:", PaymentMethod.PaymentType.Description)
              .AddCaptionText("Card No:", BankingDetailsMasked.AccountNumber)
              .AddCaptionText("Card Name:", BankingDetailsMasked.AccountName)
              If BankingDetailsMasked.CardExpiryDate = Nothing Then
                .AddCaptionText("Card Expiry:", "")
              Else
                .AddCaptionText("Card Expiry:", Format(BankingDetailsMasked.CardExpiryDate, "MM/yyyy"))
              End If

              If Len(BankingDetailsMasked.Reference) <> 0 Then
                With .AddCaptionWiki("Reference:", "**" & BankingDetailsMasked.Reference & "**")
                  If BankingDetailsMasked.Reference <> ReferenceResolved Then
                    .Cells(1).Value &= String.Format(" --resolves to-- **{0}**", ReferenceResolved)
                  End If
                End With
              End If

              ' Warnings
              If PaymentMethod.PaymentTypeCategory = isefinPaymentTypeCategory.CreditCard Then
                If Not bankingDetails.IsValid(True, False) Then
                  Warnings &= "{{Warning|" & finBL.Error.Message(True, True) & "}}"
                End If
              End If

              If bankingDetails.CardExpiryDate = Nothing Then
                Warnings &= "{{Warning|Expiry date not entered.}}"
              ElseIf bankingDetails.CardExpiryDate < ExpiryCheckDate Then
                If ExpiryCheckDate > dateAsAt Then
                  Warnings &= "{{Warning|Card will expire before " & finBL.FormatDateLong(ExpiryCheckDate) & ".}}"
                Else
                  Warnings &= "{{Warning|Card has expired.}}"
                End If
              ElseIf bankingDetails.CardExpiryDate < ExpiryCheckDate.AddMonths(2) Then
                Warnings &= "{{Info|Card expires soon.}}"
              End If

            Case isefinPaymentTypeCategory.Ezidebit
              ' --------
              ' Ezidebit
              ' --------
              .AddCaptionText("Ezidebit Customer:", BankingDetailsMasked.AccountNumber)
              .AddCaptionText("Name:", BankingDetailsMasked.AccountName)

              ' Warnings
              If Not bankingDetails.IsValid(False, False) Then
                Warnings &= "{{Warning|" & finBL.Error.Message(True, True) & "}}"
              End If

            Case isefinPaymentTypeCategory.Monoova
              ' -------
              ' Monoova
              ' -------
              ' Find Bank/ Branch information
              If finBL.SupportedCountries.CurrentSupportedCountry.ValidateBankBranch(BankingDetailsMasked, "") Then
                With BankingDetailsMasked
                  If Len(.BankName) = 0 Then
                    BankDetails = finBL.Runtime.TextUtilities.ListSeparate(", ", .BankNameShort, .BankBranchName)
                  Else
                    BankDetails = finBL.Runtime.TextUtilities.ListSeparate(", ", .BankName & " (" & .BankNameShort & ")", .BankBranchName)
                  End If
                End With
              Else
                BankDetails = ""
              End If

              ' Bank Sort Code and Account Number
              If finBL.CurrentCountry.SupportsBankSortCode Then
                .AddCaptionText(finBL.CurrentCountry.Terminology(isefinCountryTerminology.BankSortCode, True) & ":", BankingDetailsMasked.AccountSortCode)
                If Len(BankDetails) <> 0 Then .AddCaptionText("", BankDetails)
                .AddCaptionText("Account No:", BankingDetailsMasked.AccountNumber)
              Else
                .AddCaptionText("Account No:", BankingDetailsMasked.AccountNumber)
                If Len(BankDetails) <> 0 Then .AddCaptionText("", BankDetails)
              End If

              ' Account Name
              .AddCaptionText("Name:", BankingDetailsMasked.AccountName)

              ' Reference
              ReferenceResolved = BankingDetailsMasked.ReferenceResolved(account)
              With .AddCaptionWiki("Reference:", "**" & BankingDetailsMasked.Reference & "**")
                If BankingDetailsMasked.Reference <> ReferenceResolved Then .Cells(1).Value &= String.Format(" --resolves to-- **{0}**", ReferenceResolved)
              End With

              ' Warnings
              If Not bankingDetails.IsValid(True, False) Then
                Warnings &= "{{Warning|" & finBL.Error.Message(True, True) & "}}"
              End If

            Case isefinPaymentTypeCategory.PayTo
              ' -------------
              ' PayTo
              ' -------------
              .AddCaptionText("Agreement Id:", BankingDetailsMasked.ExternalId)

              ' Warnings
              If Not bankingDetails.IsValid(False, False) Then
                Warnings &= "{{Warning|" & finBL.Error.Message(True, True) & "}}"
              End If

            Case isefinPaymentTypeCategory.Split
              ' -------------
              ' Zepto (Split)
              ' -------------
              If finBL.CurrentCountry.SupportsBankSortCode Then
                .AddCaptionText(finBL.CurrentCountry.Terminology(isefinCountryTerminology.BankSortCode, True) & ":", BankingDetailsMasked.AccountSortCode)
              End If
              .AddCaptionText("Account No:", BankingDetailsMasked.AccountNumber)
              .AddCaptionText("Name:", BankingDetailsMasked.AccountName)
              .AddCaptionText("Email:", BankingDetailsMasked.AccountEmail)
              .AddCaptionText("Contact:", BankingDetailsMasked.ExternalId)

              ' Warnings
              If Not bankingDetails.IsValid(False, False) Then
                Warnings &= "{{Warning|" & finBL.Error.Message(True, True) & "}}"
              End If

            Case isefinPaymentTypeCategory.Token
              ' -----
              ' Token
              ' -----
              .AddCaptionText("Token:", BankingDetailsMasked.AccountNumber)
              .AddCaptionText("Name:", BankingDetailsMasked.AccountName)

              ' Country-Specific
              Select Case finBL.CountryCode
                Case "NZ"
                  ' Split Reference into Particulars, Code and Reference and Resolve
                  bankingDetails.Reference_SplitNZ(Particulars, Code, Reference)
                  bankingDetails.ReferenceResolved_SplitNZ(account, ParticularsResolved, CodeResolved, ReferenceResolved)

                  With .AddCaptionWiki("Particulars:", "**" & Particulars & "**")
                    If Particulars <> ParticularsResolved Then .Cells(1).Value &= String.Format(" --resolves to-- **{0}**", ParticularsResolved)
                  End With
                  With .AddCaptionWiki("Code:", "**" & Code & "**")
                    If Code <> CodeResolved Then .Cells(1).Value &= String.Format(" --resolves to-- **{0}**", CodeResolved)
                  End With
                  With .AddCaptionWiki("Reference:", "**" & Reference & "**")
                    If Reference <> ReferenceResolved Then .Cells(1).Value &= String.Format(" --resolves to-- **{0}**", ReferenceResolved)
                  End With

                Case Else
                  ' Resolve Reference
                  ReferenceResolved = BankingDetailsMasked.ReferenceResolved(account)

                  With .AddCaptionWiki("Reference:", "**" & BankingDetailsMasked.Reference & "**")
                    If BankingDetailsMasked.Reference <> ReferenceResolved Then .Cells(1).Value &= String.Format(" --resolves to-- **{0}**", ReferenceResolved)
                  End With
              End Select

              ' Warnings
              If Not bankingDetails.IsValid(False, False) Then
                Warnings &= "{{Warning|" & finBL.Error.Message(True, True) & "}}"
              End If

            Case isefinPaymentTypeCategory.ZeptoNZ
              ' -----------------
              ' Zepto New Zealand
              ' -----------------
              .AddCaptionText("Account No:", BankingDetailsMasked.AccountNumber)
              .AddCaptionText("Name:", BankingDetailsMasked.AccountName)
              .AddCaptionText("Email:", BankingDetailsMasked.AccountEmail)
              .AddCaptionText("Phone:", BankingDetailsMasked.AccountPhone)
              .AddCaptionText("Contact:", BankingDetailsMasked.ExternalId)

              ' Warnings
              If Not bankingDetails.IsValid(False, False) Then
                Warnings &= "{{Warning|" & finBL.Error.Message(True, True) & "}}"
              End If
          End Select
        End With
      End If

      ' Warnings
      If includeWarnings Then
        .TextAfter = Warnings
      End If

      ' Actions
      If includeActions Then
        With .Actions
        End With
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Bank Transaction Summary (Version 2.04, Last updated 20/07/2021).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="bankTransactionView">
  '''  Bank Transaction View to display.
  ''' </param>
  ''' <param name="ShowBatchId">
  '''  Indicates whether to show the Batch Id. Normally only set to True if the Batch Details block is not shown.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Payments page and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function BankTransactionView_TransactionSummary(callerScriptInfo As ISScriptExecutionInfo,
                                                                     bankTransactionView As finBankTransactionView,
                                                            Optional ShowBatchId As Boolean = False,
                                                            Optional includeActions As Boolean = True,
                                                            Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim BatchView As finBatchView
    Dim DateAsAt As Date
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Date As At
    DateAsAt = finBL.TimeZoneFunctions.GetCurrentDatabaseDate()

    ' Cache
    bankTransactionView.GetBatchView(BatchView)

    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Columns.AddText(16)
      .Columns.AddText()

      With .Rows
        .AddCaptionInteger("Id:", bankTransactionView.BankTransactionPk)
        .AddCaptionText("Type:", bankTransactionView.AccountTransactions(0).ElementTypeText)
        If ShowBatchId AndAlso bankTransactionView.BatchHeaderPk <> 0 Then .AddCaptionText("Batch Id:", BatchView.BatchId)
        .AddCaptionText("Source:", bankTransactionView.AccountTransactions(0).SourceText)
        If bankTransactionView.AccountTransactions(0).TransactionTypePk <> 0 Then
          .AddCaptionCodeDescription("Trans Type:", bankTransactionView.AccountTransactions(0).TransactionTypeId, bankTransactionView.AccountTransactions(0).TransactionTypeDescription)
        End If
        .AddCaptionDateTime("Date:", bankTransactionView.Date)
        Select Case bankTransactionView.BankInterfaceStatus
          Case isefinBankTransactionBankInterfaceStatus.NotApplicable
            If bankTransactionView.DateCleared <> Nothing Then
              If bankTransactionView.DateCleared > DateAsAt Then
                .AddCaptionDate("Clearing:", bankTransactionView.DateCleared)
              Else
                .AddCaptionDate("Cleared:", bankTransactionView.DateCleared)
              End If
            End If
          Case Else
            Select Case bankTransactionView.BankInterfaceStatus
              Case isefinBankTransactionBankInterfaceStatus.Success
                .AddCaptionDate("Cleared:", bankTransactionView.BankInterfaceSettlementDate)
            End Select
        End Select
        .AddCaptionText("Reference:", bankTransactionView.TransactionReference)
        If bankTransactionView.BankingDetails.PaymentFlowDirection = isefinPaymentMethodPaymentFlowDirection.Incoming Then
          .AddCaptionCurrency("Value:", -bankTransactionView.Value, True)
        Else
          .AddCaptionCurrency("Value:", bankTransactionView.Value, True)
        End If
        If Len(bankTransactionView.TransactionNotes) <> 0 Then
          .AddCaptionText("Notes:", bankTransactionView.TransactionNotes)
        End If
        .AddCaptionWiki("Created:", finBL.Utilities.GetUserAndDateWikiText("", bankTransactionView.CreatedUserPk, bankTransactionView.CreatedDate))
        If bankTransactionView.CreatedUserPk <> bankTransactionView.UpdatedUserPk OrElse bankTransactionView.CreatedDate <> bankTransactionView.UpdatedDate Then
          .AddCaptionWiki("Updated:", finBL.Utilities.GetUserAndDateWikiText("", bankTransactionView.UpdatedUserPk, bankTransactionView.UpdatedDate))
        End If

        ' Get Warnings
        Select Case bankTransactionView.BankInterfaceStatus
          Case isefinBankTransactionBankInterfaceStatus.NotApplicable
            If bankTransactionView.DateCleared <> Nothing AndAlso bankTransactionView.DateCleared > DateAsAt Then
              Warnings &= "{{warning|Funds not yet cleared.}}"
            End If
        End Select
        If bankTransactionView.ReversePk <> 0 Then
          If bankTransactionView.ReversePk > bankTransactionView.BankTransactionPk Then
            Warnings &= "{{warning|" & String.Format("Reversed by Bank Transaction Id {0}.", bankTransactionView.ReversePk) & "}}"
          Else
            Warnings &= "{{warning|" & String.Format("Reversed Bank Transaction Id {0}.", bankTransactionView.ReversePk) & "}}"
          End If
        End If
        If bankTransactionView.Fee <> 0 Then
          If Len(Warnings) <> 0 Then Warnings &= vbNewLine
          Warnings &= "{{info|" & String.Format("There was an associated fee of {0}.", finBL.FormatCurrency(bankTransactionView.Fee, True)) & "}}"
        End If
      End With

      ' Warnings
      .TextAfter = Warnings
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Bank Transaction Payments Summary.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="bankTransactionView">
  '''  Bank Transaction View to display.
  ''' </param>
  ''' <param name="showBankAccount">
  '''  Indicates whether to show the Bank Account the Transaction relates to.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Payments page and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function BankTransactionView_PaymentDetails(callerScriptInfo As ISScriptExecutionInfo,
                                                                 bankTransactionView As finBankTransactionView,
                                                        Optional showBankAccount As Boolean = False,
                                                        Optional includeActions As Boolean = True,
                                                        Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' BankTransactionView_PaymentDetails
    '
    ' Version: 2.09 (01/07/2024)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    2.04  03/08/2021  ISS      J027100   Edit Payment Details now available in Web Interfaces 
    '    2.05  06/09/2021  ISS      J027325   Rebrand Split to Zepto
    '    2.06  26/10/2022  ISS      J029865   Add Zepto NZ
    '    2.07  24/08/2022  ISS      J031120   Add Zepto AU/ NZ "Reference"
    '    2.08  20/02/2024  ISS      J032155   Add PayTo 
    '    2.09  01/07/2024  ISS      J032289   Add Monoova 
    ' #################################################################

    Dim BankingDetails As finBankingDetails
    Dim Caption As String
    Dim Code As String
    Dim Particulars As String
    Dim Reference As String
    Dim strTemp As String
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Bank Details (potentially masked)
    BankingDetails = bankTransactionView.BankingDetails.CloneForDisplay()

    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Columns.AddText(16).NoBreakChars = 16
      .Columns.AddText()

      ' Warnings
      Warnings = ""

      With .Rows
        ' Bank Account posted to
        If showBankAccount AndAlso finBL.CurrentUser.Permissions.Allow("Banking.ShowAccountDetails") Then
          .AddCaptionCodeDescription("Bank:", bankTransactionView.BankAccountId, bankTransactionView.BankAccountDescription)
        End If

        ' Payment Method
        .AddCaptionCodeDescription("Pay Method:", bankTransactionView.BankingDetails.PaymentMethodId, bankTransactionView.BankingDetails.PaymentMethodDescription)

        ' Optional Cash Register
        If Len(bankTransactionView.CashRegisterId) <> 0 Then
          .AddCaptionCodeDescription("Cash Register:", bankTransactionView.CashRegisterId, bankTransactionView.CashRegisterDescription)
        End If

        ' Main Banking Details
        If finBL.CurrentUser.Permissions.Allow("Banking.ShowAccountDetails") Then
          Select Case bankTransactionView.BankingDetails.PaymentTypeCategory
            Case isefinPaymentTypeCategory.Bank
              ' Bank

              ' Bank Sort Code
              If finBL.CurrentCountry.SupportsBankSortCode Then
                .AddCaptionText(finBL.CurrentCountry.Terminology(isefinCountryTerminology.BankSortCode, True) & ":", BankingDetails.AccountSortCode)
              End If

              ' Account Number and Name
              .AddCaptionText("Account No:", BankingDetails.AccountNumber)
              .AddCaptionText("Name:", BankingDetails.AccountName)

              ' Country-Specific
              Select Case finBL.CountryCode
                Case "NZ"
                  ' Split Reference into Particulars, Code and Reference
                  BankingDetails.Reference_SplitNZ(Particulars, Code, Reference)

                  .AddCaptionText("Particulars:", Particulars)
                  .AddCaptionText("Code:", Code)
                  .AddCaptionText("Reference:", Reference)

                Case Else
                  .AddCaptionText("Reference:", BankingDetails.Reference)
              End Select

            Case isefinPaymentTypeCategory.Cheque
              ' Cheque
              If BankingDetails.PaymentFlowDirection = isefinPaymentMethodPaymentFlowDirection.Incoming Then
                .AddCaptionText("Drawer:", BankingDetails.AccountName)
              Else
                .AddCaptionText("Payee:", BankingDetails.AccountName)
              End If

              ' Bank/ Branch information
              If Len(BankingDetails.AccountSortCode) <> 0 OrElse Len(BankingDetails.BankNameShort) <> 0 OrElse Len(BankingDetails.BankBranchName) <> 0 Then
                If Len(BankingDetails.AccountSortCode) = 0 Then
                  Caption = "Bank/Branch"
                  strTemp = ""
                Else
                  Caption = finBL.SupportedCountries.CurrentSupportedCountry.Terminology(isefinCountryTerminology.BankSortCode)
                  strTemp = BankingDetails.AccountSortCode
                  If Len(BankingDetails.BankNameShort) <> 0 OrElse Len(BankingDetails.BankBranchName) <> 0 Then If Len(strTemp) <> 0 Then strTemp &= "; "
                End If
                If Len(BankingDetails.BankNameShort) <> 0 Then
                  strTemp &= BankingDetails.BankNameShort
                  If Len(BankingDetails.BankBranchName) <> 0 Then strTemp &= ", "
                End If
                If Len(BankingDetails.BankBranchName) <> 0 Then
                  strTemp &= BankingDetails.BankBranchName
                End If

                .AddCaptionText(Caption & ":", strTemp)
              End If

              ' Cheque Number
              If Len(BankingDetails.Reference) <> 0 Then .AddCaptionText(String.Format("{0} No:", finBL.CurrentCountry.Terminology(isefinCountryTerminology.Cheque)), BankingDetails.Reference)

              ' Outwards Cheque
              If finBL.PaymentMethods.ItemByPk(BankingDetails.PaymentMethodPk).IsOutwardsCheque Then
                ' Printed
                If bankTransactionView.PrintedUserPk <> 0 Then
                  .AddCaptionWiki("Printed:", finBL.Utilities.GetUserAndDateWikiText("", bankTransactionView.PrintedUserPk, bankTransactionView.PrintedDate))
                End If

                ' Printed Status
                Select Case bankTransactionView.PrintedStatus
                  Case isefinBankTransactionPrintedStatus.NotPrinted
                    If Len(Warnings) <> 0 Then Warnings &= vbNewLine
                    Warnings &= "{{info|" & finBL.CurrentCountry.Terminology(isefinCountryTerminology.Cheque) & " has NOT been printed.}}"
                  Case isefinBankTransactionPrintedStatus.Printed
                End Select
              End If

            Case isefinPaymentTypeCategory.CreditCard, isefinPaymentTypeCategory.PosCard
              ' Credit/ POS Card
              .AddCaptionText("Card Type:", BankingDetails.PaymentType.Description)
              .AddCaptionText("Card No:", BankingDetails.AccountNumber)
              .AddCaptionText("Card Name:", BankingDetails.AccountName)
              If BankingDetails.CardExpiryDate = Nothing Then
                .AddCaptionText("Card Expiry:", "")
              Else
                .AddCaptionText("Card Expiry:", Format(BankingDetails.CardExpiryDate, "MM/yyyy"))
              End If
              .AddCaptionText("Reference:", BankingDetails.Reference)

            Case isefinPaymentTypeCategory.Ezidebit
              ' Ezidebit Customer
              .AddCaptionText("Name:", BankingDetails.AccountName)
              .AddCaptionText("Ezidebit Customer:", BankingDetails.ExternalId)

            Case isefinPaymentTypeCategory.Monoova
              ' Monoova

              ' Bank Sort Code
              If finBL.CurrentCountry.SupportsBankSortCode Then
                .AddCaptionText(finBL.CurrentCountry.Terminology(isefinCountryTerminology.BankSortCode, True) & ":", BankingDetails.AccountSortCode)
              End If

              ' Account Number and Name
              .AddCaptionText("Account No:", BankingDetails.AccountNumber)
              .AddCaptionText("Name:", BankingDetails.AccountName)

              ' Reference
              .AddCaptionText("Reference:", BankingDetails.Reference)

            Case isefinPaymentTypeCategory.PayTo
              ' PayTo
              .AddCaptionText("Agreement Id:", BankingDetails.ExternalId)
              If Len(BankingDetails.Reference) <> 0 Then .AddCaptionText("Reference:", BankingDetails.Reference)
              If Len(BankingDetails.Description) <> 0 Then .AddCaptionText("Description:", BankingDetails.Description)

            Case isefinPaymentTypeCategory.Split
              ' Zepto (Split)
              If finBL.CurrentCountry.SupportsBankSortCode Then
                .AddCaptionText(finBL.CurrentCountry.Terminology(isefinCountryTerminology.BankSortCode, True) & ":", BankingDetails.AccountSortCode)
              End If
              .AddCaptionText("Account No:", BankingDetails.AccountNumber)
              .AddCaptionText("Name:", BankingDetails.AccountName)
              .AddCaptionText("Email:", BankingDetails.AccountEmail)
              .AddCaptionText("Contact:", BankingDetails.ExternalId)
              If Len(BankingDetails.Reference) <> 0 Then .AddCaptionText("Reference:", BankingDetails.Reference)

            Case isefinPaymentTypeCategory.Token
              ' Account Token and Name
              .AddCaptionText("Token:", BankingDetails.AccountNumber)
              .AddCaptionText("Name:", BankingDetails.AccountName)

              ' Reference
              Select Case finBL.CountryCode
                Case "NZ"
                  ' Split Reference into Particulars, Code and Reference
                  BankingDetails.Reference_SplitNZ(Particulars, Code, Reference)

                  .AddCaptionText("Particulars:", Particulars)
                  .AddCaptionText("Code:", Code)
                  .AddCaptionText("Reference:", Reference)

                Case Else
                  .AddCaptionText("Reference:", BankingDetails.Reference)
              End Select

            Case isefinPaymentTypeCategory.ZeptoNZ
              ' Zepto New Zealand
              .AddCaptionText("Account No:", BankingDetails.AccountNumber)
              .AddCaptionText("Name:", BankingDetails.AccountName)
              .AddCaptionText("Email:", BankingDetails.AccountEmail)
              .AddCaptionText("Phone:", BankingDetails.AccountPhone)
              .AddCaptionText("Contact:", BankingDetails.ExternalId)
              If Len(BankingDetails.Reference) <> 0 Then .AddCaptionText("Reference:", BankingDetails.Reference)
          End Select
        End If
      End With

      ' Actions
      If includeActions Then
        With .Actions
          ' Print Receipt/Advice
          If bankTransactionView.ReversePk = 0 Then
            Select Case bankTransactionView.ElementType
              Case isefinElementType.PaymentReceived
                ' Payment Receipt
                If finBL.CurrentUser.Permissions.Allow("Banking.PaymentReceiptReprint") Then
                  If bankTransactionView.AccountTransactions.Item(0).Value < 0 AndAlso finBL.Documents.ExistsPk(finBL.AccountTypes.ItemByPk(bankTransactionView.AccountTransactions.Item(0).AccountTypePk).PaymentReceiptDocumentPk) Then
                    .AddApplicationShortcutUrl("Document", "Print Receipt", String.Format("Document?id={0}&BankTransactionPk={1}", finBL.AccountTypes.ItemByPk(bankTransactionView.AccountTransactions.Item(0).AccountTypePk).PaymentReceiptDocumentId, bankTransactionView.BankTransactionPk)).ShowInWebInterfaces = True
                  End If
                End If

              Case isefinElementType.Refund
                ' Refund Advice
                If bankTransactionView.AccountTransactions.Item(0).ReversePk = 0 AndAlso bankTransactionView.AccountTransactions.Item(0).Value > 0 AndAlso finBL.Documents.ExistsPk(finBL.AccountTypes.ItemByPk(bankTransactionView.AccountTransactions.Item(0).AccountTypePk).RefundAdviceDocumentPk) Then
                  .AddApplicationShortcutUrl("Document", "Print Refund Advice", String.Format("Document?id={0}&BankTransactionPk={1}", finBL.AccountTypes.ItemByPk(bankTransactionView.AccountTransactions.Item(0).AccountTypePk).RefundAdviceDocumentId, bankTransactionView.BankTransactionPk))
                End If

              Case isefinElementType.Withdrawal
                ' Withdrawal Advice
                If bankTransactionView.AccountTransactions.Item(0).ReversePk = 0 AndAlso bankTransactionView.AccountTransactions.Item(0).Value > 0 AndAlso finBL.Documents.ExistsPk(finBL.AccountTypes.ItemByPk(bankTransactionView.AccountTransactions.Item(0).AccountTypePk).WithdrawalAdviceDocumentPk) Then
                  .AddApplicationShortcutUrl("Document", "Print Withdrawal Advice", String.Format("Document?id={0}&BankTransactionPk={1}", finBL.AccountTypes.ItemByPk(bankTransactionView.AccountTransactions.Item(0).AccountTypePk).WithdrawalAdviceDocumentId, bankTransactionView.BankTransactionPk))
                End If
            End Select
          End If

          ' Edit Bank Transaction Link (close form if editing from Bank Transaction View form since this has no way of refreshing itself)
          If bankTransactionView.CanEditPaymentDetails Then
            .AddFormShow("BankTransactionEdit", "Edit Payment Details", "BankTransactionEdit", , String.Format("&id={0}&closeActiveForm={1}", bankTransactionView.BankTransactionPk, IIf(callerScriptInfo.FormKey = "BankTransactionView", True, False))).ShowInWebInterfaces = True
          End If
        End With
      End If

      ' Warnings
      .TextAfter = Warnings
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Bank Transaction Accounts Summary (Version 2.01, Last updated 11/05/2021).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="bankTransactionView">
  '''  Bank Transaction View to display.
  ''' </param>
  ''' <param name="includeFormShowHyperlink">
  '''  Indicates whether to include a hyperlink to show the form, e.g., when the Contact Address is linked to a Client.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Payments page and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None.</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function BankTransactionView_Accounts(callerScriptInfo As ISScriptExecutionInfo,
                                                           bankTransactionView As finBankTransactionView,
                                                  Optional includeFormShowHyperlink As Boolean = True,
                                                  Optional includeActions As Boolean = True,
                                                  Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim BankTransactionAccountTransaction As finBankTransactionAccountTransaction
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim TotalValue As Decimal
    Dim Value As Decimal
    Dim Warnings As String

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .AutoStripe = True

      ' Columns
      With .Columns
        .AddInteger("Id")
        .AddDate("Date")
        .AddCode("Type", 5)
        .AddCode("Account", 10)
        .AddText("Name")
        .AddCode("Element", 5)
        .AddCurrency("Value")
        .AddText("Notes")
      End With

      TotalValue = 0
      For Each BankTransactionAccountTransaction In bankTransactionView.AccountTransactions
        If bankTransactionView.BankingDetails.PaymentFlowDirection = isefinPaymentMethodPaymentFlowDirection.Incoming Then
          Value = -BankTransactionAccountTransaction.Value
        Else
          Value = BankTransactionAccountTransaction.Value
        End If

        With .Rows.Add().Cells
          .AddInteger(BankTransactionAccountTransaction.Pk)
          .AddDate(BankTransactionAccountTransaction.Date)
          .AddText(BankTransactionAccountTransaction.AccountTypeId)
          If includeFormShowHyperlink Then
            With .AddText(BankTransactionAccountTransaction.AccountId)
              .HyperlinkSetFormShow("Accounts", BankTransactionAccountTransaction.AccountId)
            End With
          Else
            .AddText(BankTransactionAccountTransaction.AccountId)
          End If
          .AddText(BankTransactionAccountTransaction.AccountName)
          .AddText(BankTransactionAccountTransaction.ElementId)
          .AddCurrency(Value)
          .AddText(BankTransactionAccountTransaction.Notes)
        End With

        TotalValue += Value
      Next

      ' Total
      With .Rows.Add(iseSummaryTableRowClass.FooterBold).Cells
        With .AddText("Total")
          .ColSpan = 6
          .TextAlign = iseSummaryTableCellTextAlign.Left
        End With
        .AddCurrency(TotalValue, True)
        .AddText("")
      End With

      ' Warnings
      .TextAfter = Warnings
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Bank Transaction Batch Details (Version 2.00, Last updated 08/12/2015).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="bankTransactionView">
  '''  Bank Transaction View to display.
  ''' </param>
  ''' <param name="showScriptId">
  '''  Indicates whether to a Script was involved in the Batch.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Payments page and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function BankTransactionView_BatchDetails(callerScriptInfo As ISScriptExecutionInfo,
                                                               bankTransactionView As finBankTransactionView,
                                                      Optional showScriptId As Boolean = True,
                                                      Optional includeActions As Boolean = True,
                                                      Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim BatchView As finBatchView
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    bankTransactionView.GetBatchView(BatchView)
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Columns.AddText(16).NoBreakChars = 16
      .Columns.AddText()

      With .Rows
        If bankTransactionView.BatchHeaderPk = 0 Then
          Warnings &= "{{info|Transaction is not part of a batch.}}"
        Else
          .AddCaptionText("Batch Id:", BatchView.BatchId)
          .AddCaptionText("Entry Source:", BatchView.EntrySourceText)
          If bankTransactionView.Source <> BatchView.Source Then .AddCaptionText("Source:", BatchView.SourceText)
          .AddCaptionCodeDescription("Trans Type:", BatchView.TransactionTypeId, BatchView.TransactionTypeDescription)
          If Len(BatchView.Notes) <> 0 Then .AddCaptionText("Notes:", BatchView.Notes)
          .AddCaptionWiki("Created:", finBL.Utilities.GetUserAndDateWikiText("", BatchView.CreatedUserPk, BatchView.CreatedDate))
          If BatchView.CreatedUserPk <> BatchView.UpdatedUserPk OrElse BatchView.CreatedDate <> BatchView.UpdatedDate Then
            .AddCaptionWiki("Updated:", finBL.Utilities.GetUserAndDateWikiText("", BatchView.UpdatedUserPk, BatchView.UpdatedDate))
          End If
          If showScriptId AndAlso Len(BatchView.ScriptId) <> 0 Then
            Warnings &= "{{info|Script '" & BatchView.ScriptId & "' ran during the Import of this batch.}}"
          End If
        End If
      End With

      ' Warnings
      .TextAfter = Warnings
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Bank Transaction Lodgement Details (Version 2.01, Last updated 13/07/2021).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="bankTransactionView">
  '''  Bank Transaction View to display.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Payments page and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None.</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function BankTransactionView_LodgementDetails(callerScriptInfo As ISScriptExecutionInfo,
                                                                   bankTransactionView As finBankTransactionView,
                                                          Optional includeActions As Boolean = True,
                                                          Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Columns.AddText(16).NoBreakChars = 16
      .Columns.AddText()

      With .Rows
        If bankTransactionView.BankExportPk = 0 Then
          Warnings &= "{{info|Not yet lodged.}}"
        ElseIf Not bankTransactionView.BankExportView.IsLodgement Then
          Warnings &= "{{info|This Transaction batch is not a Lodgement.}}"
        Else
          .AddCaptionDate("Date:", bankTransactionView.BankExportView.Date)
          .AddCaptionText("Export Id:", bankTransactionView.BankExportView.BankExportId)
          .AddCaptionCodeDescription("Service:", bankTransactionView.BankExportView.BankAccountServiceId, bankTransactionView.BankExportView.BankAccountServiceDescription)
          .AddCaptionWiki("Created:", finBL.Utilities.GetUserAndDateWikiText("", bankTransactionView.BankExportView.CreatedUserPk, bankTransactionView.BankExportView.CreatedDate))
        End If
      End With

      ' Warnings
      .TextAfter = Warnings
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Bank Transaction Export Summary.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="bankTransactionView">
  '''  Bank Transaction View to display.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Payments page and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''    <item><code>History</code><description>Service Log History.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None.</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function BankTransactionView_ExportDetails(callerScriptInfo As ISScriptExecutionInfo,
                                                                bankTransactionView As finBankTransactionView,
                                                       Optional includeActions As Boolean = True,
                                                       Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' BankTransactionView_ExportDetails
    '
    ' Version: 2.11 (10/09/2024)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    2.04  21/07/2021  ISS                  
    '    2.05  11/11/2021  ISS      J009640   Added specific warning if Transaction Reversed
    '    2.06  19/09/2022  ISS      J029321   Add "Reverse" button for Bank Interface
    '    2.07  26/10/2022  ISS      J029865   Add Zepto NZ
    '    2.08  27/09/2023  ISS      J032124   Respect "ServiceLogs.View" permission
    '    2.09  20/02/2024  ISS      J032155   Add PayTo 
    '    2.10  03/07/2024  ISS      J032289   Add Monoova
    '    2.11  10/09/2024  ISS      J034245   Allow Abort if the status is stuck on 'sending'
    ' #################################################################

    Dim ServiceLog As ISServiceLog
    Dim ServiceLogs As ISServiceLogs
    Dim SummaryTableHistory As ISSummaryTable
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableHistory = finBL.CreateSummaryTable()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Columns.AddText(16).NoBreakChars = 16
      .Columns.AddText()

      With .Rows
        Select Case bankTransactionView.BankInterfaceStatus
          Case isefinBankTransactionBankInterfaceStatus.NotApplicable
            If bankTransactionView.BankExportView.IsLodgement Then
              Warnings &= "{{info|This Transaction batch is a Lodgement.}}"
            ElseIf bankTransactionView.BankExportPk = 0 Then
              If bankTransactionView.PrintedStatus = isefinBankTransactionPrintedStatus.Printed Then
                Warnings &= "{{info|Transaction has been manually exported.}}"
              ElseIf bankTransactionView.IsImported Then
                Warnings &= "{{info|Transaction was imported.}}"
              ElseIf bankTransactionView.ReversePk <> 0 Then
                Warnings &= "{{info|Transaction is reversed and will not be exported.}}"
              Else
                Warnings &= "{{info|Transaction has not been exported.}}"
              End If
            Else
              .AddCaptionDate("Date:", bankTransactionView.BankExportView.Date)
              .AddCaptionText("Export Id:", bankTransactionView.BankExportView.BankExportId)
              .AddCaptionCodeDescription("Service:", bankTransactionView.BankExportView.BankAccountServiceId, bankTransactionView.BankExportView.BankAccountServiceDescription)
              .AddCaptionWiki("Created:", finBL.Utilities.GetUserAndDateWikiText("", bankTransactionView.BankExportView.CreatedUserPk, bankTransactionView.BankExportView.CreatedDate))
            End If

          Case Else
            ' Get Service Logs
            ServiceLogs = bankTransactionView.BankInterfaceServiceLogs()
            If ServiceLogs IsNot Nothing AndAlso ServiceLogs.Count <> 0 Then
              ServiceLog = bankTransactionView.BankInterfaceServiceLogs(0)
            End If

            If ServiceLog Is Nothing Then
              Select Case bankTransactionView.BankingDetails.PaymentTypeCategory
                Case isefinPaymentTypeCategory.Ezidebit, isefinPaymentTypeCategory.Monoova, isefinPaymentTypeCategory.PayTo, isefinPaymentTypeCategory.Split, isefinPaymentTypeCategory.ZeptoNZ
                  .AddCaptionText("Service:", bankTransactionView.BankingDetails.PaymentTypeCategoryText)
              End Select
            Else
              .AddCaptionText("Service:", ServiceLog.ServiceId)
              .AddCaptionWiki("Sent:", finBL.Utilities.GetUserAndDateWikiText("", ServiceLog.CreatedUserPk, ServiceLog.CreatedDate))
            End If
            If Len(bankTransactionView.BankInterfaceReference) <> 0 Then .AddCaptionText("Reference:", bankTransactionView.BankInterfaceReference)
            With .AddCaptionText("Status:", bankTransactionView.BankInterfaceStatusText)
              Select Case bankTransactionView.BankInterfaceStatus
                Case isefinBankTransactionBankInterfaceStatus.Aborted
                  .BackgroundColour = "gold"
                Case isefinBankTransactionBankInterfaceStatus.Cancelled
                  .BackgroundColour = "plum"
                Case isefinBankTransactionBankInterfaceStatus.Failed, isefinBankTransactionBankInterfaceStatus.SendFailed
                  .BackgroundColour = "pink"
                Case isefinBankTransactionBankInterfaceStatus.Pending, isefinBankTransactionBankInterfaceStatus.Queued
                  .BackgroundColour = "orange"
                Case isefinBankTransactionBankInterfaceStatus.Success
                  .BackgroundColour = "lightgreen"
              End Select
            End With
            If bankTransactionView.BankInterfaceSettlementDate <> Nothing Then
              .AddCaptionDate("Settlement Date:", bankTransactionView.BankInterfaceSettlementDate)
              .AddCaptionText("Settlement Reference:", bankTransactionView.BankInterfaceSettlementReference)
            End If

            ' Actions
            If includeActions Then
              With SummaryTableMain.Actions
                If bankTransactionView.CanSendViaBankInterface Then
                  If ServiceLog Is Nothing Then
                    .AddApplicationShortcutUrl("Send", "Send", String.Format("App://Global?Type=BankingInterface.Send&BankTransactionPk={0}", bankTransactionView.BankTransactionPk), True).ShowInWebInterfaces = True
                  Else
                    .AddApplicationShortcutUrl("Resend", "Resend", String.Format("App://Global?Type=BankingInterface.Send&BankTransactionPk={0}", bankTransactionView.BankTransactionPk), True).ShowInWebInterfaces = True

                    If bankTransactionView.CanReverse Then
                      .AddApplicationShortcutUrl("Reverse", "Reverse", String.Format("App://FormShow?form=BankTransactionReverse&id={0}", bankTransactionView.BankTransactionPk), True).ShowInWebInterfaces = True
                    End If
                  End If
                End If

                If ServiceLog IsNot Nothing Then
                  If ServiceLog.ResponseStatus = iseServiceLogResponseStatus.InProgress Then
                    If finBL.CurrentUser.Permissions.Allow("Banking.BankInterface.Requests.Update") Then
                      .AddApplicationShortcutUrl("UpdateStatus", "Update Status", String.Format("App://Global?Type=BankingInterface.UpdateStatus&ServiceLogPk={0}", ServiceLog.Pk), True).ShowInWebInterfaces = True
                    End If
                    If bankTransactionView.CanCancelViaBankInterface Then
                      .AddApplicationShortcutUrl("Cancel", "Cancel", String.Format("App://Global?Type=BankingInterface.Cancel&ServiceLogPk={0}", ServiceLog.Pk), True).ShowInWebInterfaces = True
                    End If
                  End If
                End If

                ' Stuck at "Sending" Status
                If bankTransactionView.BankInterfaceStatus = isefinBankTransactionBankInterfaceStatus.Sending Then
                  If finBL.CurrentUser.Permissions.Allow("Banking.BankInterface.Requests.Abort") Then
                    .AddApplicationShortcutUrl("Abort", "Abort", String.Format("App://Global?Type=BankingInterface.Abort&BankTransactionPk={0}", bankTransactionView.BankTransactionPk), True).ShowInWebInterfaces = True
                  End If
                End If
              End With
            End If

            ' Warnings
            Select Case bankTransactionView.BankInterfaceStatus
              Case isefinBankTransactionBankInterfaceStatus.Sending, isefinBankTransactionBankInterfaceStatus.Failed
                Warnings &= "{{warning|" & String.Format("Processing Status '{0}'.", bankTransactionView.BankInterfaceStatusText) & "|true}}"
              Case isefinBankTransactionBankInterfaceStatus.SendFailed
                Warnings &= "{{warning|" & String.Format("Processing Status '{0}'.<br>Please review Service Logs and try again.", bankTransactionView.BankInterfaceStatusText) & "|true}}"

                If ServiceLog IsNot Nothing AndAlso Len(ServiceLog.FailedReason) <> 0 Then
                  Warnings &= "{{info|Failed reason '" & ServiceLog.FailedReason & "'}}"
                End If
            End Select
        End Select
      End With

      ' Warnings
      .TextAfter = Warnings
    End With

    If ServiceLogs IsNot Nothing AndAlso ServiceLogs.Count <> 0 Then
      With SummaryTableHistory
        ' Initialise
        .TableClass = iseSummaryTableClass.TabularData

        .TextBefore = "&nbsp;"

        ' Columns
        With .Columns
          .AddText("Service Log")
          .AddDate("Date")
          .AddText("User")
          .AddText("Type")
          .AddText("Status")
        End With

        ' Rows
        With .Rows
          For Each ServiceLog In ServiceLogs
            With .Add
              If Len(ServiceLog.ExStatusHtmlColour) <> 0 Then
                .BackgroundColour = ServiceLog.ExStatusHtmlColour
                If finBL.Runtime.ColourUtilities.HtmlColourIsDark(ServiceLog.ExStatusHtmlColour) Then .ForegroundColour = "white"
              End If
              With .Cells
                With .AddText(CStr(ServiceLog.Pk))
                  If finBL.CurrentUser.Permissions.Allow("ServiceLogs.View") Then .HyperlinkSetFormShow("ServiceLog", CStr(ServiceLog.Pk))
                End With
                .AddDateTime(ServiceLog.CreatedDate,, True)
                .AddCodeDescription(ServiceLog.CreatedUserPk, finBL.Users)
                .AddText(ServiceLog.ProductId)
                .AddText(ServiceLog.ExStatus).Tooltip = ServiceLog.ExStatusTooltip
              End With
            End With
          Next
        End With
      End With
    End If

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)
    If SummaryTableHistory.Rows.Count <> 0 Then SummaryTables.Add("History", SummaryTableHistory)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Bank Transaction Audit Summary (Version 2.00, Last updated 08/12/2015).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="bankTransactionView">
  '''  Bank Transaction View to display.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Payments page and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None.</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function BankTransactionView_AuditDetails(callerScriptInfo As ISScriptExecutionInfo,
                                                               bankTransactionView As finBankTransactionView,
                                                      Optional includeActions As Boolean = True,
                                                      Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim AuditItem As finObjectAuditItem
    Dim Index As Integer
    Dim j As Integer
    Dim SummaryTables As ISSummaryTables
    Dim SummaryTablesAudit As ISSummaryTables
    Dim TableId As String

    ' Initialise
    SummaryTables = finBL.CreateSummaryTables()

    For Each AuditItem In bankTransactionView.AuditItems
      ' Get Audit Summary Tables
      SummaryTablesAudit = AuditItem.GetObjectAuditItemPreview_Details()

      ' Append Tables with unique Table Ids
      Index += 1
      For j = 0 To SummaryTablesAudit.Count - 1
        TableId = String.Format("Audit_{0}_{1}", Index, j + 1)
        SummaryTables.Add(TableId, SummaryTablesAudit.ItemByIndex(j))

        With SummaryTablesAudit.ItemByIndex(j)
          ' Heading (first table only)
          If j = 0 Then
            .Caption = String.Format("{0} on {1}", AuditItem.UserId, finBL.FormatDateTimeLong(AuditItem.Date))
          Else
            .Caption = ""
          End If

          ' Normalise columns (assuming there are 3, i.e., showing kvl information)
          If .Columns.Count = 3 Then
            With .Columns(0)
              .WidthChars = 30
              .NoBreakChars = 30
            End With
            With .Columns(1)
              .WidthChars = 30
            End With
            With .Columns(2)
              .WidthChars = 30
            End With
          End If
        End With
      Next
    Next

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Bank Transaction Import Summary (Version 2.00, Last updated 07/12/2015).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="bankTransactionView">
  '''  Bank Transaction View to display.
  ''' </param>
  ''' <param name="includeFormShowHyperlink">
  '''  Indicates whether to include a hyperlink to show the form, e.g., when the Contact Address is linked to a Client.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Payments page and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None.</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function BankTransactionView_ImportDetails(callerScriptInfo As ISScriptExecutionInfo,
                                                                bankTransactionView As finBankTransactionView,
                                                       Optional includeFormShowHyperlink As Boolean = True,
                                                       Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    If Not bankTransactionView.IsImported Then
      Warnings &= "{{info|Transaction was not imported.}}"
    Else
      If finBL.CurrentUser.Permissions.Allow("Banking.ShowAccountDetails") Then
        SummaryTableMain = finBL.Utilities.KeyValueListToSummaryTable(bankTransactionView.ImportedDetailsForDisplay, False)
      End If
    End If

    ' Warnings
    SummaryTableMain.TextAfter = Warnings

    ' Add Summary Tables
    If SummaryTableMain.HasData Then SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  ''' Batch Bank Entry Item Imported Transaction(Version 2.01, Last updated 12/05/2021).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="batchBankTransaction">
  '''  Batch Bank Transaction to display.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Bank Entry page and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function BatchBankTransaction_ImportedTransaction(callerScriptInfo As ISScriptExecutionInfo,
                                                                       batchBankTransaction As finBatchBankTransaction,
                                                              Optional includeActions As Boolean = True,
                                                              Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables


    Dim BankMatchAction As String
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      .Columns.AddText(16)
      .Columns.AddText()

      Warnings = ""

      ' Imported Details
      With .Rows
        If Len(batchBankTransaction.ImportedSource) <> 0 Then
          If Len(batchBankTransaction.ImportedSourceDescription) = 0 Then
            .AddCaptionText("Source:", batchBankTransaction.ImportedSource)
          Else
            .AddCaptionCodeDescription("Source:", batchBankTransaction.ImportedSource, batchBankTransaction.ImportedSourceDescription)
          End If
        End If
        If Len(batchBankTransaction.ImportedTransactionCode) <> 0 Then
          .AddCaptionText("Trans Code:", batchBankTransaction.ImportedTransactionCode)
        End If
        If Len(batchBankTransaction.ImportedDishonourReason) <> 0 Then
          .AddCaptionText("Dish Reason:", batchBankTransaction.ImportedDishonourReason)
        End If
        .AddCaptionDate("Date:", batchBankTransaction.ImportedDate)
        If Len(batchBankTransaction.ImportedOtherPartyName) <> 0 Then
          .AddCaptionText("Other Party:", batchBankTransaction.ImportedOtherPartyName)
        End If
        If finBL.CurrentUser.Permissions.Allow("Banking.ShowAccountDetails") Then
          If Len(batchBankTransaction.ImportedOtherPartyBankAccountSortCode) <> 0 Then
            .AddCaptionText(finBL.CurrentCountry.Terminology(isefinCountryTerminology.BankSortCode) & ":", batchBankTransaction.ImportedOtherPartyBankAccountSortCodeForDisplay)
          End If
          If Len(batchBankTransaction.ImportedOtherPartyBankAccountNumber) <> 0 Then
            Select Case batchBankTransaction.BankingDetails.PaymentTypeCategory
              Case isefinPaymentTypeCategory.CreditCard
                .AddCaptionText("Card Number:", batchBankTransaction.ImportedOtherPartyBankAccountNumberForDisplay)
              Case isefinPaymentTypeCategory.Token
                .AddCaptionText("Token:", finBL.HtmlEncode(batchBankTransaction.ImportedOtherPartyBankAccountNumberForDisplay))
              Case Else
                .AddCaptionText("Account No:", batchBankTransaction.ImportedOtherPartyBankAccountNumberForDisplay)
            End Select
          End If
        End If
        Select Case finBL.CountryCode
          Case "NZ"
            .AddCaptionText("Particulars:", batchBankTransaction.ImportedParticulars)
            .AddCaptionText("Code:", batchBankTransaction.ImportedCode)
            .AddCaptionText("Reference:", batchBankTransaction.ImportedReference)
          Case Else
            If Len(batchBankTransaction.ImportedParticulars) <> 0 Then .AddCaptionText("Particulars:", batchBankTransaction.ImportedParticulars)
            If Len(batchBankTransaction.ImportedCode) <> 0 Then .AddCaptionText("Code:", batchBankTransaction.ImportedCode)
            If Len(batchBankTransaction.ImportedReference) <> 0 Then .AddCaptionText("Reference:", batchBankTransaction.ImportedReference)
        End Select
        .AddCaptionCurrency("Value:", batchBankTransaction.ImportedValue, True)

        ' Match Code
        .AddSectionHeading2("Account Match")
        If Len(batchBankTransaction.ImportedMatch) = 0 Then
          .AddWiki("{{info|No information is defined to match to an Account.}}")
        Else
          .AddText(batchBankTransaction.ImportedMatch, iseSummaryTableCellClass.NormalBold)
          If batchBankTransaction.UpdateBankMatch Then
            BankMatchAction = "Do NOT update Accounts"
          Else
            Warnings &= "{{warning|Bank Match will NOT be updated on Accounts when committing this Batch.}}"
            BankMatchAction = "Enable updating of Accounts"
          End If
        End If
      End With

      ' Warnings
      .TextAfter = Warnings

      ' Actions
      With .Actions
        If Len(BankMatchAction) <> 0 Then .AddFormCustomAction("BankMatchToggle", BankMatchAction)
      End With
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  ''' Batch Bank Entry Item Splits(Version 2.01, Last updated 30/01/2017).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="batchBankTransaction">
  '''  Batch Bank Transaction to display.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Bank Entry page and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function BatchBankTransaction_Splits(callerScriptInfo As ISScriptExecutionInfo,
                                                          batchBankTransaction As finBatchBankTransaction,
                                                 Optional includeActions As Boolean = True,
                                                 Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim BatchBankTransactionItem As finBatchBankTransactionItem
    Dim InformationMessage As String
    Dim ShowContractualOverdueColumn As Boolean
    Dim ShowElementColumn As Boolean
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim WarningMessage As String
    Dim Warnings As String

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Find Columns to include
    ShowContractualOverdueColumn = batchBankTransaction.TransactionItems.HasContractualOverdue
    ShowElementColumn = batchBankTransaction.TransactionItems.HasElement

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .Caption = ""
      .AutoStripe = True

      If batchBankTransaction.TransactionItems.Count = 0 Then
        .TextBefore = "{{info|No Accounts entered for this Transaction.}}"
      Else
        With .Columns
          .AddBoolean(" ") ' Icon
          .AddText("Account", 10).NoBreakChars = 15
          .AddText("Account Name", 40).NoBreakChars = 50
          .AddCurrency("Balance")
          .AddCurrency("Overdue")
          If ShowContractualOverdueColumn Then .AddCurrency("Contractual")
          If ShowElementColumn Then .AddText("Element", 30)
          .AddCurrency("Value")
          .AddText("Notes", 40)
        End With

        With .Rows
          For Each BatchBankTransactionItem In batchBankTransaction.TransactionItems
            With .Add().Cells
              ' Icon
              WarningMessage = BatchBankTransactionItem.AccountWarningMessage(InformationMessage)
              If Len(WarningMessage) = 0 Then
                If Len(InformationMessage) = 0 Then
                  .AddText("{{icon|ok}}")
                Else
                  .AddText("{{icon|information}}").Tooltip = InformationMessage

                  Warnings &= "{{info|" & InformationMessage & "}}"
                End If
              Else
                .AddText("{{icon|warning}}").Tooltip = WarningMessage

                Warnings &= "{{warning|" & WarningMessage & "}}"
              End If
              With .AddText(BatchBankTransactionItem.AccountId)
                .HyperlinkSetFormShow("Accounts", BatchBankTransactionItem.AccountId)
              End With
              .AddText(BatchBankTransactionItem.AccountName)
              .AddCurrency(BatchBankTransactionItem.AccountBalance)
              Select Case BatchBankTransactionItem.AccountClass
                Case isefinAccountClass.LoanFR, isefinAccountClass.LoanFT, isefinAccountClass.LoanRC
                  .AddCurrency(BatchBankTransactionItem.AccountBalanceOverdue)
                Case Else
                  .AddText("")
              End Select
              If ShowContractualOverdueColumn Then
                If BatchBankTransactionItem.HasContractualOverdue Then
                  .AddCurrency(BatchBankTransactionItem.AccountBalanceOverdueContractual)
                Else
                  .AddText("")
                End If
              End If
              If ShowElementColumn Then
                If BatchBankTransactionItem.ElementPk = 0 Then
                  .AddText("")
                Else
                  .AddCodeDescription(BatchBankTransactionItem.ElementId, BatchBankTransactionItem.ElementDescription)
                End If
              End If
              .AddCurrency(BatchBankTransactionItem.Value)
              If Len(BatchBankTransactionItem.Notes) = 0 AndAlso Len(batchBankTransaction.Notes) <> 0 Then
                With .AddText(batchBankTransaction.Notes)
                  .CellClass = iseSummaryTableCellClass.Inactive
                End With
              Else
                .AddText(BatchBankTransactionItem.Notes)
              End If
            End With
          Next
        End With
      End If

      ' Warnings
      .TextAfter = Warnings

      ' Actions
      With .Actions
        .AddFormCustomAction("EditSplits", "Edit Splits")
      End With
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  ''' Batch Bank Entry Item Summary.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="batchBankTransaction">
  '''  Batch Bank Transaction to display.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Bank Entry page and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function BatchBankTransaction_Summary(callerScriptInfo As ISScriptExecutionInfo,
                                                           batchBankTransaction As finBatchBankTransaction,
                                                  Optional includeActions As Boolean = True,
                                                  Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' BatchBankTransaction_Summary
    '
    ' Version: 2.02 (24/03/2022)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    2.01  02/05/2021  ISS                  
    '    2.02  24/03/2022  ISS      J028489   Add Payment Method warnings       
    ' #################################################################

    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      .Columns.AddText(16)
      .Columns.AddText()

      With .Rows
        .AddCaptionDate("Date:", batchBankTransaction.Date)
        .AddCaptionCodeDescription("Pay Method:", batchBankTransaction.BankingDetails.PaymentMethodPk, finBL.PaymentMethods)
      End With

      ' Warnings
      If batchBankTransaction.BankingDetails.PaymentMethod Is Nothing Then
        Warnings &= "{{warning|Payment Method not specified.}}"
      ElseIf batchBankTransaction.BankingDetails.PaymentMethod.BankAccountPk <> batchBankTransaction.BatchBank.BankAccountPk Then
        Warnings &= "{{warning|Payment Method does not belong to this Bank Account.}}"
      End If
      If batchBankTransaction.BatchBank.Imported Then
        If batchBankTransaction.Value <> batchBankTransaction.ImportedValue Then
          Warnings &= "{{warning|" & String.Format("Transaction value of {0} does not match imported value of {1}.", finBL.FormatCurrency(batchBankTransaction.Value, True), finBL.FormatCurrency(batchBankTransaction.ImportedValue, True)) & "}}"
        End If
      End If
      .TextAfter = Warnings
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Client Accounts (Version 2.03, Last updated 23/04/2020).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="client">
  '''  The Client to summarise.
  ''' </param>
  ''' <param name="includeClosedAccounts">
  '''  Indicates whether to include Closed Accounts and Account Applications.
  ''' </param>
  ''' <param name="hideClosedAccounts">
  '''  Indicates whether to hide Closed Accounts.
  ''' </param>
  ''' <param name="showAccountDescription">
  '''  Indicates whether to show an Account Description column.
  ''' </param>
  ''' <param name="showOpening">
  '''  Indicates whether to show the Opening column.
  ''' </param>
  ''' <param name="showOverdue">
  '''  Indicates whether to show the Overdue column.
  ''' </param>
  ''' <param name="showContractualOverdue">
  '''  Indicates whether to show the Contractual Overdue column.
  ''' </param>
  ''' <param name="showTotals">
  '''  Indicates whether to show Totals.
  ''' </param>
  ''' <param name="maxDisplayRows">
  '''  <para>
  '''   The Maximum number of Rows to Display in the table before a 'Show Hidden' link is displayed.
  '''  </para>
  '''  <para>
  '''   NOTE: If this is less than the number of Non-Closed Accounts (including Account Applications) then any Closed Accounts will be hidden and this
  '''   value adjusted to ensure that Open and Quote Accounts are always shown.
  '''  </para>
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  '''  <para>
  '''   <list>
  '''    <item><code>ShowAccountsOrderBy</code><description>Order that Accounts are listed in. Options include {blank}, Reverse and DateOpenedDesc".</description></item>
  '''   </list>
  '''  </para>
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Client Key Details page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Client_Accounts2(callerScriptInfo As ISScriptExecutionInfo,
                                               client As finClient,
                                               includeClosedAccounts As Boolean,
                                               hideClosedAccounts As Boolean,
                                               showAccountDescription As Boolean,
                                               showOpening As Boolean,
                                               showOverdue As Boolean,
                                               showContractualOverdue As Boolean,
                                               showTotals As Boolean,
                                      Optional maxDisplayRows As Integer = 20,
                                      Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim AccountRegulations_NZ_HighCostConsumerCreditContract As finAccountRegulations_NZ_HighCostConsumerCreditContract
    Dim ClientAccount As finClientAccount
    Dim ClientAccounts As List(Of finClientAccount)
    Dim CountClosedWithinRepeatPeriod As Integer
    Dim CountOpen As Integer
    Dim CountOpenedinRepeatPeriod As Integer
    Dim CountMustShow As Integer
    Dim CountRemainingToShow As Integer
    Dim DateAsAt As Date
    Dim DateFromProhibitedOtherCreditor As Date
    Dim DateFromProhibitedRepeatPeriod As Date
    Dim HasLoansOpenedPriorToCommencement As Boolean
    Dim i As Integer
    Dim Include As Boolean
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim TotalBalance As Decimal
    Dim TotalContractualOverdue As Decimal
    Dim TotalOpening As Decimal
    Dim TotalOverdue As Decimal
    Dim Visible As Boolean
    Dim Warnings As String

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get the Client Accounts
    Select Case UCase(otherParameters.GetString("OrderBy"))
      Case "REVERSE"
        ClientAccounts = client.Accounts.GetClientAccounts_OrderReverse()
      Case "DATEOPENEDDESC", "DATEOPENEDDESCENDING"
        ClientAccounts = client.Accounts.GetClientAccounts_OrderDateOpenedDescending(True)
      Case Else
        ClientAccounts = client.Accounts.GetClientAccounts()
    End Select

    ' Count Accounts to show
    CountMustShow = 0
    For Each ClientAccount In client.Accounts
      If Not ClientAccount.AccountHidden Then
        Select Case ClientAccount.Source
          Case isefinClientAccountSource.Account
            ' Accounts
            Select Case ClientAccount.Status
              Case isefinAccountStatus.ClosedPending, isefinAccountStatus.Open, isefinAccountStatus.Quote
                ' Must always show
                CountMustShow += 1
            End Select

          Case isefinClientAccountSource.Application
            ' Applications
            Select Case ClientAccount.AccountAppStatus
              Case isefinAccountAppStatus.Incomplete, isefinAccountAppStatus.Reviewing, isefinAccountAppStatus.Complete
                ' Must always show
                CountMustShow += 1
            End Select
        End Select
      End If
    Next
    If CountMustShow > maxDisplayRows Then maxDisplayRows = CountMustShow

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .Caption = ""
      .AutoStripe = True
      .MaxDisplayRows = maxDisplayRows
      .ShowHiddenRowsCaption = "Show More Accounts"

      ' Warnings
      Warnings = ""

      ' Repeat High-Cost Loan warnings
      DateAsAt = finBL.TimeZoneFunctions.GetCurrentDatabaseDate()
      AccountRegulations_NZ_HighCostConsumerCreditContract = finBL.AccountRegulations.GetAccountRegulations_NZ_HighCostConsumerCreditContract(DateAsAt)

      If finBL.AccountTypes.AnyConsumerRegulationType(isefinAccountConsumerRegulationType.NZ_HighCostConsumerCreditContract) AndAlso DateAsAt >= AccountRegulations_NZ_HighCostConsumerCreditContract.DateCommenced Then
        ' Initialise
        DateFromProhibitedOtherCreditor = DateAsAt.AddDays(-AccountRegulations_NZ_HighCostConsumerCreditContract.ProhibitedOtherCreditorGapDays)
        DateFromProhibitedRepeatPeriod = DateAsAt.AddDays(-AccountRegulations_NZ_HighCostConsumerCreditContract.ProhibitedRepeatPeriodDays)

        ' Find Counts
        CountOpen = 0
        CountClosedWithinRepeatPeriod = 0
        CountOpenedinRepeatPeriod = 0
        For Each ClientAccount In client.Accounts
          If ClientAccount.Source = isefinClientAccountSource.Account Then
            Select Case ClientAccount.AccountConsumerRegulationType
              Case isefinAccountConsumerRegulationType.NZ_HighCostConsumerCreditContract
                Select Case ClientAccount.Status
                  Case isefinAccountStatus.Open, isefinAccountStatus.ClosedPending
                    ' Still Open (Treat Closed Pending as still Open)
                    CountOpen += 1
                  Case isefinAccountStatus.Closed
                    ' Closed in last 15 Days?
                    If ClientAccount.DateClosed > DateFromProhibitedOtherCreditor Then
                      CountClosedWithinRepeatPeriod += 1
                    End If
                End Select

                ' Opened in last 90 days?
                If ClientAccount.DateOpened >= DateFromProhibitedRepeatPeriod Then
                  CountOpenedinRepeatPeriod += 1
                End If

              Case Else
                Select Case ClientAccount.AccountClass
                  Case isefinAccountClass.LoanFR, isefinAccountClass.LoanFT, isefinAccountClass.LoanRC
                    ' Opened in last 90 days?
                    If ClientAccount.AccountType.CreditType = isefinAccountCreditType.Consumer AndAlso ClientAccount.DateOpened >= DateFromProhibitedRepeatPeriod AndAlso ClientAccount.DateOpened < AccountRegulations_NZ_HighCostConsumerCreditContract.DateCommenced Then
                      HasLoansOpenedPriorToCommencement = True
                    End If
                End Select
            End Select
          End If
        Next

        ' Warnings
        Select Case CountOpen
          Case 0
            ' Warn if any Closed within the last 15 days
            If CountClosedWithinRepeatPeriod <> 0 Then
              Warnings &= "{{info|" & String.Format("There have been {0} {1} closed in the last {2} days.", CountClosedWithinRepeatPeriod, AccountRegulations_NZ_HighCostConsumerCreditContract.Description(True), AccountRegulations_NZ_HighCostConsumerCreditContract.ProhibitedOtherCreditorGapDays) & "}}"
            End If
          Case 1
            Warnings &= "{{info|" & String.Format("There is 1 'Open' {0}.", AccountRegulations_NZ_HighCostConsumerCreditContract.Description(False)) & "}}"
          Case Else
            Warnings &= "{{warning|" & String.Format("There are {0} 'Open' {1}.", CountOpen, AccountRegulations_NZ_HighCostConsumerCreditContract.Description(True)) & "}}"
        End Select

        ' Repeat High-Cost Loans within last 90 Days
        If CountOpenedinRepeatPeriod <> 0 Then
          Warnings &= "{{info|" & String.Format("There have been {0} {1} opened in the last {2} days.", CountOpenedinRepeatPeriod, AccountRegulations_NZ_HighCostConsumerCreditContract.Description(True), AccountRegulations_NZ_HighCostConsumerCreditContract.ProhibitedRepeatPeriodDays) & "}}"
        End If
        If HasLoansOpenedPriorToCommencement AndAlso CountOpenedinRepeatPeriod < AccountRegulations_NZ_HighCostConsumerCreditContract.ProhibitedRepeatPeriodCount Then
          Warnings &= "{{info|" & String.Format("There may be one or more {0} opened prior to {1}, which are also within {2} days of today (since {3}).", AccountRegulations_NZ_HighCostConsumerCreditContract.Description(True), finBL.FormatDateLong(AccountRegulations_NZ_HighCostConsumerCreditContract.DateCommenced), AccountRegulations_NZ_HighCostConsumerCreditContract.ProhibitedRepeatPeriodDays, finBL.FormatDateLong(DateFromProhibitedRepeatPeriod)) & "}}"
        End If
      End If

      ' Add Warnings
      .TextBefore = Warnings

      ' Columns (including Header row)
      With .Columns
        .AddCode("Type", finBL.AccountTypes.GetLongestCode())
        .AddCode("Account", finBL.AccountFunctions.GetLongestCode())
        If showAccountDescription Then
          .AddText("Description")
        End If
        .AddCode("Role", 5) ' Making a Code column means text will not word break
        .AddDate("Opened")
        .AddDate("Matures")
        .AddCode("Status", 5) ' Making a Code column means text will not word break
        If showOpening Then .AddCurrency("Opening")
        .AddCurrency("Balance")
        If showOverdue Then .AddCurrency("Overdue")
        If showContractualOverdue Then .AddCurrency("Contractual")
      End With

      ' Accounts
      For i = 0 To ClientAccounts.Count - 1
        ClientAccount = ClientAccounts(i)

        ' Include?
        If ClientAccount.AccountHidden Then
          Include = False
          Visible = False
        Else
          Select Case ClientAccount.Source
            Case isefinClientAccountSource.Account
              ' Account
              Select Case ClientAccount.Status
                Case isefinAccountStatus.ClosedPending, isefinAccountStatus.Open, isefinAccountStatus.Quote
                  Include = True
                  Visible = True
                Case Else
                  Include = includeClosedAccounts
                  Visible = False
              End Select

            Case isefinClientAccountSource.Application
              ' Account Application
              Select Case ClientAccount.AccountAppStatus
                Case isefinAccountAppStatus.Incomplete, isefinAccountAppStatus.Reviewing, isefinAccountAppStatus.Complete
                  Include = True
                  Visible = True
                Case Else
                  Include = includeClosedAccounts
                  Visible = False
              End Select

            Case isefinClientAccountSource.Archive
              ' Archive
              Include = includeClosedAccounts
              Visible = False
          End Select
        End If

        ' Add Row
        If Include Then
          With .Rows.Add()
            ' Hide Row?
            .Visible = Visible

            With .Cells
              .AddText(ClientAccount.AccountTypeId)
              With .AddText(ClientAccount.AccountId)
                Select Case ClientAccount.Source
                  Case isefinClientAccountSource.Account
                    ' Account
                    .HyperlinkSetFormShow("Accounts", ClientAccount.AccountId)
                  Case isefinClientAccountSource.Application
                    ' Account Application
                    .HyperlinkSetFormShow("AccountApps", ClientAccount.AccountId)
                  Case isefinClientAccountSource.Archive
                    ' Archive (never included)
                End Select
              End With
              If showAccountDescription Then
                .AddText(ClientAccount.Description)
              End If
              If finBL.AccountRoles.Exists(ClientAccount.AccountRoleId) Then
                .AddText(finBL.AccountRoles(ClientAccount.AccountRoleId).DescriptionShortResolved)
              Else
                .AddText("")
              End If
              .AddDate(ClientAccount.DateOpened)
              .AddDate(ClientAccount.DateMaturity)
              .AddText(ClientAccount.StatusText)
              If showOpening Then
                .AddCurrency(ClientAccount.BalanceOpening)
              End If
              .AddCurrency(ClientAccount.Balance)
              If showOverdue Then
                With .AddCurrency(ClientAccount.BalanceOverdue)
                  If ClientAccount.BalanceOverdue > 0 Then .ForegroundColour = "red"
                End With
              End If
              If showContractualOverdue Then
                With .AddCurrency(ClientAccount.BalanceOverdueContractual)
                  If ClientAccount.BalanceOverdueContractual > 0 Then .ForegroundColour = "red"
                End With
              End If

              ' Track Totals
              If showTotals AndAlso ClientAccount.Status = isefinAccountStatus.Open Then
                TotalBalance += ClientAccount.Balance
                TotalOpening += ClientAccount.BalanceOpening
                TotalOverdue += ClientAccount.BalanceOverdue
                TotalContractualOverdue += ClientAccount.BalanceOverdueContractual
              End If
            End With
          End With
        End If
      Next

      ' Show Closed Accounts
      If CountMustShow < maxDisplayRows Then
        CountRemainingToShow = maxDisplayRows - CountMustShow

        Select Case UCase(otherParameters.GetString("OrderBy"))
          Case "REVERSE", "DATEOPENEDDESC", "DATEOPENEDDESCENDING"
            ' From the Top
            For i = 0 To .Rows.Count - 1
              If Not .Rows(i).Visible Then
                .Rows(i).Visible = True

                CountRemainingToShow -= 1
                If CountRemainingToShow = 0 Then Exit For
              End If
            Next

          Case Else
            ' From the Bottom
            For i = .Rows.Count - 1 To 0 Step -1
              If Not .Rows(i).Visible Then
                .Rows(i).Visible = True

                CountRemainingToShow -= 1
                If CountRemainingToShow = 0 Then Exit For
              End If
            Next

        End Select
      End If

      ' Add Totals Row
      If showTotals Then
        With .Rows.Add(iseSummaryTableRowClass.FooterBold).Cells
          .AddText("")
          .AddText("")
          If showAccountDescription Then
            .AddText("")
          End If
          .AddText("")
          .AddText("")
          .AddText("")
          .AddText("")
          If showOpening Then
            .AddCurrency(TotalOpening, True)
          End If
          .AddCurrency(TotalBalance, True)
          If showOverdue Then
            With .AddCurrency(TotalOverdue, True)
              If TotalOverdue > 0 Then .ForegroundColour = "red"
            End With
          End If
          If showContractualOverdue Then
            With .AddCurrency(TotalContractualOverdue, True)
              If TotalContractualOverdue > 0 Then .ForegroundColour = "red"
            End With
          End If
        End With
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Client Addresses Summary (Version 1.0, Last updated 29/07/2013).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="client">
  '''  The Client to summarise.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Client Key Details page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Client_Addresses(callerScriptInfo As ISScriptExecutionInfo,
                                               client As finClient,
                                      Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim AddressDetailsPhysical As ISAddressDetails
    Dim AddressDetailsPostal As ISAddressDetails
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Find Addresses
    AddressDetailsPhysical = client.ContactAddresses.GetCurrentPhysicalAddress()
    AddressDetailsPostal = client.ContactAddresses.GetCurrentPostalAddress()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      .Columns.AddText()

      If Not AddressDetailsPhysical.HasValue AndAlso Not AddressDetailsPostal.HasValue Then
        ' No Current Addresses
        .Rows.AddSectionHeading2("Physical & Postal Address")
        .Rows.AddText("{{warning|No current Address recorded.}}")
      ElseIf AddressDetailsPhysical.HasValue AndAlso AddressDetailsPostal.HasValue AndAlso StrComp(finBL.Addressing.FormatAddressFromAddressDetails(AddressDetailsPhysical), finBL.Addressing.FormatAddressFromAddressDetails(AddressDetailsPostal), CompareMethod.Text) = 0 Then
        ' Physical and Postal are the same
        .Rows.AddSectionHeading2("Physical & Postal Address")
        .Rows.AddAddressDetailsPhysical(AddressDetailsPhysical)
      Else
        ' Physical
        .Rows.AddSectionHeading2("Physical Address")
        If AddressDetailsPhysical.HasValue Then
          .Rows.AddAddressDetailsPhysical(AddressDetailsPhysical)
        Else
          .Rows.AddText("{{warning|No current Physical Address recorded.}}")
        End If

        ' Postal
        .Rows.AddSectionHeading2("Postal Address")
        If AddressDetailsPostal.HasValue Then
          .Rows.AddAddressDetailsPostal(AddressDetailsPostal)
        Else
          .Rows.AddText("{{warning|No current Postal Address recorded.}}")
        End If
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Client Credit Bureau Monitoring Summary.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="client">
  '''  The Client to summarise.
  ''' </param>
  ''' <param name="serviceId">
  '''  Optional Credit Bureau Service to show, or blank to include all Services.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Client Key Details pages and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>CentrixNZ</code><description>Centrix NZ Monitoring.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Client_CreditBureauMonitoring(callerScriptInfo As ISScriptExecutionInfo,
                                                            client As finClient,
                                                   Optional serviceId As String = "",
                                                   Optional includeActions As Boolean = True,
                                                   Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' Client_CreditBureauMonitoring
    '
    ' Version: 1.02 (04/08/2023)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.01  16/05/2019  ISS
    '    1.02  04/08/2023  ISS      J031309   Added finCC support for Client Monitoring
    ' #################################################################

    Dim ClientLog As finLogRO
    Dim CreditMonitorResponse As ISCreditMonitorResponse
    Dim CreditMonitorResponse_CentrixNZConsumerMonitorLoad As ISCreditMonitorResponse_CentrixNZ_ConsumerMonitorLoad
    Dim SummaryTableCentrix As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableCentrix = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Centrix
    If (Len(serviceId) = 0 OrElse StrComp(serviceId, "CentrixNZ", CompareMethod.Text) = 0) Then
      If client.IsCreditBureauMonitored("CentrixNZ") OrElse client.CanCreditBureauMonitorBeStarted("CentrixNZ") Then
        With SummaryTableCentrix
          ' Initialise
          .TableClass = iseSummaryTableClass.Information
          .Caption = "Centrix"
          .Columns.AddText(12).NoBreakChars = 20
          .Columns.AddText()

          With .Rows
            If client.GetActiveCreditBureauMonitorLog(ClientLog, "CentrixNZ") Then
              If ClientLog Is Nothing Then
                If client.IsIndividualOrSoleTrader Then
                  Warnings = "{{info|Not currently monitored.}}"
                Else
                  Warnings = "{{info|Only monitoring of Individuals is supported.}}"
                End If
              Else
                ' Get Response
                finBL.CreditBureau.GetCreditBureauMonitorResponseFromServiceLog(ClientLog.ServiceLog, CreditMonitorResponse)
                CreditMonitorResponse_CentrixNZConsumerMonitorLoad = DirectCast(CreditMonitorResponse, ISCreditMonitorResponse_CentrixNZ_ConsumerMonitorLoad)

                ' Show Details
                .AddCaptionDateTime("Date Loaded:", CreditMonitorResponse_CentrixNZConsumerMonitorLoad.EnquiryDate)
                'With .AddCaptionText("Reference:", CreditMonitorResponse_CentrixNZConsumerMonitorLoad.MonitorData.MonitorReference)
                '  .Cells(1).HyperlinkSetApplicationShortcutUrl(String.Format("FormShow?form=ClientLog&id={0}", ClientLog.Pk))
                'End With
                .AddCaptionCodeDescription("Type:", CreditMonitorResponse_CentrixNZConsumerMonitorLoad.MonitorData.MonitorType, CreditMonitorResponse_CentrixNZConsumerMonitorLoad.MonitorData.MonitorTypeDescription)
                .AddCaptionCodeDescription("Reason:", CreditMonitorResponse_CentrixNZConsumerMonitorLoad.MonitorData.EnquiryReason, CreditMonitorResponse_CentrixNZConsumerMonitorLoad.MonitorData.EnquiryReasonDescription)
              End If
            Else
              Warnings = "{{warning|" & finBL.Error.Message(True, True) & "}}"
            End If
          End With

          ' Warnings
          .TextAfter = Warnings

          ' Actions
          If includeActions Then
            With .Actions
              If ClientLog Is Nothing Then
                If client.CanCreditBureauMonitorBeStarted("CentrixNZ") Then
                  .AddApplicationShortcutUrl("Start Monitor", "Start Monitoring", String.Format("App://Global?Type=CreditBureauMonitor.Start&ClientPk={0}&ClientId={1}&ServiceId=CentrixNZ", client.Pk, client.ClientId), True).ShowInWebInterfaces = True
                End If
              Else
                .AddApplicationShortcutUrl("Review Monitor", "Review", String.Format("App://FormShow?form=ClientLog&id={0}&page=Credit Bureau Monitor", ClientLog.Pk), True).ShowInWebInterfaces = True
                If finBL.CreditBureau.IsCreditBureauMonitorOutOfDate(client, "CentrixNZ") Then
                  .AddApplicationShortcutUrl("Refresh Monitor", "Refresh Monitor", String.Format("App://Global?Type=CreditBureauMonitor.Refresh&ClientPk={0}&ClientId={1}&ServiceId=CentrixNZ", client.Pk, client.ClientId), True).ShowInWebInterfaces = True
                End If
                If client.CanCreditBureauMonitorBeStopped("CentrixNZ") Then
                  .AddApplicationShortcutUrl("Stop Monitor", "Stop Monitoring", String.Format("App://Global?Type=CreditBureauMonitor.Stop&ServiceLogPk={0}&ClientPk={1}&ClientId={2}", ClientLog.ServiceLog.Pk, client.Pk, client.ClientId), True).ShowInWebInterfaces = True
                End If
              End If
            End With
          End If
        End With
      End If
    End If

    ' Add Summary Tables
    If SummaryTableCentrix.HasData Then SummaryTables.Add("CentrixNZ", SummaryTableCentrix)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Client Incomplete Workflows Summary.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="client">
  '''  The Client to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="maxDisplayRows">
  '''  The Maximum number of Rows to Display in the table before a 'Show Hidden' link is displayed.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Client Key Details pages and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Client_IncompleteWorkflows(callerScriptInfo As ISScriptExecutionInfo,
                                                         client As finClient,
                                                Optional maxDisplayRows As Integer = 20,
                                                Optional includeActions As Boolean = True,
                                                Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' Client_IncompleteWorkflows
    '
    ' Version: 1.03 (23/08/2023)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.02  19/04/2016  ISS
    '    1.03  23/08/2023  ISS      J031278   Remove "Locate in Task Manager" link
    ' #################################################################

    Dim ClientWorkflow As finClientWorkflow
    Dim DateAsAt As Date
    Dim ShowLocateInTaskManager As Boolean
    Dim StatusIcon As String
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim TooltipText As String
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Date As At
    DateAsAt = finBL.TimeZoneFunctions.GetCurrentDatabaseDate()

    ' Determine Columns to include
    Select Case callerScriptInfo.Target
      Case iseSummaryPageTarget.Form
        If finBL.Settings.UseTaskManager1Resolved Then
          ShowLocateInTaskManager = (client.Workflows.CountInTaskManager <> 0) AndAlso Not finBL.IsRunningFromWeb() AndAlso finBL.CurrentUser.Permissions.Allow("Menu.Process.TaskManager")
        End If
    End Select

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .Caption = ""
      .AutoStripe = True
      .MaxDisplayRows = maxDisplayRows
      .ShowHiddenRowsCaption = "Show More Workflows"

      If client.Workflows.CountNotClosed = 0 Then
        ' No Incomplete Workflows (should really have been checked before calling this method to avoid loading the Workflows collection unnecessarily)
        .TextAfter = "{{info|No current Workflows.}}"
      Else
        ' Columns
        With .Columns
          .AddText(" ", 1, iseSummaryTableCellTextAlign.Center) ' Flag Colour
          .AddText(" ", 1, iseSummaryTableCellTextAlign.Center) ' Status Icon
          .AddDate("Opened")
          .AddCode("Workflow", finBL.WorkflowFunctions.GetLongestCode())
          If ShowLocateInTaskManager Then
            With .AddText(" ", 1, iseSummaryTableCellTextAlign.Center) ' Locate in Task Manager Icon
              .HideRule = iseSummaryTableColumnHideRule.DocumentWidthLessThan800px
            End With
          End If
          .AddText("Description").HideRule = iseSummaryTableColumnHideRule.DocumentWidthLessThan640px
          .AddText("Current Item").HideRule = iseSummaryTableColumnHideRule.DocumentWidthLessThan800px
          .AddCode("Allocated", finBL.Users.GetLongestCode())
        End With

        With .Rows
          For Each ClientWorkflow In client.Workflows
            If ClientWorkflow.Status <> isefinWorkflowStatus.Closed Then
              ' Status Icon (not the real Status but something to bring this item to the User's attention)
              StatusIcon = "Blank"
              TooltipText = ""
              Select Case ClientWorkflow.Status
                Case isefinWorkflowStatus.OnHold
                  StatusIcon = "Hold"
                  TooltipText = "On Hold"
                Case isefinWorkflowStatus.Pending
                  StatusIcon = "WorkflowPending"
                  TooltipText = "Pending"
                Case isefinWorkflowStatus.Open
                  If ClientWorkflow.RecallImmediate OrElse (ClientWorkflow.RecallDate <> Nothing AndAlso ClientWorkflow.RecallDate < DateAsAt) Then
                    StatusIcon = "Review"
                    If ClientWorkflow.RecallImmediate Then
                      TooltipText = "Immediate Recall"
                    Else
                      TooltipText = String.Format("Recall due to Recall Date of {0} reached", finBL.FormatDate(ClientWorkflow.RecallDate, True))
                    End If
                  ElseIf Not ClientWorkflow.RecallImmediate AndAlso ClientWorkflow.RecallDate <> Nothing AndAlso ClientWorkflow.RecallDate > DateAsAt Then
                    StatusIcon = "Hourglass"
                    TooltipText = "Waiting for Recall Date to be reached"
                  End If
              End Select

              ' Add Row
              With .Add().Cells
                If Len(ClientWorkflow.FlagColour) = 0 Then
                  .AddText("")
                Else
                  .AddText("{{flag|" & ClientWorkflow.FlagColour & "}}").Tooltip = ClientWorkflow.FlagColour
                End If
                If Len(StatusIcon) = 0 Then
                  .AddText("")
                Else
                  .AddText("{{icon|" & StatusIcon & "}}").Tooltip = TooltipText
                End If
                .AddDate(ClientWorkflow.OpenedDate)
                With .AddText(ClientWorkflow.WorkflowId)
                  .HyperlinkSetFormShow("Workflows", ClientWorkflow.WorkflowId)
                End With
                If ShowLocateInTaskManager Then
                  If ClientWorkflow.IsInTaskManager() Then
                    With .AddText("{{icon|Task_Locate|Locate in Task Manager}}")
                      .HyperlinkSetFormAction("LocateWorkflow", "workflowId=" & finBL.UrlEncode(ClientWorkflow.WorkflowId), "TaskManager", True, True)
                    End With
                  Else
                    .AddText("")
                  End If
                End If
                .AddText(ClientWorkflow.Description)
                If ClientWorkflow.Workflow.GetCurrentItem() Is Nothing Then
                  .AddText("")
                Else
                  .AddText(ClientWorkflow.Workflow.GetCurrentItem().Description)
                End If
                .AddText(ClientWorkflow.AllocatedUserId)
              End With
            End If
          Next
        End With

        ' Warnings
        .TextAfter = Warnings

        ' Actions
        If includeActions Then
          With .Actions
          End With
        End If
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Client Map
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="client">
  '''  The Client to summarise.
  ''' </param>
  ''' <param name="mapHeight">
  '''  The Map Height in pixels. If omitted, 320px is used.
  ''' </param>
  ''' <param name="addressDetails">
  '''  AddressDetails or Nothing to use the current Physical Address.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  A String value containing HTML.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Client Key Details page.
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Client_Map(callerScriptInfo As ISScriptExecutionInfo,
                                         client As finClient,
                                Optional mapHeight As Integer = 320,
                                Optional addressDetails As ISAddressDetails = Nothing,
                                Optional otherParameters As ISKeyValueList = Nothing) As String

    ' #################################################################
    ' Client_Map
    '
    ' Version: 1.02 (23/04/2024)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.01  27/05/2021
    '    1.02  23/04/2024  ISS      J033352   Support Static URL Global Setting
    ' #################################################################

    Dim ClientContactAddress As finClientContactAddress
    Dim Url As String

    ' Validate - static maps for reports are not available if not using Embedded Google Maps option
    If callerScriptInfo.Target = iseSummaryPageTarget.Report AndAlso Not finBL.Settings.UseAPIEmbeddedMaps Then
      Return "<span>Static maps for reports are not available. Please enable Embedded Google Maps in Global Settings.</span>"
    End If

    ' Initialise
    If mapHeight <= 0 Then mapHeight = 320

    ' Get Current Physical Address
    If addressDetails Is Nothing Then
      ClientContactAddress = client.ContactAddresses.GetCurrentPhysicalAddressContactAddress()
      addressDetails = ClientContactAddress.ToAddressDetails()
    End If

    If addressDetails Is Nothing OrElse Not addressDetails.HasValue Then
      ' No Address
      Return "{{info|No current physical address available.}}"
    ElseIf finBL.Settings.UseAPIEmbeddedMaps Then
      ' Get Static vs Embedded URL
      Select Case callerScriptInfo.Target
        Case iseSummaryPageTarget.Report
          Url = finBL.GetAddressMapUrl(addressDetails, True, True)
          Url &= "&size=320x200"
          ' Create an IMG to show map
          Return String.Format("<img src =""{0}"" style=""border:0;"">", Url)
        Case Else
          Url = finBL.GetAddressMapUrl(addressDetails, True)
          ' Create an iframe to show Map
          Return String.Format("<iframe width=""100%"" height=""{0}px"" style=""border:0"" loading=""lazy"" src=""{1}""></iframe>", mapHeight, Url)
      End Select
    Else
      ' Create Embedded (Interactive) Map URL
      Url = finBL.GetAddressMapUrl(addressDetails)

      ' If using Google Maps then append parameters to tweak Address
      If InStr(Url, "maps.google", CompareMethod.Text) <> 0 Then
        Url &= "&output=embed" ' Required for iframe
        Url &= "&t=h"          ' Hybrid map
        Url &= "&iwloc=near"   ' Hide info balloon
      End If

      ' Create an iframe to show Map      
      Return String.Format("<iframe style='width:100%; height:{0}px; border:none' frameborder='0' scrolling='no' marginheight='0' marginwidth='0' src=""{1}""></iframe>", mapHeight, Url)
    End If

  End Function

  ''' <summary>
  '''  Client Map From Coordinates
  '''  Returns a string containing HTML wrapping a Google Map centered on the requested coordinates in a IFrame element.
  '''  This function requires that you have a Google Maps API key configured in Settings.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="latitude">
  '''  The latitude coordinate to centre the map on. Note the Google Maps uses only 6dp precision.
  ''' </param>
  ''' <param name="longitude">
  '''  The longitude coordinate to centre the map on. Note the Google Maps uses only 6dp precision.
  ''' </param>
  ''' <param name="mapHeightHtml">
  '''  The map height expressed as an HTML snippet. e.g. "320px" or "100%"
  ''' </param>
  ''' <param name="mapWidthHtml">
  '''  The map width expressed as an HTML snippet. e.g. "480px" or "100%"
  ''' </param>
  ''' <param name="zoom">
  '''  The zoom level of the map. This can be changed by the user with the +/- buttons rendered with the map.  Valid zoom levels range from 0 (entire planet) to 22 (~half a city block).
  ''' </param>
  ''' <param name="mapMinHeightHtml">
  '''  The map minimum height expressed as an HTML snippet. e.g. "200px" or "20%"
  ''' </param>
  ''' <param name="mapMinWidthHtml">
  '''  The map minimum width expressed as an HTML snippet. e.g. "200px" or "20%"
  ''' </param>
  ''' <param name="mapMaxHeightHtml">
  '''  The map maximum height expressed as an HTML snippet. e.g. "320px" or "100%"
  ''' </param>
  ''' <param name="mapMaxWidthHtml">
  '''  The map maximum width expressed as an HTML snippet. e.g. "480px" or "100%"
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  A String value containing HTML.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., AML verification reports that show device's location.
  '''  </para>
  '''  <para>
  '''   This displays an interactive map, i.e. with scroll and zoom functions. 
  '''   It will not render correctly in summary page reports or PDF documents. 
  '''   Use Client_MapFromCoordinates for applications such as KEY.DETAILS and Client_StaticMapFromCoordinates when the ability to render to reports is required.
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Client_MapFromCoordinates(callerScriptInfo As ISScriptExecutionInfo,
                                                        latitude As Double,
                                                        longitude As Double,
                                               Optional mapHeightHtml As String = "320px",
                                               Optional mapWidthHtml As String = "480px",
                                               Optional zoom As Integer = 16,
                                               Optional mapMinWidthHtml As String = "",
                                               Optional mapMaxWidthHtml As String = "",
                                               Optional mapMinHeightHtml As String = "",
                                               Optional mapMaxHeightHtml As String = "",
                                               Optional otherParameters As ISKeyValueList = Nothing) As String

    ' #################################################################
    ' Client_MapFromCoordinates
    '
    ' Version: 1.01 (23/04/2024)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.00  28/07/2022  ISS      J029086   Created
    '    1.01  23/04/2024  ISS      J033352   Support Static URL Global Setting
    ' #################################################################

    Dim ApiKey As String
    Dim Coordinates As String
    Dim IFrameHtml As String
    Dim QueryParams As ISKeyValueList
    Dim Url As String
    Dim UrlParts As String()

    ' Validate
    If zoom < 0 OrElse zoom > 22 Then zoom = 16

    ' Get API Key
    ApiKey = finBL.Settings.AddressingGoogleMapsApiKeyBrowser

    If Len(ApiKey) <> 0 Then
      Url = finBL.Settings.AddressMapEmbeddedUrlResolved

      ' Replace placeholders in settings string
      Coordinates = String.Format("{0},{1}", finBL.FormatDoubleXml(latitude), finBL.FormatDoubleXml(longitude))
      Url = Replace(Url, "[Address]", Coordinates, , , CompareMethod.Text)
      Url = Replace(Url, "[APIKey_Browser]", finBL.Settings.AddressingGoogleMapsApiKeyBrowser, , , CompareMethod.Text)
      Url = Replace(Url, "[APIKey_Server]", finBL.Settings.AddressingGoogleMapsApiKeyServer, , , CompareMethod.Text)

      ' Add zoom, overriding any value specified in Settings string
      If Url.Contains("?"c) Then
        UrlParts = Url.Split("?"c)
        QueryParams = finBL.CreateKeyValueList()
        With QueryParams
          .FromUrlString(UrlParts(1))
          .SetValue("zoom", zoom)
          Url = UrlParts(0) & "?" & .ToUrlString()
        End With
      End If

      ' Create an iframe to show Map
      IFrameHtml = String.Format("<iframe src='{0}'", Url)
      If Len(mapWidthHtml) <> 0 Then IFrameHtml &= String.Format(" width='{0}'", mapWidthHtml)
      If Len(mapHeightHtml) <> 0 Then IFrameHtml &= String.Format(" height='{0}'", mapHeightHtml)
      IFrameHtml &= " style='border:0;"
      If Len(mapMinWidthHtml) <> 0 Then IFrameHtml &= String.Format("min-width:{0};", mapMinWidthHtml)
      If Len(mapMaxWidthHtml) <> 0 Then IFrameHtml &= String.Format("max-width:{0};", mapMaxWidthHtml)
      If Len(mapMinHeightHtml) <> 0 Then IFrameHtml &= String.Format("min-height:{0};", mapMinHeightHtml)
      If Len(mapMaxHeightHtml) <> 0 Then IFrameHtml &= String.Format("max-height:{0};", mapMaxHeightHtml)
      IFrameHtml &= "' loading='lazy'></iframe>"

      Return IFrameHtml
    Else
      Return "{{info|Coordinate-based map requires API key.}}"
    End If

  End Function

  ''' <summary>
  '''  Client Static Map From Coordinates
  '''  Returns a string containing HTML wrapping a Google Map image centered on the requested coordinates in a IFrame element.
  '''  This function requires that you have a Google Maps API key configured in Settings.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="latitude">
  '''  The latitude coordinate to centre the map on. Note the Google Maps uses only 6dp precision.
  ''' </param>
  ''' <param name="longitude">
  '''  The longitude coordinate to centre the map on. Note the Google Maps uses only 6dp precision.
  ''' </param>
  ''' <param name="mapHeight">
  '''  The map image height."
  ''' </param>
  ''' <param name="mapWidth">
  '''  The map image width."
  ''' </param>
  ''' <param name="zoom">
  '''  The zoom level of the map. 
  ''' </param>
  ''' <returns>
  '''  A String value containing HTML.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., AML verification reports that show device's location.
  '''  </para>
  '''  <para>
  '''   This displays a static map, i.e. an image. 
  '''   It does not provide scroll and zoom functions but does render correctly in summary page reports and PDF documents. 
  '''   Use Client_MapFromCoordinates for applications such as KEY.DETAILS and Client_StaticMapFromCoordinates when the ability to render to reports is required.
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Client_StaticMapFromCoordinates(callerScriptInfo As ISScriptExecutionInfo,
                                                              latitude As Double,
                                                              longitude As Double,
                                                     Optional mapHeight As Integer = 320,
                                                     Optional mapWidth As Integer = 480,
                                                     Optional zoom As Integer = 16) As String

    ' #################################################################
    ' Client_StaticMapFromCoordinates
    '
    ' Version: 1.01 (23/04/2024)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.00  11/03/2024  ISS      J033066   Created
    '    1.01  23/04/2024  ISS      J033352   Support Static URL Global Setting
    ' #################################################################

    Dim ApiKey As String
    Dim Coordinates As String
    Dim QueryParams As ISKeyValueList
    Dim UrlParts As String()
    Dim Url As String

    ' Validate
    If zoom < 0 OrElse zoom > 22 Then zoom = 16
    If mapHeight <= 0 OrElse mapHeight > 768 Then mapHeight = 320
    If mapWidth <= 0 OrElse mapWidth > 1024 Then mapWidth = 480

    ' Validate static Google Map settings
    If Not finBL.Settings.UseAPIEmbeddedMaps Then
      Return "{{info|Static maps for reports are unavailable. Please enable Embedded Google Maps in Global Settings.}}"
    End If

    ' Get API Key
    ApiKey = finBL.Settings.AddressingGoogleMapsApiKeyBrowser

    If Len(ApiKey) <> 0 Then
      ' Create an image to show static Map
      Url = finBL.Settings.AddressMapStaticUrlResolved

      ' Replace placeholders in settings string
      Coordinates = String.Format("{0},{1}", finBL.FormatDoubleXml(latitude), finBL.FormatDoubleXml(longitude))
      Url = Replace(Url, "[Address]", Coordinates, , , CompareMethod.Text)
      Url = Replace(Url, "[APIKey_Browser]", finBL.Settings.AddressingGoogleMapsApiKeyBrowser, , , CompareMethod.Text)
      Url = Replace(Url, "[APIKey_Server]", finBL.Settings.AddressingGoogleMapsApiKeyServer, , , CompareMethod.Text)

      ' Add zoom and size, overriding any values specified in Settings string
      If Url.Contains("?"c) Then
        UrlParts = Url.Split("?"c)
        QueryParams = finBL.CreateKeyValueList()
        With QueryParams
          .FromUrlString(UrlParts(1))
          .SetValue("zoom", zoom)
          .SetValue("size", String.Format("{0}x{1}", mapWidth, mapHeight))
          Url = UrlParts(0) & "?" & .ToUrlString()
        End With
      End If

      Return String.Format("<img src='{0}' style='border:0;'>", Url)
    Else
      Return "{{info|Coordinate-based map requires API key.}}"
    End If

  End Function

  ''' <summary>
  '''  Client Other Contacts Summary (Version 1.01, Last updated 15/10/2013).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="client">
  '''  The Client to summarise.
  ''' </param>
  ''' <param name="excludeContactMethodPks">
  '''  A list of Client Contact Method Pks (converted to Strings) to exclude when generating this summary.
  ''' </param>
  ''' <param name="showNotes">
  '''  Indicates whether to show any Notes recorded against the Contact Methods.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Client Key Details page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Client_OtherContacts(callerScriptInfo As ISScriptExecutionInfo,
                                                   client As finClient,
                                          Optional excludeContactMethodPks As ISList = Nothing,
                                          Optional showNotes As Boolean = False,
                                          Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim ClientContactMethod As finClientContactMethod
    Dim HasNotes As Boolean
    Dim strTemp As String
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If excludeContactMethodPks Is Nothing Then excludeContactMethodPks = New ISList()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    If client.ContactMethods.CountIncludeInSummary(True, True, False, HasNotes, excludeContactMethodPks) <> 0 Then
      With SummaryTableMain
        ' Initialise
        .TableClass = iseSummaryTableClass.TabularData
        .Caption = ""
        .AutoStripe = True

        .Columns.AddCode(5) ' Use a Code so text does not line break
        .Columns.AddText()
        If showNotes AndAlso HasNotes Then
          .Columns.AddText()
        End If

        For Each ClientContactMethod In client.ContactMethods
          If ClientContactMethod.IsCurrent AndAlso ClientContactMethod.ShowInSummary AndAlso Not excludeContactMethodPks.Exists(CStr(ClientContactMethod.Pk)) Then
            With .Rows.Add()
              ' Contact Method
              strTemp = finBL.ContactMethods(ClientContactMethod.ContactMethodId).DescriptionShortResolved
              If Len(ClientContactMethod.ValueType) <> 0 Then strTemp &= " (" & ClientContactMethod.ValueType & ")"
              .Cells.AddText(strTemp)

              ' Contact Value
              With .Cells.AddText(ClientContactMethod.Value)
                Select Case ClientContactMethod.ContactMethod.ContactType
                  Case isefinContactType.Email
                    .HyperlinkSetEmailAddress(ClientContactMethod.Value, client.ClientId, CStr(ClientContactMethod.Pk))
                  Case isefinContactType.Phone
                    .HyperlinkSetPhoneNumber(ClientContactMethod.Value, client.ClientId, CStr(ClientContactMethod.Pk))
                  Case isefinContactType.WebPage
                    .HyperlinkSetWebsiteUrl(ClientContactMethod.Value, client.ClientId, CStr(ClientContactMethod.Pk))
                  Case Else
                    If ClientContactMethod.LinkedClientPk <> 0 Then
                      .HyperlinkSetFormShow("Clients", ClientContactMethod.LinkedClientId)
                    End If
                End Select
              End With

              ' Notes
              If showNotes AndAlso HasNotes Then
                .Cells.AddText(ClientContactMethod.Notes)
              End If
            End With
          End If
        Next
      End With
    End If

    ' Link to show all Contacts
    If callerScriptInfo.FormKey = "Clients" Then
      SummaryTableMain.TextAfter = "{{info|See **[[app://FormShow?page=Contacts|Contacts]]** page for full contact details.}}"
    ElseIf client.IsNew Then
      ' Unsaved Client, therefore we cannot link to show a Page on the Clients form
    Else
      SummaryTableMain.TextAfter = "{{info|See **[[app://FormShow?form=Clients&id=" & client.ClientId & "&page=Contacts|Contacts]]** page for full contact details.}}"
    End If

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Client Related Employment Summary.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="client">
  '''  The Client to summarise.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Client Key Details page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Client_RelatedEmployment(callerScriptInfo As ISScriptExecutionInfo,
                                                       client As finClient,
                                              Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' Client_RelatedEmployment
    '
    ' Version: 1.02 (08/02/2024)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.01  19/04/2016  ISS                  
    '    1.02  08/02/2024  ISS      J032871   Updated to work with Client.Employments collection
    ' #################################################################

    Dim ClientEmployment As finClientEmployment
    Dim LinkedRecordId As String
    Dim SpecialType As isefinClientSpecialType
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim TypeText As String

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .Caption = ""
      .AutoStripe = True

      ' Columns
      With .Columns
        .AddCode("Type", 5)
        .AddCode("Code", 5)
        .AddText("Name")
        If finBL.Settings.AddOns.ExternalParty Then
          .AddBoolean("Rep")
        End If
        .AddBoolean("Current")
      End With

      ' Add Rows
      For Each ClientEmployment In client.Employments
        If ClientEmployment.LinkedClient Is Nothing Then
          TypeText = ""
        Else
          SpecialType = ClientEmployment.LinkedClient.SpecialType
          Select Case SpecialType
            Case isefinClientSpecialType.Branch
              TypeText = "Branch"
              LinkedRecordId = ClientEmployment.LinkedClient.ParentBranch.BranchId

            Case isefinClientSpecialType.ExternalParty
              If finBL.Settings.AddOns.ExternalParty Then
                TypeText = ClientEmployment.LinkedClient.ParentExternalPartyRO.ExternalPartyTypeText
                LinkedRecordId = ClientEmployment.LinkedClient.ParentExternalPartyRO.ExternalPartyId
              Else
                TypeText = ""
              End If

            Case Else
              TypeText = ""
          End Select
        End If

        If Len(TypeText) <> 0 Then
          With .Rows.Add().Cells
            .AddText(TypeText)
            With .AddText(LinkedRecordId)
              Select Case SpecialType
                Case isefinClientSpecialType.Branch
                  .HyperlinkSetFormShow("Branches", LinkedRecordId)
                Case isefinClientSpecialType.ExternalParty
                  .HyperlinkSetFormShow("ExternalParties", LinkedRecordId)
              End Select
            End With
            .AddText(finBL.Database.GetFieldString(ClientEmployment.LinkedClient.Name))
            If finBL.Settings.AddOns.ExternalParty Then
              If finBL.Database.GetFieldIntegerBoolean(ClientEmployment.ActiveSalesRep) Then
                .AddText("{{tick}}")
              Else
                .AddText("")
              End If
            End If
            If ClientEmployment.IsCurrent Then
              .AddText("{{tick}}")
            Else
              .AddText("")
            End If
          End With
        End If
      Next
    End With

    ' Clear table if nothing added (i.e., only contains a header row)
    If SummaryTableMain.Rows.Count < 2 Then SummaryTableMain.Rows.Clear()

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Client Contact Address Summary (Version 1.01, Last updated 19/04/2016).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="clientContactAddress">
  '''  The Client Contact Address to summarise.
  ''' </param>
  ''' <param name="includeFormShowHyperlink">
  '''  Indicates whether to include a hyperlink to show the form, e.g., when the Contact Address is linked to a Client.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Client Contacts Summary.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''    <item><code>Notes</code><description>Note details.</description></item>
  '''    <item><code>OtherDetails</code><description>Other details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function ClientContactAddress_Summary(callerScriptInfo As ISScriptExecutionInfo,
                                                           clientContactAddress As finClientContactAddress,
                                                  Optional includeFormShowHyperlink As Boolean = True,
                                                  Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim DateAsAt As Date
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTableNotes As ISSummaryTable
    Dim SummaryTableOtherDetails As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Date As At
    DateAsAt = finBL.TimeZoneFunctions.GetCurrentDatabaseDate()

    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Columns.AddText(16)
      .Columns.AddText()

      With .Rows
        ' Address
        If finBL.ContactMethods.Exists(clientContactAddress.ContactMethodId) Then
          .AddCaptionText("Contact:", finBL.ContactMethods(clientContactAddress.ContactMethodId).DescriptionShortResolved)
        Else
          ' Probably an incomplete, unsaved record from an Account Application
        End If
        If clientContactAddress.AddressPhysical Then
          .AddCaptionAddressDetailsPhysical("Address:", clientContactAddress.ToAddressDetails(), iseSummaryTableCellClass.Highlight1)
        Else
          .AddCaptionAddressDetailsPostal("Address:", clientContactAddress.ToAddressDetails(), iseSummaryTableCellClass.Highlight1)
        End If
        .AddCaptionTick("Physical:", clientContactAddress.AddressPhysical, False)
        .AddCaptionTick("Postal:", clientContactAddress.AddressPostal, False)
        .AddCaptionText("Status:", clientContactAddress.AddressStatus)
      End With

      ' Warnings
      If clientContactAddress.DateStop <> Nothing AndAlso DateAsAt > clientContactAddress.DateStop Then
        Warnings &= "{{warning|Expired on **" & finBL.FormatDate(clientContactAddress.DateStop, True) & "**.}}"
      ElseIf clientContactAddress.DateStart <> Nothing AndAlso DateAsAt < clientContactAddress.DateStart Then
        Warnings &= "{{info|Not valid until **" & finBL.FormatDate(clientContactAddress.DateStart, True) & "**.}}"
      End If
      .TextAfter = Warnings
    End With

    ' Notes
    If Len(clientContactAddress.Notes) <> 0 Then
      SummaryTableNotes = finBL.CreateSummaryTable()
      With SummaryTableNotes
        ' Initialise
        .TableClass = iseSummaryTableClass.Information
        .Caption = "Notes"
        .Columns.AddText(16)
        .Columns.AddText()

        .Rows.AddText(clientContactAddress.Notes)
      End With
    End If

    ' Other Details
    If clientContactAddress.DateStart <> Nothing OrElse clientContactAddress.DateStop <> Nothing OrElse clientContactAddress.Historic Then
      SummaryTableOtherDetails = finBL.CreateSummaryTable()
      With SummaryTableOtherDetails
        ' Initialise
        .TableClass = iseSummaryTableClass.Information
        .Caption = "Valid Period"
        .Columns.AddText(16).NoBreakChars = 40
        .Columns.AddText()

        .Rows.AddCaptionDate("Valid From:", clientContactAddress.DateStart)
        .Rows.AddCaptionDate("Valid To:", clientContactAddress.DateStop)

        If clientContactAddress.Historic Then
          If clientContactAddress.DateStart = Nothing AndAlso clientContactAddress.DateStop = Nothing Then
            .TextAfter = "{{info|This is a historic record.}}"
          Else
            .TextAfter = "{{info|This is a historic record and the dates displayed are estimates.}}"
          End If
        End If
      End With
    End If

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)
    If SummaryTableNotes IsNot Nothing Then SummaryTables.Add("Notes", SummaryTableNotes)
    If SummaryTableOtherDetails IsNot Nothing Then SummaryTables.Add("OtherDetails", SummaryTableOtherDetails)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Client Contact Method Summary.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="clientContactMethod">
  '''  The Client Contact Method to summarise.
  ''' </param>
  ''' <param name="includeFormShowHyperlink">
  '''  Indicates whether to include a hyperlink to show the form, e.g., when the Contact Method is linked to a Client.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Client Contacts Summary.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''    <item><code>Notes</code><description>Note details.</description></item>
  '''    <item><code>OtherDetails</code><description>Other details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function ClientContactMethod_Summary(callerScriptInfo As ISScriptExecutionInfo,
                                                          clientContactMethod As finClientContactMethod,
                                                 Optional includeFormShowHyperlink As Boolean = True,
                                                 Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' ClientContactMethod_Summary
    '
    ' Version: 1.05 (16/01/2024)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.04  12/08/2020  ISS      
    '    1.05  16/04/2024  ISS      J031917   SMS and Email now use "External Party" where appropriate
    ' #################################################################

    Dim DateAsAt As Date
    Dim ExternalParty As finExternalPartyRO
    Dim ExternalPartyId As String
    Dim strTemp As String
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTableNotes As ISSummaryTable
    Dim SummaryTableOtherDetails As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Date As At
    DateAsAt = finBL.TimeZoneFunctions.GetCurrentDatabaseDate()

    ' Special Type
    Select Case clientContactMethod.Client.SpecialType
      Case isefinClientSpecialType.ExternalParty
        If finBL.Settings.AddOns.ExternalParty Then
          ExternalParty = clientContactMethod.Client.ParentExternalPartyRO

          If ExternalParty IsNot Nothing Then
            ExternalPartyId = ExternalParty.ExternalPartyId
          End If
        End If
    End Select

    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Columns.AddText(16).NoBreakChars = 40
      .Columns.AddText()

      ' Contact Method
      With .Rows
        If finBL.ContactMethods.Exists(clientContactMethod.ContactMethodId) Then
          If Len(clientContactMethod.ValueType) = 0 Then
            .AddCaptionText("Contact:", finBL.ContactMethods(clientContactMethod.ContactMethodId).DescriptionShortResolved)
          Else
            .AddCaptionText("Contact:", String.Format("{0} ({1})", finBL.ContactMethods(clientContactMethod.ContactMethodId).DescriptionShortResolved, clientContactMethod.ValueType))
          End If
        Else
          ' Probably an incomplete, unsaved record from an Account Application
        End If

        If clientContactMethod.LinkedClientPk = 0 Then
          If clientContactMethod.ContactType = isefinContactType.Other Then
            .AddCaptionText("Details:", clientContactMethod.Value, iseSummaryTableCellClass.Highlight1)
          Else
            If clientContactMethod.Client IsNot Nothing AndAlso clientContactMethod.Client.IsNew Then
              ' Cannot hyperlink new records, e.g., from an Account Application
              .AddCaptionText("Details:", clientContactMethod.Value, iseSummaryTableCellClass.Highlight1)
            Else
              Select Case clientContactMethod.ContactType
                Case isefinContactType.Email
                  .AddCaptionWiki("Details:", String.Format("[[app://contact?clientId={0}&clientContactMethodPk={1}&emailAddress={3}&externalPartyId={4}|{2}]]", finBL.UrlEncode(clientContactMethod.Client().ClientId), clientContactMethod.Pk, clientContactMethod.Value, finBL.UrlEncode(clientContactMethod.Value), finBL.UrlEncode(ExternalPartyId)), iseSummaryTableCellClass.Highlight1)

                Case isefinContactType.Phone
                  .AddCaptionWiki("Details:", String.Format("[[app://contact?clientId={0}&clientContactMethodPk={1}&phoneNumber={3}&phoneSms={4}&externalPartyId={5}|{2}]]", finBL.UrlEncode(clientContactMethod.Client().ClientId), clientContactMethod.Pk, clientContactMethod.Value, finBL.UrlEncode(clientContactMethod.Value), clientContactMethod.PhoneSms, finBL.UrlEncode(ExternalPartyId)), iseSummaryTableCellClass.Highlight1)

                Case isefinContactType.WebPage
                  .AddCaptionWiki("Details:", String.Format("[[app://contact?clientId={0}&clientContactMethodPk={1}&websiteUrl={3}|{2}]]", finBL.UrlEncode(clientContactMethod.Client().ClientId), clientContactMethod.Pk, clientContactMethod.Value, finBL.UrlEncode(clientContactMethod.Value)), iseSummaryTableCellClass.Highlight1)
                Case Else
                  .AddCaptionWiki("Details:", String.Format("[[app://contact?clientId={0}&clientContactMethodPk={1}|{2}]]", finBL.UrlEncode(clientContactMethod.Client().ClientId), clientContactMethod.Pk, clientContactMethod.Value), iseSummaryTableCellClass.Highlight1)
              End Select
            End If
          End If
        Else
          .AddCaptionCodeDescriptionWithFormShow("Details:", clientContactMethod.LinkedClientPk, finBL.ClientFunctions, "Clients", iseSummaryTableCellClass.Highlight1)
        End If

        If finBL.ContactMethods.Exists(clientContactMethod.ContactMethodId) Then
          strTemp = ""
          Select Case finBL.ContactMethods(clientContactMethod.ContactMethodId).ContactType
            Case isefinContactType.Email
              If clientContactMethod.EmailHtml Then
                If Len(strTemp) <> 0 Then strTemp &= ", "
                strTemp &= "HTML Format"
              End If

            Case isefinContactType.Phone
              If clientContactMethod.PhoneVoice Then
                If Len(strTemp) <> 0 Then strTemp &= ", "
                strTemp &= "Voice"
              End If
              If clientContactMethod.PhoneSms Then
                If Len(strTemp) <> 0 Then strTemp &= ", "
                strTemp &= "SMS"
              End If
              If clientContactMethod.ContactMethod.PhoneMMS Then
                If clientContactMethod.PhoneMms Then
                  If Len(strTemp) <> 0 Then strTemp &= ", "
                  strTemp &= "MMS"
                End If
              End If
              If clientContactMethod.PhoneFacsimile Then
                If Len(strTemp) <> 0 Then strTemp &= ", "
                strTemp &= "Fax"
              End If
          End Select
          If Len(strTemp) <> 0 Then
            .AddCaptionText("Supports:", strTemp)
          End If
        Else
          ' Probably an incomplete, unsaved record from an Account Application
        End If
      End With

      ' Warnings
      If clientContactMethod.DateStop <> Nothing AndAlso DateAsAt > clientContactMethod.DateStop Then
        Warnings &= "{{warning|Expired on **" & finBL.FormatDate(clientContactMethod.DateStop, True) & "**.}}"
      ElseIf clientContactMethod.DateStart <> Nothing AndAlso DateAsAt < clientContactMethod.DateStart Then
        Warnings &= "{{info|Not valid until **" & finBL.FormatDate(clientContactMethod.DateStart, True) & "**.}}"
      End If
      .TextAfter = Warnings
    End With

    ' Notes
    If Len(clientContactMethod.Notes) <> 0 Then
      SummaryTableNotes = finBL.CreateSummaryTable()
      With SummaryTableNotes
        ' Initialise
        .TableClass = iseSummaryTableClass.Information
        .Caption = "Notes"
        .Columns.AddText(16).NoBreakChars = 40
        .Columns.AddText()

        .Rows.AddText(clientContactMethod.Notes)
      End With
    End If

    ' Other Details
    If clientContactMethod.DateStart <> Nothing OrElse clientContactMethod.DateStop <> Nothing OrElse clientContactMethod.Historic Then
      SummaryTableOtherDetails = finBL.CreateSummaryTable()
      With SummaryTableOtherDetails
        ' Initialise
        .TableClass = iseSummaryTableClass.Information
        .Caption = "Valid Period"
        .Columns.AddText(16).NoBreakChars = 40
        .Columns.AddText()

        .Rows.AddCaptionDate("Valid From:", clientContactMethod.DateStart)
        .Rows.AddCaptionDate("Valid To:", clientContactMethod.DateStop)

        If clientContactMethod.Historic Then
          If clientContactMethod.DateStart = Nothing AndAlso clientContactMethod.DateStop = Nothing Then
            .TextAfter = "{{info|This is a historic record.}}"
          Else
            .TextAfter = "{{info|This is a historic record and the dates displayed are estimates.}}"
          End If
        End If
      End With
    End If

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)
    If SummaryTableNotes IsNot Nothing Then SummaryTables.Add("Notes", SummaryTableNotes)
    If SummaryTableOtherDetails IsNot Nothing Then SummaryTables.Add("OtherDetails", SummaryTableOtherDetails)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Client Employment Summary.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="clientEmployment">
  '''  The Client Employment to summarise.
  ''' </param>
  ''' <param name="includeFormShowHyperlink">
  '''  Indicates whether to include a hyperlink to show the form.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Client Employment Summary.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''    <item><code>Other</code><description>Other details.</description></item>
  '''    <item><code>Notes</code><description>Note details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function ClientEmployment_Summary(callerScriptInfo As ISScriptExecutionInfo,
                                                       clientEmployment As finClientEmployment,
                                              Optional includeFormShowHyperlink As Boolean = True,
                                              Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' ClientEmployment_Summary
    '
    ' Version: 1.03 (16/01/2024)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.03  16/01/2024  ISS      J032708   Add Individual Date of Birth
    ' #################################################################

    Dim strTemp As String
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTableNotes As ISSummaryTable
    Dim SummaryTableOther As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTableNotes = finBL.CreateSummaryTable()
    SummaryTableOther = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Columns.AddText(16)
      .Columns.AddText()

      With .Rows
        ' General
        If clientEmployment.IsOrganisation Then
          If clientEmployment.LinkedClientPk = 0 Then
            .AddCaptionText("Name:", clientEmployment.OrganisationName, iseSummaryTableCellClass.Highlight1)
          Else
            .AddCaptionCodeDescriptionWithFormShow("Name:", clientEmployment.LinkedClientPk, finBL.ClientFunctions, "Clients", iseSummaryTableCellClass.Highlight1)
          End If
        Else
          If clientEmployment.IsExternalPartyEmployment Then
            If Len(clientEmployment.ClientEmploymentId) = 0 Then
              .AddCaptionWiki("Code:", "{{warning|No code specified.}}")
            Else
              .AddCaptionText("Code", clientEmployment.ClientEmploymentId)
            End If
          End If
          If clientEmployment.LinkedClientPk = 0 Then
            .AddCaptionText("Name:", clientEmployment.IndividualName, iseSummaryTableCellClass.Highlight1)
          Else
            .AddCaptionCodeDescriptionWithFormShow("Name:", clientEmployment.LinkedClientPk, finBL.ClientFunctions, "Clients", iseSummaryTableCellClass.Highlight1)
          End If

          If clientEmployment.IndividualDateOfBirth = Nothing Then
            strTemp = ""
          Else
            strTemp = String.Format("{0} old", finBL.Runtime.DateUtilities.AgeAsText(clientEmployment.IndividualDateOfBirth))
          End If
          .AddCaptionWiki("Date of Birth:", String.Format("**{0}** --{1}--", finBL.FormatDateLong(clientEmployment.IndividualDateOfBirth), strTemp))
          .AddCaptionText("Gender:", finBL.Enums.isefinGender_ToString(clientEmployment.IndividualGender))
        End If
        .AddCaptionText("Role Type:", clientEmployment.RoleType)
        If clientEmployment.LinkedClientPk = 0 Then
          strTemp = clientEmployment.PhoneNumber
          If Len(clientEmployment.Extension) <> 0 Then strTemp &= String.Format(" Ext {0}", clientEmployment.Extension)
          .AddCaptionTextPhoneNumber("Phone:", strTemp)
          .AddCaptionTextEmailAddress("Email:", clientEmployment.Email)
        Else
          .AddCaptionTextPhoneNumber("Phone:", clientEmployment.LinkedClient.ContactMethods.GetCurrentPhone().Value)
          .AddCaptionTextEmailAddress("Email:", clientEmployment.LinkedClient.ContactMethods.GetCurrentEmail().Value)
        End If
        If clientEmployment.IsExternalPartyEmployment Then
          .AddCheckBox("Is this person an Active Sales Representative for this External Party?", clientEmployment.ActiveSalesRep)
          .AddCheckBox("Is Employee available to Sub External Parties?", clientEmployment.AvailableToSubExternalParties)
        End If
      End With

      ' Warnings
      .TextAfter = Warnings
    End With

    ' Other
    Warnings = ""
    With SummaryTableOther
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = "Employment Details"
      .Columns.AddText(16)
      .Columns.AddText()

      With .Rows
        ' Employment Details
        .AddCaptionDate("From:", clientEmployment.DateStart)
        If clientEmployment.DateStop <> Nothing Then
          .AddCaptionDate("To:", clientEmployment.DateStop)
        End If
        .AddCaptionText("Period:", clientEmployment.TimeSpanText)
        If Len(clientEmployment.Occupation) <> 0 Then
          .AddCaptionText("Occupation:", clientEmployment.Occupation)
        End If
        If Len(clientEmployment.JobTitle) <> 0 Then
          .AddCaptionText("Job Title:", clientEmployment.JobTitle)
        End If
        If Len(clientEmployment.EmploymentType) <> 0 Then
          .AddCaptionText("Type:", clientEmployment.EmploymentType)
        End If
        If Len(clientEmployment.EmploymentBasis) <> 0 Then
          .AddCaptionText("Basis:", clientEmployment.EmploymentBasis)
        End If
      End With

      If clientEmployment.Historic Then
        If clientEmployment.DateStart = Nothing AndAlso clientEmployment.DateStop = Nothing Then
          Warnings &= "{{info|This is a historic record.}}"
        Else
          Warnings &= "{{info|This is a historic record and the dates displayed are estimates.}}"
        End If
      End If

      ' Warnings
      .TextAfter = Warnings
    End With

    ' Notes
    If Len(clientEmployment.Notes) <> 0 Then
      With SummaryTableNotes
        ' Initialise
        .TableClass = iseSummaryTableClass.Information
        .Caption = "Notes"
        .Columns.AddText()

        With .Rows
          .AddText(clientEmployment.Notes)
        End With
      End With
    End If

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)
    SummaryTables.Add("Other", SummaryTableOther)
    If SummaryTableNotes.HasData Then SummaryTables.Add("Notes", SummaryTableNotes)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Client Employment External User Summary (Version 1.00, Last updated 01/12/2015).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="clientEmployment">
  '''  The Client Employment to summarise.
  ''' </param>
  ''' <param name="includeFormShowHyperlink">
  '''  Indicates whether to include a hyperlink to show the form.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Client Employment Summary.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function ClientEmployment_ExternalUser(callerScriptInfo As ISScriptExecutionInfo,
                                                            clientEmployment As finClientEmployment,
                                                   Optional includeFormShowHyperlink As Boolean = True,
                                                   Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim User As finUser
    Dim Warnings As String

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Columns.AddText(16)
      .Columns.AddText()

      With .Rows
        If Len(clientEmployment.ExternalUserId) = 0 Then
          Warnings &= "{{info|This Employee is not configured to login to " & finBL.AppTitle & ".}}"
        Else
          ' Load User
          User = finBL.CreateUser()
          User.Load(clientEmployment.ExternalUserId)

          .AddCaptionCodeDescriptionWithFormShow("User:", User.Pk, finBL.Users, "UsersExtended")
          .AddCaptionTick("Active:", User.Active, True)

          If User.IsLockedOut Then
            Warnings &= "{{warning|User account is locked out. User will not be able to login.}}"
          ElseIf Not User.Active Then
            Warnings &= "{{warning|User is not active and will not be able to login.}}"
          End If
        End If
      End With

      ' Warnings
      .TextAfter = Warnings
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Client Identification Summary
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="clientIdentificationItem">
  '''  The Client Identification Item to summarise.
  ''' </param>
  ''' <param name="includeFormShowHyperlink">
  '''  Indicates whether to include a hyperlink to show the form.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Client Identification Summary.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''    <item><code>Issuer</code><description>Issuer details.</description></item>
  '''    <item><code>Notes</code><description>Note details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function ClientIdentificationItem_Summary(callerScriptInfo As ISScriptExecutionInfo,
                                                               clientIdentificationItem As finClientIdentificationItem,
                                                      Optional includeFormShowHyperlink As Boolean = True,
                                                      Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' ClientIdentificationItem_Summary
    '
    ' Version: 1.06 (01/12/2022)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.02  14/06/2016  ISS                  
    '    1.03  06/09/2021  ISS      J027127   Drivers Licence Type (AU and NZ)
    '    1.04  18/01/2022  ISS      J028079   AU Drivers Licence Card Number
    '    1.05  06/10/2022  ISS      J029781   AU Medicare Expiry Date updated
    '    1.06  01/12/2022  ISS      J029590   Add support for NZ Firearms Licence
    '    1.07  01/12/2022  ISS      J030432   Rename "Type" to "ID Type"
    ' #################################################################

    Dim IdentificationType As finIdentificationTypeRO
    Dim SummaryTableIssuer As ISSummaryTable
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTableNotes As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableIssuer = finBL.CreateSummaryTable()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTableNotes = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Cache Identification Type
    IdentificationType = clientIdentificationItem.IdentificationType

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      .Columns.AddText(20)
      .Columns.AddText()

      ' Warnings
      Warnings = ""

      With .Rows
        .AddCaptionCodeDescription("ID Type:", clientIdentificationItem.IdentificationTypeId, finBL.IdentificationTypes)

        If IdentificationType Is Nothing Then
          ' Probably from a Temporary Client
        Else
          Select Case IdentificationType.SpecialType
            Case isefinIdentificationTypeSpecialType.None
              .AddCaptionText(IdentificationType.DetailsToRecordResolved & ":", clientIdentificationItem.Value)
              If IdentificationType.AllowName Then
                .AddCaptionText("Name:", clientIdentificationItem.IdName)
              End If
              If IdentificationType.AllowDateOfBirth Then
                .AddCaptionDate("Date of Birth:", clientIdentificationItem.IdDateOfBirth)
              End If
              If IdentificationType.AllowAddress Then
                .AddCaptionText("Address:", clientIdentificationItem.IdAddress)
              End If

            Case isefinIdentificationTypeSpecialType.AU_DriversLicence
              .AddText(finBL.Enums.isefinIdentificationTypeSpecialType_ToString(IdentificationType.SpecialType), iseSummaryTableCellClass.SectionHeading2)
              .AddCaptionText("State:", clientIdentificationItem.AU_DriversLicence.State)
              .AddCaptionText("Licence No.:", clientIdentificationItem.AU_DriversLicence.LicenceNumber)
              .AddCaptionText("Card No.:", clientIdentificationItem.AU_DriversLicence.CardNumber)
              .AddCaptionText("Family Name:", clientIdentificationItem.AU_DriversLicence.FamilyName)
              .AddCaptionText("Other Names:", clientIdentificationItem.AU_DriversLicence.OtherNames)
              .AddCaptionText("Address:", clientIdentificationItem.AU_DriversLicence.Address)
              .AddCaptionDate("Date of Birth:", clientIdentificationItem.AU_DriversLicence.DateOfBirth)
              .AddCaptionText("Licence Type:", clientIdentificationItem.AU_DriversLicence.LicenceType)
              .AddCaptionDate("Expiry Date:", clientIdentificationItem.AU_DriversLicence.DateExpiry)

            Case isefinIdentificationTypeSpecialType.AU_Medicare
              .AddText(finBL.Enums.isefinIdentificationTypeSpecialType_ToString(IdentificationType.SpecialType), iseSummaryTableCellClass.SectionHeading2)
              .AddCaptionText("Colour:", clientIdentificationItem.AU_Medicare.Colour)
              .AddCaptionText("Card Number.:", clientIdentificationItem.AU_Medicare.CardNumber)
              .AddCaptionText("Reference No.:", clientIdentificationItem.AU_Medicare.IndividualReference)
              .AddCaptionText("Name:", clientIdentificationItem.AU_Medicare.CardName)
              If clientIdentificationItem.DateExpiryMonthYearOnly Then
                .AddCaptionText("Expiry Date:", Format(clientIdentificationItem.AU_Medicare.DateExpiry, "MM/yyyy"))
              Else
                .AddCaptionDate("Expiry Date:", clientIdentificationItem.AU_Medicare.DateExpiry)
              End If

            Case isefinIdentificationTypeSpecialType.AU_Passport
              .AddText(finBL.Enums.isefinIdentificationTypeSpecialType_ToString(IdentificationType.SpecialType), iseSummaryTableCellClass.SectionHeading2)
              .AddCaptionText("Document No.:", clientIdentificationItem.AU_Passport.DocumentNumber)
              .AddCaptionText("Family Name:", clientIdentificationItem.AU_Passport.FamilyName)
              .AddCaptionText("Given Names:", clientIdentificationItem.AU_Passport.GivenNames)
              .AddCaptionDate("Date of Birth:", clientIdentificationItem.AU_Passport.DateOfBirth)
              .AddCaptionDate("Date of Issue:", clientIdentificationItem.AU_Passport.DateIssue)
              .AddCaptionDate("Date of Expiry:", clientIdentificationItem.AU_Passport.DateExpiry)

            Case isefinIdentificationTypeSpecialType.NZ_DriversLicence
              .AddText(finBL.Enums.isefinIdentificationTypeSpecialType_ToString(IdentificationType.SpecialType), iseSummaryTableCellClass.SectionHeading2)
              .AddCaptionText("Licence Type:", clientIdentificationItem.NZ_DriversLicence.LicenceType)
              .AddCaptionText("1. Family Name:", clientIdentificationItem.NZ_DriversLicence.FamilyName)
              .AddCaptionText("2. Other Names:", clientIdentificationItem.NZ_DriversLicence.OtherNames)
              .AddCaptionDate("3. Date of Birth:", clientIdentificationItem.NZ_DriversLicence.DateOfBirth)
              .AddCaptionDate("4a. Issue Date:", clientIdentificationItem.NZ_DriversLicence.DateIssue)
              .AddCaptionDate("4b. Expiry Date:", clientIdentificationItem.NZ_DriversLicence.DateExpiry)
              .AddCaptionText("5a. Licence:", clientIdentificationItem.NZ_DriversLicence.LicenceNumber)
              .AddCaptionText("5b. Version:", clientIdentificationItem.NZ_DriversLicence.VersionNumber)

            Case isefinIdentificationTypeSpecialType.NZ_FirearmsLicence
              .AddText(finBL.Enums.isefinIdentificationTypeSpecialType_ToString(IdentificationType.SpecialType), iseSummaryTableCellClass.SectionHeading2)
              .AddCaptionText("Family Name:", clientIdentificationItem.NZ_FirearmsLicence.FamilyName)
              .AddCaptionText("Other Names:", clientIdentificationItem.NZ_FirearmsLicence.OtherNames)
              .AddCaptionText("Licence Number:", clientIdentificationItem.NZ_FirearmsLicence.LicenceNumber)
              .AddCaptionText("Version Number:", clientIdentificationItem.NZ_FirearmsLicence.VersionNumber)
              .AddCaptionDate("Expiry Date:", clientIdentificationItem.NZ_FirearmsLicence.DateExpiry)
              .AddCaptionDate("Date of Birth:", clientIdentificationItem.NZ_FirearmsLicence.DateOfBirth)

            Case isefinIdentificationTypeSpecialType.NZ_Passport
              .AddText(finBL.Enums.isefinIdentificationTypeSpecialType_ToString(IdentificationType.SpecialType), iseSummaryTableCellClass.SectionHeading2)
              .AddCaptionText("Passport No.:", clientIdentificationItem.NZ_Passport.PassportNumber)
              .AddCaptionText("Surname:", clientIdentificationItem.NZ_Passport.Surname)
              .AddCaptionText("Given Names:", clientIdentificationItem.NZ_Passport.GivenNames)
              .AddCaptionDate("Date of Birth:", clientIdentificationItem.NZ_Passport.DateOfBirth)
              .AddCaptionDate("Date of Issue:", clientIdentificationItem.NZ_Passport.DateIssue)
              .AddCaptionDate("Date of Expiry:", clientIdentificationItem.NZ_Passport.DateExpiry)

            Case isefinIdentificationTypeSpecialType.US_DriversLicence
              .AddText(finBL.Enums.isefinIdentificationTypeSpecialType_ToString(IdentificationType.SpecialType), iseSummaryTableCellClass.SectionHeading2)
              .AddCaptionText("State:", clientIdentificationItem.US_DriversLicence.State)
              .AddCaptionText("Licence No.:", clientIdentificationItem.US_DriversLicence.LicenceNumber)
              .AddCaptionText("Surname:", clientIdentificationItem.US_DriversLicence.Surname)
              .AddCaptionText("Other Names:", clientIdentificationItem.US_DriversLicence.OtherNames)
              .AddCaptionText("Address:", clientIdentificationItem.US_DriversLicence.Address)
              .AddCaptionDate("Date of Birth:", clientIdentificationItem.US_DriversLicence.DateOfBirth)
              .AddCaptionDate("Expiry Date:", clientIdentificationItem.US_DriversLicence.DateExpiry)
              .AddCaptionText("Gender:", clientIdentificationItem.US_DriversLicence.GenderText)

            Case isefinIdentificationTypeSpecialType.US_Passport
              .AddText(finBL.Enums.isefinIdentificationTypeSpecialType_ToString(IdentificationType.SpecialType), iseSummaryTableCellClass.SectionHeading2)
              .AddCaptionText("Passport No.:", clientIdentificationItem.US_Passport.PassportNumber)
              .AddCaptionText("Surname:", clientIdentificationItem.US_Passport.Surname)
              .AddCaptionText("Given Names:", clientIdentificationItem.US_Passport.GivenNames)
              .AddCaptionDate("Date of Birth:", clientIdentificationItem.US_Passport.DateOfBirth)
              .AddCaptionDate("Date of Issue:", clientIdentificationItem.US_Passport.DateIssue)
              .AddCaptionDate("Date of Expiry:", clientIdentificationItem.US_Passport.DateExpiry)
          End Select
        End If
      End With

      ' Warnings
      If Not clientIdentificationItem.Active Then
        If Len(Warnings) <> 0 Then Warnings &= vbNewLine
        Warnings &= "{{warning|This Identification Item is not Active.}}"
      End If
      .TextAfter = Warnings
    End With

    ' Issuer
    If IdentificationType IsNot Nothing AndAlso IdentificationType.SpecialType = isefinIdentificationTypeSpecialType.None AndAlso (IdentificationType.AllowIssuer OrElse IdentificationType.AllowExpiryDate) Then
      With SummaryTableIssuer
        ' Initialise
        .TableClass = iseSummaryTableClass.Information
        If IdentificationType.AllowIssuer AndAlso IdentificationType.AllowExpiryDate Then
          .Caption = "Issuer and Expiry details"
        ElseIf IdentificationType.AllowIssuer Then
          .Caption = "Issuer details"
        Else
          .Caption = "Expiry details"
        End If
        .Columns.AddText(20)
        .Columns.AddText()

        ' Warnings
        Warnings = ""

        With .Rows
          If IdentificationType.AllowIssuer Then
            .AddCaptionText("Issuer:", clientIdentificationItem.Issuer)
            .AddCaptionDate("Issued:", clientIdentificationItem.DateIssue)
          End If
          If IdentificationType.AllowExpiryDate Then
            .AddCaptionDate("Expires:", clientIdentificationItem.DateExpiry)
          End If
        End With

        ' Warnings
        If clientIdentificationItem.Historic Then
          If Len(Warnings) <> 0 Then Warnings &= vbNewLine
          Warnings &= "{{info|This is historic information and the dates displayed are estimates.}}"
        End If
        .TextAfter = Warnings
      End With
    End If

    ' Notes
    If Len(clientIdentificationItem.Notes) <> 0 Then
      With SummaryTableNotes
        ' Initialise
        .TableClass = iseSummaryTableClass.Information
        .Caption = "Notes"
        .Columns.AddText()

        With .Rows
          .AddText(clientIdentificationItem.Notes)
        End With
      End With
    End If

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)
    If SummaryTableIssuer.HasData Then SummaryTables.Add("Issuer", SummaryTableIssuer)
    If SummaryTableNotes.HasData Then SummaryTables.Add("Notes", SummaryTableNotes)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Client Identification Verification and Approval Summary (Version 1.00, Last updated 14/08/2015).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="clientIdentificationItem">
  '''  The Client Identification Item to summarise.
  ''' </param>
  ''' <param name="includeFormShowHyperlink">
  '''  Indicates whether to include a hyperlink to show the form.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Client Identification Summary.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Verification</code><description>Verification details.</description></item>
  '''    <item><code>Approval</code><description>Approval details.</description></item>
  '''    <item><code>Warnings</code><description>Warning details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function ClientIdentificationItem_VerificationAndApproval(callerScriptInfo As ISScriptExecutionInfo,
                                                                               clientIdentificationItem As finClientIdentificationItem,
                                                                      Optional includeFormShowHyperlink As Boolean = True,
                                                                      Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim SummaryTableApproval As ISSummaryTable
    Dim SummaryTableVerification As ISSummaryTable
    Dim SummaryTableWarnings As ISSummaryTable
    Dim SummaryTables As ISSummaryTables

    ' Initialise

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableApproval = finBL.CreateSummaryTable()
    SummaryTableVerification = finBL.CreateSummaryTable()
    SummaryTableWarnings = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Verification
    With SummaryTableVerification
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = "Verification"
      .Columns.AddText(16)
      .Columns.AddText()

      With .Rows
        If finBL.Settings.ClientIdentificationVerificationOption = isefinVerificationOption.VerificationAndApproval Then
          If clientIdentificationItem.VerificationUserPk <> 0 Then
            .AddCaptionWiki("User:", String.Format("**{0}**, {1}", finBL.Users.ItemByPk(clientIdentificationItem.VerificationUserPk).UserId, finBL.Users.ItemByPk(clientIdentificationItem.VerificationUserPk).Name))
          End If
          If clientIdentificationItem.VerificationDate <> Nothing Then
            .AddCaptionDateTime("Date:", clientIdentificationItem.VerificationDate)
          End If
        End If
      End With
    End With

    ' Approval
    With SummaryTableApproval
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = "Approval"
      .Columns.AddText(16)
      .Columns.AddText()

      With .Rows
        If clientIdentificationItem.ApprovalUserPk <> 0 Then
          .AddCaptionWiki("User:", String.Format("**{0}**, {1}", finBL.Users.ItemByPk(clientIdentificationItem.ApprovalUserPk).UserId, finBL.Users.ItemByPk(clientIdentificationItem.ApprovalUserPk).Name))
        End If
        If clientIdentificationItem.ApprovalDate <> Nothing Then
          .AddCaptionDateTime("Date:", clientIdentificationItem.ApprovalDate)
        End If
      End With
    End With

    ' Warnings
    With SummaryTableWarnings
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      .Columns.AddText()

      With .Rows
        If clientIdentificationItem.IsCurrent Then
          If finBL.Settings.ClientIdentificationVerificationOption = isefinVerificationOption.VerificationAndApproval AndAlso Not clientIdentificationItem.IsVerified Then
            .AddWiki("{{warning|Awaiting verification.}}")
          ElseIf Not clientIdentificationItem.IsApproved Then
            .AddWiki("{{warning|Awaiting approval.}}")
          End If
        Else
          If finBL.Settings.ClientIdentificationVerificationOption = isefinVerificationOption.VerificationAndApproval AndAlso Not clientIdentificationItem.IsVerified Then
            .AddWiki("{{info|Not verified.}}")
          ElseIf Not clientIdentificationItem.IsApproved Then
            .AddWiki("{{info|Not approved.}}")
          End If
        End If
      End With
    End With

    ' Add Summary Tables
    If SummaryTableVerification.HasData Then SummaryTables.Add("Verification", SummaryTableVerification)
    If SummaryTableApproval.HasData Then SummaryTables.Add("Approval", SummaryTableApproval)
    If SummaryTableWarnings.HasData Then SummaryTables.Add("Warnings", SummaryTableWarnings)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Client Statistics Set Summary (Version 1.04, Last updated 18/12/2020).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="clientStatisticsSet">
  '''  The Client Statistic Set to summarise.
  ''' </param>
  ''' <param name="frequencyPerAnnum">
  '''   The Frequency Per Annum to use.
  ''' </param>
  ''' <param name="showAvailableCalcDetails">
  '''  Indicates whether to display the Calculation Details.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Client Statistic Summary.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''    <item><code>Financial</code><description>Financial details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function ClientStatisticsSet_Summary(callerScriptInfo As ISScriptExecutionInfo,
                                                          clientStatisticsSet As finClientStatisticsSet,
                                                          frequencyPerAnnum As isefinFrequencyPerAnnum,
                                                 Optional showAvailableCalcDetails As Boolean = True,
                                                 Optional includeActions As Boolean = True,
                                                 Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim Client As finClient
    Dim DateAsAt As Date
    Dim strTemp As String
    Dim Suffix As String
    Dim SummaryTableCellClass As iseSummaryTableCellClass
    Dim SummaryTableFinancial As ISSummaryTable
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTableNotes As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableFinancial = finBL.CreateSummaryTable()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTableNotes = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Date As At
    DateAsAt = finBL.TimeZoneFunctions.GetCurrentDatabaseDate()

    ' Cache Client
    Client = clientStatisticsSet.Client

    Warnings = ""
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Columns.AddText(16)
      .Columns.AddText()

      With .Rows
        ' General
        .AddCaptionDateTime("Date As At:", clientStatisticsSet.DateStart)
        strTemp = clientStatisticsSet.StatusText
        Select Case clientStatisticsSet.Status
          Case isefinClientStatisticStatus.Open
            SummaryTableCellClass = iseSummaryTableCellClass.NormalBold
            If finBL.Settings.ClientStatisticsVerificationOption = isefinVerificationOption.VerificationAndApproval AndAlso Not clientStatisticsSet.IsVerified Then
              Suffix = "(awaiting verification)"
            Else
              Suffix = "(awaiting approval)"
            End If
          Case isefinClientStatisticStatus.Approved
            SummaryTableCellClass = iseSummaryTableCellClass.PositiveBold
            Suffix = ""
          Case isefinClientStatisticStatus.Rejected
            SummaryTableCellClass = iseSummaryTableCellClass.WarningBold
            Suffix = ""
          Case isefinClientStatisticStatus.Cancelled
            SummaryTableCellClass = iseSummaryTableCellClass.WarningBold
            Suffix = ""
        End Select
        .AddCaptionText("Status:", strTemp, SummaryTableCellClass, , , Suffix)
        If clientStatisticsSet.Source <> isefinClientStatisticsSetSource.Default Then
          .AddCaptionText("Source:", clientStatisticsSet.SourceText)
        End If
        If clientStatisticsSet.IsCurrent Then
          .AddCaptionDateTime("Expires:", clientStatisticsSet.DateExpiry)
        Else
          With .AddCaptionDateTime("Expired:", clientStatisticsSet.DateExpiry).Cells(1)
            .CellClass = iseSummaryTableCellClass.WarningBold
          End With
        End If
        If Len(clientStatisticsSet.Category) <> 0 Then
          .AddCaptionText("Category:", clientStatisticsSet.Category)
        End If
      End With

      ' Warnings
      Warnings = ""
      If clientStatisticsSet.Status = isefinClientStatisticStatus.Cancelled Then
        If Len(Warnings) <> 0 Then Warnings &= vbNewLine
        Warnings &= "{{warning|Cancelled.}}"
      ElseIf clientStatisticsSet.DateExpiry <> Nothing AndAlso clientStatisticsSet.DateExpiry < DateAsAt Then
        If Len(Warnings) <> 0 Then Warnings &= vbNewLine
        Warnings &= "{{warning|Expired.}}"
      End If
      If Client.StatisticsSetsSupportsAssetsAndLiabilities AndAlso clientStatisticsSet.AssetsAvailable < 0 Then
        If Len(Warnings) <> 0 Then Warnings &= vbNewLine
        Warnings &= "{{warning|Insolvent.}}"
      End If

      ' Warnings
      .TextAfter = Warnings
    End With

    Warnings = ""
    With SummaryTableFinancial
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .AutoStripe = True
      .MaxWidthHtml = "50em"

      If Client.StatisticsSetsSupportsIncomeAndExpenses Then
        .Caption = "Financial: " & finBL.Enums.isefinFrequencyPerAnnum_ToString(frequencyPerAnnum)
      ElseIf Client.StatisticsSetsSupportsAssetsAndLiabilities Then
        .Caption = "Assets & Liabilities"
      End If

      ' Columns
      With .Columns
        .AddText().NoBreakChars = 80
        .AddCurrency(20)
        If Client.StatisticsSetsSupportsAssetsAndLiabilities AndAlso Client.StatisticsSetsSupportsIncomeAndExpenses Then
          .AddText(4) ' Spacer
          .AddText().NoBreakChars = 80
          .AddCurrency(20)
        End If
      End With

      With .Rows
        ' Financial
        With .Add()
          With .Cells
            If Client.StatisticsSetsSupportsIncomeAndExpenses Then
              .AddCaption("Total Income:")
              .AddCurrency(clientStatisticsSet.IncomeTotal(frequencyPerAnnum))
            End If

            If Client.StatisticsSetsSupportsAssetsAndLiabilities Then
              If Client.StatisticsSetsSupportsIncomeAndExpenses Then .AddText("") ' Spacer
              .AddCaption("Total Assets:")
              .AddCurrency(clientStatisticsSet.AssetsTotal())
            End If
          End With
        End With
        With .Add()
          With .Cells
            If Client.StatisticsSetsSupportsIncomeAndExpenses Then
              .AddCaption("Total Expenses:")
              .AddCurrency(clientStatisticsSet.ExpensesTotal(frequencyPerAnnum))
            End If

            If Client.StatisticsSetsSupportsAssetsAndLiabilities Then
              If Client.StatisticsSetsSupportsIncomeAndExpenses Then .AddText("") ' Spacer
              .AddCaption("Total Liabilities:")
              .AddCurrency(clientStatisticsSet.LiabilitiesTotal())
            End If
          End With
        End With
        With .Add()
          With .Cells
            If Client.StatisticsSetsSupportsIncomeAndExpenses Then
              .AddCaption("Net Income:")
              .AddCurrency(clientStatisticsSet.IncomeNet(frequencyPerAnnum))
            End If

            If Client.StatisticsSetsSupportsAssetsAndLiabilities Then
              If Client.StatisticsSetsSupportsIncomeAndExpenses Then .AddText("") ' Spacer
              .AddCaption("Net Assets:")
              .AddCurrency(clientStatisticsSet.AssetsNet())
            End If
          End With
        End With
        With .Add()
          With .Cells
            If Client.StatisticsSetsSupportsIncomeAndExpenses Then
              If showAvailableCalcDetails Then
                If Client.IsIndividual Then
                  strTemp = String.Format("**Available Income:**" & vbNewLine & "--Net Income x {0}--", finBL.FormatPercentage(finBL.ClientGroups.Item(Client.ClientGroupId).IndividualAvailableIncomePercent / 100))
                Else
                  strTemp = String.Format("**Available Income:**" & vbNewLine & "--Net Income x {0}--", finBL.FormatPercentage(finBL.ClientGroups.Item(Client.ClientGroupId).OrganisationAvailableIncomePercent / 100))
                End If
              Else
                strTemp = "**Available Income:**"
              End If
              .AddCaptionWiki(strTemp)
              With .AddCurrency(clientStatisticsSet.IncomeAvailable(frequencyPerAnnum))
                .CellClass = iseSummaryTableCellClass.NormalBold
              End With
            End If

            If Client.StatisticsSetsSupportsAssetsAndLiabilities Then
              If Client.StatisticsSetsSupportsIncomeAndExpenses Then
                .AddText("") ' Spacer
              End If
              If showAvailableCalcDetails Then
                If Client.IsIndividual Then
                  strTemp = String.Format("**Available Assets:**" & vbNewLine & "--(Total Assets x {0}) - Total Liabilities--", finBL.FormatPercentage(finBL.ClientGroups.Item(Client.ClientGroupId).IndividualAvailableAssetsPercent / 100))
                Else
                  strTemp = String.Format("**Available Assets:**" & vbNewLine & "--(Total Assets x {0}) - Total Liabilities--", finBL.FormatPercentage(finBL.ClientGroups.Item(Client.ClientGroupId).OrganisationAvailableAssetsPercent / 100))
                End If
              Else
                strTemp = "**Available Assets:**"
              End If
              .AddCaptionWiki(strTemp)
              With .AddCurrency(clientStatisticsSet.AssetsAvailable())
                .CellClass = iseSummaryTableCellClass.NormalBold
              End With
            End If
          End With
        End With

        ' Footer
        With .Add(iseSummaryTableRowClass.FooterBold)
          With .Cells
            If Client.StatisticsSetsSupportsAssetsAndLiabilities AndAlso Client.StatisticsSetsSupportsIncomeAndExpenses Then
              .AddCaption("")
              .AddText("")
              .AddText("") ' Spacer
            End If

            If Client.StatisticsSetsSupportsAssetsAndLiabilities Then
              .AddCaption("Debt Ratio:")
              .AddPercent(clientStatisticsSet.DebtRatio(), 2, False)
            End If
          End With
        End With
      End With

      ' Warnings
      .TextAfter = Warnings
    End With

    ' Notes
    If Len(clientStatisticsSet.Notes) <> 0 Then
      With SummaryTableNotes
        ' Initialise
        .TableClass = iseSummaryTableClass.Information
        .Caption = "Notes"
        .Columns.AddText(16).NoBreakChars = 40
        .Columns.AddText()

        .Rows.AddText(clientStatisticsSet.Notes)
      End With
    End If

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)
    If SummaryTableFinancial.HasData Then SummaryTables.Add("Financial", SummaryTableFinancial)
    If SummaryTableNotes.HasData Then SummaryTables.Add("Notes", SummaryTableNotes)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Client Statistics Set Verification And Approval Summary (Version 1.01, Last updated 8/04/2016).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="clientStatisticsSet">
  '''  The Client Statistic Set to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Client Statistic Summary.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Verification details.</description></item>
  '''    <item><code>Approval</code><description>Approval details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function ClientStatisticsSet_VerificationAndApproval(callerScriptInfo As ISScriptExecutionInfo,
                                                                          clientStatisticsSet As finClientStatisticsSet,
                                                                 Optional includeActions As Boolean = True,
                                                                 Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim Client As finClient
    Dim SummaryTableApproval As ISSummaryTable
    Dim SummaryTableVerification As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise
    Client = clientStatisticsSet.Client
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableApproval = finBL.CreateSummaryTable()
    SummaryTableVerification = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Verification
    Warnings = ""
    With SummaryTableVerification
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = "Verification"
      With .Columns
        .AddText(10)
        .AddText()
      End With

      With .Rows
        If finBL.Settings.ClientStatisticsVerificationOption = isefinVerificationOption.VerificationAndApproval Then
          If clientStatisticsSet.VerificationUserPk = 0 Then
            .AddCaptionText("User:", "")
          Else
            .AddCaptionCodeDescription("User:", finBL.Users.ItemByPk(clientStatisticsSet.VerificationUserPk).UserId, finBL.Users.ItemByPk(clientStatisticsSet.VerificationUserPk).Name)
          End If
          .AddCaptionDateTime("Date:", clientStatisticsSet.VerificationDate)
        End If
      End With

      ' Warnings
      .TextAfter = Warnings
    End With

    ' Approval
    Warnings = ""
    With SummaryTableApproval
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = clientStatisticsSet.StatusText
      With .Columns
        .AddText(10)
        .AddText()
      End With

      With .Rows
        If clientStatisticsSet.ApprovalUserPk = 0 Then
          .AddCaptionText("User:", "")
        Else
          .AddCaptionCodeDescription("User:", finBL.Users.ItemByPk(clientStatisticsSet.ApprovalUserPk).UserId, finBL.Users.ItemByPk(clientStatisticsSet.ApprovalUserPk).Name)
        End If
        .AddCaptionDateTime("Date:", clientStatisticsSet.ApprovalDate)
      End With

      ' Warnings
      Select Case clientStatisticsSet.Status
        Case isefinClientStatisticStatus.Open
          If finBL.Settings.ClientStatisticsVerificationOption = isefinVerificationOption.VerificationAndApproval AndAlso Not clientStatisticsSet.IsVerified Then
            Warnings &= "{{warning|Awaiting verification.}}"
          Else
            Warnings &= "{{warning|Awaiting approval.}}"
          End If
      End Select

      ' Warnings
      .TextAfter = Warnings
    End With

    ' Add Summary Tables
    If SummaryTableVerification.HasData Then
      SummaryTables.Add("Main", SummaryTableVerification)
      If SummaryTableApproval.HasData Then SummaryTables.Add("Approval", SummaryTableApproval)
    Else
      If SummaryTableApproval.HasData Then SummaryTables.Add("Main", SummaryTableApproval)
    End If

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Client Statistics Set Income and Expenses Summary (Version 1.01, Last updated 8/03/2016).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="clientStatisticsSet">
  '''  The Client Statistic Set to summarise.
  ''' </param>
  ''' <param name="frequencyPerAnnum">
  '''   The Frequency Per Annum to use.
  ''' </param>
  ''' <param name="displayZeroValueStatistics">
  '''  Indicates whether to display Zero Value Statistics.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Client Statistic Summary.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Income</code><description>Income details.</description></item>
  '''    <item><code>Main</code><description>Expenses details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function ClientStatisticsSet_IncomeAndExpenses(callerScriptInfo As ISScriptExecutionInfo,
                                                                    clientStatisticsSet As finClientStatisticsSet,
                                                                    frequencyPerAnnum As isefinFrequencyPerAnnum,
                                                           Optional displayZeroValueStatistics As Boolean = False,
                                                           Optional includeActions As Boolean = True,
                                                           Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim SummaryTables As ISSummaryTables

    ' Initialise
    SummaryTables = finBL.CreateSummaryTables()

    ' Income
    SummaryTables.Add("Income", Me.ClientStatisticsSet_StatisticsSub(callerScriptInfo, clientStatisticsSet.Income, frequencyPerAnnum, displayZeroValueStatistics, includeActions, otherParameters))

    ' Expenses
    SummaryTables.Add("Main", Me.ClientStatisticsSet_StatisticsSub(callerScriptInfo, clientStatisticsSet.Expenses, frequencyPerAnnum, displayZeroValueStatistics, includeActions, otherParameters))

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Client Statistics Summary (Version 1.00, Last updated 14/12/2015).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="clientStatisticsSet">
  '''  The Client Statistic Set to summarise.
  ''' </param>
  ''' <param name="frequencyPerAnnum">
  '''   The Frequency Per Annum to use.
  ''' </param>
  ''' <param name="displayZeroValueStatistics">
  '''  Indicates whether to display Zero Value Statistics.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Client Statistic Summary.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Asset details.</description></item>
  '''    <item><code>Liabilities</code><description>Liabilities details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function ClientStatisticsSet_AssetsAndLiabilities(callerScriptInfo As ISScriptExecutionInfo,
                                                                       clientStatisticsSet As finClientStatisticsSet,
                                                                       frequencyPerAnnum As isefinFrequencyPerAnnum,
                                                              Optional displayZeroValueStatistics As Boolean = False,
                                                              Optional includeActions As Boolean = True,
                                                              Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim SummaryTables As ISSummaryTables

    ' Initialise
    SummaryTables = finBL.CreateSummaryTables()

    ' Assets
    SummaryTables.Add("Main", Me.ClientStatisticsSet_StatisticsSub(callerScriptInfo, clientStatisticsSet.Assets, frequencyPerAnnum, displayZeroValueStatistics, includeActions, otherParameters))

    ' Liabilities
    SummaryTables.Add("Liabilities", Me.ClientStatisticsSet_StatisticsSub(callerScriptInfo, clientStatisticsSet.Liabilities, frequencyPerAnnum, displayZeroValueStatistics, includeActions, otherParameters))

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Client Statistics Set Sub Summary (Version 1.04, Last updated 19/04/2016).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="clientStatistics">
  '''  The Client Statistic to summarise.
  ''' </param>
  ''' <param name="frequencyPerAnnum">
  '''   The Frequency Per Annum to use.
  ''' </param>
  ''' <param name="displayZeroValueStatistics">
  '''  Indicates whether to display Zero Value Statistics.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Client Statistic Summary.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function ClientStatisticsSet_StatisticsSub(callerScriptInfo As ISScriptExecutionInfo,
                                                                clientStatistics As finClientStatistics,
                                                                frequencyPerAnnum As isefinFrequencyPerAnnum,
                                                       Optional displayZeroValueStatistics As Boolean = False,
                                                       Optional includeActions As Boolean = True,
                                                       Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTable

    Dim DateAsAt As Date
    Dim IncludeAnalysis As Boolean
    Dim IncludeFrequency As Boolean
    Dim ShowAccounts As Boolean
    Dim ShowExpires As Boolean
    Dim Statistic As finClientStatistic
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Total As Decimal
    Dim Warnings As String

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Date As At
    DateAsAt = finBL.TimeZoneFunctions.GetCurrentDatabaseDate()

    ' Include Expires and Accounts columns?
    For Each Statistic In clientStatistics
      If Statistic.AccountPk <> 0 Then
        ShowAccounts = True
      End If
      If Statistic.DateExpiry <> Nothing Then
        ShowExpires = True
      End If
      If ShowAccounts AndAlso ShowExpires Then Exit For
    Next

    ' Include Frequency? and determine totals
    Select Case clientStatistics.StatisticClass
      Case isefinStatisticClass.Asset
        IncludeAnalysis = clientStatistics.HasAnalysisDataAsset
        IncludeFrequency = False
        Total = clientStatistics.Parent.AssetsTotal()
      Case isefinStatisticClass.Expense
        IncludeAnalysis = clientStatistics.HasAnalysisDataExpense
        IncludeFrequency = True
        Total = clientStatistics.Parent.ExpensesTotal(frequencyPerAnnum)
      Case isefinStatisticClass.Income
        IncludeAnalysis = clientStatistics.HasAnalysisDataIncome
        IncludeFrequency = True
        Total = clientStatistics.Parent.IncomeTotal(frequencyPerAnnum)
      Case isefinStatisticClass.Liability
        IncludeAnalysis = clientStatistics.HasAnalysisDataLiability
        IncludeFrequency = False
        Total = clientStatistics.Parent.LiabilitiesTotal()
      Case Else
        IncludeFrequency = False
        Total = 0
    End Select

    Warnings = ""
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .AutoStripe = True
      .Caption = clientStatistics.StatisticClassText
      Select Case clientStatistics.StatisticClass
        Case isefinStatisticClass.Asset, isefinStatisticClass.Liability
          .MaxWidthHtml = "40em"
        Case Else
          .MaxWidthHtml = "60em"
      End Select

      ' Columns
      With .Columns
        .AddText("Description")
        If IncludeAnalysis Then .AddText("Analysis")
        If ShowExpires Then .AddDate("Expires")
        If ShowAccounts Then .AddText("Account", 20)
        If IncludeFrequency Then .AddText("Frequency", 20)
        .AddCurrency("Value", 20)
        If IncludeFrequency Then .AddCurrency(finBL.Enums.isefinFrequencyPerAnnum_ToString(frequencyPerAnnum), 20)
      End With

      For Each Statistic In clientStatistics
        If Statistic.Value <> 0 OrElse displayZeroValueStatistics Then
          With .Rows.Add()
            With .Cells
              With .AddCaption(Statistic.Description)
                If Len(Statistic.Comments) <> 0 Then
                  .Tooltip = Statistic.Comments
                  .TooltipClass = iseSummaryTableTooltipClass.PopupNote
                End If
              End With
              If IncludeAnalysis Then
                .AddText(Statistic.Analysis)
              End If
              If ShowExpires Then
                If clientStatistics.Parent.IsCurrent AndAlso Statistic.DateExpiry <> Nothing AndAlso Statistic.DateExpiry < DateAsAt Then
                  .AddDate(Statistic.DateExpiry).CellClass = iseSummaryTableCellClass.Warning
                Else
                  .AddDate(Statistic.DateExpiry)
                End If
              End If
              If ShowAccounts Then
                With .AddText(Statistic.AccountId)
                  If Len(Statistic.AccountId) <> 0 Then
                    .HyperlinkSetFormShow("Accounts", Statistic.AccountId)
                  End If
                End With
              End If
              If IncludeFrequency Then .AddText(finBL.Enums.isefinFrequencyPerAnnum_ToString(Statistic.FrequencyPerAnnum))
              .AddCurrency(Statistic.Value)
              If IncludeFrequency Then .AddCurrency(Statistic.ValueResolved(frequencyPerAnnum))
            End With
          End With
        End If
      Next

      ' Total Row
      Select Case clientStatistics.StatisticClass
        Case isefinStatisticClass.Asset, isefinStatisticClass.Liability
          With .Rows.Add(iseSummaryTableRowClass.FooterBold).Cells
            .AddCaption("Total")
            If IncludeAnalysis Then .AddText("")
            If ShowExpires Then .AddText("")
            If ShowAccounts Then .AddText("")
            If IncludeFrequency Then .AddText("")
            .AddCurrency(Total, False, False)
            If IncludeFrequency Then .AddText("")
          End With
        Case Else
          If IncludeFrequency Then
            With .Rows.Add(iseSummaryTableRowClass.FooterBold).Cells
              .AddCaption("Total")
              If IncludeAnalysis Then .AddText("")
              If ShowExpires Then .AddText("")
              If ShowAccounts Then .AddText("")
              .AddText("")
              .AddText("")
              .AddCurrency(Total, False, False)
            End With
          End If
      End Select

      ' Warnings
      .TextAfter = Warnings
    End With

    Return SummaryTableMain

  End Function

  ''' <summary>
  '''  Decision Outcome Summary (Version 1.03, Last updated 29/05/2015).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="decisionOutcome">
  '''  The Decision Outcome to summarise.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used on the Decision Outcome Summary.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function DecisionOutcome_OutcomeSummary(callerScriptInfo As ISScriptExecutionInfo,
                                                             decisionOutcome As finDecisionOutcome,
                                                    Optional notes As String = "",
                                                    Optional warnings As String = "",
                                                    Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      .Columns.AddText(16).NoBreakChars = 12
      .Columns.AddText()

      With .Rows
        ' General
        Select Case decisionOutcome.OutcomeStatus
          Case isefinDecisionOutcomeStatus.Pass
            With .AddCaptionText("Outcome:", "Passed", iseSummaryTableCellClass.Highlight1)
              .Cells(1).ForegroundColour = "Green"
            End With
          Case isefinDecisionOutcomeStatus.Fail
            With .AddCaptionText("Outcome:", "Failed", iseSummaryTableCellClass.Highlight1)
              .Cells(1).ForegroundColour = "Red"
            End With
          Case isefinDecisionOutcomeStatus.Refer
            With .AddCaptionText("Outcome:", "Refer", iseSummaryTableCellClass.Highlight1)
              .Cells(1).ForegroundColour = "Blue"
            End With
        End Select
        If Len(decisionOutcome.OutcomeCode) <> 0 Then
          .AddCaptionText("Code:", decisionOutcome.OutcomeCode)
        End If
        .AddCaptionText("Message:", decisionOutcome.OutcomeMessageResolved)
        If finBL.DecisionCards.ExistsPk(decisionOutcome.DecisionCardPk) Then
          .AddCaptionCodeDescription("Decision Card:", decisionOutcome.DecisionCardId, finBL.DecisionCards)
        ElseIf Len(decisionOutcome.DecisionCardId) <> 0 Then
          .AddCaptionWiki("Decision Card:", "**" & decisionOutcome.DecisionCardId & "** !!--(deleted)--!!")
        End If

        ' Question
        If Len(decisionOutcome.QuestionType) <> 0 OrElse Len(decisionOutcome.QuestionId) <> 0 Then
          .AddSectionHeading2("Question")
          .AddCaptionText("Question Type:", decisionOutcome.QuestionType)
          If Len(decisionOutcome.QuestionId) <> 0 Then
            .AddCaptionText("Question Id:", decisionOutcome.QuestionId)
          End If
        End If

        ' Notes
        If Len(notes) <> 0 Then
          .AddSectionHeading2("Notes")
          .AddText(notes)
        End If
      End With

      ' Warnings
      If Len(warnings) <> 0 Then
        If Left(warnings, 2) = "{{" Then
          ' Already an HTML template
          .TextAfter = warnings
        Else
          ' Format as HTML template
          .TextAfter = "{{warning|" & warnings & "}}"
        End If
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Decision Outcome Scorecard Summary (Version 1.04, Last updated 29/05/2015).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="decisionOutcome">
  '''  The Decision Outcome to summarise.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used on the Decision Outcome Summary.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function DecisionOutcome_Scorecard(callerScriptInfo As ISScriptExecutionInfo,
                                                        decisionOutcome As finDecisionOutcome,
                                               Optional includeDescription As Boolean = True,
                                               Optional includeConditions As Boolean = False,
                                               Optional includeFailItems As Boolean = False,
                                               Optional includePostExitItems As Boolean = False,
                                               Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim DecisionOutcomeItem As finDecisionOutcomeItem
    Dim HasPriorExitRule As Boolean
    Dim i As Integer
    Dim Include As Boolean
    Dim IncludeNotes As Boolean
    Dim IncludeType As Boolean
    Dim IndentLevel As Integer
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()
    IncludeNotes = decisionOutcome.Items.HasNotes
    IncludeType = (includeFailItems OrElse includePostExitItems)

    ' Scorecard Items
    With SummaryTableMain
      .TableClass = iseSummaryTableClass.TabularData
      .AutoStripe = True

      ' Columns
      With .Columns
        .AddCode("Code", 10).NoBreakChars = 10
        If includeDescription Then .AddText("Description")
        If IncludeType Then .AddText("Type", 10).NoBreakChars = 20
        If includeConditions Then .AddText("Condition")
        .AddText("Message")
        .AddDouble("Score")
        If IncludeNotes Then .AddText("Notes")
      End With

      HasPriorExitRule = False
      For Each DecisionOutcomeItem In decisionOutcome.Items
        ' Include?
        Select Case DecisionOutcomeItem.OutcomeType
          Case isefinDecisionOutcomeType.ExitFalse
            Include = includeFailItems
          Case isefinDecisionOutcomeType.RuleFalse
            Include = includeFailItems
          Case isefinDecisionOutcomeType.EndIfBlock
            Include = False
            If IndentLevel > 0 Then IndentLevel -= 1
          Case Else
            Include = True
        End Select

        ' Add Row
        If Include Then
          With .Rows.Add()
            ' Row Colour
            If HasPriorExitRule Then
              ' Row included for information only
              .ForegroundColour = "gray"
            Else
              Select Case DecisionOutcomeItem.OutcomeType
                Case isefinDecisionOutcomeType.ExitTrue
                  Select Case decisionOutcome.OutcomeStatus
                    Case isefinDecisionOutcomeStatus.Pass : .ForegroundColour = "Green"
                    Case isefinDecisionOutcomeStatus.Fail : .ForegroundColour = "Red"
                    Case isefinDecisionOutcomeStatus.Refer : .ForegroundColour = "Blue"
                  End Select

                Case isefinDecisionOutcomeType.ExitFalse, isefinDecisionOutcomeType.RuleFalse
                  .ForegroundColour = "darkgoldenrod"

                Case isefinDecisionOutcomeType.SetOutcome
                  Select Case decisionOutcome.OutcomeStatus
                    Case isefinDecisionOutcomeStatus.Pass : .ForegroundColour = "Green"
                    Case isefinDecisionOutcomeStatus.Fail : .ForegroundColour = "Red"
                    Case isefinDecisionOutcomeStatus.Refer : .ForegroundColour = "Blue"
                  End Select

                Case isefinDecisionOutcomeType.IfBlock
                  .RowClass = iseSummaryTableRowClass.NormalBold
                  IndentLevel += 1

                Case isefinDecisionOutcomeType.ElseBlock, isefinDecisionOutcomeType.ElseIfBlock
                  .RowClass = iseSummaryTableRowClass.NormalBold
                  IndentLevel += 1
              End Select
            End If

            ' Details
            If .RowClass = iseSummaryTableRowClass.NormalBold Then
              ' Description only (i.e., If, Else etc)
              .Cells.AddText(New String(Chr(160), (IndentLevel - 1) * 3) & DecisionOutcomeItem.Description).CellClass = iseSummaryTableCellClass.CaptionBold
            Else
              ' Outcome Item
              With .Cells
                .AddText(New String(Chr(160), IndentLevel * 3) & DecisionOutcomeItem.Code)
                If includeDescription Then
                  .AddText(DecisionOutcomeItem.Description)
                End If
                If IncludeType Then
                  Select Case DecisionOutcomeItem.OutcomeType
                    Case isefinDecisionOutcomeType.ExitFalse : .AddText("Exit False")
                    Case isefinDecisionOutcomeType.ExitTrue : .AddText("Exit")
                    Case isefinDecisionOutcomeType.Information : .AddText("Info")
                    Case isefinDecisionOutcomeType.RuleFalse : .AddText("False")
                    Case isefinDecisionOutcomeType.RuleTrue : .AddText("")
                    Case isefinDecisionOutcomeType.SetOutcome : .AddText("Set Outcome")
                    Case Else : .AddText("")
                  End Select
                End If
                If includeConditions Then
                  .AddText(DecisionOutcomeItem.Conditions)
                End If
                .AddText(DecisionOutcomeItem.Message)
                If HasPriorExitRule Then
                  .AddText("")
                Else
                  Select Case DecisionOutcomeItem.OutcomeType
                    Case isefinDecisionOutcomeType.ExitFalse, isefinDecisionOutcomeType.Information, isefinDecisionOutcomeType.RuleFalse
                      .AddText("")
                    Case Else
                      .AddDouble(DecisionOutcomeItem.ScoreValue, decisionOutcome.ScoreDecimalPlaces, , , True)
                  End Select
                End If
                If IncludeNotes Then
                  .AddText(DecisionOutcomeItem.Notes)
                End If
              End With
            End If
          End With
        End If

        ' Exit Rule
        If DecisionOutcomeItem.OutcomeType = isefinDecisionOutcomeType.ExitTrue Then
          HasPriorExitRule = True
          If Not includePostExitItems Then Exit For
        End If
      Next

      ' Total
      With .Rows.Add(iseSummaryTableRowClass.FooterBold).Cells
        i = 2
        If includeDescription Then i += 1
        If IncludeType Then i += 1
        If includeConditions Then i += 2
        If HasPriorExitRule Then
          .AddText("Final Score (from Exit Rule)").ColSpan = i
        Else
          .AddText("Total Score").ColSpan = i
        End If
        .AddDouble(decisionOutcome.ScoreValue, decisionOutcome.ScoreDecimalPlaces, , , True)
        If IncludeNotes Then .AddText("")
      End With

      ' Warnings
      If decisionOutcome.Items.Count = 0 Then
        .TextAfter = "{{warning|No Decision Outcome Items for this Scorecard.}}"
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Recent Events Summary (Version 1.00, Last updated 23/08/2017).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="events">
  '''  Collection of Recent Events to display.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns></returns>
  Public Overridable Function Events_Summary(callerScriptInfo As ISScriptExecutionInfo,
                                             events As finEvents,
                                    Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTable

    Dim DateAsAt As Date
    Dim [Event] As finEvent
    Dim Description As String
    Dim i As Integer
    Dim Icon As String
    Dim IconTooltipText As String
    Dim SummaryTable As ISSummaryTable

    ' Validate

    ' Initialise
    SummaryTable = finBL.CreateSummaryTable()

    ' Get Date As At
    DateAsAt = finBL.TimeZoneFunctions.GetCurrentDatabaseDate()

    With SummaryTable
      .TableClass = iseSummaryTableClass.TabularData
      .Caption = "Events"
      .AutoStripe = True

      ' Columns
      With .Columns
        ' Anything Else
        .AddText(" ", 1, iseSummaryTableCellTextAlign.Center) ' Icon
        .AddDate("Date")
        .AddText("Description")
      End With

      ' Events (latest first)
      For i = events.Count - 1 To 0 Step -1
        ' Initialise
        [Event] = events(i)

        ' Add Row
        Description = [Event].WikiDescription
        Icon = [Event].Icon
        IconTooltipText = [Event].TooltipText
        If Len(Icon) = 0 Then Icon = "Blank"

        With .Rows.Add().Cells
          .AddText("{{Icon|" & Icon & "}}").Tooltip = IconTooltipText
          .AddDate([Event].Date)
          With .AddWiki(Description)
            If Len([Event].ApplicationShortcutUrl) <> 0 Then
              .HyperlinkSetApplicationShortcutUrl([Event].ApplicationShortcutUrl)
            End If
          End With
        End With
      Next
    End With

    Return SummaryTable

  End Function

  ''' <summary>
  '''  External Party Summary.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="externalParty">
  '''  The External Party to summarise.
  ''' </param>
  ''' <param name="includeExternalPartyIdHyperlink">
  '''  Indicates whether to include a hyperlink on the External Party Id to show the External Parties form.
  ''' </param>
  ''' <param name="includeContacts">
  '''  Indicates whether to include a 'Contacts' table listing Client Contact Methods.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., External Party Organiser Summary.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''    <item><code>Contacts</code><description>Contact details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function ExternalParty_Summary2(callerScriptInfo As ISScriptExecutionInfo,
                                                    externalParty As finExternalParty,
                                                    ByRef includedContactMethodPks As ISList,
                                           Optional includeExternalPartyIdHyperlink As Boolean = True,
                                           Optional includeContacts As Boolean = True,
                                           Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' ExternalParty_Summary2
    '
    ' Version: 1.00 (13/03/2022)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.00  15/03/2021  ISS      J027878   Created for C# compatibility
    ' #################################################################

    Dim ExternalPartyRO As finExternalPartyRO
    Dim SummaryTableContacts As ISSummaryTable
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim SummaryTables2 As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters
    includedContactMethodPks = New ISList()

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableContacts = finBL.CreateSummaryTable()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      .Columns.AddText(16)
      .Columns.AddText()

      ' Alert Message
      If Len(externalParty.Client.AlertMessage) <> 0 Then
        .TextBefore = "{{alert|" & externalParty.Client.AlertMessage & "|true}}"
      End If

      With .Rows
        ' General
        With .AddCaptionText("Code:", externalParty.ExternalPartyId)
          If includeExternalPartyIdHyperlink Then
            .Cells(1).HyperlinkSetFormShow("ExternalParties", externalParty.ExternalPartyId)
          End If
        End With
        .AddCaptionText("Description:", externalParty.Description, iseSummaryTableCellClass.Highlight1)
        .AddCaptionText("Type:", externalParty.ExternalPartyTypeText)
        'If finBL.SettingsUser.ClientShowExternalId Then
        '  .AddCaptionText("External Id:", externalParty.ParentExternalPartyId)
        'End If
        .AddCaptionCodeDescriptionWithFormShow("Client:", externalParty.Client.Pk, finBL.ClientFunctions, "Clients")

        ' Category and Region
        If Len(externalParty.Category) <> 0 Then .AddCaptionText("Category:", externalParty.Category)
        If Len(externalParty.Region) <> 0 Then .AddCaptionText("Region:", externalParty.Region)

        ' BDMs (uses ExternalPartyRO rather than ExternalParty To resolve BDMs)
        If finBL.Settings.AddOns.ExternalPartyAdvancedBdms Then
          Select Case externalParty.ExternalPartyType
            Case isefinExternalPartyType.Dealer, isefinExternalPartyType.Broker
              ' Dealer/ Broker
              ExternalPartyRO = finBL.ExternalParties(externalParty.ExternalPartyId)
              If ExternalPartyRO.BdmUserPk = 0 Then
                Warnings &= "{{warning|No BDM defined.}}"
              Else
                .AddCaptionCodeDescription("BDM:", externalParty.BdmUserId, finBL.Users)
              End If
              If ExternalPartyRO.BdmCommissionUserPk <> 0 Then
                .AddCaptionCodeDescription("Commissions:", externalParty.BdmCommissionUserId, finBL.Users)
              End If
              If ExternalPartyRO.BdmResolvedFromExternalPartyPk <> 0 AndAlso ExternalPartyRO.BdmResolvedFromExternalPartyPk <> externalParty.Pk Then
                With finBL.ExternalParties.ItemByPk(ExternalPartyRO.BdmResolvedFromExternalPartyPk)
                  Warnings &= "{{info|BDM is defined by parent " & externalParty.ExternalPartyTypeText & " **" & .ExternalPartyId & "**, '**" & .Name & "'**.}}"
                End With
              End If
          End Select
        End If
      End With

      ' Warnings
      If Not externalParty.Active Then
        Warnings &= "{{warning|This " & externalParty.ExternalPartyTypeText & " is not Active.}}"
      End If
      If Not externalParty.AllowAccountLink Then
        Warnings &= "{{info|Accounts cannot link to this " & externalParty.ExternalPartyTypeText & ".}}"
      End If
      .TextAfter = Warnings
    End With

    ' Contacts
    ' NOTE: Get directly from Client Summary
    If includeContacts Then
      SummaryTables2 = Me.Client_Summary(callerScriptInfo, externalParty.Client, False, False, includedContactMethodPks)
      If SummaryTables2.Exists("Contacts") Then
        SummaryTableContacts = SummaryTables2("Contacts")
      End If
    End If

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)
    If includeContacts Then SummaryTables.Add("Contacts", SummaryTableContacts)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Available Account Types and Promotions for an External Party (Version 1.01, Last updated 19/04/2016).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="externalParty">
  '''  The External Party to summaries.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="maxDisplayRows">
  '''  The Maximum number of Rows to Display in the table before a 'Show Hidden' link is displayed.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the External Party Organiser Summary.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function ExternalParty_AccountTypesAndPromotions(callerScriptInfo As ISScriptExecutionInfo,
                                                                      externalParty As finExternalParty,
                                                             Optional maxDisplayRows As Integer = 20,
                                                             Optional includeActions As Boolean = True,
                                                             Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim Active As Boolean
    Dim DateAsAt As Date
    Dim ExternalPartyAccountType As finExternalPartyAccountType
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Date As At
    DateAsAt = finBL.TimeZoneFunctions.GetCurrentDatabaseDate()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .Caption = ""
      .AutoStripe = True
      .MaxDisplayRows = maxDisplayRows

      If externalParty.AccountTypes.Count = 0 Then
        .TextAfter = "{{info|No Account Types available to this " & externalParty.ExternalPartyTypeText & ".}}"
      Else
        ' Columns
        With .Columns
          .AddText(" ", 1, iseSummaryTableCellTextAlign.Center) ' Available
          .AddCode("Type", finBL.AccountTypes.GetLongestCode())
          .AddText("Description")
          If finBL.Settings.AddOns.Promotions Then
            .AddCode("Promotion", 10)
            .AddText("Description")
            .AddDate("Start")
            .AddDate("Stop")
          End If
        End With

        With .Rows
          For Each ExternalPartyAccountType In externalParty.AccountTypes
            With .Add()
              ' Active?
              If finBL.AccountTypes.ItemByPk(ExternalPartyAccountType.AccountTypePk).Active Then
                If ExternalPartyAccountType.PromotionDateStop <> Nothing AndAlso ExternalPartyAccountType.PromotionDateStop < DateAsAt Then
                  Active = False
                Else
                  Active = True
                End If
              Else
                Active = False
              End If

              ' Visible?
              .Visible = Active

              ' Colour Inactive Promotions (over-and-above Active icon)
              If Len(ExternalPartyAccountType.PromotionId) <> 0 Then
                If ExternalPartyAccountType.PromotionDateStop <> Nothing AndAlso ExternalPartyAccountType.PromotionDateStop < DateAsAt Then
                  .ForegroundColour = "red"
                End If
              End If

              With .Cells
                .AddTick(Active, True, True)
                .AddText(ExternalPartyAccountType.AccountTypeId)
                .AddText(ExternalPartyAccountType.AccountTypeDescription)

                If finBL.Settings.AddOns.Promotions Then
                  .AddText(ExternalPartyAccountType.PromotionId)
                  .AddText(ExternalPartyAccountType.PromotionDescription)
                  .AddDate(ExternalPartyAccountType.PromotionDateStart)
                  .AddDate(ExternalPartyAccountType.PromotionDateStop)
                End If
              End With
            End With
          Next
        End With

        ' Warnings
        .TextAfter = Warnings

        ' Actions
        If includeActions Then
          With .Actions
          End With
        End If
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  External Party Employee Summary (Version 1.02, Last updated 07/06/2017).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="externalParty">
  '''  The External Party to summarise.
  ''' </param>
  ''' <param name="clientEmployment">
  '''  The External Party Employee to Summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., External Party Organiser Summary.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''    <item><code>Contacts</code><description>Contact Details if this Client Employment is linked to a Client.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function ExternalParty_EmployeeSummary(callerScriptInfo As ISScriptExecutionInfo,
                                                            externalParty As finExternalParty,
                                                            clientEmployment As finClientEmployment,
                                                   Optional includeContacts As Boolean = True,
                                                   Optional includeActions As Boolean = False,
                                                   Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim SummaryTableContacts As ISSummaryTable
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim SummaryTables2 As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableContacts = finBL.CreateSummaryTable()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      .Columns.AddText(16).NoBreakChars = 16
      .Columns.AddText()

      With .Rows
        ' General
        .AddCaptionText("Code:", clientEmployment.ClientEmploymentId)
        .AddCaptionText("Name:", clientEmployment.IndividualName)
        .AddCaptionText("Role Type:", clientEmployment.RoleType)
        .AddCheckBox("Is this person an Active Sales Representative for this External Party?", clientEmployment.ActiveSalesRep)
        .AddCheckBox("Is Employee available to Sub External Parties?", clientEmployment.AvailableToSubExternalParties)
      End With

      ' Warnings
      .TextAfter = Warnings
    End With

    ' Contacts
    ' NOTE: Get directly from Client Summary
    If includeContacts AndAlso clientEmployment.LinkedClientPk <> 0 Then
      SummaryTables2 = Me.Client_Summary(callerScriptInfo, externalParty.Client, False, False)
      If SummaryTables2.Exists("Contacts") Then
        SummaryTableContacts = SummaryTables2("Contacts")
      End If
    End If

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)
    If includeContacts AndAlso clientEmployment.LinkedClientPk <> 0 Then SummaryTables.Add("Contacts", SummaryTableContacts)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  External Party Employee Login Summary (Version 1.00, Last updated 27/07/2015).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="externalParty">
  '''  The External Party to summarise.
  ''' </param>
  ''' <param name="clientEmployment">
  '''  The External Party Employee to Summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., External Party Organiser Summary.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function ExternalParty_EmployeeLogin(callerScriptInfo As ISScriptExecutionInfo,
                                                          externalParty As finExternalParty,
                                                          clientEmployment As finClientEmployment,
                                                 Optional includeActions As Boolean = False,
                                                 Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim User As finUser
    Dim UserEx As finUserExtended
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      .Columns.AddText(16)
      .Columns.AddText()

      If Len(clientEmployment.ExternalUserId) = 0 Then
        ' --------------------
        ' Not an External User
        ' --------------------
        .TextBefore = "{{info|Employee is not configured to login to finPOWER Connect.}}"

        ' Actions
        If includeActions AndAlso Not finBL.Database.IsReadOnly Then
          With .Actions
            If Len(clientEmployment.ExternalUserId) = 0 Then
              .AddFormCustomAction("NewUser", "Add as User", finBL.CurrentUser.IsAdministrator)
            End If
            .AddFormShow("LinkExisting", "Link to existing User", "UsersExtended")
          End With
        End If
      Else
        ' -------------
        ' External User
        ' -------------
        ' Load User
        User = finBL.CreateUser()
        UserEx = finBL.CreateUserEx()
        If User.Load(clientEmployment.ExternalUserId) Then
          UserEx.Load(clientEmployment.ExternalUserId)
        End If

        With .Rows
          ' General
          With .AddCaptionCodeDescription("User Id:", User.UserId, finBL.Users).Cells(1)
            .HyperlinkSetFormShow("UsersExtended", User.UserId)
          End With

          ' Status
          If Not User.Active Then
            .AddCaptionText("Status:", "Not Active", iseSummaryTableCellClass.WarningBold)
          ElseIf User.IsLockedOut Then
            .AddCaptionText("Status:", "Locked Out", iseSummaryTableCellClass.WarningBold)
          Else
            .AddCaptionText("Status:", "OK", iseSummaryTableCellClass.PositiveBold)
          End If
        End With

        ' Actions
        If includeActions AndAlso Not finBL.Database.IsReadOnly Then
          With .Actions
            If Not User.Active Then
              .AddFormShow("ActivateUser", "Activate User", "Users", finBL.CurrentUser.IsAdministrator, "id=" & finBL.UrlEncode(User.UserId) & "&page=General")
            End If
            If User.IsLockedOut Then
              .AddFormShow("ClearLockout", "Clear Lockout", "Users", finBL.CurrentUser.IsAdministrator, "id=" & finBL.UrlEncode(User.UserId) & "&page=Login")
            End If
          End With
        End If
      End If

      ' Warnings
      .TextAfter = Warnings
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  External Party Employee Accounts Summary (Version 1.00, Last updated 27/07/2015).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="externalParty">
  '''  The External Party to summarise.
  ''' </param>
  ''' <param name="clientEmployment">
  '''  The External Party Employee to Summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., External Party Organiser Summary.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Sharing</code><description>Sharing With details.</description></item>
  '''    <item><code>Accounts</code><description>Available Account details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function ExternalParty_EmployeeAccounts(callerScriptInfo As ISScriptExecutionInfo,
                                                             externalParty As finExternalParty,
                                                             clientEmployment As finClientEmployment,
                                                    Optional maxDisplayRows As Integer = 20,
                                                    Optional includeActions As Boolean = False,
                                                    Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim ClientEmployment2 As finClientEmployment
    Dim HasFilteredOut As Boolean
    Dim List As ISListReadOnly
    Dim SummaryTableAvailableAccounts As ISSummaryTable
    Dim SummaryTableSharing As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableAvailableAccounts = finBL.CreateSummaryTable()
    SummaryTableSharing = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Sharing With
    With SummaryTableSharing
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .Caption = "Sharing With"
      .AutoStripe = True
      .MaxDisplayRows = maxDisplayRows

      If Not clientEmployment.ExternalPartyShareAccounts OrElse Len(clientEmployment.ExternalPartyShareEmployeePks) = 0 Then
        .TextBefore = "{{info|Not sharing any Accounts with other Employees.}}"
      Else
        With .Columns
          .AddText("Employee", 10)
          .AddText("Name")
        End With

        List = New ISListReadOnly(clientEmployment.ExternalPartyShareEmployeePks)
        For Each ClientEmployment2 In externalParty.Client.Employments
          If ClientEmployment2 IsNot clientEmployment AndAlso List.Exists(CStr(ClientEmployment2.Pk)) Then
            With .Rows.Add().Cells
              .AddText(ClientEmployment2.ClientEmploymentId)
              .AddText(ClientEmployment2.IndividualName)
            End With
          End If
        Next

        ' Warnings
        .TextAfter = Warnings
      End If
    End With

    ' Available Accounts
    If Len(clientEmployment.ExternalUserId) = 0 Then
      ' Not Applicable to non-External Users
    Else
      Warnings = ""
      With SummaryTableAvailableAccounts
        ' Initialise
        .TableClass = iseSummaryTableClass.TabularData
        .Caption = "Available Accounts"
        .AutoStripe = True
        .MaxDisplayRows = maxDisplayRows

        With .Columns
          .AddText(14).NoBreakChars = 20
          .AddText()
        End With

        With .Rows
          ' External Party/ Employee Accounts
          Select Case externalParty.ExternalPartyType
            Case isefinExternalPartyType.BulkFunder
              ' Bulk Funder
              .AddCollapsibleHeader(iseTriState.None).Cells.Add("All Accounts for this Bulk Funder")
            Case Else
              ' All Others
              If clientEmployment.ExternalPartyManager Then
                .AddCollapsibleHeader(iseTriState.None).Cells.Add(String.Format("All Accounts for this {0}", externalParty.ExternalPartyTypeText))
              Else
                .AddCollapsibleHeader(iseTriState.None).Cells.Add("All Accounts for this Employee")
              End If
          End Select

          ' Shared by other Employees
          List = externalParty.Client.Employments.GetEmployeePksListSharingWithEmployee(clientEmployment.Pk)
          If List.Count <> 0 Then
            .AddCollapsibleHeader(iseTriState.False).Cells.Add("Accounts Shared By Employees:")

            For Each ClientEmployment2 In externalParty.Client.Employments
              If ClientEmployment2 IsNot clientEmployment AndAlso List.Exists(CStr(ClientEmployment2.Pk)) Then
                With .Add().Cells
                  .AddText(ClientEmployment2.ClientEmploymentId)
                  .AddText(ClientEmployment2.IndividualName)
                End With
              End If
            Next
          End If

          ' Accounts for sub-External Parties
          If clientEmployment.ExternalPartyViewSubAccounts Then
            If Len(clientEmployment.ExternalPartySubAccountsFilter) = 0 Then
              ' For all sub-External Parties
              .AddCollapsibleHeader(iseTriState.None).Cells.Add(String.Format("Accounts for ALL sub {0}s", externalParty.ExternalPartyTypeText))
            Else
              ' For filtered list
              .AddCollapsibleHeader(iseTriState.False).Cells.Add(String.Format("Accounts for sub {0}s", externalParty.ExternalPartyTypeText))

              ' Tree of available sub-External Parties
              List = finBL.ExternalParties(externalParty.ExternalPartyId).GetChildExternalPartyPksList(clientEmployment.ExternalPartySubAccountsFilter)
              ExternalParty_EmployeeAccounts_AddSubExternalParties(externalParty.Pk, SummaryTableAvailableAccounts, List, HasFilteredOut, 0)

              ' Has Filtered Out External Parties?
              If HasFilteredOut Then
                Warnings &= "{{info|Filtered out items are shown in red.}}"
              End If
            End If
          End If
        End With

        ' Warnings
        .TextAfter = Warnings
      End With
    End If

    ' Add Summary Tables
    SummaryTables.Add("Sharing", SummaryTableSharing)
    SummaryTables.Add("Accounts", SummaryTableAvailableAccounts)

    Return SummaryTables

  End Function

  Private Sub ExternalParty_EmployeeAccounts_AddSubExternalParties(parentExternalPartyPk As Integer,
                                                                   summaryTable As ISSummaryTable,
                                                                   filterList As ISListReadOnly,
                                                                   ByRef hasFilteredOut As Boolean,
                                                                   ByRef indentLevel As Integer)

    Dim ExternalParty As finExternalPartyRO
    Dim ExternalPartyParent As finExternalPartyRO
    Dim Indent As String

    ' Initialise
    ExternalPartyParent = finBL.ExternalParties.ItemByPk(parentExternalPartyPk)

    ' Main
    If indentLevel = 0 Then
      ' Ignore original External Party since it is the one we are summarising
    Else
      Indent = New String(" "c, (indentLevel - 1) * 2)

      If filterList.Exists(CStr(parentExternalPartyPk)) Then

        ' Included
        With summaryTable.Rows.Add().Cells
          .AddText(Indent & ExternalPartyParent.ExternalPartyId)
          .AddText(Indent & ExternalPartyParent.Description)
        End With
      Else
        ' Filtered Out
        With summaryTable.Rows.Add()
          With .Cells
            .AddText(Indent & ExternalPartyParent.ExternalPartyId).CellClass = iseSummaryTableCellClass.Warning
            .AddText(Indent & ExternalPartyParent.Description).CellClass = iseSummaryTableCellClass.Warning
          End With
        End With

        hasFilteredOut = True
      End If
    End If

    ' Recurse sub-External Parties
    For Each ExternalParty In finBL.ExternalParties
      If ExternalParty.ParentExternalPartyPk = parentExternalPartyPk Then
        ' Recurse
        ExternalParty_EmployeeAccounts_AddSubExternalParties(ExternalParty.Pk, summaryTable, filterList, hasFilteredOut, indentLevel + 1)
      End If
    Next

  End Sub

  ''' <summary>
  '''  Log Summary.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="log">
  '''  The Log to summaries.
  ''' </param>
  ''' <param name="includeLogActionDetails">
  '''  Indicates whether to include Log Action details.
  ''' </param>
  ''' <param name="includeDocumentDetails">
  '''  Indicates whether to include Document and Publishing details.
  ''' </param>
  ''' <param name="includeUserDetails">
  '''  Indicates whether to include User-related details.
  ''' </param>
  ''' <param name="includeSeverityDetails">
  '''  Indicates whether to include Log Severity details.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used to summaries Logs beneath the various Logs grids and in the Task Manager.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''    <item><code>ExtendedData</code><description>Extended Data details, e.g., Email details.</description></item>
  '''    <item><code>ServiceLog</code><description>Service details, e.g., Credit Enquiry details plus actions to show reports.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Log_Summary(callerScriptInfo As ISScriptExecutionInfo,
                                          log As finLogRO,
                                 Optional includeLogActionDetails As Boolean = True,
                                 Optional includeDocumentDetails As Boolean = True,
                                 Optional includeUserDetails As Boolean = False,
                                 Optional includeSeverityDetails As Boolean = False,
                                 Optional includeActions As Boolean = True,
                                 Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' Log_Summary
    '
    ' Version: 1.18 (29/05/2023)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.15  08/04/2021  ISS                  
    '    1.16  03/11/2021  ISS      J027693   Email Attachments
    '    1.17  17/08/2022  ISS      J029394   Reply to Web Mail action
    '    1.18  14/03/2023  ISS      J030672   Exclude View Security Enquiry button where not applicable
    '          29/05/2023  ISS      J031137   Handled repeating Logs
    ' #################################################################

    Dim AccountAppId As String
    Dim AccountId As String
    Dim BankAccountEnquiryResponse As ISBankAccountEnquiryResponse
    Dim CreditEnquiryResponse As ISCreditEnquiryResponse
    Dim CreditMonitorResponse As ISCreditMonitorResponse
    Dim DateAsAt As Date
    Dim dateTemp As Date
    Dim DecisionOutcome As finDecisionOutcome
    Dim ElectronicSignatureResponse As ISElectronicSignatureResponse
    Dim kvl As ISKeyValueList
    Dim LogExists As Boolean
    Dim SecurityEnquiryResponse As ISSecurityEnquiryResponse
    Dim SecurityRegistryResponse As ISSecurityRegistryResponse
    Dim SmsReply As String
    Dim strTemp As String
    Dim SummaryTableExtendedData As ISSummaryTable
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim SummaryTableServiceLog As ISSummaryTable
    Dim tempInt As Integer
    Dim UpdateRequestAction As finUpdateRequestAction
    Dim UpdateRequestActions As finUpdateRequestActions
    Dim UpdateRequestSourceText As String
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableExtendedData = finBL.CreateSummaryTable()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTableServiceLog = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Date As At
    DateAsAt = finBL.TimeZoneFunctions.GetCurrentDatabaseDate()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      .Columns.AddText(16).NoBreakChars = 20
      .Columns.AddText()

      With .Rows
        ' Parent-specific
        ' NOTE: Only shown when a Log in the collection may be of an ambiguous type, e.g., an Account Application Log in the Account Logs collection.
        If log.Parent.MainLogClass <> log.LogClass Then
          .AddCaptionText("Log Class:", log.LogClassText)
          Select Case log.LogClass
            Case isefinLogClass.Account
              .AddCaptionCodeDescriptionWithFormShow("Account:", log.SourcePk, finBL.AccountFunctions, "Accounts")
            Case isefinLogClass.AccountApp
              .AddCaptionCodeDescriptionWithFormShow("Account App:", log.SourcePk, finBL.AccountAppFunctions, "AccountApps")
            Case isefinLogClass.Client
              .AddCaptionCodeDescriptionWithFormShow("Client:", log.SourcePk, finBL.ClientFunctions, "Clients")
            Case isefinLogClass.SecurityStmt
              .AddCaptionCodeDescriptionWithFormShow("Security Stmt:", log.SourcePk, finBL.SecurityStmtFunctions, "SecurityStmts")
            Case isefinLogClass.SecurityStmtItem
              finBL.SecurityStmtFunctions.GetSecurityStmtPkFromSecurityStmtItemPk(log.SourcePk, tempInt)
              kvl = finBL.CreateKeyValueList()
              kvl.SetInteger("ItemId", log.SourcePk)
              .AddCaptionCodeDescriptionWithFormShow("Security Item:", tempInt, finBL.SecurityStmtFunctions, "SecurityStmts", , , , , kvl)
            Case isefinLogClass.User
              .AddCaptionCodeDescription("User:", log.SourcePk, finBL.Users)
          End Select
        End If

        ' General
        With .AddCaptionText("Subject:", log.Subject, iseSummaryTableCellClass.Highlight1).Cells(1)
          Select Case callerScriptInfo.FormKey
            Case "AccountLog", "AccountAppLog", "ClientLog", "SecurityStmtLog", "SecurityStmtItemLog", "UserLog"
              ' No Subject hyperlink if displaying from a Log form (typically on the Web)

            Case Else
              .HyperlinkSetFormShow(log.GetFormKey(), CStr(log.Pk))
          End Select
        End With
        .AddCaptionUtcDateTimeWithTimeZone("Date:", log.LogUtcDate, log.LogTimeZoneId)

        ' Action details
        If includeLogActionDetails AndAlso log.ActionDate <> Nothing Then
          If log.IsIncomplete Then
            ' Incomplete
            If log.DelegatedToUserPk = 0 AndAlso log.DelegatedToRolePk = 0 Then
              strTemp = log.OwnerUserId
            ElseIf log.DelegatedToUserPk <> 0 Then
              strTemp = String.Format("User '{0}'", log.DelegatedToUserId)
            ElseIf log.DelegatedToRolePk <> 0 Then
              strTemp = String.Format("Role '{0}'", log.DelegatedToRoleId)
            End If
            With .AddCaptionUtcDateTimeWithTimeZone("Action:", log.ActionUtcDate, log.ActionTimeZoneId, String.Format("**To Action** --by-- **{0}** --on-- ", strTemp)).Cells(1)
              ' Action date passed?
              If log.ActionDate < DateAsAt Then
                .ForegroundColour = "red"
                Warnings &= " {{warning|Action date passed.}}"
              End If
            End With
          Else
            ' Complete
            .AddCaptionUtcDateTimeWithTimeZone("Action:", log.ActionCompleteUtcDate, log.ActionTimeZoneId, "**Completed** --on-- ")
          End If
        End If

        ' Repeat
        If log.RepeatUseResolved Then
          .AddCaptionText("Repeat Basis:", log.RepeatBasisText)
          .AddCaptionText("Repeat Cycle:", finBL.Utilities.DateCycleGetMnemonicFriendly(True, log.RepeatCycle))
        End If

        ' Web Mail
        If log.IsWebMailLog Then
          .AddCaptionText("Web Mail:", log.WebMailStatus(dateTemp))
          If dateTemp <> Nothing Then
            .AddCaptionDateTime("Read:", dateTemp)
          End If

          ' Web Mail Extended Data
          If log.ExtendedType = isefinLogExtendedType.ClientWebMail Then
            With log.GetExtendedDataAsKeyValueList()
              AccountAppId = .GetString("AccountAppId")
              AccountId = .GetString("AccountId")
            End With

            ' Account
            If Len(AccountId) <> 0 Then
              .AddCaptionCodeDescriptionWithFormShow("Account:", AccountId, finBL.AccountFunctions, "Accounts")
            End If

            ' Account Application
            If Len(AccountAppId) <> 0 AndAlso finBL.Settings.AddOns.AccountApplication Then
              .AddCaptionCodeDescriptionWithFormShow("Application:", AccountAppId, finBL.AccountAppFunctions, "AccountApps")
            End If
          End If
        End If

        ' Outcome
        If Len(log.LogOutcome) <> 0 Then
          .AddCaptionText("Outcome:", log.LogOutcome)
        End If

        ' Document/ Publish
        If includeDocumentDetails Then
          If log.DocumentPk <> 0 Then
            .AddCaptionCodeDescription("Document:", log.DocumentId, finBL.Documents)
          End If
          Select Case log.PublishStatus
            Case isefinLogPublishStatus.Failed
              If log.PublishFailDate = Nothing Then
                strTemp = ""
              Else
                strTemp = String.Format(" on **{0}**", finBL.FormatDateLong(log.PublishFailDate))
              End If
              If Len(log.PublishResult) <> 0 Then
                strTemp &= String.Format(" ({0})", finBL.HtmlEncode(log.PublishResult))
              End If
              .AddCaptionWiki("Publish Status:", "!!**Failed**" & strTemp & "!!")

            Case isefinLogPublishStatus.NotIssued
              .AddCaptionWiki("Publish Status:", String.Format("**Not Issued** --on-- **{0}**", finBL.FormatDateTimeLong(log.PublishedDate)))

            Case isefinLogPublishStatus.Open
              .AddCaptionText("Publish Status:", "Open")

            Case isefinLogPublishStatus.Published
              .AddCaptionUtcDateTimeWithTimeZone("Publish Status:", log.PublishedUtcDate, log.PublishOnTimeZoneId, "**Published** --on-- ")

            Case isefinLogPublishStatus.ToSend
              If log.PublishOnUtcDate = Nothing Then
                .AddCaptionText("Publish Status:", "To Send")
              Else
                .AddCaptionUtcDateTimeWithTimeZone("Publish Status:", log.PublishOnUtcDate, log.PublishOnTimeZoneId, "**To Send** --on-- ")
              End If
          End Select
          If log.Document IsNot Nothing AndAlso log.Document.SupportsSendEmail Then
            Select Case log.PublishStatus
              Case isefinLogPublishStatus.Open, isefinLogPublishStatus.ToSend
                .AddCaptionTick("Send Email:", log.DocumentSendEmailResolved)
            End Select
          End If

          ' File
          If Len(log.DocumentFileName) <> 0 Then
            .AddCaptionText("File:", "{{DocumentManagerFile itemType=""" & log.LogClass.ToString() & """ itemPk=""" & log.SourcePk & """ fileName=""" & log.DocumentFileName & """ bookmark=""" & log.DocumentBookmark & """}}")

            ' Preview Image
            If finBL.DocumentManager.IsAvailableResolved Then
              Select Case UCase(finBL.Runtime.FileUtilities.GetFileExtension(log.DocumentFileName))
                Case "GIF", "JPG", "JPEG", "PNG"
                  .AddCaptionText("", "{{DocumentManagerImage filename=""" & log.DocumentFileNameResolved & """ maxWidth=""320px""}}")
              End Select
            End If
          End If

          ' Print Status
          If log.PrintStatus <> isefinLogPrintStatus.NotApplicable Then
            .AddCaptionText("Print Status:", log.PrintStatusText)
          End If
        End If

        ' Fee
        If log.Fee <> 0 Then
          .AddCaptionCurrency("Fee:", log.Fee, True)
        End If

        ' Notes
        If Len(log.Notes) <> 0 Then
          With .AddText(log.Notes)
            .RowClass = iseSummaryTableRowClass.Alt2
            .Cells(0).CellClass = iseSummaryTableCellClass.Positive
          End With
        End If
      End With

      ' Warnings
      If log.PublishStatus = isefinLogPublishStatus.ToSend AndAlso log.PublishOnDate < DateAsAt Then
        Warnings &= " {{warning|Publish date passed.}}"
      End If
      If includeDocumentDetails AndAlso log.Document IsNot Nothing AndAlso (log.PublishStatus = isefinLogPublishStatus.Open OrElse log.PublishStatus = isefinLogPublishStatus.ToSend) Then
        If log.Document.SupportsSendEmail AndAlso log.Document.PrintDocumentEvenIfEmailed AndAlso log.DocumentSendEmailResolved Then
          Warnings &= "{{info|This Document is configured to produce a printed copy in addition to sending an Email copy.}}"
        End If
      End If
      .TextAfter = Warnings

      ' Actions
      If includeActions Then
        With .Actions
          If log.IsWebMailLog AndAlso log.LogType = isefinLogType.WebMailFromClient AndAlso Not finBL.Database.IsReadOnly AndAlso finBL.CurrentUser.Permissions.Allow("Client.Logs.Add") Then
            .AddFormShow("WebMailReply", "Reply to Web Mail", "ClientLog",, "replyToLogPk=" & If(log.ParentLogPk <> 0, log.ParentLogPk, log.Pk) & "&logType=WebMailToClient").ShowInWebInterfaces = True
          End If

          If log.RepeatLogPreviousPk <> 0 AndAlso log.RepeatLogPreviousExists(LogExists) AndAlso LogExists Then
            .AddFormShow("ShowRepeatLogPrevious", "Show Previous", "UserLog", , "id=" & log.RepeatLogPreviousPk).ShowInWebInterfaces = True
          End If
          If log.RepeatLogNextPk <> 0 AndAlso log.RepeatLogNextExists(LogExists) AndAlso LogExists Then
            .AddFormShow("ShowRepeatLogNext", "Show Next", "UserLog", , "id=" & log.RepeatLogNextPk).ShowInWebInterfaces = True
          End If
        End With
      End If
    End With

    ' Extended Data
    Warnings = ""
    With SummaryTableExtendedData
      .TableClass = iseSummaryTableClass.Information

      Select Case log.ExtendedType
        Case isefinLogExtendedType.AccountClose
          ' =============
          ' Account Close
          ' =============
          ' Actions
          With .Actions
            .AddHtmlShowFunction("AccountClose", "View Closing Summary", "AccountCloseLogSummary", "Account Closing Summary", "logPk=" & log.Pk & "&logClass=" & log.LogClass.ToString()).ShowInWebInterfaces = True
          End With

        Case isefinLogExtendedType.Email
          ' =====
          ' Email
          ' =====
          .Caption = "Email details"
          .Columns.AddText(16).NoBreakChars = 20
          .Columns.AddText()

          kvl = log.GetExtendedDataAsKeyValueList()
          With .Rows
            .AddCaptionText("To:", Replace(kvl.GetString("To"), ";", "; "))
            If Len(kvl.GetString("CC")) <> 0 Then
              .AddCaptionText("CC:", Replace(kvl.GetString("CC"), ";", "; "))
            End If
            If Len(kvl.GetString("BCC")) <> 0 Then
              .AddCaptionText("BCC:", Replace(kvl.GetString("BCC"), ";", "; "))
            End If
            If Len(kvl.GetString("SenderEmailAddress")) <> 0 Then
              .AddCaptionCodeDescription("Sender:", kvl.GetString("SenderEmailAddress"), kvl.GetString("SenderName"))
            End If
            .AddCaptionText("Subject:", kvl.GetString("Subject"))
            If Len(kvl.GetString("Attachments")) <> 0 Then
              .AddCaptionText("Attachments:", kvl.GetString("Attachments"))
            End If
          End With

          ' Actions
          If includeActions Then
            With .Actions
              With .AddApplicationShortcutUrl("PreviewEmail", "Preview Email", "HtmlShowFunction")
                .ShowInWebInterfaces = True
                With .Parameters
                  .SetBoolean("popup", True)
                  .SetString("title", "Preview Email to " & kvl.GetString("To"))

                  .SetString("function", "LogEmailPreview")
                  .SetString("logClass", log.LogClass.ToString())
                  .SetInteger("logPk", log.Pk)
                End With
              End With
            End With
          End If

        Case isefinLogExtendedType.Sms
          ' ===
          ' SMS
          ' ===
          .Caption = "SMS details"
          .Columns.AddText(16).NoBreakChars = 20
          .Columns.AddText()

          If finBL.Messaging.IsMessagingAvailable AndAlso finBL.Settings.SmsUseNewInterface Then
            Select Case log.LogClass
              Case isefinLogClass.Account
                SmsReply = String.Format("id={0}&type=Account&parentSourceLogPk={1}", log.SourceId, log.Pk)
              Case isefinLogClass.AccountApp
                SmsReply = String.Format("id={0}&type=Account Application&parentSourceLogPk={1}", log.SourceId, log.Pk)
              Case isefinLogClass.Client
                SmsReply = String.Format("id={0}&type=Client&parentSourceLogPk={1}", log.SourceId, log.Pk)
              Case isefinLogClass.User
                SmsReply = String.Format("id={0}&type=User&parentSourceLogPk={1}", log.SourceId, log.Pk)
            End Select
            If Len(SmsReply) <> 0 Then
              .Actions.AddFormShow("ReplyMessagingSMS", "Reply via SMS", "SmsMessage_New", True, SmsReply).ShowInWebInterfaces = True
            End If
          End If

          kvl = log.GetExtendedDataAsKeyValueList()
          With .Rows
            .AddCaptionText("Phone:", kvl.GetString("Phone"))
            .AddCaptionText("Message:", kvl.GetString("Message"))
          End With

        Case isefinLogExtendedType.UpdateRequest
          ' ==============
          ' Update Request
          ' ==============
          UpdateRequestActions = finBL.CreateUpdateRequestActions()
          Select Case log.LogClass
            Case isefinLogClass.Account
              UpdateRequestActions.LoadAccountLog(log.Pk)
              UpdateRequestSourceText = "AccountLog"
            Case isefinLogClass.Client
              UpdateRequestActions.LoadClientLog(log.Pk)
              UpdateRequestSourceText = "ClientLog"
            Case Else
              ' Not Implemented
          End Select

          If UpdateRequestActions.Count <> 0 Then
            .TableClass = iseSummaryTableClass.TabularData
            .Caption = "Update Requests"
            .AutoStripe = True

            With .Columns
              .AddCode(" ", 1).TextAlign = iseSummaryTableCellTextAlign.Center
              .AddText("Update", 30)
              .AddText("From")
              .AddText("To")
              .AddText("Information")
            End With

            For Each UpdateRequestAction In UpdateRequestActions
              With .Rows.Add().Cells
                ' Status Icon
                Select Case UpdateRequestAction.Status
                  Case isefinUpdateRequestActionStatus.Actioned
                    strTemp = "Check"
                  Case isefinUpdateRequestActionStatus.Declined
                    strTemp = "Cross"
                  Case isefinUpdateRequestActionStatus.Invalid
                    strTemp = "Error"
                  Case isefinUpdateRequestActionStatus.NotActioned
                    If Len(UpdateRequestAction.UpdateWarning) = 0 Then
                      strTemp = "Blank"
                    Else
                      ' Can still action but a warning exists
                      strTemp = "Warning"
                    End If
                  Case Else
                    strTemp = "Blank"
                End Select
                .AddText("{{icon|" & strTemp & "|Status: " & UpdateRequestAction.StatusText & "}}")

                .AddText(UpdateRequestAction.UpdateTitle & vbNewLine & UpdateRequestAction.UpdateDescription)
                .AddText(UpdateRequestAction.UpdateFromDescription)
                .AddText(UpdateRequestAction.UpdateToDescription)

                ' Actioned
                Select Case UpdateRequestAction.Status
                  Case isefinUpdateRequestActionStatus.Invalid
                    strTemp = "!!" & UpdateRequestAction.UpdateWarning & "!!"
                  Case Else
                    If UpdateRequestAction.ActionedDate = Nothing Then
                      If Len(UpdateRequestAction.UpdateWarning) <> 0 AndAlso UpdateRequestAction.Status = isefinUpdateRequestActionStatus.NotActioned Then
                        strTemp = "!!" & UpdateRequestAction.UpdateWarning & "!!"
                      Else
                        strTemp = ""
                      End If
                    Else
                      strTemp = UpdateRequestAction.ActionedDetailsWiki
                    End If
                End Select
                .AddWiki(strTemp)
              End With
            Next

            ' Warnings
            Select Case UpdateRequestActions.CountNotActioned()
              Case 0
              Case 1 : Warnings &= "{{warning|**1** unactioned Update Request.}}"
              Case Else : Warnings &= "{{warning|**" & UpdateRequestActions.CountNotActioned() & "** unactioned Update Requests.}}"
            End Select
            .TextAfter = Warnings

            ' Actions
            If includeActions AndAlso Len(UpdateRequestSourceText) <> 0 Then
              With .Actions
                If UpdateRequestActions.CountNotActionedCanAction() = 0 OrElse finBL.Database.IsReadOnly Then
                  With .AddFormShow("UpdateRequestAction", "View Update Request", "UpdateRequestAction")
                    .ShowInWebInterfaces = True

                    With .Parameters
                      .SetString("Source", UpdateRequestSourceText)
                      .SetInteger("Pk", log.Pk)
                    End With
                  End With
                Else
                  With .AddFormShow("UpdateRequestAction", "Action Update Request", "UpdateRequestAction")
                    .ShowInWebInterfaces = True

                    With .Parameters
                      .SetString("Source", UpdateRequestSourceText)
                      .SetInteger("Pk", log.Pk)
                    End With
                  End With
                End If
              End With
            End If
          End If

        Case Else
          ' =====
          ' Other
          ' =====
          If Len(log.ExtendedDataNotes) <> 0 Then
            .Caption = finBL.Runtime.TextUtilities.SplitWordsAtCapitals(log.ExtendedType.ToString()) & " details"
            .Columns.AddText(log.ExtendedDataNotes)
          End If
      End Select
    End With

    ' Service Log etc
    ' NOTE: As per WorkflowItem_Supplemental
    Warnings = ""
    With SummaryTableServiceLog
      If log.IsBankAccountEnquiry Then
        ' ====================
        ' Bank Account Enquiry
        ' ====================
        .TableClass = iseSummaryTableClass.Information
        .Caption = "Bank Account Enquiry"
        .Columns.AddText(16).NoBreakChars = 20
        .Columns.AddText()

        ' Get Bank Account Enquiry Response from Service Log
        If finBL.CreditBureau.GetBankAccountEnquiryResponseFromServiceLog(log.ServiceLog, BankAccountEnquiryResponse) Then
          With .Rows
            .AddCaptionText("Service:", BankAccountEnquiryResponse.ServiceName)
            .AddCaptionDateTime("Date:", BankAccountEnquiryResponse.EnquiryDate)
            .AddCaptionText("Product:", BankAccountEnquiryResponse.ProductId)
          End With
        Else
          With .Rows
            .AddCaptionText("Service:", log.ServiceLog.ServiceId)
          End With
          .TextAfter = "{{error|" & finBL.Error.Message(True) & "}}"
        End If

        ' Actions
        With .Actions
          .AddHtmlShowFunction("ServiceReport", "View Bank Account Enquiry", "ServiceReport", "Bank Account Enquiry", "serviceLogPk=" & log.ServiceLogPk).ShowInWebInterfaces = True
        End With
      ElseIf log.IsCreditBureauMonitor Then
        ' =====================
        ' Credit Bureau Monitor
        ' =====================
        .TableClass = iseSummaryTableClass.Information
        .Caption = "Credit Bureau Monitor"
        .Columns.AddText(16).NoBreakChars = 20
        .Columns.AddText()

        ' Get Credit Bureau Monitor Response from Service Log
        If finBL.CreditBureau.GetCreditBureauMonitorResponseFromServiceLog(log.ServiceLog, CreditMonitorResponse) Then
          With .Rows
            .AddCaptionText("Service:", CreditMonitorResponse.ServiceName)
            .AddCaptionDateTime("Date:", CreditMonitorResponse.EnquiryDate)
            .AddCaptionText("Status:", log.ServiceLog.ResponseStatusText)
          End With
        Else
          .TextBefore = "{{error|" & finBL.Error.Message(True) & "}}"
          With .Rows
            .AddCaptionText("Service:", log.ServiceLog.ServiceId)
          End With
        End If

        ' Actions
        With .Actions
          .AddHtmlShowFunction("ServiceReport", "View Credit Bureau Monitor", "ServiceReport", "Credit Bureau Monitor", "serviceLogPk=" & log.ServiceLogPk).ShowInWebInterfaces = True
        End With
      ElseIf log.IsCreditEnquiry Then
        ' ==============
        ' Credit Enquiry
        ' ==============
        .TableClass = iseSummaryTableClass.Information
        .Caption = "Credit Enquiry"
        .Columns.AddText(16).NoBreakChars = 20
        .Columns.AddText()

        ' Get Credit Enquiry Response from Service Log
        If finBL.CreditBureau.GetCreditEnquiryResponseFromServiceLog(log.ServiceLog, CreditEnquiryResponse) Then
          With .Rows
            .AddCaptionText("Service:", CreditEnquiryResponse.ServiceName)
            .AddCaptionDateTime("Date:", CreditEnquiryResponse.EnquiryDate)
            .AddCaptionText("Name:", CreditEnquiryResponse.Name)
            .AddCaptionText("Product:", CreditEnquiryResponse.ProductId)
          End With
        Else
          .TextBefore = "{{error|" & finBL.Error.Message(True) & "}}"
          With .Rows
            .AddCaptionText("Service:", log.ServiceLog.ServiceId)
          End With
        End If

        ' Actions
        With .Actions
          .AddHtmlShowFunction("ServiceReport", "View Credit Enquiry", "ServiceReport", "Credit Enquiry", "serviceLogPk=" & log.ServiceLogPk).ShowInWebInterfaces = True
        End With
      ElseIf log.IsElectronicSignature Then
        ' ====================
        ' Electronic Signature
        ' ====================
        .TableClass = iseSummaryTableClass.Information
        .Caption = "Electronic Signature"
        .Columns.AddText(16).NoBreakChars = 20
        .Columns.AddText()

        ' Get Electronic Signature Response from Service Log
        If finBL.ElectronicSignature.GetResponseFromServiceLog(log.ServiceLog, ElectronicSignatureResponse) Then
          If ElectronicSignatureResponse Is Nothing Then
            With .Rows
              .AddCaptionText("Service:", log.ServiceLog.ServiceId)
            End With
          Else
            With .Rows
              .AddCaptionText("Service:", ElectronicSignatureResponse.ServiceName)
              .AddCaptionDateTime("Date:", ElectronicSignatureResponse.RequestDate)
              .AddCaptionText("Status:", log.ServiceLog.ResponseStatusText)
            End With

            ' Actions
            With .Actions
              .AddHtmlShowFunction("ServiceReport", "View Electronic Signature", "ServiceReport", "Electronic Signature", "serviceLogPk=" & log.ServiceLogPk).ShowInWebInterfaces = True
            End With
          End If
        Else
          With .Rows
            .AddCaptionText("Service:", log.ServiceLog.ServiceId)
          End With
          .TextAfter = "{{error|" & finBL.Error.Message(True) & "}}"
        End If

      ElseIf log.IsSecurityEnquiry Then
        ' ================
        ' Security Enquiry
        ' ================
        .TableClass = iseSummaryTableClass.Information
        .Caption = "Security Enquiry"
        .Columns.AddText(16).NoBreakChars = 20
        .Columns.AddText()

        ' Get Security Enquiry Response from Service Log
        If finBL.SecurityEnquiry.GetSecurityEnquiryResponseFromServiceLog(log.ServiceLog, SecurityEnquiryResponse) Then
          If SecurityEnquiryResponse Is Nothing Then
            With .Rows
              .AddCaptionText("Service:", log.ServiceLog.ServiceId)
            End With
          Else
            With .Rows
              .AddCaptionText("Service:", SecurityEnquiryResponse.ServiceName)
              .AddCaptionDateTime("Date:", SecurityEnquiryResponse.EnquiryDate)
              .AddCaptionText("Product:", SecurityEnquiryResponse.ProductId)
            End With

            ' Actions
            With .Actions
              If SecurityEnquiryResponse.IsReport Then
                .AddHtmlShowFunction("ServiceReport", "View Security Enquiry", "ServiceReport", "Security Enquiry", "serviceLogPk=" & log.ServiceLogPk).ShowInWebInterfaces = True
              End If
            End With
          End If
        Else
          With .Rows
            .AddCaptionText("Service:", log.ServiceLog.ServiceId)
          End With
          .TextAfter = "{{error|" & finBL.Error.Message(True) & "}}"
        End If

      ElseIf log.IsSecurityRegisterRequest() Then
        ' =================
        ' Security Registry
        ' =================
        .TableClass = iseSummaryTableClass.Information
        .Caption = "Security Register"
        .Columns.AddText(16).NoBreakChars = 20
        .Columns.AddText()

        ' Get Security Register Response from Service Log
        If finBL.SecurityRegistry.GetSecurityRegistryResponseFromServiceLog(log.ServiceLog, SecurityRegistryResponse) Then
          If SecurityRegistryResponse Is Nothing Then
            With .Rows
              .AddCaptionText("Service:", log.ServiceLog.ServiceId)
            End With
          Else
            With .Rows
              .AddCaptionText("Service:", SecurityRegistryResponse.ServiceName)
              .AddCaptionDateTime("Date:", SecurityRegistryResponse.RequestDate)
              .AddCaptionText("Product:", SecurityRegistryResponse.ProductId)
            End With

            ' Actions
            With .Actions
              .AddHtmlShowFunction("ServiceReport", "View Security Registry Enquiry", "ServiceReport", "Security Registry Enquiry", "serviceLogPk=" & log.ServiceLogPk).ShowInWebInterfaces = True
            End With
          End If
        Else
          With .Rows
            .AddCaptionText("Service:", log.ServiceLog.ServiceId)
          End With
          .TextAfter = "{{error|" & finBL.Error.Message(True) & "}}"
        End If

      ElseIf log.ExtendedType = isefinLogExtendedType.DecisionOutcome OrElse log.ExtendedType = isefinLogExtendedType.ClientIdentificationDecisionOutcome Then
        ' ================
        ' Decision Outcome
        ' ================
        ' Initialise
        .TableClass = iseSummaryTableClass.Information
        .Caption = "Decision Outcome"
        .Columns.AddText(16).NoBreakChars = 20
        .Columns.AddText()

        If log.GetDecisionOutcomeFromExtendedData(DecisionOutcome) Then
          With .Rows
            With .AddCaptionText("Outcome:", DecisionOutcome.OutcomeStatusText, iseSummaryTableCellClass.Highlight1).Cells(1)
              Select Case DecisionOutcome.OutcomeStatus
                Case isefinDecisionOutcomeStatus.Fail : .ForegroundColour = "red"
                Case isefinDecisionOutcomeStatus.Pass : .ForegroundColour = "green"
                Case isefinDecisionOutcomeStatus.Refer : .ForegroundColour = "blue"
              End Select
            End With
            If Len(DecisionOutcome.OutcomeCode) <> 0 Then
              .AddCaptionText("Code:", DecisionOutcome.OutcomeCode)
            End If
            If Len(DecisionOutcome.OutcomeMessageResolved) <> 0 Then
              .AddCaptionText("Message:", DecisionOutcome.OutcomeMessageResolved)
            End If
            .AddCaptionCodeDescription("Decision Card:", DecisionOutcome.DecisionCardId, finBL.DecisionCards)
          End With

          ' Actions
          With .Actions
            .AddHtmlShowFunction("DecisionOutcome", "View Decision Outcome", "DecisionOutcomeSummary", "Decision Outcome", "logPk=" & log.Pk & "&logClass=" & log.LogClass.ToString()).ShowInWebInterfaces = True
          End With
        Else
          .TextAfter = "{{error|" & finBL.Error.Message(True) & "}}"
        End If
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)
    If SummaryTableExtendedData.HasData OrElse SummaryTableExtendedData.Actions.Count <> 0 Then SummaryTables.Add("ExtendedData", SummaryTableExtendedData)
    If SummaryTableServiceLog.HasData Then SummaryTables.Add("ServiceLog", SummaryTableServiceLog)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  A very simple Summary of a single Log.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="log">
  '''  The Log to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used to summarise a Log below grids such as the Task Manager 2 Bookmared folder.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Log_SummarySimple(callerScriptInfo As ISScriptExecutionInfo,
                                                log As I_finLog,
                                       Optional includeActions As Boolean = True,
                                       Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' Log_SummarySimple
    '
    ' Version: 1.00 (27/07/2023)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.00  27/07/2023  ISS      J031663   Created  
    ' #################################################################

    Dim DateAsAt As Date
    Dim strTemp As String
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Date As At
    DateAsAt = finBL.TimeZoneFunctions.GetCurrentDatabaseDate()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      .Columns.AddText(16).NoBreakChars = 20
      .Columns.AddText()

      With .Rows
        ' General
        With .AddCaptionText("Subject:", log.Subject, iseSummaryTableCellClass.Highlight1).Cells(1)
          Select Case log.GetType()
            Case GetType(finAccountLog)
              .HyperlinkSetFormShow("AccountLog", CStr(log.Pk))

            Case GetType(finAccountAppLog)
              .HyperlinkSetFormShow("AccountAppLog", CStr(log.Pk))

            Case GetType(finClientLog)
              .HyperlinkSetFormShow("ClientLog", CStr(log.Pk))

            Case GetType(finSecurityStmtLog)
              .HyperlinkSetFormShow("SecurityStmtLog", CStr(log.Pk))

            Case GetType(finSecurityStmtItemLog)
              .HyperlinkSetFormShow("SecurityStmtItemLog", CStr(log.Pk))

            Case GetType(finUserLog)
              .HyperlinkSetFormShow("UserLog", CStr(log.Pk))
          End Select
        End With
        .AddCaptionUtcDateTimeWithTimeZone("Date:", log.LogUtcDate, log.LogTimeZoneId)

        ' Action details
        If log.ActionDbDate <> Nothing Then
          If log.IsIncomplete Then
            ' Incomplete
            If log.DelegatedToUserPk = 0 AndAlso log.DelegatedToRolePk = 0 Then
              strTemp = log.OwnerUserId
            ElseIf log.DelegatedToUserPk <> 0 Then
              strTemp = String.Format("User '{0}'", log.DelegatedToUserId)
            ElseIf log.DelegatedToRolePk <> 0 Then
              strTemp = String.Format("Role '{0}'", log.DelegatedToRoleId)
            End If
            With .AddCaptionUtcDateTimeWithTimeZone("Action:", log.ActionUtcDate, log.ActionTimeZoneId, String.Format("**To Action** --by-- **{0}** --on-- ", strTemp)).Cells(1)
              ' Action date passed?
              If log.ActionDbDate < DateAsAt Then
                .ForegroundColour = "red"
                Warnings &= " {{warning|Action date passed.}}"
              End If
            End With
          Else
            ' Complete
            .AddCaptionUtcDateTimeWithTimeZone("Action:", log.ActionCompleteUtcDate, log.ActionTimeZoneId, "**Completed** --on-- ")
          End If
        End If

        ' Outcome
        If Len(log.LogOutcome) <> 0 Then
          .AddCaptionText("Outcome:", log.LogOutcome)
        End If

        ' Notes
        If Len(log.Notes) <> 0 Then
          With .AddText(log.Notes)
            .RowClass = iseSummaryTableRowClass.Alt2
            .Cells(0).CellClass = iseSummaryTableCellClass.Positive
          End With
        End If
      End With

      ' Warnings
      If log.PublishStatus = isefinLogPublishStatus.ToSend AndAlso log.PublishOnDbDate < DateAsAt Then
        Warnings &= " {{warning|Publish date passed.}}"
      End If
      .TextAfter = Warnings

      ' Actions
      If includeActions Then
        With .Actions
        End With
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Pool Summary (Version 1.00, Last updated 27/08/2014).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="pool">
  '''  The Pool to summarise.
  ''' </param>
  ''' <param name="includePoolIdHyperlink">
  '''  Indicates whether to include a hyperlink on the Pool Id to show the Pools form.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Pool Key Details page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Pool_Summary(callerScriptInfo As ISScriptExecutionInfo,
                                           pool As finPool,
                                  Optional includePoolIdHyperlink As Boolean = True,
                                  Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim TotalDeposits As Decimal
    Dim TotalLoans As Decimal
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Totals
    pool.Accounts.GetTotalAccountBalances(TotalDeposits, TotalLoans)

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      .Columns.AddText(16).NoBreakChars = 16
      .Columns.AddText()

      With .Rows
        ' General
        With .AddCaptionText("Code:", pool.PoolId)
          If includePoolIdHyperlink AndAlso Not pool.IsNew Then
            .Cells(1).HyperlinkSetFormShow("Pools", pool.PoolId)
          End If
        End With
        .AddCaptionText("Description:", pool.Description, iseSummaryTableCellClass.Highlight1)

        ' Totals
        .AddSectionHeading2("Pool Totals")
        .AddCaptionCurrency("Total Deposits:", TotalDeposits)
        .AddCaptionCurrency("less Total Loans:", TotalLoans)
        With .AddCaptionCurrency("Pool Balance:", TotalDeposits - TotalLoans, , , iseSummaryTableCellClass.Highlight2)
          If TotalDeposits - TotalLoans < 0 Then
            .Cells(1).ForegroundColour = "red"
          End If
        End With
      End With

      ' Warnings
      .TextAfter = Warnings
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Pool Deposit Accounts (Version 1.00, Last updated 27/08/2014).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="pool">
  '''  The Pool to summarise.
  ''' </param>
  ''' <param name="showAccountDescription">
  '''  Indicates whether to show an Account Description column.
  ''' </param>
  ''' <param name="showTotals">
  '''  Indicates whether to show Totals.
  ''' </param>
  ''' <param name="maxDisplayRows">
  '''  The Maximum number of Rows to Display in the table before a 'Show Hidden' link is displayed.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Pool Key Details page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Pool_Deposits(callerScriptInfo As ISScriptExecutionInfo,
                                            pool As finPool,
                                            showAccountDescription As Boolean,
                                            showTotals As Boolean,
                                   Optional maxDisplayRows As Integer = 20,
                                   Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim AccountType As finAccountTypeRO
    Dim GroupCount As Integer
    Dim GroupTotal As Decimal
    Dim Include As Boolean
    Dim PoolAccount As finPoolAccount
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Total As Decimal

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .Caption = ""
      .AutoStripe = True
      .MaxDisplayRows = maxDisplayRows
      .ShowHiddenRowsCaption = "Show More Accounts"

      ' Columns (including Header row)
      With .Columns
        .AddCode("Account", finBL.AccountFunctions.GetLongestCode())
        .AddText("Name")
        If showAccountDescription Then
          With .AddText("Description")
            .HideRule = iseSummaryTableColumnHideRule.DocumentWidthLessThan800px
          End With
        End If
        .AddCurrency("Balance")
      End With

      ' Accounts (grouped by Account Type)
      For Each AccountType In finBL.AccountTypes
        ' Initialise
        GroupCount = 0
        GroupTotal = 0

        ' Include?
        Select Case AccountType.AccountClass
          Case isefinAccountClass.Current, isefinAccountClass.Deposit
            Include = True
          Case Else
            Include = False
        End Select

        ' Add Rows for this Account Type
        If Include Then
          For Each PoolAccount In pool.Accounts
            ' Include?
            If PoolAccount.AccountTypePk = AccountType.Pk AndAlso PoolAccount.Status = isefinAccountStatus.Open Then
              Select Case PoolAccount.AccountClass
                Case isefinAccountClass.Current, isefinAccountClass.Disbursement
                  Include = PoolAccount.Balance < 0
                Case isefinAccountClass.Deposit
                  Include = True
                Case Else
                  Include = False
              End Select
            Else
              Include = False
            End If

            If Include Then
              ' Add Group Header
              If GroupCount = 0 Then
                With .Rows.Add(iseSummaryTableRowClass.HeaderCollapsible).Cells
                  .Add(String.Format("{0}, {1}", AccountType.AccountTypeId, AccountType.Description))
                End With
              End If

              ' Add Row
              With .Rows.Add()
                With .Cells
                  With .AddText(PoolAccount.AccountId)
                    .HyperlinkSetFormShow("Accounts", PoolAccount.AccountId)
                  End With
                  .AddText(PoolAccount.Name)
                  If showAccountDescription Then
                    .AddText(PoolAccount.Description)
                  End If
                  .AddCurrency(-PoolAccount.Balance)
                End With
              End With

              ' Totals
              GroupCount += 1
              GroupTotal -= PoolAccount.Balance
              Total -= PoolAccount.Balance
            End If
          Next

          ' Add Group Footer
          If showTotals AndAlso GroupCount <> 0 Then
            With .Rows.Add(iseSummaryTableRowClass.Footer)
              With .Cells
                .AddText("Total")
                .AddText("")
                If showAccountDescription Then
                  .AddText("")
                End If
                .AddCurrency(GroupTotal)
              End With
            End With
          End If
        End If
      Next

      ' Add Grand Total Row
      If showTotals Then
        With .Rows.Add(iseSummaryTableRowClass.FooterBold).Cells
          .AddText("Total Deposits").ColSpan = 2
          If showAccountDescription Then
            .AddText("")
          End If
          .AddCurrency(Total)
        End With
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Pool Loan Accounts (Version 1.00, Last updated 27/08/2014).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="pool">
  '''  The Pool to summarise.
  ''' </param>
  ''' <param name="showAccountDescription">
  '''  Indicates whether to show an Account Description column.
  ''' </param>
  ''' <param name="showTotals">
  '''  Indicates whether to show Totals.
  ''' </param>
  ''' <param name="maxDisplayRows">
  '''  The Maximum number of Rows to Display in the table before a 'Show Hidden' link is displayed.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Pool Key Details page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Pool_Loans(callerScriptInfo As ISScriptExecutionInfo,
                                         pool As finPool,
                                         showAccountDescription As Boolean,
                                         showTotals As Boolean,
                                Optional maxDisplayRows As Integer = 20,
                                Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim AccountType As finAccountTypeRO
    Dim GroupCount As Integer
    Dim GroupTotal As Decimal
    Dim Include As Boolean
    Dim PoolAccount As finPoolAccount
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Total As Decimal

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .Caption = ""
      .AutoStripe = True
      .MaxDisplayRows = maxDisplayRows
      .ShowHiddenRowsCaption = "Show More Accounts"

      ' Columns (including Header row)
      With .Columns
        .AddCode("Account", finBL.AccountFunctions.GetLongestCode())
        .AddText("Name")
        If showAccountDescription Then
          With .AddText("Description")
            .HideRule = iseSummaryTableColumnHideRule.DocumentWidthLessThan800px
          End With
        End If
        .AddCurrency("Balance")
      End With

      ' Accounts (grouped by Account Type)
      For Each AccountType In finBL.AccountTypes
        ' Initialise
        GroupCount = 0
        GroupTotal = 0

        ' Include?
        Select Case AccountType.AccountClass
          Case isefinAccountClass.Current, isefinAccountClass.Deposit
            Include = False
          Case Else
            Include = True
        End Select

        ' Add Rows for this Account Type
        If Include Then
          For Each PoolAccount In pool.Accounts
            ' Include?
            If PoolAccount.AccountTypePk = AccountType.Pk AndAlso PoolAccount.Status = isefinAccountStatus.Open Then
              Select Case PoolAccount.AccountClass
                Case isefinAccountClass.Current, isefinAccountClass.Disbursement
                  Include = PoolAccount.Balance >= 0
                Case isefinAccountClass.Deposit
                  Include = False
                Case Else
                  Include = True
              End Select
            Else
              Include = False
            End If

            If Include Then
              ' Add Group Header
              If GroupCount = 0 Then
                With .Rows.Add(iseSummaryTableRowClass.HeaderCollapsible).Cells
                  .Add(String.Format("{0}, {1}", AccountType.AccountTypeId, AccountType.Description))
                End With
              End If

              ' Add Row
              With .Rows.Add()
                With .Cells
                  With .AddText(PoolAccount.AccountId)
                    .HyperlinkSetFormShow("Accounts", PoolAccount.AccountId)
                  End With
                  .AddText(PoolAccount.Name)
                  If showAccountDescription Then
                    .AddText(PoolAccount.Description)
                  End If
                  .AddCurrency(PoolAccount.Balance)
                End With
              End With

              ' Totals
              GroupCount += 1
              GroupTotal += PoolAccount.Balance
              Total += PoolAccount.Balance
            End If
          Next

          ' Add Group Footer
          If showTotals AndAlso GroupCount <> 0 Then
            With .Rows.Add(iseSummaryTableRowClass.Footer)
              With .Cells
                .AddText("Total")
                .AddText("")
                If showAccountDescription Then
                  .AddText("")
                End If
                .AddCurrency(GroupTotal)
              End With
            End With
          End If
        End If
      Next

      ' Add Grand Total Row
      If showTotals Then
        With .Rows.Add(iseSummaryTableRowClass.FooterBold).Cells
          .AddText("Total Loans").ColSpan = 2
          If showAccountDescription Then
            .AddText("")
          End If
          .AddCurrency(Total)
        End With
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Quick Search Help HTML (Version 1.02, Last updated 26/02/2016).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An String value.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Quick Search form.
  '''  </para>
  '''  <para>
  '''   Returns a partial HTML document.
  '''  </para>
  ''' </remarks>
  Public Overridable Function QuickSearch_Help(callerScriptInfo As ISScriptExecutionInfo,
                                      Optional includeActions As Boolean = True,
                                      Optional otherParameters As ISKeyValueList = Nothing) As String

    Dim List As ISList
    Dim s As String
    Dim sb As StringBuilder

    ' Initialise ByRef Parameters

    ' Initialise
    List = New ISList()

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()

    ' What is searched as you type?
    If finBL.Settings.QuickSearchWhenTyping Then
      If finBL.Settings.QuickSearchIncludeAccountName Then
        List.Add("Accounts")
      Else
        List.Add("Accounts <small style='color:#808080'>(code only)</small>")
      End If
      List.Add("Clients")
      If finBL.Settings.AddOns.SecurityRegister AndAlso finBL.Settings.QuickSearchIncludeSecurityStmtId Then
        List.Add("Security Statements <small style='color:#808080'>(code only)</small>")
      End If
    End If
    If finBL.SettingsUser.QuickSearchIncludeAdmin Then
      List.Add("Admin <small style='color:#808080'>(limited, e.g. Account Types)</small>")
    End If
    If finBL.SettingsUser.QuickSearchIncludeMenus Then
      List.Add("Menus")
    End If
    If finBL.SettingsUser.QuickSearchIncludeReports Then
      List.Add("Reports")
    End If
    If finBL.Settings.AddOns.Workflow Then
      List.Add("Workflows <small style='color:#808080'>(code only)</small>")
    End If

    ' Initialise
    sb = New StringBuilder()

    ' Generate Help text
    With sb
      .AppendLine("<h1>{{icon|Help}} Quick Search</h1>")

      ' Quick Search when Typing
      If List.Count <> 0 Then
        .AppendLine("<p>The following will be matched as you type:</p>")
        .AppendLine("<ul style='padding-left:1.5em'>")
        For Each s In List
          .AppendLine(String.Format("<li>{0}</li>", s))
        Next
        .AppendLine("</ul>")
      End If

      If finBL.Settings.QuickSearchWhenTyping Then
        ' Deeper Search
        .AppendLine("<p>Pressing <b>Enter</b> (or {{icon|Search}}) will perform a more comprehensive search. Pressing it a second time will perform a deep search.</p>")
      Else
        ' No Searching as you type (of proper records)
        List.Clear()
        List.Add("Accounts")
        List.Add("Clients")
        If finBL.Settings.AddOns.SecurityRegister Then
          List.Add("Security Statements")
        End If

        .AppendLine("<p>Press <b>Enter</b> (or {{icon|Search}}) to search the following:</p>")
        .AppendLine("<ul style='padding-left:1.5em'>")
        For Each s In List
          .AppendLine(String.Format("<li>{0}</li>", s))
        Next
        .AppendLine("</ul>")
        .AppendLine("<p>Searching a second time will perform a deep search.</p>")
      End If

      .Append("{{info|Use quotes when searching values containing spaces, e.g., **""Queen Street""**}}")
    End With

    ' Resolve Templates
    Return sb.ToString()

  End Function

  ''' <summary>
  '''  Quick Search Result Summary (Version 1.02, Last updated 2/12/2015).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="quickSearchResult">
  '''  The Quick Search Result to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="maxDisplayRows">
  '''  The Maximum number of Rows to Display in supplemental tables (e.g., Client Accounts) before a 'Show Hidden' link is displayed.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Quick Search form.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables (depending on the item type being summarised, additional tables may be included):
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function QuickSearch_ResultSummary(callerScriptInfo As ISScriptExecutionInfo,
                                                        quickSearchResult As finQuickSearchResult,
                                               Optional maxDisplayRows As Integer = 20,
                                               Optional includeActions As Boolean = True,
                                               Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim SummaryTables As ISSummaryTables

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()

    ' Get Summary Data (in a non-HTML-specific ISSummaryTables collection)
    Select Case quickSearchResult.ObjectType
      Case isefinQuickSearchObjectType.Account
        SummaryTables = Me.QuickSearch_ResultSummary_Account(callerScriptInfo, quickSearchResult, maxDisplayRows, includeActions, otherParameters)
      Case isefinQuickSearchObjectType.AccountApp
        SummaryTables = Me.QuickSearch_ResultSummary_AccountApp(callerScriptInfo, quickSearchResult, maxDisplayRows, includeActions, otherParameters)
      Case isefinQuickSearchObjectType.AccountArchive
        SummaryTables = Me.QuickSearch_ResultSummary_AccountArchive(callerScriptInfo, quickSearchResult, maxDisplayRows, includeActions, otherParameters)
      Case isefinQuickSearchObjectType.Branch
        SummaryTables = Me.QuickSearch_ResultSummary_Branch(callerScriptInfo, quickSearchResult, maxDisplayRows, includeActions, otherParameters)
      Case isefinQuickSearchObjectType.Client
        SummaryTables = Me.QuickSearch_ResultSummary_Client(callerScriptInfo, quickSearchResult, maxDisplayRows, includeActions, otherParameters)
      Case isefinQuickSearchObjectType.StandaloneDocument
        SummaryTables = Me.QuickSearch_ResultSummary_StandaloneDocument(callerScriptInfo, quickSearchResult, maxDisplayRows, includeActions, otherParameters)
      Case isefinQuickSearchObjectType.ExternalParty
        SummaryTables = Me.QuickSearch_ResultSummary_ExternalParty(callerScriptInfo, quickSearchResult, maxDisplayRows, includeActions, otherParameters)
      Case isefinQuickSearchObjectType.MenuItem
        SummaryTables = Me.QuickSearch_ResultSummary_MenuItem(callerScriptInfo, quickSearchResult, maxDisplayRows, includeActions, otherParameters)
      Case isefinQuickSearchObjectType.Report
        SummaryTables = Me.QuickSearch_ResultSummary_Report(callerScriptInfo, quickSearchResult, maxDisplayRows, includeActions, otherParameters)
      Case isefinQuickSearchObjectType.SecurityStmt
        SummaryTables = Me.QuickSearch_ResultSummary_SecurityStmt(callerScriptInfo, quickSearchResult, maxDisplayRows, includeActions, otherParameters)
      Case isefinQuickSearchObjectType.User
        SummaryTables = Me.QuickSearch_ResultSummary_User(callerScriptInfo, quickSearchResult, maxDisplayRows, includeActions, otherParameters)
      Case isefinQuickSearchObjectType.Workflow
        SummaryTables = Me.QuickSearch_ResultSummary_Workflow(callerScriptInfo, quickSearchResult, maxDisplayRows, includeActions, otherParameters)
      Case Else
        ' Assume a global collection
        SummaryTables = Me.QuickSearch_ResultSummary_Generic(callerScriptInfo, quickSearchResult, maxDisplayRows, includeActions, otherParameters)
    End Select

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Quick Search Result Summary for an Account.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="quickSearchResult">
  '''  The Quick Search Result to summarise.
  ''' </param>
  ''' <param name="maxDisplayRows">
  '''  The Maximum number of Rows to Display in supplemental tables (e.g., Client Accounts) before a 'Show Hidden' link is displayed.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Quick Search form.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables (depending on the item type being summarised, additional tables may be included):
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''    <item><code>Clients</code><description>Account Clients.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function QuickSearch_ResultSummary_Account(callerScriptInfo As ISScriptExecutionInfo,
                                                                quickSearchResult As finQuickSearchResult,
                                                                maxDisplayRows As Integer,
                                                                includeActions As Boolean,
                                                                otherParameters As ISKeyValueList) As ISSummaryTables

    ' #################################################################
    ' QuickSearch_ResultSummary_Account
    '
    ' Version: 1.07 (20/08/2024)    
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    ' 1.04     28/03/2017
    ' 1.05     26/09/2023  ISS      J032101   Refactored AddOn checks
    ' 1.06     28/09/2023  ISS      J032114   Email/SMS Permissions finCC
    ' 1.07     20/08/2024  ISS      J034115   Added Manager
    ' #################################################################

    Dim Account As finAccount
    Dim AccountClient As finAccountClient
    Dim AddressDetails As ISAddressDetails
    Dim Popup As Boolean
    Dim SummaryTable As ISSummaryTable
    Dim SummaryTableClients As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim strTemp As String
    Dim Warnings As finWarnings

    ' Initialise
    Account = DirectCast(quickSearchResult.SourceObject, finAccount)
    SummaryTable = finBL.CreateSummaryTable()
    SummaryTableClients = finBL.CreateSummaryTable()

    ' Determine whether this Summary is being produced by a "Popup" form
    If callerScriptInfo IsNot Nothing AndAlso InStr(callerScriptInfo.FormKey, "Popup", CompareMethod.Text) <> 0 Then
      Popup = True
    End If

    ' Add Columns
    With SummaryTable
      .TableClass = iseSummaryTableClass.Information
      .Columns.AddText(12).NoBreakChars = 6 ' E.g., Bulk Funder
      .Columns.AddText(10)
      .Columns.AddText() ' Extra column to display Warnings after code
    End With

    ' Details
    With SummaryTable.Rows
      ' Code and Name
      With .AddCaptionText("Code:", Account.AccountId)
        With .Cells(1)
          .HyperlinkSetApplicationShortcutUrl(quickSearchResult.ApplicationShortcutUrl)
          .NoWrap = True
        End With

        ' Warnings (show after code for compactness)
        Warnings = Account.GetWarnings()
        If Warnings.Count = 0 Then
          .Cells.AddText("")
        Else
          If Warnings.Count = 1 Then
            strTemp = "!!**1** warning!!"
          Else
            strTemp = String.Format("!!**{0}** warnings!!", Warnings.Count)
          End If
          With .Cells.AddWiki("{{icon|Warning}} " & strTemp)
            If Not Popup Then
              .HyperlinkSetHtmlShowFunction("AccountWarningsSummary", String.Format("Warnings for Account {0}, '{1}'", Account.AccountId, Account.Name), "AccountId=" & Account.AccountId)
            End If
          End With
        End If
      End With
      .AddCaptionText("Name:", Account.Name, iseSummaryTableCellClass.Highlight1)

      ' Account Type
      .AddCaptionCodeDescription("Type:", Account.AccountTypePk, finBL.AccountTypes)

      ' Status (Wiki text)
      strTemp = "**" & Account.StatusText & "**"
      Select Case Account.Status
        Case isefinAccountStatus.Closed
          strTemp &= String.Format(" --on **{0}**--", finBL.FormatDateLong(Account.DateClosed))
        Case isefinAccountStatus.ClosedPending
          strTemp &= String.Format(" --on **{0}**--", finBL.FormatDateLong(Account.DateClosed))
        Case isefinAccountStatus.Declined, isefinAccountStatus.Unwanted
          strTemp &= String.Format(" --on **{0}**--", finBL.FormatDateLong(Account.DateClosed))
        Case isefinAccountStatus.Open
          strTemp &= String.Format(" --on **{0}**--", finBL.FormatDateLong(Account.DateOpened))
        Case isefinAccountStatus.Quote
          strTemp &= String.Format(" --on **{0}**--", finBL.FormatDateLong(Account.DateQuoted))
        Case Else
          strTemp = "!!STATUS NOT HANDLED!!"
      End Select
      .AddCaptionWiki("Status:", strTemp)

      ' Branch etc
      If finBL.SettingsUser.SummaryPagesShowBranchResolved AndAlso Account.BranchPk <> 0 Then
        With .AddCaptionCodeDescription("Branch:", Account.BranchPk, finBL.Branches).Cells(1)
          If finBL.Settings.AddOns.Entity Then
            .Value &= String.Format(" ({0})", Account.Entity.Name)
          End If
        End With
      End If
      If finBL.SettingsUser.SummaryPagesShowDepartmentResolved AndAlso Account.DepartmentPk <> 0 Then
        .AddCaptionCodeDescription("Department:", Account.DepartmentPk, finBL.Departments)
      End If
      If finBL.SettingsUser.SummaryPagesShowManagerResolved AndAlso Account.AccountManagerUserPk <> 0 Then
        .AddCaptionCodeDescription("Manager:", Account.AccountManagerUserId, finBL.Users)
      End If
      If finBL.SettingsUser.SummaryPagesShowDealerResolved AndAlso Account.DealerExternalPartyPk <> 0 Then
        With .AddCaptionCodeDescription("Dealer:", Account.DealerExternalPartyPk, finBL.ExternalParties).Cells(1)
          If finBL.ExternalParties.ItemByPk(Account.DealerExternalPartyPk).MasterExternalPartyPk <> 0 Then
            .Value &= String.Format(" ({0})", finBL.ExternalParties.ItemByPk(finBL.ExternalParties.ItemByPk(Account.DealerExternalPartyPk).MasterExternalPartyPk).Name)
          End If
        End With
      End If
      If finBL.SettingsUser.SummaryPagesShowBrokerResolved AndAlso Account.AccountTypePk <> 0 AndAlso Account.BrokerExternalPartyPk <> 0 Then
        With .AddCaptionCodeDescription("Broker:", Account.BrokerExternalPartyPk, finBL.ExternalParties).Cells(1)
          If finBL.ExternalParties.ItemByPk(Account.BrokerExternalPartyPk).MasterExternalPartyPk <> 0 Then
            .Value &= String.Format(" ({0})", finBL.ExternalParties.ItemByPk(finBL.ExternalParties.ItemByPk(Account.BrokerExternalPartyPk).MasterExternalPartyPk).Name)
          End If
        End With
      End If
      If finBL.SettingsUser.SummaryPagesShowBulkFunderResolved AndAlso Account.BulkFunderExternalPartyPk <> 0 Then
        With .AddCaptionCodeDescription("Bulk Funder:", Account.BulkFunderExternalPartyPk, finBL.ExternalParties).Cells(1)
          If finBL.ExternalParties.ItemByPk(Account.BulkFunderExternalPartyPk).MasterExternalPartyPk <> 0 Then
            .Value &= String.Format(" ({0})", finBL.ExternalParties.ItemByPk(finBL.ExternalParties.ItemByPk(Account.BulkFunderExternalPartyPk).MasterExternalPartyPk).Name)
          End If
        End With
      End If

      ' Advances less Deposits
      Select Case Account.AccountClass
        Case isefinAccountClass.LoanFR, isefinAccountClass.LoanFT
          .AddCaptionText("Advance:", finBL.FormatCurrency(Account.TotalAdvances(), True))
      End Select
    End With

    ' Actions
    If includeActions AndAlso Not finBL.Database.IsReadOnly Then
      With SummaryTable.Actions
        .AddFormShow("LogAdd", "Log", "AccountLog", finBL.CurrentUser.Permissions.Allow("Account.Logs.Add"), "AccountId=" & finBL.UrlEncode(Account.AccountId)).ShowInWebInterfaces = True
        .AddFormShow("SendEmail", "Email", "EmailMessage", finBL.HtmlWidgetUtilities.HasPermissionToViewFormKey("EmailMessage", ""), "Type=Account&Id=" & finBL.UrlEncode(Account.AccountId)).ShowInWebInterfaces = True
        .AddFormShow("SendSms", "SMS", "SMSMessage", finBL.Messaging.IsMessagingAvailable AndAlso finBL.HtmlWidgetUtilities.HasPermissionToViewFormKey("SMSMessage", ""), "Type=Account&Id=" & finBL.UrlEncode(Account.AccountId)).ShowInWebInterfaces = True
      End With
    End If

    ' Clients
    With SummaryTableClients
      .TableClass = iseSummaryTableClass.TabularData
      .AutoStripe = True
      .Caption = "Clients"

      With .Columns
        With .AddCode(" ", 1)
          .TextAlign = iseSummaryTableCellTextAlign.Center  ' Role Icon
          .HideRule = iseSummaryTableColumnHideRule.DocumentWidthLessThan240px
        End With
        .AddCode("Client", finBL.ClientFunctions.GetLongestCode())
        .AddText("Name")
        With .AddText("Address")
          .NoBreakChars = 30
          .HideRule = iseSummaryTableColumnHideRule.DocumentWidthLessThan500px
        End With
        With .AddText("Role", 10)
          .NoBreakChars = 15
          .HideRule = iseSummaryTableColumnHideRule.DocumentWidthLessThan400px
        End With
        .AddDate("DOB")
      End With

      For Each AccountClient In Account.Clients
        With .Rows.Add()
          If Len(AccountClient.AccountRole.Icon) = 0 Then
            .Cells.AddText("{{icon|Client}}")
          Else
            .Cells.AddText("{{icon|AccountRole_" & AccountClient.AccountRole.Icon & "}}")
          End If

          If AccountClient.IsClientFilteredOut Then
            .Cells.AddText(AccountClient.ClientId)
            .Cells.AddText(AccountClient.ClientName)
            .Cells.AddText("") ' Address
            .Cells.AddText(AccountClient.AccountRole.DescriptionShortResolved)
            .Cells.AddText("") ' Date of Birth
          Else
            With .Cells.AddText(AccountClient.ClientId)
              .HyperlinkSetFormShow("Clients", AccountClient.ClientId)
            End With
            .Cells.AddText(AccountClient.ClientName)

            ' Address
            AddressDetails = AccountClient.Client.ContactAddresses.GetCurrentPhysicalAddress()
            If Not AddressDetails.HasValue Then AddressDetails = AccountClient.Client.ContactAddresses.GetCurrentPostalAddress()
            If AddressDetails.HasValue Then
              .Cells.AddAddressDetailsPhysical(AddressDetails)
            Else
              .Cells.AddText("")
            End If

            .Cells.AddText(AccountClient.AccountRole.DescriptionShortResolved)
            .Cells.AddDate(AccountClient.ClientDateOfBirth)
          End If

          ' Hide Row?
          Select Case AccountClient.RoleType
            Case isefinAccountRoleType.Owner
            Case Else
              .Visible = False
          End Select
        End With
      Next
    End With

    ' Create and return collection
    SummaryTables = finBL.CreateSummaryTables()
    SummaryTables.Add("Main", SummaryTable)
    SummaryTables.Add("Clients", SummaryTableClients)
    Return SummaryTables

  End Function

  ''' <summary>
  '''  Quick Search Result Summary for an Account Application.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="quickSearchResult">
  '''  The Quick Search Result to summarise.
  ''' </param>
  ''' <param name="maxDisplayRows">
  '''  The Maximum number of Rows to Display in supplemental tables (e.g., Client Accounts) before a 'Show Hidden' link is displayed.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Quick Search form.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables (depending on the item type being summarised, additional tables may be included):
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''    <item><code>Applicants</code><description>Applicant details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function QuickSearch_ResultSummary_AccountApp(callerScriptInfo As ISScriptExecutionInfo,
                                                                   quickSearchResult As finQuickSearchResult,
                                                                   maxDisplayRows As Integer,
                                                                   includeActions As Boolean,
                                                                   otherParameters As ISKeyValueList) As ISSummaryTables

    ' #################################################################
    ' QuickSearch_ResultSummary_AccountApp
    '
    ' Version: 1.05 (29/08/2024)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    ' 1.03     10/06/2016
    ' 1.04     28/09/2023  ISS      J032114   Email/SMS Permissions finCC
    ' 1.05     29/08/2024  ISS      J034115   Added Manager, Branch, Department, Dealer and Broker
    ' #################################################################

    Dim AccountApp As finAccountApp
    Dim AccountAppApplicant As finAccountAppApplicant
    Dim Popup As Boolean
    Dim SummaryTable As ISSummaryTable
    Dim SummaryTableApplicants As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim strTemp As String

    ' Initialise
    AccountApp = DirectCast(quickSearchResult.SourceObject, finAccountApp)
    SummaryTable = finBL.CreateSummaryTable()
    SummaryTableApplicants = finBL.CreateSummaryTable()

    ' Determine whether this Summary is being produced by a "Popup" form
    If callerScriptInfo IsNot Nothing AndAlso InStr(callerScriptInfo.FormKey, "Popup", CompareMethod.Text) <> 0 Then
      Popup = True
    End If

    ' Add Columns
    With SummaryTable
      .TableClass = iseSummaryTableClass.Information
      .Columns.AddText(12)
      .Columns.AddText(10)
      .Columns.AddText() ' Extra column to display Warnings after code
    End With

    ' Details
    With SummaryTable.Rows
      ' Code and Name
      With .AddCaptionText("Code:", AccountApp.AccountAppId)
        With .Cells(1)
          .HyperlinkSetApplicationShortcutUrl(quickSearchResult.ApplicationShortcutUrl)
          .NoWrap = True
        End With
        .Cells.AddWiki("") ' Warnings (not yet implemented)
      End With
      .AddCaptionText("Name:", AccountApp.Name, iseSummaryTableCellClass.Highlight1)

      ' Account Application Type
      .AddCaptionCodeDescription("Type:", AccountApp.AccountAppTypePk, finBL.AccountAppTypes)

      ' Status (Wiki text)
      strTemp = "**" & AccountApp.StatusText & "**"
      If Len(AccountApp.StatusSub) <> 0 Then
        strTemp &= " (" & AccountApp.StatusSub & ")"
      End If
      Select Case AccountApp.Status
        Case isefinAccountAppStatus.Accepted
          strTemp &= String.Format(" --on **{0}**--", finBL.FormatDateLong(AccountApp.DateClosed))
        Case isefinAccountAppStatus.Declined, isefinAccountAppStatus.Unwanted
          strTemp &= String.Format(" --on **{0}**--", finBL.FormatDateLong(AccountApp.DateClosed))
        Case isefinAccountAppStatus.Incomplete, isefinAccountAppStatus.Reviewing, isefinAccountAppStatus.Complete
        Case Else
          strTemp = "!!STATUS NOT HANDLED!!"
      End Select
      .AddCaptionWiki("Status:", strTemp)

      ' Branch etc
      If finBL.SettingsUser.SummaryPagesShowBranchResolved AndAlso AccountApp.BranchPk <> 0 Then
        With .AddCaptionCodeDescription("Branch:", AccountApp.BranchPk, finBL.Branches).Cells(1)
          If finBL.Settings.AddOns.Entity Then
            .Value &= String.Format(" ({0})", AccountApp.Entity.Name)
          End If
        End With
      End If
      If finBL.SettingsUser.SummaryPagesShowDepartmentResolved AndAlso AccountApp.DepartmentPk <> 0 Then
        .AddCaptionCodeDescription("Department:", AccountApp.DepartmentPk, finBL.Departments)
      End If
      If finBL.SettingsUser.SummaryPagesShowManagerResolved AndAlso AccountApp.AccountManagerUserPk <> 0 Then
        .AddCaptionCodeDescription("Manager:", AccountApp.AccountManagerUserId, finBL.Users)
      End If
      If finBL.SettingsUser.SummaryPagesShowDealerResolved AndAlso AccountApp.DealerExternalPartyPk <> 0 Then
        With .AddCaptionCodeDescription("Dealer:", AccountApp.DealerExternalPartyPk, finBL.ExternalParties).Cells(1)
          If finBL.ExternalParties.ItemByPk(AccountApp.DealerExternalPartyPk).MasterExternalPartyPk <> 0 Then
            .Value &= String.Format(" ({0})", finBL.ExternalParties.ItemByPk(finBL.ExternalParties.ItemByPk(AccountApp.DealerExternalPartyPk).MasterExternalPartyPk).Name)
          End If
        End With
      End If
      If finBL.SettingsUser.SummaryPagesShowBrokerResolved AndAlso AccountApp.BrokerExternalPartyPk <> 0 Then
        With .AddCaptionCodeDescription("Broker:", AccountApp.BrokerExternalPartyPk, finBL.ExternalParties).Cells(1)
          If finBL.ExternalParties.ItemByPk(AccountApp.BrokerExternalPartyPk).MasterExternalPartyPk <> 0 Then
            .Value &= String.Format(" ({0})", finBL.ExternalParties.ItemByPk(finBL.ExternalParties.ItemByPk(AccountApp.BrokerExternalPartyPk).MasterExternalPartyPk).Name)
          End If
        End With
      End If
    End With

    ' Actions
    If includeActions AndAlso Not finBL.Database.IsReadOnly Then
      With SummaryTable.Actions
        .AddFormShow("LogAdd", "Log", "AccountAppLog", finBL.CurrentUser.Permissions.Allow("AccountApp.Logs.Add"), "AccountAppId=" & finBL.UrlEncode(AccountApp.AccountAppId)).ShowInWebInterfaces = True
        .AddFormShow("SendEmail", "Email", "EmailMessage", finBL.HtmlWidgetUtilities.HasPermissionToViewFormKey("EmailMessage", ""), "Type=Account Application&Id=" & finBL.UrlEncode(AccountApp.AccountAppId)).ShowInWebInterfaces = True
        .AddFormShow("SendSms", "SMS", "SMSMessage", finBL.Messaging.IsMessagingAvailable AndAlso finBL.HtmlWidgetUtilities.HasPermissionToViewFormKey("SMSMessage", ""), "Type=Account Application&Id=" & finBL.UrlEncode(AccountApp.AccountAppId)).ShowInWebInterfaces = True
      End With
    End If

    ' Applicants
    With SummaryTableApplicants
      .TableClass = iseSummaryTableClass.Information
      .Caption = "Applicants"
      .Columns.AddText()

      With .Rows
        For Each AccountAppApplicant In AccountApp.Applicants
          If AccountAppApplicant.ClientPk = 0 Then
            strTemp = "Applicant"
          Else
            strTemp = "Client"
          End If

          With .AddText("{{icon|" & strTemp & "}} " & If(Len(AccountAppApplicant.Name) = 0, "Unknown", AccountAppApplicant.Name))
            If AccountAppApplicant.ClientPk <> 0 Then
              .Cells(0).HyperlinkSetFormShow("Clients", AccountAppApplicant.ClientId)
            End If
          End With
        Next
      End With
    End With

    ' Create and return collection
    SummaryTables = finBL.CreateSummaryTables()
    SummaryTables.Add("Main", SummaryTable)
    SummaryTables.Add("Applicants", SummaryTableApplicants)
    Return SummaryTables

  End Function

  ''' <summary>
  '''  Quick Search Result Summary for an Account Archive (Version 1.0, Last updated 29/08/2013).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="quickSearchResult">
  '''  The Quick Search Result to summarise.
  ''' </param>
  ''' <param name="maxDisplayRows">
  '''  The Maximum number of Rows to Display in supplemental tables (e.g., Client Accounts) before a 'Show Hidden' link is displayed.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Quick Search form.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables (depending on the item type being summarised, additional tables may be included):
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function QuickSearch_ResultSummary_AccountArchive(callerScriptInfo As ISScriptExecutionInfo,
                                                                       quickSearchResult As finQuickSearchResult,
                                                                       maxDisplayRows As Integer,
                                                                       includeActions As Boolean,
                                                                       otherParameters As ISKeyValueList) As ISSummaryTables

    Dim AccountArchiveView As finAccountArchiveView
    Dim SummaryTable As ISSummaryTable
    Dim SummaryTables As ISSummaryTables

    ' Initialise
    AccountArchiveView = DirectCast(quickSearchResult.SourceObject, finAccountArchiveView)
    SummaryTable = finBL.CreateSummaryTable()

    ' Add Columns
    With SummaryTable
      .TableClass = iseSummaryTableClass.Information
      .Columns.AddText(14)
      .Columns.AddText()
    End With

    ' Details
    With SummaryTable.Rows
      ' Code and Description
      With .AddCaptionText("Account:", AccountArchiveView.AccountId)
        .Cells(1).HyperlinkSetApplicationShortcutUrl(quickSearchResult.ApplicationShortcutUrl)
      End With
      .AddCaptionText("Name:", AccountArchiveView.Name, iseSummaryTableCellClass.Highlight1)

      ' Account Type
      .AddCaptionCodeDescription("Type:", AccountArchiveView.AccountTypePk, finBL.AccountTypes)

      ' Other
      .AddCaptionText("Archive Type:", AccountArchiveView.ArchiveTypeText)
    End With

    ' Create and return collection
    SummaryTables = finBL.CreateSummaryTables()
    SummaryTables.Add("Main", SummaryTable)
    Return SummaryTables

  End Function

  ''' <summary>
  '''  Quick Search Result Summary for a Branch (Version 1.0, Last updated 29/08/2013).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="quickSearchResult">
  '''  The Quick Search Result to summarise.
  ''' </param>
  ''' <param name="maxDisplayRows">
  '''  The Maximum number of Rows to Display in supplemental tables (e.g., Client Accounts) before a 'Show Hidden' link is displayed.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Quick Search form.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables (depending on the item type being summarised, additional tables may be included):
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function QuickSearch_ResultSummary_Branch(callerScriptInfo As ISScriptExecutionInfo,
                                                               quickSearchResult As finQuickSearchResult,
                                                               maxDisplayRows As Integer,
                                                               includeActions As Boolean,
                                                               otherParameters As ISKeyValueList) As ISSummaryTables

    Dim Branch As finBranchRO
    Dim strTemp As String
    Dim SummaryTable As ISSummaryTable
    Dim SummaryTables As ISSummaryTables

    ' Initialise
    Branch = DirectCast(quickSearchResult.SourceObject, finBranchRO)
    SummaryTable = finBL.CreateSummaryTable()

    ' Add Columns
    With SummaryTable
      .TableClass = iseSummaryTableClass.Information
      .Columns.AddText(12)
      .Columns.AddText()
    End With

    ' Details
    With SummaryTable.Rows
      ' Code and Description
      With .AddCaptionText("Code:", Branch.BranchId)
        .Cells(1).HyperlinkSetApplicationShortcutUrl(quickSearchResult.ApplicationShortcutUrl)
      End With
      .AddCaptionText("Description:", Branch.Description, iseSummaryTableCellClass.Highlight1)

      ' Client
      strTemp = Branch.ClientId ' Cache since it is read from the database when accessed
      With .AddCaptionText("Client:", "{{icon|Client}} " & strTemp)
        .Cells(1).HyperlinkSetFormShow("Clients", strTemp)
      End With
    End With

    ' Create and return collection
    SummaryTables = finBL.CreateSummaryTables()
    SummaryTables.Add("Main", SummaryTable)
    Return SummaryTables

  End Function

  ''' <summary>
  '''  Quick Search Result Summary for a Client.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="quickSearchResult">
  '''  The Quick Search Result to summarise.
  ''' </param>
  ''' <param name="maxDisplayRows">
  '''  The Maximum number of Rows to Display in supplemental tables (e.g., Client Accounts) before a 'Show Hidden' link is displayed.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Quick Search form.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables (depending on the item type being summarised, additional tables may be included):
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''    <item><code>Accounts</code><description>Client Accounts (will only exist if the Client has any Accounts).</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function QuickSearch_ResultSummary_Client(callerScriptInfo As ISScriptExecutionInfo,
                                                               quickSearchResult As finQuickSearchResult,
                                                               maxDisplayRows As Integer,
                                                               includeActions As Boolean,
                                                               otherParameters As ISKeyValueList) As ISSummaryTables

    ' #################################################################
    ' QuickSearch_ResultSummary_Client
    '
    ' Version: 1.14 (20/08/2024)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.09  11/08/2021  ISS
    '    1.10  04/01/2023  ISS      J030243
    '    1.11  26/09/2023  ISS      J032101   Refactored AddOn checks
    '    1.12  28/09/2023  ISS      J032114   Email/SMS Permissions finCC
    '    1.13  12/12/2023  ISS      J032613   "Add New Account" action (finCC)
    '          16/04/2024  ISS      J031917   SMS and Email now use "External Party" where appropriate
    '    1.14  20/08/2024  ISS      J034115   Added Manager
    ' #################################################################

    Dim Client As finClient
    Dim ClientAccount As finClientAccount
    Dim ClientAccounts As List(Of finClientAccount)
    Dim ClientContactAddress As finClientContactAddress
    Dim ClientContactMethod As finClientContactMethod
    Dim ClientContactMethodPhone As finClientContactMethod
    Dim ClientContactMethodPhoneHome As finClientContactMethod
    Dim ClientContactMethodMobile As finClientContactMethod
    Dim DateAsAt As Date
    Dim ExternalParty As finExternalPartyRO
    Dim ExternalPartyId As String
    Dim i As Integer
    Dim Popup As Boolean
    Dim QuickSearchContext As isefinQuickSearchContext
    Dim strTemp As String
    Dim SummaryTable As ISSummaryTable
    Dim SummaryTableAccounts As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As finWarnings

    ' Initialise
    SummaryTable = finBL.CreateSummaryTable()
    SummaryTableAccounts = finBL.CreateSummaryTable()

    ' Get Date As At
    DateAsAt = finBL.TimeZoneFunctions.GetCurrentDatabaseDate()

    ' Determine whether this Summary is being produced by a "Popup" form
    If callerScriptInfo IsNot Nothing AndAlso InStr(callerScriptInfo.FormKey, "Popup", CompareMethod.Text) <> 0 Then
      Popup = True
    End If

    ' Get Other Parameters
    If otherParameters IsNot Nothing Then
      QuickSearchContext = DirectCast(otherParameters.GetEnum("context", GetType(isefinQuickSearchContext), isefinQuickSearchContext.Unspecified), isefinQuickSearchContext)
    End If

    ' Cache Client
    Client = DirectCast(quickSearchResult.SourceObject, finClient)

    ' Special Type
    Select Case Client.SpecialType
      Case isefinClientSpecialType.ExternalParty
        If finBL.Settings.AddOns.ExternalParty Then
          ExternalParty = Client.ParentExternalPartyRO

          If ExternalParty IsNot Nothing Then
            ExternalPartyId = ExternalParty.ExternalPartyId
          End If
        End If
    End Select

    ' Add Columns
    With SummaryTable
      .TableClass = iseSummaryTableClass.Information
      .Columns.AddText(12)
      .Columns.AddText(10)
      .Columns.AddText() ' Extra column to display Warnings after code
    End With

    ' Details
    With SummaryTable.Rows
      ' Code and Name
      With .AddCaptionText("Code:", Client.ClientId)
        With .Cells(1)
          If Not quickSearchResult.IsFilteredOut Then
            .HyperlinkSetApplicationShortcutUrl(quickSearchResult.ApplicationShortcutUrl)
            .NoWrap = True
          End If
        End With

        ' Warnings (show after code for compactness)
        If quickSearchResult.IsFilteredOut Then
          .Cells.AddText("")
        Else
          Warnings = Client.GetWarnings()
          If Warnings.Count = 0 Then
            .Cells.AddText("")
          Else
            If Warnings.Count = 1 Then
              strTemp = "!!**1** warning!!"
            Else
              strTemp = String.Format("!!**{0}** warnings!!", Warnings.Count)
            End If
            With .Cells.AddWiki("{{icon|Warning}} " & strTemp)
              If Not Popup Then
                .HyperlinkSetHtmlShowFunction("ClientWarningsSummary", String.Format("Warnings for Client {0}, '{1}'", Client.ClientId, Client.Name), "ClientId=" & Client.ClientId)
              End If
            End With
          End If
        End If
      End With
      .AddCaptionText("Name:", Client.Name, iseSummaryTableCellClass.Highlight1)

      ' Branch etc
      If finBL.SettingsUser.SummaryPagesShowBranchResolved AndAlso Client.BranchPk <> 0 Then
        With .AddCaptionCodeDescription("Branch:", Client.BranchPk, finBL.Branches).Cells(1)
          If finBL.Settings.AddOns.Entity Then
            .Value &= String.Format(" ({0})", Client.Entity.Name)
          End If
        End With
      End If
      If finBL.SettingsUser.SummaryPagesShowManagerResolved AndAlso Client.ClientManagerUserPk <> 0 Then
        .AddCaptionCodeDescription("Manager:", Client.ClientManagerUserId, finBL.Users)
      End If

      ' Individual/ Sole Trader
      If Client.IsIndividualOrSoleTrader Then
        If Client.Gender <> isefinGender.Unknown Then .AddCaptionText("Gender:", Client.GenderText)
        strTemp = ""
        If Client.ClientType.IsIndividualDeceased Then
          If Client.DateOfBirth = Nothing OrElse Client.DateOfDeath = Nothing OrElse Client.DateOfBirth > Client.DateOfDeath Then
            strTemp = "Deceased"
          Else
            strTemp = String.Format("Deceased ({0} at death)", finBL.Runtime.DateUtilities.AgeAsText(Client.DateOfBirth, Client.DateOfDeath))
          End If
        Else
          strTemp = finBL.Runtime.DateUtilities.AgeAsText(Client.DateOfBirth)
        End If
        If Client.DateOfBirth <> Nothing Then .AddCaptionDate("DOB:", Client.DateOfBirth, strTemp)
        If Client.ClientType.IsIndividualDeceased AndAlso Client.DateOfDeath <> Nothing Then
          .AddCaptionDate("DOD:", Client.DateOfDeath)
        End If
      End If

      ' Organisation
      If Client.IsOrganisation Then
        If Client.LegalNameResolved <> Client.Name Then .AddCaptionText("Legal:", Client.LegalNameResolved)
      End If

      If Not quickSearchResult.IsFilteredOut Then
        ' Mobile, Home and Phone Number
        ClientContactMethodMobile = Client.ContactMethods.GetCurrentMobile()
        ClientContactMethodPhoneHome = Client.ContactMethods.GetCurrentPhoneHome()
        ClientContactMethodPhone = Client.ContactMethods.GetCurrentPhone()

        If ClientContactMethodMobile IsNot Nothing AndAlso ClientContactMethodMobile.HasValues() Then
          .AddCaptionTextPhoneNumber("Mobile:", ClientContactMethodMobile.Value, , Client.ClientId, CStr(ClientContactMethodMobile.Pk),,,, ExternalPartyId)
        End If
        If ClientContactMethodPhoneHome IsNot Nothing AndAlso ClientContactMethodPhoneHome.HasValues() Then
          If ClientContactMethodPhoneHome Is ClientContactMethodMobile Then
            ' Home phone and mobile are on-in-the-same so omit
          Else
            .AddCaptionTextPhoneNumber("Home:", ClientContactMethodPhoneHome.Value, , Client.ClientId, CStr(ClientContactMethodPhoneHome.Pk),,,, ExternalPartyId)
          End If
        End If
        If ClientContactMethodPhone IsNot Nothing AndAlso ClientContactMethodPhone.HasValues() Then
          If ClientContactMethodPhone Is ClientContactMethodMobile OrElse
             ClientContactMethodPhone Is ClientContactMethodPhoneHome Then
            ' Phone and mobile or home are on-in-the-same so omit
          Else
            .AddCaptionTextPhoneNumber("Phone:", ClientContactMethodPhone.Value, , Client.ClientId, CStr(ClientContactMethodPhone.Pk),,,, ExternalPartyId)
          End If
        End If

        ' Email
        ClientContactMethod = Client.ContactMethods.GetCurrentEmail()
        If ClientContactMethod IsNot Nothing Then
          .AddCaptionTextEmailAddress("Email:", ClientContactMethod.Value, , Client.ClientId, CStr(ClientContactMethod.Pk),,,, ExternalPartyId)
        End If

        ' Address
        ClientContactAddress = Client.ContactAddresses.GetCurrentPhysicalAddressContactAddress()
        If ClientContactAddress IsNot Nothing Then
          .AddCaptionAddressDetailsPhysical("Address:", ClientContactAddress.ToAddressDetails())
        End If
      End If
    End With

    ' Actions
    If includeActions AndAlso Not quickSearchResult.IsFilteredOut AndAlso Not finBL.Database.IsReadOnly Then
      With SummaryTable.Actions
        .AddFormShow("LogAdd", "Log", "ClientLog", finBL.CurrentUser.Permissions.Allow("Client.Logs.Add"), "ClientId=" & finBL.UrlEncode(Client.ClientId)).ShowInWebInterfaces = True
        If Len(ExternalPartyId) = 0 Then
          .AddFormShow("SendEmail", "Email", "EmailMessage", finBL.HtmlWidgetUtilities.HasPermissionToViewFormKey("EmailMessage", ""), "Type=Client&Id=" & finBL.UrlEncode(Client.ClientId)).ShowInWebInterfaces = True
        Else
          .AddFormShow("SendEmail", "Email", "EmailMessage", finBL.HtmlWidgetUtilities.HasPermissionToViewFormKey("EmailMessage", ""), "Type=External Party&Id=" & finBL.UrlEncode(ExternalPartyId)).ShowInWebInterfaces = True
        End If
        If Len(ExternalPartyId) = 0 Then
          .AddFormShow("SendSms", "SMS", "SMSMessage", finBL.Messaging.IsMessagingAvailable AndAlso finBL.HtmlWidgetUtilities.HasPermissionToViewFormKey("SMSMessage", ""), "Type=Client&Id=" & finBL.UrlEncode(Client.ClientId) & "&externalPartyId=" & finBL.UrlEncode(ExternalPartyId)).ShowInWebInterfaces = True
        Else
          .AddFormShow("SendSms", "SMS", "SMSMessage", finBL.Messaging.IsMessagingAvailable AndAlso finBL.HtmlWidgetUtilities.HasPermissionToViewFormKey("SMSMessage", ""), "Type=External Party&Id=" & finBL.UrlEncode(ExternalPartyId)).ShowInWebInterfaces = True
        End If
        If finBL.IsRunningFromWeb Then
          .AddFormShow("AccountAdd", "Add New Account", "AccountNew", finBL.CurrentUser.Permissions.Allow("Account.Add") AndAlso Not Client.IsIndividualDeceased, "clientsToAdd=" & finBL.UrlEncode(Client.ClientId)).ShowInWebInterfaces = True
        End If
      End With
    End If

    ' Warnings
    If quickSearchResult.IsFilteredOut Then
      SummaryTable.TextAfter = "{{warning|You do not have permission to view this Client's full details.}}"
    End If

    ' Accounts (list is reverse order so most appropriate at the top)
    If Not quickSearchResult.IsFilteredOut Then
      ClientAccounts = Client.Accounts.GetClientAccounts_OrderReverse()

      With SummaryTableAccounts
        .TableClass = iseSummaryTableClass.TabularData
        .Caption = "Accounts"
        .AutoStripe = True

        ' Columns
        With .Columns
          .AddCode("Type", finBL.AccountTypes.GetLongestCode()).HideRule = iseSummaryTableColumnHideRule.DocumentWidthLessThan320px
          .AddCode("Account", finBL.AccountFunctions.GetLongestCode())
          .AddText("Description")
          .AddCode("Role", 5).HideRule = iseSummaryTableColumnHideRule.DocumentWidthLessThan320px
          .AddDate("Opened").HideRule = iseSummaryTableColumnHideRule.DocumentWidthLessThan500px
          .AddDate("Matures").HideRule = iseSummaryTableColumnHideRule.DocumentWidthLessThan640px
          .AddText("Status").HideRule = iseSummaryTableColumnHideRule.DocumentWidthLessThan240px
          .AddCurrency("Balance").HideRule = iseSummaryTableColumnHideRule.DocumentWidthLessThan500px
          .AddCurrency("Overdue").HideRule = iseSummaryTableColumnHideRule.DocumentWidthLessThan640px
        End With

        For i = 0 To ClientAccounts.Count - 1
          ClientAccount = ClientAccounts(i)

          If ClientAccount.AccountHidden Then
            ' Do not include
          Else
            With .Rows.Add()
              Select Case ClientAccount.Source
                Case isefinClientAccountSource.Account
                  ' Account
                  .Cells.AddText(ClientAccount.AccountTypeId)
                  With .Cells.AddText(ClientAccount.AccountId)
                    .HyperlinkSetFormShow("Accounts", ClientAccount.AccountId)
                  End With
                  .Cells.AddText(ClientAccount.Description)
                  .Cells.AddText(ClientAccount.AccountRole.DescriptionShortResolved)
                  .Cells.AddDate(ClientAccount.DateOpened)
                  .Cells.AddDate(ClientAccount.DateMaturity)
                  .Cells.AddText(ClientAccount.StatusText)
                  .Cells.AddCurrency(ClientAccount.Balance)
                  With .Cells.AddCurrency(ClientAccount.BalanceOverdue,, True)
                    If ClientAccount.BalanceOverdue > 0 Then
                      .ForegroundColour = "red"
                    End If
                  End With

                  ' Hide based on Status
                  If Client.Accounts.CountVisible() <= 5 Then
                    ' Always show
                    .Visible = True
                  Else
                    Select Case ClientAccount.Status
                      Case isefinAccountStatus.Closed
                        ' Don't hide if closed within past 90 days
                        .Visible = (DateDiff(DateInterval.Day, ClientAccount.DateClosed, DateAsAt) <= 90)
                      Case isefinAccountStatus.ClosedPending, isefinAccountStatus.Quote, isefinAccountStatus.Open
                        .Visible = True
                      Case isefinAccountStatus.Declined, isefinAccountStatus.Unwanted
                        ' Don't hide if opening date within past 90 days
                        .Visible = (DateDiff(DateInterval.Day, ClientAccount.DateOpened, DateAsAt) <= 90)
                      Case Else
                        ' Hide
                        .Visible = False
                    End Select
                  End If

                Case isefinClientAccountSource.Application
                  ' Application
                  .Cells.AddText(ClientAccount.AccountTypeId)
                  With .Cells.AddText(ClientAccount.AccountId)
                    .HyperlinkSetFormShow("AccountApps", ClientAccount.AccountId)
                  End With
                  .Cells.AddText(ClientAccount.Description)
                  If ClientAccount.AccountRole Is Nothing Then
                    .Cells.AddText("")
                  Else
                    .Cells.AddText(ClientAccount.AccountRole.DescriptionShortResolved)
                  End If
                  .Cells.AddText("") ' Opened
                  .Cells.AddText("") ' Matures
                  .Cells.AddText(ClientAccount.StatusText)
                  .Cells.AddText("") ' Balance
                  .Cells.AddText("") ' Overdue

                  ' Hide
                  If Client.Accounts.CountVisible() <= 5 Then
                    ' Always show
                    .Visible = True
                  Else
                    Select Case ClientAccount.AccountAppStatus
                      Case isefinAccountAppStatus.Incomplete, isefinAccountAppStatus.Reviewing, isefinAccountAppStatus.Complete
                        .Visible = True
                        .BackgroundColour = "#ffffe0"
                      Case Else
                        .Visible = False
                    End Select
                  End If

                Case isefinClientAccountSource.Archive
                  ' Archive
                  .Cells.AddText(ClientAccount.AccountTypeId)
                  With .Cells.AddText(ClientAccount.AccountId)
                    .HyperlinkSetFormShow("AccountArchiveView", CStr(ClientAccount.AccountPk))
                  End With
                  .Cells.AddText(ClientAccount.Description)
                  If ClientAccount.AccountRole Is Nothing Then
                    .Cells.AddText("")
                  Else
                    .Cells.AddText(ClientAccount.AccountRole.DescriptionShortResolved)
                  End If
                  .Cells.AddDate(ClientAccount.DateOpened)
                  .Cells.AddDate(ClientAccount.DateMaturity)
                  .Cells.AddText(ClientAccount.StatusText & " (Archived)")
                  .Cells.AddText("") ' Balance
                  .Cells.AddText("") ' Overdue

                  ' Hide?
                  If Client.Accounts.CountVisible() <= 5 Then
                    ' Always show
                    .Visible = True
                  Else
                    .Visible = False
                  End If
              End Select

              ' Force Visibility?
              Select Case QuickSearchContext
                Case isefinQuickSearchContext.AccountTransactionEntry
                  ' Open Accounts only
                  .Visible = ClientAccount.Source = isefinClientAccountSource.Account AndAlso ClientAccount.Status = isefinAccountStatus.Open
              End Select
            End With
          End If
        Next
      End With
    End If

    ' Create and return collection
    SummaryTables = finBL.CreateSummaryTables()
    SummaryTables.Add("Main", SummaryTable)
    If SummaryTableAccounts.Rows.Count > 1 Then SummaryTables.Add("Accounts", SummaryTableAccounts)
    Return SummaryTables

  End Function

  ''' <summary>
  '''  Quick Search Result Summary for an External Party (Version 1.04, Last updated 11/03/2021).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="quickSearchResult">
  '''  The Quick Search Result to summarise.
  ''' </param>
  ''' <param name="maxDisplayRows">
  '''  The Maximum number of Rows to Display in supplemental tables (e.g., Client Accounts) before a 'Show Hidden' link is displayed.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Quick Search form.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables (depending on the item type being summarised, additional tables may be included):
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function QuickSearch_ResultSummary_ExternalParty(callerScriptInfo As ISScriptExecutionInfo,
                                                                      quickSearchResult As finQuickSearchResult,
                                                                      maxDisplayRows As Integer,
                                                                      includeActions As Boolean,
                                                                      otherParameters As ISKeyValueList) As ISSummaryTables

    Dim Client As finClient
    Dim ClientAccount As finClientAccount
    Dim DateAsAt As Date
    Dim ExternalParty As finExternalPartyRO
    Dim i As Integer
    Dim strTemp As String
    Dim SummaryTable As ISSummaryTable
    Dim SummaryTableAccounts As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As finWarnings

    ' Initialise
    SummaryTable = finBL.CreateSummaryTable()
    SummaryTableAccounts = finBL.CreateSummaryTable()

    ' Get Date As At
    DateAsAt = finBL.TimeZoneFunctions.GetCurrentDatabaseDate()

    ' Cache External Party and Client
    ExternalParty = DirectCast(quickSearchResult.SourceObject, finExternalPartyRO)
    ExternalParty.GetClient(Client)

    ' Add Columns
    With SummaryTable
      .TableClass = iseSummaryTableClass.Information
      .Columns.AddText(12)
      .Columns.AddText()
      .Columns.AddText() ' Extra column to display Warnings after code
    End With

    ' Details
    With SummaryTable.Rows
      ' Code and Description
      With .AddCaptionText("Code:", ExternalParty.ExternalPartyId)
        With .Cells(1)
          If finBL.Settings.AddOns.ExternalParty Then
            .HyperlinkSetApplicationShortcutUrl(quickSearchResult.ApplicationShortcutUrl)
          End If
          .NoWrap = True
        End With

        ' Warnings (show after code for compactness)
        Warnings = Client.GetWarnings()
        If Warnings.Count <> 0 Then
          If Warnings.Count = 1 Then
            strTemp = "!!**1** warning!!"
          Else
            strTemp = String.Format("!!**{0}** warnings!!", Warnings.Count)
          End If
          With .Cells.AddWiki("{{icon|Warning}} " & strTemp)
            .HyperlinkSetHtmlShowFunction("ClientWarningsSummary", String.Format("Warnings for Client {0}, '{1}'", Client.ClientId, Client.Name), "ClientId=" & Client.ClientId)
          End With
        End If
      End With
      .AddCaptionText("Description:", ExternalParty.Description, iseSummaryTableCellClass.Highlight1)

      ' Type and Client
      .AddCaptionText("Type:", ExternalParty.ExternalPartyTypeText)
      strTemp = ExternalParty.ClientId ' Cache since it is read from the database when accessed
      With .AddCaptionText("Client:", "{{icon|Client}} " & strTemp)
        .Cells(1).HyperlinkSetFormShow("Clients", strTemp)
      End With
    End With

    ' Accounts
    With SummaryTableAccounts
      .TableClass = iseSummaryTableClass.TabularData
      .Caption = "Accounts"

      ' Columns
      With .Columns
        .AddCode("Code", finBL.AccountFunctions.GetLongestCode())
        .AddText("Description")
        .AddCode("Type", 5).HideRule = iseSummaryTableColumnHideRule.DocumentWidthLessThan320px ' When rendered as HTML, don't display if screen < 320px
        .AddText("Status").HideRule = iseSummaryTableColumnHideRule.DocumentWidthLessThan240px ' When rendered as HTML, don't display if screen < 240px
      End With

      For i = Client.Accounts.Count - 1 To 0 Step -1
        ClientAccount = Client.Accounts(i)

        If ClientAccount.AccountHidden Then
          ' Do not include
        Else
          With .Rows.Add()
            Select Case ClientAccount.Source
              Case isefinClientAccountSource.Account
                ' Account
                With .Cells.AddText(ClientAccount.AccountId)
                  .HyperlinkSetFormShow("Accounts", ClientAccount.AccountId)
                End With
                .Cells.AddText(ClientAccount.Description)
                .Cells.AddText(ClientAccount.AccountTypeId)
                .Cells.AddText(ClientAccount.StatusText)

                ' Hide based on Status
                If Client.Accounts.CountVisible() <= 5 Then
                  ' Always show
                  .Visible = True
                Else
                  Select Case ClientAccount.Status
                    Case isefinAccountStatus.Closed
                      ' Don't hide if closed within past 90 days
                      .Visible = (DateDiff(DateInterval.Day, ClientAccount.DateClosed, DateAsAt) <= 90)
                    Case isefinAccountStatus.ClosedPending, isefinAccountStatus.Quote, isefinAccountStatus.Open
                    Case isefinAccountStatus.Declined, isefinAccountStatus.Unwanted
                      ' Don't hide if opening date within past 90 days
                      .Visible = (DateDiff(DateInterval.Day, ClientAccount.DateOpened, DateAsAt) <= 90)
                    Case Else
                      ' Hide
                      .Visible = False
                  End Select
                End If

              Case isefinClientAccountSource.Application
                ' Application
                With .Cells.AddText(ClientAccount.AccountId)
                  .HyperlinkSetFormShow("Accounts", ClientAccount.AccountId)
                End With
                .Cells.AddText(ClientAccount.Description)
                .Cells.AddText(ClientAccount.AccountTypeId)
                .Cells.AddText(ClientAccount.StatusText)

                ' Hide
                If Client.Accounts.CountVisible() <= 5 Then
                  ' Always show
                  .Visible = True
                Else
                  Select Case ClientAccount.AccountAppStatus
                    Case isefinAccountAppStatus.Incomplete, isefinAccountAppStatus.Reviewing, isefinAccountAppStatus.Complete
                      .Visible = True
                      .BackgroundColour = "#ffffe0"
                    Case Else
                      .Visible = False
                  End Select
                End If

              Case isefinClientAccountSource.Archive
                ' Archive
                With .Cells.AddText(ClientAccount.AccountId)
                  .HyperlinkSetFormShow("AccountArchiveView", CStr(ClientAccount.AccountPk))
                End With
                .Cells.AddText(ClientAccount.Description)
                .Cells.AddText(ClientAccount.AccountTypeId)
                .Cells.AddText(ClientAccount.StatusText & " (Archived)")

                ' Hide
                If Client.Accounts.CountVisible() <= 5 Then
                  ' Always show
                  .Visible = True
                Else
                  .Visible = False
                End If
            End Select
          End With
        End If
      Next
    End With

    ' Create and return collection
    SummaryTables = finBL.CreateSummaryTables()
    SummaryTables.Add("Main", SummaryTable)
    If Client.Accounts.Count <> 0 Then SummaryTables.Add("Accounts", SummaryTableAccounts)
    Return SummaryTables

  End Function

  ''' <summary>
  '''  Quick Search Result Summary for a Generic result.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="quickSearchResult">
  '''  The Quick Search Result to summarise.
  ''' </param>
  ''' <param name="maxDisplayRows">
  '''  The Maximum number of Rows to Display in supplemental tables (e.g., Client Accounts) before a 'Show Hidden' link is displayed.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Quick Search form.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables (depending on the item type being summarised, additional tables may be included):
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function QuickSearch_ResultSummary_Generic(callerScriptInfo As ISScriptExecutionInfo,
                                                                quickSearchResult As finQuickSearchResult,
                                                                maxDisplayRows As Integer,
                                                                includeActions As Boolean,
                                                                otherParameters As ISKeyValueList) As ISSummaryTables

    ' #################################################################
    ' QuickSearch_ResultSummary_Generic
    '
    ' Version: 1.04 (28/07/2022)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.04  28/07/2022  ISS      J029258
    ' #################################################################

    Dim SummaryTable As ISSummaryTable
    Dim SummaryTables As ISSummaryTables

    ' Initialise
    SummaryTable = finBL.CreateSummaryTable()

    ' Add Columns
    With SummaryTable
      .TableClass = iseSummaryTableClass.Information
      .Columns.AddText(12)
      .Columns.AddText()
    End With

    ' Details
    With SummaryTable.Rows
      ' Type
      Select Case quickSearchResult.SourceObject.GetType()
        Case Else
          If TypeOf quickSearchResult.SourceObject Is I_ISObjectName Then
            .AddCaptionText("Type:", DirectCast(quickSearchResult.SourceObject, I_ISObjectName).GetObjectName(False))
          End If
      End Select

      ' Code and Description
      With .AddCaptionText("Code:", quickSearchResult.Id)
        .Cells(1).HyperlinkSetApplicationShortcutUrl(quickSearchResult.ApplicationShortcutUrl)
      End With
      .AddCaptionText("Description:", quickSearchResult.Name, iseSummaryTableCellClass.Highlight1)

      ' Active (only if inactive since we don't know (without checking) whether this item supports an Active flag
      If Not quickSearchResult.Active Then
        .AddCaptionTick("Active:", quickSearchResult.Active, True)
      End If

      ' Type-specific
      If quickSearchResult.SourceObject IsNot Nothing Then
        Select Case quickSearchResult.SourceObject.GetType()
          Case GetType(finResourceRO)
            ' Resource
            Dim Resource As finResourceRO = DirectCast(quickSearchResult.SourceObject, finResourceRO)

            .AddCaptionText("Resource Type:", Resource.ResourceTypeText)

          Case GetType(finScriptRO)
            ' Script
            Dim Script As finScriptRO = DirectCast(quickSearchResult.SourceObject, finScriptRO)

            .AddCaptionText("Script Type:", Script.ScriptTypeText)
        End Select
      End If
    End With

    ' Create and return collection
    SummaryTables = finBL.CreateSummaryTables()
    SummaryTables.Add("Main", SummaryTable)
    Return SummaryTables

  End Function

  ''' <summary>
  '''  Quick Search Result Summary for a Menu Item or finPOWER Connect Cloud View Item (Version 1.03, Last updated 8/12/2020).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="quickSearchResult">
  '''  The Quick Search Result to summarise.
  ''' </param>
  ''' <param name="maxDisplayRows">
  '''  The Maximum number of Rows to Display in supplemental tables (e.g., Client Accounts) before a 'Show Hidden' link is displayed.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Quick Search form.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables (depending on the item type being summarised, additional tables may be included):
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function QuickSearch_ResultSummary_MenuItem(callerScriptInfo As ISScriptExecutionInfo,
                                                                 quickSearchResult As finQuickSearchResult,
                                                                 maxDisplayRows As Integer,
                                                                 includeActions As Boolean,
                                                                 otherParameters As ISKeyValueList) As ISSummaryTables

    Dim CustomMenuItem As ISCustomMenuItem
    Dim ParentCustomMenuItem As ISCustomMenuItem
    Dim strTemp As String
    Dim SummaryTable As ISSummaryTable
    Dim SummaryTables As ISSummaryTables

    ' Initialise
    CustomMenuItem = DirectCast(quickSearchResult.SourceObject, ISCustomMenuItem)
    SummaryTable = finBL.CreateSummaryTable()

    ' Add Columns
    With SummaryTable
      .TableClass = iseSummaryTableClass.Information
      .Columns.AddText(12)
      .Columns.AddText()
    End With

    ' Details
    With SummaryTable.Rows
      If finBL.IsRunningFromWeb Then
        ' finPOWER Connect Cloud
        With .AddCaptionText("Item:", quickSearchResult.Name, iseSummaryTableCellClass.Highlight1)
          If Len(CustomMenuItem.Icon) <> 0 Then
            .Cells(1).Value = "{{icon|" & CustomMenuItem.Icon & "}} " & .Cells(1).Value
          End If
          .Cells(1).HyperlinkSetApplicationShortcutUrl(quickSearchResult.ApplicationShortcutUrl)
        End With

        Select Case UCase(CustomMenuItem.Action)
          Case "ADMINISTRATION", "PROCESSES", "REPORTING"
            .AddCaptionWiki("Location:", "**" & CustomMenuItem.Action & "** view")

          Case Else
            .AddCaptionWiki("Location:", "**" & CustomMenuItem.Action & "** menu")
        End Select
      Else
        ' finPOWER Connect
        With .AddCaptionText("Menu:", quickSearchResult.Name, iseSummaryTableCellClass.Highlight1)
          .Cells(1).HyperlinkSetApplicationShortcutUrl(quickSearchResult.ApplicationShortcutUrl)
        End With

        strTemp = "**" & CustomMenuItem.Caption & "**"
        ParentCustomMenuItem = CustomMenuItem.ParentMenuItem
        Do While ParentCustomMenuItem IsNot Nothing
          strTemp = ParentCustomMenuItem.Caption & ", " & strTemp
          ParentCustomMenuItem = ParentCustomMenuItem.ParentMenuItem
        Loop
        .AddCaptionWiki("Location:", strTemp)
      End If
    End With

    ' Create and return collection
    SummaryTables = finBL.CreateSummaryTables()
    SummaryTables.Add("Main", SummaryTable)
    Return SummaryTables

  End Function

  ''' <summary>
  '''  Quick Search Result Summary for a Report (Version 1.0, Last updated 29/08/2013).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="quickSearchResult">
  '''  The Quick Search Result to summarise.
  ''' </param>
  ''' <param name="maxDisplayRows">
  '''  The Maximum number of Rows to Display in supplemental tables (e.g., Client Accounts) before a 'Show Hidden' link is displayed.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Quick Search form.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables (depending on the item type being summarised, additional tables may be included):
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function QuickSearch_ResultSummary_Report(callerScriptInfo As ISScriptExecutionInfo,
                                                               quickSearchResult As finQuickSearchResult,
                                                               maxDisplayRows As Integer,
                                                               includeActions As Boolean,
                                                               otherParameters As ISKeyValueList) As ISSummaryTables

    Dim CustomMenuItem As ISCustomMenuItem
    Dim SummaryTable As ISSummaryTable
    Dim SummaryTables As ISSummaryTables

    ' Initialise
    CustomMenuItem = DirectCast(quickSearchResult.SourceObject, ISCustomMenuItem)
    SummaryTable = finBL.CreateSummaryTable()

    ' Add Columns
    With SummaryTable
      .TableClass = iseSummaryTableClass.Information
      .Columns.AddText(12)
      .Columns.AddText()
    End With

    ' Details
    With SummaryTable.Rows
      ' Description
      With .AddCaptionText("Report:", quickSearchResult.Name, iseSummaryTableCellClass.Highlight1)
        .Cells(1).HyperlinkSetApplicationShortcutUrl(quickSearchResult.ApplicationShortcutUrl)
      End With
    End With

    ' Create and return collection
    SummaryTables = finBL.CreateSummaryTables()
    SummaryTables.Add("Main", SummaryTable)
    Return SummaryTables

  End Function

  ''' <summary>
  '''  Quick Search Result Summary for a Security Statement.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="quickSearchResult">
  '''  The Quick Search Result to summarise.
  ''' </param>
  ''' <param name="maxDisplayRows">
  '''  The Maximum number of Rows to Display in supplemental tables (e.g., Client Accounts) before a 'Show Hidden' link is displayed.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Quick Search form.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables (depending on the item type being summarised, additional tables may be included):
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''    <item><code>SecurityItems</code><description>Security Item details.</description></item>
  '''    <item><code>Accounts</code><description>Security Statement Accounts (will only exist if the Security Statement has Accounts).</description></item>
  '''    <item><code>Clients</code><description>Security Statement Clients (will only exist if the Security Statement has Clients).</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function QuickSearch_ResultSummary_SecurityStmt(callerScriptInfo As ISScriptExecutionInfo,
                                                                     quickSearchResult As finQuickSearchResult,
                                                                     maxDisplayRows As Integer,
                                                                     includeActions As Boolean,
                                                                     otherParameters As ISKeyValueList) As ISSummaryTables

    ' #################################################################
    ' QuickSearch_ResultSummary_SecurityStmt
    '
    ' Version: 1.02 (20/08/2024)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.01  22/12/2015  ISS
    '    1.02  20/08/2024  ISS      J034115   Added Branch and Manager
    ' #################################################################

    Dim Popup As Boolean
    Dim SecurityStmt As finSecurityStmt
    Dim SecurityStmtAccount As finSecurityStmtAccount
    Dim SecurityStmtClient As finSecurityStmtClient
    Dim SecurityStmtItem As finSecurityStmtItemBase
    Dim strTemp As String
    Dim SummaryTable As ISSummaryTable
    Dim SummaryTableAccounts As ISSummaryTable
    Dim SummaryTableClients As ISSummaryTable
    Dim SummaryTableSecurityItems As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As finWarnings

    ' Initialise
    SecurityStmt = DirectCast(quickSearchResult.SourceObject, finSecurityStmt)
    SummaryTable = finBL.CreateSummaryTable()
    SummaryTableAccounts = finBL.CreateSummaryTable()
    SummaryTableClients = finBL.CreateSummaryTable()
    SummaryTableSecurityItems = finBL.CreateSummaryTable()

    ' Determine whether this Summary is being produced by a "Popup" form
    If callerScriptInfo IsNot Nothing AndAlso InStr(callerScriptInfo.FormKey, "Popup", CompareMethod.Text) <> 0 Then
      Popup = True
    End If

    ' Add Columns
    With SummaryTable
      .TableClass = iseSummaryTableClass.Information
      .Columns.AddText(12)
      .Columns.AddText(10)
      .Columns.AddText() ' Extra column to display Warnings after code
    End With

    ' Details
    With SummaryTable.Rows
      ' Code and Description
      With .AddCaptionText("Code:", SecurityStmt.SecurityStmtId)
        With .Cells(1)
          .HyperlinkSetApplicationShortcutUrl(quickSearchResult.ApplicationShortcutUrl)
          .NoWrap = True
        End With

        ' Warnings (show after code for compactness)
        Warnings = SecurityStmt.GetWarnings()
        If Warnings.Count <> 0 Then
          If Warnings.Count = 1 Then
            strTemp = "!!**1** warning!!"
          Else
            strTemp = String.Format("!!**{0}** warnings!!", Warnings.Count)
          End If
          With .Cells.AddWiki("{{icon|Warning}} " & strTemp)
            If Not Popup Then
              .HyperlinkSetHtmlShowFunction("SecurityStmtWarningsSummary", String.Format("Warnings for Security Statement {0}, '{1}'", SecurityStmt.SecurityStmtId, SecurityStmt.Description), "SecurityStmtId=" & SecurityStmt.SecurityStmtId)
            End If
          End With
        End If
      End With
      .AddCaptionText("Description:", SecurityStmt.Description, iseSummaryTableCellClass.Highlight1)

      ' Branch etc
      If finBL.SettingsUser.SummaryPagesShowBranchResolved AndAlso SecurityStmt.BranchPk <> 0 Then
        With .AddCaptionCodeDescription("Branch:", SecurityStmt.BranchPk, finBL.Branches).Cells(1)
          If finBL.Settings.AddOns.Entity Then
            .Value &= String.Format(" ({0})", SecurityStmt.Entity.Name)
          End If
        End With
      End If
      If finBL.SettingsUser.SummaryPagesShowManagerResolved AndAlso SecurityStmt.ManagerUserPk <> 0 Then
        .AddCaptionCodeDescription("Manager:", SecurityStmt.ManagerUserId, finBL.Users)
      End If
    End With

    ' Security Items
    With SummaryTableSecurityItems
      .TableClass = iseSummaryTableClass.TabularData
      .Caption = "Security Items"
      .AutoStripe = True
      .Columns.AddText()

      With .Rows
        For Each SecurityStmtItem In SecurityStmt.SecurityItems
          If Len(SecurityStmtItem.SecurityType.Icon) = 0 Then
            strTemp = "SecurityStatement"
          Else
            strTemp = "SecurityType_" & SecurityStmtItem.SecurityType.Icon
          End If
          With .AddText("{{icon|" & strTemp & "|" & SecurityStmtItem.SecurityType.DescriptionShortResolved & "}} " & SecurityStmtItem.Description)
            ' Hide Row if Defunct
            'If SecurityStmtItem.Defunct Then .Visible = False
          End With
        Next
      End With
    End With

    ' Clients
    With SummaryTableClients
      .TableClass = iseSummaryTableClass.TabularData
      .Caption = "Clients"
      .AutoStripe = True

      ' Columns
      With .Columns
        .AddCode("Code", finBL.ClientFunctions.GetLongestCode())
        .AddText("Name")
      End With

      For Each SecurityStmtClient In SecurityStmt.Clients
        ' Add Row
        With .Rows.Add()
          With .Cells.AddText(SecurityStmtClient.ClientId)
            .HyperlinkSetFormShow("Clients", SecurityStmtClient.ClientId)
          End With
          .Cells.AddText(SecurityStmtClient.ClientName)
        End With
      Next
    End With

    ' Accounts
    With SummaryTableAccounts
      .TableClass = iseSummaryTableClass.TabularData
      .Caption = "Accounts"
      .AutoStripe = True

      ' Columns
      With .Columns
        .AddCode("Code", finBL.AccountFunctions.GetLongestCode())
        .AddText("Description")
        .AddCode("Type", 5).HideRule = iseSummaryTableColumnHideRule.DocumentWidthLessThan320px ' When rendered as HTML, don't display if screen < 320px
        .AddText("Status").HideRule = iseSummaryTableColumnHideRule.DocumentWidthLessThan240px ' When rendered as HTML, don't display if screen < 240px
      End With

      For Each SecurityStmtAccount In SecurityStmt.Accounts
        ' Add Row
        With .Rows.Add()
          With .Cells.AddText(SecurityStmtAccount.AccountId)
            .HyperlinkSetFormShow("Accounts", SecurityStmtAccount.AccountId)
          End With
          .Cells.AddText(SecurityStmtAccount.AccountDescription)
          .Cells.AddText(SecurityStmtAccount.AccountTypeId)
          .Cells.AddText(SecurityStmtAccount.AccountStatusText)
        End With
      Next
    End With

    ' Create and return collection
    SummaryTables = finBL.CreateSummaryTables()
    SummaryTables.Add("Main", SummaryTable)
    If SecurityStmt.SecurityItems.Count <> 0 Then SummaryTables.Add("SecurityItems", SummaryTableSecurityItems)
    If SecurityStmt.Accounts.Count <> 0 Then SummaryTables.Add("Accounts", SummaryTableAccounts)
    If SecurityStmt.Clients.Count <> 0 Then SummaryTables.Add("Clients", SummaryTableClients)
    Return SummaryTables

  End Function

  ''' <summary>
  '''  Quick Search Result Summary for a Standalone Document, i.e., a Document that can be run outside of a Log (Version 1.0, Last updated 29/08/2013).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="quickSearchResult">
  '''  The Quick Search Result to summarise.
  ''' </param>
  ''' <param name="maxDisplayRows">
  '''  The Maximum number of Rows to Display in supplemental tables (e.g., Client Accounts) before a 'Show Hidden' link is displayed.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Quick Search form.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables (depending on the item type being summarised, additional tables may be included):
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function QuickSearch_ResultSummary_StandaloneDocument(callerScriptInfo As ISScriptExecutionInfo,
                                                                           quickSearchResult As finQuickSearchResult,
                                                                           maxDisplayRows As Integer,
                                                                           includeActions As Boolean,
                                                                           otherParameters As ISKeyValueList) As ISSummaryTables

    Dim Document As finDocumentRO
    Dim SummaryTable As ISSummaryTable
    Dim SummaryTables As ISSummaryTables

    ' Initialise
    Document = DirectCast(quickSearchResult.SourceObject, finDocumentRO)
    SummaryTable = finBL.CreateSummaryTable()

    ' Add Columns
    With SummaryTable
      .TableClass = iseSummaryTableClass.Information
      .Columns.AddText(12)
      .Columns.AddText()
    End With

    ' Details
    With SummaryTable.Rows
      ' Code and Description
      With .AddCaptionText("Code:", Document.DocumentId)
        .Cells(1).HyperlinkSetApplicationShortcutUrl(quickSearchResult.ApplicationShortcutUrl)
      End With
      .AddCaptionText("Description:", Document.Description, iseSummaryTableCellClass.Highlight1)

      ' Category and File Type
      .AddCaptionText("Category:", Document.Category)
      .AddCaptionText("File Type:", Document.FileTypeText)

      ' Fee
      If Document.ChargeFee Then
        .AddCaptionText("Fee:", finBL.FormatCurrency(Document.Fee, True))
      End If
    End With

    ' Create and return collection
    SummaryTables = finBL.CreateSummaryTables()
    SummaryTables.Add("Main", SummaryTable)
    Return SummaryTables

  End Function

  ''' <summary>
  '''  Quick Search Result Summary for a Workflow (Version 1.00, Last updated 2/12/2015).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="quickSearchResult">
  '''  The Quick Search Result to summarise.
  ''' </param>
  ''' <param name="maxDisplayRows">
  '''  The Maximum number of Rows to Display in supplemental tables (e.g., Client Accounts) before a 'Show Hidden' link is displayed.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Quick Search form.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables (depending on the item type being summarised, additional tables may be included):
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function QuickSearch_ResultSummary_Workflow(callerScriptInfo As ISScriptExecutionInfo,
                                                                 quickSearchResult As finQuickSearchResult,
                                                                 maxDisplayRows As Integer,
                                                                 includeActions As Boolean,
                                                                 otherParameters As ISKeyValueList) As ISSummaryTables

    Dim Workflow As finWorkflow
    Dim strTemp As String
    Dim SummaryTable As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As finWarnings

    ' Initialise
    Workflow = DirectCast(quickSearchResult.SourceObject, finWorkflow)
    SummaryTable = finBL.CreateSummaryTable()

    ' Add Columns
    With SummaryTable
      .TableClass = iseSummaryTableClass.Information
      .Columns.AddText(10)
      .Columns.AddText(10)
      .Columns.AddText() ' Extra column to display Warnings after code
    End With

    ' Details
    With SummaryTable.Rows
      ' Code and Description
      With .AddCaptionText("Code:", Workflow.WorkflowId)
        With .Cells(1)
          If Not quickSearchResult.IsFilteredOut Then
            .HyperlinkSetApplicationShortcutUrl(quickSearchResult.ApplicationShortcutUrl)
            .NoWrap = True
          End If
        End With

        ' Warnings (show after code for compactness)
        If Not quickSearchResult.IsFilteredOut Then
          Warnings = Workflow.GetWarnings()
          If Warnings.Count <> 0 Then
            If Warnings.Count = 1 Then
              strTemp = "!!**1** warning!!"
            Else
              strTemp = String.Format("!!**{0}** warnings!!", Warnings.Count)
            End If
            With .Cells.AddWiki("{{icon|Warning}} " & strTemp)
              .HyperlinkSetHtmlShowFunction("WorkflowWarningsSummary", String.Format("Warnings for Workflow {0}, '{1}'", Workflow.WorkflowId, Workflow.Description), "WorkflowId=" & finBL.UrlEncode(Workflow.WorkflowId))
            End With
          End If
        End If
      End With
      .AddCaptionText("Description:", Workflow.Description, iseSummaryTableCellClass.Highlight1)

      ' Status and Workflow Type
      .AddCaptionText("Status:", Workflow.StatusTextResolved)
      .AddCaptionCodeDescription("Type:", Workflow.WorkflowTypeId, finBL.WorkflowTypes)

      ' Target Object
      .AddSectionHeading2("Target")
      Select Case Workflow.WorkflowType.TargetObjectType
        Case isefinWorkflowTargetObjectType.Account
          .AddCaptionText("Account:", Workflow.AccountId).Cells(1).HyperlinkSetFormShow("Accounts", Workflow.AccountId)
          .AddCaptionText("Name:", finBL.AccountFunctions.GetRecordDescription(Workflow.AccountId))

        Case isefinWorkflowTargetObjectType.AccountApp
          .AddCaptionText("Application:", Workflow.AccountAppId).Cells(1).HyperlinkSetFormShow("AccountApps", Workflow.AccountAppId)
          .AddCaptionText("Name:", finBL.AccountAppFunctions.GetRecordDescription(Workflow.AccountAppId))

        Case isefinWorkflowTargetObjectType.Client
          .AddCaptionText("Client:", Workflow.ClientId).Cells(1).HyperlinkSetFormShow("Clients", Workflow.ClientId)
          .AddCaptionText("Name:", finBL.ClientFunctions.GetRecordDescription(Workflow.ClientId))
      End Select
    End With

    ' Warnings
    If quickSearchResult.IsFilteredOut Then
      SummaryTable.TextAfter = "{{warning|You do not have permission to view this Workflow.}}"
    End If

    ' Create and return collection
    SummaryTables = finBL.CreateSummaryTables()
    SummaryTables.Add("Main", SummaryTable)
    Return SummaryTables

  End Function

  ''' <summary>
  '''  Quick Search Result Summary for a User.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="quickSearchResult">
  '''  The Quick Search Result to summarise.
  ''' </param>
  ''' <param name="maxDisplayRows">
  '''  The Maximum number of Rows to Display in supplemental tables (e.g., Client Accounts) before a 'Show Hidden' link is displayed.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Quick Search form.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables (depending on the item type being summarised, additional tables may be included):
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function QuickSearch_ResultSummary_User(callerScriptInfo As ISScriptExecutionInfo,
                                                             quickSearchResult As finQuickSearchResult,
                                                             maxDisplayRows As Integer,
                                                             includeActions As Boolean,
                                                             otherParameters As ISKeyValueList) As ISSummaryTables

    ' #################################################################
    ' QuickSearch_ResultSummary_User
    '
    ' Version: 1.02 (28/09/2023)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.01  19/10/2021  ISS      J027593   Caption column sizing        
    '    1.02  28/09/2023  ISS      J032114   Email/SMS Permissions finCC
    ' #################################################################

    'Dim strTemp As String
    Dim ShowDetails As Boolean
    Dim SummaryTable As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim User As finUserRO
    'Dim Warnings As finWarnings

    ' Initialise
    User = DirectCast(quickSearchResult.SourceObject, finUserRO)
    SummaryTable = finBL.CreateSummaryTable()

    ' Add Columns
    With SummaryTable
      .TableClass = iseSummaryTableClass.Information
      .Columns.AddText(10)
      .Columns.AddText(12)
      .Columns.AddText() ' Extra column to display Warnings after code
    End With

    ' Details
    With SummaryTable.Rows
      ' Code and Name
      With .AddCaptionText("Code:", User.UserId)
        With .Cells(1)
          If Not quickSearchResult.IsFilteredOut Then
            .HyperlinkSetApplicationShortcutUrl(quickSearchResult.ApplicationShortcutUrl)
            .NoWrap = True
          End If
        End With

        ' Warnings (show after code for compactness)
        If quickSearchResult.IsFilteredOut Then
          .Cells.AddText("")
        Else
          'Warnings = User.GetWarnings()
          .Cells.AddText("")
        End If
      End With
      .AddCaptionText("Name:", User.Name, iseSummaryTableCellClass.Highlight1)

      ' Details
      If finBL.CurrentUserInformation.IsExternalUser Then
        ShowDetails = (finBL.CurrentUserInformation.ExternalPartyPk = User.ExternalPartyPk)
      Else
        ShowDetails = True
      End If

      If ShowDetails Then
        ' Contact
        If Len(User.Phone) <> 0 OrElse Len(User.Mobile) <> 0 OrElse Len(User.Email) <> 0 Then
          .AddSectionHeading2("Contact")
          If Len(User.Phone) <> 0 Then .AddCaptionTextPhoneNumber("Phone:", User.Phone,, User.UserId,,,, "User")
          If Len(User.Mobile) <> 0 Then .AddCaptionTextPhoneNumber("Mobile:", User.Mobile,, User.UserId,,,, "User")
          If Len(User.Email) <> 0 Then .AddCaptionTextEmailAddress("Email:", User.Email,, User.UserId,,,, "User")
        End If

        ' Actions
        If includeActions AndAlso Not finBL.Database.IsReadOnly Then
          With SummaryTable.Actions
            .AddFormShow("LogAdd", "Log", "UserLog", finBL.CurrentUser.IsAdministrator OrElse finBL.CurrentUser.UserId = User.UserId, "UserId=" & finBL.UrlEncode(User.UserId)).ShowInWebInterfaces = True
            If Len(User.Email) <> 0 Then .AddFormShow("SendEmail", "Email", "EmailMessage", finBL.HtmlWidgetUtilities.HasPermissionToViewFormKey("EmailMessage", ""), "Type=User&Id=" & finBL.UrlEncode(User.UserId)).ShowInWebInterfaces = True
            If Len(User.Mobile) <> 0 OrElse Len(User.Phone) <> 0 Then .AddFormShow("SendSms", "SMS", "SMSMessage", finBL.Messaging.IsMessagingAvailable AndAlso finBL.HtmlWidgetUtilities.HasPermissionToViewFormKey("SMSMessage", ""), "Type=User&Id=" & finBL.UrlEncode(User.UserId)).ShowInWebInterfaces = True
          End With
        End If

      End If
    End With

    ' Warnings
    If quickSearchResult.IsFilteredOut Then
      SummaryTable.TextAfter = "{{warning|You do not have permission to view this User.}}"
    End If

    ' Create and return collection
    SummaryTables = finBL.CreateSummaryTables()
    SummaryTables.Add("Main", SummaryTable)
    Return SummaryTables

  End Function

  ''' <summary>
  '''  Security Statement Accounts Summary (Version 1.01, Last updated 12/07/2017).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="securityStmt">
  '''  The Security Statement to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="maxDisplayRows">
  '''  The Maximum number of Rows to Display in the table before a 'Show Hidden' link is displayed.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Key Details page and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function SecurityStmt_Accounts(callerScriptInfo As ISScriptExecutionInfo,
                                                    securityStmt As finSecurityStmt,
                                           Optional maxDisplayRows As Integer = 20,
                                           Optional includeActions As Boolean = True,
                                           Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim AccountBalance As Decimal
    Dim SecurityStmtAccount As finSecurityStmtAccount
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()
    AccountBalance = 0

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .Caption = ""
      .AutoStripe = True
      .MaxDisplayRows = maxDisplayRows
      .ShowHiddenRowsCaption = "Show More Accounts"

      ' Columns
      With .Columns
        If securityStmt.Accounts.HasFilteredOutAccounts Then .AddCode(" ", 1).TextAlign = iseSummaryTableCellTextAlign.Center ' Warning Icon
        .AddCode("Account", finBL.ClientFunctions.GetLongestCode())
        .AddText("Name")
        .AddText("Status", 10)
        .AddText("Role", 15)
        .AddCurrency("Balance")
      End With

      With .Rows
        For Each SecurityStmtAccount In securityStmt.Accounts
          AccountBalance += SecurityStmtAccount.AccountBalance
          ' Add Row
          With .Add().Cells
            If securityStmt.Accounts.HasFilteredOutAccounts Then
              If SecurityStmtAccount.IsAccountFilteredOut Then
                ' Account Filtered Out
                .AddText("{{icon|Warning|You do not have permission to view this Account}}")
              ElseIf SecurityStmtAccount.Account.Clients.HasFilteredOutClients Then
                ' Account Client Filtered Out
                .AddText("{{icon|Warning|You do not have permission to view a Client linked to this Account}}")
              Else
                .AddText("")
              End If
            End If
            With .AddText(SecurityStmtAccount.AccountId)
              .HyperlinkSetFormShow("Accounts", SecurityStmtAccount.AccountId)
            End With
            If SecurityStmtAccount.IsAccountFilteredOut Then
              .AddWiki(SecurityStmtAccount.AccountName & " --!!(Filtered Out)!!--")
            Else
              .AddText(SecurityStmtAccount.AccountName)
            End If
            .AddText(SecurityStmtAccount.AccountStatusText)
            .AddText(SecurityStmtAccount.Role)
            .AddCurrency(SecurityStmtAccount.AccountBalance)
          End With
        Next
      End With

      With .Rows.Add(iseSummaryTableRowClass.FooterBold).Cells
        With .AddText("")
          .ColSpan = 4
        End With
        .AddCurrency(AccountBalance, True)
      End With

      ' Warnings
      .TextAfter = Warnings

      ' Actions
      If includeActions Then
        With .Actions
        End With
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Security Statement Clients Summary (Version 1.00, Last updated 03/12/2014).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="securityStmt">
  '''  The Security Statement to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="maxDisplayRows">
  '''  The Maximum number of Rows to Display in the table before a 'Show Hidden' link is displayed.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Key Details page and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function SecurityStmt_Clients(callerScriptInfo As ISScriptExecutionInfo,
                                                   securityStmt As finSecurityStmt,
                                          Optional maxDisplayRows As Integer = 20,
                                          Optional includeActions As Boolean = True,
                                          Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim SecurityStmtClient As finSecurityStmtClient
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .Caption = ""
      .AutoStripe = True
      .MaxDisplayRows = maxDisplayRows
      .ShowHiddenRowsCaption = "Show More Clients"

      ' Columns
      With .Columns
        .AddCode(" ", 1).TextAlign = iseSummaryTableCellTextAlign.Center ' Status Icon
        .AddCode("Client", finBL.ClientFunctions.GetLongestCode())
        .AddText("Name")
        .AddText("Role", 15)
      End With

      With .Rows
        For Each SecurityStmtClient In securityStmt.Clients
          ' Add Row
          With .Add().Cells
            If SecurityStmtClient.IsClientFilteredOut Then
              ' Filtered Out
              .AddText("{{icon|Warning|You do not have permission to view this Client}}")
              .AddText(SecurityStmtClient.ClientId)
              .AddWiki(SecurityStmtClient.ClientName & " --!!(Filtered Out)!!--")
              .AddText(SecurityStmtClient.Role)
            Else
              ' Normal
              Select Case SecurityStmtClient.ClientStatus
                Case isefinClientStatus.None
                  .AddText("")
                Case Else
                  .AddText("{{icon|ClientStatus" & SecurityStmtClient.ClientStatus.ToString() & "|Status: " & SecurityStmtClient.ClientStatusText & "}}")
              End Select
              With .AddText(SecurityStmtClient.ClientId)
                .HyperlinkSetFormShow("Clients", SecurityStmtClient.ClientId)
              End With
              .AddWiki(SecurityStmtClient.ClientName)
              .AddText(SecurityStmtClient.Role)
            End If
          End With
        Next
      End With

      ' Warnings
      .TextAfter = Warnings

      ' Actions
      If includeActions Then
        With .Actions
        End With
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Security Statement MotorWeb Security Monitor Details.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="securityStmt">
  '''  The Security Statement to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Security Statement Key Details page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function SecurityStmt_MotorWebSecurityMonitor(callerScriptInfo As ISScriptExecutionInfo,
                                                                   securityStmt As finSecurityStmt,
                                                          Optional includeActions As Boolean = True,
                                                          Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' SecurityStmt_MotorWebSecurityMonitor
    '
    ' Version: 1.01 (05/07/2023)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.00  03/12/2014  ISS                Created
    '    1.01  05/07/2023  ISS      J031343   Form Actions now available to Web Interfaces
    ' #################################################################

    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      .Columns.AddText(20)
      .Columns.AddText()

      With .Rows
        ' General
        .AddCaptionDate("Monitor Date:", securityStmt.SecurityMonitorDate)
      End With

      ' Warnings
      If securityStmt.SecurityMonitorDate <> Nothing Then
        Warnings &= "{{Info|Motor Vehicles are being monitored via MotorWeb.}}"
      End If
      If securityStmt.SecurityMonitorHold Then
        Warnings &= "{{Info|Motor Vehicle monitoring is on Hold.}}"
      End If
      .TextAfter = Warnings

      ' Actions
      If includeActions Then
        With .Actions
          .AddFormAction("SecurityMonitorClearHold", "Clear Hold", Not finBL.Database.IsReadOnly AndAlso securityStmt.SecurityMonitorDate = Nothing AndAlso securityStmt.SecurityMonitorHold AndAlso securityStmt.CanHoldMonitorSecurity).ShowInWebInterfaces = True
          .AddFormAction("SecurityMonitorSetHold", "Hold Monitor", Not finBL.Database.IsReadOnly AndAlso securityStmt.SecurityMonitorDate = Nothing AndAlso Not securityStmt.SecurityMonitorHold AndAlso securityStmt.CanHoldMonitorSecurity).ShowInWebInterfaces = True
          .AddFormAction("SecurityMonitorSet", "Start Monitoring", Not finBL.Database.IsReadOnly AndAlso securityStmt.SecurityMonitorDate = Nothing AndAlso Not securityStmt.SecurityMonitorHold AndAlso securityStmt.CanMonitorSecurity(False)).ShowInWebInterfaces = True
          .AddFormAction("SecurityMonitorClear", "Stop Monitoring", Not finBL.Database.IsReadOnly AndAlso securityStmt.SecurityMonitorDate <> Nothing AndAlso finBL.CurrentUser.Permissions.Allow("SecurityStmt.MotorWeb.VehicleMonitor")).ShowInWebInterfaces = True
        End With
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Security Statement Security Item Enquiries.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="securityStmtItem">
  '''  The Security Statement Item to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Security Statement Key Details page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function SecurityStmt_SecurityItemEnquiries(callerScriptInfo As ISScriptExecutionInfo,
                                                                 securityStmtItem As finSecurityStmtItemBase,
                                                        Optional includeActions As Boolean = True,
                                                        Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' SecurityStmt_SecurityItemEnquiries
    '
    ' Version: 1.02 (11/11/2024)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.00  29/05/2015  ISS                Created
    '    1.01  14/06/2024  ISS      J033547   Reversed order of items so most recent are displayed first
    '    1.02  11/11/2024  ISS      J034681   Show the Summary Page Report instead of the Service Log
    ' #################################################################

    Dim DifferencesUpdate As Boolean
    Dim DifferencesView As Boolean
    Dim i As Integer
    Dim j As Integer
    Dim ServiceLog As ISServiceLog
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Show Differences?
    Select Case callerScriptInfo.FormKey
      Case "AccountNew"
        DifferencesView = True
        DifferencesUpdate = True
      Case "SecurityStmts"
        DifferencesView = True
        DifferencesUpdate = callerScriptInfo.FormRecordMode = iseFormRecordMode.Add OrElse callerScriptInfo.FormRecordMode = iseFormRecordMode.Edit
      Case Else
        DifferencesView = False
    End Select

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .Caption = ""
      .AutoStripe = True

      If securityStmtItem.SecurityEnquiries.Count = 0 Then
        .TextBefore = "{{info|No Security Enquiries found.}}"
      Else
        ' Columns
        With .Columns
          .AddDateTime("Created")
          .AddText("User")
          .AddText("Service")
          .AddText("Product")
          If DifferencesView Then .AddText("Differences")
        End With

        With .Rows
          For i = securityStmtItem.SecurityEnquiries.Count - 1 To 0 Step -1
            ServiceLog = securityStmtItem.SecurityEnquiries(i)

            With .Add()
              ' Only show last Enquiry for each Service/ Product
              For j = i + 1 To securityStmtItem.SecurityEnquiries.Count - 1
                If ServiceLog.ServiceId = securityStmtItem.SecurityEnquiries(j).ServiceId AndAlso ServiceLog.ProductId = securityStmtItem.SecurityEnquiries(j).ProductId AndAlso ServiceLog.ProductOptions = securityStmtItem.SecurityEnquiries(j).ProductOptions Then
                  .Visible = False
                  Exit For
                End If
              Next

              With .Cells
                .AddDateTime(ServiceLog.CreatedDate)
                .AddText(finBL.Users.ItemByPkSafe(ServiceLog.CreatedUserPk).UserIdResolved)
                .AddText(ServiceLog.ServiceId)
                With .AddText(ServiceLog.ProductId & If(Len(ServiceLog.ProductOptions) = 0, "", " (" & ServiceLog.ProductOptions & ")"))
                  .HyperlinkSetHtmlShowFunction("ServiceReport", "Security Enquiry", "serviceLogPk=" & ServiceLog.Pk)
                  .Tooltip = ServiceLog.ProductOptionsTooltip
                End With
                If DifferencesView Then
                  Select Case UCase(ServiceLog.ServiceId) & "." & UCase(ServiceLog.ProductId)
                    Case "CENTRIXNZ.CONFIRM OWNER"
                    Case Else
                      With .AddText(If(DifferencesUpdate, "Update", "View"))
                        .HyperlinkSetFormAction("SecurityEnquiryDifference", "ServiceLogPk=" & CStr(ServiceLog.Pk))
                      End With
                  End Select
                End If
              End With
            End With
          Next
        End With
      End If

      ' Warnings
      .TextAfter = Warnings

      ' Actions
      If includeActions Then
        With .Actions
        End With
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Security Statement; Security Item Files Summary
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="securityStmtItem">
  '''  The Security Statement Item to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Security Statement Item Key Details page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function SecurityStmt_SecurityItemFiles(callerScriptInfo As ISScriptExecutionInfo,
                                                             securityStmtItem As finSecurityStmtItemBase,
                                                    Optional includeActions As Boolean = True,
                                                    Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' SecurityStmt_SecurityItemFiles
    '
    ' Version: 1.00 (24/05/2024)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.00  24/05/2024  ISS      J033492   Created
    ' #################################################################

    Dim DocumentFile As finDocumentFile
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .Caption = ""

      If securityStmtItem.DocumentFiles.Count <> 0 Then
        ' Columns
        With .Columns
          .AddText("File Name")
          .AddDate("Created")
        End With

        ' Files
        For Each DocumentFile In securityStmtItem.DocumentFiles.GetChronologicalList(finBL.Settings.GridsSortReverseChronological)
          With .Rows.Add().Cells
            .AddWiki("{{DocumentManagerFile itemType='SecurityStmtItem' itemId='" & securityStmtItem.SecurityStmt.SecurityStmtId & "' itemPk='" & securityStmtItem.Pk & "' fileName='" & DocumentFile.FileNameWithCategoryAndExtension & "' }}")
            .AddDate(DocumentFile.FileCreatedDate)
          End With
        Next
      End If
    End With

    ' Add the Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Security Statement Security Item Insurance (Version 1.02, Last updated 15/04/2019).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="securityStmtItem">
  '''  The Security Statement Item to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Security Statement Key Details page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function SecurityStmt_SecurityItemInsurance(callerScriptInfo As ISScriptExecutionInfo,
                                                                 securityStmtItem As finSecurityStmtItemBase,
                                                        Optional includeActions As Boolean = True,
                                                        Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      .Columns.AddText(20)
      .Columns.AddText()

      Select Case securityStmtItem.BaseType
        Case isefinSecurityBaseType.Insurance, isefinSecurityBaseType.Investment
          ' N/A

        Case Else
          If securityStmtItem.HasInsuranceDetails Then
            With .Rows
              If securityStmtItem.InsuranceExternalPartyPk = 0 Then
                .AddCaptionText("Company:", securityStmtItem.InsuranceCompany)
              Else
                .AddCaptionText("Insurer:", securityStmtItem.InsuranceExternalPartyId)
                .AddCaptionText("Company:", securityStmtItem.InsuranceExternalParty.Name)
              End If
              .AddCaptionText("Type:", securityStmtItem.InsuranceType)
              .AddCaptionText("Policy No:", securityStmtItem.InsurancePolicy)
              .AddCaptionDate("Renewal Date:", securityStmtItem.InsuranceRenewalDate)
              If securityStmtItem.InsuranceSumInsured = 0 AndAlso securityStmtItem.InsurancePremium = 0 Then
                ' Don't display
              Else
                .AddCaptionCurrency("Cover:", securityStmtItem.InsuranceSumInsured, True)
                .AddCaptionCurrency("Premium:", securityStmtItem.InsurancePremium, True)
              End If
            End With
          Else
            .TextBefore = "{{info|No Insurance details recorded for this item.}}"
          End If
      End Select

      ' Warnings
      .TextAfter = Warnings
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Security Statement Security Item Logs.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="securityStmtItem">
  '''  The Security Statement Item to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="maxDisplayRows">
  '''  The maximum number of rows to display
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Security Statement Item Key Details page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function SecurityStmt_SecurityItemLogs(callerScriptInfo As ISScriptExecutionInfo,
                                                            securityStmtItem As finSecurityStmtItemBase,
                                                   Optional includeActions As Boolean = True,
                                                   Optional maxDisplayRows As Integer = 20,
                                                   Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' SecurityStmt_SecurityItemLogs
    '
    ' Version: 1.00 (24/05/2024)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.00  24/05/2024  ISS      J033546   Created
    ' #################################################################

    Dim Action As String
    Dim Log As finLogRO
    Dim ShowAction As Boolean
    Dim ShowSeverity As Boolean
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Determine Columns to include
    ShowAction = False
    ShowSeverity = False
    For Each Log In securityStmtItem.Logs
      If Log.ActionUtcDate <> Nothing Then ShowAction = True
      If Log.LogSeverityPk <> 0 Then ShowSeverity = True
    Next

    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .Caption = ""
      .MaxDisplayRows = maxDisplayRows

      If securityStmtItem.Logs.Count <> 0 Then
        ' Columns
        With .Columns
          If ShowSeverity Then .AddBoolean(" ")
          .AddDate("Date")
          .AddText("Subject")
          If ShowAction Then .AddText("Action", 10)
        End With

        ' Logs
        For Each Log In securityStmtItem.Logs.GetChronologicalList(finBL.Settings.GridsSortReverseChronological)
          With .Rows.Add().Cells
            ' Log Severity
            If ShowSeverity Then
              If Log.LogSeverityPk = 0 Then
                .AddText("")
              ElseIf Log.ActionDate <> Nothing AndAlso Log.ActionCompleteDate = Nothing Then
                .AddText("{{colourblock|" & Log.LogSeverity.OpenColourBackground & "|" & Log.LogSeverity.LogSeverityId & ", " & Log.LogSeverity.Description & "}}")
              Else
                .AddText("{{colourblock|" & Log.LogSeverity.CompleteColourBackground & "|" & Log.LogSeverity.LogSeverityId & ", " & Log.LogSeverity.Description & "}}")
              End If
            End If

            .AddDate(Log.LogDate)
            .AddText(Log.Subject).HyperlinkSetFormShow("SecurityStmtItemLog", CStr(Log.Pk))

            ' Log Action
            If ShowAction Then
              If Log.ActionDate = Nothing Then
                Action = ""
              ElseIf Log.ActionCompleteDate = Nothing Then
                Action = finBL.FormatDateForGrid(Log.ActionDate)
              Else
                Action = "Complete"
              End If
              .AddText(Action)
            End If
          End With
        Next
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Security Statement Security Item Owner and Location details (Version 1.00, Last updated 05/12/2014).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="securityStmtItem">
  '''  The Security Statement Item to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Security Statement Key Details page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function SecurityStmt_SecurityItemOwnerAndLocation(callerScriptInfo As ISScriptExecutionInfo,
                                                                        securityStmtItem As finSecurityStmtItemBase,
                                                               Optional includeActions As Boolean = True,
                                                               Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim AddressDetails As ISAddressDetails
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      .Columns.AddText(20)
      .Columns.AddText()

      Select Case securityStmtItem.BaseType
        Case isefinSecurityBaseType.Land
          ' Land (only show owner details)
          If securityStmtItem.HasOwnerDetails Then
            With .Rows
              .AddCaptionCodeDescriptionWithFormShow("Owner:", securityStmtItem.OwnerClientPk, finBL.ClientFunctions, "Clients")
              .AddCaptionText("Details:", securityStmtItem.OwnerDetails)
            End With
          Else
            .TextBefore = "{{info|No Owner details recorded for this item.}}"
          End If

        Case Else
          If securityStmtItem.HasOwnerAndLocationDetails Then
            With .Rows
              .AddCaptionCodeDescriptionWithFormShow("Owner:", securityStmtItem.OwnerClientPk, finBL.ClientFunctions, "Clients")
              .AddCaptionText("Details:", securityStmtItem.OwnerDetails)
              AddressDetails = securityStmtItem.ToAddressDetails()
              If AddressDetails.HasValue Then
                .AddCaptionAddressDetailsPhysical("Address:", AddressDetails)
              End If
            End With
          Else
            .TextBefore = "{{info|No Owner or Location details recorded for this item.}}"
          End If
      End Select

      ' Warnings
      .TextAfter = Warnings
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Security Statement Item Monitoring Details.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="securityStmtItem">
  '''  The Security Statement Item to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function SecurityStmt_SecurityItemMonitoring(callerScriptInfo As ISScriptExecutionInfo,
                                                                  securityStmtItem As finSecurityStmtItemBase,
                                                         Optional includeActions As Boolean = True,
                                                         Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' SecurityStmt_SecurityItemMonitoring
    '
    ' Version: 1.00 (28/02/2023)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.00  28/02/2023  ISS      J028790   Created
    '          28/02/2023  ISS      J030270   Added support for finCC
    ' #################################################################

    Dim ParametersUrl As String
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      .Columns.AddText(20)
      .Columns.AddText()

      With .Rows
        ' General
        Select Case securityStmtItem.MonitorType
          Case isefinSecurityStmtMonitorType.None
            ' Not Monitored
            Warnings &= "{{Info|Not currently monitored.}}"

          Case isefinSecurityStmtMonitorType.Held
            ' Held
            Warnings &= "{{Info|Monitoring is on Hold.}}"

          Case isefinSecurityStmtMonitorType.InfoAgent
            ' Monitored by InfoAgent
            .AddCaptionDate("Monitor Date:", securityStmtItem.MonitorDate)

            Warnings &= "{{Info|Motor Vehicle is currently being monitored by InfoAgent.}}"
        End Select
      End With

      ' Warnings
      .TextAfter = Warnings

      ' Actions
      If includeActions Then
        ' Parameters required for finCC implementation
        ParametersUrl = String.Format("SecurityStmtId={0}&SecurityStmtItemPk={1}", securityStmtItem.SecurityStmt.SecurityStmtId, securityStmtItem.Pk)

        With .Actions
          If securityStmtItem.CanHoldMonitoring() Then
            .AddFormAction("SecurityItemMonitorClearHold", "Clear Hold", securityStmtItem.MonitorType = isefinSecurityStmtMonitorType.Held, ParametersUrl).ShowInWebInterfaces = True
            .AddFormAction("SecurityItemMonitorSetHold", "Hold Monitoring", securityStmtItem.MonitorType = isefinSecurityStmtMonitorType.None, ParametersUrl).ShowInWebInterfaces = True
          End If
          If securityStmtItem.CanStartMonitoring(iseSecurityEnquiryService.InfoAgent) Then .AddFormAction("SecurityItemMonitorStart", "Start Monitoring via InfoAgent", , ParametersUrl).ShowInWebInterfaces = True
          If securityStmtItem.CanStopMonitoring(iseSecurityEnquiryService.InfoAgent) Then .AddFormAction("SecurityItemMonitorStop", "Stop Monitoring", , ParametersUrl).ShowInWebInterfaces = True
        End With
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Security Statement Security Item Summary.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="securityStmtItem">
  '''  The Security Statement Item to summarise.
  ''' </param>
  ''' <param name="includeValuation">
  '''  Indicates whether to include basic Valuation details if applicable.
  ''' </param>
  ''' <param name="includeFullDescription">
  '''  Indicates whether to include a full description if applicable.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Security Statement Key Details page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''    <item><code>SecurityType</code><description>Security Type specific details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function SecurityStmt_SecurityItemSummary(callerScriptInfo As ISScriptExecutionInfo,
                                                               securityStmtItem As finSecurityStmtItemBase,
                                                      Optional includeValuation As Boolean = True,
                                                      Optional includeFullDescription As Boolean = True,
                                                      Optional includeActions As Boolean = True,
                                                      Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' SecurityStmt_SecurityItemSummary
    '
    ' Version: 1.08 (30/05/2024)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.06  17/12/2018  ISS
    '    1.07  15/06/2022  ISS      J026356   Added Land Size and Mortgage Registration No
    '    1.08  30/05/2024  ISS      J033154   Added Priority Value for Land items
    ' #################################################################

    Dim IdendificationTerminology As String
    Dim SecurityStmtItemAircraft As finSecurityStmtItemAircraft
    Dim SecurityStmtItemBoat As finSecurityStmtItemBoat
    Dim SecurityStmtItemInvestment As finSecurityStmtItemInvestment
    Dim SecurityStmtItemLand As finSecurityStmtItemLand
    Dim SecurityStmtItemMotorVehicle As finSecurityStmtItemMotorVehicle
    Dim SecurityStmtItemSerialNumberedGood As finSecurityStmtItemSerialNumberedGood
    Dim ServiceLog As ISServiceLog
    Dim strTemp As String
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTableSecurityType As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTableSecurityType = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      .Columns.AddText(20)
      .Columns.AddText()

      With .Rows
        ' General
        .AddCaptionText("Description:", securityStmtItem.Description, iseSummaryTableCellClass.Highlight1)
        .AddCaptionCodeDescription("Type:", securityStmtItem.SecurityTypePk, finBL.SecurityTypes)
        .AddCaptionText("Class:", securityStmtItem.CollateralClass.Description)
        .AddCaptionText("Reference:", securityStmtItem.Reference)

        ' Valuation
        If includeValuation AndAlso (securityStmtItem.Value <> 0 OrElse securityStmtItem.SecurityValue <> 0) Then
          .AddCaptionCurrency("Value:", securityStmtItem.Value, True)
          .AddCaptionCurrency("Security Value:", securityStmtItem.SecurityValue, True)
        End If

        ' Full Description
        Select Case securityStmtItem.BaseType
          Case isefinSecurityBaseType.SerialNumberedGood
            With DirectCast(securityStmtItem, finSecurityStmtItemSerialNumberedGood)
              strTemp = .DescriptionFull
            End With

          Case isefinSecurityBaseType.Standard
            With DirectCast(securityStmtItem, finSecurityStmtItemStandard)
              strTemp = .DescriptionFull
            End With

          Case Else
            strTemp = ""
        End Select
        If Len(strTemp) <> 0 Then
          .AddSectionHeading2("Full Description")
          .AddText(strTemp)
        End If
      End With

      ' Boat Registration Warnings
      If securityStmtItem.BaseType = isefinSecurityBaseType.Boat Then
        If finBL.Settings.AddOns.SecurityRegisterPPSR AndAlso securityStmtItem.CollateralClassBase <> iseSecurityCollateralClassBase.NotApplicable AndAlso Not securityStmtItem.Defunct AndAlso Not securityStmtItem.TradeIn Then
          IdendificationTerminology = finBL.SecurityRegister.Terminology(iseSecurityRegisterTerminology.IdentificationNumber)
          SecurityStmtItemBoat = securityStmtItem.ItemAsBoat

          Select Case finBL.CountryCode
            Case "AU"
              If Len(SecurityStmtItemBoat.HIN) <> 0 Then
                Warnings &= "{{info|The HIN will be used as the " & IdendificationTerminology & " when registering this boat on the PPSR.}}"
              ElseIf Len(SecurityStmtItemBoat.IdentificationNumber) <> 0 Then
                Warnings &= "{{info|The Official Number will be used as the " & IdendificationTerminology & " when registering this boat on the PPSR. The HIN is the preferred " & IdendificationTerminology & ".}}"
              Else
                If SecurityStmtItemBoat.CollateralClassBase = iseSecurityCollateralClassBase.AU_Com_Watercraft Then
                  Warnings &= "{{info|The Description will be used when registering this boat on the PPSR.}}"
                End If
              End If

            Case "NZ"
              If Len(SecurityStmtItemBoat.RegistrationNumber) <> 0 Then
                If StrComp(SecurityStmtItemBoat.RegistrationNumber, SecurityStmtItemBoat.HIN) = 0 Then
                  Warnings &= "{{info|The Registration number will be used as the " & IdendificationTerminology & " when registering this boat on the PPSR.}}"
                Else
                  Warnings &= "{{info|The Registration number will be used as the " & IdendificationTerminology & " when registering this boat on the PPSR. The HIN is the preferred " & IdendificationTerminology & ".}}"
                End If
              ElseIf Len(SecurityStmtItemBoat.HIN) <> 0 Then
                Warnings &= "{{info|The HIN will be used as the " & IdendificationTerminology & " when registering this boat on the PPSR.}}"
              ElseIf Len(SecurityStmtItemBoat.IdentificationNumber) <> 0 Then
                Warnings &= "{{info|The Identification will be used as the " & IdendificationTerminology & " when registering this boat on the PPSR. The HIN is the preferred " & IdendificationTerminology & ".}}"
              End If
          End Select
        End If
      End If

      ' Warnings
      If securityStmtItem.BaseType = isefinSecurityBaseType.MotorVehicle AndAlso securityStmtItem.SecurityStmt.SecurityMonitorDate <> Nothing Then
        Warnings &= "{{info|Motor Vehicle is being monitored via MotorWeb.}}"
      End If
      If securityStmtItem.Defunct Then Warnings &= "{{info|Item is Defunct.}}"
      If securityStmtItem.TradeIn Then Warnings &= "{{info|Item is a Trade-In.}}"
      If finBL.Settings.AddOns.SecurityRegisterPPSR AndAlso securityStmtItem.CollateralClassBase = iseSecurityCollateralClassBase.NotApplicable Then
        Warnings &= "{{info|Item is collateral class 'Not Applicable'.}}"
      End If
      .TextAfter = Warnings
    End With

    ' Security Type
    Warnings = ""
    With SummaryTableSecurityType
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Columns.AddText(20)
      .Columns.AddText()

      With .Rows
        ' Security Type Specific
        Select Case securityStmtItem.BaseType
          Case isefinSecurityBaseType.Aircraft
            ' ========
            ' Aircraft
            ' ========
            SecurityStmtItemAircraft = securityStmtItem.ItemAsAircraft
            SummaryTableSecurityType.Caption = "Aircraft details"
            .AddCaptionText("Reg Mark:", SecurityStmtItemAircraft.RegistrationMark)
            .AddCaptionText("Manufacturer No:", SecurityStmtItemAircraft.ManufacturerSerialNumber)
            .AddCaptionText("Origin Country:", SecurityStmtItemAircraft.CountryOfOrigin)
            .AddCaptionText("Class:", SecurityStmtItemAircraft.AircraftClass)
            .AddCaptionText("Make:", SecurityStmtItemAircraft.Make)
            .AddCaptionText("Model:", SecurityStmtItemAircraft.Model)
            If SecurityStmtItemAircraft.Year = 0 Then
              .AddCaptionText("Year:", "")
            Else
              .AddCaptionText("Year:", CStr(SecurityStmtItemAircraft.Year))
            End If

          Case isefinSecurityBaseType.Boat
            ' ====
            ' Boat
            ' ====
            SecurityStmtItemBoat = securityStmtItem.ItemAsBoat
            Select Case finBL.CountryCode
              Case "AU"
                SummaryTableSecurityType.Caption = "Watercraft details"
              Case Else
                SummaryTableSecurityType.Caption = "Boat details"
            End Select
            .AddCaptionText("Reg No:", SecurityStmtItemBoat.RegistrationNumber)
            .AddCaptionText(finBL.SupportedCountries.CurrentSupportedCountry.Terminology(isefinCountryTerminology.BoatIdentificationNumber, True) & ":", SecurityStmtItemBoat.IdentificationNumber)
            .AddCaptionText("Origin Country:", SecurityStmtItemBoat.CountryOfOrigin)
            .AddCaptionText("Boat Type:", SecurityStmtItemBoat.BoatType)
            .AddCaptionText("Boat Name:", SecurityStmtItemBoat.BoatName)
            .AddCaptionText("HIN:", SecurityStmtItemBoat.HIN)
            .AddCaptionText("Hull Length:", SecurityStmtItemBoat.HullLength)
            .AddCaptionText("Hull Type:", SecurityStmtItemBoat.HullType)
            .AddCaptionText("Make:", SecurityStmtItemBoat.Make)
            .AddCaptionText("Model:", SecurityStmtItemBoat.Model)
            .AddCaptionText("Colour:", SecurityStmtItemBoat.Colour)
            If SecurityStmtItemBoat.Year = 0 Then
              .AddCaptionText("Year:", "")
            Else
              .AddCaptionText("Year:", CStr(SecurityStmtItemBoat.Year))
            End If

          Case isefinSecurityBaseType.Insurance
            ' =========
            ' Insurance
            ' =========
            SummaryTableSecurityType.Caption = "Insurance details"
            If securityStmtItem.InsuranceExternalPartyPk = 0 Then
              .AddCaptionText("Company:", securityStmtItem.InsuranceCompany)
            Else
              .AddCaptionText("Insurer:", securityStmtItem.InsuranceExternalPartyId)
              .AddCaptionText("Company:", securityStmtItem.InsuranceExternalParty.Name)
            End If
            .AddCaptionText("Type:", securityStmtItem.InsuranceType)
            .AddCaptionText("Policy No:", securityStmtItem.InsurancePolicy)
            .AddCaptionCurrency("Cover:", securityStmtItem.InsuranceSumInsured, True)
            .AddCaptionCurrency("Premium:", securityStmtItem.InsurancePremium, True)
            .AddCaptionDate("Renewal:", securityStmtItem.InsuranceRenewalDate)

          Case isefinSecurityBaseType.Investment
            ' ==========
            ' Investment
            ' ==========
            SecurityStmtItemInvestment = securityStmtItem.ItemAsInvestment
            SummaryTableSecurityType.Caption = "Investment details"
            .AddCaptionText("Code:", SecurityStmtItemInvestment.InvestmentCode)
            .AddCaptionDate("Valuation Date:", SecurityStmtItemInvestment.ValuationDate)
            .AddCaptionText("Currency:", SecurityStmtItemInvestment.Currency)
            .AddCaptionText("Quantity:", Format(SecurityStmtItemInvestment.Quantity, "###,###,##0"))
            .AddCaptionCurrency("Unit Price:", SecurityStmtItemInvestment.UnitPrice, True)
            .AddCaptionCurrency("Market Value:", SecurityStmtItemInvestment.MarketValue, True)
            .AddSectionHeading2("Value Secured")
            .AddCaptionPercentage("Percentage:", SecurityStmtItemInvestment.ValuationPercentUse / 100, 2, True)
            .AddCaptionCurrency("Security Value:", SecurityStmtItemInvestment.SecurityValue, True)
            .AddSectionHeading2("Review date")
            .AddCaptionDate("Review:", SecurityStmtItemInvestment.ReviewDate)

          Case isefinSecurityBaseType.Land
            ' ====
            ' Land
            ' ====
            SecurityStmtItemLand = securityStmtItem.ItemAsLand
            SummaryTableSecurityType.Caption = "Land details"
            .AddCaptionText("Title:", SecurityStmtItemLand.LandTitle)
            .AddCaptionText("Lot:", SecurityStmtItemLand.Lot)
            .AddCaptionText("DP:", SecurityStmtItemLand.DP)
            .AddCaptionText("Zone:", SecurityStmtItemLand.LandZone)
            .AddCaptionText("Land Use:", SecurityStmtItemLand.LandUse)
            .AddCaptionText("Land Size:", SecurityStmtItemLand.LandSize)
            .AddCaptionAddressDetailsPhysical("Location:", securityStmtItem.ToAddressDetails())

            .AddSectionHeading2("Mortgage details")
            .AddCaptionText("Type:", SecurityStmtItemLand.MortgageType)
            .AddCaptionText("Registered:", SecurityStmtItemLand.MortgageRegistered)
            .AddCaptionText("Registration No:", SecurityStmtItemLand.MortgageRegistrationNo)
            .AddCaptionDate("Date Registered:", SecurityStmtItemLand.MortgageRegistrationDate)
            .AddCaptionDate("Date Discharged:", SecurityStmtItemLand.MortgageDischargeDate)
            .AddCaptionCurrency("Priority Value:", SecurityStmtItemLand.PriorityValue, True)

          Case isefinSecurityBaseType.MotorVehicle
            ' =============
            ' Motor Vehicle
            ' =============
            SecurityStmtItemMotorVehicle = securityStmtItem.ItemAsMotorVehicle
            SummaryTableSecurityType.Caption = "Motor Vehicle Identification details"
            .AddCaptionText("Reg No:", SecurityStmtItemMotorVehicle.RegistrationNumber)
            If finBL.CountryCode = "AU" Then .AddCaptionText("State:", SecurityStmtItemMotorVehicle.RegState)
            .AddCaptionText("VIN:", SecurityStmtItemMotorVehicle.VIN)
            .AddCaptionText("Chassis:", SecurityStmtItemMotorVehicle.Chassis)
            .AddCaptionText("Manufacturer No:", SecurityStmtItemMotorVehicle.ManufacturerSerialNumber)
            .AddCaptionText("Engine No:", SecurityStmtItemMotorVehicle.EngineNumber)

            .AddSectionHeading2("Other details")
            .AddCaptionText("Vehicle Type:", SecurityStmtItemMotorVehicle.VehicleType)
            .AddCaptionText("Body Style:", SecurityStmtItemMotorVehicle.BodyStyle)
            .AddCaptionText("Make:", SecurityStmtItemMotorVehicle.Make)
            With .AddCaptionWiki("Model:", "**" & SecurityStmtItemMotorVehicle.Model & "**").Cells(1)
              If Len(SecurityStmtItemMotorVehicle.ModelSub) <> 0 Then
                .Value &= ", **" & SecurityStmtItemMotorVehicle.ModelSub & "**"
              End If
            End With
            .AddCaptionText("Colour:", SecurityStmtItemMotorVehicle.Colour)
            If SecurityStmtItemMotorVehicle.Year = 0 Then
              .AddCaptionText("Year:", "")
            Else
              .AddCaptionText("Year:", CStr(SecurityStmtItemMotorVehicle.Year))
            End If

          Case isefinSecurityBaseType.SerialNumberedGood
            ' ====================
            ' Serial Numbered Good
            ' ====================
            SecurityStmtItemSerialNumberedGood = securityStmtItem.ItemAsSerialNumberedGood
            SummaryTableSecurityType.Caption = "Serial Numbered Good details"
            .AddCaptionText("Serial No:", SecurityStmtItemSerialNumberedGood.SerialNumber)
            .AddCaptionText("Make:", SecurityStmtItemSerialNumberedGood.Make)
            With .AddCaptionWiki("Model:", "**" & SecurityStmtItemSerialNumberedGood.Model & "**").Cells(1)
              If Len(SecurityStmtItemSerialNumberedGood.ModelSub) <> 0 Then
                .Value &= ", **" & SecurityStmtItemSerialNumberedGood.ModelSub & "**"
              End If
            End With
            .AddCaptionText("Colour:", SecurityStmtItemSerialNumberedGood.Colour)
            If SecurityStmtItemSerialNumberedGood.Year = 0 Then
              .AddCaptionText("Year:", "")
            Else
              .AddCaptionText("Year:", CStr(SecurityStmtItemSerialNumberedGood.Year))
            End If
            .AddCaptionText("Origin Country:", SecurityStmtItemSerialNumberedGood.CountryOfOrigin)
            .AddCaptionText("Description:", SecurityStmtItemSerialNumberedGood.DescriptionGoods)

          Case isefinSecurityBaseType.Standard
            ' ========
            ' Standard
            ' ========

          Case Else
            ' Just in case!
            Warnings &= "{{warning|No summary is available for this type of Security Item.}}"
        End Select
      End With

      ' Warnings
      .TextAfter = Warnings

      ' Actions
      If includeActions Then
        With .Actions
          ' MotorWeb
          If securityStmtItem.BaseType = isefinSecurityBaseType.MotorVehicle AndAlso finBL.Settings.AddOns.SecurityEnquiry_MotorWeb AndAlso callerScriptInfo.FormKey = "SecurityStmts" Then
            If Len(SecurityStmtItemMotorVehicle.MotorWebReference) <> 0 Then
              ' NOTE: Include ServiceLogPk as a fallback and for Web support
              ServiceLog = SecurityStmtItemMotorVehicle.GetMotorWebReferenceHtmlServiceLog()

              If ServiceLog IsNot Nothing Then
                Select Case UCase(ServiceLog.ProductId)
                  Case "ASSET CHECK", "ASSET CHECK PREVIOUS REPORT", "ASSET CHECK PDF"
                    .AddApplicationShortcutUrl("ShowVIR", "Show Asset Check Report", String.Format("app://global?type=MotorWeb.AssetCheck&securityStmtPk={0}&securityStmtItemPk={1}&serviceLogPk={2}&title=MotorWeb VIR", securityStmtItem.SecurityStmt.Pk, SecurityStmtItemMotorVehicle.Pk, ServiceLog.Pk)).ShowInWebInterfaces = True
                  Case "REGO CHECK", "REGO CHECK PREVIOUS REPORT"
                    .AddApplicationShortcutUrl("ShowVIR", "Show Rego Check Report", String.Format("app://global?type=MotorWeb.RegoCheck&securityStmtPk={0}&securityStmtItemPk={1}&serviceLogPk={2}&title=MotorWeb VIR", securityStmtItem.SecurityStmt.Pk, SecurityStmtItemMotorVehicle.Pk, ServiceLog.Pk)).ShowInWebInterfaces = True
                  Case Else
                    .AddApplicationShortcutUrl("ShowVIR", "Show VIR Report", String.Format("app://global?type=MotorWeb.Vir&securityStmtPk={0}&securityStmtItemPk={1}&serviceLogPk={2}&title=MotorWeb VIR", securityStmtItem.SecurityStmt.Pk, SecurityStmtItemMotorVehicle.Pk, ServiceLog.Pk)).ShowInWebInterfaces = True
                End Select
              Else
                .AddApplicationShortcutUrl("ShowVIR", "Show MotorWeb Report", String.Format("app://global?type=MotorWeb.Vir&securityStmtPk={0}&securityStmtItemPk={1}&serviceLogPk={2}&title=MotorWeb VIR", securityStmtItem.SecurityStmt.Pk, SecurityStmtItemMotorVehicle.Pk, 0)).ShowInWebInterfaces = True
              End If
            End If
          End If
        End With
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)
    SummaryTables.Add("SecurityType", SummaryTableSecurityType)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Security Statement Security Item User Defined details (Version 1.00, Last updated 05/12/2014).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="securityStmtItem">
  '''  The Security Statement Item to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Security Statement Key Details page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function SecurityStmt_SecurityItemUserDefined(callerScriptInfo As ISScriptExecutionInfo,
                                                                   securityStmtItem As finSecurityStmtItemBase,
                                                          Optional includeActions As Boolean = True,
                                                          Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim Parameters As ISParameters
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables

    Parameters = finBL.SecurityStmtFunctions.CreateUserDefinedParametersSecurityItem(securityStmtItem.SecurityType.UserDefinedParameterSetPk)
    Parameters.UpdateFromKeyValueList(securityStmtItem.UserData)

    If securityStmtItem.SecurityType.UserDefinedParameterSetPk = 0 AndAlso Not finBL.Settings.HasSecurityStmtItemUser Then
      SummaryTables = finBL.CreateSummaryTables()
      SummaryTableMain = finBL.CreateSummaryTable()
      SummaryTables.Add("Main", SummaryTableMain)
    Else
      SummaryTables = finBL.Utilities.ParametersToSummaryTables(Parameters)
    End If

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Security Statement Security Item Valuation (Version 1.00, Last updated 04/12/2014).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="securityStmtItem">
  '''  The Security Statement Item to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Security Statement Key Details page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function SecurityStmt_SecurityItemValuation(callerScriptInfo As ISScriptExecutionInfo,
                                                                 securityStmtItem As finSecurityStmtItemBase,
                                                        Optional includeActions As Boolean = True,
                                                        Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim SecurityStmtItemAircraft As finSecurityStmtItemAircraft
    Dim SecurityStmtItemBoat As finSecurityStmtItemBoat
    Dim SecurityStmtItemLand As finSecurityStmtItemLand
    Dim SecurityStmtItemMotorVehicle As finSecurityStmtItemMotorVehicle
    Dim SecurityStmtItemSerialNumberedGood As finSecurityStmtItemSerialNumberedGood
    Dim SecurityStmtItemStandard As finSecurityStmtItemStandard
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""

      If securityStmtItem.Defunct OrElse securityStmtItem.TradeIn Then
        .TextBefore = "{{info|Not applicable to Defunct or Trade-In Items.}}"
      Else
        Select Case securityStmtItem.BaseType
          Case isefinSecurityBaseType.Aircraft
            ' ========
            ' Aircraft
            ' ========
            SecurityStmtItemAircraft = securityStmtItem.ItemAsAircraft
            .Columns.AddText(20)
            .Columns.AddText()
            With .Rows
              .AddCaptionText("Valuer:", SecurityStmtItemAircraft.ValuationValuer)
              .AddCaptionDate("Last Date:", SecurityStmtItemAircraft.ValuationDate)
              .AddCaptionDate("Review:", SecurityStmtItemAircraft.ReviewDate)
              .AddCaptionCurrency("Value:", SecurityStmtItemAircraft.Value, True)
              .AddCaptionCurrency("Security Value:", SecurityStmtItemAircraft.SecurityValue, True)
            End With

          Case isefinSecurityBaseType.Boat
            ' ====
            ' Boat
            ' ====
            SecurityStmtItemBoat = securityStmtItem.ItemAsBoat
            .Columns.AddText(20)
            .Columns.AddText()
            With .Rows
              .AddCaptionText("Valuer:", SecurityStmtItemBoat.ValuationValuer)
              .AddCaptionDate("Last Date:", SecurityStmtItemBoat.ValuationDate)
              .AddCaptionDate("Review:", SecurityStmtItemBoat.ReviewDate)
              .AddCaptionCurrency("Value:", SecurityStmtItemBoat.Value, True)
              .AddCaptionCurrency("Security Value:", SecurityStmtItemBoat.SecurityValue, True)
            End With

          Case isefinSecurityBaseType.Insurance
            ' =========
            ' Insurance
            ' =========
            .TextBefore = "{{info|Valuation details are not applicable to 'Insurance' Items.}}"

          Case isefinSecurityBaseType.Investment
            ' ==========
            ' Investment
            ' ==========

          Case isefinSecurityBaseType.Land
            ' ====
            ' Land
            ' ====
            SecurityStmtItemLand = securityStmtItem.ItemAsLand
            .Columns.AddText(20)
            .Columns.AddCurrency()
            .Columns.AddText()
            With .Rows
              .AddCaptionText("Valuer:", SecurityStmtItemLand.ValuationValuer)
              .AddCaptionDate("Last Date:", SecurityStmtItemLand.ValuationDate)
              .AddCaptionDate("Review:", SecurityStmtItemLand.ReviewDate)

              .AddSectionHeading2("Value")
              .AddCaptionCurrency("Land Value:", SecurityStmtItemLand.ValuationLandValue, True)
              .AddCaptionCurrency("Improvements:", SecurityStmtItemLand.ValuationImprovementsValue, True)
              .AddCaptionCurrency("Other/Chattels:", SecurityStmtItemLand.ValuationOtherValue, True)
              .AddCaptionCurrency("Total Value:", SecurityStmtItemLand.Value, True).RowClass = iseSummaryTableRowClass.FooterBold

              If SecurityStmtItemLand.HasPriorRankingMortgage Then
                .AddSectionHeading2("Prior Ranking Mortgages")
                With .AddCaptionCurrency("1st Mortgage:", SecurityStmtItemLand.ValuationPriorRanking, True).Cells
                  .AddText(SecurityStmtItemLand.ValuationPriorRankingNotes).CellClass = iseSummaryTableCellClass.Small
                End With
                If SecurityStmtItemLand.ValuationPriorRanking2 <> 0 Then
                  With .AddCaptionCurrency("2nd Mortgage:", SecurityStmtItemLand.ValuationPriorRanking2, True).Cells
                    .AddText(SecurityStmtItemLand.ValuationPriorRankingNotes2).CellClass = iseSummaryTableCellClass.Small
                  End With
                End If
                If SecurityStmtItemLand.ValuationPriorRanking3 <> 0 Then
                  With .AddCaptionCurrency("3rd Mortgage:", SecurityStmtItemLand.ValuationPriorRanking3, True).Cells
                    .AddText(SecurityStmtItemLand.ValuationPriorRankingNotes3).CellClass = iseSummaryTableCellClass.Small
                  End With
                End If
                If SecurityStmtItemLand.ValuationPriorRanking4 <> 0 Then
                  With .AddCaptionCurrency("4th Mortgage:", SecurityStmtItemLand.ValuationPriorRanking4, True).Cells
                    .AddText(SecurityStmtItemLand.ValuationPriorRankingNotes4).CellClass = iseSummaryTableCellClass.Small
                  End With
                End If
                .AddCaptionCurrency("Total Prior:", SecurityStmtItemLand.ValuationPriorRankingTotal, True).RowClass = iseSummaryTableRowClass.FooterBold
              End If

              .AddSectionHeading2("Value Secured")
              With .AddCaptionPercentage("Percentage:", SecurityStmtItemLand.ValuationPercentUse / 100, 2, True).Cells
                If SecurityStmtItemLand.HasPriorRankingMortgage Then
                  .AddText("(Total Prior + Security Value) / Total Value").CellClass = iseSummaryTableCellClass.Small
                Else
                  .AddText("(Security Value) / Total Value").CellClass = iseSummaryTableCellClass.Small
                End If
              End With
              .AddCaptionCurrency("Security Value:", SecurityStmtItemLand.SecurityValue, True).RowClass = iseSummaryTableRowClass.FooterBold
            End With

          Case isefinSecurityBaseType.MotorVehicle
            ' =============
            ' Motor Vehicle
            ' =============
            SecurityStmtItemMotorVehicle = securityStmtItem.ItemAsMotorVehicle
            .Columns.AddText(20)
            .Columns.AddText()
            With .Rows
              .AddCaptionText("Valuer:", SecurityStmtItemMotorVehicle.ValuationValuer)
              .AddCaptionDate("Last Date:", SecurityStmtItemMotorVehicle.ValuationDate)
              .AddCaptionDate("Review:", SecurityStmtItemMotorVehicle.ReviewDate)
              .AddCaptionCurrency("Value:", SecurityStmtItemMotorVehicle.Value, True)
              .AddCaptionCurrency("Security Value:", SecurityStmtItemMotorVehicle.SecurityValue, True)
            End With

          Case isefinSecurityBaseType.SerialNumberedGood
            ' ====================
            ' Serial Numbered Good
            ' ====================
            SecurityStmtItemSerialNumberedGood = securityStmtItem.ItemAsSerialNumberedGood
            .Columns.AddText(20)
            .Columns.AddText()
            With .Rows
              .AddCaptionText("Valuer:", SecurityStmtItemSerialNumberedGood.ValuationValuer)
              .AddCaptionDate("Last Date:", SecurityStmtItemSerialNumberedGood.ValuationDate)
              .AddCaptionDate("Review:", SecurityStmtItemSerialNumberedGood.ReviewDate)
              .AddCaptionCurrency("Value:", SecurityStmtItemSerialNumberedGood.Value, True)
              .AddCaptionCurrency("Security Value:", SecurityStmtItemSerialNumberedGood.SecurityValue, True)
            End With

          Case isefinSecurityBaseType.Standard
            ' ========
            ' Standard
            ' ========
            SecurityStmtItemStandard = securityStmtItem.ItemAsStandard
            .Columns.AddText(20)
            .Columns.AddText()
            With .Rows
              .AddCaptionText("Valuer:", SecurityStmtItemStandard.ValuationValuer)
              .AddCaptionDate("Last Date:", SecurityStmtItemStandard.ValuationDate)
              .AddCaptionDate("Review:", SecurityStmtItemStandard.ReviewDate)
              .AddCaptionCurrency("Value:", SecurityStmtItemStandard.Value, True)
              .AddCaptionCurrency("Security Value:", SecurityStmtItemStandard.SecurityValue, True)
            End With
        End Select
      End If

      ' Warnings
      .TextAfter = Warnings
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Retrieves Collateral Summary for a Financing Statement for the Australian B2G PPSR.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="financingStatement">
  '''  The Financing Statement to get a Collateral Summary for.
  ''' </param>
  ''' <param name="alwaysIncludeNoResult">
  '''  Will ensure Yes / No fields always display, even if the result is "No". Default behaviour is to hide if result is "No".
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., View Financing Statement page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function SecurityStmt_SecurityRegisterAUCollateralItemSummary(callerScriptInfo As ISScriptExecutionInfo,
                                                                                   financingStatement As ISFinancingStatement,
                                                                          Optional alwaysIncludeNoResult As Boolean = False,
                                                                          Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' SecurityStmt_SecurityRegisterAUCollateralItemSummary
    '
    ' Version 1.00, Last updated 26/08/2021
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.00  26/08/2021  ISS      J026951   Created.         
    ' #################################################################

    Dim SummaryTable As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Success As Boolean

    ' Assume Success
    Success = True

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTable = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Configure Summary Table
    SummaryTable.TableClass = iseSummaryTableClass.Information

    ' Columns
    With SummaryTable.Columns
      .AddText(12).NoBreakChars = 40
      .AddText()
    End With

    ' Validate
    If financingStatement.CollateralItems.Count = 0 Then
      Success = False
      SummaryTable.TextAfter = "{{warning|Financing Statement does not have any Collateral.}}"
    End If

    ' Collateral
    If Success Then
      With financingStatement.CollateralItems(0)
        Select Case .CollateralClass
          Case iseSecurityCollateralClassBase.AU_Com_Agriculture, iseSecurityCollateralClassBase.AU_Com_Agriculture_Crops, iseSecurityCollateralClassBase.AU_Com_Agriculture_Livestock
            ' Agriculture, Agriculture Livestock, Agriculture Crops (Commercial)
            SummaryTable.AddRowCaptionText("Collateral Type:", "Commercial Property")
            SummaryTable.AddRowCaptionText("Collateral Class:", .CollateralClassText)
            SummaryTable.AddRowCaptionText("Description:", .Description)

            SummaryTable.AddRowCaptionBooleanYesNo("Are Proceeds Claimed?:", .ProceedsClaimed, alwaysIncludeNoResult)
            If Len(.ProceedsClaimedDescription) <> 0 Then
              SummaryTable.AddRowCaptionText("Proceeds Claimed Description:", .ProceedsClaimedDescription)
            End If

            SummaryTable.AddRowCaptionBooleanYesNo("Is Purchase Money Security Interest?:", .PurchaseMoneySecurityInterest, alwaysIncludeNoResult)
            SummaryTable.AddRowCaptionBooleanYesNo("Are Assets Subject to Control?:", .AssetSubjectToControl, alwaysIncludeNoResult)
            SummaryTable.AddRowCaptionBooleanYesNo("Is Inventory?:", .Inventory, alwaysIncludeNoResult)
            SummaryTable.AddRowCaptionBooleanYesNo("Is Subordinate?:", .Subordinate, alwaysIncludeNoResult)

          Case iseSecurityCollateralClassBase.AU_Con_Agriculture, iseSecurityCollateralClassBase.AU_Con_Agriculture_Crops, iseSecurityCollateralClassBase.AU_Con_Agriculture_Livestock
            ' Agriculture, Agriculture Livestock, Agriculture Crops (Consumer)
            SummaryTable.AddRowCaptionText("Collateral Type:", "Consumer Property")
            SummaryTable.AddRowCaptionText("Collateral Class:", .CollateralClassText)
            SummaryTable.AddRowCaptionText("Description:", .Description)

            SummaryTable.AddRowCaptionBooleanYesNo("Are Proceeds Claimed?:", .ProceedsClaimed, alwaysIncludeNoResult)
            If Len(.ProceedsClaimedDescription) <> 0 Then
              SummaryTable.AddRowCaptionText("Proceeds Claimed Description:", .ProceedsClaimedDescription)
            End If

            SummaryTable.AddRowCaptionBooleanYesNo("Is Subordinate?:", .Subordinate, alwaysIncludeNoResult)

          Case iseSecurityCollateralClassBase.AU_Com_Aircraft_AircraftEngine, iseSecurityCollateralClassBase.AU_Con_Aircraft_AircraftEngine
            ' Aircraft Engine (Commercial and Consumer)
            If .CollateralClass = iseSecurityCollateralClassBase.AU_Com_Aircraft_AircraftEngine Then
              SummaryTable.AddRowCaptionText("Collateral Type:", "Commercial Property")
            Else
              SummaryTable.AddRowCaptionText("Collateral Type:", "Consumer Property")
            End If

            SummaryTable.AddRowCaptionText("Collateral Class:", .CollateralClassText)
            SummaryTable.AddRowCaptionText("Aircraft Engine Manufacturer's Number:", .ManufacturerSerialNumber)
            SummaryTable.AddRowCaptionText("Manufacturer's Name:", .Make)
            SummaryTable.AddRowCaptionText("Manufacturer's Generic Model Designator:", .Model)

          Case iseSecurityCollateralClassBase.AU_Com_Aircraft_Airframe
            ' Aircraft Airframe (Commercial)
            SummaryTable.AddRowCaptionText("Collateral Type:", "Commercial Property")
            SummaryTable.AddRowCaptionText("Collateral Class:", .CollateralClassText)
            SummaryTable.AddRowCaptionText("Aircraft Nationality:", .Country)
            SummaryTable.AddRowCaptionText("Airframe Manufacturer's Number:", .ManufacturerSerialNumber)
            SummaryTable.AddRowCaptionText("Manufacturer's Name:", .Make)
            SummaryTable.AddRowCaptionText("Manufacturer's Generic Model Designator:", .Model)

            SummaryTable.AddRowCaptionBooleanYesNo("Are Proceeds Claimed?:", .ProceedsClaimed, alwaysIncludeNoResult)
            If Len(.ProceedsClaimedDescription) <> 0 Then
              SummaryTable.AddRowCaptionText("Proceeds Claimed Description:", .ProceedsClaimedDescription)
            End If

            SummaryTable.AddRowCaptionBooleanYesNo("Is Purchase Money Security Interest?:", .PurchaseMoneySecurityInterest, alwaysIncludeNoResult)
            SummaryTable.AddRowCaptionBooleanYesNo("Are Assets Subject to Control?:", .AssetSubjectToControl, alwaysIncludeNoResult)
            SummaryTable.AddRowCaptionBooleanYesNo("Is Inventory?:", .Inventory, alwaysIncludeNoResult)
            SummaryTable.AddRowCaptionBooleanYesNo("Is Subordinate?:", .Subordinate, alwaysIncludeNoResult)

          Case iseSecurityCollateralClassBase.AU_Con_Aircraft_Airframe
            ' Aircraft Airframe (Consumer)
            SummaryTable.AddRowCaptionText("Collateral Type:", "Consumer Property")
            SummaryTable.AddRowCaptionText("Collateral Class:", .CollateralClassText)
            SummaryTable.AddRowCaptionText("Aircraft Nationality:", .Country)
            SummaryTable.AddRowCaptionText("Airframe Manufacturer's Number:", .ManufacturerSerialNumber)
            SummaryTable.AddRowCaptionText("Manufacturer's Name:", .Make)
            SummaryTable.AddRowCaptionText("Manufacturer's Generic Model Designator:", .Model)

            SummaryTable.AddRowCaptionBooleanYesNo("Are Proceeds Claimed?:", .ProceedsClaimed, alwaysIncludeNoResult)
            If Len(.ProceedsClaimedDescription) <> 0 Then
              SummaryTable.AddRowCaptionText("Proceeds Claimed Description:", .ProceedsClaimedDescription)
            End If

            SummaryTable.AddRowCaptionBooleanYesNo("Is Purchase Money Security Interest?:", .PurchaseMoneySecurityInterest, alwaysIncludeNoResult)
            SummaryTable.AddRowCaptionBooleanYesNo("Is Subordinate?:", .Subordinate, alwaysIncludeNoResult)

          Case iseSecurityCollateralClassBase.AU_Com_Aircraft_Helicopter
            ' Aircraft Helicopter (Commercial)
            SummaryTable.AddRowCaptionText("Collateral Type:", "Commercial Property")
            SummaryTable.AddRowCaptionText("Collateral Class:", .CollateralClassText)
            SummaryTable.AddRowCaptionText("Aircraft Nationality:", .Country)
            SummaryTable.AddRowCaptionText("Helicopter Manufacturer's Number:", .ManufacturerSerialNumber)
            SummaryTable.AddRowCaptionText("Manufacturer's Name:", .Make)
            SummaryTable.AddRowCaptionText("Manufacturer's Generic Model Designator:", .Model)

            SummaryTable.AddRowCaptionBooleanYesNo("Are Proceeds Claimed?:", .ProceedsClaimed, alwaysIncludeNoResult)
            If Len(.ProceedsClaimedDescription) <> 0 Then
              SummaryTable.AddRowCaptionText("Proceeds Claimed Description:", .ProceedsClaimedDescription)
            End If

            SummaryTable.AddRowCaptionBooleanYesNo("Is Purchase Money Security Interest?:", .PurchaseMoneySecurityInterest, alwaysIncludeNoResult)
            SummaryTable.AddRowCaptionBooleanYesNo("Are Assets Subject to Control?:", .AssetSubjectToControl, alwaysIncludeNoResult)
            SummaryTable.AddRowCaptionBooleanYesNo("Is Inventory?:", .Inventory, alwaysIncludeNoResult)
            SummaryTable.AddRowCaptionBooleanYesNo("Is Subordinate?:", .Subordinate, alwaysIncludeNoResult)

          Case iseSecurityCollateralClassBase.AU_Con_Aircraft_Helicopter
            ' Aircraft Helicopter (Consumer)
            SummaryTable.AddRowCaptionText("Collateral Type:", "Consumer Property")
            SummaryTable.AddRowCaptionText("Collateral Class:", .CollateralClassText)
            SummaryTable.AddRowCaptionText("Aircraft Nationality:", .Country)
            SummaryTable.AddRowCaptionText("Helicopter Manufacturer's Number:", .ManufacturerSerialNumber)
            SummaryTable.AddRowCaptionText("Manufacturer's Name:", .Make)
            SummaryTable.AddRowCaptionText("Manufacturer's Generic Model Designator:", .Model)

            SummaryTable.AddRowCaptionBooleanYesNo("Are Proceeds Claimed?:", .ProceedsClaimed, alwaysIncludeNoResult)
            If Len(.ProceedsClaimedDescription) <> 0 Then
              SummaryTable.AddRowCaptionText("Proceeds Claimed Description:", .ProceedsClaimedDescription)
            End If

            SummaryTable.AddRowCaptionBooleanYesNo("Is Purchase Money Security Interest?:", .PurchaseMoneySecurityInterest, alwaysIncludeNoResult)
            SummaryTable.AddRowCaptionBooleanYesNo("Is Subordinate?:", .Subordinate, alwaysIncludeNoResult)

          Case iseSecurityCollateralClassBase.AU_Com_Aircraft_SmallAircraft, iseSecurityCollateralClassBase.AU_Con_Aircraft_SmallAircraft
            ' Small Aircraft (Commercial and Consumer)
            If .CollateralClass = iseSecurityCollateralClassBase.AU_Com_Aircraft_AircraftEngine Then
              SummaryTable.AddRowCaptionText("Collateral Type:", "Commercial Property")
            Else
              SummaryTable.AddRowCaptionText("Collateral Type:", "Consumer Property")
            End If

            SummaryTable.AddRowCaptionText("Collateral Class:", .CollateralClassText)
            SummaryTable.AddRowCaptionText("Aircraft Nationality:", .Country)
            SummaryTable.AddRowCaptionText("Aircraft Nationality Code and Registration Mark:", .RegistrationMark)

            SummaryTable.AddRowCaptionBooleanYesNo("Are Proceeds Claimed?:", .ProceedsClaimed, alwaysIncludeNoResult)
            If Len(.ProceedsClaimedDescription) <> 0 Then
              SummaryTable.AddRowCaptionText("Proceeds Claimed Description:", .ProceedsClaimedDescription)
            End If

            SummaryTable.AddRowCaptionBooleanYesNo("Is Purchase Money Security Interest?:", .PurchaseMoneySecurityInterest, alwaysIncludeNoResult)
            SummaryTable.AddRowCaptionBooleanYesNo("Is Subordinate?:", .Subordinate, alwaysIncludeNoResult)

          Case iseSecurityCollateralClassBase.AU_Con_FinancialProperty_ChattelPaper
            ' Financial Property - Chattel Paper (Consumer)
            SummaryTable.AddRowCaptionText("Collateral Type:", "Consumer Property")
            SummaryTable.AddRowCaptionText("Collateral Class:", .CollateralClassText)
            SummaryTable.AddRowCaptionText("Description:", .Description)

            SummaryTable.AddRowCaptionBooleanYesNo("Are Proceeds Claimed?:", .ProceedsClaimed, alwaysIncludeNoResult)
            If Len(.ProceedsClaimedDescription) <> 0 Then
              SummaryTable.AddRowCaptionText("Proceeds Claimed Description:", .ProceedsClaimedDescription)
            End If

          Case iseSecurityCollateralClassBase.AU_Com_FinancialProperty_ChattelPaper
            ' Financial Property - Chattel Paper (Commercial)
            SummaryTable.AddRowCaptionText("Collateral Type:", "Commercial Property")
            SummaryTable.AddRowCaptionText("Collateral Class:", .CollateralClassText)
            SummaryTable.AddRowCaptionText("Description:", .Description)

            SummaryTable.AddRowCaptionBooleanYesNo("Are Proceeds Claimed?:", .ProceedsClaimed, alwaysIncludeNoResult)
            If Len(.ProceedsClaimedDescription) <> 0 Then
              SummaryTable.AddRowCaptionText("Proceeds Claimed Description:", .ProceedsClaimedDescription)
            End If

            SummaryTable.AddRowCaptionBooleanYesNo("Are Assets Subject to Control?:", .AssetSubjectToControl, alwaysIncludeNoResult)
            SummaryTable.AddRowCaptionBooleanYesNo("Is Inventory?:", .Inventory, alwaysIncludeNoResult)
            SummaryTable.AddRowCaptionBooleanYesNo("Is Subordinate?:", .Subordinate, alwaysIncludeNoResult)

          Case iseSecurityCollateralClassBase.AU_Com_FinancialProperty_Currency
            ' Financial Property - Currency (Commercial)
            SummaryTable.AddRowCaptionText("Collateral Type:", "Commercial Property")
            SummaryTable.AddRowCaptionText("Collateral Class:", .CollateralClassText)
            SummaryTable.AddRowCaptionText("Description:", .Description)

            SummaryTable.AddRowCaptionBooleanYesNo("Are Proceeds Claimed?:", .ProceedsClaimed, alwaysIncludeNoResult)
            If Len(.ProceedsClaimedDescription) <> 0 Then
              SummaryTable.AddRowCaptionText("Proceeds Claimed Description:", .ProceedsClaimedDescription)
            End If

            SummaryTable.AddRowCaptionBooleanYesNo("Is Purchase Money Security Interest?:", .PurchaseMoneySecurityInterest, alwaysIncludeNoResult)
            SummaryTable.AddRowCaptionBooleanYesNo("Are Assets Subject to Control?:", .AssetSubjectToControl, alwaysIncludeNoResult)
            SummaryTable.AddRowCaptionBooleanYesNo("Is Inventory?:", .Inventory, alwaysIncludeNoResult)
            SummaryTable.AddRowCaptionBooleanYesNo("Is Subordinate?:", .Subordinate, alwaysIncludeNoResult)

          Case iseSecurityCollateralClassBase.AU_Con_FinancialProperty_Currency
            ' Financial Property - Currency (Consumer)
            SummaryTable.AddRowCaptionText("Collateral Type:", "Consumer Property")
            SummaryTable.AddRowCaptionText("Collateral Class:", .CollateralClassText)
            SummaryTable.AddRowCaptionText("Description:", .Description)

            SummaryTable.AddRowCaptionBooleanYesNo("Are Proceeds Claimed?:", .ProceedsClaimed, alwaysIncludeNoResult)
            If Len(.ProceedsClaimedDescription) <> 0 Then
              SummaryTable.AddRowCaptionText("Proceeds Claimed Description:", .ProceedsClaimedDescription)
            End If

            SummaryTable.AddRowCaptionBooleanYesNo("Is Subordinate?:", .Subordinate, alwaysIncludeNoResult)

          Case iseSecurityCollateralClassBase.AU_Com_FinancialProperty_DocumentOfTitle
            ' Financial Property - Document of Title (Commercial)
            SummaryTable.AddRowCaptionText("Collateral Type:", "Commercial Property")
            SummaryTable.AddRowCaptionText("Collateral Class:", .CollateralClassText)
            SummaryTable.AddRowCaptionText("Description:", .Description)

            SummaryTable.AddRowCaptionBooleanYesNo("Are Proceeds Claimed?:", .ProceedsClaimed, alwaysIncludeNoResult)
            If Len(.ProceedsClaimedDescription) <> 0 Then
              SummaryTable.AddRowCaptionText("Proceeds Claimed Description:", .ProceedsClaimedDescription)
            End If

            SummaryTable.AddRowCaptionBooleanYesNo("Is Purchase Money Security Interest?:", .PurchaseMoneySecurityInterest, alwaysIncludeNoResult)
            SummaryTable.AddRowCaptionBooleanYesNo("Are Assets Subject to Control?:", .AssetSubjectToControl, alwaysIncludeNoResult)
            SummaryTable.AddRowCaptionBooleanYesNo("Is Inventory?:", .Inventory, alwaysIncludeNoResult)
            SummaryTable.AddRowCaptionBooleanYesNo("Is Subordinate?:", .Subordinate, alwaysIncludeNoResult)

          Case iseSecurityCollateralClassBase.AU_Con_FinancialProperty_DocumentOfTitle
            ' Financial Property - Document of Title (Consumer)
            SummaryTable.AddRowCaptionText("Collateral Type:", "Consumer Property")
            SummaryTable.AddRowCaptionText("Collateral Class:", .CollateralClassText)
            SummaryTable.AddRowCaptionText("Description:", .Description)

            SummaryTable.AddRowCaptionBooleanYesNo("Are Proceeds Claimed?:", .ProceedsClaimed, alwaysIncludeNoResult)
            If Len(.ProceedsClaimedDescription) <> 0 Then
              SummaryTable.AddRowCaptionText("Proceeds Claimed Description:", .ProceedsClaimedDescription)
            End If

            SummaryTable.AddRowCaptionBooleanYesNo("Is Subordinate?:", .Subordinate, alwaysIncludeNoResult)

          Case iseSecurityCollateralClassBase.AU_Com_FinancialProperty_IntermediatedSecurity
            ' Financial Property - Intermediated Security (Commercial)
            SummaryTable.AddRowCaptionText("Collateral Type:", "Commercial Property")
            SummaryTable.AddRowCaptionText("Collateral Class:", .CollateralClassText)
            SummaryTable.AddRowCaptionText("Description:", .Description)

            SummaryTable.AddRowCaptionBooleanYesNo("Are Proceeds Claimed?:", .ProceedsClaimed, alwaysIncludeNoResult)
            If Len(.ProceedsClaimedDescription) <> 0 Then
              SummaryTable.AddRowCaptionText("Proceeds Claimed Description:", .ProceedsClaimedDescription)
            End If

            SummaryTable.AddRowCaptionBooleanYesNo("Is Inventory?:", .Inventory, alwaysIncludeNoResult)
            SummaryTable.AddRowCaptionBooleanYesNo("Is Subordinate?:", .Subordinate, alwaysIncludeNoResult)

          Case iseSecurityCollateralClassBase.AU_Con_FinancialProperty_IntermediatedSecurity
            ' Financial Property - Intermediated Security (Consumer)
            SummaryTable.AddRowCaptionText("Collateral Type:", "Consumer Property")
            SummaryTable.AddRowCaptionText("Collateral Class:", .CollateralClassText)
            SummaryTable.AddRowCaptionText("Description:", .Description)

            SummaryTable.AddRowCaptionBooleanYesNo("Are Proceeds Claimed?:", .ProceedsClaimed, alwaysIncludeNoResult)
            If Len(.ProceedsClaimedDescription) <> 0 Then
              SummaryTable.AddRowCaptionText("Proceeds Claimed Description:", .ProceedsClaimedDescription)
            End If

            SummaryTable.AddRowCaptionBooleanYesNo("Is Subordinate?:", .Subordinate, alwaysIncludeNoResult)

          Case iseSecurityCollateralClassBase.AU_Com_FinancialProperty_NegotiableInstrument
            ' Financial Property - Negotiable Instrument (Commercial)
            SummaryTable.AddRowCaptionText("Collateral Type:", "Commercial Property")
            SummaryTable.AddRowCaptionText("Collateral Class:", .CollateralClassText)
            SummaryTable.AddRowCaptionText("Description:", .Description)

            SummaryTable.AddRowCaptionBooleanYesNo("Are Proceeds Claimed?:", .ProceedsClaimed, alwaysIncludeNoResult)
            If Len(.ProceedsClaimedDescription) <> 0 Then
              SummaryTable.AddRowCaptionText("Proceeds Claimed Description:", .ProceedsClaimedDescription)
            End If

            SummaryTable.AddRowCaptionBooleanYesNo("Are Assets Subject to Control?:", .AssetSubjectToControl, alwaysIncludeNoResult)
            SummaryTable.AddRowCaptionBooleanYesNo("Is Subordinate?:", .Subordinate, alwaysIncludeNoResult)

          Case iseSecurityCollateralClassBase.AU_Con_FinancialProperty_NegotiableInstrument
            ' Financial Property - Negotiable Instrument (Consumer)
            SummaryTable.AddRowCaptionText("Collateral Type:", "Consumer Property")
            SummaryTable.AddRowCaptionText("Collateral Class:", .CollateralClassText)
            SummaryTable.AddRowCaptionText("Description:", .Description)

            SummaryTable.AddRowCaptionBooleanYesNo("Are Proceeds Claimed?:", .ProceedsClaimed, alwaysIncludeNoResult)
            If Len(.ProceedsClaimedDescription) <> 0 Then
              SummaryTable.AddRowCaptionText("Proceeds Claimed Description:", .ProceedsClaimedDescription)
            End If

            SummaryTable.AddRowCaptionBooleanYesNo("Is Subordinate?:", .Subordinate, alwaysIncludeNoResult)

          Case iseSecurityCollateralClassBase.AU_Com_FinancialProperty_InvestmentInstrument
            ' Financial Property - Investment Instrument (Commercial)
            SummaryTable.AddRowCaptionText("Collateral Type:", "Commercial Property")
            SummaryTable.AddRowCaptionText("Collateral Class:", .CollateralClassText)
            SummaryTable.AddRowCaptionText("Description:", .Description)

            SummaryTable.AddRowCaptionBooleanYesNo("Are Proceeds Claimed?:", .ProceedsClaimed, alwaysIncludeNoResult)
            If Len(.ProceedsClaimedDescription) <> 0 Then
              SummaryTable.AddRowCaptionText("Proceeds Claimed Description:", .ProceedsClaimedDescription)
            End If

            SummaryTable.AddRowCaptionBooleanYesNo("Are Assets Subject to Control?:", .AssetSubjectToControl, alwaysIncludeNoResult)
            SummaryTable.AddRowCaptionBooleanYesNo("Is Inventory?:", .Inventory, alwaysIncludeNoResult)
            SummaryTable.AddRowCaptionBooleanYesNo("Is Subordinate?:", .Subordinate, alwaysIncludeNoResult)

          Case iseSecurityCollateralClassBase.AU_Con_FinancialProperty_InvestmentInstrument
            ' Financial Property - Negotiable Instrument (Consumer)
            SummaryTable.AddRowCaptionText("Collateral Type:", "Consumer Property")
            SummaryTable.AddRowCaptionText("Collateral Class:", .CollateralClassText)
            SummaryTable.AddRowCaptionText("Description:", .Description)

            SummaryTable.AddRowCaptionBooleanYesNo("Are Proceeds Claimed?:", .ProceedsClaimed, alwaysIncludeNoResult)
            If Len(.ProceedsClaimedDescription) <> 0 Then
              SummaryTable.AddRowCaptionText("Proceeds Claimed Description:", .ProceedsClaimedDescription)
            End If

            SummaryTable.AddRowCaptionBooleanYesNo("Is Subordinate?:", .Subordinate, alwaysIncludeNoResult)

          Case iseSecurityCollateralClassBase.AU_Com_AllPresent, iseSecurityCollateralClassBase.AU_Con_AllPresent
            ' All present and after-acquired property. (Commercial and Consumer)
            If .CollateralClass = iseSecurityCollateralClassBase.AU_Com_AllPresent Then
              SummaryTable.AddRowCaptionText("Collateral Type:", "Commercial Property")
            Else
              SummaryTable.AddRowCaptionText("Collateral Type:", "Consumer Property")
            End If
            SummaryTable.AddRowCaptionText("Collateral Class:", .CollateralClassText)

            SummaryTable.AddRowCaptionBooleanYesNo("Are Proceeds Claimed?:", .ProceedsClaimed, alwaysIncludeNoResult)
            If Len(.ProceedsClaimedDescription) <> 0 Then
              SummaryTable.AddRowCaptionText("Proceeds Claimed Description:", .ProceedsClaimedDescription)
            End If

            SummaryTable.AddRowCaptionBooleanYesNo("Is Subordinate?:", .Subordinate, alwaysIncludeNoResult)

          Case iseSecurityCollateralClassBase.AU_Com_AllPresentExcept, iseSecurityCollateralClassBase.AU_Con_AllPresentExcept
            ' All present and after-acquired property. (Commercial and Consumer)
            If .CollateralClass = iseSecurityCollateralClassBase.AU_Com_AllPresentExcept Then
              SummaryTable.AddRowCaptionText("Collateral Type:", "Commercial Property")
            Else
              SummaryTable.AddRowCaptionText("Collateral Type:", "Consumer Property")
            End If
            SummaryTable.AddRowCaptionText("Collateral Class:", .CollateralClassText)
            SummaryTable.AddRowCaptionText("Description:", .Description)

            SummaryTable.AddRowCaptionBooleanYesNo("Are Proceeds Claimed?:", .ProceedsClaimed, alwaysIncludeNoResult)
            If Len(.ProceedsClaimedDescription) <> 0 Then
              SummaryTable.AddRowCaptionText("Proceeds Claimed Description:", .ProceedsClaimedDescription)
            End If

            SummaryTable.AddRowCaptionBooleanYesNo("Is Subordinate?:", .Subordinate, alwaysIncludeNoResult)

          Case iseSecurityCollateralClassBase.AU_Com_IntangibleProperty_Account
            ' Intangible Property - Account (Commercial)
            SummaryTable.AddRowCaptionText("Collateral Type:", "Commercial Property")
            SummaryTable.AddRowCaptionText("Collateral Class:", .CollateralClassText)
            SummaryTable.AddRowCaptionText("Description:", .Description)

            SummaryTable.AddRowCaptionBooleanYesNo("Are Proceeds Claimed?:", .ProceedsClaimed, alwaysIncludeNoResult)
            If Len(.ProceedsClaimedDescription) <> 0 Then
              SummaryTable.AddRowCaptionText("Proceeds Claimed Description:", .ProceedsClaimedDescription)
            End If

            SummaryTable.AddRowCaptionBooleanYesNo("Are Assets Subject to Control?:", .AssetSubjectToControl, alwaysIncludeNoResult)
            SummaryTable.AddRowCaptionBooleanYesNo("Is Inventory?:", .Inventory, alwaysIncludeNoResult)
            SummaryTable.AddRowCaptionBooleanYesNo("Is Subordinate?:", .Subordinate, alwaysIncludeNoResult)

          Case iseSecurityCollateralClassBase.AU_Con_IntangibleProperty_Account
            ' Intangible Property - Account (Consumer)
            SummaryTable.AddRowCaptionText("Collateral Type:", "Consumer Property")
            SummaryTable.AddRowCaptionText("Collateral Class:", .CollateralClassText)
            SummaryTable.AddRowCaptionText("Description:", .Description)

            SummaryTable.AddRowCaptionBooleanYesNo("Are Proceeds Claimed?:", .ProceedsClaimed, alwaysIncludeNoResult)
            If Len(.ProceedsClaimedDescription) <> 0 Then
              SummaryTable.AddRowCaptionText("Proceeds Claimed Description:", .ProceedsClaimedDescription)
            End If

            SummaryTable.AddRowCaptionBooleanYesNo("Is Subordinate?:", .Subordinate, alwaysIncludeNoResult)

          Case iseSecurityCollateralClassBase.AU_Com_IntangibleProperty_IntellectualProperty_CircuitLayout, iseSecurityCollateralClassBase.AU_Com_IntangibleProperty_IntellectualProperty, iseSecurityCollateralClassBase.AU_Com_IntangibleProperty_GeneralIntangible, iseSecurityCollateralClassBase.AU_Com_IntangibleProperty_IntellectualProperty_Copyright
            ' Intangible Property - Intellectual Property - Circuit Layout, Copyright and General (Commercial)
            SummaryTable.AddRowCaptionText("Collateral Type:", "Commercial Property")
            SummaryTable.AddRowCaptionText("Collateral Class:", .CollateralClassText)
            SummaryTable.AddRowCaptionText("Description:", .Description)

            SummaryTable.AddRowCaptionBooleanYesNo("Are Proceeds Claimed?:", .ProceedsClaimed, alwaysIncludeNoResult)
            If Len(.ProceedsClaimedDescription) <> 0 Then
              SummaryTable.AddRowCaptionText("Proceeds Claimed Description:", .ProceedsClaimedDescription)
            End If

            SummaryTable.AddRowCaptionBooleanYesNo("Is Purchase Money Security Interest?:", .PurchaseMoneySecurityInterest, alwaysIncludeNoResult)
            SummaryTable.AddRowCaptionBooleanYesNo("Are Assets Subject to Control?:", .AssetSubjectToControl, alwaysIncludeNoResult)
            SummaryTable.AddRowCaptionBooleanYesNo("Is Inventory?:", .Inventory, alwaysIncludeNoResult)
            SummaryTable.AddRowCaptionBooleanYesNo("Is Subordinate?:", .Subordinate, alwaysIncludeNoResult)

          Case iseSecurityCollateralClassBase.AU_Con_IntangibleProperty_IntellectualProperty_CircuitLayout, iseSecurityCollateralClassBase.AU_Con_IntangibleProperty_GeneralIntangible, iseSecurityCollateralClassBase.AU_Con_IntangibleProperty_IntellectualProperty_Copyright
            ' Intangible Property - Intellectual Property - Circuit Layout, Copyright and General (Consumer)
            SummaryTable.AddRowCaptionText("Collateral Type:", "Consumer Property")
            SummaryTable.AddRowCaptionText("Collateral Class:", .CollateralClassText)
            SummaryTable.AddRowCaptionText("Description:", .Description)

            SummaryTable.AddRowCaptionBooleanYesNo("Are Proceeds Claimed?:", .ProceedsClaimed, alwaysIncludeNoResult)
            If Len(.ProceedsClaimedDescription) <> 0 Then
              SummaryTable.AddRowCaptionText("Proceeds Claimed Description:", .ProceedsClaimedDescription)
            End If

            SummaryTable.AddRowCaptionBooleanYesNo("Is Subordinate?:", .Subordinate, alwaysIncludeNoResult)

          Case iseSecurityCollateralClassBase.AU_Com_IntangibleProperty_IntellectualProperty_Patent
            ' Intangible Property - Intellectual Property - Patent (Commercial)
            SummaryTable.AddRowCaptionText("Collateral Type:", "Commercial Property")
            SummaryTable.AddRowCaptionText("Collateral Class:", .CollateralClassText)
            SummaryTable.AddRowCaptionText("Description:", .Description)
            SummaryTable.AddRowCaptionText("Patent Number:", .IdentifyingNumbers)

            SummaryTable.AddRowCaptionBooleanYesNo("Are Proceeds Claimed?:", .ProceedsClaimed, alwaysIncludeNoResult)
            If Len(.ProceedsClaimedDescription) <> 0 Then
              SummaryTable.AddRowCaptionText("Proceeds Claimed Description:", .ProceedsClaimedDescription)
            End If

            SummaryTable.AddRowCaptionBooleanYesNo("Is Purchase Money Security Interest?:", .PurchaseMoneySecurityInterest, alwaysIncludeNoResult)
            SummaryTable.AddRowCaptionBooleanYesNo("Are Assets Subject to Control?:", .AssetSubjectToControl, alwaysIncludeNoResult)
            SummaryTable.AddRowCaptionBooleanYesNo("Is Inventory?:", .Inventory, alwaysIncludeNoResult)
            SummaryTable.AddRowCaptionBooleanYesNo("Is Subordinate?:", .Subordinate, alwaysIncludeNoResult)

          Case iseSecurityCollateralClassBase.AU_Con_IntangibleProperty_IntellectualProperty_Patent
            ' Intangible Property - Intellectual Property - Patent (Consumer)
            SummaryTable.AddRowCaptionText("Collateral Type:", "Consumer Property")
            SummaryTable.AddRowCaptionText("Collateral Class:", .CollateralClassText)
            SummaryTable.AddRowCaptionText("Description:", .Description)
            SummaryTable.AddRowCaptionText("Patent Number:", .IdentifyingNumbers)

            SummaryTable.AddRowCaptionBooleanYesNo("Are Proceeds Claimed?:", .ProceedsClaimed, alwaysIncludeNoResult)
            If Len(.ProceedsClaimedDescription) <> 0 Then
              SummaryTable.AddRowCaptionText("Proceeds Claimed Description:", .ProceedsClaimedDescription)
            End If

            SummaryTable.AddRowCaptionBooleanYesNo("Is Subordinate?:", .Subordinate, alwaysIncludeNoResult)

          Case iseSecurityCollateralClassBase.AU_Com_IntangibleProperty_IntellectualProperty_Design
            ' Intangible Property - Intellectual Property - Design (Commercial)
            SummaryTable.AddRowCaptionText("Collateral Type:", "Commercial Property")
            SummaryTable.AddRowCaptionText("Collateral Class:", .CollateralClassText)
            SummaryTable.AddRowCaptionText("Description:", .Description)
            SummaryTable.AddRowCaptionText("Design Number:", .IdentifyingNumbers)

            SummaryTable.AddRowCaptionBooleanYesNo("Are Proceeds Claimed?:", .ProceedsClaimed, alwaysIncludeNoResult)
            If Len(.ProceedsClaimedDescription) <> 0 Then
              SummaryTable.AddRowCaptionText("Proceeds Claimed Description:", .ProceedsClaimedDescription)
            End If

            SummaryTable.AddRowCaptionBooleanYesNo("Is Purchase Money Security Interest?:", .PurchaseMoneySecurityInterest, alwaysIncludeNoResult)
            SummaryTable.AddRowCaptionBooleanYesNo("Are Assets Subject to Control?:", .AssetSubjectToControl, alwaysIncludeNoResult)
            SummaryTable.AddRowCaptionBooleanYesNo("Is Inventory?:", .Inventory, alwaysIncludeNoResult)
            SummaryTable.AddRowCaptionBooleanYesNo("Is Subordinate?:", .Subordinate, alwaysIncludeNoResult)

          Case iseSecurityCollateralClassBase.AU_Con_IntangibleProperty_IntellectualProperty_Design
            ' Intangible Property - Intellectual Property - Design (Consumer)
            SummaryTable.AddRowCaptionText("Collateral Type:", "Consumer Property")
            SummaryTable.AddRowCaptionText("Collateral Class:", .CollateralClassText)
            SummaryTable.AddRowCaptionText("Description:", .Description)
            SummaryTable.AddRowCaptionText("Design Number:", .IdentifyingNumbers)

            SummaryTable.AddRowCaptionBooleanYesNo("Are Proceeds Claimed?:", .ProceedsClaimed, alwaysIncludeNoResult)
            If Len(.ProceedsClaimedDescription) <> 0 Then
              SummaryTable.AddRowCaptionText("Proceeds Claimed Description:", .ProceedsClaimedDescription)
            End If

            SummaryTable.AddRowCaptionBooleanYesNo("Is Subordinate?:", .Subordinate, alwaysIncludeNoResult)

          Case iseSecurityCollateralClassBase.AU_Com_IntangibleProperty_IntellectualProperty_PlantBreedersRight
            ' Intangible Property - Intellectual Property - Plant Breeders Rights (Commercial)
            SummaryTable.AddRowCaptionText("Collateral Type:", "Commercial Property")
            SummaryTable.AddRowCaptionText("Collateral Class:", .CollateralClassText)
            SummaryTable.AddRowCaptionText("Description:", .Description)
            SummaryTable.AddRowCaptionText("Plant Breeder's right number:", .IdentifyingNumbers)

            SummaryTable.AddRowCaptionBooleanYesNo("Are Proceeds Claimed?:", .ProceedsClaimed, alwaysIncludeNoResult)
            If Len(.ProceedsClaimedDescription) <> 0 Then
              SummaryTable.AddRowCaptionText("Proceeds Claimed Description:", .ProceedsClaimedDescription)
            End If

            SummaryTable.AddRowCaptionBooleanYesNo("Is Purchase Money Security Interest?:", .PurchaseMoneySecurityInterest, alwaysIncludeNoResult)
            SummaryTable.AddRowCaptionBooleanYesNo("Are Assets Subject to Control?:", .AssetSubjectToControl, alwaysIncludeNoResult)
            SummaryTable.AddRowCaptionBooleanYesNo("Is Inventory?:", .Inventory, alwaysIncludeNoResult)
            SummaryTable.AddRowCaptionBooleanYesNo("Is Subordinate?:", .Subordinate, alwaysIncludeNoResult)

          Case iseSecurityCollateralClassBase.AU_Con_IntangibleProperty_IntellectualProperty_PlantBreedersRight
            ' Intangible Property - Intellectual Property - Plant Breeders Rights (Consumer)
            SummaryTable.AddRowCaptionText("Collateral Type:", "Consumer Property")
            SummaryTable.AddRowCaptionText("Collateral Class:", .CollateralClassText)
            SummaryTable.AddRowCaptionText("Description:", .Description)
            SummaryTable.AddRowCaptionText("Plant Breeder's right number:", .IdentifyingNumbers)

            SummaryTable.AddRowCaptionBooleanYesNo("Are Proceeds Claimed?:", .ProceedsClaimed, alwaysIncludeNoResult)
            If Len(.ProceedsClaimedDescription) <> 0 Then
              SummaryTable.AddRowCaptionText("Proceeds Claimed Description:", .ProceedsClaimedDescription)
            End If

            SummaryTable.AddRowCaptionBooleanYesNo("Is Subordinate?:", .Subordinate, alwaysIncludeNoResult)

          Case iseSecurityCollateralClassBase.AU_Com_IntangibleProperty_IntellectualProperty_Trademark
            ' Intangible Property - Intellectual Property - Trademark (Commercial)
            SummaryTable.AddRowCaptionText("Collateral Type:", "Commercial Property")
            SummaryTable.AddRowCaptionText("Collateral Class:", .CollateralClassText)
            SummaryTable.AddRowCaptionText("Description:", .Description)
            SummaryTable.AddRowCaptionText("Trade Mark number:", .IdentifyingNumbers)

            SummaryTable.AddRowCaptionBooleanYesNo("Are Proceeds Claimed?:", .ProceedsClaimed, alwaysIncludeNoResult)
            If Len(.ProceedsClaimedDescription) <> 0 Then
              SummaryTable.AddRowCaptionText("Proceeds Claimed Description:", .ProceedsClaimedDescription)
            End If

            SummaryTable.AddRowCaptionBooleanYesNo("Is Purchase Money Security Interest?:", .PurchaseMoneySecurityInterest, alwaysIncludeNoResult)
            SummaryTable.AddRowCaptionBooleanYesNo("Are Assets Subject to Control?:", .AssetSubjectToControl, alwaysIncludeNoResult)
            SummaryTable.AddRowCaptionBooleanYesNo("Is Inventory?:", .Inventory, alwaysIncludeNoResult)
            SummaryTable.AddRowCaptionBooleanYesNo("Is Subordinate?:", .Subordinate, alwaysIncludeNoResult)

          Case iseSecurityCollateralClassBase.AU_Con_IntangibleProperty_IntellectualProperty_Trademark
            ' Intangible Property - Intellectual Property - Trademark (Consumer)
            SummaryTable.AddRowCaptionText("Collateral Type:", "Consumer Property")
            SummaryTable.AddRowCaptionText("Collateral Class:", .CollateralClassText)
            SummaryTable.AddRowCaptionText("Description:", .Description)
            SummaryTable.AddRowCaptionText("Trade Mark number:", .IdentifyingNumbers)

            SummaryTable.AddRowCaptionBooleanYesNo("Are Proceeds Claimed?:", .ProceedsClaimed, alwaysIncludeNoResult)
            If Len(.ProceedsClaimedDescription) <> 0 Then
              SummaryTable.AddRowCaptionText("Proceeds Claimed Description:", .ProceedsClaimedDescription)
            End If

            SummaryTable.AddRowCaptionBooleanYesNo("Is Subordinate?:", .Subordinate, alwaysIncludeNoResult)

          Case iseSecurityCollateralClassBase.AU_Com_MotorVehicle, iseSecurityCollateralClassBase.AU_Con_MotorVehicle
            ' Motor Vehicle (Commercial and Consumer)
            If .CollateralClass = iseSecurityCollateralClassBase.AU_Com_MotorVehicle Then
              SummaryTable.AddRowCaptionText("Collateral Type:", "Commercial Property")
            Else
              SummaryTable.AddRowCaptionText("Collateral Type:", "Consumer Property")
            End If
            SummaryTable.AddRowCaptionText("Collateral Class:", .CollateralClassText)
            If Len(.Description) <> 0 Then SummaryTable.AddRowCaptionText("Description:", .Description)

            ' Register Serial Number Type
            Select Case .RegisterSerialNumberType
              Case iseRegisterSerialNumberType.AU_MotorVehicle_Chassis
                SummaryTable.AddRowCaptionText("Chassis number:", .Chassis)
              Case iseRegisterSerialNumberType.AU_MotorVehicle_VIN
                SummaryTable.AddRowCaptionText("VIN:", .Vin)
              Case iseRegisterSerialNumberType.AU_MotorVehicle_ManufacturersNumber
                SummaryTable.AddRowCaptionText("Manufacturer's Number:", .ManufacturerSerialNumber)
              Case iseRegisterSerialNumberType.None
                ' Nothing
              Case Else
                SummaryTable.AddRowCaptionText("Unknown Motor Vehicle Type:", .RegisterSerialNumber)
            End Select

            ' Other details
            If Len(.RegistrationNumber) <> 0 Then SummaryTable.AddRowCaptionText("Vehicle Registration Number:", .RegistrationNumber)

            SummaryTable.AddRowCaptionBooleanYesNo("Are Proceeds Claimed?:", .ProceedsClaimed, alwaysIncludeNoResult)
            If Len(.ProceedsClaimedDescription) <> 0 Then
              SummaryTable.AddRowCaptionText("Proceeds Claimed Description:", .ProceedsClaimedDescription)
            End If

            SummaryTable.AddRowCaptionBooleanYesNo("Is Purchase Money Security Interest?:", .PurchaseMoneySecurityInterest, alwaysIncludeNoResult)
            SummaryTable.AddRowCaptionBooleanYesNo("Is Subordinate?:", .Subordinate, alwaysIncludeNoResult)

          Case iseSecurityCollateralClassBase.AU_Com_OtherGood, iseSecurityCollateralClassBase.AU_Com_Agriculture, iseSecurityCollateralClassBase.AU_Com_Agriculture_Crops, iseSecurityCollateralClassBase.AU_Com_Agriculture_Livestock
            ' Other Good, Agriculture, Agriculture Livestock and Agriculture Crops (Commercial)
            SummaryTable.AddRowCaptionText("Collateral Type:", "Commercial Property")
            SummaryTable.AddRowCaptionText("Collateral Class:", .CollateralClassText)
            SummaryTable.AddRowCaptionText("Description:", .Description)

            SummaryTable.AddRowCaptionBooleanYesNo("Are Proceeds Claimed?:", .ProceedsClaimed, alwaysIncludeNoResult)
            If Len(.ProceedsClaimedDescription) <> 0 Then
              SummaryTable.AddRowCaptionText("Proceeds Claimed Description:", .ProceedsClaimedDescription)
            End If

            SummaryTable.AddRowCaptionBooleanYesNo("Is Purchase Money Security Interest?:", .PurchaseMoneySecurityInterest, alwaysIncludeNoResult)
            SummaryTable.AddRowCaptionBooleanYesNo("Are Assets Subject to Control?:", .AssetSubjectToControl, alwaysIncludeNoResult)
            SummaryTable.AddRowCaptionBooleanYesNo("Is Inventory?:", .Inventory, alwaysIncludeNoResult)
            SummaryTable.AddRowCaptionBooleanYesNo("Is Subordinate?:", .Subordinate, alwaysIncludeNoResult)

          Case iseSecurityCollateralClassBase.AU_Con_OtherGood, iseSecurityCollateralClassBase.AU_Con_Agriculture, iseSecurityCollateralClassBase.AU_Con_Agriculture_Crops, iseSecurityCollateralClassBase.AU_Con_Agriculture_Livestock
            ' Other Good, Agriculture, Agriculture Livestock and Agriculture Crops (Consumer)
            SummaryTable.AddRowCaptionText("Collateral Type:", "Consumer Property")
            SummaryTable.AddRowCaptionText("Collateral Class:", .CollateralClassText)
            SummaryTable.AddRowCaptionText("Description:", .Description)

            SummaryTable.AddRowCaptionBooleanYesNo("Are Proceeds Claimed?:", .ProceedsClaimed, alwaysIncludeNoResult)
            If Len(.ProceedsClaimedDescription) <> 0 Then
              SummaryTable.AddRowCaptionText("Proceeds Claimed Description:", .ProceedsClaimedDescription)
            End If

            SummaryTable.AddRowCaptionBooleanYesNo("Is Subordinate?:", .Subordinate, alwaysIncludeNoResult)

          Case iseSecurityCollateralClassBase.AU_Com_Watercraft
            ' Water Craft (Commercial)
            SummaryTable.AddRowCaptionText("Collateral Type:", "Commercial Property")
            SummaryTable.AddRowCaptionText("Collateral Class:", .CollateralClassText)

            ' Register Serial Number Type
            Select Case .RegisterSerialNumberType
              Case iseRegisterSerialNumberType.AU_Watercraft_HIN
                SummaryTable.AddRowCaptionText("HIN:", .Hin)
              Case iseRegisterSerialNumberType.AU_Watercraft_OfficialNumber
                SummaryTable.AddRowCaptionText("Official Number:", .OfficialNumber)
              Case Else
                SummaryTable.AddRowCaptionText("Description:", .Description)
            End Select

            SummaryTable.AddRowCaptionBooleanYesNo("Are Proceeds Claimed?:", .ProceedsClaimed, alwaysIncludeNoResult)
            If Len(.ProceedsClaimedDescription) <> 0 Then
              SummaryTable.AddRowCaptionText("Proceeds Claimed Description:", .ProceedsClaimedDescription)
            End If

            SummaryTable.AddRowCaptionBooleanYesNo("Is Purchase Money Security Interest?:", .PurchaseMoneySecurityInterest, alwaysIncludeNoResult)
            SummaryTable.AddRowCaptionBooleanYesNo("Are Assets Subject to Control?:", .AssetSubjectToControl, alwaysIncludeNoResult)
            SummaryTable.AddRowCaptionBooleanYesNo("Is Inventory?:", .Inventory, alwaysIncludeNoResult)
            SummaryTable.AddRowCaptionBooleanYesNo("Is Subordinate?:", .Subordinate, alwaysIncludeNoResult)

          Case iseSecurityCollateralClassBase.AU_Con_Watercraft
            ' Watercraft (Consumer)
            SummaryTable.AddRowCaptionText("Collateral Type:", "Consumer Property")
            SummaryTable.AddRowCaptionText("Collateral Class:", .CollateralClassText)

            ' Register Serial Number Type
            Select Case .RegisterSerialNumberType
              Case iseRegisterSerialNumberType.AU_Watercraft_HIN
                SummaryTable.AddRowCaptionText("HIN:", .Hin)
              Case iseRegisterSerialNumberType.AU_Watercraft_OfficialNumber
                SummaryTable.AddRowCaptionText("Official Number:", .OfficialNumber)
              Case Else
                SummaryTable.AddRowCaptionText("Description:", .Description)
            End Select

            SummaryTable.AddRowCaptionBooleanYesNo("Are Proceeds Claimed?:", .ProceedsClaimed, alwaysIncludeNoResult)
            If Len(.ProceedsClaimedDescription) <> 0 Then
              SummaryTable.AddRowCaptionText("Proceeds Claimed Description:", .ProceedsClaimedDescription)
            End If

            SummaryTable.AddRowCaptionBooleanYesNo("Is Purchase Money Security Interest?:", .PurchaseMoneySecurityInterest, alwaysIncludeNoResult)
            SummaryTable.AddRowCaptionBooleanYesNo("Is Subordinate?:", .Subordinate, alwaysIncludeNoResult)

          Case Else
            ' Fallback
            SummaryTable.AddRowCaptionText("Collateral Type:", "Unknown")
            SummaryTable.AddRowCaptionText("Collateral Class:", .CollateralClassText)
            SummaryTable.AddRowCaptionText("Description:", .Description)
        End Select

        ' Earlier Registration Id
        If Len(.RegisterPriorReference) <> 0 Then
          SummaryTable.AddRowCaptionText("Earlier Registration:", .RegisterPriorReference)
        End If
      End With
    End If

    ' Add to Summary Tables
    SummaryTables.Add("CollateralSummary", SummaryTable)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Security Statement Security Register AU Summary (Version 1.01, Last updated 5/05/2021).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="securityStmt">
  '''  The Security Statement to summarise.
  ''' </param>
  ''' <param name="currentOnly">
  '''  Indicates whether to display Current Items only.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Security Statement Key Details page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function SecurityStmt_SecurityRegisterAUSummary(callerScriptInfo As ISScriptExecutionInfo,
                                                                     securityStmt As finSecurityStmt,
                                                            Optional currentOnly As Boolean = True,
                                                            Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim Include As Boolean
    Dim IncludePPSR As Boolean
    Dim IsCommercial As Boolean
    Dim IsConsumer As Boolean
    Dim SecurityStmtItem As finSecurityStmtItemBase
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()
    IncludePPSR = finBL.Settings.AddOns.SecurityRegisterPPSR
    IsCommercial = False
    IsConsumer = False

    For Each SecurityStmtItem In securityStmt.SecurityItems
      With SecurityStmtItem
        If .Defunct OrElse .TradeIn OrElse (.RegisterStatus = iseSecurityStmtRegisterStatus.NotApplicable) OrElse (.CollateralClassBase = iseSecurityCollateralClassBase.NotApplicable) Then
          ' Not Included
        Else
          If .CollateralClass.IsCollateralItemCommercial Then
            IsCommercial = True
          Else
            IsConsumer = True
          End If
        End If
      End With
    Next

    ' Main
    With SummaryTableMain
      If securityStmt.SecurityItems.Count = 0 Then
        If finBL.Settings.SecurityStmtInsuranceBrokerTerminology Then
          .TextBefore = "{{info|No Policies listed for this Security Statement.}}"
        Else
          .TextBefore = "{{info|No Security Items listed for this Security Statement.}}"
        End If
      ElseIf Not securityStmt.HasSecuredItems Then
        If finBL.Settings.SecurityStmtInsuranceBrokerTerminology Then
          .TextBefore = "{{info|Only Policies not applicable to the PPSR are listed for this Security Statement.}}"
        Else
          .TextBefore = "{{info|Only Security Items not applicable to the PPSR are listed for this Security Statement.}}"
        End If
      Else
        ' Initialise
        .TableClass = iseSummaryTableClass.TabularData
        .Caption = ""
        .AutoStripe = True

        ' Columns
        With .Columns
          .AddText(" ").WidthHtml = "1em"
          If IncludePPSR Then .AddText(" ").WidthHtml = "16px" ' Icon
          .AddText("Description")
          .AddText("Reg Number").WidthHtml = "10em"
          If IsCommercial AndAlso IsConsumer Then
            .AddText("Class")
          ElseIf IsCommercial Then
            .AddText("Commercial Class")
          Else
            .AddText("Consumer Class")
          End If
          .AddText("Status").WidthHtml = "16em"
          .AddText("Action").WidthHtml = "11em"
          .AddDate("Expires").WidthHtml = "6em"
        End With

        ' Show Security Items
        For Each SecurityStmtItem In securityStmt.SecurityItems
          With .Rows.Add().Cells
            ' Include?
            If currentOnly Then
              Include = SecurityStmtItem.IsSecuredItem
            Else
              If SecurityStmtItem.RegisterStatus = iseSecurityStmtRegisterStatus.Registered Then
                Include = True
              ElseIf SecurityStmtItem.CollateralClassBase = iseSecurityCollateralClassBase.NotApplicable Then
                Include = False
              ElseIf SecurityStmtItem.RegisterStatus = iseSecurityStmtRegisterStatus.NotApplicable Then
                Include = False
              ElseIf SecurityStmtItem.TradeIn OrElse SecurityStmtItem.Defunct Then
                Include = False
              Else
                Include = True
              End If
            End If

            If Include Then
              ' Index
              .AddInteger(securityStmt.SecurityItems.IndexOf(SecurityStmtItem) + 1)

              ' Icon and Link
              If IncludePPSR Then
                With .AddWiki("")
                  Select Case SecurityStmtItem.RegisterStatus
                    Case iseSecurityStmtRegisterStatus.Registered
                      .Value = "{{icon|PPSRView_AU}}"
                      .HyperlinkSetApplicationShortcutUrl("app://FormAction?action=PPSRG2BView&stmtId=" & finBL.HtmlEncode(securityStmt.SecurityStmtId) & "&id=" & CStr(SecurityStmtItem.Pk))
                      .Tooltip = "View PPSR Registration"
                  End Select
                End With
              End If

              ' Description
              With .AddText(SecurityStmtItem.Description)
                If SecurityStmtItem.Pk <> 0 Then
                  .HyperlinkSetApplicationShortcutUrl(String.Format("app://FormAction?action=ItemShow&stmtId={0}&id={1}&page=PPSR", finBL.HtmlEncode(securityStmt.SecurityStmtId), SecurityStmtItem.Pk))
                End If
              End With

              ' Reg Number
              .AddText(SecurityStmtItem.RegisterId)

              ' Class
              With .AddText("")
                If IsCommercial AndAlso IsConsumer Then
                  .Value = finBL.SecurityCollateralClasses.ItemByPk(SecurityStmtItem.CollateralClassBase).Description
                Else
                  .Value = finBL.Enums.iseSecurityCollateralClassBase_ToString(SecurityStmtItem.CollateralClassBase)
                End If
              End With

              ' Status
              With .AddWiki("")
                Select Case SecurityStmtItem.RegisterStatus
                  Case iseSecurityStmtRegisterStatus.Discharged, iseSecurityStmtRegisterStatus.Expired
                    .Value = "**" & SecurityStmtItem.RegisterStatusText & "**"
                    .ForegroundColour = "blue"
                    If SecurityStmtItem.RegisterDateDischarged <> Nothing Then
                      .Value &= " on " & finBL.FormatDate(SecurityStmtItem.RegisterDateDischarged, True)
                      .Tooltip = finBL.FormatDateTime(SecurityStmtItem.RegisterDateDischarged, True, True)
                    End If
                  Case iseSecurityStmtRegisterStatus.Registered
                    .Value = "**" & SecurityStmtItem.RegisterStatusText & "**"
                    .ForegroundColour = "green"
                    If SecurityStmtItem.RegisterDateRegistered <> Nothing Then
                      .Value &= " on " & finBL.FormatDate(SecurityStmtItem.RegisterDateRegistered, True)
                      .Tooltip = finBL.FormatDateTime(SecurityStmtItem.RegisterDateRegistered, True, True)
                    End If
                  Case Else
                    .Value = SecurityStmtItem.RegisterStatusText
                End Select
              End With

              ' Action
              With .AddWiki("")
                If SecurityStmtItem.RegisterActionStatus = isefinSecurityStmtRegisterActionStatus.None Then
                  .Value = String.Format("**{0}**", SecurityStmtItem.RegisterActionText)
                Else
                  .Value = String.Format("**{0} ({1})**", SecurityStmtItem.RegisterActionText, SecurityStmtItem.RegisterActionStatusText)
                End If
                .ForegroundColour = "red"
              End With

              ' Expires
              With .AddText("")
                .TextAlign = iseSummaryTableCellTextAlign.Right
                Select Case SecurityStmtItem.RegisterStatus
                  Case iseSecurityStmtRegisterStatus.Registered, iseSecurityStmtRegisterStatus.New, iseSecurityStmtRegisterStatus.Historic
                    .Value = finBL.FormatDate(SecurityStmtItem.RegisterDateExpiry, True)
                    .Tooltip = finBL.FormatDateTime(SecurityStmtItem.RegisterDateExpiry, True, True, False)
                    If finBL.SecurityStmtFunctions.IsFinancingStmtExpiring(SecurityStmtItem.RegisterDateExpiry) Then
                      .CellClass = iseSummaryTableCellClass.NormalBold
                      .ForegroundColour = "red"
                    End If
                End Select
              End With
            End If
          End With
        Next

        ' Warnings
        .TextAfter = "{{info|All dates are shown in **Canberra time** (the time is hidden and can be viewed by hovering over the date).}}"
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Security Statement Summary.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="securityStmt">
  '''  The Security Statement to summarise.
  ''' </param>
  ''' <param name="includeSecurityStmtIdHyperlink">
  '''  Indicates whether to include a hyperlink on the Security Statement Id to show the Security Statements form.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Security Statement Key Details page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''    <item><code>Notes</code><description>Notes (if configured under Global Settings, General, Summary Pages).</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function SecurityStmt_Summary(callerScriptInfo As ISScriptExecutionInfo,
                                                   securityStmt As finSecurityStmt,
                                          Optional includeSecurityStmtIdHyperlink As Boolean = True,
                                          Optional includeActions As Boolean = True,
                                          Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' SecurityStmt_Summary
    '
    ' Version: 1.04 (20/08/2024)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.01  06/03/2015  ISS                  
    '    1.02  07/08/2023  ISS      J031733   Notes added if configured
    '          07/08/2023  ISS      J031731   Support hashtags in Notes
    '          26/09/2023  ISS      J032101   Refactored AddOn checks
    '    1.03  10/05/2024  ISS      J033263   Added Alert Message
    '    1.04  20/08/2024  ISS      J034115   Added Manager
    ' #################################################################

    Dim Notes As String
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTableNotes As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      .Columns.AddText(20)
      .Columns.AddText()

      ' Alert Message
      If Len(securityStmt.AlertMessage) <> 0 Then .TextBefore = "{{alert|" & securityStmt.AlertMessage & "|True}}"

      With .Rows
        ' General
        If Len(securityStmt.SecurityStmtId) = 0 AndAlso securityStmt.AccountApp IsNot Nothing Then
          ' Temporary Security Statement from Account Application
          .AddCaptionText("Code:", "[New]")
        Else
          With .AddCaptionText("Code:", securityStmt.SecurityStmtId)
            If includeSecurityStmtIdHyperlink AndAlso Not securityStmt.IsNew Then
              .Cells(1).HyperlinkSetFormShow("SecurityStmts", securityStmt.SecurityStmtId)
            End If
          End With
        End If
        If finBL.SettingsUser.SecurityShowExternalId Then
          .AddCaptionText("External Id:", securityStmt.ExternalId)
        End If
        .AddCaptionText("Description:", securityStmt.Description, iseSummaryTableCellClass.Highlight1)
        If finBL.SecurityStmtGroups.Count <> 1 Then
          .AddCaptionCodeDescription("Group:", securityStmt.SecurityStmtGroupPk, finBL.SecurityStmtGroups)
        End If

        ' Branch etc
        If finBL.SettingsUser.SummaryPagesShowBranchResolved AndAlso securityStmt.BranchPk <> 0 Then
          With .AddCaptionCodeDescription("Branch:", securityStmt.BranchPk, finBL.Branches).Cells(1)
            If finBL.Settings.AddOns.Entity Then
              .Value &= String.Format(" ({0})", securityStmt.Entity.Name)
            End If
          End With
        End If
        If finBL.SettingsUser.SummaryPagesShowManagerResolved AndAlso securityStmt.ManagerUserPk <> 0 Then
          .AddCaptionCodeDescription("Manager:", securityStmt.ManagerUserId, finBL.Users)
        End If
      End With

      ' Warnings
      .TextAfter = Warnings
    End With

    ' Notes
    If finBL.Settings.SummaryPagesShowNotes AndAlso Len(securityStmt.Notes) <> 0 Then
      SummaryTableNotes = finBL.CreateSummaryTable()

      ' Support hashtagging?
      Notes = securityStmt.Notes
      If finBL.Settings.QuickSearch2SupportHashtags Then
        Notes = finBL.Utilities.ParseHashTags(Notes)
      End If

      ' Main
      With SummaryTableNotes
        ' Initialise
        .TableClass = iseSummaryTableClass.Information
        .Caption = "Notes"
        .Columns.AddText()

        .Rows.AddText(Notes)
      End With
    End If

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)
    If SummaryTableNotes IsNot Nothing Then SummaryTables.Add("Notes", SummaryTableNotes)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Security Statement Item PPSR B2G Summary (Version 1.00, Last updated 06/07/2021).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="securityStmtItem">
  '''  The Security Statement Item.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  Public Overridable Function SecurityStmt_PPSRItemSummaryAU(callerScriptInfo As ISScriptExecutionInfo,
                                                             securityStmtItem As finSecurityStmtItemBase) As ISSummaryTables

    Dim SummaryTable As ISSummaryTable
    Dim SummaryTables As ISSummaryTables

    ' Initialise
    SummaryTable = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    With SummaryTable
      If finBL.CountryCode <> "AU" Then
        .TextBefore = "{{warning|Security Item PPSR Information is only applicable in Australian databases.}}"
      ElseIf securityStmtItem Is Nothing Then
        .TextBefore = "{{warning|Invalid Security Statement Item.}}"
      ElseIf securityStmtItem.RegisterStatus = iseSecurityStmtRegisterStatus.NotApplicable Then
        .TextBefore = "{{info|Not applicable.}}"
      Else
        ' Initialise
        .TableClass = iseSummaryTableClass.Information
        .Caption = ""
        .Columns.AddText(14)
        .Columns.AddText()

        With .Rows
          Select Case securityStmtItem.RegisterStatus
            Case iseSecurityStmtRegisterStatus.Cancelled
              .AddCaptionText("Status:", securityStmtItem.RegisterStatusText)
              .AddCaptionText("Reg No:", securityStmtItem.RegisterId)

            Case iseSecurityStmtRegisterStatus.Discharged, iseSecurityStmtRegisterStatus.Expired
              With .AddCaptionWiki("Status:", "**" & securityStmtItem.RegisterStatusText & "**").Cells(1)
                If securityStmtItem.RegisterDateDischarged <> Nothing Then
                  .Value &= String.Format(" on **{0}**", finBL.FormatDateTimeLong(securityStmtItem.RegisterDateDischarged, False, True))
                End If
              End With
              .AddCaptionText("Reg No:", securityStmtItem.RegisterId)

            Case iseSecurityStmtRegisterStatus.New
              .AddCaptionText("Status:", securityStmtItem.RegisterStatusText)
              If securityStmtItem.RegisterAction <> iseSecurityStmtRegisterAction.None Then
                With .AddCaptionWiki("Action:", "**" & securityStmtItem.RegisterActionText & "**").Cells(1)
                  If securityStmtItem.RegisterActionStatus <> isefinSecurityStmtRegisterActionStatus.None Then
                    .Value &= String.Format(", **{0}**", securityStmtItem.RegisterActionStatusText)
                  End If
                End With
              End If

            Case iseSecurityStmtRegisterStatus.Registered
              With .AddCaptionWiki("Status:", "**" & securityStmtItem.RegisterStatusText & "**").Cells(1)
                If securityStmtItem.RegisterDateRegistered <> Nothing Then
                  .Value &= String.Format(" on **{0}**", finBL.FormatDateTimeLong(securityStmtItem.RegisterDateRegistered, False, True))
                End If
              End With
              If securityStmtItem.RegisterAction <> iseSecurityStmtRegisterAction.None Then
                With .AddCaptionWiki("Action:", "**" & securityStmtItem.RegisterActionText & "**").Cells(1)
                  If securityStmtItem.RegisterActionStatus <> isefinSecurityStmtRegisterActionStatus.None Then
                    .Value &= String.Format(", **{0}**", securityStmtItem.RegisterActionStatusText)
                  End If
                End With
              End If
              .AddCaptionText("Reg No:", securityStmtItem.RegisterId)
              With .AddCaptionDate("Expires:", securityStmtItem.RegisterDateExpiry).Cells(1)
                If securityStmtItem.RegisterDateExpiry <> Nothing AndAlso finBL.TimeZoneFunctions.GetCurrentDatabaseDate() >= securityStmtItem.RegisterDateExpiry Then
                  .CellClass = iseSummaryTableCellClass.WarningBold
                End If
              End With
          End Select
        End With

        .TextAfter = "{{info|All dates are shown in **Canberra time**.}}"
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTable)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Security Statement PPSR Summary.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="securityStmt">
  '''  The Security Statement to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Security Statement Key Details page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function SecurityStmt_PPSRSummary(callerScriptInfo As ISScriptExecutionInfo,
                                                       securityStmt As finSecurityStmt,
                                              Optional includeActions As Boolean = True,
                                              Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' SecurityStmt_PPSRSummary
    '
    ' Version: 1.03 (30/03/2023)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.02  13/02/2019  ISS                  
    '    1.03  30/03/2023  ISS      J030475   Add for other Countries
    ' #################################################################

    Dim DateAsAt As Date
    Dim Include As Boolean
    Dim Index As Integer
    Dim SecurityStmtItem As finSecurityStmtItemBase
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Date As At
    DateAsAt = finBL.TimeZoneFunctions.GetCurrentDatabaseDate()

    ' Main
    With SummaryTableMain
      Select Case finBL.CountryCode
        Case "AU"
          ' =========
          ' Australia
          ' =========
          If securityStmt.SecurityItems.Count = 0 Then
            If finBL.Settings.SecurityStmtInsuranceBrokerTerminology Then
              .TextBefore = "{{info|No Policies listed for this Security Statement.}}"
            Else
              .TextBefore = "{{info|No Security Items listed for this Security Statement.}}"
            End If
          ElseIf Not securityStmt.HasSecuredItems Then
            If finBL.Settings.SecurityStmtInsuranceBrokerTerminology Then
              .TextBefore = "{{info|Only Policies not applicable to the PPSR are listed for this Security Statement.}}"
            Else
              .TextBefore = "{{info|Only Security Items not applicable to the PPSR are listed for this Security Statement.}}"
            End If
          Else
            ' Initialise
            .TableClass = iseSummaryTableClass.TabularData
            .Caption = ""
            .AutoStripe = True

            ' Columns
            With .Columns
              .AddInteger("#", 1)
              .AddCode(" ", 1).TextAlign = iseSummaryTableCellTextAlign.Center  ' Icon
              .AddText("Description")
              .AddText("Status", 12)
              .AddText("Action", 12)
              .AddText("Action Status", 12)
            End With

            With .Rows
              Index = 0
              For Each SecurityStmtItem In securityStmt.SecurityItems
                ' Index
                Index += 1

                ' Include?
                Include = SecurityStmtItem.IsSecuredItem

                ' Add Row
                If Include Then
                  With .Add().Cells
                    .AddInteger(Index)
                    If Len(SecurityStmtItem.SecurityType.Icon) = 0 Then
                      .AddText("")
                    Else
                      .AddText("{{icon|SecurityType_" & SecurityStmtItem.SecurityType.Icon & "}}")
                    End If
                    With .AddText(SecurityStmtItem.Description)
                      .HyperlinkSetFormAction("ItemShow", String.Format("id={0}&stmtId={1}", SecurityStmtItem.Pk, finBL.Runtime.HtmlUtilities.UrlEncode(securityStmt.SecurityStmtId)))
                    End With
                    .AddText(SecurityStmtItem.RegisterStatusText)
                    .AddText(SecurityStmtItem.RegisterActionText)
                    .AddText(SecurityStmtItem.RegisterActionStatusText)
                  End With
                End If
              Next
            End With
          End If

        Case "NZ"
          ' ===========
          ' New Zealand
          ' ===========
          If securityStmt.RegisterStatus = iseSecurityStmtRegisterStatus.NotApplicable Then
            SummaryTableMain.TextBefore = "{{info|Not applicable.}}"
          Else
            ' Initialise
            .TableClass = iseSummaryTableClass.Information
            .Caption = ""
            .Columns.AddText(20)
            .Columns.AddText()

            With .Rows
              Select Case securityStmt.RegisterStatus
                Case iseSecurityStmtRegisterStatus.Cancelled
                  .AddCaptionText("Status:", securityStmt.RegisterStatusText)
                  .AddCaptionText("Reg No:", securityStmt.FsId)

                Case iseSecurityStmtRegisterStatus.Discharged, iseSecurityStmtRegisterStatus.Expired
                  With .AddCaptionWiki("Status:", "**" & securityStmt.RegisterStatusText & "**").Cells(1)
                    If securityStmt.DateDischarged <> Nothing Then
                      .Value &= String.Format(" on **{0}**", finBL.FormatDateTimeLong(securityStmt.DateDischarged, False, True))
                    End If
                  End With
                  .AddCaptionText("Reg No:", securityStmt.FsId)

                Case iseSecurityStmtRegisterStatus.New
                  .AddCaptionText("Status:", securityStmt.RegisterStatusText)
                  If securityStmt.RegisterAction <> iseSecurityStmtRegisterAction.None Then
                    With .AddCaptionWiki("Action:", "**" & securityStmt.RegisterActionText & "**").Cells(1)
                      If securityStmt.RegisterActionStatus <> isefinSecurityStmtRegisterActionStatus.None Then
                        .Value &= String.Format(", **{0}**", securityStmt.RegisterActionStatusText)
                      End If
                    End With
                  End If

                Case iseSecurityStmtRegisterStatus.Registered
                  With .AddCaptionWiki("Status:", "**" & securityStmt.RegisterStatusText & "**").Cells(1)
                    If securityStmt.DateRegistered <> Nothing Then
                      .Value &= String.Format(" on **{0}**", finBL.FormatDateTimeLong(securityStmt.DateRegistered, False, True))
                    End If
                  End With
                  If securityStmt.RegisterAction <> iseSecurityStmtRegisterAction.None Then
                    With .AddCaptionWiki("Action:", "**" & securityStmt.RegisterActionText & "**").Cells(1)
                      If securityStmt.RegisterActionStatus <> isefinSecurityStmtRegisterActionStatus.None Then
                        .Value &= String.Format(", **{0}**", securityStmt.RegisterActionStatusText)
                      End If
                    End With
                  End If
                  .AddCaptionText("Reg No:", securityStmt.FsId)
                  With .AddCaptionDate("Expires:", securityStmt.DateExpiry).Cells(1)
                    If securityStmt.DateExpiry <> Nothing AndAlso DateAsAt >= securityStmt.DateExpiry Then
                      .CellClass = iseSummaryTableCellClass.WarningBold
                    End If
                  End With
              End Select
            End With
          End If

        Case Else
          ' =====
          ' Other
          ' =====
          If securityStmt.RegisterStatus = iseSecurityStmtRegisterStatus.NotApplicable Then
            SummaryTableMain.TextBefore = "{{info|Not applicable.}}"
          Else
            ' Initialise
            .TableClass = iseSummaryTableClass.Information
            .Caption = ""
            .Columns.AddText(20)
            .Columns.AddText()

            With .Rows
              Select Case securityStmt.RegisterStatus
                Case iseSecurityStmtRegisterStatus.Cancelled
                  .AddCaptionText("Status:", securityStmt.RegisterStatusText)
                  .AddCaptionText("Reg No:", securityStmt.FsId)

                Case iseSecurityStmtRegisterStatus.Discharged, iseSecurityStmtRegisterStatus.Expired
                  With .AddCaptionWiki("Status:", "**" & securityStmt.RegisterStatusText & "**").Cells(1)
                    If securityStmt.DateDischarged <> Nothing Then
                      .Value &= String.Format(" on **{0}**", finBL.FormatDateTimeLong(securityStmt.DateDischarged, False, True))
                    End If
                  End With
                  .AddCaptionText("Reg No:", securityStmt.FsId)

                Case iseSecurityStmtRegisterStatus.New
                  .AddCaptionText("Status:", securityStmt.RegisterStatusText)

                Case iseSecurityStmtRegisterStatus.Registered
                  With .AddCaptionWiki("Status:", "**" & securityStmt.RegisterStatusText & "**").Cells(1)
                    If securityStmt.DateRegistered <> Nothing Then
                      .Value &= String.Format(" on **{0}**", finBL.FormatDateTimeLong(securityStmt.DateRegistered, False, True))
                    End If
                  End With
                  .AddCaptionText("Reg No:", securityStmt.FsId)
                  With .AddCaptionDate("Expires:", securityStmt.DateExpiry).Cells(1)
                    If securityStmt.DateExpiry <> Nothing AndAlso DateAsAt >= securityStmt.DateExpiry Then
                      .CellClass = iseSummaryTableCellClass.WarningBold
                    End If
                  End With
              End Select
            End With
          End If
      End Select

      ' Warnings
      .TextAfter = Warnings
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Security Statement Security Items
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="securityStmt">
  '''  The Security Statement to summarise.
  ''' </param>
  ''' <param name="showReference">
  '''  Indicates whether to include a 'Reference' column.
  ''' </param>
  ''' <param name="showTradeIn">
  '''  Indicates whether to include a 'Trade In' column.
  ''' </param>
  ''' <param name="showDefunct">
  '''  Indicates whether to include a 'Defunct' column.
  ''' </param>
  ''' <param name="includeTradeIns">
  '''  Indicates whether to Include Trade In Items.
  ''' </param>
  ''' <param name="includeDefunct">
  '''  Indicates whether to Include Defunct Items.
  ''' </param>
  ''' <param name="includeRegisterStatusNa">
  '''  Indicates whether to Include Items with a Register Status of 'Not Applicable'.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="maxDisplayRows">
  '''  The Maximum number of Rows to Display in the table before a 'Show Hidden' link is displayed.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Security Statement Key Details pages and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function SecurityStmt_SecurityItems(callerScriptInfo As ISScriptExecutionInfo,
                                                         securityStmt As finSecurityStmt,
                                                Optional showReference As Boolean = True,
                                                Optional showTradeIn As Boolean = False,
                                                Optional showDefunct As Boolean = False,
                                                Optional includeTradeIns As Boolean = True,
                                                Optional includeDefunct As Boolean = False,
                                                Optional includeRegisterStatusNa As Boolean = False,
                                                Optional maxDisplayRows As Integer = 20,
                                                Optional includeActions As Boolean = True,
                                                Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' SecurityStmt_SecurityItems
    '
    ' Version: 1.01 (31/01/2023)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.00  08/11/2013  ISS      
    '    1.01  31/01/2023  ISS      J028790   Created
    ' #################################################################

    Dim SecurityStmtItem As finSecurityStmtItemBase
    Dim Include As Boolean
    Dim IncludeColumnMonitoring As Boolean
    Dim Index As Integer
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Columns
    IncludeColumnMonitoring = False
    If finBL.SecurityEnquiry.Service_InfoAgent.IsMonitoringUsed() Then
      For Each SecurityStmtItem In securityStmt.SecurityItems
        If SecurityStmtItem.MonitorType <> isefinSecurityStmtMonitorType.None Then
          IncludeColumnMonitoring = True
          Exit For
        ElseIf SecurityStmtItem.CanStartMonitoring(iseSecurityEnquiryService.InfoAgent) Then
          IncludeColumnMonitoring = True
          Exit For
        End If
      Next
    End If

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .Caption = ""
      .AutoStripe = True
      .MaxDisplayRows = maxDisplayRows
      .ShowHiddenRowsCaption = "Show More Security Items"

      ' Columns
      If securityStmt.SecurityItems.Count = 0 Then
        If finBL.Settings.SecurityStmtInsuranceBrokerTerminology Then
          .TextBefore = "{{info|No Policies listed for this Security Statement.}}"
        Else
          .TextBefore = "{{info|No Security Items listed for this Security Statement.}}"
        End If
      ElseIf Not includeDefunct AndAlso Not includeTradeIns AndAlso securityStmt.HasOnlyDefunctAndTradeIns Then
        If finBL.Settings.SecurityStmtInsuranceBrokerTerminology Then
          .TextBefore = "{{info|Only Trade-In or Defunct Policies listed for this Security Statement.}}"
        Else
          .TextBefore = "{{info|Only Trade-In or Defunct Security Items listed for this Security Statement.}}"
        End If
      Else
        With .Columns
          .AddInteger("#", 1)
          .AddCode(" ", 1).TextAlign = iseSummaryTableCellTextAlign.Center  ' Icon
          If IncludeColumnMonitoring Then .AddCode(" ", 1).TextAlign = iseSummaryTableCellTextAlign.Center  ' Icon
          .AddCode("Type", 5)
          If showReference Then .AddText("Reference", 10)
          If showTradeIn Then .AddBoolean("Trade-In").NoBreakChars = 10
          If showDefunct Then .AddBoolean("Defunct")
          If finBL.Settings.SecurityStmtInsuranceBrokerTerminology Then
            .AddText("Policy No", 10).NoBreakChars = 20
            .AddText("Description")
            .AddCurrency("Cover")
            .AddCurrency("Premium")
          Else
            .AddText("Serial No", 10).NoBreakChars = 20
            .AddText("Description")
            .AddCurrency("Value")
            .AddCurrency("Security Value").NoBreakChars = 20
          End If
        End With

        With .Rows
          Index = 0
          For Each SecurityStmtItem In securityStmt.SecurityItems
            ' Index
            Index += 1

            ' Include?
            If SecurityStmtItem.RegisterStatus = iseSecurityStmtRegisterStatus.NotApplicable AndAlso Not includeRegisterStatusNa Then
              Include = False
            ElseIf SecurityStmtItem.TradeIn AndAlso Not includeTradeIns Then
              Include = False
            ElseIf SecurityStmtItem.Defunct AndAlso Not includeDefunct Then
              Include = False
            Else
              Include = True
            End If

            ' Add Row
            If Include Then
              With .Add().Cells
                .AddInteger(Index)
                If Len(SecurityStmtItem.SecurityType.Icon) = 0 Then
                  .AddText("")
                Else
                  .AddText("{{icon|SecurityType_" & SecurityStmtItem.SecurityType.Icon & "}}")
                End If
                If IncludeColumnMonitoring Then
                  Select Case SecurityStmtItem.MonitorType
                    Case isefinSecurityStmtMonitorType.Held
                      .AddText("{{icon|Hold}}").Tooltip = "Monitoring is on hold"
                    Case isefinSecurityStmtMonitorType.InfoAgent
                      .AddText("{{icon|Logo_InfoAgent}}").Tooltip = "Monitored by InfoAgent"
                    Case Else
                      If SecurityStmtItem.CanStartMonitoring(iseSecurityEnquiryService.InfoAgent) Then
                        .AddText("{{icon|Blank}}").Tooltip = "Not currently monitored"
                      Else
                        .AddText("")
                      End If
                  End Select
                End If
                .AddText(SecurityStmtItem.SecurityType.DescriptionShortResolved)
                If showReference Then
                  .AddText(SecurityStmtItem.Reference)
                End If
                If showTradeIn Then
                  .AddTick(SecurityStmtItem.TradeIn, , True)
                End If
                If showDefunct Then
                  .AddTick(SecurityStmtItem.Defunct, , True)
                End If
                .AddText(SecurityStmtItem.SerialNumberResolved)
                With .AddText(SecurityStmtItem.Description)
                  If includeActions AndAlso Not SecurityStmtItem.IsNew Then
                    .HyperlinkSetFormAction("ItemShow", String.Format("id={0}&stmtId={1}", SecurityStmtItem.Pk, securityStmt.SecurityStmtId))
                  End If
                End With
                If finBL.Settings.SecurityStmtInsuranceBrokerTerminology Then
                  .AddCurrency(SecurityStmtItem.InsuranceSumInsured)
                  .AddCurrency(SecurityStmtItem.InsurancePremium)
                Else
                  .AddCurrency(SecurityStmtItem.Value)
                  .AddCurrency(SecurityStmtItem.SecurityValue)
                End If
              End With
            End If
          Next
        End With
      End If

      ' Warnings
      .TextAfter = Warnings

      ' Actions
      If includeActions Then
        With .Actions
        End With
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Task Manager Mailbox Item (Version 1.02, Last updated 16/10/2017).
  ''' </summary>
  Public Overridable Function TaskManager_MailboxItemSummary_Item(callerScriptInfo As ISScriptExecutionInfo,
                                                                  mailboxItem As finMailboxItemRO,
                                                         Optional includeActions As Boolean = True,
                                                         Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim ChangeEvent As String
    Dim ChangeEvents As ISList
    Dim Client As finClient
    Dim dr As IDataReader
    Dim EntityName As String
    Dim FormShowSecurityStatementItem As String
    Dim Plate As String
    Dim PlateLine As String
    Dim PPSROwnerPk As Integer
    Dim Properties As ISKeyValueList
    Dim RegisterStatus As iseSecurityStmtRegisterStatus
    Dim RegistrationExpiryDate As Date
    Dim RegistrationLine As String
    Dim SecurityStmt As finSecurityStmt
    Dim SecurityStmtId As String
    Dim SecurityStmtPk As Integer
    Dim sqb As ISSelectQueryBuilder
    Dim strTemp As String
    Dim SummaryTable As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim UpdatePlate As String
    Dim UpdateRegistration As String
    Dim UpdateWOF As String
    Dim Warnings As finWarnings
    Dim WofCofExpiryDate As Date
    Dim WOFLine As String

    ' Initialise
    Client = finBL.CreateClient()
    Properties = finBL.Runtime.CreateKeyValueList()
    SummaryTables = finBL.CreateSummaryTables()
    Warnings = finBL.CreateWarnings()

    SummaryTable = SummaryTables.CreateSummaryTableInformation("", "Item", 2)
    With SummaryTable
      .WidthHtml = "100%"

      ' Deleted
      If mailboxItem.UserDeleted Then
        .TextBefore = "{{warning|Deleted Mail Item}}"
      ElseIf includeActions AndAlso (Not mailboxItem.UserRead) Then
        .Actions.AddApplicationShortcutUrl("MarkAsRead", "Mark as Read", String.Format("App://FormAction?action=MarkAsRead&id={0}&UserPk={1}", mailboxItem.Pk, mailboxItem.UserPk), True)
      End If

      ' Type
      .AddRowCaptionText("Type:", mailboxItem.TypeText)

      ' Subject
      .AddRowCaptionText("Subject:", mailboxItem.Subject)

      ' Date
      Select Case mailboxItem.Type
        Case isefinMailboxItemType.MotorWebAlert
          .AddRowCaptionDate("Date:", mailboxItem.Date, True)
        Case isefinMailboxItemType.NZBNChangeEvent
          .AddRowCaptionDate("Date:", mailboxItem.Date, True)
        Case isefinMailboxItemType.PPSRB2GAUMailboxIncoming
          .AddRowCaptionDateTimeWithTimeZone("Date:", mailboxItem.Date, "2780", True)
        Case Else
          .AddRowCaptionDate("Date:", mailboxItem.Date, True)
      End Select

      ' Importance
      Select Case mailboxItem.Importance
        Case isefinMailboxItemImportance.Medium, isefinMailboxItemImportance.Low
          strTemp = "Priority_Low"
        Case isefinMailboxItemImportance.Critical, isefinMailboxItemImportance.High
          strTemp = "Priority_High"
        Case Else
          strTemp = ""
      End Select
      If Len(strTemp) <> 0 Then
        .AddRowCaptionWiki("Importance:", "**" & mailboxItem.Importance.ToString() & "** {{icon|" & strTemp & "||vertical-align:middle}}")
      End If

      ' Type
      Select Case mailboxItem.Type
        Case isefinMailboxItemType.MotorWebAlert
          ' Properties
          Properties.FromXmlString(mailboxItem.ExtendedData)
          Plate = Properties.GetString("Plate")
          RegistrationExpiryDate = Properties.GetDate("RegistrationExpiryDate")
          WofCofExpiryDate = Properties.GetDate("WofCofExpiryDate")

          If mailboxItem.OwnerPk = 0 Then
            ' If there are possible matches they will appear in the Possible Matches section
            Warnings.AddWarning("Not linked to a Security Statement.", , , isefinWarningLevel.High)
          Else
            Select Case mailboxItem.OwnerType
              Case isefinMailboxItemOwnerType.SecurityStmt
              ' Nothing to do
              Case isefinMailboxItemOwnerType.SecurityStmtItem
                ' Find Security Statement and Item
                sqb = finBL.Database.CreateSelectQueryBuilder()
                sqb.Table = "SecurityStmt"
                sqb.Fields.AddList("SecurityStmt.SecurityStmtId,SecurityStmt.Description,SecurityStmt.Pk")
                sqb.Fields.Add("SecurityStmtItem.Description", "SecurityStmtItemDescription")
                sqb.SqlWhere.AppendComparisonInteger("SecurityStmtItem.Pk", "=", mailboxItem.OwnerPk)
                sqb.Joins.Add("SecurityStmtItem", "SecurityStmt.Pk", "SecurityStmtItem.SecurityStmtPk")

                If sqb.ExecuteDataReader2(dr) Then
                  If dr.Read Then
                    SecurityStmtPk = finBL.Database.GetFieldInteger(dr!Pk)

                    If SecurityStmtPk <> 0 AndAlso mailboxItem.OwnerPk <> 0 Then
                      SecurityStmt = finBL.CreateSecurityStmt()
                      If SecurityStmt.LoadPk(SecurityStmtPk) Then
                        If StrComp(Plate, SecurityStmt.SecurityItems.ItemByPk(mailboxItem.OwnerPk).ItemAsMotorVehicle.RegistrationNumber, CompareMethod.Text) <> 0 Then
                          PlateLine = String.Format(" (Currently {0})", SecurityStmt.SecurityItems.ItemByPk(mailboxItem.OwnerPk).ItemAsMotorVehicle.RegistrationNumber)
                        End If
                        If SecurityStmt.SecurityItems.ItemByPk(mailboxItem.OwnerPk).ItemAsMotorVehicle.RegistrationRenewalDate <> Nothing AndAlso RegistrationExpiryDate.Date > SecurityStmt.SecurityItems.ItemByPk(mailboxItem.OwnerPk).ItemAsMotorVehicle.RegistrationRenewalDate.Date Then
                          RegistrationLine = String.Format(" (Currently {0})", finBL.FormatDateLong(SecurityStmt.SecurityItems.ItemByPk(mailboxItem.OwnerPk).ItemAsMotorVehicle.RegistrationRenewalDate))
                        End If
                        If SecurityStmt.SecurityItems.ItemByPk(mailboxItem.OwnerPk).ItemAsMotorVehicle.WOFRenewalDate <> Nothing AndAlso WofCofExpiryDate.Date > SecurityStmt.SecurityItems.ItemByPk(mailboxItem.OwnerPk).ItemAsMotorVehicle.WOFRenewalDate.Date Then
                          WOFLine = String.Format(" (Currently {0})", finBL.FormatDateLong(SecurityStmt.SecurityItems.ItemByPk(mailboxItem.OwnerPk).ItemAsMotorVehicle.WOFRenewalDate))
                        End If

                        If Len(Plate) <> 0 AndAlso StrComp(Plate, SecurityStmt.SecurityItems.ItemByPk(mailboxItem.OwnerPk).ItemAsMotorVehicle.RegistrationNumber, CompareMethod.Text) <> 0 Then
                          UpdatePlate = String.Format("action=UpdateVehicleDetails&Id={0}&SecurityStmtPk={1}&SecurityStmtItemPk={2}&RegistrationRenewalDate=&WofRenewalDate&Plate={3}", mailboxItem.Pk, SecurityStmtPk, mailboxItem.OwnerPk, Plate)
                        End If
                        If RegistrationExpiryDate <> Nothing AndAlso RegistrationExpiryDate.Date > SecurityStmt.SecurityItems.ItemByPk(mailboxItem.OwnerPk).ItemAsMotorVehicle.RegistrationRenewalDate.Date Then
                          UpdateRegistration = String.Format("action=UpdateVehicleDetails&Id={0}&SecurityStmtPk={1}&SecurityStmtItemPk={2}&RegistrationRenewalDate={3}&WofRenewalDate=&Plate=", mailboxItem.Pk, SecurityStmtPk, mailboxItem.OwnerPk, RegistrationExpiryDate.ToString("o"))
                        End If
                        If WofCofExpiryDate <> Nothing AndAlso WofCofExpiryDate.Date > SecurityStmt.SecurityItems.ItemByPk(mailboxItem.OwnerPk).ItemAsMotorVehicle.WOFRenewalDate.Date Then
                          UpdateWOF = String.Format("action=UpdateVehicleDetails&Id={0}&SecurityStmtPk={1}&SecurityStmtItemPk={2}&RegistrationRenewalDate=&WofRenewalDate={3}&Plate=", mailboxItem.Pk, SecurityStmtPk, mailboxItem.OwnerPk, WofCofExpiryDate.ToString("o"))
                        End If
                      End If
                    End If

                    FormShowSecurityStatementItem = String.Format("form=SecurityStmts&id={0}&ItemId={1}&ItemPage=PPSR", finBL.Database.GetFieldString(dr!SecurityStmtId), mailboxItem.OwnerPk)
                  Else
                    Warnings.AddWarning("Could not find Security Stmt for Security Statement Item " & CStr(mailboxItem.OwnerPk) & ".", , , isefinWarningLevel.High)
                  End If
                  finBL.Database.DataReaderClose(dr)
                End If
            End Select
          End If

          ' Details
          .AddRowCaptionText("Message:", mailboxItem.Message, False)
          .AddRowCaptionText("Financing Statement:", Properties.GetString("FS"), False)
          .AddRowCaptionText("VIN:", Properties.GetString("VIN"), False)

          If Len(Plate) = 0 OrElse Len(PlateLine) = 0 Then
            .AddRowCaptionText("Plate:", Properties.GetString("Plate"), False)
          Else
            .AddRowCaptionWiki("Plate:", String.Format("**{0} --{1}--**", Plate, PlateLine) & "  {{button caption='Update' hyperlink='app://formaction?" & UpdatePlate & "'}}", False, iseSummaryTableCellClass.WarningBold)
          End If

          .AddRowCaptionDate("Plate Effective Date:", Properties.GetDate("PlateEffectiveDate"), False)
          .AddRowCaptionDate("Registration Deregistered Date:", Properties.GetDate("RegistrationDeregisteredDate"), False)

          ' Registration Expiry
          If RegistrationExpiryDate <> Nothing Then
            If Len(RegistrationLine) = 0 Then
              .AddRowCaptionDate("Registration Expiry Date:", RegistrationExpiryDate, False)
            Else
              .AddRowCaptionWiki("Registration Expiry Date:", String.Format("**{0} --{1}--**", finBL.FormatDate(RegistrationExpiryDate, True), RegistrationLine) & "  {{button caption='Update' hyperlink='app://formaction?" & UpdateRegistration & "'}}", False, iseSummaryTableCellClass.WarningBold)
            End If
          End If

          ' WOF COF Expiry
          If WofCofExpiryDate <> Nothing Then
            If Len(WOFLine) = 0 Then
              .AddRowCaptionDate("WOF COF Expiry Date:", WofCofExpiryDate, False)
            Else
              .AddRowCaptionWiki("WOF COF Expiry Date:", String.Format("**{0} --{1}--**", finBL.FormatDate(WofCofExpiryDate, True), WOFLine) & "  {{button caption='Update' hyperlink='app://formaction?" & UpdateWOF & "'}}", False, iseSummaryTableCellClass.WarningBold)
            End If
          End If

        Case isefinMailboxItemType.NZBNChangeEvent
          ' Properties
          Properties.FromXmlString(mailboxItem.ExtendedData)

          ' Change Events
          ChangeEvents = New ISList()
          ChangeEvents.AppendCsvString(Properties.GetString("ChangeEvents"))
          ChangeEvents.Sort()

          strTemp = ""
          For Each ChangeEvent In ChangeEvents
            If Len(strTemp) <> 0 Then strTemp &= vbNewLine
            strTemp &= ChangeEvent
          Next

          ' Entity Name
          EntityName = Properties.GetString("EntityName")

          ' Output
          With .Rows.AddCaptionText("NZBN:", mailboxItem.ExternalId)
            .Cells(1).HyperlinkSetExternal(String.Format("https://www.nzbn.govt.nz/nzbndetails#details={0}", finBL.UrlEncode(mailboxItem.ExternalId)))
          End With
          .AddRowCaptionText("Entity Name:", EntityName)
          .AddRowCaptionWiki("Change Events:", String.Format("**{0}**", strTemp))
          .AddRowCaptionText("Message:", mailboxItem.Message)

          If mailboxItem.OwnerPk <> 0 Then
            Client.LoadPk(mailboxItem.OwnerPk)
            If StrComp(Client.LegalNameResolved, EntityName, CompareMethod.Text) <> 0 Then
              Warnings.AddWarning("The Entity Names are different.", , , isefinWarningLevel.High)
            End If
          End If

        Case isefinMailboxItemType.PPSRB2GAUMailboxIncoming
          ' Properties
          Properties.FromXmlString(mailboxItem.ExtendedData)

          ' Owner
          Select Case mailboxItem.OwnerType
            Case isefinMailboxItemOwnerType.None
              ' Other Type
              .AddRowCaptionText("Message:", mailboxItem.GetMessageText(), False)

            Case isefinMailboxItemOwnerType.SecurityStmtItem
              ' Security Statement Item
              .AddRowCaptionText("Notice Id:", mailboxItem.To)

              If includeActions Then
                If mailboxItem.OwnerPk = 0 Then
                  ' Try again to locate Security Stmt Item
                  If finBL.SecurityRegister.GetSecurityStmtItemPkFromRegistrationNumber(Properties.GetString("RegistrationNumber1", ""), True, PPSROwnerPk, SecurityStmtPk) Then
                    If PPSROwnerPk = 0 Then
                      Warnings.AddWarning("Security Statement Item not found for Registration '" & Properties.GetString("RegistrationNumber1", "") & "'.&nbsp;&nbsp;Manually enter the Registration number onto the correct Security Statement Item then refresh this page.", , , isefinWarningLevel.High)
                    Else
                      ' Security Stmt Item found
                      If Not finBL.Database.GetIdFromPk("SecurityStmt", PPSROwnerPk, SecurityStmtId) Then
                        Warnings.AddWarning("This Mail Item has not been linked to the Security Statement Item " & CStr(PPSROwnerPk) & ".", , , isefinWarningLevel.High)
                      End If
                    End If
                  End If
                Else
                  ' Find Security Stmt Id
                  sqb = finBL.Database.CreateSelectQueryBuilder()
                  sqb.Table = "SecurityStmt"
                  sqb.Fields.AddList("SecurityStmtId,SecurityStmtItem.Description")
                  sqb.SqlWhere.AppendComparisonInteger("SecurityStmtItem.Pk", "=", mailboxItem.OwnerPk)
                  sqb.Joins.Add("SecurityStmtItem", "SecurityStmt.Pk", "SecurityStmtItem.SecurityStmtPk")

                  If sqb.ExecuteDataReader2(dr) Then
                    If dr.Read Then
                      ' DO Nothing
                    Else
                      .AddRowCaptionText("Security Statement Item:", CStr(mailboxItem.OwnerPk))
                      Warnings.AddWarning("Could not find Security Stmt for Security Statement Item " & CStr(mailboxItem.OwnerPk) & ".", , , isefinWarningLevel.High)
                    End If
                    finBL.Database.DataReaderClose(dr)
                  End If
                End If
              End If
          End Select

          ' Status Message and Warnings
          If Len(mailboxItem.StatusMessage) <> 0 Then
            Warnings.AddWarning(mailboxItem.StatusMessage, , , isefinWarningLevel.High)

            Select Case mailboxItem.NotificationType
              Case "VerificationStatementRegistrationRemoved"
                If mailboxItem.OwnerPk <> 0 Then
                  If includeActions AndAlso finBL.SecurityStmtFunctions.GetSecurityStmtItemRegisterStatus(mailboxItem.OwnerPk, RegisterStatus) AndAlso RegisterStatus <> iseSecurityStmtRegisterStatus.Removed Then
                    .Actions.AddApplicationShortcutUrl("UpdateSecurityStatus", "Update Security Item Register Status to Removed", String.Format("App://FormAction?action=UpdateSecurityStatus&Id={0}&ItemId={1}&Status={2}", mailboxItem.Pk, mailboxItem.OwnerPk, iseSecurityStmtRegisterStatus.Removed), True)
                  End If
                End If
            End Select
          End If
      End Select

      ' Attachment
      If mailboxItem.Attachment Then
        If Len(mailboxItem.DocumentFileName) = 0 Then
          .AddRowCaptionText("File Name:", "Attachment not downloaded")
        Else
          With .Rows.AddCaptionText("File Name:", mailboxItem.DocumentFileName)
            .Cells(1).HyperlinkSetExternal(mailboxItem.DocumentFileNameResolved)
          End With
        End If
      End If

      ' Flag
      If Len(mailboxItem.UserFlagColour) <> 0 OrElse Len(mailboxItem.UserFlagNotes) <> 0 Then
        If Len(mailboxItem.UserFlagColour) = 0 Then
          strTemp = ""
        Else
          strTemp = "{{icon|Flag[" & mailboxItem.UserFlagColour & "]||vertical-align:middle}}"
        End If
        If Len(mailboxItem.UserFlagNotes) <> 0 Then
          If Len(strTemp) <> 0 Then strTemp &= " "
          strTemp &= String.Format("**{0}**", mailboxItem.UserFlagNotes)
        End If
        .AddRowCaptionWiki("Flags:", strTemp)
      End If

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

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Task Manager Mailbox Possible Matches (Version 1.01, Last updated 19/05/2017).
  ''' </summary>
  Public Overridable Function TaskManager_MailboxItemSummary_PossibleMatches(callerScriptInfo As ISScriptExecutionInfo,
                                                                             mailboxItem As finMailboxItemRO,
                                                                    Optional includeActions As Boolean = True,
                                                                    Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim PPSROwnerPk As Integer
    Dim Properties As ISKeyValueList
    Dim SecurityStatementMatch As finSecurityStmtMatch
    Dim SecurityStatementMatches As List(Of finSecurityStmtMatch)
    Dim SummaryTable As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warning As String
    Dim SecurityStmtPk As Integer
    Dim SecurityStmtId As String
    Dim SecurityStmt As finSecurityStmt

    ' Initialise
    SummaryTables = finBL.CreateSummaryTables()
    Properties = finBL.Runtime.CreateKeyValueList()

    SummaryTable = SummaryTables.CreateSummaryTableTabular("", "PossibleMatches", 2)
    With SummaryTable
      .WidthHtml = "100%"

      ' Columns
      With .Columns
        .AddText("Security Statement")
        .AddText("Security Item")
        .AddText("Link")
      End With

      Select Case mailboxItem.Type
        Case isefinMailboxItemType.MotorWebAlert
          ' Properties
          Properties.FromXmlString(mailboxItem.ExtendedData)

          If mailboxItem.OwnerPk = 0 Then
            ' Find matches
            If finBL.SecurityRegister.GetSecurityListForFinancingStatement(Properties.GetString("FS"), Properties.GetString("VIN"), Properties.GetString("Plate"), SecurityStatementMatches) Then
              ' Rows
              With .Rows
                For Each SecurityStatementMatch In SecurityStatementMatches
                  With .Add.Cells
                    .AddCodeDescription(SecurityStatementMatch.SecurityStmtId, SecurityStatementMatch.SecurityStmtDescription).HyperlinkSetFormShow("SecurityStmts", SecurityStatementMatch.SecurityStmtId)
                    .AddText(SecurityStatementMatch.SecurityStmtItemDescription).HyperlinkSetApplicationShortcut("FormShow", String.Format("form=SecurityStmts&id={0}&ItemId={1}&ItemPage=PPSR", SecurityStatementMatch.SecurityStmtId, SecurityStatementMatch.SecurityStmtItemPk))
                    If SecurityStatementMatch.SecurityStmtItemPk = 0 Then
                      .AddWiki("{{icon|Link}}").HyperlinkSetFormAction("LinkMailboxItem", String.Format("Id={0}&SecurityStmtPk={1}", mailboxItem.Pk, SecurityStatementMatch.SecurityStmtPk))
                    Else
                      .AddWiki("{{icon|Link}}").HyperlinkSetFormAction("LinkMailboxItem", String.Format("Id={0}&SecurityStmtItemPk={1}", mailboxItem.Pk, SecurityStatementMatch.SecurityStmtItemPk))
                    End If
                  End With
                Next
              End With
            End If
          End If

        Case isefinMailboxItemType.PPSRB2GAUMailboxIncoming
          If mailboxItem.OwnerPk = 0 Then
            ' Try again to locate Security Stmt Item
            If finBL.SecurityRegister.GetSecurityStmtItemPkFromRegistrationNumber(Properties.GetString("RegistrationNumber1", ""), True, PPSROwnerPk, SecurityStmtPk) Then
              If PPSROwnerPk <> 0 Then
                ' Security Stmt Item found
                SecurityStmt = finBL.CreateSecurityStmt()
                If SecurityStmt.LoadPk(SecurityStmtPk) Then

                  ' Rows
                  With .Rows
                    With .Add.Cells

                      .AddCodeDescription(SecurityStmt.SecurityStmtId, SecurityStmt.Description).HyperlinkSetFormShow("SecurityStmts", SecurityStmtId)
                      .AddText(SecurityStmt.SecurityItems.ItemByPk(PPSROwnerPk).Description).HyperlinkSetApplicationShortcut("FormShow", String.Format("form=SecurityStmts&id={0}&ItemId={1}&ItemPage=PPSR", SecurityStmt.SecurityStmtId, PPSROwnerPk))
                      If SecurityStatementMatch.SecurityStmtItemPk = 0 Then
                        .AddWiki("{{icon|Link}}").HyperlinkSetFormAction("LinkMailboxItem", String.Format("Id={0}&SecurityStmtPk={1}", mailboxItem.Pk, PPSROwnerPk))
                      Else
                        .AddWiki("{{icon|Link}}").HyperlinkSetFormAction("LinkMailboxItem", String.Format("Id={0}&SecurityStmtItemPk={1}", mailboxItem.Pk, PPSROwnerPk))
                      End If

                    End With
                  End With

                End If
              End If
            End If

          End If

      End Select

      .TextAfter = Warning
    End With
    SummaryTables.Add("PossibleMatches", SummaryTable)

    Return SummaryTables

  End Function

  Public Overridable Function TaskManager_MailboxItemSummary_SecurityStatement(callerScriptInfo As ISScriptExecutionInfo,
                                                                               mailboxItem As finMailboxItemRO,
                                                                      Optional includeActions As Boolean = True,
                                                                      Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' TaskManager_MailboxItemSummary_SecurityStatement
    '
    ' Version: 1.04 (30/05/2024)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.04  30/05/2024  ISS      J033154   Added Priority Value for Land items             
    ' #################################################################

    Dim dr As IDataReader
    Dim SecurityStmt As finSecurityStmt
    Dim SecurityStmtItemAircraft As finSecurityStmtItemAircraft
    Dim SecurityStmtItemBoat As finSecurityStmtItemBoat
    Dim SecurityStmtItemInvestment As finSecurityStmtItemInvestment
    Dim SecurityStmtItemLand As finSecurityStmtItemLand
    Dim SecurityStmtItemMotorVehicle As finSecurityStmtItemMotorVehicle
    Dim SecurityStmtItemSerialNumberedGood As finSecurityStmtItemSerialNumberedGood
    Dim sqb As ISSelectQueryBuilder
    Dim SummaryTable As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

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

    SummaryTable = SummaryTables.CreateSummaryTableInformation("", "SecurityStatement", 2)
    With SummaryTable
      .WidthHtml = "100%"

      If mailboxItem.OwnerPk <> 0 Then
        Select Case mailboxItem.OwnerType
          Case isefinMailboxItemOwnerType.SecurityStmt
            ' Find Security Statement
            SecurityStmt = finBL.CreateSecurityStmt()
            If SecurityStmt.LoadPk(mailboxItem.OwnerPk) Then

              ' Security Statement
              .AddRowCaptionText("Code:", SecurityStmt.SecurityStmtId)
              If finBL.SettingsUser.SecurityShowExternalId Then
                .AddRowCaptionText("External Id:", SecurityStmt.ExternalId)
              End If
              .AddRowCaptionText("Description:", SecurityStmt.Description, , iseSummaryTableCellClass.Highlight1)
              '                If finBL.SecurityStmtGroups.Count <> 1 Then
              '                  .AddRowCaptionCodeDescription("Group:", SecurityStmt.SecurityStmtGroupPk, finBL.SecurityStmtGroups)
              '                End If
              '                If finBL.SettingsUser.SummaryPagesShowBranchResolved AndAlso securityStmt.BranchPk <> 0 Then
              '                  With .Rows.AddCaptionCodeDescription("Branch:", SecurityStmt.BranchPk, finBL.Branches).Cells(1)
              '                    If finBL.Settings.AddOns.Entity Then
              '                      .Value &= String.Format(" ({0})", SecurityStmt.Entity.Name)
              '                    End If
              '                  End With
              '                End If

              ' Actions
              If includeActions AndAlso SecurityStmt IsNot Nothing AndAlso SecurityStmt.Pk <> 0 Then
                .Actions.AddFormShow("ShowSecurityStmts", "View", "SecurityStmts", True, String.Format("id={0}", SecurityStmt.SecurityStmtId))
              End If
            End If

          Case isefinMailboxItemOwnerType.SecurityStmtItem
            ' Find Security Statement and Item
            sqb = finBL.Database.CreateSelectQueryBuilder()
            sqb.Table = "SecurityStmt"
            sqb.Fields.AddList("SecurityStmt.SecurityStmtId,SecurityStmt.Description,SecurityStmt.Pk")
            sqb.Fields.Add("SecurityStmtItem.Description", "SecurityStmtItemDescription")
            sqb.SqlWhere.AppendComparisonInteger("SecurityStmtItem.Pk", "=", mailboxItem.OwnerPk)
            sqb.Joins.Add("SecurityStmtItem", "SecurityStmt.Pk", "SecurityStmtItem.SecurityStmtPk")

            If sqb.ExecuteDataReader2(dr) Then
              If dr.Read Then
                ' Find Security Statement
                SecurityStmt = finBL.CreateSecurityStmt()
                If SecurityStmt.LoadPk(finBL.Database.GetFieldInteger(dr!Pk)) Then

                  ' Security Statement
                  .AddRowCaptionText("Code:", SecurityStmt.SecurityStmtId)
                  If finBL.SettingsUser.SecurityShowExternalId Then
                    .AddRowCaptionText("External Id:", SecurityStmt.ExternalId)
                  End If
                  .AddRowCaptionText("Description:", SecurityStmt.Description, , iseSummaryTableCellClass.Highlight1)
                  '                If finBL.SecurityStmtGroups.Count <> 1 Then
                  '                  .AddRowCaptionCodeDescription("Group:", SecurityStmt.SecurityStmtGroupPk, finBL.SecurityStmtGroups)
                  '                End If
                  '                If finBL.SettingsUser.SummaryPagesShowBranchResolved AndAlso securityStmt.BranchPk <> 0 Then
                  '                  With .Rows.AddCaptionCodeDescription("Branch:", SecurityStmt.BranchPk, finBL.Branches).Cells(1)
                  '                    If finBL.Settings.AddOns.Entity Then
                  '                      .Value &= String.Format(" ({0})", SecurityStmt.Entity.Name)
                  '                    End If
                  '                  End With
                  '                End If

                  ' Security Type Specific
                  Select Case SecurityStmt.SecurityItems.ItemByPk(mailboxItem.OwnerPk).BaseType
                    Case isefinSecurityBaseType.Aircraft
                      ' ========
                      ' Aircraft
                      ' ========
                      SecurityStmtItemAircraft = SecurityStmt.SecurityItems.ItemByPk(mailboxItem.OwnerPk).ItemAsAircraft
                      .Rows.AddSectionHeading2("Aircraft details")
                      .AddRowCaptionText("Reg Mark:", SecurityStmtItemAircraft.RegistrationMark)
                      .AddRowCaptionText("Manufacturer No:", SecurityStmtItemAircraft.ManufacturerSerialNumber)
                      .AddRowCaptionText("Origin Country:", SecurityStmtItemAircraft.CountryOfOrigin)
                      .AddRowCaptionText("Class:", SecurityStmtItemAircraft.AircraftClass)
                      .AddRowCaptionText("Make:", SecurityStmtItemAircraft.Make)
                      .AddRowCaptionText("Model:", SecurityStmtItemAircraft.Model)
                      If SecurityStmtItemAircraft.Year = 0 Then
                        .AddRowCaptionText("Year:", "")
                      Else
                        .AddRowCaptionText("Year:", CStr(SecurityStmtItemAircraft.Year))
                      End If

                    Case isefinSecurityBaseType.Boat
                      ' ====
                      ' Boat
                      ' ====
                      SecurityStmtItemBoat = SecurityStmt.SecurityItems.ItemByPk(mailboxItem.OwnerPk).ItemAsBoat
                      Select Case finBL.CountryCode
                        Case "AU"
                          .Rows.AddSectionHeading2("Watercraft details")
                        Case Else
                          .Rows.AddSectionHeading2("Boat details")
                      End Select
                      .AddRowCaptionText("Reg No:", SecurityStmtItemBoat.RegistrationNumber)
                      .AddRowCaptionText(finBL.SupportedCountries.CurrentSupportedCountry.Terminology(isefinCountryTerminology.BoatIdentificationNumber, True) & ":", SecurityStmtItemBoat.IdentificationNumber)
                      .AddRowCaptionText("Origin Country:", SecurityStmtItemBoat.CountryOfOrigin)
                      .AddRowCaptionText("Boat Type:", SecurityStmtItemBoat.BoatType)
                      .AddRowCaptionText("Boat Name:", SecurityStmtItemBoat.BoatName)
                      .AddRowCaptionText("HIN:", SecurityStmtItemBoat.HIN)
                      .AddRowCaptionText("Hull Length:", SecurityStmtItemBoat.HullLength)
                      .AddRowCaptionText("Hull Type:", SecurityStmtItemBoat.HullType)
                      .AddRowCaptionText("Make:", SecurityStmtItemBoat.Make)
                      .AddRowCaptionText("Model:", SecurityStmtItemBoat.Model)
                      .AddRowCaptionText("Colour:", SecurityStmtItemBoat.Colour)
                      If SecurityStmtItemBoat.Year = 0 Then
                        .AddRowCaptionText("Year:", "")
                      Else
                        .AddRowCaptionText("Year:", CStr(SecurityStmtItemBoat.Year))
                      End If

                    Case isefinSecurityBaseType.Insurance
                      ' =========
                      ' Insurance
                      ' =========
                      .Rows.AddSectionHeading2("Insurance details")
                      If SecurityStmt.SecurityItems.ItemByPk(mailboxItem.OwnerPk).InsuranceExternalPartyPk = 0 Then
                        .AddRowCaptionText("Company:", SecurityStmt.SecurityItems.ItemByPk(mailboxItem.OwnerPk).InsuranceCompany)
                      Else
                        .AddRowCaptionText("Insurer:", SecurityStmt.SecurityItems.ItemByPk(mailboxItem.OwnerPk).InsuranceExternalPartyId)
                        .AddRowCaptionText("Company:", SecurityStmt.SecurityItems.ItemByPk(mailboxItem.OwnerPk).InsuranceExternalParty.Name)
                      End If
                      .AddRowCaptionText("Type:", SecurityStmt.SecurityItems.ItemByPk(mailboxItem.OwnerPk).InsuranceType)
                      .AddRowCaptionText("Policy No:", SecurityStmt.SecurityItems.ItemByPk(mailboxItem.OwnerPk).InsurancePolicy)
                      .AddRowCaptionCurrency("Cover:", SecurityStmt.SecurityItems.ItemByPk(mailboxItem.OwnerPk).InsuranceSumInsured, True)
                      .AddRowCaptionCurrency("Premium:", SecurityStmt.SecurityItems.ItemByPk(mailboxItem.OwnerPk).InsurancePremium, True)
                      .AddRowCaptionDate("Renewal:", SecurityStmt.SecurityItems.ItemByPk(mailboxItem.OwnerPk).InsuranceRenewalDate)

                    Case isefinSecurityBaseType.Investment
                      ' ==========
                      ' Investment
                      ' ==========
                      SecurityStmtItemInvestment = SecurityStmt.SecurityItems.ItemByPk(mailboxItem.OwnerPk).ItemAsInvestment
                      .Rows.AddSectionHeading2("Investment details")
                      .AddRowCaptionText("Code:", SecurityStmtItemInvestment.InvestmentCode)
                      .AddRowCaptionDate("Valuation Date:", SecurityStmtItemInvestment.ValuationDate)
                      .AddRowCaptionText("Currency:", SecurityStmtItemInvestment.Currency)
                      .AddRowCaptionText("Quantity:", Format(SecurityStmtItemInvestment.Quantity, "###,###,##0"))
                      .AddRowCaptionCurrency("Unit Price:", SecurityStmtItemInvestment.UnitPrice, True)
                      .AddRowCaptionCurrency("Market Value:", SecurityStmtItemInvestment.MarketValue, True)

                      .Rows.AddSectionHeading2("Value Secured")
                      .Rows.AddCaptionPercentage("Percentage:", SecurityStmtItemInvestment.ValuationPercentUse / 100, 2, True)
                      .AddRowCaptionCurrency("Security Value:", SecurityStmtItemInvestment.SecurityValue, True)

                      .Rows.AddSectionHeading2("Review date")
                      .AddRowCaptionDate("Review:", SecurityStmtItemInvestment.ReviewDate)

                    Case isefinSecurityBaseType.Land
                      ' ====
                      ' Land
                      ' ====
                      SecurityStmtItemLand = SecurityStmt.SecurityItems.ItemByPk(mailboxItem.OwnerPk).ItemAsLand
                      .Rows.AddSectionHeading2("Land details")
                      .AddRowCaptionText("Title:", SecurityStmtItemLand.LandTitle)
                      .AddRowCaptionText("Lot:", SecurityStmtItemLand.Lot)
                      .AddRowCaptionText("DP:", SecurityStmtItemLand.DP)
                      .AddRowCaptionText("Zone:", SecurityStmtItemLand.LandZone)
                      .AddRowCaptionText("Land Use:", SecurityStmtItemLand.LandUse)
                      .AddRowCaptionAddressDetailsPhysical("Location:", SecurityStmt.SecurityItems.ItemByPk(mailboxItem.OwnerPk).ToAddressDetails())

                      .Rows.AddSectionHeading2("Mortgage details")
                      .AddRowCaptionText("Type:", SecurityStmtItemLand.MortgageType)
                      .AddRowCaptionText("Registered:", SecurityStmtItemLand.MortgageRegistered)
                      .AddRowCaptionDate("Date Registered:", SecurityStmtItemLand.MortgageRegistrationDate)
                      .AddRowCaptionDate("Date Discharged:", SecurityStmtItemLand.MortgageDischargeDate)
                      .AddRowCaptionCurrency("Priority Value:", SecurityStmtItemLand.PriorityValue)

                    Case isefinSecurityBaseType.MotorVehicle
                      ' =============
                      ' Motor Vehicle
                      ' =============
                      SecurityStmtItemMotorVehicle = SecurityStmt.SecurityItems.ItemByPk(mailboxItem.OwnerPk).ItemAsMotorVehicle
                      .Rows.AddSectionHeading2("Motor Vehicle Identification details")
                      .AddRowCaptionText("Reg No:", SecurityStmtItemMotorVehicle.RegistrationNumber)
                      If finBL.CountryCode = "AU" Then .AddRowCaptionText("State:", SecurityStmtItemMotorVehicle.RegState)
                      .AddRowCaptionText("VIN:", SecurityStmtItemMotorVehicle.VIN)
                      .AddRowCaptionText("Chassis:", SecurityStmtItemMotorVehicle.Chassis)
                      .AddRowCaptionText("Manufacturer No:", SecurityStmtItemMotorVehicle.ManufacturerSerialNumber)
                      .AddRowCaptionText("Engine No:", SecurityStmtItemMotorVehicle.EngineNumber)

                      .Rows.AddSectionHeading2("Other details")
                      .AddRowCaptionText("Vehicle Type:", SecurityStmtItemMotorVehicle.VehicleType)
                      .AddRowCaptionText("Body Style:", SecurityStmtItemMotorVehicle.BodyStyle)
                      .AddRowCaptionText("Make:", SecurityStmtItemMotorVehicle.Make)
                      With .Rows.AddCaptionWiki("Model:", "**" & SecurityStmtItemMotorVehicle.Model & "**").Cells(1)
                        If Len(SecurityStmtItemMotorVehicle.ModelSub) <> 0 Then
                          .Value &= ", **" & SecurityStmtItemMotorVehicle.ModelSub & "**"
                        End If
                      End With
                      .AddRowCaptionText("Colour:", SecurityStmtItemMotorVehicle.Colour)
                      If SecurityStmtItemMotorVehicle.Year = 0 Then
                        .AddRowCaptionText("Year:", "")
                      Else
                        .AddRowCaptionText("Year:", CStr(SecurityStmtItemMotorVehicle.Year))
                      End If

                    Case isefinSecurityBaseType.SerialNumberedGood
                      ' ====================
                      ' Serial Numbered Good
                      ' ====================
                      SecurityStmtItemSerialNumberedGood = SecurityStmt.SecurityItems.ItemByPk(mailboxItem.OwnerPk).ItemAsSerialNumberedGood
                      .Rows.AddSectionHeading2("Serial Numbered Good details")
                      .AddRowCaptionText("Serial No:", SecurityStmtItemSerialNumberedGood.SerialNumber)
                      .AddRowCaptionText("Make:", SecurityStmtItemSerialNumberedGood.Make)
                      With .Rows.AddCaptionWiki("Model:", "**" & SecurityStmtItemSerialNumberedGood.Model & "**").Cells(1)
                        If Len(SecurityStmtItemSerialNumberedGood.ModelSub) <> 0 Then
                          .Value &= ", **" & SecurityStmtItemSerialNumberedGood.ModelSub & "**"
                        End If
                      End With
                      .AddRowCaptionText("Colour:", SecurityStmtItemSerialNumberedGood.Colour)
                      If SecurityStmtItemSerialNumberedGood.Year = 0 Then
                        .AddRowCaptionText("Year:", "")
                      Else
                        .AddRowCaptionText("Year:", CStr(SecurityStmtItemSerialNumberedGood.Year))
                      End If
                      .AddRowCaptionText("Origin Country:", SecurityStmtItemSerialNumberedGood.CountryOfOrigin)
                      .AddRowCaptionText("Description:", SecurityStmtItemSerialNumberedGood.DescriptionGoods)

                    Case isefinSecurityBaseType.Standard
                      ' ========
                      ' Standard
                      ' ========

                    Case Else
                      ' Just in case!
                      Warnings &= "{{warning|No summary is available for this type of Security Item.}}"
                  End Select
                  finBL.Database.DataReaderClose(dr)

                  ' Actions
                  If includeActions AndAlso SecurityStmt IsNot Nothing AndAlso SecurityStmt.Pk <> 0 Then
                    .Actions.AddFormShow("ShowSecurityStmtsId", "View", "SecurityStmts", True, String.Format("id={0}&ItemId={1}&ItemPage=PPSR", SecurityStmt.SecurityStmtId, mailboxItem.OwnerPk))
                  End If
                End If
              End If
            End If
        End Select
      End If

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

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Task Manager Mailbox Users (Version 1.01, Last updated 19/05/2017).
  ''' </summary>
  Public Overridable Function TaskManager_MailboxItemSummary_Users(callerScriptInfo As ISScriptExecutionInfo,
                                                                   mailboxItem As finMailboxItemRO,
                                                          Optional includeActions As Boolean = True,
                                                          Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim dr As IDataReader
    Dim RowClass As iseSummaryTableRowClass
    Dim sqb As ISSelectQueryBuilder
    Dim SummaryTable As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim UserId As String
    Dim UserName As String
    Dim UserPk As Integer
    Dim Warnings As String

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTables = finBL.CreateSummaryTables()

    ' Warnings
    Warnings = ""

    ' Find other Users who have access to this MailboxItem
    sqb = finBL.Database.CreateSelectQueryBuilder()
    With sqb
      .Table = "MailboxItemUser"
      .Fields.AddList("UserPk,ActionDate,ActionCompleteDate,Deleted")
      With .SqlWhere
        .AppendComparisonInteger("MailboxItemPk", "=", mailboxItem.Pk)
      End With
      .OrderByFields.Add("UserPk")
    End With

    SummaryTable = SummaryTables.CreateSummaryTableTabular("", "Users", 2)
    With SummaryTable
      .AutoStripe = True
      .WidthHtml = "100%"

      ' Columns
      With .Columns
        .AddText("User")
        .AddText("Name")
        .AddDate("Action")
        .AddDate("Complete")
        .AddText("Deleted").TextAlign = iseSummaryTableCellTextAlign.Center
      End With

      ' Rows
      With .Rows
        If sqb.ExecuteDataReader2(dr) Then
          Do While dr.Read
            UserPk = finBL.Database.GetFieldInteger(dr!UserPk)

            If finBL.Users.ExistsPk(UserPk) Then
              If UserPk = mailboxItem.UserPk Then
                RowClass = iseSummaryTableRowClass.FooterBold
              Else
                RowClass = iseSummaryTableRowClass.Normal
              End If
              UserId = finBL.Users.ItemByPk(UserPk).UserId
              UserName = finBL.Users.ItemByPk(UserPk).Name
            Else
              RowClass = iseSummaryTableRowClass.Normal
              UserId = CStr(UserPk)
              UserName = "Not Found"
            End If

            With .Add(RowClass).Cells
              .AddText(UserId)
              .AddText(UserName)
              .AddDate(finBL.Database.GetFieldDate(dr!ActionDate), True)
              .AddDate(finBL.Database.GetFieldDate(dr!ActionCompleteDate), True)
              .AddTick(finBL.Database.GetFieldIntegerBoolean(dr!Deleted), False, True)
            End With
          Loop
        Else
          If Len(Warnings) <> 0 Then Warnings &= vbNewLine
          Warnings &= "{{Warning|" & finBL.Error.Message & "}}"
        End If
        finBL.Database.DataReaderClose(dr)
      End With

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

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Task Manager Search Result Summary (Version 1.02, Last updated 03/02/2015).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="searchResult">
  '''  The Search Result or Nothing.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Task Manager Search form.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function TaskManager_SearchResultSummary(callerScriptInfo As ISScriptExecutionInfo,
                                                              searchResult As finTaskManagerSearchResult,
                                                     Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim strTemp As String
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Task As finTask
    Dim TaskManagerAccountApp As finTaskManagerAccountApp
    Dim TaskManagerMonitoredAccount As finTaskManagerMonitoredAccount
    Dim TaskManagerWorkflow As finTaskManagerWorkflow

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    With SummaryTableMain
      If searchResult Is Nothing Then
        ' Help HTML
        strTemp = ""
        strTemp &= "<h1>{{icon|Help}} Task Manager Search</h1>"
        strTemp &= "<p>The following will be matched as you type:</p>"
        strTemp &= "<ul style='padding-left:1.5em'>"
        If finBL.Settings.AddOns.AccountApplication Then
          strTemp &= "<li>Account Applications <small style='color:#808080'>(E.g. codes, description, type)</small></li>"
        End If
        strTemp &= "<li>Folder Names</li>"
        strTemp &= "<li>Tasks <small style='color:#808080'>(E.g. code, subject, type)</small></li>"
        strTemp &= "<li>Monitored Accounts <small style='color:#808080'>(E.g. code, name)</small></li>"
        If finBL.Settings.AddOns.Workflow Then
          strTemp &= "<li>Workflows <small style='color:#808080'>(E.g. codes, description, type)</small></li>"
        End If
        strTemp &= "</ul>"

        strTemp &= "<p>Pressing <b>Enter</b> (or {{icon|Search}}) will perform a more comprehensive search, e.g., folder notes.</p>"

        strTemp &= "<p>Clicking the drilldown ({{icon|Drilldown}}) button more than once will find the next occurrence of that result.</p>"

        .TextAfter = strTemp
      Else
        ' Summarise Search Result

        ' Initialise
        .TableClass = iseSummaryTableClass.Information
        .Caption = ""
        .Columns.AddText(10).NoBreakChars = 20
        .Columns.AddText()

        Select Case searchResult.ObjectType
          Case isefinTaskManagerSearchObjectType.AccountApp
            ' Account Application
            TaskManagerAccountApp = DirectCast(searchResult.SourceObject, finTaskManagerAccountApp)
            With TaskManagerAccountApp
              ' General
              With SummaryTableMain.Rows.AddCaptionText("Application Id:", .AccountAppId)
                .Cells(1).HyperlinkSetFormShow("AccountApps", TaskManagerAccountApp.AccountAppId)
              End With
              SummaryTableMain.Rows.AddCaptionText("Name:", .Name, iseSummaryTableCellClass.Highlight1)
              SummaryTableMain.Rows.AddCaptionCodeDescription("Type:", .AccountAppTypeId, finBL.AccountAppTypes)
              SummaryTableMain.Rows.AddCaptionText("Status:", .AccountAppStatusText)
              If Len(.AccountAppStatusSub) <> 0 Then
                SummaryTableMain.Rows.AddCaptionText("Sub Status:", .AccountAppStatusSub)
              End If
            End With

          Case isefinTaskManagerSearchObjectType.Folder
            ' Folder
            With DirectCast(searchResult.SourceObject, finTaskManagerFolder)
              'SummaryTableMain.Rows.AddCaptionText("Folder Id:", .FolderId)
              SummaryTableMain.Rows.AddCaptionText("Name:", .FolderName, iseSummaryTableCellClass.Highlight1)
              SummaryTableMain.Rows.AddCaptionText("Type:", .FolderTypeText)
            End With

          Case isefinTaskManagerSearchObjectType.MonitoredAccount
            ' Monitored Account
            TaskManagerMonitoredAccount = DirectCast(searchResult.SourceObject, finTaskManagerMonitoredAccount)
            With TaskManagerMonitoredAccount
              ' General
              With SummaryTableMain.Rows.AddCaptionText("Account Id:", .AccountId)
                .Cells(1).HyperlinkSetFormShow("Accounts", TaskManagerMonitoredAccount.AccountId)
              End With
              SummaryTableMain.Rows.AddCaptionText("Name:", .Name, iseSummaryTableCellClass.Highlight1)
              SummaryTableMain.Rows.AddCaptionCodeDescription("Type:", .AccountTypeId, finBL.AccountTypes)
              SummaryTableMain.Rows.AddCaptionText("Status:", .AccountStatusText)
            End With

          Case isefinTaskManagerSearchObjectType.Task
            ' Task
            Task = DirectCast(searchResult.SourceObject, finTask)
            With Task
              ' General
              SummaryTableMain.Rows.AddCaptionText("Task Type:", .TaskTypeText)

              ' General (by task type)
              Select Case .TaskType
                Case isefinTaskType.AccountClosedPendingReviewDate, isefinTaskType.AccountLog, isefinTaskType.AccountPendingWithdrawalReviewDate, isefinTaskType.AccountQuoteOutstanding, isefinTaskType.AccountReadyToOpen, isefinTaskType.AccountReviewDate, isefinTaskType.AccountSuspendReviewDate
                  ' Account
                  With SummaryTableMain.Rows.AddCaptionText("Account Id:", .Code)
                    .Cells(1).HyperlinkSetFormShow("Accounts", Task.Code)
                  End With
                  SummaryTableMain.Rows.AddCaptionText("Name:", .Name, iseSummaryTableCellClass.Highlight1)

                Case isefinTaskType.ClientLog, isefinTaskType.ClientReviewDate
                  ' Client
                  With SummaryTableMain.Rows.AddCaptionText("Client Id:", .Code)
                    .Cells(1).HyperlinkSetFormShow("Clients", Task.Code)
                  End With
                  SummaryTableMain.Rows.AddCaptionText("Name:", .Name, iseSummaryTableCellClass.Highlight1)

                Case isefinTaskType.SecurityStmtLog, isefinTaskType.SecurityStmtReviewDate, isefinTaskType.SecurityStmtItemLog
                  ' Security Statement
                  With SummaryTableMain.Rows.AddCaptionText("Security Stmt Id:", .Code)
                    .Cells(1).HyperlinkSetFormShow("SecurityStmts", Task.Code)
                  End With
                  SummaryTableMain.Rows.AddCaptionText("Description:", .Name, iseSummaryTableCellClass.Highlight1)
              End Select

              ' Task type specific
              Select Case .TaskType
                Case isefinTaskType.AccountLog
                  ' Account Log
                  With SummaryTableMain.Rows.AddCaptionText("Log:", .Subject)
                    .Cells(1).HyperlinkSetFormShow("AccountLog", CStr(Task.Pk))
                  End With

                Case isefinTaskType.ClientLog
                  ' Client Log
                  With SummaryTableMain.Rows.AddCaptionText("Log:", .Subject)
                    .Cells(1).HyperlinkSetFormShow("ClientLog", CStr(Task.Pk))
                  End With

                Case isefinTaskType.SecurityStmtItemLog
                  ' Security Item Log
                  With SummaryTableMain.Rows.AddCaptionText("Log:", .Subject)
                    .Cells(1).HyperlinkSetFormShow("SecurityStmtItemLog", CStr(Task.Pk))
                  End With

                Case isefinTaskType.SecurityStmtLog
                  ' Security Stmt Log
                  With SummaryTableMain.Rows.AddCaptionText("Log:", .Subject)
                    .Cells(1).HyperlinkSetFormShow("SecurityStmtLog", CStr(Task.Pk))
                  End With

                Case isefinTaskType.UserLog
              End Select
            End With

          Case isefinTaskManagerSearchObjectType.Workflow
            ' Workflow
            TaskManagerWorkflow = DirectCast(searchResult.SourceObject, finTaskManagerWorkflow)
            With TaskManagerWorkflow
              ' General
              With SummaryTableMain.Rows.AddCaptionText("Workflow Id:", .WorkflowId)
                .Cells(1).HyperlinkSetFormShow("Workflows", TaskManagerWorkflow.WorkflowId)
              End With
              SummaryTableMain.Rows.AddCaptionText("Description:", .WorkflowDescription, iseSummaryTableCellClass.Highlight1)
              SummaryTableMain.Rows.AddCaptionCodeDescription("Type:", .WorkflowTypeId, finBL.WorkflowTypes)

              ' Target Type-specific
              Select Case TaskManagerWorkflow.TargetObjectType
                Case isefinWorkflowTargetObjectType.Account
                  ' Account
                  With SummaryTableMain.Rows.AddCaptionText("Account Id:", .TargetObjectId)
                    .Cells(1).HyperlinkSetFormShow("Accounts", TaskManagerWorkflow.TargetObjectId)
                  End With
                  SummaryTableMain.Rows.AddCaptionText("Name:", .TargetObjectDescription)
              End Select
            End With

        End Select
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Task Manager Monitored Account History (Version 1.00, Last updated 05/01/2015).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="taskManagerMonitoredAccount">
  '''  The Task Manager Monitored Account.
  ''' </param>
  ''' <param name="view">
  '''  The View to include or a blank String to include all Views (one Summary Table will be generated per View which can be quite slow so is not recommended).
  ''' </param>
  ''' <param name="includeAuditLogs">
  '''  Indicates whether to include Audit Logs.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Previously used in the Task Manager Search form.
  '''   Obsolete, use Events_Summary() instead.
  '''  </para>
  '''  <para>
  '''   Returns one Summary Table per view type, names as per the View:
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function TaskManagerMonitoredAccount_History(callerScriptInfo As ISScriptExecutionInfo,
                                                                  taskManagerMonitoredAccount As finTaskManagerMonitoredAccount,
                                                                  view As String,
                                                                  includeAuditLogs As Boolean,
                                                         Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim List As ISList
    Dim s As String
    Dim SummaryTable As ISSummaryTable
    Dim SummaryTables As ISSummaryTables

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTables = finBL.CreateSummaryTables()

    ' Determine available Views
    If Len(view) = 0 Then
      ' All Views
      List = New ISList("All,Logs,Transactions,Workflows,Other")
    Else
      ' Specified View
      List = New ISList(view)
    End If

    ' Create Summary Tables (one per View)
    For Each s In List
      ' Initialise
      SummaryTable = Nothing

      ' Account Views
      Select Case UCase(s)
        Case "ALL", "LOGS", "OTHER", "TRANSACTIONS", "WORKFLOWS"
          SummaryTable = TaskManager_EventHistory(callerScriptInfo, taskManagerMonitoredAccount.AccountEventHistory, s, includeAuditLogs, otherParameters)
        Case Else
          ' Unhandled View
      End Select

      ' Add Summary Table
      If SummaryTable IsNot Nothing Then SummaryTables.Add(s, SummaryTable)
    Next

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Task Manager Workflow History (Version 1.00, Last updated 05/01/2015).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="taskManagerWorkflow">
  '''  The Task Manager Workflow.
  ''' </param>
  ''' <param name="view">
  '''  The View to include or a blank String to include all Views (one Summary Table will be generated per View which can be quite slow so is not recommended).
  ''' </param>
  ''' <param name="includeAuditLogs">
  '''  Indicates whether to include Audit Logs.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Previously used in the Task Manager Search form.
  '''   Obsolete, use Events_Summary() instead.
  '''  </para>
  '''  <para>
  '''   Returns one Summary Table per view type, names as per the View:
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function TaskManagerWorkflow_History(callerScriptInfo As ISScriptExecutionInfo,
                                                          taskManagerWorkflow As finTaskManagerWorkflow,
                                                          view As String,
                                                          includeAuditLogs As Boolean,
                                                 Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim List As ISList
    Dim s As String
    Dim SummaryTable As ISSummaryTable
    Dim SummaryTables As ISSummaryTables

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTables = finBL.CreateSummaryTables()

    ' Determine available Views
    If Len(view) = 0 Then
      ' All Views
      Select Case taskManagerWorkflow.WorkflowType.TargetObjectType
        Case isefinWorkflowTargetObjectType.Account
          List = New ISList("All,Logs,Transactions,Workflows,Other")
        Case isefinWorkflowTargetObjectType.AccountApp
          List = New ISList("All,Logs,Workflows,Other")
        Case isefinWorkflowTargetObjectType.Client
          List = New ISList("All,Logs,Workflows,Other")
      End Select
    Else
      ' Specified View
      List = New ISList(view)
    End If

    ' Create Summary Tables (one per View)
    For Each s In List
      ' Initialise
      SummaryTable = Nothing

      Select Case taskManagerWorkflow.WorkflowType.TargetObjectType
        Case isefinWorkflowTargetObjectType.Account
          ' Account Views
          Select Case UCase(s)
            Case "ALL", "LOGS", "OTHER", "TRANSACTIONS", "WORKFLOWS"
              SummaryTable = TaskManager_EventHistory(callerScriptInfo, taskManagerWorkflow.WorkflowEventHistory, s, includeAuditLogs, otherParameters)
            Case Else
              ' Unhandled View
          End Select

        Case isefinWorkflowTargetObjectType.AccountApp
          ' Account Application Views
          ' Not yet implemented

        Case isefinWorkflowTargetObjectType.Client
          ' Client Views
          Select Case UCase(s)
            Case "ALL", "LOGS", "OTHER", "WORKFLOWS"
              SummaryTable = TaskManager_EventHistory(callerScriptInfo, taskManagerWorkflow.WorkflowEventHistory, s, includeAuditLogs, otherParameters)
            Case Else
              ' Unhandled View
          End Select
      End Select

      ' Add Summary Table
      If SummaryTable IsNot Nothing Then SummaryTables.Add(s, SummaryTable)
    Next

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Task Manager Workflow History for Account Workflows, custom View (Version 1.00, Last updated 05/01/2014).
  ''' </summary>
  Public Overridable Function TaskManagerWorkflow_History_Client_Custom(callerScriptInfo As ISScriptExecutionInfo,
                                                                        taskManagerWorkflow As finTaskManagerWorkflow,
                                                                        view As String,
                                                                        includeAuditLogs As Boolean,
                                                               Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTable

    Dim SummaryTable As ISSummaryTable

    ' Initialise
    SummaryTable = finBL.CreateSummaryTable()

    'With SummaryTable
    '  .TableClass = iseSummaryTableClass.TabularData
    '  .Caption = "Custom Client View"
    '  With .Columns
    '  End With
    'End With

    Return SummaryTable

  End Function

  ''' <summary>
  '''  Warnings Summary (Version 1.02, Last updated 28/08/2015).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="warnings">
  '''  The Warnings collection to summarise.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Client and Account Key Details pages.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function WarningsSummary(callerScriptInfo As ISScriptExecutionInfo,
                                              warnings As finWarnings,
                                     Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim Categorise As Boolean
    Dim CategoryLast As String
    Dim DetailsWiki As String
    Dim IncludeLevel As Boolean
    Dim LevelColour As String
    Dim RowClass As iseSummaryTableRowClass
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warning As finWarning

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()
    RowClass = iseSummaryTableRowClass.Alt1

    ' Determine Columns to include and whether to Categorise
    CategoryLast = "~"
    For Each Warning In warnings
      If Warning.Level <> isefinWarningLevel.None Then
        IncludeLevel = True
      End If
      If Len(Warning.Category) <> 0 Then
        Categorise = True
      End If
    Next

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      If IncludeLevel Then .Columns.AddCode(1) ' Colour Icon (used to represent Warning level)
      .Columns.AddText()

      For Each Warning In warnings
        With Warning
          ' Category Heading
          If Categorise AndAlso .Category <> CategoryLast Then
            CategoryLast = .Category
            RowClass = iseSummaryTableRowClass.Alt1

            If Len(.Category) = 0 Then
              SummaryTableMain.Rows.AddSectionHeading2("No Category")
            Else
              SummaryTableMain.Rows.AddSectionHeading2(.Category)
            End If
          End If

          ' Level Colour
          If IncludeLevel Then
            Select Case .Level
              Case isefinWarningLevel.Critical : LevelColour = "#C00000"
              Case isefinWarningLevel.High : LevelColour = "red"
              Case isefinWarningLevel.Low : LevelColour = "yellow"
              Case isefinWarningLevel.Medium : LevelColour = "orange"
              Case isefinWarningLevel.None : LevelColour = "white"
              Case Else : LevelColour = ""
            End Select
          End If

          ' Details (use simple Wiki text so we can colour and include hyperlinks)
          If .Level = isefinWarningLevel.Critical Then
            DetailsWiki = "**"
          Else
            DetailsWiki = ""
          End If
          ' Main Source Start (may contain its own Application Shortcut)
          If Len(.MasterTitle) <> 0 Then
            If Len(.MasterApplicationShortcutUrl) = 0 Then
              DetailsWiki &= .MasterTitle
            Else
              DetailsWiki &= "[[app://" & .MasterApplicationShortcutUrl & "|" & .MasterTitle & "]]"
            End If
          End If
          ' Title
          If Len(.Title) <> 0 Then
            If Len(DetailsWiki) <> 0 AndAlso DetailsWiki <> "**" Then DetailsWiki &= vbNewLine
            If Len(.ApplicationShortcutUrl) = 0 Then
              DetailsWiki &= .Title
            Else
              DetailsWiki &= "[[app://" & .ApplicationShortcutUrl & "|" & .Title & "]]"
            End If
          End If
          ' Warning
          If Len(DetailsWiki) <> 0 AndAlso DetailsWiki <> "**" Then DetailsWiki &= vbNewLine
          DetailsWiki &= "!!" & .Warning & "!!"
          If .Level = isefinWarningLevel.Critical Then
            DetailsWiki &= "**"
          End If

          ' Add Row
          With SummaryTableMain.Rows.Add(RowClass).Cells
            If IncludeLevel Then
              .Add("{{colourblock|" & LevelColour & "|" & Warning.Level.ToString() & "}}")
            End If
            .AddWiki(DetailsWiki)
          End With

          ' Alt Row Colouring
          If RowClass = iseSummaryTableRowClass.Alt1 Then
            RowClass = iseSummaryTableRowClass.Alt2
          Else
            RowClass = iseSummaryTableRowClass.Alt1
          End If
        End With
      Next

      ' Warnings
      If .Rows.Count = 0 Then
        .TextAfter = "{{info|No warnings.}}"
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Workflow Summary (Version 1.01, Last updated 19/04/2016).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="workflow">
  '''  The Workflow to summarise.
  ''' </param>
  ''' <param name="includeWorkflowIdHyperlink">
  '''  Indicates whether to include a hyperlink on the Workflow Id to show the Workflows form.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Workflow Key Details page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Workflow_Summary(callerScriptInfo As ISScriptExecutionInfo,
                                               workflow As finWorkflow,
                                      Optional includeWorkflowIdHyperlink As Boolean = True,
                                      Optional includeActions As Boolean = True,
                                      Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim DateAsAtDb As Date
    Dim DateAsAtUtc As Date
    Dim RecallImmediateDetails As String
    Dim strTemp As String
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim UnactionedCount As Integer
    Dim UnpublishedCount As Integer
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Date As At
    DateAsAtDb = finBL.TimeZoneFunctions.GetCurrentDatabaseDate()
    DateAsAtUtc = finBL.TimeZoneFunctions.GetCurrentUtcDateTime()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      .Columns.AddText(16)
      .Columns.AddText()

      With .Rows
        ' General
        With .AddCaptionText("Code:", workflow.WorkflowId)
          If includeWorkflowIdHyperlink Then
            .Cells(1).HyperlinkSetFormShow("Workflows", workflow.WorkflowId)
          End If
        End With
        .AddCaptionText("Description:", workflow.Description, iseSummaryTableCellClass.Highlight1)
        If StrComp(workflow.Description, workflow.WorkflowType.Description, CompareMethod.Text) = 0 Then
          ' Omit Type for compactness if it matches Workflow's Description
        Else
          .AddCaptionCodeDescription("Type:", workflow.WorkflowTypePk, finBL.WorkflowTypes)
        End If

        ' Status
        If workflow.Status = isefinWorkflowStatus.Closed Then
          strTemp = String.Format("(Opened on **{0}**, closed on **{1}**)", finBL.FormatDateLong(workflow.OpenedDate), finBL.FormatDateLong(workflow.ClosedDate))
        Else
          If workflow.RecallImmediate Then
            RecallImmediateDetails = workflow.RecallImmediateDetails
            If Len(RecallImmediateDetails) = 0 Then
              RecallImmediateDetails = "User setting manually"
            Else
              RecallImmediateDetails = Replace(RecallImmediateDetails, vbNewLine, ", ")
            End If
            strTemp = String.Format("!!(Recalled due to: **{0}**)!!", RecallImmediateDetails)
          ElseIf workflow.RecallDate = Nothing Then
            strTemp = ""
          ElseIf workflow.RecallUtcDate < DateAsAtUtc Then
            strTemp = String.Format("!!(Recall date of **{0}** passed)!!", finBL.FormatDateTimeLongWithTimeZone(workflow.RecallTzDate, workflow.RecallTimeZoneId))
          Else
            strTemp = String.Format("(Awaiting recall date of **{0}**)", finBL.FormatDateTimeLongWithTimeZone(workflow.RecallTzDate, workflow.RecallTimeZoneId))
          End If
        End If
        If Len(strTemp) = 0 AndAlso workflow.Status <> isefinWorkflowStatus.Closed Then
          strTemp = String.Format("(Opened on **{0}**)", finBL.FormatDateLong(workflow.OpenedDate))
        End If
        .AddCaptionWiki("Status:", String.Format("**{0}** --{1}--", workflow.StatusTextResolved, strTemp))

        ' Flag
        If Len(workflow.FlagColour) <> 0 OrElse Len(workflow.FlagNotes) <> 0 Then
          ' Flag Icon
          If Len(workflow.FlagColour) = 0 Then
            strTemp = ""
          Else
            strTemp = "{{Flag|" & workflow.FlagColour & "|" & workflow.FlagColour & "}} "
          End If

          ' Flag Notes
          If Len(workflow.FlagNotes) = 0 Then
            ' No Notes
          ElseIf InStr(workflow.FlagNotes, vbNewLine) <> 0 Then
            ' Multi-Line Notes
            strTemp &= " {{popupNote|" & workflow.FlagNotes & "}}"
          Else
            ' Single Line Notes
            strTemp &= " " & workflow.FlagNotes
          End If

          .AddCaptionText("Flag:", strTemp)
        End If

        ' Outcome and other Status-related details
        Select Case workflow.Status
          Case isefinWorkflowStatus.Closed
            If Len(workflow.ClosedOutcome) <> 0 Then
              .AddCaptionText("Outcome:", workflow.ClosedOutcome)
            End If
            If Len(workflow.ClosedNotes) <> 0 Then
              .AddCaptionText("Notes:", workflow.ClosedNotes)
            End If

          Case isefinWorkflowStatus.OnHold
            If workflow.ReviewDate <> Nothing Then
              .AddCaptionDate("Review:", workflow.ReviewDate)
            End If
        End Select

        ' Opened-from and Closed-to
        If workflow.OpenedFromWorkflowPk <> 0 Then
          With .AddCaptionText("Opened From:", workflow.OpenedFromWorkflowId)
            .Cells(1).HyperlinkSetFormShow("Workflows", workflow.OpenedFromWorkflowId)
          End With
        End If
        If workflow.ClosedToWorkflowPk <> 0 Then
          With .AddCaptionText("Closed To:", workflow.ClosedToWorkflowId)
            .Cells(1).HyperlinkSetFormShow("Workflows", workflow.ClosedToWorkflowId)
          End With
        End If

        ' Allocated User
        With .AddCaptionWiki("Allocated To:", "")
          If workflow.AllocatedUserPk = 0 AndAlso workflow.Status = isefinWorkflowStatus.Closed Then
            .Cells(1).Value = "**Not Allocated**"
          ElseIf workflow.AllocatedUserPk = 0 Then
            .Cells(1).Value = "!!**Not Allocated**!!"
          Else
            .Cells(1).Value = String.Format("**{0}**, {1}", workflow.AllocatedUserId, finBL.Users.ItemByPkSafe(workflow.AllocatedUserPk).Name)
          End If

          ' Pending
          If includeActions AndAlso workflow.PendingAllocatedUserPk <> 0 AndAlso finBL.CurrentUserInformation.IsWorkflowManager Then
            .Cells(1).Value &= String.Format(" --([[app://FormAction?action=WorkflowPendingUserAccept&workflow={2}|Accept pending user]] **{0}**, {1})--", workflow.PendingAllocatedUserId, finBL.Users.ItemByPkSafe(workflow.PendingAllocatedUserPk).Name, workflow.Pk)
          End If
        End With
      End With

      ' Warnings
      If workflow.AutoSuspendUntilDate <> Nothing AndAlso workflow.AutoSuspendUntilDate > DateAsAtDb Then
        If Len(workflow.WorkflowType.Category) = 0 Then
          Warnings &= "{{info|Automatic creation of another Workflow of type **" & workflow.WorkflowTypeId & "**, " & workflow.WorkflowType.Description & " for this " & workflow.WorkflowType.TargetObjectTypeText & " is suspended until **" & finBL.FormatDateLongWithTimeZone(workflow.AutoSuspendUntilDate, finBL.TimeZoneId) & "**.}}"
        Else
          Warnings &= "{{info|Automatic creation of another Workflow of category **" & workflow.WorkflowType.Category & "** for this " & workflow.WorkflowType.TargetObjectTypeText & " is suspended until **" & finBL.FormatDateLongWithTimeZone(workflow.AutoSuspendUntilDate, finBL.TimeZoneId) & "**.}}"
        End If
      End If
      If workflow.GetLogCountIncomplete(True, True, UnactionedCount, UnpublishedCount) Then
        strTemp = ""
        Select Case UnactionedCount
          Case 0
          Case 1 : strTemp = "**1** unactioned Log"
          Case Else : strTemp = "**" & CStr(UnactionedCount) & "** unactioned Logs"
        End Select

        Select Case UnpublishedCount
          Case 0
          Case 1
            If Len(strTemp) <> 0 Then strTemp &= ", "
            strTemp &= "**1** unpublished Log"
          Case Else
            If Len(strTemp) <> 0 Then strTemp &= ", "
            strTemp &= "**" & CStr(UnpublishedCount) & "** unpublished Logs"
        End Select

        If Len(strTemp) <> 0 Then
          Warnings &= "{{info|" & strTemp & ".}}"
        End If
      Else
        Warnings &= "{{warning|Failed to count unactioned Logs.|true}}"
      End If
      .TextAfter = Warnings

      ' Actions
      If includeActions Then
        With .Actions
          .AddFormAction("WorkflowOpenPending", "Open 'Pending' Workflow", Not finBL.Database.IsReadOnly AndAlso finBL.CurrentUser.Permissions.Allow("Workflow.OpenPending") AndAlso workflow.Status = isefinWorkflowStatus.Pending, String.Format("workflow={0}", workflow.Pk))
        End With
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Workflow Target Object Summary (Version 1.0, Last updated 28/08/2013).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="workflow">
  '''  The Workflow to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Workflow Key Details page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Workflow_TargetSummary(callerScriptInfo As ISScriptExecutionInfo,
                                                     workflow As finWorkflow,
                                            Optional includeActions As Boolean = True,
                                            Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim SummaryTables As ISSummaryTables

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()

    Select Case workflow.WorkflowType.TargetObjectType
      Case isefinWorkflowTargetObjectType.Account
        SummaryTables = Me.Workflow_TargetSummary_Account(callerScriptInfo, workflow, includeActions, otherParameters)
      Case isefinWorkflowTargetObjectType.AccountApp
        SummaryTables = Me.Workflow_TargetSummary_AccountApp(callerScriptInfo, workflow, includeActions, otherParameters)
      Case isefinWorkflowTargetObjectType.Client
        SummaryTables = Me.Workflow_TargetSummary_Client(callerScriptInfo, workflow, includeActions, otherParameters)
    End Select

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Workflow Target Account Summary (Version 1.0, Last updated 28/08/2013).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="workflow">
  '''  The Account-based Workflow to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Workflow Key Details page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Workflow_TargetSummary_Account(callerScriptInfo As ISScriptExecutionInfo,
                                                             workflow As finWorkflow,
                                                    Optional includeActions As Boolean = True,
                                                    Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim SummaryTables As ISSummaryTables

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()

    ' Main (retrieve standard Financial Status)
    SummaryTables = Me.Account_FinancialStatus(callerScriptInfo, workflow.Account, Nothing, Nothing, 120, True, True, True, , , includeActions)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Workflow Target Account Application Summary (Version 1.01, Last updated 30/03/2016).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="workflow">
  '''  The Account-based Workflow to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Workflow Key Details page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Workflow_TargetSummary_AccountApp(callerScriptInfo As ISScriptExecutionInfo,
                                                                workflow As finWorkflow,
                                                       Optional includeActions As Boolean = True,
                                                       Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim SummaryTables As ISSummaryTables

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()

    ' Main (retrieve standard Account Application Summary)
    SummaryTables = Me.AccountApp_Summary(callerScriptInfo, workflow.AccountApp, callerScriptInfo.FormKey <> "AccountApps", True, True, True, includeActions, Nothing)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Workflow Target Client Summary (Version 1.0, Last updated 19/02/2015).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="workflow">
  '''  The Client-based Workflow to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Workflow Key Details page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Workflow_TargetSummary_Client(callerScriptInfo As ISScriptExecutionInfo,
                                                            workflow As finWorkflow,
                                                   Optional includeActions As Boolean = True,
                                                   Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim SummaryTables As ISSummaryTables

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()

    ' Main (retrieve standard Summary)
    SummaryTables = Me.Client_Summary(callerScriptInfo, workflow.Client, True, False)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Workflow Logs Summary (Version 1.05, Last updated 20/11/2019).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="logs">
  '''  The Workflow or Workflow Item Logs to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Workflow Key Details page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Workflow_Logs(callerScriptInfo As ISScriptExecutionInfo,
                                            logs As finLogs,
                                   Optional maxDisplayRows As Integer = 20,
                                   Optional includeActions As Boolean = True,
                                   Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim Action As String
    Dim Log As finLogRO
    Dim LogClassesList As ISList
    Dim i As Integer
    Dim ShowAction As Boolean
    Dim ShowLogClass As Boolean
    Dim ShowPublish As Boolean
    Dim ShowSeverity As Boolean
    Dim ShowReply As Boolean
    Dim strTemp As String
    Dim Subject As String
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Determine Columns to include
    ShowAction = False
    ShowPublish = False
    ShowSeverity = False
    If TypeOf logs.Parent Is finWorkflow Then
      ShowReply = DirectCast(logs.Parent, finWorkflow).WorkflowType.SummaryPageShowLogReply
    End If
    LogClassesList = New ISList()
    For Each Log In logs
      If Log.ActionUtcDate <> Nothing AndAlso Log.ActionCompleteUtcDate = Nothing Then ShowAction = True
      If Log.PublishStatus <> isefinLogPublishStatus.None Then ShowPublish = True
      If Log.LogSeverityPk <> 0 Then ShowSeverity = True
      LogClassesList.Add(Log.LogClass.ToString(), True)
    Next
    ShowLogClass = LogClassesList.Count > 1

    ' Main
    With SummaryTableMain
      If logs.Count = 0 Then
        .TextBefore = "{{info|No linked Logs.}}"
      Else
        ' Initialise
        .TableClass = iseSummaryTableClass.TabularData
        .Caption = ""
        .AutoStripe = True
        .MaxDisplayRows = maxDisplayRows
        .ShowHiddenRowsCaption = "Show More Logs"

        ' Columns
        With .Columns
          If ShowLogClass Then .AddBoolean(" ")
          If ShowSeverity Then .AddBoolean(" ")
          .AddDate("Date")
          .AddText("Subject")
          If ShowAction Then .AddText("Action", 10)
          If ShowPublish Then .AddCode("Publish", 10)
          If ShowReply Then .AddBoolean("")
        End With

        With .Rows
          ' Reverse order so latest are at the top
          For i = logs.Count - 1 To 0 Step -1
            ' Initialise
            Log = logs(i)

            With .Add()
              ' Incomplete
              If Log.IsIncomplete OrElse Log.IsAwaitingPublish Then
                .RowClass = iseSummaryTableRowClass.NormalBold
              End If

              ' Hide if not issued
              If Log.PublishStatus = isefinLogPublishStatus.NotIssued Then
                .Visible = False
              End If

              With .Cells
                If ShowLogClass Then
                  .AddText("{{icon|" & Log.GetLogClassIcon() & "|" & Log.LogClassText & "}}")
                End If

                If ShowSeverity Then
                  If Log.LogSeverityPk = 0 Then
                    .AddText("")
                  ElseIf Log.ActionDate <> Nothing AndAlso Log.ActionCompleteDate = Nothing Then
                    .AddText("{{colourblock|" & Log.LogSeverity.OpenColourBackground & "|" & Log.LogSeverity.LogSeverityId & ", " & Log.LogSeverity.Description & "}}")
                  Else
                    .AddText("{{colourblock|" & Log.LogSeverity.CompleteColourBackground & "|" & Log.LogSeverity.LogSeverityId & ", " & Log.LogSeverity.Description & "}}")
                  End If
                End If

                .AddDate(Log.LogDate)

                ' Make Subject splitable (auto-generated subjects such as Credit Enquiries have no spaces and therefore force columns too wide)
                Subject = Log.Subject
                If Len(Subject) > 20 Then
                  If InStr(Subject, ".") <> 0 Then
                    Subject = Replace(Subject, ".", ". ")
                  End If
                End If
                With .AddText(Subject)
                  If Len(Log.Notes) = 0 Then
                    ' Hyperlink to show Log
                    .HyperlinkSetFormShow(Log.LogFormKey, CStr(Log.Pk))
                  Else
                    ' Append Log Notes
                    strTemp = Trim(Replace(Log.Notes, vbNewLine, " "))
                    If Len(strTemp) > 100 Then
                      strTemp = Trim(Left(strTemp, 100))
                      If Right(strTemp, 1) = "." Then
                        strTemp &= ".."
                      Else
                        strTemp &= "..."
                      End If
                    End If

                    ' Convert to WikiText and hyperlink only the Subject
                    .ValueFormat = iseSummaryTableCellFormat.WikiTextSimple
                    .Value = "[[app://FormShow?Form=" & Log.LogFormKey & "&id=" & Log.Pk & "|" & .Value & "]]" & vbNewLine & "--" & strTemp & "--"
                  End If
                End With

                If ShowAction Then
                  If Log.ActionDate = Nothing Then
                    Action = ""
                  ElseIf Log.ActionCompleteDate = Nothing Then
                    Action = finBL.FormatDateForGrid(Log.ActionDate)
                  Else
                    Action = "Complete"
                  End If
                  .AddText(Action)
                End If
                If ShowPublish Then
                  If Log.PublishStatus = isefinLogPublishStatus.None Then
                    .AddText("")
                  Else
                    .AddText(Log.PublishStatusText)
                  End If
                End If
                If ShowReply Then
                  With .AddText("{{icon|Log_Reply}}")
                    If Log.ParentLogPk = 0 Then
                      .Hyperlink = "app://FormShow?Form=" & Log.LogFormKey & "&replyToLogPk=" & Log.Pk
                    Else
                      .Hyperlink = "app://FormShow?Form=" & Log.LogFormKey & "&replyToLogPk=" & Log.ParentLogPk
                    End If
                  End With
                End If
              End With
            End With
          Next
        End With

        ' Warnings
        .TextAfter = Warnings

        ' Actions
        If includeActions Then
          With .Actions
          End With
        End If
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Workflow Items Summary including links to action a Workflow Item if applicable (Version 1.07, Last updated 1/04/2021).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="Workflow">
  '''  The Workflow to summarise.
  ''' </param>
  ''' <param name="workflowItemGroupPk">
  '''  The primary key of the Workflow Item Group to summarise or zero to summarise all Item Groups.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Workflow Key Details page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>GroupDetails</code><description>Details of the Item Group is summarising a single Item Group.</description></item>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Workflow_Items(callerScriptInfo As ISScriptExecutionInfo,
                                             workflow As finWorkflow,
                                    Optional workflowItemGroupPk As Integer = 0,
                                    Optional includeActions As Boolean = True,
                                    Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim ActionsWikiText As String
    Dim UrlAction As String
    Dim CompactView As Boolean
    Dim CompletedGroupsStarted As Boolean
    Dim CurrentWorkflowItemGroup As finWorkflowItem
    Dim CurrentWorkflowItem As finWorkflowItem
    Dim CurrentGroupFound As Boolean
    Dim DateAsAtUtc As Date
    Dim FalseOutcome As String
    Dim GroupedItemToggle As Boolean
    Dim HasAutoActionItems As Boolean
    Dim HelpNotesAdded As Boolean
    Dim HelpNotes As String
    Dim HelpNotesHtml As Boolean
    Dim HelpNotesPosition As String
    Dim i As Integer
    Dim j As Integer
    Dim Include As Boolean
    Dim LastWorkflowItemGroup As finWorkflowItem
    Dim LatestWorkflowItem As finWorkflowItem
    Dim UrlOutcome As String
    Dim Parameters As ISKeyValueList
    Dim ShowActionedUserAndDate As Boolean
    Dim ShowOtherActionColumn As Boolean
    Dim ShowCompletedItemGroups As Boolean
    Dim ShowCompletedItemGroupsAsSingleGroup As Boolean
    Dim ShowFutureItemGroups As Boolean
    Dim ShowNaInPastItemGroups As Boolean
    Dim ShowSkipped As Boolean
    Dim ShowSkippedInNonCurrentGroup As Boolean
    Dim ShowSkippedItemGroups As Boolean
    Dim ShowNa As Boolean
    Dim ShowNaItemGroups As Boolean
    Dim ShowSeparateLastItemGroup As Boolean
    Dim strTemp As String
    Dim SummaryTableCell As ISSummaryTableCell
    Dim SummaryTableGroupDetails As ISSummaryTable
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim TooltipText As String
    Dim TrueOutcome As String
    Dim UrlViewDetails As String
    Dim Warnings As String
    Dim WorkflowItem As finWorkflowItem
    Dim WorkflowItemNext As finWorkflowItem
    Dim WorkflowItemGroup As finWorkflowItem
    Dim WorkflowItemGroupItems As List(Of finWorkflowItem)
    Dim WorkflowItemOutcomeItem As finWorkflowItemOutcomeItem
    Dim WorkflowItemOutcomeItems As List(Of finWorkflowItemOutcomeItem)

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Date As At
    DateAsAtUtc = finBL.TimeZoneFunctions.GetCurrentUtcDateTime()

    ' Get display options from Workflow Type
    ' NOTE: More options are listed below than currently exist on a Workflow Type. This is for flexibility
    If workflow.WorkflowType IsNot Nothing Then
      With workflow.WorkflowType
        CompactView = .SummaryPageCompactView
        ShowCompletedItemGroups = True
        ShowCompletedItemGroupsAsSingleGroup = .SummaryPageShowCompletedItemGroupsAsSingleGroup
        ShowFutureItemGroups = .SummaryPageShowFutureItemGroups
        ShowNa = .SummaryPageShowNaItems
        ShowSeparateLastItemGroup = .SummaryPageSeparateLastItemGroup
        ShowNaInPastItemGroups = ShowNa
        ShowNaItemGroups = ShowNa
        ShowSkipped = .SummaryPageShowSkippedItems
        ShowSkippedInNonCurrentGroup = ShowSkipped
        ShowSkippedItemGroups = .SummaryPageShowSkippedItemGroups
        ShowActionedUserAndDate = .SummaryPageShowActionedUserAndDate
      End With
    End If

    ' finPOWER Connect Cloud tweaks
    If callerScriptInfo IsNot Nothing AndAlso callerScriptInfo.Target = iseSummaryPageTarget.WebInternal AndAlso callerScriptInfo.FormPageKey = "Items" Then
      ' Items page should show full details
      CompactView = False
      ShowCompletedItemGroups = True
      ShowCompletedItemGroupsAsSingleGroup = False
      ShowFutureItemGroups = True
      ShowNa = True
      ShowSeparateLastItemGroup = True
      ShowNaInPastItemGroups = True
      ShowNaItemGroups = True
      ShowSkipped = True
      ShowSkippedInNonCurrentGroup = True
      ShowSkippedItemGroups = True
      ShowActionedUserAndDate = True
    End If

    ' Find Columns to include
    If Not includeActions OrElse workflow.Status = isefinWorkflowStatus.Closed Then
      ShowOtherActionColumn = False
    Else
      ShowOtherActionColumn = True ' finBL.CurrentUser.Permissions.Allow("Workflow.ItemReset")
    End If

    ' Get Current Item Group and Current Item
    CurrentWorkflowItemGroup = workflow.GetCurrentItemGroup()
    CurrentWorkflowItem = workflow.GetCurrentItem()
    HasAutoActionItems = workflow.HasAutoActionItems()

    ' Find Last Item Group (either Complete or with Completed Items)
    If CurrentWorkflowItemGroup IsNot Nothing Then
      i = workflow.ItemGroups.IndexOf(CurrentWorkflowItemGroup)
      For j = i - 1 To 0 Step -1
        With workflow.ItemGroups(j)
          Select Case .Status
            Case isefinWorkflowItemStatus.ItemGroupDeleted
            Case Else
              If .Status = isefinWorkflowItemStatus.Complete OrElse .Items.CountComplete() <> 0 Then
                LastWorkflowItemGroup = workflow.ItemGroups(j)
                Exit For
              End If
          End Select
        End With
      Next
    End If

    ' Find primary key of Last Updated Workflow Item in the current Item Group
    If CurrentWorkflowItemGroup IsNot Nothing Then
      For Each WorkflowItem In CurrentWorkflowItemGroup.Items
        If WorkflowItem IsNot CurrentWorkflowItem AndAlso WorkflowItem.ItemType <> isefinWorkflowItemType.ItemGroup Then ' AndAlso WorkflowItem.Status <> isefinWorkflowItemStatus.NotStarted Then
          If WorkflowItem.Status <> isefinWorkflowItemStatus.NotStarted AndAlso (LatestWorkflowItem Is Nothing OrElse WorkflowItem.UpdatedUtcDate > LatestWorkflowItem.UpdatedUtcDate) Then
            LatestWorkflowItem = WorkflowItem
          End If
        End If
      Next
    End If

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .Caption = ""
      .AutoStripe = True

      ' Columns
      With .Columns
        .AddText("", 1) ' Grouped Items Icon/ Marker
        .AddText("", 1) ' Status Icon
        .AddText("") ' Description
        If CompactView Then .AddText("", -1) ' Action (for compact view, -1 indicates an unspecified width)
        If ShowOtherActionColumn Then .AddText("", 1) ' Other Action, e.g., Reset/ N/A
      End With

      For Each WorkflowItemGroup In workflow.ItemGroups
        ' Initialise
        GroupedItemToggle = False

        ' Include Item Group?
        If workflowItemGroupPk <> 0 AndAlso WorkflowItemGroup.Pk = workflowItemGroupPk Then
          ' Include specified Item Group
          Include = True
        ElseIf workflowItemGroupPk <> 0 AndAlso WorkflowItemGroup.Pk <> workflowItemGroupPk Then
          ' Exclude since not specified Item Group
          Include = False
        ElseIf WorkflowItemGroup.Status = isefinWorkflowItemStatus.ItemGroupDeleted Then
          ' Never include Deleted
          Include = False
        ElseIf WorkflowItemGroup.IsCurrentItemGroup() Then
          ' Always include Current Item Group
          Include = True
          CurrentGroupFound = True
        ElseIf CurrentGroupFound AndAlso Not ShowFutureItemGroups Then
          ' Do not include Future Item Groups
          Include = False
        ElseIf Not CurrentGroupFound AndAlso Not ShowCompletedItemGroups Then
          ' Do not include Completed Item Groups
          Include = False
        ElseIf WorkflowItemGroup.Status = isefinWorkflowItemStatus.Skipped AndAlso Not ShowSkippedItemGroups Then
          ' Do not include Skipped Item Group (unless it has completed Items)
          Include = (WorkflowItemGroup.Items.CountComplete() <> 0)
        ElseIf WorkflowItemGroup.Status = isefinWorkflowItemStatus.NotApplicable AndAlso Not ShowNaItemGroups Then
          ' Do not include Item Groups flagged as 'Not Applicable'
          Include = False
        Else
          Include = True
        End If

        If Include Then
          ' Item Group Header
          If workflowItemGroupPk <> 0 Then
            ' Don't add Group Header if summarising a single Item Group
          ElseIf WorkflowItemGroup Is CurrentWorkflowItemGroup Then
            ' Current Item Group (do not allow collapse)
            With .Rows.AddCollapsibleHeader(iseTriState.None)
              .Cells.AddText(WorkflowItemGroup.Description).CellClass = iseSummaryTableCellClass.NormalBold
            End With
          ElseIf ShowCompletedItemGroupsAsSingleGroup AndAlso ShowSeparateLastItemGroup AndAlso WorkflowItemGroup Is LastWorkflowItemGroup Then
            ' Show Last Item Group as a separate group
            With .Rows.AddCollapsibleHeader(iseTriState.True)
              .Cells.AddText(WorkflowItemGroup.Description & " (Last)").CellClass = iseSummaryTableCellClass.Normal
            End With
          ElseIf Not ShowCompletedItemGroupsAsSingleGroup OrElse CurrentGroupFound Then
            ' Other Item Group (completed/ future)
            With .Rows.AddCollapsibleHeader(iseTriState.True)
              .CollapsedStatus = iseTriState.True
              With .Cells.AddText(WorkflowItemGroup.Description)
                .CellClass = iseSummaryTableCellClass.Normal

                Select Case WorkflowItemGroup.Status
                  Case isefinWorkflowItemStatus.Skipped, isefinWorkflowItemStatus.NotApplicable
                    .ForegroundColour = "#989898"
                End Select
              End With
            End With
          ElseIf ShowCompletedItemGroupsAsSingleGroup AndAlso Not CurrentGroupFound Then
            ' All completed groups
            If CompletedGroupsStarted Then
              ' Completed Item Groups shown as single Group
            Else
              ' Add Completed Items Group
              With .Rows.AddCollapsibleHeader(iseTriState.True)
                With .Cells.AddText("Completed Groups")
                  .CellClass = iseSummaryTableCellClass.Normal
                End With
              End With
              CompletedGroupsStarted = True
            End If

            ' Add Header
            .Rows.AddSectionHeading2(WorkflowItemGroup.Description)
          End If

          ' Get all Items in the Item Group and add an entry for the Item Group itself so everything can be handled in a single loop
          WorkflowItemGroupItems = New List(Of finWorkflowItem)
          For Each WorkflowItem In WorkflowItemGroup.Items
            WorkflowItemGroupItems.Add(WorkflowItem)
          Next
          WorkflowItemGroupItems.Add(WorkflowItemGroup)

          ' Items
          For Each WorkflowItem In WorkflowItemGroupItems
            ' Include?
            If WorkflowItem.HiddenResolved Then
              ' Hidden
              Include = False
            ElseIf WorkflowItem.ItemType = isefinWorkflowItemType.ItemGroup Then
              ' Always include Item Groups
              Include = True
            Else
              Select Case WorkflowItem.Status
                Case isefinWorkflowItemStatus.NotApplicable
                  If ShowNa Then
                    If WorkflowItemGroup.IsCurrentItemGroup() Then
                      Include = True
                    ElseIf CurrentGroupFound Then
                      ' Show in future group
                      Include = True
                    Else
                      ' Show/ do not show in past groups
                      Include = ShowNaInPastItemGroups
                    End If
                  Else
                    Include = False
                  End If

                Case isefinWorkflowItemStatus.Skipped
                  If ShowSkipped Then
                    If WorkflowItemGroup.IsCurrentItemGroup() Then
                      Include = True
                    Else
                      ' Show/ do not show in non-current groups
                      Include = ShowSkippedInNonCurrentGroup
                    End If
                  Else
                    Include = False
                  End If

                Case Else
                  Include = True
              End Select
            End If

            If Include Then
              ' Create Action and Outcome URLs
              UrlAction = String.Format("app://FormAction?action=WorkflowItemAction&workflow={0}&itemPk={1}", workflow.Pk, WorkflowItem.Pk)
              UrlOutcome = String.Format("app://FormAction?action=WorkflowItemSetOutcome&workflow={0}&itemPk={1}&outcome=", workflow.Pk, WorkflowItem.Pk)

              ' Create URL to view details
              Parameters = finBL.CreateKeyValueList()
              With Parameters
                .SetString("WorkflowId", workflow.WorkflowId)
                .SetInteger("WorkflowItemPk", WorkflowItem.Pk)
                .SetBoolean("Popup", True)
                .SetInteger("Width", 768)
                .SetInteger("Height", 580)
              End With
              UrlViewDetails = finBL.CreateApplicationShortcutHtmlShowFunction("WorkflowItemSummary", False, "Workflow Item Summary", Parameters).ToUrlString(False)

              ' Add Row
              With .Rows.Add()
                ' Style row
                If workflow.Status = isefinWorkflowStatus.Closed AndAlso WorkflowItem.ItemType <> isefinWorkflowItemType.ItemGroup Then
                  ' Do not style if Workflow is closed
                ElseIf WorkflowItem Is CurrentWorkflowItem Then
                  ' Current Item
                  .BackgroundColour = "#90FF90"
                  .ElementId = "CURRENT"
                ElseIf WorkflowItem.ItemType = isefinWorkflowItemType.ItemGroup Then
                  ' Item Group
                  .RowClass = iseSummaryTableRowClass.Footer
                ElseIf WorkflowItem Is LatestWorkflowItem Then
                  ' Last Updated Item
                  .BackgroundColour = "#CCFFFC"
                  .ElementId = "LATEST"
                End If

                With .Cells
                  ' Grouped Items marker
                  i = WorkflowItemGroupItems.IndexOf(WorkflowItem)
                  If i < WorkflowItemGroupItems.Count - 1 Then
                    WorkflowItemNext = WorkflowItemGroupItems(i + 1)
                  Else
                    WorkflowItemNext = Nothing
                  End If
                  If WorkflowItem.GroupWithPrevious OrElse (WorkflowItemNext IsNot Nothing AndAlso WorkflowItemNext.GroupWithPrevious) Then
                    If GroupedItemToggle Then
                      With .AddText("{{icon|bullet[DarkOrange]|Grouped Item|8}}")
                        .HyperlinkSetApplicationShortcutUrl(UrlViewDetails)
                      End With
                    Else
                      With .AddText("{{icon|bullet[CornflowerBlue]|Grouped Item|8}}")
                        .HyperlinkSetApplicationShortcutUrl(UrlViewDetails)
                      End With
                    End If
                  Else
                    .AddText("")
                  End If
                  If WorkflowItem.GroupWithPrevious AndAlso (WorkflowItemNext IsNot Nothing AndAlso Not WorkflowItemNext.GroupWithPrevious) Then
                    GroupedItemToggle = Not GroupedItemToggle
                  End If

                  ' -----------
                  ' Status Icon
                  ' -----------
                  ' Icon
                  If WorkflowItem.ItemType = isefinWorkflowItemType.ItemGroup Then
                    If WorkflowItem.Status = isefinWorkflowItemStatus.Complete Then
                      strTemp = "Workflow_Finish"
                    Else
                      strTemp = "Workflow_Unfinished"
                    End If
                  ElseIf WorkflowItem.Status = isefinWorkflowItemStatus.Complete Then
                    strTemp = WorkflowItem.GetStatusCompleteIcon()
                  Else
                    Select Case WorkflowItem.Status
                      Case isefinWorkflowItemStatus.NotApplicable : strTemp = "Blank"
                      Case isefinWorkflowItemStatus.NotStarted : strTemp = "WorkflowItemStatus_None"
                      Case isefinWorkflowItemStatus.Open : strTemp = "WorkflowItemStatus_None,Hourglass"
                      Case isefinWorkflowItemStatus.Skipped : strTemp = "bullet[#e0e0e0]"
                      Case Else : strTemp = "Blank"
                    End Select
                  End If

                  ' Icon Overlay
                  If strTemp <> "Blank" AndAlso InStr(strTemp, ",") = 0 Then
                    If WorkflowItem.Status = isefinWorkflowItemStatus.NotStarted AndAlso Not WorkflowItem.IsValid("") Then
                      ' Invalid
                      strTemp &= ",Warning"
                    ElseIf WorkflowItem.Logs.Count <> 0 Then
                      ' Has Logs
                      strTemp &= ",Log"
                    ElseIf WorkflowItem.Status = isefinWorkflowItemStatus.Complete AndAlso WorkflowItem.StatusNotesEntryMethod <> isefinWorkflowItemStatusNotesEntryMethod.None AndAlso Len(WorkflowItem.StatusNotes) <> 0 Then
                      ' Has Status Notes
                      strTemp &= ",Document"
                    ElseIf WorkflowItem.Status = isefinWorkflowItemStatus.Complete AndAlso (WorkflowItem.StatusNotesEntryMethod = isefinWorkflowItemStatusNotesEntryMethod.ParametersUserDefinedWorkflowItem OrElse WorkflowItem.StatusNotesEntryMethod = isefinWorkflowItemStatusNotesEntryMethod.ParametersUserDefinedWorkflow) Then
                      ' Has User Data (or at least is configured to allow entry of User Data)
                      strTemp &= ",Query"
                    ElseIf workflow.GetCountResetsByWorkflowItemPk(WorkflowItem.Pk) <> 0 Then
                      ' Overlay to indicate this item has been reset
                      strTemp &= ",Reset"
                    ElseIf (WorkflowItem.Status = isefinWorkflowItemStatus.Complete OrElse WorkflowItem.Status = isefinWorkflowItemStatus.NotStarted OrElse WorkflowItem.Status = isefinWorkflowItemStatus.Open) AndAlso WorkflowItem.AutoAction Then
                      ' Overlay to indicate 'Auto Action' item
                      strTemp &= ",Execute"
                    ElseIf WorkflowItem.Status = isefinWorkflowItemStatus.NotStarted AndAlso WorkflowItem.Automatic Then
                      ' Overlay to indicate automatic item
                      strTemp &= ",ArrowGreen_Down"
                    ElseIf WorkflowItem.StatusUpdatedFromScript Then
                      strTemp &= ",Script"
                    End If
                  End If

                  ' Tooltip
                  If WorkflowItem.Status = isefinWorkflowItemStatus.NotStarted Then
                    If WorkflowItem.Automatic Then
                      TooltipText = "Automatic Item, Not Started"
                    Else
                      TooltipText = "Not Started"
                    End If
                  Else
                    TooltipText = WorkflowItem.StatusText
                  End If
                  TooltipText &= " (Click to view details)"
                  Select Case WorkflowItem.Logs.Count
                    Case 0
                    Case 1
                      TooltipText &= vbNewLine & "1 Log"
                    Case Else
                      TooltipText &= vbNewLine & String.Format("{0} Logs", WorkflowItem.Logs.Count)
                  End Select

                  ' Add Cell
                  With .AddWiki("{{icon|" & strTemp & "|" & TooltipText & "}}")
                    .HyperlinkSetApplicationShortcutUrl(UrlViewDetails)
                  End With

                  ' -----------
                  ' Description
                  ' -----------
                  ' Description
                  If WorkflowItem.IsCurrentItem() Then
                    strTemp = "**" & WorkflowItem.Description & "**"
                  Else
                    strTemp = WorkflowItem.Description
                  End If
                  SummaryTableCell = .AddWiki(strTemp)
                  With SummaryTableCell
                    ' Colour
                    Select Case WorkflowItem.Status
                      Case isefinWorkflowItemStatus.NotApplicable : .ForegroundColour = "#a0a0a0"
                      Case isefinWorkflowItemStatus.Skipped : .ForegroundColour = "#a0a0a0"
                    End Select
                  End With

                  ' Help Notes (always display as a popup if HTML or if this item cannot be actioned)
                  ' NOTE: Shown for completed items since it is quite common for a Script to update the notes, e.g., to provide a link to a record that was updated
                  Select Case WorkflowItem.Status
                    Case isefinWorkflowItemStatus.Complete, isefinWorkflowItemStatus.NotStarted, isefinWorkflowItemStatus.Open
                      HelpNotes = WorkflowItem.GetHelpNotesAsWikiText(HelpNotesPosition)
                      HelpNotesHtml = False
                      If Len(HelpNotes) = 0 Then
                        HelpNotes = WorkflowItem.GetHelpNotesAsHtml(HelpNotesPosition)
                        HelpNotesPosition = "" ' Force HTML to popup
                        HelpNotesHtml = Len(HelpNotes) <> 0
                      End If
                      HelpNotesAdded = False

                      If Len(HelpNotes) <> 0 Then
                        Select Case HelpNotesPosition
                          Case ""
                            ' Popup (append info icon to end of Description)
                            If Not HelpNotesHtml Then HelpNotes = finBL.Utilities.WikiTextSimpleToHtml(HelpNotes)
                            SummaryTableCell.Value &= " [[app://HtmlShow?popup=True&html=" & finBL.UrlEncode(HelpNotes) & "|{{icon|InformationTip|View Help|11}}]]"

                          Case "^"
                            ' Before action links
                            SummaryTableCell.Value &= "{{help|" & HelpNotes & "}}"
                            HelpNotesAdded = True

                          Case "*"
                            ' After action links
                            ' NOTE: Handled later
                        End Select
                      End If
                  End Select

                  ' Outcome
                  If WorkflowItem.Status = isefinWorkflowItemStatus.Complete Then
                    If Len(WorkflowItem.StatusOutcome) <> 0 Then
                      strTemp = "**" & WorkflowItem.StatusOutcome & "** "
                    Else
                      strTemp = ""
                    End If
                    If ShowActionedUserAndDate Then
                      If WorkflowItem.CompletedUserPk = 0 Then
                        strTemp &= String.Format("--(completed automatically on {0})--", finBL.FormatDateLong(WorkflowItem.CompletedDate))
                      Else
                        strTemp &= String.Format("--({0} on {1})--", WorkflowItem.CompletedUserId, finBL.FormatDateLong(WorkflowItem.CompletedDate))
                      End If
                    End If
                    If Len(strTemp) <> 0 Then
                      If HelpNotesAdded Then
                        ' Help template provides a new line
                      Else
                        SummaryTableCell.Value &= vbNewLine
                      End If
                      SummaryTableCell.Value &= "  " & strTemp
                    End If
                  ElseIf WorkflowItem.ItemType = isefinWorkflowItemType.ItemGroup AndAlso (WorkflowItem.Status <> isefinWorkflowItemStatus.NotStarted AndAlso WorkflowItem.Status <> isefinWorkflowItemStatus.Open) Then
                    ' Always show Item Group Status, e.g., Skipped
                    SummaryTableCell.Value &= vbNewLine & "  (" & WorkflowItem.StatusText & ")"
                  End If

                  ' Main Action (Action/ Set Outcome)
                  ' NOTE: In Compact view, this will be added in its own column instead of the Description column
                  If includeActions AndAlso workflow.Status = isefinWorkflowStatus.Open AndAlso Not finBL.Database.IsReadOnly Then
                    ' Initialise
                    ActionsWikiText = ""

                    If HasAutoActionItems Then
                      ' User cannot Action if this Workflow has 'Auto Action' items
                      Select Case WorkflowItem.Status
                        Case isefinWorkflowItemStatus.NotStarted, isefinWorkflowItemStatus.Open
                          If WorkflowItem.AutoAction Then
                            ActionsWikiText = "{{info|This 'auto-action' item will be actioned when the Workflow is processed.}}"
                          End If
                      End Select
                    ElseIf WorkflowItem.CanAction("") Then
                      ' Action
                      If WorkflowItem.Status = isefinWorkflowItemStatus.Open AndAlso WorkflowItem.ItemType <> isefinWorkflowItemType.ItemGroup Then
                        ' Open Items (i.e., Complete Action only, regardless of Item Type)
                        ActionsWikiText = "{{button icon='WorkflowItem_ActionComplete' iconsize='16' tooltip=""Complete 'Open' item"" hyperlink=""" & UrlAction & """}} "
                      Else
                        ' Not Started
                        Select Case WorkflowItem.ItemType
                          Case isefinWorkflowItemType.CheckListItem
                            ' Check List Item
                            ActionsWikiText = "{{button icon='check' iconsize='16' tooltip=""" & WorkflowItem.GetActionDescription(TrueOutcome) & """ hyperlink=""" & UrlAction & """}} "

                          Case isefinWorkflowItemType.Question, isefinWorkflowItemType.ItemGroup
                            ' Set Outcome
                            If WorkflowItem.OutcomeItems.Count = 0 Then
                              Warnings &= "{{warning|No outcomes defined.}}"
                            ElseIf WorkflowItem.OutcomeItems.CountVisible = 0 Then
                              Warnings &= "{{warning|No visible outcomes defined.}}"
                            ElseIf WorkflowItem.OutcomeItems.HasYesTrueOutcomeOnly(TrueOutcome) Then
                              ' Single Yes/ True outcome only so represent like a Check List Item
                              ActionsWikiText = "{{button icon='check' iconsize='16' tooltip=""" & WorkflowItem.GetActionDescription(TrueOutcome) & """ hyperlink=""" & UrlOutcome & TrueOutcome & """}}"
                            ElseIf WorkflowItem.OutcomeItems.HasYesNoTrueFalseOutcomes(TrueOutcome, FalseOutcome) Then
                              ' Yes/ No or True/ False items only
                              ActionsWikiText = "{{button icon='check' iconsize='16' tooltip=""" & WorkflowItem.GetActionDescription(TrueOutcome) & """ hyperlink=""" & UrlOutcome & TrueOutcome & """}} "
                              ActionsWikiText &= "{{button icon='cross' iconsize='16' tooltip=""" & WorkflowItem.GetActionDescription(FalseOutcome) & """ hyperlink=""" & UrlOutcome & FalseOutcome & """}} "
                            Else
                              ' Bulleted list of outcomes (do not show hidden, repeating outcomes or automatic outcomes for Item Groups)
                              WorkflowItemOutcomeItems = WorkflowItem.OutcomeItems.GetUserOutcomesList()
                              For Each WorkflowItemOutcomeItem In WorkflowItemOutcomeItems
                                If Len(ActionsWikiText) <> 0 Then ActionsWikiText &= "<br>"
                                ActionsWikiText &= "{{icon|LogsThread2_ChildLast}} [[" & UrlOutcome & finBL.UrlEncode(WorkflowItemOutcomeItem.Outcome) & "|" & WorkflowItemOutcomeItem.OutcomeDescriptionResolved & "]]"
                              Next
                            End If

                          Case Else
                            ' Action
                            ActionsWikiText = "{{button icon='WorkflowItem_Action' iconsize='16' tooltip=""" & WorkflowItem.GetActionDescription(TrueOutcome) & """ hyperlink=""" & UrlAction & """}} "
                        End Select
                      End If
                    End If

                    If Len(ActionsWikiText) <> 0 Then
                      If CompactView Then
                        ' Actions will be added in the next column in Compact view
                      Else
                        ' Append spacer?
                        If Not HelpNotesAdded Then SummaryTableCell.Value &= "{{icon|blank||20}}" & vbNewLine

                        ' Append actions
                        SummaryTableCell.Value &= ActionsWikiText
                      End If
                    End If
                  End If

                  ' Other information
                  If WorkflowItem.ItemType <> isefinWorkflowItemType.ItemGroup AndAlso WorkflowItem.Status = isefinWorkflowItemStatus.Open Then
                    If workflow.RecallUtcDate <> Nothing Then
                      If workflow.RecallDate < DateAsAtUtc Then
                        SummaryTableCell.Value &= "{{warning|Recall date **" & finBL.FormatDateTimeLongWithTimeZone(workflow.RecallTzDate, workflow.RecallTimeZoneId) & "** has passed.}}"
                      Else
                        SummaryTableCell.Value &= "{{info|Awaiting recall date of **" & finBL.FormatDateTimeLongWithTimeZone(workflow.RecallTzDate, workflow.RecallTimeZoneId) & "**.}}"
                      End If
                    End If
                  End If

                  ' Help (After)
                  If Len(HelpNotes) <> 0 AndAlso Not HelpNotesAdded Then
                    Select Case HelpNotesPosition
                      Case "*"
                        ' After action links
                        SummaryTableCell.Value &= "{{help|" & HelpNotes & "}}"
                        HelpNotesAdded = True
                    End Select
                  End If

                  ' --------------------------
                  ' Action (Compact View only)
                  ' --------------------------
                  If CompactView Then
                    .AddWiki(ActionsWikiText)
                  End If

                  ' ------------
                  ' Other Action
                  ' ------------
                  If ShowOtherActionColumn Then
                    strTemp = ""
                    Select Case WorkflowItem.Status
                      Case isefinWorkflowItemStatus.NotApplicable
                        ' Reset N/A Status
                        If (WorkflowItemGroup.Status = isefinWorkflowItemStatus.Open OrElse WorkflowItemGroup.Status = isefinWorkflowItemStatus.NotStarted) AndAlso WorkflowItem.AllowNotApplicableResolved Then
                          strTemp = "[[app://FormAction?action=WorkflowItemToggleNotApplicable&workflow=" & workflow.Pk & "&itemPk=" & WorkflowItem.Pk & "|{{icon|WorkflowItem_Reset|Undo 'Not Applicable' status}}]]"
                        End If

                      Case isefinWorkflowItemStatus.Skipped
                        ' Reset Skipped Status
                        If (WorkflowItemGroup.Status = isefinWorkflowItemStatus.Open OrElse WorkflowItemGroup.Status = isefinWorkflowItemStatus.NotStarted) AndAlso WorkflowItem.AllowResetResolved Then
                          strTemp = "[[??|{{icon|WorkflowItem_Reset}}]]"
                        End If

                        ' Reset skip option (finPOWER Connect Cloud, Items page only)
                        If callerScriptInfo.FormKey = "Workflows" AndAlso callerScriptInfo.FormPageKey = "Items" Then
                          If (WorkflowItemGroup.Status = isefinWorkflowItemStatus.Open OrElse WorkflowItemGroup.Status = isefinWorkflowItemStatus.NotStarted) AndAlso WorkflowItem.AllowSkipUnskipResolved Then
                            strTemp = "[[app://FormAction?action=WorkflowItemUnskip&workflow=" & workflow.Pk & "&itemPk=" & WorkflowItem.Pk & "|{{icon|WorkflowItem_Unskip|Unskip this Item}}]]"
                          End If
                        End If

                      Case isefinWorkflowItemStatus.Complete, isefinWorkflowItemStatus.Open
                        ' Reset to Not Started
                        If WorkflowItemGroup.Status = isefinWorkflowItemStatus.Open AndAlso
                           WorkflowItem.AllowResetResolved Then
                          strTemp = "[[app://FormAction?action=WorkflowItemReset&workflow=" & workflow.Pk & "&itemPk=" & WorkflowItem.Pk & "|{{icon|WorkflowItem_Reset|Reset this Item}}]]"
                        End If

                      Case isefinWorkflowItemStatus.NotStarted
                        ' Set N/A Status
                        If (WorkflowItemGroup.Status = isefinWorkflowItemStatus.Open OrElse WorkflowItemGroup.Status = isefinWorkflowItemStatus.NotStarted) AndAlso WorkflowItem.AllowNotApplicableResolved Then
                          strTemp = "[[app://FormAction?action=WorkflowItemToggleNotApplicable&workflow=" & workflow.Pk & "&itemPk=" & WorkflowItem.Pk & "|{{icon|WorkflowItem_NA|Set this Item to 'Not Applicable'}}]]"
                        End If

                        ' Skip option (finPOWER Connect Cloud, Items page only)
                        If callerScriptInfo.FormKey = "Workflows" AndAlso callerScriptInfo.FormPageKey = "Items" Then
                          If (WorkflowItemGroup.Status = isefinWorkflowItemStatus.Open OrElse WorkflowItemGroup.Status = isefinWorkflowItemStatus.NotStarted) AndAlso WorkflowItem.AllowSkipUnskipResolved Then
                            strTemp = "[[app://FormAction?action=WorkflowItemSkip&workflow=" & workflow.Pk & "&itemPk=" & WorkflowItem.Pk & "|{{icon|WorkflowItem_Skip|Skip this Item}}]]"
                          End If
                        End If
                    End Select

                    ' Add Cell
                    .AddWiki(strTemp)
                  End If
                End With
              End With
            End If
          Next
        End If
      Next

      ' Warnings
      .TextAfter = Warnings

      ' Actions
      If includeActions Then
        With .Actions
        End With
      End If
    End With

    ' Group Details
    If workflowItemGroupPk <> 0 AndAlso workflow.ItemGroups.ExistsPk(workflowItemGroupPk) Then
      ' Get Workflow Item Group
      WorkflowItem = workflow.ItemGroups.ItemByPk(workflowItemGroupPk)

      SummaryTableGroupDetails = finBL.CreateSummaryTable()
      With SummaryTableGroupDetails
        ' Initialise
        .TableClass = iseSummaryTableClass.Information
        .Caption = ""
        .Columns.AddText(10)
        .Columns.AddText()

        With .Rows
          If Len(WorkflowItem.ItemId) <> 0 Then
            .AddCaptionText("Code:", WorkflowItem.ItemId)
          End If
          .AddCaptionText("Description:", WorkflowItem.Description, iseSummaryTableCellClass.Highlight1)
          .AddCaptionText("Status:", WorkflowItem.StatusText)
          If Len(WorkflowItem.StatusOutcome) <> 0 Then
            If WorkflowItem.Status = isefinWorkflowItemStatus.Complete AndAlso WorkflowItem.OutcomeItems.Count <> 0 Then
              ' With Icon
              strTemp = "**" & WorkflowItem.StatusOutcomeResolved & "** {{icon|" & WorkflowItem.GetStatusCompleteIcon & "}}"
              .AddCaptionWiki("Outcome:", strTemp, iseSummaryTableCellClass.Highlight2)
            Else
              ' Without Icon
              .AddCaptionText("Outcome:", WorkflowItem.StatusOutcomeResolved, iseSummaryTableCellClass.Highlight2)
            End If
          End If
          .AddCaptionText("", "")
        End With
      End With
    End If

    ' Add Summary Tables
    If SummaryTableGroupDetails IsNot Nothing Then SummaryTables.Add("GroupDetails", SummaryTableGroupDetails)
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Workflow Train Stops HTML diagram (Version 1.00, Last updated 25/03/2015).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="workflowTrainStops">
  '''  The Workflow Train Stops.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  A String value containing HTML.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Workflow Key Details page.
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Workflow_TrainStops(callerScriptInfo As ISScriptExecutionInfo,
                                                  workflowTrainStops As finWorkflowTrainStops,
                                         Optional includeActions As Boolean = True,
                                         Optional otherParameters As ISKeyValueList = Nothing) As String

    Const DEFAULT_BULLET_SIZE As Integer = 13
    Const DEFAULT_JOINER_HALF_SIZE As Integer = 27

    Dim BulletBorderColour As String
    Dim BulletColour As String
    Dim BulletSize As Integer
    Dim BulletStrikethrough As Boolean
    Dim BulletStyle As String
    Dim BulletStyleResolved As isefinWorkflowTrainStopBulletStyle
    Dim CaptionBold As Boolean
    Dim CaptionColour As String
    Dim CaptionStrikethrough As Boolean
    Dim CaptionStyle As String
    Dim CurrentGroupFound As Boolean
    Dim CustomMenuItem As ISCustomMenuItem
    Dim i As Integer
    Dim JoinerHalfSize As Integer
    Dim sb As StringBuilder
    Dim WorkflowTrainStop As finWorkflowTrainStop

    ' Initialise
    sb = New StringBuilder()

    If workflowTrainStops IsNot Nothing AndAlso workflowTrainStops.Count <> 0 Then
      ' Initialise
      If workflowTrainStops.BulletSize = 0 Then
        BulletSize = DEFAULT_BULLET_SIZE
      Else
        BulletSize = workflowTrainStops.BulletSize
      End If

      ' Initialise HTML
      sb.Append("<div style='box-sizing:border-box; font-size:0.9em'>")

      For i = 0 To workflowTrainStops.Count - 1
        ' Initialise
        BulletBorderColour = ""
        BulletColour = ""
        BulletStrikethrough = False
        BulletStyle = ""
        CaptionBold = False
        CaptionColour = ""
        CaptionStrikethrough = False
        CaptionStyle = ""
        WorkflowTrainStop = workflowTrainStops(i)

        ' Get Joiner Half Size (can be overridden on each Train Stop)
        If WorkflowTrainStop.JoinerHalfSizeResolved = 0 Then
          JoinerHalfSize = DEFAULT_JOINER_HALF_SIZE
        Else
          JoinerHalfSize = WorkflowTrainStop.JoinerHalfSizeResolved
        End If

        sb.AppendFormat("<div style='display:inline-block; box-sizing:border-box; width:{0}px; margin:4px 0 4px 0; vertical-align:top'>", JoinerHalfSize + JoinerHalfSize + BulletSize)

        ' ----------------------------------------------------------------
        ' Bullet and Joiners (includes IE10 backward compatibility styles)
        ' ----------------------------------------------------------------
        sb.Append("<div style='display:-ms-flexbox; display:flex; -ms-flex-align:center; -ms-flex-pack:center; align-items:center'>")

        ' Bullet Style
        Select Case WorkflowTrainStop.BulletStyle
          Case isefinWorkflowTrainStopBulletStyle.Automatic
            ' Determine from Workflow Item Group
            If WorkflowTrainStop.CurrentTrainStop Then
              BulletStyleResolved = isefinWorkflowTrainStopBulletStyle.Current
            ElseIf WorkflowTrainStop.WorkflowItemGroup Is Nothing Then
              ' Unknown so assume Future
              BulletStyleResolved = isefinWorkflowTrainStopBulletStyle.Future
            Else
              If CurrentGroupFound Then
                ' Future
                BulletStyleResolved = isefinWorkflowTrainStopBulletStyle.Future
              ElseIf WorkflowTrainStop.WorkflowItemGroup.Status = isefinWorkflowItemStatus.Skipped Then
                ' Skipped
                If WorkflowTrainStop.WorkflowItemGroup.Items.CountComplete() = 0 Then
                  BulletStyleResolved = isefinWorkflowTrainStopBulletStyle.SkippedAll
                Else
                  BulletStyleResolved = isefinWorkflowTrainStopBulletStyle.SkippedPartial
                End If
              Else
                ' Completed
                BulletStyleResolved = isefinWorkflowTrainStopBulletStyle.Completed
              End If
            End If

          Case Else
            ' Custom
            BulletStyleResolved = WorkflowTrainStop.BulletStyle
        End Select

        Select Case BulletStyleResolved
          Case isefinWorkflowTrainStopBulletStyle.Completed
            BulletBorderColour = "#2D5680"
            BulletColour = "#3E78B3"

          Case isefinWorkflowTrainStopBulletStyle.Current
            BulletBorderColour = "#2D5680"
            BulletColour = "#E9B35D"

          Case isefinWorkflowTrainStopBulletStyle.Future
            BulletBorderColour = "#2D5680"
            BulletColour = "transparent"

          Case isefinWorkflowTrainStopBulletStyle.SkippedAll
            BulletBorderColour = "#A3B8CC"
            BulletColour = "transparent"
            BulletStrikethrough = True

          Case isefinWorkflowTrainStopBulletStyle.SkippedPartial
            BulletBorderColour = "#A3B8CC"
            BulletColour = "#f0f0f0"
        End Select

        If Len(WorkflowTrainStop.BulletColour) <> 0 Then
          BulletColour = WorkflowTrainStop.BulletColour
        End If

        If Len(WorkflowTrainStop.CaptionColour) <> 0 Then CaptionColour = WorkflowTrainStop.CaptionColour

        BulletStyle = ""
        If Len(BulletBorderColour) <> 0 Then
          If Len(BulletStyle) <> 0 Then BulletStyle &= ";"
          BulletStyle &= ";border-color:" & BulletBorderColour
        End If
        If Len(BulletColour) <> 0 Then
          If Len(BulletStyle) <> 0 Then BulletStyle &= ";"
          BulletStyle &= ";background-color:" & BulletColour
        End If
        If BulletStrikethrough Then
          ' Handled when creating bullet DIV
        End If

        If WorkflowTrainStop.CurrentTrainStop Then
          CurrentGroupFound = True
        End If

        ' Caption Style
        Select Case BulletStyleResolved
          Case isefinWorkflowTrainStopBulletStyle.Completed

          Case isefinWorkflowTrainStopBulletStyle.Current
            CaptionBold = True

          Case isefinWorkflowTrainStopBulletStyle.Future
            CaptionColour = "#A0A0A0"

          Case isefinWorkflowTrainStopBulletStyle.SkippedAll
            CaptionColour = "#c0c0c0"
            CaptionStrikethrough = True

          Case isefinWorkflowTrainStopBulletStyle.SkippedPartial
            CaptionColour = "#A0A0A0"
            CaptionStrikethrough = True
        End Select

        If Len(WorkflowTrainStop.CaptionColour) <> 0 Then CaptionColour = WorkflowTrainStop.CaptionColour

        CaptionStyle = ""
        If Len(CaptionColour) <> 0 Then
          If Len(CaptionStyle) <> 0 Then CaptionStyle &= ";"
          CaptionStyle &= ";color:" & CaptionColour
        End If
        If CaptionStrikethrough Then
          If Len(CaptionStyle) <> 0 Then CaptionStyle &= ";"
          CaptionStyle &= ";text-decoration:line-through"
        End If

        ' Joiner (left)
        sb.AppendFormat("<div style='width:{0}px; height:1px; background-color:{1}'></div>", JoinerHalfSize, If(i = 0, "", "#2D5680"))

        ' Bullet
        If Len(WorkflowTrainStop.ApplicationShortcutUrl) <> 0 Then
          sb.AppendFormat("<a href='{0}'>", WorkflowTrainStop.ApplicationShortcutUrl)
        End If

        Select Case WorkflowTrainStop.BulletShapeResolved
          Case isefinWorkflowTrainStopBulletShape.Default, isefinWorkflowTrainStopBulletShape.Square
            sb.AppendFormat("<div style='width:{2}px; height:{2}px; border:1px solid; {0}' title='{1}'>", BulletStyle, finBL.HtmlEncode(WorkflowTrainStop.Caption), BulletSize)
          Case isefinWorkflowTrainStopBulletShape.Circle
            sb.AppendFormat("<div style='width:{2}px; height:{2}px; border:1px solid; border-radius:{3}px; {0}' title='{1}'>", BulletStyle, finBL.HtmlEncode(WorkflowTrainStop.Caption), BulletSize, BulletSize / 2)
        End Select

        If BulletStrikethrough Then
          sb.AppendFormat("<div style='height:1px; background-color:{0}; margin-top:{1}px'></div>", BulletBorderColour, CInt(BulletSize / 2) - 1)
        End If
        sb.Append("</div>")
        If Len(WorkflowTrainStop.ApplicationShortcutUrl) <> 0 Then
          sb.Append("</a>")
        End If

        ' Joiner (right)
        sb.AppendFormat("<div style='width:{0}px; height:1px; background-color:{1}'></div></a>", JoinerHalfSize, If(i = workflowTrainStops.Count - 1, "", "#2D5680"))
        sb.Append("</div>")

        ' Caption
        sb.AppendFormat("<div style='text-align:center; width:{1}px; overflow:hidden; {0}'>", CaptionStyle, JoinerHalfSize + JoinerHalfSize + BulletSize)
        sb.Append(finBL.HtmlEncode(WorkflowTrainStop.Caption))
        sb.Append("</div>")

        ' -------
        ' Actions
        ' -------
        If WorkflowTrainStop.ActionsMenu.MenuItems.Count <> 0 Then
          sb.Append("<ul style='padding:0; margin:4px 0 0 0; text-align:center; background-color:#f0f0f0; border:1px dotted silver'>")
          For Each CustomMenuItem In WorkflowTrainStop.ActionsMenu.MenuItems
            sb.Append("<li style='display:inline-block; margin:0.25em'>")
            sb.AppendFormat("<a href=""{0}"">{1}</a>", CustomMenuItem.Action, finBL.HtmlEncode(CustomMenuItem.Caption))
            sb.Append("</li>")
          Next
          sb.Append("</ul>")
        End If

        sb.Append("</div>")
      Next

      ' Finalise HTML
      sb.Append("</div>")
    End If

    Return sb.ToString()

  End Function

  ''' <summary>
  '''  Workflow Item Summary.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="workflowItem">
  '''  The Workflow Item to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Workflow Key Details page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function WorkflowItem_Summary(callerScriptInfo As ISScriptExecutionInfo,
                                                   workflowItem As finWorkflowItem,
                                          Optional includeActions As Boolean = True,
                                          Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' WorkflowItem_Summary
    '
    ' Version: 1.03 (01/05/2023)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.02  15/05/2019  ISS                Updated
    '    1.03  01/05/2023  ISS      J030842   'Allocate to User' now supports clearing an Allocated User
    ' #################################################################

    Dim ActionsWikiText As String
    Dim UrlAction As String
    Dim CannotActionMessage As String
    Dim tempDate As Date
    Dim FalseOutcome As String
    Dim HasAutoActionItems As Boolean
    Dim i As Integer
    Dim OutcomeUrl As String
    Dim ScriptDenied As Boolean
    Dim strTemp As String
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim TrueOutcome As String
    Dim Warnings As String
    Dim Workflow As finWorkflow
    Dim WorkflowItemOutcomeItem As finWorkflowItemOutcomeItem
    Dim WorkflowItemOutcomeItems As List(Of finWorkflowItemOutcomeItem)

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()
    Workflow = workflowItem.Workflow
    HasAutoActionItems = Workflow.HasAutoActionItems()

    ' Create Action and Outcome URLs
    UrlAction = String.Format("app://FormAction?action=WorkflowItemAction&workflow={0}&itemPk={1}", Workflow.Pk, workflowItem.Pk)
    OutcomeUrl = String.Format("app://FormAction?action=WorkflowItemSetOutcome&workflow={0}&itemPk={1}&outcome=", Workflow.Pk, workflowItem.Pk)

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      .Columns.AddText(10).NoBreakChars = 16
      .Columns.AddText()

      With .Rows
        ' Description (include Help popup if Help is HTML since we can't display this in a Summary Table)
        If Len(workflowItem.GetHelpNotesAsWikiText()) = 0 Then
          strTemp = workflowItem.GetHelpNotesAsHtml()
        Else
          strTemp = ""
        End If
        If Len(strTemp) = 0 Then
          .AddText(workflowItem.Description, iseSummaryTableCellClass.Highlight1)
        Else
          With .AddText(workflowItem.Description, iseSummaryTableCellClass.Highlight1).Cells(0)
            .ValueFormat = iseSummaryTableCellFormat.WikiTextSimple
            .Value &= " [[app://HtmlShow?popup=True&html=" & finBL.UrlEncode(strTemp) & "|{{icon|InformationTip|View Help|11}}]]"
          End With
        End If

        ' Status
        If workflowItem.Status <> isefinWorkflowItemStatus.NotStarted Then
          .AddCaptionText("Status:", workflowItem.StatusText)
          If Len(workflowItem.StatusOutcome) <> 0 Then
            If workflowItem.Status = isefinWorkflowItemStatus.Complete AndAlso workflowItem.OutcomeItems.Count <> 0 Then
              ' With Icon
              strTemp = "**" & workflowItem.StatusOutcomeResolved & "** {{icon|" & workflowItem.GetStatusCompleteIcon() & "}}"
              .AddCaptionWiki("Outcome:", strTemp, iseSummaryTableCellClass.Highlight2)
            Else
              ' Without Icon
              .AddCaptionText("Outcome:", workflowItem.StatusOutcomeResolved, iseSummaryTableCellClass.Highlight2)
            End If
          End If
          If workflowItem.Status = isefinWorkflowItemStatus.Open Then
            ' Open
          Else
            .AddCaptionUtcDateTimeWithTimeZone("Date:", workflowItem.CompletedUtcDate, finBL.TimeZoneId)
            If workflowItem.CompletedUserPk = 0 Then
              .AddCaptionText("User:", "Completed Automatically")
            Else
              .AddCaptionCodeDescription("User:", workflowItem.CompletedUserId, finBL.Users)
            End If
          End If
        End If

        ' Status Notes
        If workflowItem.Status <> isefinWorkflowItemStatus.NotStarted AndAlso Len(workflowItem.StatusNotes) <> 0 Then
          .AddSectionHeading2("Notes")
          .AddText(workflowItem.StatusNotes)
        End If

        ' Main Action (Action/ Set Outcome)
        If Workflow.Status = isefinWorkflowStatus.Open AndAlso Not finBL.Database.IsReadOnly Then
          ' Initialise
          ActionsWikiText = ""

          If HasAutoActionItems Then
            ' User cannot Action if this Workflow has 'Auto Action' items
            Select Case workflowItem.Status
              Case isefinWorkflowItemStatus.NotStarted, isefinWorkflowItemStatus.Open
                If workflowItem.AutoAction Then
                  .AddText("{{icon|Execute|Auto-Action Item|24}}")
                  Warnings &= "{{info|This 'auto-action' item will be actioned when the Workflow is processed.}}"
                Else
                  Warnings &= "{{info|This Workflow has 'auto-action' items that will be actioned when the Workflow is processed. Until then, no other items can be actioned.}}"
                End If
            End Select
          Else
            Select Case workflowItem.Status
              Case isefinWorkflowItemStatus.NotStarted, isefinWorkflowItemStatus.Open
                If workflowItem.CanAction(CannotActionMessage, ScriptDenied) Then
                  If includeActions Then
                    If workflowItem.Status = isefinWorkflowItemStatus.Open AndAlso workflowItem.ItemType <> isefinWorkflowItemType.ItemGroup Then
                      ' Open Items (i.e., Complete Action only, regardless of Item Type)
                      ActionsWikiText = "{{button icon='WorkflowItem_ActionComplete' iconsize='16' tooltip=""Complete 'Open' item"" hyperlink=""" & UrlAction & """}} "
                    Else
                      Select Case workflowItem.ItemType
                        Case isefinWorkflowItemType.CheckListItem
                          ' Check List Item
                          ActionsWikiText = "{{button icon='check' iconsize='24' tooltip=""" & workflowItem.GetActionDescription(TrueOutcome) & """ hyperlink=""" & UrlAction & """}} "

                        Case isefinWorkflowItemType.Question, isefinWorkflowItemType.ItemGroup
                          ' Set Outcome
                          If workflowItem.OutcomeItems.Count = 0 Then
                            Warnings &= "{{warning|No outcomes defined.}}"
                          ElseIf workflowItem.OutcomeItems.CountVisible = 0 Then
                            Warnings &= "{{warning|No visible outcomes defined.}}"
                          ElseIf workflowItem.OutcomeItems.HasYesTrueOutcomeOnly(TrueOutcome) Then
                            ' Single Yes/ True outcome only so represent like a Check List Item
                            ActionsWikiText = "{{button icon='check' iconsize='24' tooltip=""" & workflowItem.GetActionDescription(TrueOutcome) & """ hyperlink=""" & OutcomeUrl & TrueOutcome & """}}"
                          ElseIf workflowItem.OutcomeItems.HasYesNoTrueFalseOutcomes(TrueOutcome, FalseOutcome) Then
                            ' Yes/ No or True/ False items only
                            ActionsWikiText = "{{button icon='check' iconsize='24' tooltip=""" & workflowItem.GetActionDescription(TrueOutcome) & """ hyperlink=""" & OutcomeUrl & TrueOutcome & """}} "
                            ActionsWikiText &= "{{button icon='cross' iconsize='24' tooltip=""" & workflowItem.GetActionDescription(FalseOutcome) & """ hyperlink=""" & OutcomeUrl & FalseOutcome & """}} "
                          Else
                            ' Bulleted list of outcomes (do not show hidden, repeating outcomes or automatic outcomes for Item Groups)
                            WorkflowItemOutcomeItems = workflowItem.OutcomeItems.GetUserOutcomesList()
                            For Each WorkflowItemOutcomeItem In WorkflowItemOutcomeItems
                              If Len(ActionsWikiText) <> 0 Then ActionsWikiText &= "<br>"
                              ActionsWikiText &= "{{icon|LogsThread2_ChildLast}} [[" & OutcomeUrl & finBL.UrlEncode(WorkflowItemOutcomeItem.Outcome) & "|" & WorkflowItemOutcomeItem.OutcomeDescriptionResolved & "]]"
                            Next
                          End If

                        Case Else
                          ' Action
                          If workflowItem.Status = isefinWorkflowItemStatus.Open AndAlso workflowItem.ItemType <> isefinWorkflowItemType.ItemGroup Then
                            ActionsWikiText = "{{button icon='WorkflowItem_ActionComplete' iconsize='24' tooltip=""" & workflowItem.GetActionDescription(TrueOutcome) & """ hyperlink=""" & UrlAction & """}} "
                          Else
                            ActionsWikiText = "{{button icon='WorkflowItem_Action' iconsize='24' tooltip=""" & workflowItem.GetActionDescription(TrueOutcome) & """ hyperlink=""" & UrlAction & """}} "
                          End If
                      End Select
                    End If
                    .AddWiki(ActionsWikiText)

                    ' Other information
                    If workflowItem.Status = isefinWorkflowItemStatus.NotStarted Then
                      Select Case workflowItem.ItemType
                        Case isefinWorkflowItemType.AllocateToUser
                          ' Allocate to User
                          If workflowItem.AllocateToSupervisor Then
                            Warnings = "{{info|This Workflow will be allocated to your supervisor.}}" & Warnings
                          ElseIf workflowItem.UserPkResolved = 0 Then
                            Warnings = "{{info|The allocated User for this Workflow will be cleared.}}" & Warnings
                          Else
                            Warnings = "{{info|This Workflow will be allocated to **" & workflowItem.UserIdResolved & "**, '" & finBL.Users.ItemByPkSafe(workflowItem.UserPkResolved).Name & "'.}}" & Warnings
                          End If

                        Case isefinWorkflowItemType.Document
                          ' Send Document
                          If finBL.Documents.ExistsPk(workflowItem.DocumentPk) Then
                            If workflowItem.DocumentPublishImmediately Then
                              Warnings = "{{info|" & finBL.Documents.ItemByPk(workflowItem.DocumentPk).FileTypeText & " Document will be published immediately.}}" & Warnings
                            Else
                              Warnings = "{{info|" & finBL.Documents.ItemByPk(workflowItem.DocumentPk).FileTypeText & " Document will be published when the Publish Documents wizard is run.}}" & Warnings
                            End If
                          End If

                        Case isefinWorkflowItemType.Review, isefinWorkflowItemType.Wait
                          ' Review/ Wait
                          If StrComp(workflowItem.Period, "Immediate", CompareMethod.Text) = 0 Then
                            ' Immediate
                          Else
                            tempDate = finBL.Utilities.DateCycleGetTermEndDateFromWorkflow(workflowItem.Period, workflowItem.WaitPeriodBase, workflowItem.PeriodWorkingDays, Workflow, workflowItem.PeriodWorkingDaysCalendarType)
                            Warnings = "{{info|Setting " & workflowItem.ItemTypeText & " period to **" & workflowItem.PeriodDescription & "** will recall this Workflow on **" & finBL.FormatDateLong(tempDate) & "**.}}" & Warnings
                          End If
                      End Select
                    End If
                  End If
                Else
                  If Len(CannotActionMessage) <> 0 Then
                    Warnings &= "{{warning|Cannot action this item. " & CannotActionMessage & "}}"
                  End If
                End If
            End Select

            ' Help notes (Wiki Text)
            Select Case workflowItem.Status
              Case isefinWorkflowItemStatus.Complete, isefinWorkflowItemStatus.NotStarted, isefinWorkflowItemStatus.Open
                If Len(workflowItem.Notes) <> 0 Then
                  strTemp = workflowItem.GetHelpNotesAsWikiText()
                  If Len(strTemp) <> 0 Then
                    Warnings = "{{help|" & strTemp & "}}" & Warnings
                  End If
                End If
            End Select
          End If
        End If

        ' Completed Details
        If workflowItem.Status = isefinWorkflowItemStatus.Complete Then
          ' General Updates performed
          If workflowItem.GeneralUpdatesPerformed Then
            .AddSectionHeading2("Updates Performed")

            ' Flag Colour
            If workflowItem.FlagColourUpdate Then
              If Len(workflowItem.FlagColour) = 0 Then
                .AddCaptionText("Flag " & finBL.CurrentCountry.Terminology(isefinCountryTerminology.Colour) & ":", "Clear Flag")
              Else
                .AddCaptionText("Flag " & finBL.CurrentCountry.Terminology(isefinCountryTerminology.Colour) & ":", "{{icon|Flag[" & workflowItem.FlagColour & "]|" & workflowItem.FlagColour & "}}")
              End If
            End If

            ' Monitor Categories
            If Workflow.WorkflowType.TargetObjectType = isefinWorkflowTargetObjectType.Account AndAlso
               (workflowItem.MonitorCategoryAUpdate OrElse workflowItem.MonitorCategoryBUpdate OrElse workflowItem.MonitorCategoryCUpdate) Then
              If workflowItem.MonitorCategoryAUpdate Then
                If workflowItem.MonitorCategoryAPk = 0 Then
                  .AddCaptionWiki(String.Format("{0}:", finBL.Settings.MonitorCategoryADescriptionResolved), "--(Clear)--")
                Else
                  .AddCaptionCodeDescription(String.Format("{0}:", finBL.Settings.MonitorCategoryADescriptionResolved), workflowItem.MonitorCategoryAPk, finBL.MonitorCategories)
                End If
              End If
              If workflowItem.MonitorCategoryBUpdate Then
                If workflowItem.MonitorCategoryBPk = 0 Then
                  .AddCaptionWiki(String.Format("{0}:", finBL.Settings.MonitorCategoryBDescriptionResolved), "--(Clear)--")
                Else
                  .AddCaptionCodeDescription(String.Format("{0}:", finBL.Settings.MonitorCategoryBDescriptionResolved), workflowItem.MonitorCategoryBPk, finBL.MonitorCategories)
                End If
              End If
              If workflowItem.MonitorCategoryCUpdate Then
                If workflowItem.MonitorCategoryCPk = 0 Then
                  .AddCaptionWiki(String.Format("{0}:", finBL.Settings.MonitorCategoryCDescriptionResolved), "--(Clear)--")
                Else
                  .AddCaptionCodeDescription(String.Format("{0}:", finBL.Settings.MonitorCategoryCDescriptionResolved), workflowItem.MonitorCategoryCPk, finBL.MonitorCategories)
                End If
              End If
            End If
          End If

          ' Account Application
          If Workflow.WorkflowType.TargetObjectType = isefinWorkflowTargetObjectType.Account AndAlso workflowItem.AccountAppStatusSubUpdate Then
            If Len(workflowItem.AccountAppStatusSub) = 0 Then
              .AddCaptionWiki("Sub-Status:", "--(Clear)--")
            Else
              .AddCaptionText("Sub-Status:", workflowItem.AccountAppStatusSub)
            End If
          End If
        End If
      End With

      ' Warnings
      If Workflow.Status = isefinWorkflowStatus.Open AndAlso (workflowItem.Status = isefinWorkflowItemStatus.NotStarted OrElse workflowItem.Status = isefinWorkflowItemStatus.Open) Then
        If workflowItem.Automatic Then Warnings &= "{{info|This is an automatic item that will be actioned when the Workflow is processed.}}"
      End If
      If Workflow.Status = isefinWorkflowStatus.Open AndAlso workflowItem.Status = isefinWorkflowItemStatus.NotStarted AndAlso workflowItem.GroupWithPrevious Then
        Warnings &= "{{info|This grouped item will be skipped if the previous item is successfully actioned.}}"
      End If
      i = Workflow.GetCountResetsByWorkflowItemPk(workflowItem.Pk)
      Select Case i
        Case 0
        Case 1 : Warnings &= "{{info|This item has been reset **1** time.}}"
        Case Else : Warnings &= "{{info|This item has been reset **" & i & "** times.}}"
      End Select
      .TextAfter = Warnings

      ' Actions
      If includeActions AndAlso Workflow.Status <> isefinWorkflowStatus.Closed Then
        With .Actions
          If workflowItem.AllowResetResolved Then
            .AddFormAction("WorkflowItemReset", "Reset this Item", Not finBL.Database.IsReadOnly, String.Format("workflow={0}&itemPk={1}", Workflow.Pk, workflowItem.Pk))
          End If
          If workflowItem.AllowSkipUnskipResolved Then
            .AddFormAction("WorkflowItemToggleSkipped", If(workflowItem.Status = isefinWorkflowItemStatus.Skipped, "Unskip this Item", "Skip this Item"), Not finBL.Database.IsReadOnly, String.Format("workflow={0}&itemPk={1}", Workflow.Pk, workflowItem.Pk))
          End If
          If workflowItem.AllowNotApplicableResolved Then
            .AddFormAction("WorkflowItemToggleNotApplicable", If(workflowItem.Status = isefinWorkflowItemStatus.NotApplicable, "Undo 'Not Applicable'", "Not Applicable"), Not finBL.Database.IsReadOnly, String.Format("workflow={0}&itemPk={1}", Workflow.Pk, workflowItem.Pk))
          End If
        End With
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Workflow Item Audit Items Summary (Version 1.0, Last updated 12/02/2015).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="workflowItem">
  '''  The Workflow Item to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Workflow Key Details page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function WorkflowItem_AuditItems(callerScriptInfo As ISScriptExecutionInfo,
                                                      workflowItem As finWorkflowItem,
                                             Optional includeActions As Boolean = True,
                                             Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim AuditItems As List(Of finObjectAuditItem)
    Dim kvl As ISKeyValueList
    Dim ObjectAuditItem As finObjectAuditItem
    Dim strTemp As String
    Dim SummaryTableAuditDetails As ISSummaryTable
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()
    kvl = finBL.CreateKeyValueList()

    ' Get Audit Items
    AuditItems = workflowItem.Workflow.GetAuditItemsByWorkflowItemPk(workflowItem.Pk)

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .Caption = ""
      .AutoStripe = True

      If AuditItems.Count <> 0 Then
        ' Columns
        With .Columns
          .AddDate("Date")
          .AddText("User", 10)
          .AddText("Details")
        End With

        For Each ObjectAuditItem In AuditItems
          ' Get audit details
          SummaryTableAuditDetails = finBL.CreateSummaryTable()
          With SummaryTableAuditDetails
            .TableClass = iseSummaryTableClass.Information
            .Columns.AddText(10).NoBreakChars = 16
            .Columns.AddText()

            With .Rows
              .AddCaptionDateTime("Date:", ObjectAuditItem.Date)
              .AddCaptionCodeDescription("User:", ObjectAuditItem.UserId, finBL.Users)
              .AddCaptionText("Details:", ObjectAuditItem.Notes)
              If kvl.Exists("Status") Then .AddCaptionText("Status:", kvl.GetString("Status"))
              If kvl.Exists("StatusOutcome") Then .AddCaptionText("Outcome:", kvl.GetString("StatusOutcome"))
              If kvl.Exists("StatusNotes") Then .AddCaptionText("Notes:", kvl.GetString("StatusNotes"))
            End With
          End With
          kvl.FromXmlString(ObjectAuditItem.ValueOriginal)
          strTemp = finBL.Utilities.GetHtmlFromSummaryTable(SummaryTableAuditDetails)

          With .Rows.Add().Cells
            .AddDate(ObjectAuditItem.Date)
            .AddText(ObjectAuditItem.UserId)
            With .AddText(ObjectAuditItem.Notes)
              ' Show details popup
              If Len(strTemp) <> 0 Then
                .Hyperlink = finBL.CreateApplicationShortcutHtmlShow(strTemp, "Audit Details", True).ToUrlString(False)
                .HyperlinkClass = iseSummaryTableHyperlinkClass.ApplicationShortcut
              End If
            End With
          End With
        Next
      End If

      ' Warnings
      If workflowItem.Status = isefinWorkflowItemStatus.Complete AndAlso workflowItem.AutoAction Then
        Warnings &= "{{info|This item was auto-actioned.}}"
      End If
      If workflowItem.StatusUpdatedFromScript Then
        Warnings &= "{{info|This item's status was set from Script code.}}"
      End If
      .TextAfter = Warnings

      ' Actions
      If includeActions Then
        With .Actions
        End With
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Workflow Item Supplemental details for completed Workflow Items (Version 1.04, Last updated 24/09/2018).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="workflowItem">
  '''  The Workflow Item to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>Workflow
  '''   Used in various places, e.g., Workflow Key Details page.
  '''  </para>
  '''  <para>
  '''   Returns the a Summary Table for each supplemental piece of information, e.g., if there is a Log linked to a Credit Enquiry.
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function WorkflowItem_Supplemental(callerScriptInfo As ISScriptExecutionInfo,
                                                        workflowItem As finWorkflowItem,
                                               Optional includeActions As Boolean = True,
                                               Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim BankAccountEnquiryResponse As ISBankAccountEnquiryResponse
    Dim CountBankEnquiry As Integer
    Dim CountCreditBureauMonitor As Integer
    Dim CountCreditEnquiry As Integer
    Dim CountDecisionOutcome As Integer
    Dim CountDocument As Integer
    Dim CountElectronicSignature As Integer
    Dim CountOutgoingCommunication As Integer
    Dim CountPpsrSearch As Integer
    Dim CountSecurityEnquiry As Integer
    Dim CreditMonitorResponse As ISCreditMonitorResponse
    Dim CreditEnquiryResponse As ISCreditEnquiryResponse
    Dim DecisionOutcome As finDecisionOutcome
    Dim ElectronicSignatureResponse As ISElectronicSignatureResponse
    Dim i As Integer
    Dim kvl As ISKeyValueList
    Dim Log As finLogRO
    Dim SecurityEnquiryResponse As ISSecurityEnquiryResponse
    Dim ServiceLogsHandled As ISList
    Dim strTemp As String
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String
    Dim Workflow As finWorkflow

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTables = finBL.CreateSummaryTables()
    Workflow = workflowItem.Workflow
    ServiceLogsHandled = New ISList()

    If workflowItem.Status = isefinWorkflowItemStatus.Complete Then
      ' Log-based (in reverse order so recent are at the top)
      For i = workflowItem.Logs.Count - 1 To 0 Step -1
        ' Initialise
        Log = workflowItem.Logs(i)
        Warnings = ""

        If Log.IsBankAccountEnquiry AndAlso Not ServiceLogsHandled.Exists(CStr(Log.ServiceLogPk)) Then
          ' --------------------
          ' Bank Account Enquiry
          ' --------------------
          SummaryTableMain = finBL.CreateSummaryTable()
          With SummaryTableMain
            ' Initialise
            .TableClass = iseSummaryTableClass.Information
            .Caption = "Bank Account Enquiry"
            .Columns.AddText(10).NoBreakChars = 16
            .Columns.AddText()

            ' Get Bank Account Enquiry Response from Service Log
            If finBL.CreditBureau.GetBankAccountEnquiryResponseFromServiceLog(Log.ServiceLog, BankAccountEnquiryResponse) Then
              With .Rows
                .AddCaptionText("Service:", BankAccountEnquiryResponse.ServiceName)
                .AddCaptionDateTime("Date:", BankAccountEnquiryResponse.EnquiryDate)
                .AddCaptionText("Product:", BankAccountEnquiryResponse.ProductId)
              End With
            Else
              With .Rows
                .AddCaptionText("Service:", Log.ServiceLog.ServiceId)
              End With
              .TextAfter = "{{error|" & finBL.Error.Message(True) & "}}"
            End If

            ' Actions
            With .Actions
              .AddHtmlShowFunction("ServiceReport", "View Bank Account Enquiry", "ServiceReport", "Bank Account Enquiry", "serviceLogPk=" & Log.ServiceLogPk).ShowInWebInterfaces = True
            End With
          End With

          ' Add Summary Table
          CountBankEnquiry += 1
          SummaryTables.Add("BankEnquiry" & CountBankEnquiry, SummaryTableMain)

          ' Record Service Log
          ServiceLogsHandled.Add(CStr(Log.ServiceLogPk))
        ElseIf Log.IsCreditBureauMonitor AndAlso Not ServiceLogsHandled.Exists(CStr(Log.ServiceLogPk)) Then
          ' =====================
          ' Credit Bureau Monitor
          ' =====================
          SummaryTableMain = finBL.CreateSummaryTable()
          With SummaryTableMain
            ' Initialise
            .TableClass = iseSummaryTableClass.Information
            .Caption = "Credit Bureau Monitor"
            .Columns.AddText(10).NoBreakChars = 16
            .Columns.AddText()

            ' Get Credit Enquiry Response from Service Log
            If finBL.CreditBureau.GetCreditBureauMonitorResponseFromServiceLog(Log.ServiceLog, CreditMonitorResponse) Then
              With .Rows
                .AddCaptionText("Service:", CreditMonitorResponse.ServiceName)
                .AddCaptionDateTime("Date:", CreditMonitorResponse.EnquiryDate)
                .AddCaptionText("Status:", Log.ServiceLog.ResponseStatusText)
              End With
            Else
              SummaryTableMain.TextBefore = "{{error|" & finBL.Error.Message(True) & "}}"
              With .Rows
                .AddCaptionText("Service:", Log.ServiceLog.ServiceId)
              End With
            End If

            ' Actions
            With .Actions
              .AddHtmlShowFunction("ServiceReport", "View Credit Bureau Monitor", "ServiceReport", "Credit Bureau Monitor", "serviceLogPk=" & Log.ServiceLogPk).ShowInWebInterfaces = True
            End With
          End With

          ' Add Summary Table
          CountCreditBureauMonitor += 1
          SummaryTables.Add("CreditBureauMonitor" & CountCreditBureauMonitor, SummaryTableMain)

          ' Record Service Log
          ServiceLogsHandled.Add(CStr(Log.ServiceLogPk))
        ElseIf Log.IsCreditEnquiry AndAlso Not ServiceLogsHandled.Exists(CStr(Log.ServiceLogPk)) Then
          ' --------------
          ' Credit Enquiry
          ' --------------
          SummaryTableMain = finBL.CreateSummaryTable()
          With SummaryTableMain
            ' Initialise
            .TableClass = iseSummaryTableClass.Information
            .Caption = "Credit Enquiry"
            .Columns.AddText(10).NoBreakChars = 16
            .Columns.AddText()

            ' Get Credit Enquiry Response from Service Log
            If finBL.CreditBureau.GetCreditEnquiryResponseFromServiceLog(Log.ServiceLog, CreditEnquiryResponse) Then
              With .Rows
                .AddCaptionText("Service:", CreditEnquiryResponse.ServiceName)
                .AddCaptionDateTime("Date:", CreditEnquiryResponse.EnquiryDate)
                .AddCaptionText("Name:", CreditEnquiryResponse.Name)
                .AddCaptionText("Product:", CreditEnquiryResponse.ProductId)
              End With
            Else
              SummaryTableMain.TextBefore = "{{error|" & finBL.Error.Message(True) & "}}"
              With .Rows
                .AddCaptionText("Service:", Log.ServiceLog.ServiceId)
              End With
            End If

            ' Actions
            With .Actions
              .AddHtmlShowFunction("ServiceReport", "View Credit Enquiry", "ServiceReport", "Credit Enquiry", "serviceLogPk=" & Log.ServiceLogPk).ShowInWebInterfaces = True
            End With
          End With

          ' Add Summary Table
          CountCreditEnquiry += 1
          SummaryTables.Add("CreditEnquiry" & CountCreditEnquiry, SummaryTableMain)

          ' Record Service Log
          ServiceLogsHandled.Add(CStr(Log.ServiceLogPk))
        ElseIf Log.IsElectronicSignature AndAlso Not ServiceLogsHandled.Exists(CStr(Log.ServiceLogPk)) Then
          ' ====================
          ' Electronic Signature
          ' ====================
          SummaryTableMain = finBL.CreateSummaryTable()
          With SummaryTableMain
            ' Initialise
            .TableClass = iseSummaryTableClass.Information
            .Caption = "Electronic Signature"
            .Columns.AddText(10).NoBreakChars = 16
            .Columns.AddText()

            ' Get Electronic Signature Response from Service Log
            If finBL.ElectronicSignature.GetResponseFromServiceLog(Log.ServiceLog, ElectronicSignatureResponse) Then
              With .Rows
                .AddCaptionText("Service:", ElectronicSignatureResponse.ServiceName)
                .AddCaptionDateTime("Date:", ElectronicSignatureResponse.RequestDate)
                .AddCaptionText("Status:", Log.ServiceLog.ResponseStatusText)
              End With
            Else
              SummaryTableMain.TextBefore = "{{error|" & finBL.Error.Message(True) & "}}"
              With .Rows
                .AddCaptionText("Service:", Log.ServiceLog.ServiceId)
              End With
            End If

            ' Actions
            With .Actions
              .AddHtmlShowFunction("ServiceReport", "View Electronic Signature", "ServiceReport", "Electronic Signature", "serviceLogPk=" & Log.ServiceLogPk).ShowInWebInterfaces = True
            End With
          End With

          ' Add Summary Table
          CountElectronicSignature += 1
          SummaryTables.Add("ElectronicSignature" & CountElectronicSignature, SummaryTableMain)

          ' Record Service Log
          ServiceLogsHandled.Add(CStr(Log.ServiceLogPk))
        ElseIf Log.IsSecurityEnquiry AndAlso Not ServiceLogsHandled.Exists(CStr(Log.ServiceLogPk)) Then
          ' ----------------
          ' Security Enquiry
          ' ----------------
          SummaryTableMain = finBL.CreateSummaryTable()
          With SummaryTableMain
            .TableClass = iseSummaryTableClass.Information
            .Caption = "Security Enquiry"
            .Columns.AddText(16).NoBreakChars = 20
            .Columns.AddText()

            ' Get Security Enquiry Response from Service Log
            If finBL.SecurityEnquiry.GetSecurityEnquiryResponseFromServiceLog(Log.ServiceLog, SecurityEnquiryResponse) Then
              With .Rows
                .AddCaptionText("Service:", SecurityEnquiryResponse.ServiceName)
                .AddCaptionDateTime("Date:", SecurityEnquiryResponse.EnquiryDate)
                .AddCaptionText("Product:", SecurityEnquiryResponse.ProductId)
              End With

              ' Actions
              With .Actions
                .AddHtmlShowFunction("ServiceReport", "View Security Enquiry", "ServiceReport", "Security Enquiry", "serviceLogPk=" & Log.ServiceLogPk).ShowInWebInterfaces = True
              End With
            Else
              With .Rows
                .AddCaptionText("Service:", Log.ServiceLog.ServiceId)
              End With
              .TextAfter = "{{error|" & finBL.Error.Message(True) & "}}"
            End If
          End With

          ' Add Summary Table
          CountSecurityEnquiry += 1
          SummaryTables.Add("SecurityEnquiry" & CountSecurityEnquiry, SummaryTableMain)

          ' Record Service Log
          ServiceLogsHandled.Add(CStr(Log.ServiceLogPk))
        ElseIf Log.ExtendedType = isefinLogExtendedType.DecisionOutcome OrElse Log.ExtendedType = isefinLogExtendedType.ClientIdentificationDecisionOutcome Then
          ' ----------------
          ' Decision Outcome
          ' ----------------
          SummaryTableMain = finBL.CreateSummaryTable()
          With SummaryTableMain
            ' Initialise
            .TableClass = iseSummaryTableClass.Information
            .Caption = "Decision Outcome"
            .Columns.AddText(10).NoBreakChars = 16
            .Columns.AddText()

            If Log.GetDecisionOutcomeFromExtendedData(DecisionOutcome) Then
              With .Rows
                With .AddCaptionText("Outcome:", DecisionOutcome.OutcomeStatusText, iseSummaryTableCellClass.Highlight1).Cells(1)
                  Select Case DecisionOutcome.OutcomeStatus
                    Case isefinDecisionOutcomeStatus.Fail : .ForegroundColour = "red"
                    Case isefinDecisionOutcomeStatus.Pass : .ForegroundColour = "green"
                    Case isefinDecisionOutcomeStatus.Refer : .ForegroundColour = "blue"
                  End Select
                End With
                If Len(DecisionOutcome.OutcomeCode) <> 0 Then
                  .AddCaptionText("Code:", DecisionOutcome.OutcomeCode)
                End If
                If Len(DecisionOutcome.OutcomeMessageResolved) <> 0 Then
                  .AddCaptionText("Message:", DecisionOutcome.OutcomeMessageResolved)
                End If
                .AddCaptionCodeDescription("Decision Card:", DecisionOutcome.DecisionCardId, finBL.DecisionCards)
              End With

              ' Actions
              With .Actions
                .AddHtmlShowFunction("DecisionOutcome", "View Decision Outcome", "DecisionOutcomeSummary", "Decision Outcome", "logPk=" & Log.Pk & "&logClass=" & Log.LogClass.ToString())
              End With
            Else
              .TextAfter = "{{error|" & finBL.Error.Message(True) & "}}"
            End If
          End With

          ' Add Summary Table
          CountDecisionOutcome += 1
          SummaryTables.Add("DecisionOutcome" & CountDecisionOutcome, SummaryTableMain)
        ElseIf Log.IsDocumentLog OrElse (Log.ExtendedType = isefinLogExtendedType.Email OrElse Log.ExtendedType = isefinLogExtendedType.Sms) AndAlso Log.PublishStatus <> isefinLogPublishStatus.NotIssued Then
          ' ------------------------
          ' Document (or Email/ SMS)
          ' ------------------------
          kvl = Log.GetExtendedDataAsKeyValueList()

          SummaryTableMain = finBL.CreateSummaryTable()
          With SummaryTableMain
            ' Initialise
            .TableClass = iseSummaryTableClass.Information
            Select Case Log.LogType
              Case isefinLogType.Document
                .Caption = "Document"
              Case isefinLogType.DocumentEmail
                .Caption = "Email Document"
              Case isefinLogType.DocumentSms
                .Caption = "SMS Document"
              Case Else
                Select Case Log.ExtendedType
                  Case isefinLogExtendedType.Email
                    .Caption = "Email"
                  Case isefinLogExtendedType.Sms
                    .Caption = "SMS"
                  Case Else
                    .Caption = "Log"
                End Select
            End Select
            .Columns.AddText(10).NoBreakChars = 16
            .Columns.AddText()

            With .Rows
              If Log.DocumentPk <> 0 Then
                .AddCaptionCodeDescription("Document:", Log.DocumentId, finBL.Documents)
              End If

              ' Extended Type-specific
              Select Case Log.ExtendedType
                Case isefinLogExtendedType.Email
                  ' Email
                  strTemp = kvl.GetString("To")
                  strTemp = Replace(strTemp, ";", "; ")
                  strTemp = Replace(strTemp, ",", ", ")
                  .AddCaptionText("To:", strTemp).RowClass = iseSummaryTableRowClass.Alt2

                Case isefinLogExtendedType.Sms
                  ' SMS
                  strTemp = kvl.GetString("Phone")
                  strTemp = Replace(strTemp, ";", "; ")
                  strTemp = Replace(strTemp, ",", ", ")
                  .AddCaptionText("To:", strTemp).RowClass = iseSummaryTableRowClass.Alt2
                  .AddCaptionText("Message:", kvl.GetString("Message")).RowClass = iseSummaryTableRowClass.Alt2
              End Select

              ' Status-Specific
              Select Case Log.PublishStatus
                Case isefinLogPublishStatus.Open, isefinLogPublishStatus.ToSend
                  .AddCaptionText("Status:", Log.PublishStatusText)
                  If Log.PublishOnUtcDate <> Nothing Then
                    .AddCaptionUtcDateTimeWithTimeZone("Publish On:", Log.PublishOnUtcDate, Log.PublishOnTimeZoneId)
                  End If

                Case isefinLogPublishStatus.Published
                  .AddCaptionText("Status:", Log.PublishStatusText).Cells(1).ForegroundColour = "green"
                  If Log.PublishedUtcDate <> Nothing Then
                    .AddCaptionUtcDateTimeWithTimeZone("Published On:", Log.PublishedUtcDate, Log.PublishOnTimeZoneId)
                  End If

                Case isefinLogPublishStatus.Failed
                  .AddCaptionText("Status:", Log.PublishStatusText).Cells(1).ForegroundColour = "red"

                Case Else
                  .AddCaptionText("Status:", Log.PublishStatusText)
              End Select
            End With

            ' Actions
            With .Actions
              .AddFormShow("DocumentView", "View Document Details", Log.LogFormKey, True, "id=" & Log.Pk & "&page=Document")

              ' Extended-Type specific
              Select Case Log.ExtendedType
                Case isefinLogExtendedType.Email
                  ' Email
                  .AddHtmlShowFunction("DocumentPreviewEmail", "Preview Email", "LogEmailPreview", "Preview Email to " & kvl.GetString("To"), "popup=true&logClass=" & Log.LogClass.ToString() & "&logPk=" & Log.Pk)
              End Select
            End With

            ' Warnings
            If Log.PublishStatus = isefinLogPublishStatus.Open OrElse Log.PublishStatus = isefinLogPublishStatus.ToSend Then
              Warnings &= "{{info|Document will be published when the Publish Documents wizard is run.}}"
            End If
            .TextAfter = Warnings
          End With

          ' Add Summary Table
          CountDocument += 1
          SummaryTables.Add("Document" & CountDocument, SummaryTableMain)
        ElseIf Log.ServiceLog IsNot Nothing AndAlso StrComp(Log.ServiceLog.ServiceId, "PPSRG2B.NZ", CompareMethod.Text) = 0 AndAlso StrComp(Log.ServiceLog.ProductId, "PPSR_SEARCH", CompareMethod.Text) = 0 Then
          ' ---------------
          ' PPSR G2B Search
          ' ---------------
          SummaryTableMain = finBL.CreateSummaryTable()
          With SummaryTableMain
            ' Initialise
            .TableClass = iseSummaryTableClass.Information
            .Caption = "PPSR G2B Search"
            .Columns.AddText(10).NoBreakChars = 16
            .Columns.AddText()

            With .Rows
              .AddCaptionUtcDateTimeWithTimeZone("Date:", Log.LogUtcDate, Log.LogTimeZoneId)
              .AddCaptionText("Subject:", Log.Subject)
              .AddText(Log.Notes)
            End With

            ' Actions
            With .Actions
              .AddFormShow("LogView", "View PPSR G2B Search", Log.LogFormKey, True, "id=" & Log.Pk & "&page=PPSR G2B Search")
            End With
          End With

          ' Add Summary Table
          CountPpsrSearch += 1
          SummaryTables.Add("PPSRSearch" & CountPpsrSearch, SummaryTableMain)
        ElseIf Log.ServiceLog IsNot Nothing AndAlso StrComp(Log.ServiceLog.ServiceId, "PPSRNZ", CompareMethod.Text) = 0 AndAlso StrComp(Log.ServiceLog.ProductId, "SEARCH", CompareMethod.Text) = 0 Then
          ' --------------
          ' PPSR NZ Search
          ' --------------
          SummaryTableMain = finBL.CreateSummaryTable()
          With SummaryTableMain
            ' Initialise
            .TableClass = iseSummaryTableClass.Information
            .Caption = "PPSR Search"
            .Columns.AddText(10).NoBreakChars = 16
            .Columns.AddText()

            With .Rows
              .AddCaptionUtcDateTimeWithTimeZone("Date:", Log.LogUtcDate, Log.LogTimeZoneId)
              .AddCaptionText("Subject:", Log.Subject)
              .AddText(Log.Notes)
            End With

            ' Actions
            With .Actions
              .AddFormShow("LogView", "View PPSR Search", Log.LogFormKey, True, "id=" & Log.Pk & "&page=PPSR Transaction")
            End With
          End With

          ' Add Summary Table
          CountPpsrSearch += 1
          SummaryTables.Add("PPSRSearch" & CountPpsrSearch, SummaryTableMain)
        ElseIf workflowItem.ItemType = isefinWorkflowItemType.OutgoingCommunication Then
          ' ----------------------
          ' Outgoing Communication
          ' ----------------------
          SummaryTableMain = finBL.CreateSummaryTable()
          With SummaryTableMain
            ' Initialise
            .TableClass = iseSummaryTableClass.Information
            .Caption = "Outgoing Communication"
            .Columns.AddText(10).NoBreakChars = 16
            .Columns.AddText()

            With .Rows
              .AddCaptionUtcDateTimeWithTimeZone("Date:", Log.LogUtcDate, Log.LogTimeZoneId)
              .AddCaptionText("Subject:", Log.Subject)
              .AddText(Log.Notes)
            End With

            ' Actions
            With .Actions
              .AddFormShow("LogView", "View Log", Log.LogFormKey, True, "id=" & Log.Pk)
            End With
          End With

          ' Add Summary Table
          CountOutgoingCommunication += 1
          SummaryTables.Add("OutgoingCommunication" & CountOutgoingCommunication, SummaryTableMain)
        End If
      Next
    End If

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Balance Allocations Summary (Version 1.02, Last updated 30/05/2018).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="account">
  '''  The Account to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Account Financial page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main Interest details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_BalanceAllocations(callerScriptInfo As ISScriptExecutionInfo,
                                                         account As finAccount,
                                                Optional includeActions As Boolean = True,
                                                Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim Balance As Decimal
    Dim BalancePrincipalNIB As Decimal
    Dim BalancePrincipalIB As Decimal
    Dim BalanceInterest As Decimal
    Dim BalanceFeeNIB As Decimal
    Dim BalanceFeeIB As Decimal
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Values
    account.GetBalanceAllocations(BalancePrincipalNIB, BalancePrincipalIB, BalanceInterest, BalanceFeeNIB, BalanceFeeIB)
    Balance = BalancePrincipalNIB + BalancePrincipalIB + BalanceInterest + BalanceFeeNIB + BalanceFeeIB

    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .Columns.AddText()
      .Columns.AddCurrency()

      With .Rows
        Select Case account.AccountClass
          Case isefinAccountClass.Deposit
            If BalancePrincipalNIB <> 0 Then .AddCaptionCurrency("Principal (Non Interest Bearing)", -BalancePrincipalNIB)
            .AddCaptionCurrency("Principal (Interest Bearing)", -BalancePrincipalIB)
            .AddCaptionCurrency("Interest", -BalanceInterest)
            If BalanceFeeNIB <> 0 Then .AddCaptionCurrency("Fees (Non Interest Bearing)", -BalanceFeeNIB)
            If BalanceFeeIB <> 0 Then .AddCaptionCurrency("Fees (Interest Bearing)", -BalanceFeeIB)
            With .AddCaptionCurrency("Current Balance", -Balance, True)
              .RowClass = iseSummaryTableRowClass.FooterBold
            End With

          Case isefinAccountClass.Disbursement
            .AddCaptionCurrency("Principal", BalancePrincipalNIB + BalancePrincipalIB)
            If BalanceInterest <> 0 Then .AddCaptionCurrency("Interest", BalanceInterest)
            If BalanceFeeNIB + BalanceFeeIB <> 0 Then .AddCaptionCurrency("Fees", BalanceFeeNIB + BalanceFeeIB)
            With .AddCaptionCurrency("Current Balance", Balance, True)
              .RowClass = iseSummaryTableRowClass.FooterBold
            End With

          Case Else
            If BalancePrincipalNIB <> 0 Then .AddCaptionCurrency("Principal (Non Interest Bearing)", BalancePrincipalNIB)
            .AddCaptionCurrency("Principal (Interest Bearing)", BalancePrincipalIB)
            .AddCaptionCurrency("Interest", BalanceInterest)
            If BalanceFeeNIB <> 0 Then .AddCaptionCurrency("Fees (Non Interest Bearing)", BalanceFeeNIB)
            If BalanceFeeIB <> 0 Then .AddCaptionCurrency("Fees (Interest Bearing)", BalanceFeeIB)
            With .AddCaptionCurrency("Current Balance", Balance, True)
              .RowClass = iseSummaryTableRowClass.FooterBold
            End With
        End Select
      End With

      ' Warnings
      Select Case account.AccountClass
        Case isefinAccountClass.Deposit
        Case Else
          If Balance < 0 Then
            If BalancePrincipalNIB > 0 OrElse BalancePrincipalIB > 0 OrElse BalanceInterest > 0 OrElse BalanceFeeNIB > 0 OrElse BalanceFeeIB > 0 Then
              Warnings &= "{{warning|Balance breakdown includes positive amounts.}}"
            End If
          Else
            If BalancePrincipalNIB < 0 OrElse BalancePrincipalIB < 0 OrElse BalanceInterest < 0 OrElse BalanceFeeNIB < 0 OrElse BalanceFeeIB < 0 Then
              Warnings &= "{{warning|Balance breakdown includes negative amounts.}}"
            End If
          End If
      End Select
      .TextAfter = Warnings

      ' Actions
      If includeActions Then
        With .Actions
          .AddFormAction("BalanceAdjustment", "Balance Adjustment", Not finBL.Database.IsReadOnly AndAlso account.Status = isefinAccountStatus.Open AndAlso finBL.CurrentUser.Permissions.Allow("Account.BalanceAdjustment")).ShowInWebInterfaces = True
        End With
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Dates Summary.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="account">
  '''  The Account to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Account Financial page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main Interest details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_Dates(callerScriptInfo As ISScriptExecutionInfo,
                                            account As finAccount,
                                   Optional includeActions As Boolean = True,
                                   Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' Account_Dates
    '
    ' Version: 1.03 (11/01/2023)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.03  11/01/2023  ISS      J030287   Added action to print Quotation
    ' #################################################################

    Dim Ok As Boolean
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Values

    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Columns.AddText(12)
      .Columns.AddText()

      With .Rows
        .AddCaptionWiki("Created:", finBL.Utilities.GetUserAndDateWikiText("", account.CreatedUserPk, account.CreatedDate))
        .AddCaptionDate("Quoted:", account.DateQuoted)
        Select Case account.Status
          Case isefinAccountStatus.Quote
          Case isefinAccountStatus.Declined
            .AddCaptionDate("Declined:", account.DateClosed)
          Case isefinAccountStatus.Unwanted
            .AddCaptionDate("Unwanted:", account.DateClosed)
          Case Else
            .AddCaptionDate("Accepted:", account.DateAccepted)
            .AddCaptionDate("Signed:", account.DateSigned)
            If account.OpenedDate = Nothing Then
              ' Not available, e.g., this Account was opened during a conversion
              .AddCaptionText("Opened:", "Not available")
            Else
              .AddCaptionWiki("Opened:", finBL.Utilities.GetUserAndDateWikiText("", account.OpenedUserPk, account.OpenedDate))
            End If
        End Select
      End With

      ' Warnings
      .TextAfter = Warnings

      ' Actions
      If includeActions Then
        With .Actions
          Ok = False
          If account.DateQuoted = Nothing OrElse finBL.CurrentUser.Permissions.Allow("Account.DateQuotedUpdate") Then Ok = True
          If account.DateAccepted = Nothing OrElse finBL.CurrentUser.Permissions.Allow("Account.DateAcceptedUpdate") Then Ok = True
          If account.DateSigned = Nothing OrElse finBL.CurrentUser.Permissions.Allow("Account.DateSignedUpdate") Then Ok = True
          If Ok Then
            .AddFormAction("AccountDateEdit", "Edit Dates", Not finBL.Database.IsReadOnly AndAlso account.Status = isefinAccountStatus.Open).ShowInWebInterfaces = True
          End If
          Select Case account.Status
            Case isefinAccountStatus.Quote, isefinAccountStatus.Declined, isefinAccountStatus.Unwanted
              If account.AccountType.QuoteDocumentPk <> 0 Then
                .AddApplicationShortcutUrl("PrintQuotation", "Print Quotation", "app://global?type=Account.PrintQuotation&accountId=" & finBL.UrlEncode(account.AccountId)).ShowInWebInterfaces = True
              End If
          End Select
        End With
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Comparison Summary (Version 1.03 Last updated 17/03/2020).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="account">
  '''  The Account to summarise.
  ''' </param>
  ''' <param name="accountCalc">
  '''  The Account Calculation.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Account Financial page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main Interest details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_ComparisonRate(callerScriptInfo As ISScriptExecutionInfo,
                                                     account As finAccount,
                                            Optional accountCalc As finAccountCalc = Nothing,
                                            Optional includeActions As Boolean = True,
                                            Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Calculation
    If accountCalc Is Nothing Then
      accountCalc = account.Calculation
    End If

    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Columns.AddText(12)
      .Columns.AddText()

      With .Rows
        If account.Status = isefinAccountStatus.Quote Then
          If accountCalc.ComparisonRateCalc.Calculate Then
            If accountCalc.ComparisonRate < 0 Then
              .AddCaptionWiki("Rate:", "**!!Error!!**")
            Else
              .AddCaptionPercentage("Rate:", accountCalc.ComparisonRate / 100, 8, True)
            End If
            If accountCalc.ComparisonRateMaximum <> 0 Then
              .AddCaptionPercentage("Maximum:", accountCalc.ComparisonRateMaximum / 100, 8, True)
            End If
          Else
            Warnings &= "{{Warning|" & finBL.Error.Message(True) & "}}"
          End If

          ' Warning if scripted
          If accountCalc.ComparisonRateCalc.IsScripted Then
            Warnings &= "{{Warning|" & String.Format("Comparison Rate used script '{0}'.", accountCalc.ComparisonRateCalc.ScriptId) & "}}"
          End If
        Else
          If accountCalc.ComparisonRate < 0 Then
            .AddCaptionWiki("Rate:", "**!!Error!!**")
          Else
            .AddCaptionPercentage("Rate:", accountCalc.ComparisonRate / 100, 8, True)
          End If
          If accountCalc.ComparisonRateMaximum <> 0 Then
            .AddCaptionPercentage("Maximum:", accountCalc.ComparisonRateMaximum / 100, 8, True)
          End If
        End If
      End With

      ' Warnings
      If accountCalc.ComparisonRateMaximum <> 0 AndAlso accountCalc.ComparisonRate > accountCalc.ComparisonRateMaximum Then
        Warnings &= "{{Warning|" & String.Format("Rate exceeds maximum limit of {0}.", finBL.FormatPercentage(accountCalc.ComparisonRateMaximum / 100, 4)) & "|true}}"
      End If
      .TextAfter = Warnings

      ' Actions
      If includeActions Then
        With .Actions
        End With
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Financial Details Summary. Note, designed for Revolving Credit Loan, Deposit and Disbursement Accounts.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="account">
  '''  The Account to summarise.
  ''' </param>
  ''' <param name="accountCalc">
  '''  The Account Calculation.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Account Financial page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main Financial details.</description></item>
  '''    <item><code>Investment</code><description>Investment details (for Deposit Accounts).</description></item>
  '''    <item><code>CreditLimits</code><description>Credit Limit details (where Account has Credit Limits).</description></item>
  '''    <item><code>MaturityInstructions</code><description>Maturity Instruction details (for Deposit Accounts).</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_FinancialDetails(callerScriptInfo As ISScriptExecutionInfo,
                                                       account As finAccount,
                                              Optional accountCalc As finAccountCalc = Nothing,
                                              Optional includeActions As Boolean = True,
                                              Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' Account_FinancialDetails
    '
    ' Version: 1.21 (30/01/2024)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.15  12/08/2020  ISS                  
    '    1.16  21/02/2022  ISS      J028215   Add Additional Investment information
    '    1.17  29/03/2023  ISS      J030794   Credit Limit "Review" button now available in finPOWER Connect Cloud
    '    1.18  08/01/2024  ISS      J032698   Updated Permission Keys
    '    1.19  10/01/2024  ISS      J032713   Updated Permission Keys
    '    1.20  24/01/2024  ISS      J032781   Updated Permission Keys
    '    1.21  30/01/2024  ISS      J032813   Updated Permission Keys
    ' #################################################################

    Dim AvailableCredit1 As Decimal
    Dim AvailableCredit2 As Decimal
    Dim AvailableCredit3 As Decimal
    Dim Balance As Decimal
    Dim CreditLimit1 As Decimal
    Dim CreditLimit1FutureChange As Boolean
    Dim CreditLimit2 As Decimal
    Dim CreditLimit2FutureChange As Boolean
    Dim CreditLimit3 As Decimal
    Dim CreditLimit3FutureChange As Boolean
    Dim DateAsAt As Date
    Dim DateMaturity As Date
    Dim Days As Long
    Dim InvestmentAdditional As Decimal
    Dim InvestmentNew As Decimal
    Dim InvestmentPending As Decimal
    Dim InvestmentReceived As Decimal
    Dim InvestmentReinvested As Decimal
    Dim InvestmentTransferIn As Decimal
    Dim InvestmentTransferOut As Decimal
    Dim InvestmentValue As Decimal
    Dim OtherDeductions As Decimal
    Dim PendingWithdrawals As Decimal
    Dim SummaryTableCreditLimits As ISSummaryTable
    Dim SummaryTableInvestment As ISSummaryTable
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTableMaturityInstructions As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim UnclearedFunds As Decimal
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableCreditLimits = finBL.CreateSummaryTable()
    SummaryTableInvestment = finBL.CreateSummaryTable()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTableMaturityInstructions = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Date As At
    DateAsAt = finBL.TimeZoneFunctions.GetCurrentDatabaseDate()

    ' Get Calculation
    If accountCalc Is Nothing Then
      accountCalc = account.Calculation
    End If

    With SummaryTableMain
      ' Initialise
      Warnings = ""
      .TableClass = iseSummaryTableClass.Information
      .Columns.AddText(16)
      .Columns.AddText()

      With .Rows
        ' Date Opened
        .AddCaptionDate("Date Opened:", accountCalc.OpeningDate)

        Select Case account.AccountClass
          Case isefinAccountClass.Deposit
            ' Term and Maturity Date
            If account.IsQuoteOrClosedQuote Then
              ' Quote
              Select Case accountCalc.TermCycle
                Case "On Call"
                  .AddCaptionText("Term:", "On Call")
                Case "On Date"
                  .AddCaptionText("Term:", accountCalc.TermCycleDescriptionResolved)
                  .AddCaptionDate("Maturity:", accountCalc.DateMaturity, accountCalc.DateMaturity.DayOfWeek.ToString)
                Case Else
                  If accountCalc.TermCycle = accountCalc.TermCycleResolved Then
                    .AddCaptionText("Term:", accountCalc.TermCycleDescription)
                  Else
                    .AddCaptionWiki("Term:", String.Format("**{0}** --adjusted to {1}--", accountCalc.TermCycleDescription, accountCalc.TermCycleDescriptionResolved))
                  End If
                  .AddCaptionDate("Maturity:", accountCalc.DateMaturity, accountCalc.DateMaturity.DayOfWeek.ToString)
              End Select
            Else
              ' Open/ Closed
              If accountCalc.IsCalcVersionOpening Then
                Select Case accountCalc.OriginalTermCycle
                  Case "On Call"
                    .AddCaptionText("Term:", accountCalc.OriginalTermCycleDescriptionResolved)
                  Case "On Date"
                    .AddCaptionWiki("Term:", String.Format("**{0}** (on date)", accountCalc.OriginalTermCycleDescriptionResolved))
                    .AddCaptionDate("Maturity:", accountCalc.OriginalDateMaturity, accountCalc.OriginalDateMaturity.DayOfWeek.ToString)
                  Case Else
                    If accountCalc.OriginalTermCycle = accountCalc.OriginalTermCycleResolved Then
                      .AddCaptionText("Term:", accountCalc.OriginalTermCycleDescriptionResolved)
                    Else
                      .AddCaptionWiki("Term:", String.Format("**{0}** --adjusted to {1}--", accountCalc.OriginalTermCycleDescription, accountCalc.OriginalTermCycleDescriptionResolved))
                    End If
                    .AddCaptionDate("Maturity:", accountCalc.OriginalDateMaturity, accountCalc.OriginalDateMaturity.DayOfWeek.ToString)
                End Select
              Else
                If accountCalc.TermCycle = accountCalc.OriginalTermCycleResolved OrElse Len(accountCalc.OriginalTermCycleResolved) = 0 Then
                  .AddCaptionText("Term:", accountCalc.TermCycleDescription)
                Else
                  .AddCaptionWiki("Term:", String.Format("**{0}** --originally {1}--", accountCalc.TermCycleDescription, accountCalc.OriginalTermCycleDescriptionResolved))
                End If
                If accountCalc.TermCycle <> "On Call" Then
                  .AddCaptionDate("Maturity:", accountCalc.DateMaturity, accountCalc.DateMaturity.DayOfWeek.ToString)

                  ' Warnings
                  If account.Status = isefinAccountStatus.Open AndAlso accountCalc.DateMaturity <> Nothing AndAlso accountCalc.DateMaturity < DateAsAt Then
                    Days = DateDiff(DateInterval.Day, accountCalc.DateMaturity, DateAsAt)
                    If Days = 1 Then
                      Warnings &= "{{Warning|Past Maturity by 1 day.}}"
                    Else
                      Warnings &= "{{Warning|" & String.Format("Past Maturity by **{0}** days.", Days) & "}}"
                    End If
                  End If
                End If
              End If
            End If

            ' Actions
            If includeActions Then
              With SummaryTableMain.Actions
                If account.SupportsMaturityDateChanges Then
                  With .AddFormAction("MaturityDateReview", "Review", accountCalc.IsCalcVersionFuture AndAlso finBL.CurrentUser.Permissions.Allow("Account.MaturityDate.View"))
                    .ShowInWebInterfaces = True
                  End With
                End If
              End With
            End If

          Case Else
            ' Maturity Date
            If accountCalc.IsCalcVersionOpening Then
              DateMaturity = accountCalc.OriginalDateMaturity
            Else
              DateMaturity = account.Calculation.DateMaturity
            End If

            If accountCalc.AccountType.TermUse OrElse DateMaturity <> Nothing Then
              If DateMaturity = Nothing Then
                .AddCaptionText("Maturity:", "Not defined")
              Else
                .AddCaptionDate("Maturity:", DateMaturity)
              End If

              ' Maturity Warning
              If DateMaturity <> Nothing AndAlso DateMaturity < DateAsAt Then
                Days = DateDiff(DateInterval.Day, DateMaturity, DateAsAt)
                If Days = 1 Then
                  Warnings &= "{{Warning|Past Maturity by 1 day.}}"
                Else
                  Warnings &= "{{Warning|" & String.Format("Past Maturity by **{0}** days.", Days) & "}}"
                End If
              End If

              ' Actions
              If includeActions Then
                With SummaryTableMain.Actions
                  If account.SupportsMaturityDateChanges Then
                    With .AddFormAction("MaturityDateReview", "Review", accountCalc.IsCalcVersionFuture AndAlso finBL.CurrentUser.Permissions.Allow("Account.MaturityDate.View"))
                      .ShowInWebInterfaces = True
                    End With
                  End If
                End With
              End If
            End If

        End Select
      End With

      ' Warnings
      .TextAfter = Warnings

      ' Actions
      If includeActions Then
        With .Actions
          Select Case callerScriptInfo.FormKey
            Case "Accounts"
              ' Schedule drilldown
              If accountCalc.IsCalcVersionOpening Then
                .AddFormAction("ShowSchedule", "Schedule", , String.Format("index={0}", 0)).ShowInWebInterfaces = True
              ElseIf accountCalc.IsCalcVersionFuture Then
                .AddFormAction("ShowSchedule", "Schedule", , String.Format("index={0}", account.CalculationVersions.Count - 1)).ShowInWebInterfaces = True
              End If
            Case "AccountArchiveView"
              ' Schedule drilldown
              If accountCalc.IsCalcVersionOpening Then
                .AddFormAction("ShowSchedule", "Schedule").ShowInWebInterfaces = True
              End If
          End Select
        End With
      End If
    End With

    With SummaryTableInvestment
      ' Initialise
      Warnings = ""
      .TableClass = iseSummaryTableClass.Information
      .Caption = "Investment Details"
      .Columns.AddText(16).NoBreakChars = 10
      .Columns.AddText()

      Select Case account.AccountClass
        Case isefinAccountClass.Deposit
          ' Get Information
          account.GetInvestmentDetails(InvestmentValue, InvestmentReceived, InvestmentPending,, InvestmentNew, InvestmentReinvested, InvestmentTransferIn, InvestmentTransferOut, InvestmentAdditional)

          With .Rows
            ' Investment
            .AddCaptionCurrency("Investment:", InvestmentValue, True)
            .AddCaptionCurrency("Received:", InvestmentReceived, True)
            If InvestmentPending > 0 Then
              .AddCaptionCurrency("Pending:", InvestmentPending, True, iseSummaryTableRowClass.Normal, iseSummaryTableCellClass.WarningBold)

              Warnings &= "{{warning|Investment is pending.}}"
            ElseIf InvestmentPending < 0 Then
              .AddCaptionCurrency("Overpaid:", InvestmentPending, True, iseSummaryTableRowClass.Normal, iseSummaryTableCellClass.WarningBold)

              Warnings &= "{{warning|Investment is overpaid.}}"
            End If

            ' Additional Investments
            If InvestmentAdditional <> 0 Then .AddCaptionCurrency("Additional:", InvestmentAdditional, True)
          End With

          ' Warnings
          If account.CreationMethod = isefinAccountCreationMethod.Reinvested Then
            Warnings &= "{{info|Deposit was created from a Reinvestment.}}"
          End If

          ' Actions
          If includeActions Then
            With .Actions
              .AddFormAction("InvestmentValueChange", "Review", Not finBL.Database.IsReadOnly AndAlso accountCalc.IsCalcVersionFuture AndAlso finBL.CurrentUser.Permissions.Allow("Account.InvestmentValue.View")).ShowInWebInterfaces = True
            End With
          End If

          ' Warnings
          .TextAfter = Warnings
      End Select
    End With

    With SummaryTableCreditLimits
      ' Initialise
      Warnings = ""
      .TableClass = iseSummaryTableClass.Information
      .Caption = "Credit Limits"
      .Columns.AddText(16).NoBreakChars = 10
      .Columns.AddText()

      If accountCalc.AccountType.CreditLimitCount > 0 Then
        If accountCalc.IsCalcVersionOpening Then
          With .Rows
            ' Credit Limit 1
            .AddCaptionCurrency(accountCalc.AccountType.CreditLimit1DescriptionResolved & ":", accountCalc.CreditLimit1, True)

            ' Credit Limit 2
            If accountCalc.AccountType.CreditLimitCount > 1 Then
              .AddCaptionCurrency(accountCalc.AccountType.CreditLimit2DescriptionResolved & ":", accountCalc.CreditLimit2, True)
            End If

            ' Credit Limit 3
            If accountCalc.AccountType.CreditLimitCount > 2 Then
              .AddCaptionCurrency(accountCalc.AccountType.CreditLimit3DescriptionResolved & ":", accountCalc.CreditLimit3, True)
            End If
          End With
        Else
          ' Get Information
          account.GetBalance(Balance)
          account.GetCreditLimits(DateAsAt, CreditLimit1, CreditLimit2, CreditLimit3, "", CreditLimit1FutureChange, CreditLimit2FutureChange, CreditLimit3FutureChange)
          account.GetPendingWithdrawals(PendingWithdrawals)
          If account.AccountType.CreditLimitUseUnclearedFunds Then
            account.GetUnclearedFunds2(UnclearedFunds)
          Else
            UnclearedFunds = 0
          End If
          account.GetCreditLimitOtherDeductions(OtherDeductions)
          AvailableCredit1 = CreditLimit1 - Balance - PendingWithdrawals - UnclearedFunds - OtherDeductions
          AvailableCredit2 = CreditLimit2 - Balance - PendingWithdrawals - UnclearedFunds - OtherDeductions
          AvailableCredit3 = CreditLimit3 - Balance - PendingWithdrawals - UnclearedFunds - OtherDeductions

          With .Rows
            ' Credit Limit 1
            If AvailableCredit1 < 0 Then
              .AddCaptionWiki(accountCalc.AccountType.CreditLimit1DescriptionResolved & ":", String.Format("**{0}** --Over Limit **!!{1}!!**--", finBL.FormatCurrency(CreditLimit1, True), finBL.FormatCurrency(-AvailableCredit1, True)))

              ' Add Warning
              Warnings &= "{{Warning|" & String.Format("Balance exceeds {0}.", accountCalc.AccountType.CreditLimit1DescriptionResolved) & "}}"
            Else
              .AddCaptionWiki(accountCalc.AccountType.CreditLimit1DescriptionResolved & ":", String.Format("**{0}** --Available **{1}**--", finBL.FormatCurrency(CreditLimit1, True), finBL.FormatCurrency(AvailableCredit1, True)))
            End If

            ' Credit Limit 2
            If accountCalc.AccountType.CreditLimitCount > 1 Then
              If AvailableCredit2 < 0 Then
                .AddCaptionWiki(accountCalc.AccountType.CreditLimit2DescriptionResolved & ":", String.Format("**{0}** --Over Limit **!!{1}!!**--", finBL.FormatCurrency(CreditLimit2, True), finBL.FormatCurrency(-AvailableCredit2, True)))

                ' Add Warning
                Warnings &= "{{Warning|" & String.Format("Balance exceeds {0}.", accountCalc.AccountType.CreditLimit2DescriptionResolved) & "}}"
              Else
                .AddCaptionWiki(accountCalc.AccountType.CreditLimit2DescriptionResolved & ":", String.Format("**{0}** --Available **{1}**--", finBL.FormatCurrency(CreditLimit2, True), finBL.FormatCurrency(AvailableCredit2, True)))
              End If
            End If

            ' Credit Limit 3
            If accountCalc.AccountType.CreditLimitCount > 2 Then
              If AvailableCredit3 < 0 Then
                .AddCaptionWiki(accountCalc.AccountType.CreditLimit3DescriptionResolved & ":", String.Format("**{0}** --Over Limit **!!{1}!!**--", finBL.FormatCurrency(CreditLimit3, True), finBL.FormatCurrency(-AvailableCredit3, True)))

                ' Add Warning
                Warnings &= "{{Warning|" & String.Format("Balance exceeds {0}.", accountCalc.AccountType.CreditLimit3DescriptionResolved) & "}}"
              Else
                .AddCaptionWiki(accountCalc.AccountType.CreditLimit3DescriptionResolved & ":", String.Format("**{0}** --Available **{1}**--", finBL.FormatCurrency(CreditLimit3, True), finBL.FormatCurrency(AvailableCredit3, True)))
              End If
            End If
          End With
        End If

        ' Warnings
        If Not accountCalc.IsCalcVersionOpening Then
          If CreditLimit1FutureChange OrElse CreditLimit2FutureChange OrElse CreditLimit3FutureChange Then
            Warnings &= "{{Warning|Future Credit Limit changes exist.}}"
          End If
        End If
        .TextAfter = Warnings

        ' Actions
        If includeActions Then
          With .Actions
            .AddFormAction("CreditLimitReview", "Review", Not finBL.Database.IsReadOnly AndAlso accountCalc.IsCalcVersionFuture AndAlso finBL.CurrentUser.Permissions.Allow("Account.CreditLimit.View")).ShowInWebInterfaces = True
          End With
        End If
      End If
    End With


    With SummaryTableMaturityInstructions
      ' Initialise
      Warnings = ""
      .TableClass = iseSummaryTableClass.Information
      .Caption = "Maturity Instructions"
      .Columns.AddText(16).NoBreakChars = 10
      .Columns.AddText()

      If account.Status = isefinAccountStatus.Quote OrElse accountCalc.IsCalcVersionFuture OrElse accountCalc.IsCalcVersionClosing Then
        Select Case account.AccountClass
          Case isefinAccountClass.Deposit
            If account.IsFixedTerm Then
              With .Rows
                ' Investment
                .AddCaptionText("Instruction:", account.MaturityInstructionText)
                Select Case account.MaturityInstruction
                  Case isefinAccountMaturityInstruction.ReinvestAmount
                    .AddCaptionCurrency("Amount:", account.MaturityValue, True)
                End Select
                Select Case account.MaturityInstruction
                  Case isefinAccountMaturityInstruction.ReinvestAll, isefinAccountMaturityInstruction.ReinvestAmount, isefinAccountMaturityInstruction.ReinvestPrincipal
                    If Len(account.MaturityAccountId) <> 0 Then
                      .AddCaptionWiki("Reinvest:", String.Format("**Account [[app://formshow?form=Accounts&id={0}|{1}]]**", finBL.UrlEncode(account.MaturityAccountId), account.MaturityAccountId))
                    ElseIf Len(account.MaturityAccountTypeId) <> 0 Then
                      With .AddCaptionCodeDescription("Reinvest:", account.MaturityAccountTypePk, finBL.AccountTypes)
                        .Cells(1).Value = "**Account Type** " & .Cells(1).Value
                      End With
                    Else
                      .AddCaptionText("Reinvest:", "")
                    End If
                End Select
                Select Case account.MaturityInstruction
                  Case isefinAccountMaturityInstruction.PayoutAll, isefinAccountMaturityInstruction.ReinvestAmount, isefinAccountMaturityInstruction.ReinvestPrincipal
                    Select Case account.MaturityPaymentType
                      Case isefinAccountMaturityPaymentType.Transfer
                        If Len(account.MaturityTransferToAccountId) = 0 Then
                          .AddCaptionText("Repayment:", account.MaturityPaymentTypeText)
                        Else
                          .AddCaptionWiki("Repayment:", String.Format("**Transfer** to **[[app://formshow?form=Accounts&id={0}|{1}]]**", finBL.UrlEncode(account.MaturityTransferToAccountId), account.MaturityTransferToAccountId))
                        End If
                      Case Else
                        .AddCaptionText("Repayment:", account.MaturityPaymentTypeText)
                    End Select
                End Select
              End With

              ' Warnings
              .TextAfter = Warnings

              ' Actions
              If includeActions Then
                With .Actions
                  With .AddFormAction("MaturityInstructionReview", "Review", Not finBL.Database.IsReadOnly AndAlso accountCalc.IsCalcVersionFuture AndAlso finBL.CurrentUser.Permissions.Allow("Account.MaturityInstruction.View"))
                    .ShowInWebInterfaces = True
                  End With
                End With
              End If
            End If
        End Select
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)
    If SummaryTableInvestment.HasData Then SummaryTables.Add("Investment Summary", SummaryTableInvestment)
    If SummaryTableCreditLimits.HasData Then SummaryTables.Add("CreditLimits", SummaryTableCreditLimits)
    If SummaryTableMaturityInstructions.HasData Then SummaryTables.Add("Maturity Instructions", SummaryTableMaturityInstructions)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Tax Certificates (Version 1.0, Last updated 19/09/2014).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="account">
  '''  The Account to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Payments page and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_TaxCertificates(callerScriptInfo As ISScriptExecutionInfo,
                                                      account As finAccount,
                                             Optional includeActions As Boolean = True,
                                             Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim AccountTaxCertificate As finAccountTaxCertificate
    Dim LastYear As Integer
    Dim RowAlt As iseSummaryTableRowClass
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()
    RowAlt = iseSummaryTableRowClass.Alt2

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .AutoStripe = False
      .Caption = ""

      If account.TaxCertificates.Count = 0 Then
        ' No Tax Certificates
        Warnings &= "{{info|No Tax Certificates generated.}}"
      Else
        ' Columns
        With .Columns
          .AddText("Certificate")
          .AddDate("Date")
          .AddText("Type")
          .AddText("Avg Rate", 8, iseSummaryTableCellTextAlign.Right).NoBreakChars = 8
          .AddCurrency("Gross", 12)
          .AddCurrency("W/Tax", 12)
          .AddCurrency("Net", 12)
        End With

        With .Rows
          For Each AccountTaxCertificate In account.TaxCertificates
            ' Stripe when Year changes
            If Year(AccountTaxCertificate.Date) <> LastYear Then
              LastYear = Year(AccountTaxCertificate.Date)
              If RowAlt = iseSummaryTableRowClass.Alt1 Then
                RowAlt = iseSummaryTableRowClass.Alt2
              Else
                RowAlt = iseSummaryTableRowClass.Alt1
              End If
            End If

            ' Add Row
            With .Add(RowAlt).Cells
              With .AddText(AccountTaxCertificate.CertificateNumber)
                If AccountTaxCertificate.ClientLogPk <> 0 Then
                  ' Show Tax Certificate Log
                  .HyperlinkSetFormShow("ClientLog", CStr(AccountTaxCertificate.ClientLogPk))
                End If
              End With
              .AddDate(AccountTaxCertificate.Date)
              .AddText(AccountTaxCertificate.TaxCertificateTypeText)
              .AddText(finBL.FormatPercentage(AccountTaxCertificate.AverageWTaxRate / 100, 4))
              .AddCurrency(AccountTaxCertificate.TotalGross)
              .AddCurrency(AccountTaxCertificate.TotalWithholdingTax)
              .AddCurrency(AccountTaxCertificate.TotalNet)
            End With
          Next
        End With
      End If

      ' Warnings
      .TextAfter = Warnings

      ' Actions
      If includeActions Then
        With .Actions
        End With
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Term and Payments Summary.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="account">
  '''  The Account to summarise.
  ''' </param>
  ''' <param name="calculationVersionIndex">
  '''  The finAccountCalcVersions index to use.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Payments page and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Term</code><description>Term details.</description></item>
  '''    <item><code>Payments</code><description>Payment details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_TermAndPayments(callerScriptInfo As ISScriptExecutionInfo,
                                                      account As finAccount,
                                             Optional calculationVersionIndex As Integer = -1,
                                             Optional includeActions As Boolean = True,
                                             Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' Account_TermAndPayments
    '
    ' Version 1.04, Last updated 13/10/2022
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.03  06/03/2019  ISS                  
    '    1.04  13/10/2022  ISS      J029443   Add Restructure Action to finPOWER Connect Cloud
    ' #################################################################

    Dim AccountCalc As finAccountCalc
    Dim accountCalcOpening As finAccountCalc
    Dim AccountCalcScheduleItem As finAccountCalcScheduleItem
    Dim BalloonPaymentDate As Date
    Dim BalloonPaymentValue As Decimal
    Dim DateAsAt As Date
    Dim dateTemp As Date
    Dim i As Integer
    Dim IsFutureCalculation As Boolean
    Dim IsOpeningCalculation As Boolean
    Dim PaymentCount As Integer
    Dim PaymentCountAdditional As Integer
    Dim PaymentCountBalloon As Integer
    Dim PaymentCountOverridden As Integer
    Dim PaymentCountPromise As Integer
    Dim PaymentCountRegular As Integer
    Dim PaymentCountTransaction As Integer
    Dim PaymentCountZero As Integer
    Dim RegularPaymentFinalDate As Date
    Dim RegularPaymentFinalOverridden As Boolean
    Dim RegularPaymentFinalValue As Decimal
    Dim RegularPaymentFirstDate As Date
    Dim RegularPaymentFirstOverridden As Boolean
    Dim RegularPaymentFirstValue As Decimal
    Dim RegularPaymentUpfrontDate As Date
    Dim RegularPaymentUpfrontOverridden As Boolean
    Dim RegularPaymentUpfrontValue As Decimal
    Dim strTemp As String
    Dim SummaryTablePayments As ISSummaryTable
    Dim SummaryTableTerm As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTablePayments = finBL.CreateSummaryTable()
    SummaryTableTerm = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Date As At
    DateAsAt = finBL.TimeZoneFunctions.GetCurrentDatabaseDate()

    ' Find AccountCalc - Opening or as Restructured
    If account.IsQuoteOrClosedQuote Then
      ' Quote
      calculationVersionIndex = -1
      AccountCalc = account.Calculation
      accountCalcOpening = account.Calculation

      ' Set Flags
      IsOpeningCalculation = True
      IsFutureCalculation = True
    Else
      ' Validate Calculation Version Index
      If calculationVersionIndex < 0 Then calculationVersionIndex = account.CalculationVersions.Count - 1

      ' Always need Opening
      account.CalculationVersions.GetLatestCalculation(0, accountCalcOpening)

      ' Get Opening or Restructured
      If account.CalculationVersions(calculationVersionIndex).Restructured Then
        account.CalculationVersions.GetLatestCalculation(calculationVersionIndex, AccountCalc)
      Else
        AccountCalc = accountCalcOpening
      End If

      ' Set Flags
      With account.CalculationVersions(calculationVersionIndex)
        IsOpeningCalculation = .Opening
        IsFutureCalculation = .Future
      End With
    End If

    ' Find Original/ Restructured Payment Details
    PaymentCount = AccountCalc.Schedule.CountPayments(False, PaymentCountRegular, PaymentCountZero, PaymentCountOverridden, PaymentCountBalloon, PaymentCountAdditional, PaymentCountPromise, PaymentCountTransaction)
    AccountCalc.GetPaymentRegularUpfront(RegularPaymentUpfrontDate, RegularPaymentUpfrontValue, RegularPaymentUpfrontOverridden)
    AccountCalc.GetPaymentRegularFirst(RegularPaymentFirstDate, RegularPaymentFirstValue, RegularPaymentFirstOverridden)
    AccountCalc.GetPaymentRegularFinal(RegularPaymentFinalDate, RegularPaymentFinalValue, RegularPaymentFinalOverridden)
    AccountCalc.GetPaymentBalloon(BalloonPaymentDate, BalloonPaymentValue)

    ' Term
    With SummaryTableTerm
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      If AccountCalc.IsRestructured Then .Caption = "Restructured" Else .Caption = "Term"
      .Columns.AddText(16)
      .Columns.AddText()

      With .Rows
        If AccountCalc.IsRestructured Then
          .AddCaptionDate("Opened:", AccountCalc.OpeningDate)
          .AddCaptionWiki("Orig Term:", String.Format("**{0}**, maturing **{1}**", accountCalcOpening.TermCycleDescription, finBL.FormatDateLong(accountCalcOpening.DateMaturity)))
          .AddCaptionDate("Restructured:", AccountCalc.DateRestructured)
          .AddCaptionText("Type:", AccountCalc.RestructureType)
          .AddCaptionText("By Whom:", AccountCalc.RestructureByWhom)
          If Len(AccountCalc.RestructureReason) <> 0 Then
            .AddCaptionText("Reason:", AccountCalc.RestructureReason)
          End If
          If AccountCalc.OriginalDateMaturity <> Nothing Then
            .AddCaptionDate("Maturity:", AccountCalc.OriginalDateMaturity)
          End If
        Else
          If IsOpeningCalculation Then
            .AddCaptionDate("Opening:", AccountCalc.OpeningDate)
          Else
            .AddCaptionDate("Opened:", AccountCalc.OpeningDate)
          End If
          .AddCaptionText("Term:", accountCalcOpening.TermCycleDescription)
          If AccountCalc.OriginalDateMaturity <> Nothing Then
            .AddCaptionDate("Maturity:", AccountCalc.OriginalDateMaturity)
          End If
          If (Not IsOpeningCalculation) AndAlso AccountCalc.DateMaturity <> AccountCalc.OriginalDateMaturity Then
            .AddCaptionDate("New Maturity:", AccountCalc.DateMaturity)
          End If
        End If
        If AccountCalc.ResidualValue <> 0 Then
          .AddCaptionCurrency("Residual:", AccountCalc.ResidualValue, True)
        End If
      End With

      ' Warnings
      If AccountCalc.IsCalcVersionClosing Then
        Warnings &= "{{warning|" & String.Format("Closed on **{0}**.", finBL.FormatDateLong(account.DateClosed)) & "}}"
      End If
      .TextAfter = Warnings

      ' Actions
      If includeActions Then
        With .Actions
        End With
      End If
    End With

    ' Payments
    With SummaryTablePayments
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      If IsOpeningCalculation Then
        .Caption = "Payments"
      ElseIf AccountCalc.IsRestructured Then
        .Caption = "Restructured Payments"
      Else
        .Caption = "Original Payments"
      End If
      .Columns.AddText(16)
      .Columns.AddText()

      With .Rows
        ' Total Payments
        If PaymentCount <> PaymentCountRegular OrElse PaymentCountZero <> 0 Then
          If PaymentCount = 1 Then
            .AddCaptionWiki("Payments:", "**1** Payment in total")
          Else
            .AddCaptionWiki("Payments:", String.Format("**{0}** Payments in total", PaymentCount))
          End If
        End If

        ' Regular Payments
        If PaymentCountRegular <> 0 OrElse PaymentCountZero <> 0 OrElse PaymentCountOverridden <> 0 Then
          If RegularPaymentFirstDate = Nothing AndAlso RegularPaymentUpfrontDate <> Nothing Then
            ' Only Upfront Payment
            .AddCaptionWiki("Upfront:", String.Format("**{0}** on **{1}**", finBL.FormatCurrency(RegularPaymentUpfrontValue, True), finBL.FormatDateLong(RegularPaymentUpfrontDate)))
          ElseIf RegularPaymentFirstDate = RegularPaymentFinalDate Then
            ' Only one payment!
            If RegularPaymentUpfrontDate <> Nothing Then .AddCaptionWiki("Upfront", String.Format("**{0}** on **{1}**", finBL.FormatCurrency(RegularPaymentUpfrontValue, True), finBL.FormatDateLong(RegularPaymentUpfrontDate)))
            .AddCaptionWiki("Payment:", String.Format("**{0}** on **{1}**", finBL.FormatCurrency(RegularPaymentFirstValue, True), finBL.FormatDateLong(RegularPaymentFirstDate)))
          Else
            If Right(finBL.Utilities.DateCycleGetMnemonicFriendly(True, AccountCalc.PaymentCycle), 2) = "ly" Then
              strTemp = String.Format("**{0}** due **{1}**", PaymentCountRegular + PaymentCountOverridden, finBL.Utilities.DateCycleGetMnemonicFriendly(True, AccountCalc.PaymentCycle))
            Else
              strTemp = String.Format("**{0}** due **{1}**", PaymentCountRegular + PaymentCountOverridden, AccountCalc.PaymentCycleDescription)
            End If
            If AccountCalc.PaymentRegular <> 0 AndAlso RegularPaymentFirstValue <> AccountCalc.PaymentRegular Then
              strTemp &= String.Format("<br>Regular Payment **{0}**", finBL.FormatCurrency(AccountCalc.PaymentRegular, True))
            End If
            If PaymentCountOverridden <> 0 Then
              strTemp &= String.Format("<br>Including **{0}** Overridden Payment{1}", PaymentCountOverridden, IIf(PaymentCountOverridden = 1, "", "s"))
            End If
            .AddCaptionWiki("Regular:", strTemp)
            If RegularPaymentUpfrontDate <> Nothing Then .AddCaptionWiki("Upfront:", String.Format("**{0}** on **{1}**", finBL.FormatCurrency(RegularPaymentUpfrontValue, True), finBL.FormatDateLong(RegularPaymentUpfrontDate)))
            .AddCaptionWiki("First Regular:", String.Format("**{0}** on **{1}**{2}", finBL.FormatCurrency(RegularPaymentFirstValue, True), finBL.FormatDateLong(RegularPaymentFirstDate), IIf(RegularPaymentFirstOverridden, " overridden", "")))
            .AddCaptionWiki("Final Regular:", String.Format("**{0}** on **{1}**{2}", finBL.FormatCurrency(RegularPaymentFinalValue, True), finBL.FormatDateLong(RegularPaymentFinalDate), IIf(RegularPaymentFinalOverridden, " overridden", "")))

            ' Warnings
            If Not AccountCalc.IsRestructured Then
              dateTemp = AccountCalc.PaymentFirstDateResolved
              If dateTemp = AccountCalc.PaymentFirstDateDefault Then
                If dateTemp <> finBL.Utilities.DateCycleGetTermEndDate(AccountCalc.PaymentCycle, AccountCalc.OpeningDate) Then
                  Warnings &= "{{info|Non-Standard First Payment Date.}}"
                End If
              ElseIf AccountCalc.AccountType.PaymentFirstPeriod = "Standard" Then
                Warnings &= "{{warning|Non-Standard First Payment Date.}}"
              Else
                Warnings &= "{{warning|Atypical First Payment Date.}}"
              End If
            End If
            If PaymentCountZero <> 0 Then
              Warnings &= "{{info|" & String.Format("**{0}** Zero Regular Payment{1}.", PaymentCountZero, IIf(PaymentCountZero = 1, "", "s")) & "}}"
            End If
          End If
        End If

        ' Additional Payments
        If PaymentCountAdditional <> 0 Then
          i = 0
          strTemp = ""
          For Each AccountCalcScheduleItem In AccountCalc.Schedule
            If (Not AccountCalcScheduleItem.IsExisting) AndAlso AccountCalcScheduleItem.ScheduleType = isefinAccountCalcScheduleType.PaymentAdditional AndAlso AccountCalcScheduleItem.Value <> 0 Then
              i += 1
              If Len(strTemp) <> 0 Then strTemp &= "<br>"
              strTemp &= String.Format("**{0}** on **{1}**", finBL.FormatCurrency(-AccountCalcScheduleItem.Value, True), finBL.FormatDateLong(AccountCalcScheduleItem.Date))
            End If
            If i = 2 And PaymentCountAdditional <> 3 Then Exit For
          Next
          If i < PaymentCountAdditional Then strTemp &= String.Format("<br>Plus **{0}** other Additional payments", PaymentCountAdditional - i)
          .AddCaptionWiki("Additional:", strTemp)
        End If

        ' Promise Payments
        If PaymentCountPromise <> 0 Then
          i = 0
          strTemp = ""
          For Each AccountCalcScheduleItem In AccountCalc.Schedule
            If (Not AccountCalcScheduleItem.IsExisting) AndAlso AccountCalcScheduleItem.ScheduleType = isefinAccountCalcScheduleType.PaymentPromise AndAlso AccountCalcScheduleItem.Value <> 0 Then
              i += 1
              If Len(strTemp) <> 0 Then strTemp &= "<br>"
              strTemp &= String.Format("**{0}** on **{1}**", finBL.FormatCurrency(-AccountCalcScheduleItem.Value, True), finBL.FormatDateLong(AccountCalcScheduleItem.Date))
            End If
            If i = 2 And PaymentCountPromise <> 3 Then Exit For
          Next
          If i < PaymentCountPromise Then strTemp &= String.Format("<br>Plus **{0}** other Promises", PaymentCountPromise - i)
          .AddCaptionWiki("Promises:", strTemp)
        End If

        ' Balloon Payment
        If BalloonPaymentValue <> 0 Then
          .AddCaptionWiki("Balloon:", String.Format("**{0}** on **{1}**", finBL.FormatCurrency(BalloonPaymentValue, True), finBL.FormatDateLong(BalloonPaymentDate)))
        End If

        ' Transaction Payments
        If PaymentCountTransaction <> 0 Then
          If PaymentCountTransaction = 1 Then
            .AddCaptionWiki("Other:", "**1** other transactional payment")
          Else
            .AddCaptionWiki("Other:", String.Format("**{0}** other transactional payments", PaymentCountTransaction))
          End If
        End If
      End With

      ' Warnings
      If AccountCalc.OptionPaymentsInAdvance Then Warnings &= "{{info|Payments in Advance.}}"
      Select Case AccountCalc.OptionPaymentAllocationMethod
        Case isefinAccountPaymentAllocationMethod.Standard
        Case Else
          Warnings &= "{{info|" & AccountCalc.OptionPaymentAllocationMethodText & " payments.}}"
      End Select
      If AccountCalc.PaymentBalloon <> 0 AndAlso AccountCalc.OptionPaymentsFinalPlusBalloon <> AccountCalc.AccountType.OptionPaymentsFinalPlusBalloon Then
        If AccountCalc.OptionPaymentsFinalPlusBalloon Then
          Warnings &= "{{Info|Balloon includes regular payment.}}"
        Else
          Warnings &= "{{Info|Balloon excludes regular payment.}}"
        End If
      End If
      .TextAfter = Warnings

      ' Actions
      If includeActions Then
        With .Actions
          Select Case callerScriptInfo.FormKey
            Case "Accounts"
              ' Schedule drilldown
              Select Case account.Status
                Case isefinAccountStatus.Quote, isefinAccountStatus.Declined, isefinAccountStatus.Unwanted
                  .AddFormAction("ShowSchedule", "Schedule", , String.Format("index={0}", 0)).ShowInWebInterfaces = True
                Case Else
                  If IsOpeningCalculation AndAlso calculationVersionIndex <> -1 Then
                    .AddFormAction("ShowSchedule", "Schedule", , String.Format("index={0}", calculationVersionIndex)).ShowInWebInterfaces = True
                  ElseIf AccountCalc.IsRestructured AndAlso (Not IsFutureCalculation) Then
                    .AddFormAction("ShowSchedule", "Schedule", , String.Format("index={0}", calculationVersionIndex)).ShowInWebInterfaces = True
                  ElseIf account.CanRestructure AndAlso IsFutureCalculation Then
                    .AddFormAction("AccountRestructure", "Restructure", , String.Format("index={0}", calculationVersionIndex)).ShowInWebInterfaces = True
                  End If
              End Select

            Case "AccountApps"
              ' Schedule drilldown
              If account.IsNew Then
                .AddFormAction("ShowSchedule", "Schedule").ShowInWebInterfaces = True
              Else
                ' Not available for real Accounts
              End If

            Case "AccountArchiveView"
              ' Schedule drilldown
              If IsOpeningCalculation Then
                .AddFormAction("ShowSchedule", "Schedule").ShowInWebInterfaces = True
              End If
          End Select
        End With
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Term", SummaryTableTerm)
    SummaryTables.Add("Payments", SummaryTablePayments)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Transaction Allocations Summary.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="account">
  '''  The Account to summarise.
  ''' </param>
  ''' <param name="index">
  '''  The Transaction index to use.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Transactions page and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Summary.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_TransactionAllocations(callerScriptInfo As ISScriptExecutionInfo,
                                                             account As finAccount,
                                                             index As Integer,
                                                    Optional includeActions As Boolean = True,
                                                    Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' Account_TransactionAllocations
    '
    ' Version 1.05 (07/01/2022)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.04  06/04/2020  ISS                  
    '    1.05  07/01/2022  ISS      J028119   Allocations not showing when expected
    ' #################################################################

    Dim AccountTransaction As finAccountTransaction
    Dim strTemp As String
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Information
    If account Is Nothing OrElse index < 0 OrElse index > account.Transactions.Count Then
      AccountTransaction = Nothing
    Else
      AccountTransaction = account.Transactions(index)
    End If

    ' Summary table
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .AutoStripe = True
      .Caption = ""

      ' Clear Warnings
      Warnings = ""

      If AccountTransaction Is Nothing Then
      ElseIf AccountTransaction.ReversePk <> 0 AndAlso Not AccountTransaction.AffectsBalance Then
        .TextBefore = "{{info|Allocations are not applicable to reversed Transactions.}}"
      ElseIf AccountTransaction.Value = 0 AndAlso (AccountTransaction.HighCostLoanAdjustmentType = isefinAccountTransactionHCLAdjustmentType.NotApplicable) AndAlso (AccountTransaction.ValueAllocatedFeeIB = 0 AndAlso AccountTransaction.ValueAllocatedFeeNIB = 0 AndAlso AccountTransaction.ValueAllocatedInterest = 0 AndAlso AccountTransaction.ValueAllocatedPrincipalIB = 0 AndAlso AccountTransaction.ValueAllocatedPrincipalNIB = 0) AndAlso AccountTransaction.Overdue = 0 AndAlso AccountTransaction.OverdueContractual = 0 Then
        .TextBefore = "{{info|Allocations are not applicable to this Transaction.}}"
      Else
        ' Columns
        With .Columns
          .AddText(" ")
          .AddCurrency("Transaction", 16)
          .AddCurrency("Balance", 18)
        End With

        With .Rows
          ' Value Allocations
          Select Case account.AccountClass
            Case isefinAccountClass.Deposit
              If AccountTransaction.ValueAllocatedPrincipalNIB <> 0 OrElse AccountTransaction.BalancePrincipalNIB <> 0 Then
                With .Add().Cells
                  .AddCaptionWiki("**Principal** --(Non Interest Bearing)--")
                  .AddCurrency(-AccountTransaction.ValueAllocatedPrincipalNIB)
                  .AddCurrency(-AccountTransaction.BalancePrincipalNIB)
                End With
              End If
              If AccountTransaction.ValueAllocatedPrincipalIB <> 0 OrElse AccountTransaction.BalancePrincipalIB <> 0 Then
                With .Add().Cells
                  .AddCaptionWiki("**Principal** --(Interest Bearing)--")
                  .AddCurrency(-AccountTransaction.ValueAllocatedPrincipalIB)
                  .AddCurrency(-AccountTransaction.BalancePrincipalIB)
                End With
              End If
              If AccountTransaction.ValueAllocatedInterest <> 0 OrElse AccountTransaction.BalanceInterest <> 0 Then
                With .Add().Cells
                  Select Case AccountTransaction.WithholdingTaxResidentStatus
                    Case isefinAccountTransactionResidentStatus.ApprovedIssuerLevy
                      If AccountTransaction.WithholdingTaxRate = 0 Then
                        strTemp = String.Format("Interest --AIL @ {0}--", finBL.FormatPercentage(AccountTransaction.WithholdingTaxRate / 100, 4))
                      Else
                        strTemp = String.Format("Interest --{0} less {1} AIL {2}--", finBL.FormatCurrency(-AccountTransaction.ValueAllocatedInterest - AccountTransaction.WithholdingTaxValue, True), finBL.FormatPercentage(AccountTransaction.WithholdingTaxRate / 100, 4), finBL.FormatCurrency(-AccountTransaction.WithholdingTaxValue, True))
                      End If
                    Case isefinAccountTransactionResidentStatus.NonResident
                      If AccountTransaction.WithholdingTaxRate = 0 Then
                        strTemp = String.Format("Interest --NRWT @ {0}--", finBL.FormatPercentage(AccountTransaction.WithholdingTaxRate / 100, 4))
                      Else
                        strTemp = String.Format("Interest --{0} less {1} NRWT {2}--", finBL.FormatCurrency(-AccountTransaction.ValueAllocatedInterest - AccountTransaction.WithholdingTaxValue, True), finBL.FormatPercentage(AccountTransaction.WithholdingTaxRate / 100, 4), finBL.FormatCurrency(-AccountTransaction.WithholdingTaxValue, True))
                      End If
                    Case isefinAccountTransactionResidentStatus.Resident
                      If AccountTransaction.WithholdingTaxRate = 0 Then
                        strTemp = String.Format("Interest --RWT @ {0}--", finBL.FormatPercentage(AccountTransaction.WithholdingTaxRate / 100, 4))
                      Else
                        strTemp = String.Format("**Interest** --{0} less {1} RWT {2}--", finBL.FormatCurrency(-AccountTransaction.ValueAllocatedInterest - AccountTransaction.WithholdingTaxValue, True), finBL.FormatPercentage(AccountTransaction.WithholdingTaxRate / 100, 4), finBL.FormatCurrency(-AccountTransaction.WithholdingTaxValue, True))
                      End If
                    Case Else
                      strTemp = "**Interest**"
                  End Select
                  .AddCaptionWiki(strTemp)
                  .AddCurrency(-AccountTransaction.ValueAllocatedInterest)
                  .AddCurrency(-AccountTransaction.BalanceInterest)
                End With
              End If
              If AccountTransaction.ValueAllocatedFeeNIB <> 0 OrElse AccountTransaction.BalanceFeeNIB <> 0 Then
                With .Add().Cells
                  .AddCaptionWiki("**Fees** --(Non Interest Bearing)--")
                  .AddCurrency(-AccountTransaction.ValueAllocatedFeeNIB)
                  .AddCurrency(-AccountTransaction.BalanceFeeNIB)
                End With
              End If
              If AccountTransaction.ValueAllocatedFeeIB <> 0 OrElse AccountTransaction.BalanceFeeIB <> 0 Then
                With .Add().Cells
                  .AddCaptionWiki("**Fees** --(Interest Bearing)--")
                  .AddCurrency(-AccountTransaction.ValueAllocatedFeeIB)
                  .AddCurrency(-AccountTransaction.BalanceFeeIB)
                End With
              End If

              ' Value
              With .Add(iseSummaryTableRowClass.FooterBold).Cells
                .AddCaption("Total")
                .AddCurrency(-AccountTransaction.Value)
                .AddCurrency(-AccountTransaction.Balance)
              End With

            Case Else
              If AccountTransaction.ValueAllocatedPrincipalNIB <> 0 OrElse AccountTransaction.ValueAllocatedPrincipalIB <> 0 OrElse AccountTransaction.ValueAllocatedInterest <> 0 OrElse AccountTransaction.ValueAllocatedFeeNIB <> 0 OrElse AccountTransaction.ValueAllocatedFeeIB <> 0 Then
                If AccountTransaction.ValueAllocatedPrincipalNIB <> 0 OrElse AccountTransaction.BalancePrincipalNIB <> 0 Then
                  With .Add().Cells
                    .AddCaptionWiki("**Principal** --(Non Interest Bearing)--")
                    .AddCurrency(AccountTransaction.ValueAllocatedPrincipalNIB)
                    .AddCurrency(AccountTransaction.BalancePrincipalNIB)
                  End With
                End If
                If AccountTransaction.ValueAllocatedPrincipalIB <> 0 OrElse AccountTransaction.BalancePrincipalIB <> 0 Then
                  With .Add().Cells
                    .AddCaptionWiki("**Principal** --(Interest Bearing)--")
                    .AddCurrency(AccountTransaction.ValueAllocatedPrincipalIB)
                    .AddCurrency(AccountTransaction.BalancePrincipalIB)
                  End With
                End If
                If AccountTransaction.ValueAllocatedInterest <> 0 OrElse AccountTransaction.BalanceInterest <> 0 Then
                  With .Add().Cells
                    .AddCaptionWiki("**Interest**")
                    .AddCurrency(AccountTransaction.ValueAllocatedInterest)
                    .AddCurrency(AccountTransaction.BalanceInterest)
                  End With
                End If
                If AccountTransaction.ValueAllocatedFeeNIB <> 0 OrElse AccountTransaction.BalanceFeeNIB <> 0 Then
                  With .Add().Cells
                    .AddCaptionWiki("**Fees** --(Non Interest Bearing)--")
                    .AddCurrency(AccountTransaction.ValueAllocatedFeeNIB)
                    .AddCurrency(AccountTransaction.BalanceFeeNIB)
                  End With
                End If
                If AccountTransaction.ValueAllocatedFeeIB <> 0 OrElse AccountTransaction.BalanceFeeIB <> 0 Then
                  With .Add().Cells
                    .AddCaptionWiki("**Fees** --(Interest Bearing)--")
                    .AddCurrency(AccountTransaction.ValueAllocatedFeeIB)
                    .AddCurrency(AccountTransaction.BalanceFeeIB)
                  End With
                End If
              End If

              ' Value
              With .Add(iseSummaryTableRowClass.FooterBold).Cells
                .AddCaption("Total")
                .AddCurrency(AccountTransaction.Value)
                .AddCurrency(AccountTransaction.Balance)
              End With

              ' Overdue Allocations
              If account.SupportsOverdue Then
                If account.AccountType.ShowOverdue Then
                  If AccountTransaction.Overdue <> 0 OrElse AccountTransaction.BalanceOverdue <> 0 OrElse AccountTransaction.AllocationMethodOverdue = isefinAccountTransactionAllocationMethod.Manual Then
                    With .Add().Cells
                      If AccountTransaction.AllocationMethodValue = AccountTransaction.AllocationMethodOverdue Then
                        .AddCaptionWiki("**Overdue**")
                      Else
                        .AddCaptionWiki(String.Format("**Overdue** --({0})--", AccountTransaction.AllocationMethodOverdueText))
                      End If
                      .AddCurrency(AccountTransaction.Overdue)
                      .AddCurrency(AccountTransaction.BalanceOverdue)
                    End With
                  End If
                End If
                If account.AccountType.ShowContractualOverdue Then
                  If AccountTransaction.OverdueContractual <> 0 OrElse AccountTransaction.BalanceOverdueContractual <> 0 OrElse AccountTransaction.AllocationMethodOverdueC = isefinAccountTransactionAllocationMethod.Manual Then
                    With .Add().Cells
                      If AccountTransaction.AllocationMethodValue = AccountTransaction.AllocationMethodOverdueC Then
                        .AddCaptionWiki("**Contractual Overdue**")
                      Else
                        .AddCaptionWiki(String.Format("**Contractual Overdue** --({0})--", AccountTransaction.AllocationMethodOverdueCText))
                      End If
                      .AddCurrency(AccountTransaction.OverdueContractual)
                      .AddCurrency(AccountTransaction.BalanceOverdueContractual)
                    End With
                  End If
                End If
              End If

              ' Original Value - before Consumer Regulation adjustment
              If AccountTransaction.HighCostLoanAdjustmentType <> isefinAccountTransactionHCLAdjustmentType.NotApplicable Then
                If account.ConsumerRegulationType = isefinAccountConsumerRegulationType.NotApplicable Then
                  Warnings &= "{{info|" & String.Format("Value has been reduced from {0}.", finBL.FormatCurrency(AccountTransaction.HighCostLoanValueOriginal, True)) & "}}"
                Else
                  Warnings &= "{{info|" & String.Format("Value has been reduced from {0} under '{1}' regulations.<br>Reason was '{2}'.", finBL.FormatCurrency(AccountTransaction.HighCostLoanValueOriginal, True), account.ConsumerRegulationTypeText, AccountTransaction.HighCostLoanAdjustmentTypeText) & "}}"
                End If
              End If
          End Select
        End With
      End If

      ' Warnings
      If AccountTransaction IsNot Nothing Then
      End If
      .TextAfter = Warnings

      ' Actions
      If includeActions Then
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Summary", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Transaction Audit Summary
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="account">
  '''  The Account to summarise.
  ''' </param>
  ''' <param name="accountCalcDays">
  '''  The Calculation Audit information.
  ''' </param>
  ''' <param name="alwaysShowInterestAccruedMethod">
  '''  Indicates whether to always show the Interest Accrued Method.
  ''' </param>
  ''' <param name="showScriptRunWarning">
  '''  Indicates whether to show if a Script was run during the Batch Import.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Transactions page and Account Schedule drilldown form.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Summary.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_TransactionAuditSummary(callerScriptInfo As ISScriptExecutionInfo,
                                                              account As finAccount,
                                                              accountCalcDays As finAccountCalcDays,
                                                     Optional alwaysShowInterestAccruedMethod As Boolean = False,
                                                     Optional showScriptRunWarning As Boolean = True,
                                                     Optional includeActions As Boolean = True,
                                                     Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' Account_TransactionAuditSummary
    '
    ' Version: 1.03 (24/07/2024)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.01  23/07/2014
    '    1.02  27/10/2021  ISS      J027618   Added Credit Limit 2/3 columns
    '    1.03  24/07/2024  ISS      J032515   Updated to use Other Interest description
    ' #################################################################

    Dim AccountCalcAudit As finAccountCalcAudit
    Dim AccountCalcAudits As finAccountCalcAudits
    Dim HasCreditLimit1 As Boolean
    Dim HasCreditLimit2 As Boolean
    Dim HasCreditLimit3 As Boolean
    Dim HasDefaultInterest As Boolean
    Dim HasFeeIB As Boolean
    Dim HasFeeNIB As Boolean
    Dim HasInDefault As Boolean
    Dim HasInterestRateFlat As Boolean
    Dim HasInterestRateTable As Boolean
    Dim HasOtherInterest As Boolean
    Dim HasOverdueAdjustment As Boolean
    Dim HasPrincipalNIB As Boolean
    Dim strTemp As String
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Auditing information
    If accountCalcDays IsNot Nothing Then
      AccountCalcAudits = accountCalcDays.GetAccountCalcAudits()
    End If

    ' Summary table
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .AutoStripe = True
      .Caption = ""

      If AccountCalcAudits Is Nothing Then
        .TextBefore = "{{warning|Failed to load Audit information.|True}}"
      Else
        ' Show Column flags
        Select Case account.AccountClass
          Case isefinAccountClass.Deposit
            HasCreditLimit1 = False
            HasCreditLimit2 = False
            HasCreditLimit3 = False
            HasDefaultInterest = False
            HasFeeIB = AccountCalcAudits.HasFeeIB
            HasFeeNIB = AccountCalcAudits.HasFeeNIB
            HasInDefault = False
            HasInterestRateFlat = False
            HasInterestRateTable = AccountCalcAudits.HasInterestRateTable
            HasOtherInterest = AccountCalcAudits.HasOtherInterest
            HasPrincipalNIB = AccountCalcAudits.HasPrincipalNIB
          Case Else
            HasCreditLimit1 = AccountCalcAudits.HasCreditLimit
            HasCreditLimit2 = AccountCalcAudits.HasCreditLimit2
            HasCreditLimit3 = AccountCalcAudits.HasCreditLimit3
            HasDefaultInterest = AccountCalcAudits.HasDefaultInterest
            HasFeeIB = AccountCalcAudits.HasFeeIB
            HasFeeNIB = AccountCalcAudits.HasFeeNIB
            HasInDefault = AccountCalcAudits.HasInDefault
            HasInterestRateFlat = AccountCalcAudits.HasInterestRateFlat
            HasInterestRateTable = AccountCalcAudits.HasInterestRateTable
            HasOtherInterest = AccountCalcAudits.HasOtherInterest
            HasPrincipalNIB = AccountCalcAudits.HasPrincipalNIB
        End Select

        ' Columns
        With .Columns
          .AddDate("From")
          .AddDate("To")
          .AddInteger("Days")
          If HasCreditLimit1 Then .AddCurrency(account.AccountType.CreditLimit1DescriptionResolved)
          If HasCreditLimit2 Then .AddCurrency(account.AccountType.CreditLimit2DescriptionResolved)
          If HasCreditLimit3 Then .AddCurrency(account.AccountType.CreditLimit3DescriptionResolved)
          If HasPrincipalNIB Then .AddCurrency("Principal NIB Balance")
          .AddCurrency("Principal Balance")
          .AddCurrency("Interest Balance")
          If HasFeeNIB Then .AddCurrency("Fees NIB Balance")
          If HasFeeIB Then .AddCurrency("Fees Balance")
          .AddCurrency("Balance")
          If account.SupportsOverdue AndAlso account.Status <> isefinAccountStatus.Quote Then
            If account.AccountType.ShowOverdue Then .AddCurrency("Overdue Balance")
            If account.AccountType.ShowContractualOverdue Then .AddCurrency("Contractual Balance")
          End If
          If HasInterestRateTable Then .AddText("Rate Table")
          If HasInterestRateFlat Then
            .AddDouble("Interest Rate")
            .AddDouble("True Rate")
          Else
            .AddDouble("Interest Rate")
          End If
          .AddCurrency("Interest")
          If HasDefaultInterest Then
            .AddDouble("Default Rate")
            .AddCurrency("Default Interest")
          End If
          If HasInDefault Then .AddBoolean("In Default")
          If HasOtherInterest Then
            .AddDouble(account.AccountType.OtherInterestDescriptionResolved & " Rate")
            .AddCurrency(account.AccountType.OtherInterestDescriptionResolved)
          End If
        End With

        With .Rows
          HasOverdueAdjustment = False
          For Each AccountCalcAudit In AccountCalcAudits
            With .Add().Cells
              .AddDate(AccountCalcAudit.DateFrom)
              .AddDate(AccountCalcAudit.DateTo)
              .AddInteger(CInt(DateDiff(DateInterval.Day, AccountCalcAudit.DateFrom, AccountCalcAudit.DateTo) + 1))
              If HasCreditLimit1 Then .AddCurrency(AccountCalcAudit.CreditLimit)
              If HasCreditLimit2 Then .AddCurrency(AccountCalcAudit.CreditLimit2)
              If HasCreditLimit3 Then .AddCurrency(AccountCalcAudit.CreditLimit3)
              Select Case account.AccountClass
                Case isefinAccountClass.Deposit
                  If HasPrincipalNIB Then .AddCurrency(-AccountCalcAudit.BalancePrincipalNIB)
                  .AddCurrency(-AccountCalcAudit.BalancePrincipalIB)
                  .AddCurrency(-AccountCalcAudit.BalanceInterest)
                  If HasFeeNIB Then .AddCurrency(-AccountCalcAudit.BalanceFeeNIB)
                  If HasFeeIB Then .AddCurrency(-AccountCalcAudit.BalanceFeeIB)
                  .AddCurrency(-AccountCalcAudit.Balance)
                Case Else
                  If HasPrincipalNIB Then
                    If (AccountCalcAudit.Balance > 0 AndAlso AccountCalcAudit.BalancePrincipalNIB < 0) OrElse (AccountCalcAudit.Balance < 0 AndAlso AccountCalcAudit.BalancePrincipalNIB > 0) Then
                      .AddCurrency(AccountCalcAudit.BalancePrincipalNIB).CellClass = iseSummaryTableCellClass.Warning
                    Else
                      .AddCurrency(AccountCalcAudit.BalancePrincipalNIB)
                    End If
                  End If
                  If (AccountCalcAudit.Balance > 0 AndAlso AccountCalcAudit.BalancePrincipalIB < 0) OrElse (AccountCalcAudit.Balance < 0 AndAlso AccountCalcAudit.BalancePrincipalIB > 0) Then
                    .AddCurrency(AccountCalcAudit.BalancePrincipalIB).CellClass = iseSummaryTableCellClass.Warning
                  Else
                    .AddCurrency(AccountCalcAudit.BalancePrincipalIB)
                  End If
                  If (AccountCalcAudit.Balance > 0 AndAlso AccountCalcAudit.BalanceInterest < 0) OrElse (AccountCalcAudit.Balance < 0 AndAlso AccountCalcAudit.BalanceInterest > 0) Then
                    .AddCurrency(AccountCalcAudit.BalanceInterest).CellClass = iseSummaryTableCellClass.Warning
                  Else
                    .AddCurrency(AccountCalcAudit.BalanceInterest)
                  End If
                  If HasFeeNIB Then
                    If (AccountCalcAudit.Balance > 0 AndAlso AccountCalcAudit.BalanceFeeNIB < 0) OrElse (AccountCalcAudit.Balance < 0 AndAlso AccountCalcAudit.BalanceFeeNIB > 0) Then
                      .AddCurrency(AccountCalcAudit.BalanceFeeNIB).CellClass = iseSummaryTableCellClass.Warning
                    Else
                      .AddCurrency(AccountCalcAudit.BalanceFeeNIB)
                    End If
                  End If
                  If HasFeeIB Then
                    If (AccountCalcAudit.Balance > 0 AndAlso AccountCalcAudit.BalanceFeeIB < 0) OrElse (AccountCalcAudit.Balance < 0 AndAlso AccountCalcAudit.BalanceFeeIB > 0) Then
                      .AddCurrency(AccountCalcAudit.BalanceFeeIB).CellClass = iseSummaryTableCellClass.Warning
                    Else
                      .AddCurrency(AccountCalcAudit.BalanceFeeIB)
                    End If
                  End If
                  .AddCurrency(AccountCalcAudit.Balance)
              End Select
              If account.SupportsOverdue AndAlso account.Status <> isefinAccountStatus.Quote Then
                If account.AccountType.ShowOverdue Then
                  If AccountCalcAudit.BalanceOverdue = AccountCalcAudit.BalanceOverdueAdjusted Then
                    .AddCurrency(AccountCalcAudit.BalanceOverdue)
                  Else
                    HasOverdueAdjustment = True
                    .AddText(finBL.FormatCurrency(AccountCalcAudit.BalanceOverdueAdjusted) & "*")
                  End If
                End If
                If account.AccountType.ShowContractualOverdue Then
                  If AccountCalcAudit.BalanceOverdueContractual = AccountCalcAudit.BalanceOverdueContractualAdjusted Then
                    .AddCurrency(AccountCalcAudit.BalanceOverdueContractual)
                  Else
                    HasOverdueAdjustment = True
                    .AddText(finBL.FormatCurrency(AccountCalcAudit.BalanceOverdueContractualAdjusted) & "*")
                  End If
                End If
              End If
              If HasInterestRateTable Then
                If AccountCalcAudit.InterestRateTablePk = 0 Then
                  strTemp = ""
                ElseIf AccountCalcAudit.InterestRatePremium = 0 Then
                  strTemp = finBL.RateTables.ItemByPk(AccountCalcAudit.InterestRateTablePk).RateTableId
                ElseIf AccountCalcAudit.InterestRatePremium > 0 Then
                  strTemp = finBL.RateTables.ItemByPk(AccountCalcAudit.InterestRateTablePk).RateTableId & "+" & finBL.FormatPercentage(AccountCalcAudit.InterestRatePremium / 100, 4)
                Else
                  strTemp = finBL.RateTables.ItemByPk(AccountCalcAudit.InterestRateTablePk).RateTableId & "-" & finBL.FormatPercentage(-AccountCalcAudit.InterestRatePremium / 100, 4)
                End If
                .AddText(strTemp)
              End If
              Select Case account.AccountClass
                Case isefinAccountClass.Deposit
                  .AddPercent(AccountCalcAudit.InterestRate / 100, 4)
                  .AddDouble(-AccountCalcAudit.Interest, 4)
                  If HasOtherInterest Then
                    .AddPercent(AccountCalcAudit.OtherInterestRate / 100, 4)
                    .AddDouble(-AccountCalcAudit.OtherInterest, 4)
                  End If
                Case Else
                  If HasInterestRateFlat Then
                    'FUDGE: InterestRateFlat=0 and InterestRate<>0 indicates a date after Maturity, and an Interest period may cover pre and post Maturity
                    If AccountCalcAudit.InterestRateFlat = 0 Then
                      .AddPercent(AccountCalcAudit.InterestRate / 100, 4)
                      .AddPercent(AccountCalcAudit.InterestRate / 100, 4)
                    Else
                      .AddPercent(AccountCalcAudit.InterestRateFlat / 100, 4)
                      .AddPercent(AccountCalcAudit.InterestRate / 100, 4)
                    End If
                  Else
                    .AddPercent(AccountCalcAudit.InterestRate / 100, 4)
                  End If
                  .AddDouble(AccountCalcAudit.Interest, 4)
                  If HasDefaultInterest Then
                    .AddPercent((AccountCalcAudit.DefaultInterestRate - AccountCalcAudit.InterestRate) / 100, 4)
                    .AddDouble(AccountCalcAudit.DefaultInterest, 4)
                  End If
                  If HasInDefault Then .AddTick(AccountCalcAudit.InDefault)
                  If HasOtherInterest Then
                    .AddPercent(AccountCalcAudit.OtherInterestRate / 100, 4)
                    .AddDouble(AccountCalcAudit.OtherInterest, 4)
                  End If
              End Select
            End With
          Next

          ' Total
          With .Add(iseSummaryTableRowClass.FooterBold).Cells
            .AddCaption("")
            .AddCaption("")
            .AddCaption("")
            If HasCreditLimit1 Then .AddCaption("")
            If HasCreditLimit2 Then .AddCaption("")
            If HasCreditLimit3 Then .AddCaption("")
            If HasPrincipalNIB Then .AddCaption("")
            .AddCaption("")
            .AddCaption("")
            If HasFeeNIB Then .AddCaption("")
            If HasFeeIB Then .AddCaption("")
            .AddCaption("")
            If account.SupportsOverdue AndAlso account.Status <> isefinAccountStatus.Quote Then
              If account.AccountType.ShowOverdue Then .AddCaption("")
              If account.AccountType.ShowContractualOverdue Then .AddCaption("")
            End If
            If HasInterestRateTable Then .AddCaption("")
            If HasInterestRateFlat Then .AddCaption("")
            .AddCaption("")
            Select Case account.AccountClass
              Case isefinAccountClass.Deposit
                .AddCurrency(-accountCalcDays.TotalInterest)
                If HasOtherInterest Then
                  .AddCaption("")
                  .AddCurrency(-accountCalcDays.TotalOtherInterest)
                End If
              Case Else
                .AddCurrency(accountCalcDays.TotalInterest)
                If HasDefaultInterest Then
                  .AddCaption("")
                  .AddCurrency(accountCalcDays.TotalDefaultInterest)
                End If
                If HasInDefault Then .AddCaption("")
                If HasOtherInterest Then
                  .AddCaption("")
                  .AddCurrency(accountCalcDays.TotalOtherInterest)
                End If
            End Select
          End With
        End With
      End If

      ' Warnings
      Warnings = ""
      If accountCalcDays IsNot Nothing Then
        ' Script warning
        If showScriptRunWarning AndAlso accountCalcDays.IsScripted Then
          Warnings &= "{{warning|" & String.Format("Calculation ran script '{0}'.", accountCalcDays.ScriptId) & "}}"
        End If

        ' Interest has been overridden
        If accountCalcDays.InterestOverridden Then
          Warnings &= "{{warning|Interest has been overridden.}}"
        End If

        ' Interest Rounding Adjustment
        If accountCalcDays.InterestRoundingAdjustment <> 0 Then
          Warnings &= "{{info|" & String.Format("Includes Interest rounding adjustment of **{0}**.", finBL.FormatCurrency(accountCalcDays.InterestRoundingAdjustment, True)) & "}}"
        End If

        ' Interest Accrual Method
        If account.Calculation.OptionInterestAccruedMethod <> accountCalcDays.InterestAccruedMethod OrElse account.AccountType.OptionInterestAccruedMethod <> accountCalcDays.InterestAccruedMethod Then
          Warnings &= "{{warning|" & String.Format("Interest accrual method '**{0}**'.", accountCalcDays.InterestAccruedMethodText) & "}}"
        ElseIf alwaysShowInterestAccruedMethod Then
          Warnings &= "{{info|" & String.Format("Interest accrual method '**{0}**'.", accountCalcDays.InterestAccruedMethodText) & "}}"
        End If

        ' Interest Charged Upfront
        If account.Status <> isefinAccountStatus.Quote Then
          If accountCalcDays.InterestChargeUpfront Then
            Warnings &= "{{info|Precomputed Interest is charged upfront.}}"
          ElseIf accountCalcDays.InterestChargeOriginal AndAlso accountCalcDays.DateTo < account.Calculation.DateMaturity Then
            Warnings &= "{{info|Original precomputed Interest charged.}}"
          End If
        End If

        ' Suspensions
        If accountCalcDays.SuspendInterest Then
          Warnings &= "{{info|Interest (including Default Interest and Fees) is suspended.}}"
        Else
          If accountCalcDays.SuspendDefaultInterest Then Warnings &= "{{info|Default Interest is suspended.}}"
          If accountCalcDays.SuspendDefaultFees Then Warnings &= "{{info|Default Fees are suspended.}}"
          If accountCalcDays.SuspendFacilityFee Then Warnings &= "{{info|Facility Fee is suspended.}}"
        End If

        ' Negative Balance?
        If accountCalcDays.BaseValueAdjusted Then
          Warnings &= "{{warning|Interest Base value was adjusted due to negative Balances.}}"
        End If

        ' Interest Rounding
        If account.AccountType.OptionInterestRoundMethod <> accountCalcDays.InterestRoundMethod OrElse account.AccountType.OptionInterestRoundMethod <> isefinAccountCalcInterestRoundMethod.Nearest Then
          Select Case accountCalcDays.InterestRoundMethod
            Case isefinAccountCalcInterestRoundMethod.Nearest
              Warnings &= "{{info|Interest is rounded to the nearest currency value}}"
            Case Else
              Warnings &= "{{info|" & String.Format("Interest is rounded {0}.", accountCalcDays.InterestRoundMethodText) & "}}"
          End Select
        End If

        ' Payment Grace Period
        If accountCalcDays.PaymentGracePeriod <> -1 Then
          Warnings &= "{{info|" & String.Format("Payment grace period used was **{0}** business days.", accountCalcDays.PaymentGracePeriod) & "}}"
        End If

        ' Overdue Adjustment
        If HasOverdueAdjustment Then
          Warnings &= "{{Info|* Overdue Balance adjusted.}}"
        End If
      End If
      .TextAfter = Warnings

      ' Actions
      If includeActions Then
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Summary", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Transaction Batch Summary (Version 1.0, Last updated 23/07/2014).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="batchView">
  '''  The Batch to summarise.
  ''' </param>
  ''' <param name="accountTransaction">
  '''  Optional Account Transaction. Used to omit certain details if the Batch property is the same as the Transaction.
  ''' </param>
  ''' <param name="showScriptRunWarning">
  '''  Indicates whether to show if a Script was run during the Batch Import.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Transactions page and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Summary.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_TransactionBatchSummary(callerScriptInfo As ISScriptExecutionInfo,
                                                              batchView As finBatchView,
                                                     Optional accountTransaction As finAccountTransaction = Nothing,
                                                     Optional showScriptRunWarning As Boolean = True,
                                                     Optional includeActions As Boolean = True,
                                                     Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Information

    ' Summary table
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Columns.AddText(16)
      .Columns.AddText()

      With .Rows
        If batchView IsNot Nothing Then
          ' General
          .AddCaptionText("Batch Id:", batchView.BatchId)
          .AddCaptionText("Entry Source:", batchView.EntrySourceText)
          If accountTransaction Is Nothing OrElse accountTransaction.Source <> batchView.Source Then
            .AddCaptionText("Source:", batchView.SourceText)
          End If
          If accountTransaction Is Nothing OrElse accountTransaction.TransactionTypePk <> batchView.TransactionTypePk Then
            .AddCaptionCodeDescription("Trans Type:", batchView.TransactionTypeId, batchView.TransactionTypeDescription)
          End If
          If Len(batchView.Notes) <> 0 Then .AddCaptionText("Notes:", batchView.Notes)
          .AddCaptionWiki("Created:", finBL.Utilities.GetUserAndDateWikiText("", batchView.CreatedUserPk, batchView.CreatedDate))
          If batchView.CreatedUserPk <> batchView.UpdatedUserPk OrElse batchView.CreatedDate <> batchView.UpdatedDate Then
            .AddCaptionWiki("Updated:", finBL.Utilities.GetUserAndDateWikiText("", batchView.UpdatedUserPk, batchView.UpdatedDate))
          End If
        End If
      End With

      ' Warnings
      If batchView IsNot Nothing Then
        ' Script Involved
        If Len(batchView.ScriptId) <> 0 AndAlso showScriptRunWarning Then
          Warnings &= "{{warning|" & String.Format("Script '{0}' ran during the Import of this batch.", batchView.ScriptId) & "}}"
        End If
      End If
      .TextAfter = Warnings

      ' Actions
      If includeActions Then
        With .Actions
        End With
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Summary", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Transaction Disbursement Summary.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="account">
  '''  The Account to summarise.
  ''' </param>
  ''' <param name="index">
  '''  The Transaction index to use.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Transactions page and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Summary.</description></item>
  '''    <item><code>OriginalCalculation</code><description>Original Calculation details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_TransactionDisbursementSummary(callerScriptInfo As ISScriptExecutionInfo,
                                                                     account As finAccount,
                                                                     index As Integer,
                                                            Optional includeActions As Boolean = True,
                                                            Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' Account_TransactionDisbursementSummary
    '
    ' Version: 1.02 (20/09/2022)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.01  27/10/2017  ISS                  
    '    1.02  20/09/2022  ISS      J029358   Show Reference from Account Disbursement
    ' #################################################################

    Dim AccountTransaction As finAccountTransaction
    Dim AccountDisbursementPayee As finAccountDisbursementPayee
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTableOriginalCalculation As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTableOriginalCalculation = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Information
    If account Is Nothing OrElse index < 0 OrElse index > account.Transactions.Count Then
      AccountTransaction = Nothing
      AccountDisbursementPayee = Nothing
    Else
      AccountTransaction = account.Transactions(index)

      If AccountTransaction.ElementType = isefinElementType.Disbursement Then
        ' Get Disbursement, ignore errors as will just return Nothing
        AccountTransaction.GetAccountDisbursement(AccountDisbursementPayee)
      Else
        AccountDisbursementPayee = Nothing
      End If
    End If

    ' Summary table
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Columns.AddText(16)
      .Columns.AddText()

      With .Rows
        If AccountDisbursementPayee IsNot Nothing Then
          ' General
          If account.Pk = AccountDisbursementPayee.AccountPk Then
            .AddCaptionCodeDescription("Account:", AccountDisbursementPayee.AccountId, AccountDisbursementPayee.AccountName)
          Else
            .AddCaptionCodeDescriptionWithFormShow("Account:", AccountDisbursementPayee.AccountPk, finBL.AccountFunctions, "Accounts", "Disbursements")
          End If
          .AddCaptionText("Type:", AccountDisbursementPayee.TypeText)
          If AccountTransaction.DateDeferredTo <> Nothing Then .AddCaptionDate("Date Due:", AccountTransaction.DateDeferredTo)
          If Len(AccountDisbursementPayee.Reference) <> 0 Then .AddCaptionText("Reference:", AccountDisbursementPayee.Reference)
          If Len(AccountDisbursementPayee.Notes) <> 0 Then .AddCaptionText("Notes:", AccountDisbursementPayee.Notes)
        Else
        End If
      End With

      ' Warnings
      Warnings = ""
      If AccountTransaction IsNot Nothing Then
        ' Reversed Warning
        If AccountDisbursementPayee Is Nothing Then
          If AccountTransaction.ReversePk <> 0 Then
            If AccountTransaction.ReversePk > AccountTransaction.Pk Then
              Warnings &= "{{warning|" & String.Format("Reversed by Transaction Id **{0}**.", AccountTransaction.ReversePk) & "}}"
            Else
              Warnings &= "{{warning|" & String.Format("Reversed Transaction Id **{0}**.", AccountTransaction.ReversePk) & "}}"
            End If
          End If
        Else
          If AccountDisbursementPayee.Status = isefinDisbursementStatus.Reversed Then
            Warnings &= "{{warning|" & finBL.Utilities.GetUserAndDateWikiText("Reversed", AccountDisbursementPayee.CancelledUserPk, AccountDisbursementPayee.CancelledDate) & "}}"
          End If
        End If
      End If
      .TextAfter = Warnings

      ' Actions
      If includeActions Then
      End If
    End With

    ' Original Calculation table
    If AccountDisbursementPayee IsNot Nothing AndAlso AccountDisbursementPayee.CalculationBasis <> isefinDisbursementCalcBasis.None Then
      With SummaryTableOriginalCalculation
        ' Initialise
        .TableClass = iseSummaryTableClass.Information
        .Caption = "Original Calculation"
        .Columns.AddText(16)
        .Columns.AddText()

        With .Rows
          If AccountDisbursementPayee IsNot Nothing Then
            If AccountDisbursementPayee.CalculationBasis <> isefinDisbursementCalcBasis.None Then
              If AccountDisbursementPayee.CalculationElementPk <> 0 Then
                .AddCaptionCodeDescription("Element:", AccountDisbursementPayee.CalculationElementId, AccountDisbursementPayee.CalculationElementDescription)
              End If
              .AddCaptionText("Basis:", AccountDisbursementPayee.CalculationBasisText)
              .AddCaptionCurrency("Value:", AccountDisbursementPayee.CalculationBaseValue)
              Select Case AccountDisbursementPayee.CalculationBasis
                Case isefinDisbursementCalcBasis.Percentage, isefinDisbursementCalcBasis.PresentValue, isefinDisbursementCalcBasis.PresentValueAF
                  .AddCaptionPercentage("Rate:", AccountDisbursementPayee.CalculationRate / 100, 4)
                Case isefinDisbursementCalcBasis.Difference, isefinDisbursementCalcBasis.SetValue
                  .AddCaptionCurrency("Rate:", AccountDisbursementPayee.CalculationRate)
              End Select
              If AccountDisbursementPayee.CalculationValue = AccountDisbursementPayee.Value Then
                .AddCaptionCurrency("Value:", AccountDisbursementPayee.CalculationValue, True)
              Else
                .AddCaptionCurrency("Value:", AccountDisbursementPayee.CalculationValue, True, , iseSummaryTableCellClass.Warning)
              End If
            End If
          End If
        End With
      End With
    End If

    ' Add Summary Tables
    SummaryTables.Add("Summary", SummaryTableMain)
    SummaryTables.Add("Original Calculation", SummaryTableOriginalCalculation)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Transaction Summary
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="account">
  '''  The Account to summarise.
  ''' </param>
  ''' <param name="index">
  '''  The Transaction index to use.
  ''' </param>
  ''' <param name="showAccount">
  '''  Indicates whether to show the Account Id and Name.
  ''' </param>
  ''' <param name="showBatchId">
  '''  Indicates whether to show the Batch Id that this Transaction was created from.
  ''' </param>
  ''' <param name="showUserDetails">
  '''  Indicates whether to show User details, i.e., User Flag and User Notes.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Account Transactions page and various other places.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Summary.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_TransactionSummary(callerScriptInfo As ISScriptExecutionInfo,
                                                         account As finAccount,
                                                         index As Integer,
                                                Optional showAccount As Boolean = True,
                                                Optional showBatchId As Boolean = True,
                                                Optional showUserDetails As Boolean = True,
                                                Optional includeActions As Boolean = True,
                                                Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' Account_TransactionSummary
    '
    ' Version 1.11 (10/04/2024)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.05  23/07/2021  ISS                  
    '    1.06  23/09/2021  ISS      J027435   Added date funds will be cleared
    '    1.07  08/10/2021  ISS      J027539   Added Actions to open Statement and Bank Transaction
    '    1.08  04/08/2022  ISS      J029305   Changed View Bank Transaction action to FormShow
    '    1.09  20/12/2023  ISS      J032256   Added "Show Related Bank Transaction" action
    '    1.10  22/01/2024  ISS      J032762   Added Updated Date and User
    '    1.11  10/04/2024  ISS      J033245   Added Created Application Version
    ' #################################################################

    Dim AccountLogPk As Integer
    Dim AccountTransaction As finAccountTransaction
    Dim BatchView As finBatchView
    Dim DateAsAt As Date
    Dim PaymentMethodPk As Integer
    Dim strTemp As String
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Date As At
    DateAsAt = finBL.TimeZoneFunctions.GetCurrentDatabaseDate()

    ' Get Information
    If account Is Nothing OrElse index < 0 OrElse index > account.Transactions.Count Then
      AccountTransaction = Nothing
    Else
      AccountTransaction = account.Transactions(index)
    End If

    ' Summary table
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Columns.AddText(16)
      .Columns.AddText()

      With .Rows
        If AccountTransaction IsNot Nothing Then
          ' Account Id
          If showAccount Then
            .AddCaptionCodeDescription("Account:", account.AccountId, account.Name)
          End If

          ' General
          .AddCaptionText("Id:", CStr(AccountTransaction.Pk))
          If showBatchId AndAlso AccountTransaction.BatchHeaderPk <> 0 Then
            If AccountTransaction.GetBatchView(BatchView) AndAlso BatchView IsNot Nothing Then
              .AddCaptionText("Batch Id:", BatchView.BatchId)
            End If
          End If
          .AddCaptionText("Type:", AccountTransaction.ElementTypeText)
          If Len(AccountTransaction.ScheduleTypeText) = 0 OrElse AccountTransaction.SourceText = AccountTransaction.ScheduleTypeText Then
            .AddCaptionText("Source:", AccountTransaction.SourceText)
          Else
            .AddCaptionText("Source:", String.Format("{0} ({1})", AccountTransaction.SourceText, AccountTransaction.ScheduleTypeText))
          End If
          If AccountTransaction.TransactionTypePk <> 0 Then
            .AddCaptionCodeDescription("Trans Type:", AccountTransaction.TransactionTypeId, AccountTransaction.TransactionTypeDescription)
          End If
          If AccountTransaction.ElementPk <> 0 Then
            .AddCaptionCodeDescription("Element:", AccountTransaction.ElementId, AccountTransaction.ElementDescription)
          End If
          .AddCaptionText("Reference:", AccountTransaction.Reference)
          If Len(AccountTransaction.Notes) <> 0 Then .AddCaptionText("Notes:", AccountTransaction.Notes)

          ' User Details
          If showUserDetails Then
            If Len(AccountTransaction.UserFlag) <> 0 OrElse Len(AccountTransaction.UserNotes) <> 0 Then
              If Len(AccountTransaction.UserFlag) <> 0 Then
                If Len(AccountTransaction.GetUserFlagColour) = 0 Then
                  strTemp = ""
                Else
                  strTemp = "{{icon|Flag[" & AccountTransaction.GetUserFlagColour & "]}} "
                End If

                If Len(AccountTransaction.GetUserFlagDescription) = 0 Then
                  .AddCaptionText("User Flag:", strTemp & AccountTransaction.UserFlag)
                Else
                  .AddCaptionCodeDescription("User Flag:", strTemp & AccountTransaction.UserFlag, AccountTransaction.GetUserFlagDescription)
                End If
              End If
              If Len(AccountTransaction.UserNotes) <> 0 Then
                .AddCaptionText("User Notes:", AccountTransaction.UserNotes)
              End If
            End If
          End If

          ' Other User Details
          If Len(AccountTransaction.CreatedAppVersion) = 0 Then
            .AddCaptionWiki("Created:", finBL.Utilities.GetUserAndDateWikiText("", AccountTransaction.CreatedUserPk, AccountTransaction.CreatedDate))
          Else
            .AddCaptionWiki("Created:", String.Format("{0} Version {1}.", finBL.Utilities.GetUserAndDateWikiText("", AccountTransaction.CreatedUserPk, AccountTransaction.CreatedDate), AccountTransaction.CreatedAppVersion))
          End If
          If AccountTransaction.CreatedUserPk <> AccountTransaction.UpdatedUserPk OrElse AccountTransaction.CreatedUtcDate <> AccountTransaction.UpdatedUtcDate Then
            .AddCaptionWiki("Last Updated:", finBL.Utilities.GetUserAndDateWikiText("", AccountTransaction.UpdatedUserPk, AccountTransaction.UpdatedDate))
          End If
          If AccountTransaction.AuthorisedUserPk <> 0 Then
            .AddCaptionWiki("Authorised:", finBL.Utilities.GetUserAndDateWikiText("", AccountTransaction.AuthorisedUserPk, AccountTransaction.AuthorisedDate))
          End If
        End If
      End With

      ' Actions
      If AccountTransaction IsNot Nothing Then
        With .Actions
          If AccountTransaction.BankTransactionPk <> 0 Then
            With .AddFormShow("ShowBankTransaction", "View Bank Transaction", "BankTransactionView")
              .Parameters.Add("id", CStr(AccountTransaction.BankTransactionPk))
              .ShowInWebInterfaces = True
            End With
          End If
          If AccountTransaction.BankTransactionRelatedPk <> 0 Then
            With .AddFormShow("ShowBankTransaction", "View Related Bank Transaction", "BankTransactionView")
              .Parameters.Add("id", CStr(AccountTransaction.BankTransactionRelatedPk))
              .ShowInWebInterfaces = True
            End With
          End If
          If AccountTransaction.AccountLogPk <> 0 Then
            If account.AccountClass = isefinAccountClass.Disbursement Then
              .AddFormShow("StatementView", "View Remittance", "AccountLog", finBL.CurrentUser.Permissions.Allow("Account.Form.Page.Logs"), String.Format("id={0}", AccountTransaction.AccountLogPk)).ShowInWebInterfaces = True
            Else
              .AddFormShow("StatementView", "View Statement", "AccountLog", finBL.CurrentUser.Permissions.Allow("Account.Form.Page.Logs"), String.Format("id={0}", AccountTransaction.AccountLogPk)).ShowInWebInterfaces = True
            End If
          End If
        End With
      End If

      ' Warnings
      If AccountTransaction IsNot Nothing Then
        ' Requires Authorisation
        If AccountTransaction.RequiresAuthorisation Then
          Warnings &= "{{warning|Transaction requires Authorisation.}}"
        End If

        ' Reversed Transaction
        If AccountTransaction.ReversePk <> 0 Then
          If AccountTransaction.ReversePk > AccountTransaction.Pk Then
            Warnings &= "{{warning|" & String.Format("Reversed by Transaction Id **{0}**.", AccountTransaction.ReversePk) & "}}"
          Else
            Warnings &= "{{warning|" & String.Format("Reversed Transaction Id **{0}**.", AccountTransaction.ReversePk) & "}}"
          End If
        End If

        ' Negative Payment Reversed
        If AccountTransaction.NegativePaymentReversePk <> 0 Then
          If AccountTransaction.NegativePaymentReversePk > AccountTransaction.Pk Then
            Warnings &= "{{warning|" & String.Format("Reversed by Negative Payment Transaction Id **{0}**.", AccountTransaction.NegativePaymentReversePk) & "}}"
          Else
            Warnings &= "{{warning|" & String.Format("Negative Payment matched to Transaction Id **{0}**.", AccountTransaction.NegativePaymentReversePk) & "}}"
          End If
        End If

        ' Bank Transaction not cleared
        If AccountTransaction.ReversePk = 0 AndAlso AccountTransaction.NegativePaymentReversePk = 0 Then
          Select Case finBL.Enums.isefinBankTransactionBankInterfaceStatus_FromDateCleared(AccountTransaction.DateCleared)
            Case isefinBankTransactionBankInterfaceStatus.ToSend
              Warnings &= "{{info|Ready to send Bank Transaction.}}"
            Case isefinBankTransactionBankInterfaceStatus.Sending
              Warnings &= "{{warning|Failed whilst sending Bank Transaction.|true}}"
            Case isefinBankTransactionBankInterfaceStatus.SendFailed
              Warnings &= "{{warning|Send Failed. Ready to Resend Bank Transaction.}}"
            Case isefinBankTransactionBankInterfaceStatus.Queued
              Warnings &= "{{warning|Queued, awaiting Funds to be cleared.}}"
            Case isefinBankTransactionBankInterfaceStatus.Pending
              Warnings &= "{{warning|Pending, awaiting Funds to be cleared.}}"
            Case Else
              ' Inwards Bank Transaction
              If AccountTransaction.DateCleared > DateAsAt Then
                Warnings &= "{{warning|" & String.Format("Funds not yet cleared. Funds will be cleared on **{0}**.", finBL.FormatDateLong(AccountTransaction.DateCleared)) & "}}"
              End If
          End Select
        End If

        ' Transfer
        If AccountTransaction.TransferPk <> 0 Then
          If AccountTransaction.TransferPk > AccountTransaction.Pk Then
            Warnings &= "{{info|" & String.Format("Transferred to Account **{0}**, Transaction Id **{1}**.", AccountTransaction.TransferAccountId, AccountTransaction.TransferPk) & "}}"
          Else
            Warnings &= "{{info|" & String.Format("Transferred from Account **{0}**, Transaction Id **{1}**.", AccountTransaction.TransferAccountId, AccountTransaction.TransferPk) & "}}"
          End If
        End If

        ' Loan Class Accounts - Direct Debit Status
        Select Case account.AccountClass
          Case isefinAccountClass.LoanFR, isefinAccountClass.LoanFT, isefinAccountClass.LoanRC
            If account.BankingDetails.ExistsBankingDetailsType(isefinAccountBankingDetailsType.Incoming) Then
              PaymentMethodPk = account.BankingDetails(isefinAccountBankingDetailsType.Incoming).BankingDetails.PaymentMethodPk
            Else
              PaymentMethodPk = 0
            End If
            If AccountTransaction.DirectDebitStatus = isefinTransactionDirectDebitStatus.ToBeProcessed AndAlso finBL.PaymentMethods.ExistsPk(PaymentMethodPk) Then
              Warnings &= "{{info|" & String.Format("'{0}' of {1} is still to be processed.", finBL.HtmlEncode(finBL.PaymentMethods.ItemByPk(PaymentMethodPk).Description), finBL.FormatCurrency(AccountTransaction.DirectDebitValue, True)) & "}}"
            End If
        End Select

        ' Loan class Accounts - Promise Status
        Select Case account.AccountClass
          Case isefinAccountClass.LoanFR, isefinAccountClass.LoanFT, isefinAccountClass.LoanRC
            If AccountTransaction.PromiseStatus <> isefinTransactionPromiseStatus.NotApplicable OrElse AccountTransaction.PromiseValue <> 0 Then
              Warnings &= "{{info|" & String.Format("Promise {0} - **{1}**.", finBL.FormatCurrency(AccountTransaction.PromiseValue, True), finBL.HtmlEncode(AccountTransaction.PromiseStatusText)) & "}}"
            End If
        End Select

        ' Disbursement class Accounts - not paid/ remitted
        Select Case account.AccountClass
          Case isefinAccountClass.Disbursement
            If AccountTransaction.AccountLogPk = 0 Then
              Warnings &= "{{info|Not yet paid/ remitted.}}"
            End If
        End Select

        ' Restructure
        If AccountTransaction.AccountCalculationPk <> 0 Then
          Warnings &= "{{info|Transaction is prior to current Account Restructure.}}"
        End If
      End If
      .TextAfter = Warnings

      ' Actions
      If includeActions Then
        With .Actions
          If AccountTransaction.GetFeeAccountLogPk(AccountLogPk) AndAlso AccountLogPk <> 0 Then
            .AddFormShow("ShowFeeAccountLog", "Open Related Log", "AccountLog", finBL.CurrentUser.Permissions.Allow("Account.Form.Page.Logs"), String.Format("id={0}", AccountLogPk))
          End If
        End With
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Summary", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Financial Details "Remaining Payments" Summary. Note, designed for Fixed Term Accounts (Version 1.02, Last updated 16/10/2019).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="account">
  '''  The Account to summarise.
  ''' </param>
  ''' <param name="accountCalcOpening">
  '''  The opening Account Calculation.
  ''' </param>
  ''' <param name="accountCalc">
  '''  The Account Calculation.
  ''' </param>
  ''' <param name="showScheduleWithoutPaymentsAction">
  ''' </param>
  ''' <param name="showScheduleWithRestructuredTransactionsAction">
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Account Financial page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main Payments Remaining details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_RemainingPayments(callerScriptInfo As ISScriptExecutionInfo,
                                                        account As finAccount,
                                               Optional accountCalcOpening As finAccountCalc = Nothing,
                                               Optional accountCalc As finAccountCalc = Nothing,
                                               Optional showScheduleAction As Boolean = False,
                                               Optional showScheduleWithRestructuredTransactionsAction As Boolean = False,
                                               Optional showScheduleWithoutPaymentsAction As Boolean = False,
                                               Optional includeActions As Boolean = True,
                                               Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim AccountCalcScheduleItem As finAccountCalcScheduleItem
    Dim Balance As Decimal
    Dim BalanceFinal As Decimal
    Dim BalloonPaymentDate As Date
    Dim BalloonPaymentValue As Decimal
    Dim DateAsAt As Date
    Dim Days As Long
    Dim i As Integer
    Dim NextPaymentDate As Date
    Dim NextPaymentValue As Decimal
    Dim PaymentCount As Integer
    Dim PaymentCountAdditional As Integer
    Dim PaymentCountBalloon As Integer
    Dim PaymentCountOverridden As Integer
    Dim PaymentCountPromise As Integer
    Dim PaymentCountRegular As Integer
    Dim PaymentCountTransaction As Integer
    Dim PaymentCountZero As Integer
    Dim PaymentFinalDate As Date
    Dim PaymentFinalDateOriginal As Date
    Dim strTemp As String
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Date As At
    DateAsAt = finBL.TimeZoneFunctions.GetCurrentDatabaseDate()

    ' Get Calculation
    If accountCalcOpening Is Nothing Then
      account.CalculationVersions(0).GetAccountCalc(accountCalcOpening)
    End If
    If accountCalc Is Nothing Then
      accountCalc = account.Calculation
    End If

    ' Get Information
    account.GetBalance(Balance)
    account.GetNextPayment(NextPaymentDate, NextPaymentValue)
    accountCalc.GetPaymentBalloon(BalloonPaymentDate, BalloonPaymentValue)
    PaymentFinalDate = accountCalc.PaymentFinalDate
    PaymentFinalDateOriginal = accountCalcOpening.PaymentFinalDate
    If accountCalc.Schedule.Count = 0 Then
      BalanceFinal = 0
    Else
      BalanceFinal = accountCalc.Schedule(accountCalc.Schedule.Count - 1).Balance
    End If

    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Columns.AddText(16).NoBreakChars = 10
      .Columns.AddText()

      With .Rows
        If Balance < 0 Then
          ' Add a warning
          Warnings &= "{{Info|Account has a **CREDIT** balance.}}"
        Else
          ' Find Remaining Payment Details
          PaymentCount = accountCalc.Schedule.CountPayments(False, PaymentCountRegular, PaymentCountZero, PaymentCountOverridden, PaymentCountBalloon, PaymentCountAdditional, PaymentCountPromise, PaymentCountTransaction)

          ' Total Remaining Payments
          If PaymentFinalDate = Nothing Then
            If accountCalc.ResidualValue <> 0 Then
              If accountCalc.Schedule.Count <> 0 AndAlso accountCalc.Schedule(accountCalc.Schedule.Count - 1).Balance <= accountCalc.ResidualValue Then
                strTemp = "Residual Value"
              Else
                strTemp = "!!Insufficient (Residual Value)!!"
              End If
            Else
              strTemp = "!!Insufficient!!"
            End If
          Else
            strTemp = String.Format("**{0}** Payment{1} in total remaining", PaymentCount, IIf(PaymentCount = 1, "", "s"))
            If accountCalc.DateMaturity <> Nothing AndAlso PaymentFinalDate > accountCalc.DateMaturity Then
              i = 0
              For Each AccountCalcScheduleItem In accountCalc.Schedule
                If (Not AccountCalcScheduleItem.IsExisting) AndAlso AccountCalcScheduleItem.Date > accountCalc.DateMaturity Then
                  Select Case AccountCalcScheduleItem.ScheduleType
                    Case isefinAccountCalcScheduleType.Payment, isefinAccountCalcScheduleType.PaymentAdditional, isefinAccountCalcScheduleType.PaymentOverridden, isefinAccountCalcScheduleType.PaymentPromise, isefinAccountCalcScheduleType.PaymentBalloon, isefinAccountCalcScheduleType.PaymentTransaction
                      If AccountCalcScheduleItem.Value <> 0 Then i += 1
                  End Select
                End If
              Next
              If i = PaymentCount Then
                strTemp &= "<br>!!(All payments dated after Maturity)!!"
              ElseIf i > 0 Then
                strTemp &= String.Format("<br>!!(**{0}** Payment{1} dated after Maturity)!!", i, IIf(i = 1, "", "s"))
              End If
            End If
          End If
          .AddCaptionWiki("Payments:", strTemp)

          ' Payment Frequency
          If accountCalcOpening.PaymentCycle = accountCalc.PaymentCycle Then
            .AddCaptionText("Frequency:", accountCalc.PaymentCycleDescription)
          Else
            .AddCaptionText("Arrangement:", accountCalc.PaymentCycleDescription)
          End If

          ' Next Payment
          If NextPaymentDate = Nothing Then
            Warnings &= "{{Warning|No further payments listed for this Account.}}"
          ElseIf NextPaymentDate = DateAsAt Then
            .AddCaptionWiki("Next Payment:", String.Format("**{0}** due **today**", finBL.FormatCurrency(NextPaymentValue, True)))
          Else
            .AddCaptionWiki("Next Payment:", String.Format("**{0}** due **{1}**", finBL.FormatCurrency(NextPaymentValue, True), finBL.FormatDateLong(NextPaymentDate)))
          End If

          ' Balloon
          If PaymentCountBalloon <> 0 Then
            If account.PaymentsByDirectDebit AndAlso accountCalc.OptionPaymentDirectDebitBalloon Then
              .AddCaptionWiki("Balloon:", String.Format("**{0}** due **{1}** --by Direct Debit--", finBL.FormatCurrency(BalloonPaymentValue, True), finBL.FormatDateLong(BalloonPaymentDate)))
            Else
              .AddCaptionWiki("Balloon:", String.Format("**{0}** due **{1}**", finBL.FormatCurrency(BalloonPaymentValue, True), finBL.FormatDateLong(BalloonPaymentDate)))
            End If
          End If

          ' Projected Final Payment Date
          If accountCalc.DateMaturity <> Nothing Then
            If accountCalc.ResidualValue <> 0 Then
              ' If Residual then always should be paid on Maturity, or its past Maturity
            ElseIf NextPaymentDate = Nothing OrElse PaymentFinalDate = Nothing Then
              .AddCaptionWiki("Projected Final:", "!!Payments insufficient!!")
            ElseIf accountCalc.OptionPaymentsInAdvance AndAlso PaymentFinalDate < PaymentFinalDateOriginal Then
              Days = DateDiff(DateInterval.Day, PaymentFinalDate, PaymentFinalDateOriginal)
              .AddCaptionWiki("Projected Final:", String.Format("**++{0}++** --**{1}** day{2} early--", finBL.FormatDateLong(PaymentFinalDate), Days, IIf(Days = 1, "", "s")))
            ElseIf (Not accountCalc.OptionPaymentsInAdvance) AndAlso PaymentFinalDate < accountCalc.DateMaturity Then
              Days = DateDiff(DateInterval.Day, PaymentFinalDate, accountCalc.DateMaturity)
              .AddCaptionWiki("Projected Final:", String.Format("**++{0}++** --**{1}** day{2} prior to Maturity--", finBL.FormatDateLong(PaymentFinalDate), Days, IIf(Days = 1, "", "s")))
            ElseIf PaymentFinalDate > accountCalc.DateMaturity Then
              Days = DateDiff(DateInterval.Day, accountCalc.DateMaturity, PaymentFinalDate)
              .AddCaptionWiki("Projected Final:", String.Format("**!!{0}!!** --**{1}** day{2} past Maturity--", finBL.FormatDateLong(PaymentFinalDate), Days, IIf(Days = 1, "", "s")))
            End If
          End If

          ' Warnings
          If PaymentCountOverridden = 1 Then
            Warnings &= "{{warning|There is 1 Overriding Regular Payment remaining.}}"
          ElseIf PaymentCountOverridden > 1 Then
            Warnings &= "{{warning|" & String.Format("There are {0} Overriding Regular Payments remaining.", PaymentCountOverridden) & "}}"
          End If
          If PaymentCountAdditional = 1 Then
            Warnings &= "{{warning|There is 1 Additional Payment remaining.}}"
          ElseIf PaymentCountAdditional > 1 Then
            Warnings &= "{{warning|" & String.Format("There are {0} Additional Payments remaining.", PaymentCountAdditional) & "}}"
          End If
          If PaymentCountBalloon <> 0 Then
            Warnings &= "{{warning|Balloon Payment is remaining.}}"
          End If
          If PaymentCountPromise = 1 Then
            Warnings &= "{{warning|There is 1 Promise remaining.}}"
          ElseIf PaymentCountPromise > 1 Then
            Warnings &= "{{warning|" & String.Format("There are {0} Promises remaining.", PaymentCountPromise) & "}}"
          End If
        End If

        ' Maturity Warnings
        If accountCalc.DateMaturity <> Nothing Then
          If accountCalc.DateMaturity < DateAsAt Then
            Days = DateDiff(DateInterval.Day, accountCalc.DateMaturity, DateAsAt)
            Warnings &= "{{Warning|" & String.Format("Past Maturity by **{0}** day{1}.", Days, IIf(Days > 1, "s", "")) & "}}"
          ElseIf NextPaymentDate = Nothing Then
          ElseIf PaymentFinalDate <> Nothing Then
            If accountCalc.ResidualValue <> 0 AndAlso PaymentFinalDate < accountCalc.DateMaturity Then
              ' If has Residual Value will always continue to Maturity
            ElseIf accountCalc.OptionPaymentsInAdvance AndAlso PaymentFinalDate < PaymentFinalDateOriginal Then
              Warnings &= "{{Warning|Account will be paid off early.}}"
            ElseIf (Not accountCalc.OptionPaymentsInAdvance) AndAlso PaymentFinalDate < accountCalc.DateMaturity Then
              Warnings &= "{{Warning|Account will be paid off early.}}"
            ElseIf PaymentFinalDate > accountCalc.DateMaturity Then
              Warnings &= "{{Warning|Final Payment is scheduled after Maturity Date.}}"
            End If
          End If
        End If

        ' Residual Value Warning
        If accountCalc.ResidualValue <> 0 Then
          If accountCalc.Schedule.Count = 0 OrElse NextPaymentDate = Nothing OrElse BalanceFinal >= accountCalc.ResidualValue Then
            Warnings &= "{{info|" & String.Format("Residual Value of **{0}**.", finBL.FormatCurrency(account.Calculation.ResidualValue, True)) & "}}"
          Else
            Warnings &= "{{warning|" & String.Format("Projected Residual Value of **{0}**.", finBL.FormatCurrency(BalanceFinal, True)) & "}}"
          End If
        End If
      End With

      ' Warnings
      .TextAfter = Warnings

      ' Actions
      If includeActions Then
        With .Actions
          ' Schedule drilldown
          .AddFormAction("ShowSchedule", "Schedule", showScheduleAction AndAlso accountCalc.IsCalcVersionFuture, String.Format("index={0}", account.CalculationVersions.Count - 1)).ShowInWebInterfaces = True
          .AddFormAction("ShowScheduleRestructured", "Schedule (with Restructured Transactions)", showScheduleWithRestructuredTransactionsAction AndAlso accountCalc.IsRestructured, String.Format("index={0}", account.CalculationVersions.Count - 1)).ShowInWebInterfaces = True
          .AddFormAction("ShowSchedulePayments", "Schedule (omit Future Payments)", showScheduleWithoutPaymentsAction AndAlso accountCalc.IsCalcVersionFuture, String.Format("index={0}", account.CalculationVersions.Count - 1)).ShowInWebInterfaces = True
        End With
      End If
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Payment Arrangement Changes Summary
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="accountPayArrangementAdd ">
  '''  The Account Payment Arrangement.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Payment Arrangement wizard.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Summary of changes. Not returned if requires calculation.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_PaymentArrangement_Changes(callerScriptInfo As ISScriptExecutionInfo,
                                                                 accountPayArrangementAdd As finAccountPayArrangementAdd,
                                                        Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' Account_PaymentArrangement_Changes
    '
    ' Version 1.05, Last updated 25/03/2024
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.03  13/04/2020  ISS                  
    '    1.04  15/09/2021  ISS      J027267   Added 'Rate of Charge' for NZ HCCCC
    '    1.05  04/03/2024  ISS      J032994   Revamped information in table
    '          06/03/2024  ISS      J032909   New PeriodToWordsWithHint function used
    '          25/03/2024  ISS      J032774   Revamped information in table
    ' #################################################################

    Dim Balance As Decimal
    Dim AccountCalcCurrent As finAccountCalc
    Dim AccountCalcNew As finAccountCalc
    Dim AccountCalcOriginal As finAccountCalc
    Dim AccountCalcRestructured As finAccountCalc
    Dim AccountCalcScheduleItem As finAccountCalcScheduleItem
    Dim AccountTransaction As finAccountTransaction
    Dim CurrentArrangementPaymentsInsufficient As Boolean
    Dim CurrentArrangementTotalCostOfBorrowing As Decimal
    Dim CurrentArrangementTotalFees As Decimal
    Dim CurrentArrangementTotalInterest As Decimal
    Dim CurrentArrangementTotalPayments As Decimal
    Dim CurrentArrangementTotalPaymentsToDate As Decimal
    Dim CurrentPaymentsInsufficient As Boolean
    Dim CurrentTotalCostOfBorrowing As Decimal
    Dim CurrentTotalFees As Decimal
    Dim CurrentTotalInterest As Decimal
    Dim CurrentTotalInterestRemaining As Decimal
    Dim CurrentTotalPayments As Decimal
    Dim CurrentTotalPaymentsRemaining As Decimal
    Dim CurrentTotalPaymentsToDate As Decimal
    Dim DirectDebitValue As Decimal
    Dim NewPaymentsInsufficient As Boolean
    Dim NewTotalCostOfBorrowing As Decimal
    Dim NewTotalFees As Decimal
    Dim NewTotalInterest As Decimal
    Dim NewTotalInterestRemaining As Decimal
    Dim NewTotalPayments As Decimal
    Dim NewTotalPaymentsRemaining As Decimal
    Dim NewTotalPaymentsToDate As Decimal
    Dim OriginalTotalCostOfBorrowing As Decimal
    Dim OriginalTotalFees As Decimal
    Dim OriginalTotalInterest As Decimal
    Dim OriginalTotalPayments As Decimal
    Dim PaymentArrangement As finAccountPayArrangement
    Dim PaymentArrangementCurrent As finAccountPayArrangement
    Dim PaymentRegular As Decimal
    Dim RestructuredTotalCostOfBorrowing As Decimal
    Dim RestructuredTotalFees As Decimal
    Dim RestructuredTotalInterest As Decimal
    Dim RestructuredTotalPayments As Decimal
    Dim RestructuredTotalPaymentsToDate As Decimal
    Dim strTemp As String
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Value As Decimal
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    If accountPayArrangementAdd.Calculation.IsCalculationRequired Then
      ' Ignore
    Else
      ' Get Information
      With accountPayArrangementAdd
        .Account.GetBalance(Balance)
        .Account.GetDirectDebitsAwaitingProcessing(0, DirectDebitValue, #12/31/9999#)
      End With

      ' Get Original Account Calculation
      accountPayArrangementAdd.Account.CalculationVersions(0).GetAccountCalc(AccountCalcOriginal)

      ' Get Original Totals
      OriginalTotalCostOfBorrowing = 0
      OriginalTotalFees = 0
      OriginalTotalInterest = 0
      OriginalTotalPayments = 0
      For Each AccountCalcScheduleItem In AccountCalcOriginal.Schedule
        Select Case AccountCalcScheduleItem.ElementType
          Case isefinElementType.Cost, isefinElementType.Journal
            OriginalTotalCostOfBorrowing += AccountCalcScheduleItem.Value
          Case isefinElementType.Fee
            OriginalTotalCostOfBorrowing += AccountCalcScheduleItem.Value
            OriginalTotalFees += AccountCalcScheduleItem.Value
          Case isefinElementType.Interest, isefinElementType.InterestDefault
            OriginalTotalCostOfBorrowing += AccountCalcScheduleItem.Value
            OriginalTotalInterest += AccountCalcScheduleItem.Value
          Case isefinElementType.PaymentReceived
            OriginalTotalPayments -= AccountCalcScheduleItem.Value
        End Select
      Next

      ' Get Restructured Account Calculation
      accountPayArrangementAdd.Account.CalculationVersions.GetLatestCalculation(-1, AccountCalcRestructured)
      If AccountCalcRestructured.AccountCalcPk = AccountCalcOriginal.AccountCalcPk Then
        ' Hasn't been restructured
        AccountCalcRestructured = Nothing
      End If

      ' Get Restructured Totals
      If AccountCalcRestructured IsNot Nothing Then
        RestructuredTotalCostOfBorrowing = 0
        RestructuredTotalFees = 0
        RestructuredTotalInterest = 0
        RestructuredTotalPayments = 0
        RestructuredTotalPaymentsToDate = 0

        ' Add Transactions from prior to the Restructure
        For Each AccountTransaction In accountPayArrangementAdd.Account.Transactions
          If AccountTransaction.AccountCalculationPk <> 0 Then
            Select Case AccountTransaction.ElementType
              Case isefinElementType.Cost, isefinElementType.Journal
                RestructuredTotalCostOfBorrowing += AccountTransaction.Value
              Case isefinElementType.Fee
                RestructuredTotalCostOfBorrowing += AccountTransaction.Value
                RestructuredTotalFees += AccountTransaction.Value
              Case isefinElementType.Interest, isefinElementType.InterestDefault
                RestructuredTotalCostOfBorrowing += AccountTransaction.Value
                RestructuredTotalInterest += AccountTransaction.Value
              Case isefinElementType.PaymentReceived
                RestructuredTotalPaymentsToDate -= AccountTransaction.Value
                RestructuredTotalPayments -= AccountTransaction.Value
            End Select
          End If
        Next

        ' Add Future Schedule
        For Each AccountCalcScheduleItem In AccountCalcRestructured.Schedule
          If AccountCalcScheduleItem.ScheduleType = isefinAccountCalcScheduleType.OpeningRestructure Then
            ' Ignore Opening Schedule Transaction
          Else
            Select Case AccountCalcScheduleItem.ElementType
              Case isefinElementType.Cost, isefinElementType.Journal
                RestructuredTotalCostOfBorrowing += AccountCalcScheduleItem.Value
              Case isefinElementType.Fee
                RestructuredTotalCostOfBorrowing += AccountCalcScheduleItem.Value
                RestructuredTotalFees += AccountCalcScheduleItem.Value
              Case isefinElementType.Interest, isefinElementType.InterestDefault
                RestructuredTotalCostOfBorrowing += AccountCalcScheduleItem.Value
                RestructuredTotalInterest += AccountCalcScheduleItem.Value
              Case isefinElementType.PaymentReceived
                RestructuredTotalPayments -= AccountCalcScheduleItem.Value
            End Select
          End If
        Next
      End If

      ' Get Current Payment Arrangement - ignoring Promises
      PaymentArrangementCurrent = Nothing
      For Each PaymentArrangement In accountPayArrangementAdd.Account.PaymentArrangements
        Select Case PaymentArrangement.Source
          Case isefinAccountPaymentArrangementSource.Promise
          Case Else
            If AccountCalcRestructured IsNot Nothing AndAlso PaymentArrangement.CreatedUtcDate < AccountCalcRestructured.CreatedUtcDate Then
              ' Ignore if prior to Restructure?
            Else
              PaymentArrangementCurrent = PaymentArrangement
            End If
        End Select
      Next

      ' Get Current Payment Arrangement Totals
      If PaymentArrangementCurrent IsNot Nothing Then
        CurrentArrangementPaymentsInsufficient = (PaymentArrangementCurrent.PaymentFinalDate = Nothing)
        CurrentArrangementTotalCostOfBorrowing = PaymentArrangementCurrent.TotalCostOfBorrowing
        CurrentArrangementTotalFees = PaymentArrangementCurrent.TotalFees
        CurrentArrangementTotalInterest = PaymentArrangementCurrent.TotalInterest
        CurrentArrangementTotalPayments = PaymentArrangementCurrent.TotalPayments
        CurrentArrangementTotalPaymentsToDate = PaymentArrangementCurrent.TotalPaymentsToDate
      End If

      ' Get Current Account Calculation
      AccountCalcCurrent = accountPayArrangementAdd.Account.Calculation

      ' Get Current Totals
      If AccountCalcCurrent.PaymentFinalDate = Nothing Then
        ' Not being paid off
        CurrentPaymentsInsufficient = True
        CurrentTotalCostOfBorrowing = 0
        CurrentTotalFees = 0
        CurrentTotalInterest = 0
        CurrentTotalInterestRemaining = 0
        CurrentTotalPayments = 0
        CurrentTotalPaymentsRemaining = 0
        CurrentTotalPaymentsToDate = -accountPayArrangementAdd.Account.Transactions.Total(isefinElementType.PaymentReceived)
      Else
        CurrentPaymentsInsufficient = False
        With accountPayArrangementAdd.Account.Transactions
          CurrentTotalCostOfBorrowing = .Total(isefinElementType.Cost) + .Total(isefinElementType.Journal) + .Total(isefinElementType.Fee) + .Total(isefinElementType.Interest) + .Total(isefinElementType.InterestDefault)
          CurrentTotalFees = .Total(isefinElementType.Fee)
          CurrentTotalInterest = .Total(isefinElementType.Interest) + .Total(isefinElementType.InterestDefault)
          CurrentTotalInterestRemaining = 0
          CurrentTotalPayments = - .Total(isefinElementType.PaymentReceived)
          CurrentTotalPaymentsRemaining = 0
          CurrentTotalPaymentsToDate = - .Total(isefinElementType.PaymentReceived)
        End With
        For Each AccountCalcScheduleItem In AccountCalcCurrent.Schedule
          If AccountCalcScheduleItem.IsExisting Then
            ' Ignore as already counted
          Else
            Select Case AccountCalcScheduleItem.ElementType
              Case isefinElementType.Cost, isefinElementType.Journal
                CurrentTotalCostOfBorrowing += AccountCalcScheduleItem.Value
              Case isefinElementType.Fee
                CurrentTotalCostOfBorrowing += AccountCalcScheduleItem.Value
                CurrentTotalFees += AccountCalcScheduleItem.Value
              Case isefinElementType.Interest, isefinElementType.InterestDefault
                CurrentTotalCostOfBorrowing += AccountCalcScheduleItem.Value
                CurrentTotalInterest += AccountCalcScheduleItem.Value
                CurrentTotalInterestRemaining += AccountCalcScheduleItem.Value
              Case isefinElementType.PaymentReceived
                CurrentTotalPayments -= AccountCalcScheduleItem.Value
                CurrentTotalPaymentsRemaining -= AccountCalcScheduleItem.Value
            End Select
          End If
        Next
      End If

      ' Get New (Future) Account Calculation)
      AccountCalcNew = accountPayArrangementAdd.Calculation

      If AccountCalcNew.PaymentFinalDate = Nothing Then
        ' Not being paid off
        NewPaymentsInsufficient = True
        NewTotalCostOfBorrowing = 0
        NewTotalFees = 0
        NewTotalInterest = 0
        NewTotalInterestRemaining = 0
        NewTotalPayments = 0
        NewTotalPaymentsRemaining = 0
        NewTotalPaymentsToDate = -accountPayArrangementAdd.Account.Transactions.Total(isefinElementType.PaymentReceived)
      Else
        NewPaymentsInsufficient = False
        With accountPayArrangementAdd.Account.Transactions
          NewTotalCostOfBorrowing = .Total(isefinElementType.Cost) + .Total(isefinElementType.Journal) + .Total(isefinElementType.Fee) + .Total(isefinElementType.Interest) + .Total(isefinElementType.InterestDefault)
          NewTotalFees = .Total(isefinElementType.Fee)
          NewTotalInterest = .Total(isefinElementType.Interest) + .Total(isefinElementType.InterestDefault)
          NewTotalInterestRemaining = 0
          NewTotalPayments = - .Total(isefinElementType.PaymentReceived)
          NewTotalPaymentsRemaining = 0
          NewTotalPaymentsToDate = - .Total(isefinElementType.PaymentReceived)
        End With
        For Each AccountCalcScheduleItem In AccountCalcNew.Schedule
          If AccountCalcScheduleItem.IsExisting Then
            ' Ignore as already counted
          Else
            Select Case AccountCalcScheduleItem.ElementType
              Case isefinElementType.Cost, isefinElementType.Journal
                NewTotalCostOfBorrowing += AccountCalcScheduleItem.Value
              Case isefinElementType.Fee
                NewTotalCostOfBorrowing += AccountCalcScheduleItem.Value
                NewTotalFees += AccountCalcScheduleItem.Value
              Case isefinElementType.Interest, isefinElementType.InterestDefault
                NewTotalCostOfBorrowing += AccountCalcScheduleItem.Value
                NewTotalInterest += AccountCalcScheduleItem.Value
                NewTotalInterestRemaining += AccountCalcScheduleItem.Value
              Case isefinElementType.PaymentReceived
                NewTotalPayments -= AccountCalcScheduleItem.Value
                NewTotalPaymentsRemaining -= AccountCalcScheduleItem.Value
            End Select
          End If
        Next
      End If

      With SummaryTableMain
        ' Initialise
        .TableClass = iseSummaryTableClass.TabularData
        .Caption = ""
        .AutoStripe = True

        ' Columns
        With .Columns
          .AddText(" ").NoBreakChars = 12
          .AddDate("Original")
          If AccountCalcRestructured IsNot Nothing Then .AddDate("Last" & vbNewLine & "Restructure")
          If PaymentArrangementCurrent IsNot Nothing Then .AddDate("Last" & vbNewLine & "Variation")
          .AddDate("Current")
          .AddDate("New")
        End With

        With .Rows
          '*************************************************************
          ' Dated
          '*************************************************************
          With .Add.Cells()
            .AddText("Dated").CellClass = iseSummaryTableCellClass.Caption
            .AddDate(AccountCalcOriginal.OpeningDate, True)
            If AccountCalcRestructured IsNot Nothing Then .AddDate(AccountCalcRestructured.DateRestructured, True)
            If PaymentArrangementCurrent IsNot Nothing Then .AddDate(PaymentArrangementCurrent.ArrangementDate, True)
            .AddText("")
            .AddDate(accountPayArrangementAdd.ArrangementDate, True)
          End With

          '*************************************************************
          ' Regular Payment
          '*************************************************************
          With .Add.Cells()
            .AddText("Regular Payment").CellClass = iseSummaryTableCellClass.Caption

            ' Original
            strTemp = String.Format("{0} {1}", AccountCalcOriginal.PaymentCycleDescriptionWithoutCycleDays, finBL.FormatCurrency(AccountCalcOriginal.PaymentRegular, True))
            If AccountCalcOriginal.PaymentCycleFreqPA = 0 OrElse AccountCalcNew.PaymentCycleFreqPA = 0 Then PaymentRegular = 0 Else PaymentRegular = finBL.CurrencyRound(AccountCalcOriginal.PaymentRegular * CDec(AccountCalcOriginal.PaymentCycleFreqPA) / CDec(AccountCalcNew.PaymentCycleFreqPA))
            If PaymentRegular <> 0 Then
              Select Case PaymentRegular
                Case < AccountCalcNew.PaymentRegular
                  strTemp &= String.Format("<br>--{0} Increase {1}--", IIf(AccountCalcOriginal.PaymentCycleFreqPA = AccountCalcNew.PaymentCycleFreqPA, "", AccountCalcNew.PaymentCycleDescriptionWithoutCycleDays), finBL.FormatCurrency(AccountCalcNew.PaymentRegular - PaymentRegular, True))
                Case > AccountCalcNew.PaymentRegular
                  strTemp &= String.Format("<br>--{0} Decrease {1}--", IIf(AccountCalcOriginal.PaymentCycleFreqPA = AccountCalcNew.PaymentCycleFreqPA, "", AccountCalcNew.PaymentCycleDescriptionWithoutCycleDays), finBL.FormatCurrency(PaymentRegular - AccountCalcNew.PaymentRegular, True))
              End Select
            End If
            .AddWiki(strTemp)

            ' Restructured
            If AccountCalcRestructured IsNot Nothing Then
              strTemp = String.Format("{0} {1}", AccountCalcRestructured.PaymentCycleDescriptionWithoutCycleDays, finBL.FormatCurrency(AccountCalcRestructured.PaymentRegular, True))
              If AccountCalcRestructured.PaymentCycleFreqPA = 0 OrElse AccountCalcNew.PaymentCycleFreqPA = 0 Then PaymentRegular = 0 Else PaymentRegular = finBL.CurrencyRound(AccountCalcRestructured.PaymentRegular * CDec(AccountCalcRestructured.PaymentCycleFreqPA) / CDec(AccountCalcNew.PaymentCycleFreqPA))
              If PaymentRegular <> 0 Then
                Select Case PaymentRegular
                  Case < AccountCalcNew.PaymentRegular
                    strTemp &= String.Format("<br>--{0} Increase {1}--", IIf(AccountCalcRestructured.PaymentCycleFreqPA = AccountCalcNew.PaymentCycleFreqPA, "", AccountCalcNew.PaymentCycleDescriptionWithoutCycleDays), finBL.FormatCurrency(AccountCalcNew.PaymentRegular - PaymentRegular, True))
                  Case > AccountCalcNew.PaymentRegular
                    strTemp &= String.Format("<br>--{0} Decrease {1}--", IIf(AccountCalcRestructured.PaymentCycleFreqPA = AccountCalcNew.PaymentCycleFreqPA, "", AccountCalcNew.PaymentCycleDescriptionWithoutCycleDays), finBL.FormatCurrency(PaymentRegular - AccountCalcNew.PaymentRegular, True))
                End Select
              End If
              .AddWiki(strTemp)
            End If

            ' Payment Arrangement
            If PaymentArrangementCurrent IsNot Nothing Then
              strTemp = String.Format("{0} {1}", PaymentArrangementCurrent.PaymentCycleDescriptionWithoutCycleDays, finBL.FormatCurrency(PaymentArrangementCurrent.PaymentRegular, True))
              If PaymentArrangementCurrent.PaymentCycleFreqPA = 0 OrElse AccountCalcNew.PaymentCycleFreqPA = 0 Then PaymentRegular = 0 Else PaymentRegular = finBL.CurrencyRound(PaymentArrangementCurrent.PaymentRegular * CDec(PaymentArrangementCurrent.PaymentCycleFreqPA) / CDec(AccountCalcNew.PaymentCycleFreqPA))
              If PaymentRegular <> 0 Then
                Select Case PaymentRegular
                  Case < AccountCalcNew.PaymentRegular
                    strTemp &= String.Format("<br>--{0} Increase {1}--", IIf(PaymentArrangementCurrent.PaymentCycleFreqPA = AccountCalcNew.PaymentCycleFreqPA, "", AccountCalcNew.PaymentCycleDescriptionWithoutCycleDays), finBL.FormatCurrency(AccountCalcNew.PaymentRegular - PaymentRegular, True))
                  Case > AccountCalcNew.PaymentRegular
                    strTemp &= String.Format("<br>--{0} Decrease {1}--", IIf(PaymentArrangementCurrent.PaymentCycleFreqPA = AccountCalcNew.PaymentCycleFreqPA, "", AccountCalcNew.PaymentCycleDescriptionWithoutCycleDays), finBL.FormatCurrency(PaymentRegular - AccountCalcNew.PaymentRegular, True))
                End Select
              End If
              .AddWiki(strTemp)
            End If

            ' Current
            strTemp = String.Format("{0} {1}", AccountCalcCurrent.PaymentCycleDescriptionWithoutCycleDays, finBL.FormatCurrency(AccountCalcCurrent.PaymentRegular, True))
            If AccountCalcCurrent.PaymentCycleFreqPA = 0 OrElse AccountCalcNew.PaymentCycleFreqPA = 0 Then PaymentRegular = 0 Else PaymentRegular = finBL.CurrencyRound(AccountCalcCurrent.PaymentRegular * CDec(AccountCalcCurrent.PaymentCycleFreqPA) / CDec(AccountCalcNew.PaymentCycleFreqPA))
            If PaymentRegular <> 0 Then
              Select Case PaymentRegular
                Case < AccountCalcNew.PaymentRegular
                  strTemp &= String.Format("<br>--{0} Increase {1}--", IIf(AccountCalcCurrent.PaymentCycleFreqPA = AccountCalcNew.PaymentCycleFreqPA, "", AccountCalcNew.PaymentCycleDescriptionWithoutCycleDays), finBL.FormatCurrency(AccountCalcNew.PaymentRegular - PaymentRegular, True))
                Case > AccountCalcNew.PaymentRegular
                  strTemp &= String.Format("<br>--{0} Decrease {1}--", IIf(AccountCalcCurrent.PaymentCycleFreqPA = AccountCalcNew.PaymentCycleFreqPA, "", AccountCalcNew.PaymentCycleDescriptionWithoutCycleDays), finBL.FormatCurrency(PaymentRegular - AccountCalcNew.PaymentRegular, True))
              End Select
            End If
            .AddWiki(strTemp)

            ' New
            .AddText(String.Format("{0} {1}", AccountCalcNew.PaymentCycleDescriptionWithoutCycleDays, finBL.FormatCurrency(AccountCalcNew.PaymentRegular, True)))
          End With

          '*************************************************************
          ' Length of Loan (Term for Original/ Restructure)
          '*************************************************************
          With .Add.Cells()
            .AddText("Length of Loan").CellClass = iseSummaryTableCellClass.Caption
            .AddText(AccountCalcOriginal.TermCycleDescriptionResolved())
            If AccountCalcRestructured IsNot Nothing Then .AddText(AccountCalcRestructured.TermCycleDescriptionResolved)
            If PaymentArrangementCurrent IsNot Nothing Then .AddText(finBL.Runtime.DateUtilities.PeriodToWordsWithHint(AccountCalcOriginal.OpeningDate, PaymentArrangementCurrent.PaymentFinalDate, PaymentArrangementCurrent.PaymentCycleFreqPA))
            .AddText(finBL.Runtime.DateUtilities.PeriodToWordsWithHint(AccountCalcOriginal.OpeningDate, AccountCalcCurrent.PaymentFinalDate, AccountCalcCurrent.PaymentCycleFreqPA))
            .AddText(finBL.Runtime.DateUtilities.PeriodToWordsWithHint(AccountCalcOriginal.OpeningDate, AccountCalcNew.PaymentFinalDate, AccountCalcNew.PaymentCycleFreqPA))
          End With

          '*************************************************************
          ' Final Payment
          '*************************************************************
          If AccountCalcNew.Schedule.Count > 0 AndAlso AccountCalcNew.Schedule.Item(AccountCalcNew.Schedule.Count - 1).Balance > AccountCalcNew.ResidualValue Then
            Warnings &= "{{warning|Payments are insufficient to pay off the Account.|True}}"
          Else
            strTemp = finBL.FormatDateLong(AccountCalcNew.PaymentFinalDate)

            If Balance < 0 Then
              Warnings &= "{{info|Account has a CREDIT Balance.}}"
            ElseIf AccountCalcNew.ResidualValue <> 0 AndAlso AccountCalcNew.PaymentFinalDate < AccountCalcNew.DateMaturity Then
              ' Residual Value still due at Maturity
            Else
              If AccountCalcCurrent.PaymentFinalDate = Nothing Then
                ' If current Calculation does not have a final date compare to the Original Calculation for something meaningful
                If AccountCalcNew.PaymentFinalDate < AccountCalcOriginal.PaymentFinalDate Then
                  Warnings &= "{{info|Projected final payment date is now **" & strTemp & "**.}}"
                ElseIf AccountCalcNew.PaymentFinalDate > AccountCalcOriginal.PaymentFinalDate Then
                  Warnings &= "{{warning|Projected final payment date is now **" & strTemp & "**.}}"
                End If
              Else
                If AccountCalcNew.PaymentFinalDate < AccountCalcCurrent.PaymentFinalDate Then
                  Warnings &= "{{info|Projected final payment date is now **" & strTemp & "**.}}"
                ElseIf AccountCalcNew.PaymentFinalDate > AccountCalcCurrent.PaymentFinalDate Then
                  Warnings &= "{{warning|Projected final payment date is now **" & strTemp & "**.}}"
                End If
              End If
            End If
          End If
          With .Add().Cells
            .AddText("Final Payment")

            ' Original
            strTemp = finBL.FormatDate(AccountCalcOriginal.PaymentFinalDate, True)
            If AccountCalcOriginal.PaymentFinalDate <> Nothing AndAlso AccountCalcNew.PaymentFinalDate <> Nothing Then
              Select Case AccountCalcOriginal.PaymentFinalDate
                Case < AccountCalcNew.PaymentFinalDate
                  strTemp &= String.Format("<br>--!!Increase {0}!!--", finBL.Runtime.DateUtilities.PeriodToWords(AccountCalcOriginal.PaymentFinalDate, AccountCalcNew.PaymentFinalDate, AccountCalcNew.PaymentCycleFreqPA))
                Case > AccountCalcNew.PaymentFinalDate
                  strTemp &= String.Format("<br>--++Decrease {0}++--", finBL.Runtime.DateUtilities.PeriodToWords(AccountCalcNew.PaymentFinalDate, AccountCalcOriginal.PaymentFinalDate, AccountCalcNew.PaymentCycleFreqPA))
              End Select
            End If
            .AddWiki(strTemp)

            ' Restructured
            If AccountCalcRestructured IsNot Nothing Then
              strTemp = finBL.FormatDate(AccountCalcRestructured.PaymentFinalDate, True)
              If AccountCalcRestructured.PaymentFinalDate <> Nothing AndAlso AccountCalcNew.PaymentFinalDate <> Nothing Then
                Select Case AccountCalcRestructured.PaymentFinalDate
                  Case < AccountCalcNew.PaymentFinalDate
                    strTemp &= String.Format("<br>--!!Increase {0}!!--", finBL.Runtime.DateUtilities.PeriodToWords(AccountCalcRestructured.PaymentFinalDate, AccountCalcNew.PaymentFinalDate, AccountCalcNew.PaymentCycleFreqPA))
                  Case > AccountCalcNew.PaymentFinalDate
                    strTemp &= String.Format("<br>--++Decrease {0}++--", finBL.Runtime.DateUtilities.PeriodToWords(AccountCalcNew.PaymentFinalDate, AccountCalcRestructured.PaymentFinalDate, AccountCalcNew.PaymentCycleFreqPA))
                End Select
              End If
              .AddWiki(strTemp)
            End If

            ' Payment Arrangement
            If PaymentArrangementCurrent IsNot Nothing Then
              strTemp = finBL.FormatDate(PaymentArrangementCurrent.PaymentFinalDate, True)
              If PaymentArrangementCurrent.PaymentFinalDate <> Nothing AndAlso AccountCalcNew.PaymentFinalDate <> Nothing Then
                Select Case PaymentArrangementCurrent.PaymentFinalDate
                  Case < AccountCalcNew.PaymentFinalDate
                    strTemp &= String.Format("<br>--!!Increase {0}!!--", finBL.Runtime.DateUtilities.PeriodToWords(PaymentArrangementCurrent.PaymentFinalDate, AccountCalcNew.PaymentFinalDate, AccountCalcNew.PaymentCycleFreqPA))
                  Case > AccountCalcNew.PaymentFinalDate
                    strTemp &= String.Format("<br>--++Decrease {0}++--", finBL.Runtime.DateUtilities.PeriodToWords(AccountCalcNew.PaymentFinalDate, PaymentArrangementCurrent.PaymentFinalDate, AccountCalcNew.PaymentCycleFreqPA))
                End Select
              End If
              .AddWiki(strTemp)
            End If

            ' Current
            strTemp = finBL.FormatDate(AccountCalcCurrent.PaymentFinalDate, True)
            If AccountCalcCurrent.PaymentFinalDate <> Nothing AndAlso AccountCalcNew.PaymentFinalDate <> Nothing Then
              Select Case AccountCalcCurrent.PaymentFinalDate
                Case < AccountCalcNew.PaymentFinalDate
                  strTemp &= String.Format("<br>--!!Increase {0}!!--", finBL.Runtime.DateUtilities.PeriodToWords(AccountCalcCurrent.PaymentFinalDate, AccountCalcNew.PaymentFinalDate, AccountCalcNew.PaymentCycleFreqPA))
                Case > AccountCalcNew.PaymentFinalDate
                  strTemp &= String.Format("<br>--++Decrease {0}++--", finBL.Runtime.DateUtilities.PeriodToWords(AccountCalcNew.PaymentFinalDate, AccountCalcCurrent.PaymentFinalDate, AccountCalcNew.PaymentCycleFreqPA))
              End Select
            End If
            .AddWiki(strTemp)

            ' New
            If AccountCalcNew.PaymentFinalDate = Nothing Then
              .AddWiki("!!**ERROR**!!").Tooltip = "Payments are insufficient to pay off the Account."
            Else
              .AddDate(AccountCalcNew.PaymentFinalDate, True)
            End If
          End With

          '*************************************************************
          ' Balloon Payment
          '*************************************************************
          If AccountCalcOriginal.PaymentBalloon <> 0 OrElse (AccountCalcRestructured IsNot Nothing AndAlso AccountCalcRestructured.PaymentBalloon <> 0) OrElse AccountCalcCurrent.PaymentBalloon <> 0 OrElse AccountCalcNew.PaymentBalloon <> 0 Then
            ' Get Project Balloon Payment
            AccountCalcNew.GetPaymentBalloon(Nothing, Value)

            With .Add().Cells
              .AddText("Balloon Payment")
              .AddCurrency(AccountCalcOriginal.PaymentBalloon, True)
              If AccountCalcRestructured IsNot Nothing Then .AddCurrency(AccountCalcRestructured.PaymentBalloon, True)
              .AddCurrency(AccountCalcCurrent.PaymentBalloon, True)
              If Value = 0 Then
                .AddCurrency(0, True).CellClass = iseSummaryTableCellClass.WarningBold
              Else
                .AddCurrency(AccountCalcNew.PaymentBalloon, True)
              End If
            End With

            If AccountCalcNew.PaymentBalloon <> Value Then
              If AccountCalcNew.OptionPaymentsFinalPlusBalloon Then
                Warnings &= "{{warning|" & String.Format("Projected Balloon (including regular) Payment is **{0}**.", finBL.FormatCurrency(Value, True)) & "}}"
              Else
                Warnings &= "{{warning|" & String.Format("Projected Balloon Payment is **{0}**.", finBL.FormatCurrency(Value, True)) & "}}"
              End If
            End If
          End If

          '*************************************************************
          ' Total Interest
          '*************************************************************
          With .Add.Cells()
            .AddText("Total Interest").CellClass = iseSummaryTableCellClass.Caption

            ' Original
            strTemp = finBL.FormatCurrency(OriginalTotalInterest, True)
            If Not NewPaymentsInsufficient Then
              Select Case OriginalTotalInterest
                Case < NewTotalInterest
                  strTemp &= String.Format("<br>--!!Increase {0}!!--", finBL.FormatCurrency(NewTotalInterest - OriginalTotalInterest, True))
                Case > NewTotalInterest
                  strTemp &= String.Format("<br>--++Decrease {0}++--", finBL.FormatCurrency(OriginalTotalInterest - NewTotalInterest, True))
              End Select
            End If
            .AddWiki(strTemp)

            ' Restructured
            If AccountCalcRestructured IsNot Nothing Then
              strTemp = finBL.FormatCurrency(RestructuredTotalInterest, True)
              If Not NewPaymentsInsufficient Then
                Select Case RestructuredTotalInterest
                  Case < NewTotalInterest
                    strTemp &= String.Format("<br>--!!Increase {0}!!--", finBL.FormatCurrency(NewTotalInterest - RestructuredTotalInterest, True))
                  Case > NewTotalInterest
                    strTemp &= String.Format("<br>--++Decrease {0}++--", finBL.FormatCurrency(RestructuredTotalInterest - NewTotalInterest, True))
                End Select
              End If
              .AddWiki(strTemp)
            End If

            ' Payment Arrangement
            If PaymentArrangementCurrent IsNot Nothing Then
              If CurrentArrangementPaymentsInsufficient Then
                .AddText("")
              Else
                strTemp = finBL.FormatCurrency(CurrentArrangementTotalInterest, True)
                If Not NewPaymentsInsufficient Then
                  Select Case CurrentArrangementTotalInterest
                    Case < NewTotalInterest
                      strTemp &= String.Format("<br>--!!Increase {0}!!--", finBL.FormatCurrency(NewTotalInterest - CurrentArrangementTotalInterest, True))
                    Case > NewTotalInterest
                      strTemp &= String.Format("<br>--++Decrease {0}++--", finBL.FormatCurrency(CurrentArrangementTotalInterest - NewTotalInterest, True))
                  End Select
                End If
                .AddWiki(strTemp)
              End If
            End If

            ' Current
            If CurrentPaymentsInsufficient Then
              .AddText("")
            Else
              strTemp = finBL.FormatCurrency(CurrentTotalInterest, True)
              If Not NewPaymentsInsufficient Then
                Select Case CurrentTotalInterest
                  Case < NewTotalInterest
                    strTemp &= String.Format("<br>--!!Increase {0}!!--", finBL.FormatCurrency(NewTotalInterest - CurrentTotalInterest, True))
                  Case > NewTotalInterest
                    strTemp &= String.Format("<br>--++Decrease {0}++--", finBL.FormatCurrency(CurrentTotalInterest - NewTotalInterest, True))
                End Select
              End If
              .AddWiki(strTemp)
            End If

            ' New
            If NewPaymentsInsufficient Then
              .AddText("")
            Else
              .AddCurrency(NewTotalInterest, True)
            End If
          End With

          '*************************************************************
          ' Total Interest Remaining
          '*************************************************************
          With .Add.Cells()
            .AddText("Total Interest Remaining").CellClass = iseSummaryTableCellClass.Caption
            .AddText("")
            If AccountCalcRestructured IsNot Nothing Then .AddText("")
            If PaymentArrangementCurrent IsNot Nothing Then .AddText("")
            .AddText("")
            If NewPaymentsInsufficient Then
              .AddText("")
            Else
              .AddCurrency(NewTotalInterestRemaining, True)
            End If
          End With

          '*************************************************************
          ' Total Fees
          '*************************************************************
          With .Add.Cells()
            .AddText("Total Fees").CellClass = iseSummaryTableCellClass.Caption

            ' Original
            strTemp = finBL.FormatCurrency(OriginalTotalFees, True)
            If Not NewPaymentsInsufficient Then
              Select Case OriginalTotalFees
                Case < NewTotalFees
                  strTemp &= String.Format("<br>--!!Increase {0}!!--", finBL.FormatCurrency(NewTotalFees - OriginalTotalFees, True))
                Case > NewTotalFees
                  strTemp &= String.Format("<br>--++Decrease {0}++--", finBL.FormatCurrency(OriginalTotalFees - NewTotalFees, True))
              End Select
            End If
            .AddWiki(strTemp)

            ' Restructured
            If AccountCalcRestructured IsNot Nothing Then
              strTemp = finBL.FormatCurrency(RestructuredTotalFees, True)
              If Not NewPaymentsInsufficient Then
                Select Case RestructuredTotalFees
                  Case < NewTotalFees
                    strTemp &= String.Format("<br>--!!Increase {0}!!--", finBL.FormatCurrency(NewTotalFees - RestructuredTotalFees, True))
                  Case > NewTotalFees
                    strTemp &= String.Format("<br>--++Decrease {0}++--", finBL.FormatCurrency(RestructuredTotalFees - NewTotalFees, True))
                End Select
              End If
              .AddWiki(strTemp)
            End If

            ' Payment Arrangement
            If PaymentArrangementCurrent IsNot Nothing Then
              If CurrentArrangementPaymentsInsufficient Then
                .AddText("")
              Else
                strTemp = finBL.FormatCurrency(CurrentArrangementTotalFees, True)
                If Not NewPaymentsInsufficient Then
                  Select Case CurrentArrangementTotalFees
                    Case < NewTotalFees
                      strTemp &= String.Format("<br>--!!Increase {0}!!--", finBL.FormatCurrency(NewTotalFees - CurrentArrangementTotalFees, True))
                    Case > NewTotalFees
                      strTemp &= String.Format("<br>--++Decrease {0}++--", finBL.FormatCurrency(CurrentArrangementTotalFees - NewTotalFees, True))
                  End Select
                End If
                .AddWiki(strTemp)
              End If
            End If

            ' Current
            If CurrentPaymentsInsufficient Then
              .AddText("")
            Else
              strTemp = finBL.FormatCurrency(CurrentTotalFees, True)
              If Not NewPaymentsInsufficient Then
                Select Case CurrentTotalFees
                  Case < NewTotalFees
                    strTemp &= String.Format("<br>--!!Increase {0}!!--", finBL.FormatCurrency(NewTotalFees - CurrentTotalFees, True))
                  Case > NewTotalFees
                    strTemp &= String.Format("<br>--++Decrease {0}++--", finBL.FormatCurrency(CurrentTotalFees - NewTotalFees, True))
                End Select
              End If
              .AddWiki(strTemp)
            End If

            ' New
            If NewPaymentsInsufficient Then
              .AddText("")
            Else
              .AddCurrency(NewTotalFees, True)
            End If
          End With

          '*************************************************************
          ' Total Cost of Borrowing
          '*************************************************************
          With .Add.Cells()
            .AddText("Total Cost of Borrowing").CellClass = iseSummaryTableCellClass.Caption

            ' Original
            strTemp = finBL.FormatCurrency(OriginalTotalCostOfBorrowing, True)
            If Not NewPaymentsInsufficient Then
              Select Case OriginalTotalCostOfBorrowing
                Case < NewTotalCostOfBorrowing
                  strTemp &= String.Format("<br>--!!Increase {0}!!--", finBL.FormatCurrency(NewTotalCostOfBorrowing - OriginalTotalCostOfBorrowing, True))
                Case > NewTotalCostOfBorrowing
                  strTemp &= String.Format("<br>--++Decrease {0}++--", finBL.FormatCurrency(OriginalTotalCostOfBorrowing - NewTotalCostOfBorrowing, True))
              End Select
            End If
            .AddWiki(strTemp)

            ' Restructured
            If AccountCalcRestructured IsNot Nothing Then
              strTemp = finBL.FormatCurrency(RestructuredTotalCostOfBorrowing, True)
              If Not NewPaymentsInsufficient Then
                Select Case RestructuredTotalCostOfBorrowing
                  Case < NewTotalCostOfBorrowing
                    strTemp &= String.Format("<br>--!!Increase {0}!!--", finBL.FormatCurrency(NewTotalCostOfBorrowing - RestructuredTotalCostOfBorrowing, True))
                  Case > NewTotalCostOfBorrowing
                    strTemp &= String.Format("<br>--++Decrease {0}++--", finBL.FormatCurrency(RestructuredTotalCostOfBorrowing - NewTotalCostOfBorrowing, True))
                End Select
              End If
              .AddWiki(strTemp)
            End If

            ' Payment Arrangement
            If PaymentArrangementCurrent IsNot Nothing Then
              If CurrentArrangementPaymentsInsufficient Then
                .AddText("")
              Else
                strTemp = finBL.FormatCurrency(CurrentArrangementTotalCostOfBorrowing, True)
                If Not NewPaymentsInsufficient Then
                  Select Case CurrentArrangementTotalCostOfBorrowing
                    Case < NewTotalCostOfBorrowing
                      strTemp &= String.Format("<br>--!!Increase {0}!!--", finBL.FormatCurrency(NewTotalCostOfBorrowing - CurrentArrangementTotalCostOfBorrowing, True))
                    Case > NewTotalCostOfBorrowing
                      strTemp &= String.Format("<br>--++Decrease {0}++--", finBL.FormatCurrency(CurrentArrangementTotalCostOfBorrowing - NewTotalCostOfBorrowing, True))
                  End Select
                End If
                .AddWiki(strTemp)
              End If
            End If

            ' Current
            If CurrentPaymentsInsufficient Then
              .AddText("")
            Else
              strTemp = finBL.FormatCurrency(CurrentTotalCostOfBorrowing, True)
              If Not NewPaymentsInsufficient Then
                Select Case CurrentTotalCostOfBorrowing
                  Case < NewTotalCostOfBorrowing
                    strTemp &= String.Format("<br>--!!Increase {0}!!--", finBL.FormatCurrency(NewTotalCostOfBorrowing - CurrentTotalCostOfBorrowing, True))
                  Case > NewTotalCostOfBorrowing
                    strTemp &= String.Format("<br>--++Decrease {0}++--", finBL.FormatCurrency(CurrentTotalCostOfBorrowing - NewTotalCostOfBorrowing, True))
                End Select
              End If
              .AddWiki(strTemp)
            End If

            ' New
            If NewPaymentsInsufficient Then
              .AddText("")
            Else
              .AddCurrency(NewTotalCostOfBorrowing, True)
            End If
          End With

          '*************************************************************
          ' Total Payments
          '*************************************************************
          With .Add.Cells()
            .AddText("Total Payments").CellClass = iseSummaryTableCellClass.Caption

            ' Original
            strTemp = finBL.FormatCurrency(OriginalTotalPayments, True)
            If Not NewPaymentsInsufficient Then
              Select Case OriginalTotalPayments
                Case < NewTotalPayments
                  strTemp &= String.Format("<br>--!!Increase {0}!!--", finBL.FormatCurrency(NewTotalPayments - OriginalTotalPayments, True))
                Case > NewTotalPayments
                  strTemp &= String.Format("<br>--++Decrease {0}++--", finBL.FormatCurrency(OriginalTotalPayments - NewTotalPayments, True))
              End Select
            End If
            .AddWiki(strTemp)

            ' Restructured
            If AccountCalcRestructured IsNot Nothing Then
              strTemp = finBL.FormatCurrency(RestructuredTotalPayments, True)
              If Not NewPaymentsInsufficient Then
                Select Case RestructuredTotalPayments
                  Case < NewTotalPayments
                    strTemp &= String.Format("<br>--!!Increase {0}!!--", finBL.FormatCurrency(NewTotalPayments - RestructuredTotalPayments, True))
                  Case > NewTotalPayments
                    strTemp &= String.Format("<br>--++Decrease {0}++--", finBL.FormatCurrency(RestructuredTotalPayments - NewTotalPayments, True))
                End Select
              End If
              .AddWiki(strTemp)
            End If

            ' Payment Arrangement
            If PaymentArrangementCurrent IsNot Nothing Then
              If CurrentArrangementPaymentsInsufficient Then
                .AddText("")
              Else
                strTemp = finBL.FormatCurrency(CurrentArrangementTotalPayments, True)
                If Not NewPaymentsInsufficient Then
                  Select Case CurrentArrangementTotalPayments
                    Case < NewTotalPayments
                      strTemp &= String.Format("<br>--!!Increase {0}!!--", finBL.FormatCurrency(NewTotalPayments - CurrentArrangementTotalPayments, True))
                    Case > NewTotalPayments
                      strTemp &= String.Format("<br>--++Decrease {0}++--", finBL.FormatCurrency(CurrentArrangementTotalPayments - NewTotalPayments, True))
                  End Select
                End If
                .AddWiki(strTemp)
              End If
            End If

            ' Current
            If CurrentPaymentsInsufficient Then
              .AddText("")
            Else
              strTemp = finBL.FormatCurrency(CurrentTotalPayments, True)
              If Not NewPaymentsInsufficient Then
                Select Case CurrentTotalPayments
                  Case < NewTotalPayments
                    strTemp &= String.Format("<br>--!!Increase {0}!!--", finBL.FormatCurrency(NewTotalPayments - CurrentTotalPayments, True))
                  Case > NewTotalPayments
                    strTemp &= String.Format("<br>--++Decrease {0}++--", finBL.FormatCurrency(CurrentTotalPayments - NewTotalPayments, True))
                End Select
              End If
              .AddWiki(strTemp)
            End If

            ' New
            If NewPaymentsInsufficient Then
              .AddText("")
            Else
              .AddCurrency(NewTotalPayments, True)
            End If
          End With

          '*************************************************************
          ' Total Payments Remaining
          '*************************************************************
          With .Add.Cells()
            .AddText("Total Payments Remaining").CellClass = iseSummaryTableCellClass.Caption
            .AddText("")
            If AccountCalcRestructured IsNot Nothing Then .AddText("")
            If PaymentArrangementCurrent IsNot Nothing Then .AddText("")
            .AddText("")
            If NewPaymentsInsufficient Then
              .AddText("")
            Else
              .AddCurrency(NewTotalPaymentsRemaining, True)
            End If
          End With

          '*************************************************************
          ' NZ HCCCC Rate of Charge
          '*************************************************************
          Select Case accountPayArrangementAdd.Account.ConsumerRegulationType
            Case isefinAccountConsumerRegulationType.NZ_HighCostConsumerCreditContract
              With .Add.Cells()
                .AddText("Rate of Charge").CellClass = iseSummaryTableCellClass.Caption
                If AccountCalcOriginal.ComparisonRateType = isefinAccountCalcComparisonRateType.NewZealandRateOfCharge Then
                  If AccountCalcOriginal.ComparisonRate < 0 Then
                    .AddText("Error")
                  Else
                    .AddPercent(AccountCalcOriginal.ComparisonRate / 100, 4, True, iseSummaryTableCellTextAlign.Left)
                  End If
                Else
                  .AddText("")
                End If
                If AccountCalcRestructured IsNot Nothing Then .AddText("")
                If PaymentArrangementCurrent IsNot Nothing Then
                  If PaymentArrangementCurrent.ComparisonRate < 0 Then
                    .AddText("Error")
                  Else
                    .AddPercent(PaymentArrangementCurrent.ComparisonRate / 100, 4, True, iseSummaryTableCellTextAlign.Left)
                  End If
                End If
                .AddText("")
                If accountPayArrangementAdd.ComparisonRate < 0 Then
                  .AddText("Error")
                Else
                  .AddPercent(accountPayArrangementAdd.ComparisonRate / 100, 4, True, iseSummaryTableCellTextAlign.Left)
                End If
              End With
          End Select
        End With

        ' Warning - Residual Value
        If AccountCalcNew.ResidualValue <> 0 Then
          If AccountCalcNew.Schedule.Count = 0 OrElse AccountCalcNew.Schedule(AccountCalcNew.Schedule.Count - 1).Balance >= AccountCalcNew.ResidualValue Then
            Warnings &= "{{info|" & String.Format("Residual Value of **{0}**.", finBL.FormatCurrency(AccountCalcNew.ResidualValue, True)) & "}}"
          Else
            Warnings &= "{{warning|" & String.Format("Projected Residual Value of **{0}**.", finBL.FormatCurrency(AccountCalcNew.Schedule(AccountCalcNew.Schedule.Count - 1).Balance, True)) & "}}"
          End If
        End If

        ' Warning - Direct Debits due
        If DirectDebitValue <> 0 Then
          Warnings &= "{{warning|Account has Direct Debits of **" & finBL.FormatCurrency(DirectDebitValue, True) & "** awaiting processing.<br>**These will be cleared if the Payment Arrangement is completed**.}}"
        End If

        ' Warning - Term extended
        Select Case accountPayArrangementAdd.Account.AccountClass
          Case isefinAccountClass.LoanFR, isefinAccountClass.LoanFT
            If callerScriptInfo.FormKey = "AccountPaymentPromiseAdd" Then
              ' Ignore check if doing a Promise
            ElseIf accountPayArrangementAdd.Calculation.PaymentFinalDate = Nothing OrElse (accountPayArrangementAdd.Calculation.PaymentFinalDate > accountPayArrangementAdd.Calculation.DateMaturity) Then
              If finBL.CurrentUser.Permissions.Allow("Account.PaymentArrangementAdd.AllowFinalPostMaturity") Then
                ' Permission Key allows User to override Account Type setting
              ElseIf Not accountPayArrangementAdd.Account.AccountType.OptionAllowPayArrangeExtendTerm Then
                Warnings &= "{{warning|You do not have permission to extend payments beyond the maturity date of the Account.|True}}"
              End If
            End If
        End Select

        ' Warning - Pending Floating Interest Rate changes exist
        If accountPayArrangementAdd.Account.HistoryItems.CountPendingFloatingInterestRateChanges <> 0 Then
          Warnings &= "{{Warning|Pending Floating Interest Rate changes exist.}}"
        End If

        ' Warning - High-Cost Loan
        Select Case accountPayArrangementAdd.Account.ConsumerRegulationType
          Case isefinAccountConsumerRegulationType.NZ_HighCostConsumerCreditContract
            If AccountCalcNew.ComparisonRateMaximum <> 0 AndAlso accountPayArrangementAdd.ComparisonRate > AccountCalcNew.ComparisonRateMaximum Then
              Warnings &= "{{Warning|" & String.Format("NZ High-Cost Consumer Credit Contract Rate of Charge **{0}** exceeds maximum limit of **{1}**.", finBL.FormatPercentage(accountPayArrangementAdd.ComparisonRate / 100, 4), finBL.FormatPercentage(AccountCalcNew.ComparisonRateMaximum / 100, 4)) & "|true}}"
            Else
              Warnings &= "{{Info|" & String.Format("NZ High-Cost Consumer Credit Contract Rate of Charge **{0}**.", finBL.FormatPercentage(accountPayArrangementAdd.ComparisonRate / 100, 4)) & "}}"
            End If

            If AccountCalcNew.Schedule.CountHighCostLoanAdjusted <> 0 Then
              Warnings &= "{{Warning|" & String.Format("One or more future Transactions will be reduced under 'NZ High-Cost Consumer Credit Contract' Regulations. **The first reduced Transaction is dated {0}.**", finBL.FormatDateLong(AccountCalcNew.Schedule.FirstHighCostLoanAdjusted.Date)) & "}}"
            End If
        End Select

        ' Warnings
        .TextAfter = Warnings
      End With

      ' Add Summary Tables
      SummaryTables.Add("Main", SummaryTableMain)
    End If

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Payment Arrangement Schedule (Version 1.01, Last updated 10/07/2018).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="accountPayArrangementAdd ">
  '''  The Account Payment Arrangement.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Payment Arrangement wizard.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Schedule of Payment. Not returned if requires calculation.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_PaymentArrangement_Schedule(callerScriptInfo As ISScriptExecutionInfo,
                                                                  accountPayArrangementAdd As finAccountPayArrangementAdd,
                                                         Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables


    Dim AccountCalcScheduleItem As finAccountCalcScheduleItem
    Dim Ok As Boolean
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    If accountPayArrangementAdd.Calculation.IsCalculationRequired Then
      ' Ignore
    Else
      With SummaryTableMain
        ' Initialise
        .TableClass = iseSummaryTableClass.TabularData
        .Caption = ""
        .AutoStripe = True

        ' Columns
        With .Columns
          .AddBoolean(" ") ' Icon
          .AddDate("Date")
          .AddText("Reference").NoBreakChars = 10
          .AddText("Notes")
          .AddCurrency("Value")
        End With

        For Each AccountCalcScheduleItem In accountPayArrangementAdd.Calculation.Schedule
          If AccountCalcScheduleItem.IsExisting Then
            Ok = False
          Else
            Select Case AccountCalcScheduleItem.ScheduleType
              Case isefinAccountCalcScheduleType.Payment, isefinAccountCalcScheduleType.PaymentAdditional, isefinAccountCalcScheduleType.PaymentOverridden, isefinAccountCalcScheduleType.PaymentPromise, isefinAccountCalcScheduleType.PaymentBalloon, isefinAccountCalcScheduleType.PaymentMinimum
                If AccountCalcScheduleItem.ScheduleSubType = isefinAccountCalcScheduleSubType.PaymentGrace Then
                  Ok = False
                ElseIf AccountCalcScheduleItem.Value < 0 OrElse AccountCalcScheduleItem.TransactionValue < 0 Then
                  Ok = True
                Else
                  Ok = False
                End If
              Case Else
                Ok = False
            End Select
          End If

          If Ok Then
            With .Rows.Add()
              Select Case AccountCalcScheduleItem.ScheduleType
                Case isefinAccountCalcScheduleType.PaymentAdditional, isefinAccountCalcScheduleType.PaymentPromise, isefinAccountCalcScheduleType.PaymentOverridden
                  .RowClass = iseSummaryTableRowClass.Footer
              End Select

              With .Cells
                Select Case AccountCalcScheduleItem.ScheduleType
                  Case isefinAccountCalcScheduleType.PaymentAdditional
                    .AddText("{{icon|Payment_Additional}}")
                  Case isefinAccountCalcScheduleType.PaymentPromise
                    .AddText("{{icon|Payment_Promise}}")
                  Case isefinAccountCalcScheduleType.PaymentOverridden
                    .AddText("{{icon|Payment_Overridden}}")
                  Case Else
                    .AddText("")
                End Select
                .AddDate(AccountCalcScheduleItem.Date)
                .AddText(AccountCalcScheduleItem.Reference)
                If AccountCalcScheduleItem.ScheduleType = isefinAccountCalcScheduleType.PaymentMinimum Then
                  .AddWiki("!!Estimated payment!!")
                Else
                  .AddText(AccountCalcScheduleItem.Notes)
                End If
                Select Case AccountCalcScheduleItem.ScheduleSubType
                  Case isefinAccountCalcScheduleSubType.None, isefinAccountCalcScheduleSubType.PaymentAlternateSchedule, isefinAccountCalcScheduleSubType.PaymentStandardTransaction
                    .AddCurrency(-AccountCalcScheduleItem.Value)
                  Case Else
                    .AddCurrency(-AccountCalcScheduleItem.TransactionValue)
                End Select
              End With
            End With
          End If
        Next

        ' Warnings
        .TextAfter = Warnings
      End With

      ' Add Summary Tables
      SummaryTables.Add("Main", SummaryTableMain)
    End If

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Disbursement Summary.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="accountDisbursement">
  '''  The Account Disbursement to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Accounts form, Disbursements page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''    <item><code>OriginalCalculation</code><description>Original Calculation details.</description></item>
  '''    <item><code>Payee</code><description>Payee details.</description></item>
  '''    <item><code>Payment</code><description>Payment details.</description></item>
  '''    <item><code>Notes</code><description>Notes.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function AccountDisbursement_Summary(callerScriptInfo As ISScriptExecutionInfo,
                                                          accountDisbursement As finAccountDisbursement,
                                                 Optional includeActions As Boolean = True,
                                                 Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' AccountDisbursement_Summary
    '
    ' Version 1.08, Last updated 03/09/2021
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.06  15/07/2021  ISS                  
    '    1.07  27/08/2021  ISS      J027295   Enhance Payment information esp for Bank Interface
    '    1.08  03/09/2021  ISS      J027303   Fix description in Comments
    ' #################################################################


    Dim Account As finAccount
    Dim BankTransactionView As finBankTransactionView
    Dim DateAsAt As Date
    Dim DisbursementDateAsAt As Date
    Dim ShowWarnings As Boolean
    Dim SummaryTableBankingDetails As ISSummaryTable
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTableNotes As ISSummaryTable
    Dim SummaryTableOriginalCalculation As ISSummaryTable
    Dim SummaryTablePayee As ISSummaryTable
    Dim SummaryTablePayment As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim SummaryTablesBankingDetails As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTableNotes = finBL.CreateSummaryTable()
    SummaryTableOriginalCalculation = finBL.CreateSummaryTable()
    SummaryTablePayee = finBL.CreateSummaryTable()
    SummaryTablePayment = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Date As At
    DateAsAt = finBL.TimeZoneFunctions.GetCurrentDatabaseDate()

    ' Main
    If accountDisbursement IsNot Nothing Then
      With SummaryTableMain
        ' Initialise
        .TableClass = iseSummaryTableClass.Information
        .Caption = ""

        ' Columns
        .Columns.AddText(16).NoBreakChars = 16
        .Columns.AddText()

        ' Clear Warnings
        Warnings = ""

        With .Rows
          ' General
          .AddCaptionText("Type:", accountDisbursement.TypeText, iseSummaryTableCellClass.Highlight1)
          Select Case accountDisbursement.Status
            Case isefinDisbursementStatus.Cancelled, isefinDisbursementStatus.Reversed
              If accountDisbursement.CancelledDate = Nothing Then
                .AddCaptionText("Status:", accountDisbursement.StatusText, iseSummaryTableCellClass.WarningBold)
              Else
                .AddCaptionWiki("Status:", String.Format("**!!{0}!!** --by {1}--", accountDisbursement.StatusText, finBL.Utilities.GetUserAndDateWikiText("", accountDisbursement.CancelledUserPk, accountDisbursement.CancelledDate)))
              End If
            Case Else
              .AddCaptionText("Status:", accountDisbursement.StatusText)
          End Select
          If accountDisbursement.ElementPk = 0 Then
            .AddCaptionText("Element:", "Not specified", iseSummaryTableCellClass.WarningBold)
          Else
            .AddCaptionCodeDescription("Element:", accountDisbursement.ElementId, accountDisbursement.ElementDescription)
          End If
          .AddCaptionDate("Date:", accountDisbursement.Date)
          If accountDisbursement.DateDue <> Nothing Then
            If accountDisbursement.DateDue < DateAsAt Then
              Select Case accountDisbursement.Status
                Case isefinDisbursementStatus.Hold, isefinDisbursementStatus.Pending
                  .AddCaptionDate("Date Due:", accountDisbursement.DateDue, , iseSummaryTableCellClass.WarningBold)
                Case Else
                  .AddCaptionDate("Date Due:", accountDisbursement.DateDue)
              End Select
            Else
              .AddCaptionDate("Date Due:", accountDisbursement.DateDue)
            End If
          End If
          If Len(accountDisbursement.Reference) <> 0 Then .AddCaptionText("Reference:", accountDisbursement.Reference)
          Select Case accountDisbursement.Type
            Case isefinDisbursementType.Recovery, isefinDisbursementType.CommissionRecovery
              .AddCaptionWiki("Value:", String.Format("**!!{0} {1}!!**", finBL.FormatCurrency(-accountDisbursement.Value, True), finBL.HtmlEncode(accountDisbursement.TypeText)))
            Case Else
              .AddCaptionCurrency("Value:", accountDisbursement.Value, True)
          End Select
          If Len(accountDisbursement.Classification) <> 0 Then .AddCaptionText("Classification:", accountDisbursement.Classification)
          If Len(accountDisbursement.Key) <> 0 Then .AddCaptionText("Key:", accountDisbursement.Key)
        End With

        ' Warnings
        .TextAfter = Warnings
      End With
    End If

    ' Original Calculation
    If accountDisbursement IsNot Nothing AndAlso accountDisbursement.CalculationBasis <> isefinDisbursementCalcBasis.None Then
      With SummaryTableOriginalCalculation
        ' Initialise
        .TableClass = iseSummaryTableClass.Information
        .Caption = "Original Calculation"

        ' Columns
        .Columns.AddText(16).NoBreakChars = 16
        .Columns.AddText()

        ' Clear Warnings
        Warnings = ""

        With .Rows
          If accountDisbursement.CalculationElementPk <> 0 Then
            .AddCaptionCodeDescription("Element:", accountDisbursement.CalculationElementId, accountDisbursement.CalculationElementDescription)
          End If
          .AddCaptionText("Reference:", accountDisbursement.CalculationBasisText)
          .AddCaptionCurrency("Base Value:", accountDisbursement.CalculationBaseValue, True)
          Select Case accountDisbursement.CalculationBasis
            Case isefinDisbursementCalcBasis.Percentage, isefinDisbursementCalcBasis.PresentValue, isefinDisbursementCalcBasis.PresentValueAF
              .AddCaptionPercentage("Rate:", accountDisbursement.CalculationRate / 100, 4, True)
            Case isefinDisbursementCalcBasis.Difference, isefinDisbursementCalcBasis.SetValue
              .AddCaptionCurrency("Rate:", accountDisbursement.CalculationRate, True)
          End Select
          If accountDisbursement.CalculationValue = accountDisbursement.Value Then
            .AddCaptionCurrency("Value:", accountDisbursement.CalculationValue, True)
          Else
            .AddCaptionCurrency("Value:", accountDisbursement.CalculationValue, True, , iseSummaryTableCellClass.WarningBold)
          End If
        End With

        ' Warnings
        .TextAfter = Warnings
      End With
    End If

    ' Payer/ Payee
    If accountDisbursement IsNot Nothing Then
      With SummaryTablePayee
        ' Initialise
        .TableClass = iseSummaryTableClass.Information
        If accountDisbursement.Value < 0 Then
          .Caption = "Payer (Incoming payment)"
        Else
          .Caption = "Payee"
        End If

        ' Columns
        .Columns.AddText(16).NoBreakChars = 16
        .Columns.AddText()

        ' Clear Warnings
        Warnings = ""

        With .Rows
          .AddCaptionText("Type:", accountDisbursement.PayeeTypeText)

          Select Case accountDisbursement.PayeeType
            Case isefinDisbursementPayeeType.Account
              .AddCaptionText("Payee Name:", accountDisbursement.PayeeName)

              If accountDisbursement.BankingDetails Is Nothing Then
                .AddCaptionText("Pay Method:", "")
              Else
                ' Find Information
                Select Case accountDisbursement.Status
                  Case isefinDisbursementStatus.Cancelled, isefinDisbursementStatus.Complete, isefinDisbursementStatus.Historic, isefinDisbursementStatus.Reversed
                    Account = Nothing
                    DisbursementDateAsAt = Nothing
                    ShowWarnings = False
                  Case Else
                    Account = accountDisbursement.Account
                    If accountDisbursement.DateDue <> Nothing Then
                      If accountDisbursement.DateDue > DateAsAt Then
                        DisbursementDateAsAt = accountDisbursement.DateDue
                      Else
                        DisbursementDateAsAt = Nothing
                      End If
                    Else
                      If accountDisbursement.Date > DateAsAt Then
                        DisbursementDateAsAt = accountDisbursement.Date
                      Else
                        DisbursementDateAsAt = Nothing
                      End If
                    End If
                    ShowWarnings = True
                End Select

                ' Get Banking Details Summary Table
                SummaryTablesBankingDetails = finBL.SummaryPageStandardBlocks.BankingDetails_Summary2(callerScriptInfo, accountDisbursement.BankingDetails, Account, DisbursementDateAsAt, ShowWarnings, Nothing)

                ' Add Cheque Printed detail
                If SummaryTablesBankingDetails.Exists("Main") Then
                  Select Case accountDisbursement.Status
                    Case isefinDisbursementStatus.Hold, isefinDisbursementStatus.Pending
                      If accountDisbursement.BankingDetails.PaymentMethod IsNot Nothing AndAlso accountDisbursement.BankingDetails.PaymentMethod.IsOutwardsCheque Then
                        Select Case accountDisbursement.BankingDetails.PrintCheque
                          Case isefinPrintCheque.AlreadyPrinted, isefinPrintCheque.PrintLater, isefinPrintCheque.PrintNow
                            With SummaryTablesBankingDetails.Item("Main")
                              .Rows.AddCaptionText("Printed:", accountDisbursement.BankingDetails.PrintChequeText)
                            End With
                        End Select
                      End If
                  End Select
                End If

                ' Get Banking Details Summary Tables
                SummaryTableBankingDetails = SummaryTablesBankingDetails.Item("Main")

                ' Add to Summary Table
                .AppendFromSummaryTable(SummaryTableBankingDetails)

                ' Add Warnings
                Warnings &= SummaryTableBankingDetails.TextAfter
              End If

            Case Else
              If accountDisbursement.ExternalPartyPk = 0 Then
                .AddCaptionText(accountDisbursement.PayeeTypeText & ":", "")
              Else
                .AddCaptionCodeDescriptionWithFormShow(accountDisbursement.PayeeTypeText & ":", accountDisbursement.ExternalPartyId, finBL.ExternalParties, "ExternalParties")
              End If

              ' Account used to Disburse
              Account = accountDisbursement.GetExternalPartyAccount
              If Account IsNot Nothing Then
                .AddCaptionCodeDescriptionWithFormShow("Account:", Account.AccountId, Account.Name, "Accounts")
              End If
          End Select
        End With

        ' Warnings
        .TextAfter = Warnings
      End With
    End If

    ' Payment
    If accountDisbursement IsNot Nothing AndAlso accountDisbursement.BankTransactionPk <> 0 Then
      With SummaryTablePayment
        ' Initialise
        .TableClass = iseSummaryTableClass.Information
        .Caption = "Payment"

        ' Columns
        .Columns.AddText(16).NoBreakChars = 16
        .Columns.AddText()

        ' Clear Warnings
        Warnings = ""

        With .Rows
          BankTransactionView = accountDisbursement.GetBankTransactionView

          If accountDisbursement.PayeeType <> isefinDisbursementPayeeType.Account Then
            .AddCaptionCodeDescription("Pay Method:", BankTransactionView.BankingDetails.PaymentMethodId, BankTransactionView.BankingDetails.PaymentMethodDescription)
          End If
          .AddCaptionDate("Date:", BankTransactionView.Date)

          Select Case BankTransactionView.BankInterfaceStatus
            Case isefinBankTransactionBankInterfaceStatus.NotApplicable
              If BankTransactionView.BankingDetails.PaymentMethod.IsDirectCredit OrElse BankTransactionView.BankingDetails.PaymentMethod.IsDirectDebit Then
                If BankTransactionView.BankExportView Is Nothing OrElse BankTransactionView.BankExportView.Date = Nothing Then
                  .AddCaptionText("Exported:", "Not yet exported")
                Else
                  .AddCaptionDate("Exported:", BankTransactionView.BankExportView.Date)
                End If
              ElseIf BankTransactionView.BankingDetails.PaymentMethod.IsOutwardsCheque Then
                Select Case BankTransactionView.PrintedStatus
                  Case isefinBankTransactionPrintedStatus.Printed
                    .AddCaptionText(String.Format("{0} No:", finBL.CurrentCountry.Terminology(isefinCountryTerminology.Cheque)), BankTransactionView.TransactionReference)
                End Select
                .AddCaptionText("Printed:", BankTransactionView.PrintedStatusText)
              End If

            Case Else
              ' Bank Interface
              .AddCaptionText("Service:", BankTransactionView.BankingDetails.PaymentTypeCategoryText)
              With .AddCaptionText("Status:", BankTransactionView.BankInterfaceStatusText)
                Select Case BankTransactionView.BankInterfaceStatus
                  Case isefinBankTransactionBankInterfaceStatus.Aborted
                    .BackgroundColour = "gold"
                  Case isefinBankTransactionBankInterfaceStatus.Cancelled
                    .BackgroundColour = "plum"
                  Case isefinBankTransactionBankInterfaceStatus.Failed, isefinBankTransactionBankInterfaceStatus.SendFailed
                    .BackgroundColour = "pink"
                  Case isefinBankTransactionBankInterfaceStatus.Pending, isefinBankTransactionBankInterfaceStatus.Queued
                    .BackgroundColour = "orange"
                  Case isefinBankTransactionBankInterfaceStatus.Success
                    .BackgroundColour = "lightgreen"
                End Select
              End With
              If BankTransactionView.BankInterfaceSettlementDate <> Nothing Then
                .AddCaptionDate("Settlement Date:", BankTransactionView.BankInterfaceSettlementDate)
                .AddCaptionText("Settlement Reference:", BankTransactionView.BankInterfaceSettlementReference)
              End If
          End Select
        End With

        ' Warnings
        If BankTransactionView.ReversePk <> 0 Then
          If BankTransactionView.ReversePk > BankTransactionView.BankTransactionPk Then
            Warnings &= "{{warning|" & String.Format("Reversed by Bank Transaction Id {0}.", BankTransactionView.ReversePk) & "}}"
          Else
            Warnings &= "{{warning|" & String.Format("Reversed Bank Transaction Id {0}.", BankTransactionView.ReversePk) & "}}"
          End If
        End If

        ' Actions
        If includeActions Then
          With .Actions
            .AddFormAction("ShowBankTransaction", "View", True, String.Format("BankTransactionPk={0}", accountDisbursement.BankTransactionPk))
          End With
        End If

        ' Warnings
        .TextAfter = Warnings
      End With
    End If

    ' Notes
    If accountDisbursement IsNot Nothing AndAlso Len(accountDisbursement.Notes) <> 0 Then
      With SummaryTableNotes
        ' Initialise
        .TableClass = iseSummaryTableClass.Information
        .Caption = "Notes"

        ' Columns
        .Columns.AddText(16).NoBreakChars = 16
        .Columns.AddText()

        With .Rows
          .AddText(accountDisbursement.Notes)
        End With
      End With
    End If

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)
    If SummaryTableOriginalCalculation.HasData Then SummaryTables.Add("OriginalCalculation", SummaryTableOriginalCalculation)
    If SummaryTablePayee.HasData Then SummaryTables.Add("Payee", SummaryTablePayee)
    If SummaryTablePayment.HasData Then SummaryTables.Add("Payment", SummaryTablePayment)
    If SummaryTableNotes.HasData Then SummaryTables.Add("Notes", SummaryTableNotes)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Disbursements Payout Reconciliation (Version 1.01, Last updated 23/11/2017).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="account">
  '''  The Account to print a Disbursement Payout Reconciliation for.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Accounts form, Disbursements page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_Disbursements_PayoutReconciliation(callerScriptInfo As ISScriptExecutionInfo,
                                                                         account As finAccount,
                                                                Optional includeActions As Boolean = True,
                                                                Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim PayoutValueComplete As Decimal
    Dim PayoutValueHoldPending As Decimal
    Dim PayoutValueTotal As Decimal
    Dim PayoutValueTransactions As Decimal
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Values
    With account.Disbursements
      PayoutValueComplete = .TotalPayout(False, False, True, True)
      PayoutValueHoldPending = .TotalPayout(True, True, False, False)
      PayoutValueTotal = PayoutValueComplete + PayoutValueHoldPending
      PayoutValueTransactions = account.Transactions.TotalDisbursementPayout
    End With

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""

      ' Columns
      .Columns.AddText(20).NoBreakChars = 20
      .Columns.AddCurrency()

      ' Clear Warnings
      Warnings = ""

      With .Rows
        .AddCaptionCurrency("To be disbursed:", PayoutValueTransactions, True, , iseSummaryTableCellClass.Highlight1)
        .AddCaptionCurrency("Already paid:", PayoutValueComplete)
        .AddCaptionCurrency("Held/ Pending:", PayoutValueHoldPending)
        If PayoutValueTotal = PayoutValueTransactions Then
          .AddCaptionCurrency("Variance:", PayoutValueTotal - PayoutValueTransactions, True, , iseSummaryTableCellClass.Highlight1)
        ElseIf PayoutValueTotal > PayoutValueTransactions Then
          With .AddCaptionCurrency("Overpaid:", PayoutValueTotal - PayoutValueTransactions, True, iseSummaryTableRowClass.NormalBold, iseSummaryTableCellClass.Highlight1)
            .ForegroundColour = "red"
          End With
        Else
          With .AddCaptionCurrency("Underpaid:", PayoutValueTotal - PayoutValueTransactions, True, iseSummaryTableRowClass.NormalBold, iseSummaryTableCellClass.Highlight1)
            .ForegroundColour = "red"
          End With
        End If
      End With

      ' Payout Closed
      If account.DisbursementPayoutsClosed Then
        If PayoutValueTotal = PayoutValueTransactions Then
          Warnings &= "{{info|Disbursement Payouts are Closed.}}"
        ElseIf PayoutValueTotal > PayoutValueTransactions Then
          Warnings &= "{{warning|Disbursement Payouts are Closed - but Disbursements are overpaid.}}"
        Else
          Warnings &= "{{warning|Disbursement Payouts are Closed - but Disbursements are underpaid.}}"
        End If

        If includeActions Then
          With SummaryTableMain.Actions
            Select Case account.Status
              Case isefinAccountStatus.Open, isefinAccountStatus.ClosedPending, isefinAccountStatus.Closed
                .AddFormAction("DisbursementPayoutsReopen", "Reopen Payouts", Not finBL.Database.IsReadOnly AndAlso finBL.CurrentUser.Permissions.Allow("Account.Disbursements.PayoutsReopen"))
            End Select
          End With
        End If
      Else
        If includeActions Then
          With SummaryTableMain.Actions
            Select Case account.Status
              Case isefinAccountStatus.Open, isefinAccountStatus.ClosedPending, isefinAccountStatus.Closed
                .AddFormAction("DisbursementPayoutsClose", "Close Payouts", Not finBL.Database.IsReadOnly AndAlso finBL.CurrentUser.Permissions.Allow("Account.Disbursements.PayoutsClose"))
            End Select
          End With
        End If
      End If

      ' Warnings
      .TextAfter = Warnings
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Disbursements Totals (Version 1.01, Last updated 20/10/2015).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="account">
  '''  The Account to print Disbursement Totals for.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Accounts form, Disbursements page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Payout</code><description>Payout totals.</description></item>
  '''    <item><code>Commission</code><description>Commission totals.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function Account_Disbursements_Totals(callerScriptInfo As ISScriptExecutionInfo,
                                                           account As finAccount,
                                                  Optional includeActions As Boolean = True,
                                                  Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim AccountDisbursement As finAccountDisbursement
    Dim SummaryTablePayout As ISSummaryTable
    Dim SummaryTableCommission As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim TotalCommissionPaid As Decimal
    Dim TotalCommissionToPay As Decimal
    Dim TotalCommissionRecoveryPaid As Decimal
    Dim TotalCommissionRecoveryToPay As Decimal
    Dim TotalCostPaid As Decimal
    Dim TotalCostToPay As Decimal
    Dim TotalPayoutPaid As Decimal
    Dim TotalPayoutToPay As Decimal
    Dim TotalRecoveryPaid As Decimal
    Dim TotalRecoveryToPay As Decimal
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableCommission = finBL.CreateSummaryTable()
    SummaryTablePayout = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Calculate Totals
    For Each AccountDisbursement In account.Disbursements
      Select Case AccountDisbursement.Status
        Case isefinDisbursementStatus.Hold, isefinDisbursementStatus.Closing, isefinDisbursementStatus.Pending
          Select Case AccountDisbursement.Type
            Case isefinDisbursementType.Commission
              TotalCommissionToPay += AccountDisbursement.Value
            Case isefinDisbursementType.CommissionRecovery
              TotalCommissionRecoveryToPay += AccountDisbursement.Value
            Case isefinDisbursementType.Cost
              TotalCostToPay += AccountDisbursement.Value
            Case isefinDisbursementType.Payout
              TotalPayoutToPay += AccountDisbursement.Value
            Case isefinDisbursementType.Recovery
              TotalRecoveryToPay += AccountDisbursement.Value
          End Select
        Case isefinDisbursementStatus.Complete, isefinDisbursementStatus.Historic
          Select Case AccountDisbursement.Type
            Case isefinDisbursementType.Commission
              TotalCommissionPaid += AccountDisbursement.Value
            Case isefinDisbursementType.CommissionRecovery
              TotalCommissionRecoveryPaid += AccountDisbursement.Value
            Case isefinDisbursementType.Cost
              TotalCostPaid += AccountDisbursement.Value
            Case isefinDisbursementType.Payout
              TotalPayoutPaid += AccountDisbursement.Value
            Case isefinDisbursementType.Recovery
              TotalRecoveryPaid += AccountDisbursement.Value
          End Select
      End Select
    Next

    ' Payout Totals
    With SummaryTablePayout
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .Caption = "Disbursement Totals"

      ' Clear Warnings
      Warnings = ""

      ' Columns
      With .Columns
        .AddText(" ", 20).NoBreakChars = 20
        .AddCurrency("Paid", 20)
        .AddCurrency("To Pay", 20)
        .AddCurrency("Total", 20)
      End With

      With .Rows
        ' Payouts
        If account.SupportsDisbursementTypePayout Then
          With .Add(iseSummaryTableRowClass.Normal).Cells
            .AddCaption("Payouts")
            .AddCurrency(TotalPayoutPaid)
            .AddCurrency(TotalPayoutToPay)
            .AddCurrency(TotalPayoutPaid + TotalPayoutToPay)
          End With
        End If

        ' Costs
        With .Add(iseSummaryTableRowClass.Normal).Cells
          .AddCaption("Costs")
          .AddCurrency(TotalCostPaid)
          .AddCurrency(TotalCostToPay)
          .AddCurrency(TotalCostPaid + TotalCostToPay)
        End With

        ' Recoveries
        With .Add(iseSummaryTableRowClass.Normal).Cells
          .AddCaption("Recoveries")
          .AddCurrency(TotalRecoveryPaid)
          .AddCurrency(TotalRecoveryToPay)
          .AddCurrency(TotalRecoveryPaid + TotalRecoveryToPay)
        End With

        ' Total
        With .Add(iseSummaryTableRowClass.FooterBold).Cells
          .AddCaption("Total")
          .AddCurrency(TotalPayoutPaid + TotalCostPaid + TotalRecoveryPaid, True)
          With .AddCurrency(TotalPayoutToPay + TotalCostToPay + TotalRecoveryToPay, True)
            If TotalPayoutToPay <> 0 OrElse TotalCostToPay <> 0 OrElse TotalRecoveryToPay <> 0 Then
              .CellClass = iseSummaryTableCellClass.WarningBold
            End If
          End With
          .AddCurrency(TotalPayoutPaid + TotalCostPaid + TotalRecoveryPaid + TotalPayoutToPay + TotalCostToPay + TotalRecoveryToPay, True)
        End With
      End With

      ' Warnings
      .TextAfter = Warnings
    End With

    ' Commission Totals
    If finBL.CurrentUser.Permissions.Allow("Account.Commissions.View") Then
      With SummaryTableCommission
        ' Initialise
        .TableClass = iseSummaryTableClass.TabularData
        .Caption = "Commission Totals"

        ' Clear Warnings
        Warnings = ""

        ' Columns
        With .Columns
          .AddText(" ", 20).NoBreakChars = 20
          .AddCurrency("Paid", 20)
          .AddCurrency("To Pay", 20)
          .AddCurrency("Total", 20)
        End With

        With .Rows
          ' Commissions
          With .Add(iseSummaryTableRowClass.Normal).Cells
            .AddCaption("Commissions")
            .AddCurrency(TotalCommissionPaid)
            .AddCurrency(TotalCommissionToPay)
            .AddCurrency(TotalCommissionPaid + TotalCommissionToPay)
          End With

          ' Recoveries
          With .Add(iseSummaryTableRowClass.Normal).Cells
            .AddCaption("Recoveries")
            .AddCurrency(TotalCommissionRecoveryPaid)
            .AddCurrency(TotalCommissionRecoveryToPay)
            .AddCurrency(TotalCommissionRecoveryPaid + TotalCommissionRecoveryToPay)
          End With

          ' Total
          With .Add(iseSummaryTableRowClass.FooterBold).Cells
            .AddCaption("Total")
            .AddCurrency(TotalCommissionPaid + TotalCommissionRecoveryPaid, True)
            With .AddCurrency(TotalCommissionToPay + TotalCommissionRecoveryToPay, True)
              If TotalCommissionToPay <> 0 OrElse TotalCommissionRecoveryToPay <> 0 Then
                .CellClass = iseSummaryTableCellClass.WarningBold
              End If
            End With
            .AddCurrency(TotalCommissionToPay + TotalCommissionRecoveryToPay + TotalCommissionPaid + TotalCommissionRecoveryPaid, True)
          End With
        End With

        ' Warnings
        .TextAfter = Warnings
      End With
    End If

    ' Add Summary Tables
    SummaryTables.Add("Payout", SummaryTablePayout)
    If SummaryTableCommission.HasData Then SummaryTables.Add("Commission", SummaryTableCommission)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Disbursement Payee Summary (Version 1.0, Last updated 18/08/2015).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="accountDisbursementPayee">
  '''  The Account Disbursement Payee to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Accounts form, Disbursement Payees page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function AccountDisbursementPayee_Summary(callerScriptInfo As ISScriptExecutionInfo,
                                                               accountDisbursementPayee As finAccountDisbursementPayee,
                                                      Optional includeActions As Boolean = True,
                                                      Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    If accountDisbursementPayee IsNot Nothing Then
      With SummaryTableMain
        ' Initialise
        .TableClass = iseSummaryTableClass.Information
        .Caption = ""

        ' Columns
        .Columns.AddText(15).NoBreakChars = 15
        .Columns.AddText()

        ' Clear Warnings
        Warnings = ""

        With .Rows
          ' Account
          .AddSectionHeading2("Account")
          With .AddCaptionText("Account:", accountDisbursementPayee.AccountId)
            .Cells(1).HyperlinkSetFormShow("Accounts", accountDisbursementPayee.AccountId)
          End With
          .AddCaptionText("Name:", accountDisbursementPayee.AccountName)

          ' Payee/ Payer
          If accountDisbursementPayee.Value < 0 Then
            .AddSectionHeading2("Payer (Incoming payment)")
          Else
            .AddSectionHeading2("Payee")
          End If
          .AddCaptionText("Type:", accountDisbursementPayee.PayeeTypeText)
          Select Case accountDisbursementPayee.PayeeType
            Case isefinDisbursementPayeeType.Account
            Case Else
              If accountDisbursementPayee.ExternalPartyPk = 0 Then
                .AddCaptionText(accountDisbursementPayee.PayeeTypeText & ":", "")
              Else
                .AddCaptionCodeDescriptionWithFormShow(accountDisbursementPayee.PayeeTypeText & ":", accountDisbursementPayee.ExternalPartyId, finBL.ExternalParties, "ExternalParties")
              End If
          End Select
        End With

        ' Warnings
        .TextAfter = Warnings
      End With
    End If

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Account Disbursement Payee Disbursement Summary (Version 1.02, Last updated 25/10/2017).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="accountDisbursementPayee">
  '''  The Account Disbursement Payee to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Accounts form, Disbursements page.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''    <item><code>OriginalCalculation</code><description>Original Calculation details.</description></item>
  '''    <item><code>Notes</code><description>Notes.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function AccountDisbursementPayee_DisbursementSummary(callerScriptInfo As ISScriptExecutionInfo,
                                                                           accountDisbursementPayee As finAccountDisbursementPayee,
                                                                  Optional includeActions As Boolean = True,
                                                                  Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim DateAsAt As Date
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTableNotes As ISSummaryTable
    Dim SummaryTableOriginalCalculation As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTableNotes = finBL.CreateSummaryTable()
    SummaryTableOriginalCalculation = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Date As At
    DateAsAt = finBL.TimeZoneFunctions.GetCurrentDatabaseDate()

    ' Main
    If accountDisbursementPayee IsNot Nothing Then
      With SummaryTableMain
        ' Initialise
        .TableClass = iseSummaryTableClass.Information
        .Caption = ""

        ' Columns
        .Columns.AddText(15).NoBreakChars = 15
        .Columns.AddText()

        ' Clear Warnings
        Warnings = ""

        With .Rows
          .AddCaptionText("Type:", accountDisbursementPayee.TypeText, iseSummaryTableCellClass.Highlight1)
          Select Case accountDisbursementPayee.Status
            Case isefinDisbursementStatus.Cancelled, isefinDisbursementStatus.Reversed
              If accountDisbursementPayee.CancelledDate = Nothing Then
                .AddCaptionText("Status:", accountDisbursementPayee.StatusText, iseSummaryTableCellClass.WarningBold)
              Else
                .AddCaptionWiki("Status:", String.Format("**!!{0}!!** --by {1}--", accountDisbursementPayee.StatusText, finBL.Utilities.GetUserAndDateWikiText("", accountDisbursementPayee.CancelledUserPk, accountDisbursementPayee.CancelledDate)))
              End If
            Case Else
              .AddCaptionText("Status:", accountDisbursementPayee.StatusText)
          End Select
          If accountDisbursementPayee.ElementPk = 0 Then
            .AddCaptionText("Element:", "Not specified", iseSummaryTableCellClass.WarningBold)
          Else
            .AddCaptionCodeDescription("Element:", accountDisbursementPayee.ElementId, accountDisbursementPayee.ElementDescription)
          End If
          .AddCaptionDate("Date:", accountDisbursementPayee.Date)
          If accountDisbursementPayee.DateDue <> Nothing Then
            If accountDisbursementPayee.DateDue < DateAsAt Then
              Select Case accountDisbursementPayee.Status
                Case isefinDisbursementStatus.Hold, isefinDisbursementStatus.Pending
                  .AddCaptionDate("Date Due:", accountDisbursementPayee.DateDue, , iseSummaryTableCellClass.WarningBold)
                Case Else
                  .AddCaptionDate("Date Due:", accountDisbursementPayee.DateDue)
              End Select
            Else
              .AddCaptionDate("Date Due:", accountDisbursementPayee.DateDue)
            End If
          End If
          If Len(accountDisbursementPayee.Reference) <> 0 Then .AddCaptionText("Reference:", accountDisbursementPayee.Reference)
          Select Case accountDisbursementPayee.Type
            Case isefinDisbursementType.Recovery, isefinDisbursementType.CommissionRecovery
              .AddCaptionWiki("Value:", String.Format("**!!{0} {1}!!**", finBL.FormatCurrency(-accountDisbursementPayee.Value, True), finBL.HtmlEncode(accountDisbursementPayee.TypeText)))
            Case Else
              .AddCaptionCurrency("Value:", accountDisbursementPayee.Value, True)
          End Select
          If Len(accountDisbursementPayee.Classification) <> 0 Then .AddCaptionText("Classification:", accountDisbursementPayee.Classification)
          If Len(accountDisbursementPayee.Key) <> 0 Then .AddCaptionText("Key:", accountDisbursementPayee.Key)
        End With

        ' Warnings
        .TextAfter = Warnings
      End With
    End If

    ' Original Calculation
    If accountDisbursementPayee IsNot Nothing AndAlso accountDisbursementPayee.CalculationBasis <> isefinDisbursementCalcBasis.None Then
      With SummaryTableOriginalCalculation
        ' Initialise
        .TableClass = iseSummaryTableClass.Information
        .Caption = "Original Calculation"

        ' Columns
        .Columns.AddText(15).NoBreakChars = 15
        .Columns.AddText()

        ' Clear Warnings
        Warnings = ""

        With .Rows
          If accountDisbursementPayee.CalculationElementPk <> 0 Then
            .AddCaptionCodeDescription("Element:", accountDisbursementPayee.CalculationElementId, accountDisbursementPayee.CalculationElementDescription)
          End If
          .AddCaptionText("Reference:", accountDisbursementPayee.CalculationBasisText)
          .AddCaptionCurrency("Base Value:", accountDisbursementPayee.CalculationBaseValue)
          Select Case accountDisbursementPayee.CalculationBasis
            Case isefinDisbursementCalcBasis.Percentage, isefinDisbursementCalcBasis.PresentValue, isefinDisbursementCalcBasis.PresentValueAF
              .AddCaptionPercentage("Rate:", accountDisbursementPayee.CalculationRate / 100, 4, True)
            Case isefinDisbursementCalcBasis.Difference, isefinDisbursementCalcBasis.SetValue
              .AddCaptionCurrency("Rate:", accountDisbursementPayee.CalculationRate, True)
          End Select
          If accountDisbursementPayee.CalculationValue = accountDisbursementPayee.Value Then
            .AddCaptionCurrency("Value:", accountDisbursementPayee.CalculationValue, True)
          Else
            .AddCaptionCurrency("Value:", accountDisbursementPayee.CalculationValue, True, , iseSummaryTableCellClass.WarningBold)
          End If
        End With

        ' Warnings
        .TextAfter = Warnings
      End With
    End If

    ' Notes
    If accountDisbursementPayee IsNot Nothing AndAlso Len(accountDisbursementPayee.Notes) <> 0 Then
      With SummaryTableNotes
        ' Initialise
        .TableClass = iseSummaryTableClass.Information
        .Caption = "Notes"

        ' Columns
        .Columns.AddText(15).NoBreakChars = 15
        .Columns.AddText()

        With .Rows
          .AddText(accountDisbursementPayee.Notes)
        End With
      End With
    End If

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)
    If SummaryTableOriginalCalculation.HasData Then SummaryTables.Add("OriginalCalculation", SummaryTableOriginalCalculation)
    If SummaryTableNotes.HasData Then SummaryTables.Add("Notes", SummaryTableNotes)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Approve Disbursements Summary (Version 1.0, Last updated 4/09/2015).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="accountDisbursementsApproveItem">
  '''  The Account Disbursement Approve Item to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used on the Approve Disbursements wizard.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function AccountDisbursementsApprove_Summary(callerScriptInfo As ISScriptExecutionInfo,
                                                                  accountDisbursementsApproveItem As finAccountDisbursementsApproveItem,
                                                         Optional includeActions As Boolean = True,
                                                         Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""

      ' Columns
      .Columns.AddText(16).NoBreakChars = 16
      .Columns.AddText()

      ' Clear Warnings
      Warnings = ""

      With .Rows
        ' General
        With .AddCaptionText("Account:", accountDisbursementsApproveItem.AccountId)
          .Cells(1).HyperlinkSetFormShow("Accounts", accountDisbursementsApproveItem.AccountId)
        End With
        .AddCaptionText("Name:", accountDisbursementsApproveItem.AccountName)

        ' Add Warnings
        If accountDisbursementsApproveItem.Processed Then
          Warnings &= "{{info|Already processed.}}"
        ElseIf Len(accountDisbursementsApproveItem.InvalidMessageResolved) <> 0 Then
          Warnings &= "{{warning|" & accountDisbursementsApproveItem.InvalidMessageResolved & "}}"
        End If
      End With

      ' Warnings
      .TextAfter = Warnings
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Approve Disbursements Disbursement Summary (Version 1.03, Last updated 5/07/2021).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="accountDisbursementsApproveItem">
  '''  The Account Disbursement Approve Item to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used on the Approve Disbursements wizard.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''    <item><code>OriginalCalculation</code><description>Original Calculation details.</description></item>
  '''    <item><code>Payee</code><description>Payee details.</description></item>
  '''    <item><code>Notes</code><description>Notes.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function AccountDisbursementsApprove_DisbursementSummary(callerScriptInfo As ISScriptExecutionInfo,
                                                                              accountDisbursementsApproveItem As finAccountDisbursementsApproveItem,
                                                                     Optional includeActions As Boolean = True,
                                                                     Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    Dim Account As finAccount
    Dim BankingDetails As finBankingDetails
    Dim DateAsAt As Date
    Dim DisbursementDateAsAt As Date
    Dim ShowWarnings As Boolean
    Dim SummaryTableBankingDetails As ISSummaryTable
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTableNotes As ISSummaryTable
    Dim SummaryTableOriginalCalculation As ISSummaryTable
    Dim SummaryTablePayee As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim SummaryTablesBankingDetails As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTableNotes = finBL.CreateSummaryTable()
    SummaryTableOriginalCalculation = finBL.CreateSummaryTable()
    SummaryTablePayee = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Get Date As At
    DateAsAt = finBL.TimeZoneFunctions.GetCurrentDatabaseDate()

    ' Main
    If accountDisbursementsApproveItem IsNot Nothing Then
      With SummaryTableMain
        ' Initialise
        .TableClass = iseSummaryTableClass.Information
        .Caption = ""

        ' Columns
        .Columns.AddText(16).NoBreakChars = 16
        .Columns.AddText()

        ' Clear Warnings
        Warnings = ""

        With .Rows
          ' General
          .AddCaptionText("Type:", accountDisbursementsApproveItem.TypeText, iseSummaryTableCellClass.Highlight1)
          .AddCaptionText("Status:", accountDisbursementsApproveItem.StatusText)
          If accountDisbursementsApproveItem.ElementPk = 0 Then
            .AddCaptionText("Element:", "Not specified", iseSummaryTableCellClass.WarningBold)
          Else
            .AddCaptionCodeDescription("Element:", accountDisbursementsApproveItem.ElementId, accountDisbursementsApproveItem.ElementDescription)
          End If
          .AddCaptionDate("Date:", accountDisbursementsApproveItem.Date)
          If accountDisbursementsApproveItem.DateDue <> Nothing Then
            If accountDisbursementsApproveItem.DateDue < DateAsAt Then
              Select Case accountDisbursementsApproveItem.Status
                Case isefinDisbursementStatus.Hold, isefinDisbursementStatus.Pending
                  .AddCaptionDate("Date Due:", accountDisbursementsApproveItem.DateDue, , iseSummaryTableCellClass.WarningBold)
                Case Else
                  .AddCaptionDate("Date Due:", accountDisbursementsApproveItem.DateDue)
              End Select
            Else
              .AddCaptionDate("Date Due:", accountDisbursementsApproveItem.DateDue)
            End If
          End If
          If Len(accountDisbursementsApproveItem.Reference) <> 0 Then .AddCaptionText("Reference:", accountDisbursementsApproveItem.Reference)
          Select Case accountDisbursementsApproveItem.Type
            Case isefinDisbursementType.Recovery, isefinDisbursementType.CommissionRecovery
              .AddCaptionWiki("Value:", String.Format("**!!{0} {1}!!**", finBL.FormatCurrency(-accountDisbursementsApproveItem.Value, True), finBL.HtmlEncode(accountDisbursementsApproveItem.TypeText)))
            Case Else
              .AddCaptionCurrency("Value:", accountDisbursementsApproveItem.Value, True)
          End Select
          If Len(accountDisbursementsApproveItem.Classification) <> 0 Then .AddCaptionText("Classification:", accountDisbursementsApproveItem.Classification)
        End With

        ' Warnings
        .TextAfter = Warnings
      End With
    End If

    ' Original Calculation
    If accountDisbursementsApproveItem IsNot Nothing AndAlso accountDisbursementsApproveItem.CalculationBasis <> isefinDisbursementCalcBasis.None Then
      With SummaryTableOriginalCalculation
        ' Initialise
        .TableClass = iseSummaryTableClass.Information
        .Caption = "Original Calculation"

        ' Columns
        .Columns.AddText(16).NoBreakChars = 16
        .Columns.AddText()

        ' Clear Warnings
        Warnings = ""

        With .Rows
          If accountDisbursementsApproveItem.CalculationElementPk <> 0 Then
            .AddCaptionCodeDescription("Element:", accountDisbursementsApproveItem.CalculationElementId, accountDisbursementsApproveItem.CalculationElementDescription)
          End If
          .AddCaptionText("Reference:", accountDisbursementsApproveItem.CalculationBasisText)
          .AddCaptionCurrency("Base Value:", accountDisbursementsApproveItem.CalculationBaseValue, True)
          Select Case accountDisbursementsApproveItem.CalculationBasis
            Case isefinDisbursementCalcBasis.Percentage, isefinDisbursementCalcBasis.PresentValue, isefinDisbursementCalcBasis.PresentValueAF
              .AddCaptionPercentage("Rate:", accountDisbursementsApproveItem.CalculationRate / 100, 4, True)
            Case isefinDisbursementCalcBasis.Difference, isefinDisbursementCalcBasis.SetValue
              .AddCaptionCurrency("Rate:", accountDisbursementsApproveItem.CalculationRate, True)
          End Select
          If accountDisbursementsApproveItem.CalculationValue = accountDisbursementsApproveItem.Value Then
            .AddCaptionCurrency("Value:", accountDisbursementsApproveItem.CalculationValue, True)
          Else
            .AddCaptionCurrency("Value:", accountDisbursementsApproveItem.CalculationValue, True, , iseSummaryTableCellClass.WarningBold)
          End If
        End With

        ' Warnings
        .TextAfter = Warnings
      End With
    End If

    ' Payer/ Payee
    If accountDisbursementsApproveItem IsNot Nothing Then
      With SummaryTablePayee
        ' Initialise
        .TableClass = iseSummaryTableClass.Information
        If accountDisbursementsApproveItem.Value < 0 Then
          .Caption = "Payer (Incoming payment)"
        Else
          .Caption = "Payee"
        End If

        ' Columns
        .Columns.AddText(16).NoBreakChars = 16
        .Columns.AddText()

        ' Clear Warnings
        Warnings = ""

        With .Rows
          .AddCaptionText("Type:", accountDisbursementsApproveItem.PayeeTypeText)

          Select Case accountDisbursementsApproveItem.PayeeType
            Case isefinDisbursementPayeeType.Account
              ' Get Bank Details
              BankingDetails = accountDisbursementsApproveItem.BankingDetails.CloneForDisplay()

              .AddCaptionText("Payee Name:", accountDisbursementsApproveItem.PayeeName)

              If BankingDetails.PaymentMethod Is Nothing Then
                .AddCaptionText("Pay Method:", "")
              Else
                ' Find Information
                Select Case accountDisbursementsApproveItem.Status
                  Case isefinDisbursementStatus.Cancelled, isefinDisbursementStatus.Complete, isefinDisbursementStatus.Historic, isefinDisbursementStatus.Reversed
                    Account = Nothing
                    DisbursementDateAsAt = Nothing
                    ShowWarnings = False
                  Case Else
                    Account = accountDisbursementsApproveItem.Account
                    If accountDisbursementsApproveItem.DateDue <> Nothing Then
                      If accountDisbursementsApproveItem.DateDue > DateAsAt Then
                        DisbursementDateAsAt = accountDisbursementsApproveItem.DateDue
                      Else
                        DisbursementDateAsAt = Nothing
                      End If
                    Else
                      If accountDisbursementsApproveItem.Date > DateAsAt Then
                        DisbursementDateAsAt = accountDisbursementsApproveItem.Date
                      Else
                        DisbursementDateAsAt = Nothing
                      End If
                    End If
                    ShowWarnings = True
                End Select

                ' Get Banking Details Summary Table
                SummaryTablesBankingDetails = finBL.SummaryPageStandardBlocks.BankingDetails_Summary2(callerScriptInfo, BankingDetails, Account, DisbursementDateAsAt, ShowWarnings, Nothing)

                ' Get Banking Details Summary Tables
                SummaryTableBankingDetails = SummaryTablesBankingDetails.Item("Main")

                ' Add to Summary Table
                .AppendFromSummaryTable(SummaryTableBankingDetails)

                ' Add Warnings
                Warnings &= SummaryTableBankingDetails.TextAfter
              End If

            Case Else
              If accountDisbursementsApproveItem.ExternalPartyPk = 0 Then
                .AddCaptionText(accountDisbursementsApproveItem.PayeeTypeText & ":", "")
              Else
                .AddCaptionCodeDescriptionWithFormShow(accountDisbursementsApproveItem.PayeeTypeText & ":", accountDisbursementsApproveItem.ExternalPartyId, finBL.ExternalParties, "ExternalParties")
              End If

              ' Account used to Disburse
              Account = accountDisbursementsApproveItem.GetExternalPartyAccount
              If Account IsNot Nothing Then
                .AddCaptionCodeDescriptionWithFormShow("Account:", Account.AccountId, Account.Name, "Accounts")
              End If
          End Select
        End With

        ' Warnings
        .TextAfter = Warnings
      End With
    End If

    ' Notes
    If accountDisbursementsApproveItem IsNot Nothing AndAlso Len(accountDisbursementsApproveItem.Notes) <> 0 Then
      With SummaryTableNotes
        ' Initialise
        .TableClass = iseSummaryTableClass.Information
        .Caption = "Notes"

        ' Columns
        .Columns.AddText(16).NoBreakChars = 16
        .Columns.AddText()

        With .Rows
          .AddText(accountDisbursementsApproveItem.Notes)
        End With
      End With
    End If

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)
    If SummaryTableOriginalCalculation.HasData Then SummaryTables.Add("OriginalCalculation", SummaryTableOriginalCalculation)
    If SummaryTablePayee.HasData Then SummaryTables.Add("Payee", SummaryTablePayee)
    If SummaryTableNotes.HasData Then SummaryTables.Add("Notes", SummaryTableNotes)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Disbursement Account Payment Summary.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="accountDisbursementPayment">
  '''  The Account Disbursement Payment to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Summary.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function AccountDisbursementPayment_Summary(callerScriptInfo As ISScriptExecutionInfo,
                                                                 accountDisbursementPayment As finAccountDisbursementPayment,
                                                        Optional includeActions As Boolean = True,
                                                        Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' AccountDisbursementPayment_Summary
    '
    ' Version: 1.01 (20/09/2022)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.00  06/05/2016  ISS                  
    '    1.01  20/09/2022  ISS      J029358   Show Reference
    ' #################################################################


    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""
      .Columns.AddText(12).NoBreakChars = 20
      .Columns.AddText()

      Warnings = ""

      With .Rows
        With .AddCaptionText("Account:", accountDisbursementPayment.AccountId)
          .Cells(1).HyperlinkSetFormShow("Accounts", accountDisbursementPayment.AccountId)
        End With
        .AddCaptionText("Name:", accountDisbursementPayment.AccountName)

        If accountDisbursementPayment.Value = 0 Then
          ' Nil Payment
          .AddSectionHeading2("Nil Payment")

          ' Warning
          Warnings &= "{{info|No payment required. Remittance for information purposes only.}}"
        Else
          ' Payee/ Payer
          If accountDisbursementPayment.Value < 0 Then
            .AddSectionHeading2("Payee (Outgoing payment)")
          Else
            .AddSectionHeading2("Payer (Incoming payment)")
          End If
          If accountDisbursementPayment.PaymentMethodPk = 0 Then
            .AddCaptionText("Pay Method:", "")
          Else
            .AddCaptionCodeDescription("Pay Method:", accountDisbursementPayment.PaymentMethodPk, finBL.PaymentMethods)
          End If
          .AddCaptionText("Reference:", accountDisbursementPayment.ReferenceResolved)
          If accountDisbursementPayment.Value > 0 Then
            .AddCaptionText("Value:", String.Format("{0} Incoming", finBL.FormatCurrency(accountDisbursementPayment.Value, True)), iseSummaryTableCellClass.WarningBold)
            If accountDisbursementPayment.Fee <> 0 Then
              .AddCaptionCurrency("Fees:", accountDisbursementPayment.Fee, True)
              .AddCaptionCurrency("Net Payment:", accountDisbursementPayment.ValueNet, True)
            End If
          Else
            .AddCaptionCurrency("Value:", -accountDisbursementPayment.Value, True)
            If accountDisbursementPayment.Fee <> 0 Then
              .AddCaptionCurrency("Fees:", accountDisbursementPayment.Fee, True)
              .AddCaptionCurrency("Net Withdrawal:", -accountDisbursementPayment.ValueNet, True)
            End If
          End If
        End If
      End With

      ' Warnings
      If Len(accountDisbursementPayment.InvalidMessage) <> 0 Then
        Warnings &= "{{warning|" & accountDisbursementPayment.InvalidMessage & "}}"
      End If
      .TextAfter = Warnings
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Disbursement Account Payment Transactions.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="accountDisbursementPayment">
  '''  The Account Disbursement Payment to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Disbursement Account Payments wizard.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Summary.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function AccountDisbursementPayment_Transactions(callerScriptInfo As ISScriptExecutionInfo,
                                                                      accountDisbursementPayment As finAccountDisbursementPayment,
                                                             Optional includeActions As Boolean = True,
                                                             Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' AccountDisbursementPayment_Transactions
    '
    ' Version: 1.01 (20/09/2022)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.00  06/05/2016  ISS                  
    '    1.01  20/09/2022  ISS      J029358   Show Reference from Account Disbursement
    ' #################################################################

    Dim AccountDisbursementPaymentItem As finAccountDisbursementPaymentItem
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .Caption = ""
      .AutoStripe = True

      ' Columns
      With .Columns
        .AddDate("Date")
        .AddDate("Due")
        .AddText("Reference")
        .AddCurrency("Value")
        .AddText("Notes")
      End With

      ' Rows
      With .Rows
        For Each AccountDisbursementPaymentItem In accountDisbursementPayment.Transactions
          With .Add()
            With .Cells
              .AddDate(AccountDisbursementPaymentItem.Date)
              .AddDate(AccountDisbursementPaymentItem.DateDue)
              If Len(AccountDisbursementPaymentItem.AccountDisbursementReference) = 0 Then
                .AddText(AccountDisbursementPaymentItem.Reference)
              Else
                .AddWiki(String.Format("{0}<br>  --{1}--", AccountDisbursementPaymentItem.Reference, AccountDisbursementPaymentItem.AccountDisbursementReference))
              End If
              With .AddCurrency(AccountDisbursementPaymentItem.Value, True)
                ' Strike through line if not included
                If Not AccountDisbursementPaymentItem.Include Then
                  .CellClass = iseSummaryTableCellClass.Strike
                End If
              End With
              .AddText(AccountDisbursementPaymentItem.Notes)
            End With
          End With
        Next
      End With

      ' Warnings
      .TextAfter = Warnings
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Score Chart HTML Diagram (Version 1.01, Last updated 31/10/2019).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="scoreChartDiagramOptions">
  '''  The Options to use when creating the Score Chart Diagram.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  A String value containing HTML.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in various places, e.g., Account Key Details page.
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function ScoreChartDiagram(callerScriptInfo As ISScriptExecutionInfo,
                                                minValue As Decimal,
                                                maxValue As Decimal,
                                                value As Decimal,
                                                scoreChartDiagramOptions As finScoreChartDiagramOptions,
                                       Optional includeActions As Boolean = True,
                                       Optional otherParameters As ISKeyValueList = Nothing,
                                       Optional textAfter As String = "") As String

    Dim ImageData As String
    Dim NewMinValue As Decimal
    Dim NewMaxValue As Decimal
    Dim NewValue As Decimal
    Dim sb As StringBuilder
    Dim ValuePos As Decimal

    ' Initialise
    sb = New StringBuilder()
    If scoreChartDiagramOptions Is Nothing Then scoreChartDiagramOptions = finBL.CreateScoreChartDiagramOptions()

    ' Calculate Value Position as a percentage between Min and Max values
    If maxValue > minValue AndAlso value >= minValue AndAlso value <= maxValue Then
      If minValue < 0 Then
        ' Offset for negative ranges
        NewMinValue = 0
        NewMaxValue = maxValue - minValue
        NewValue = value - minValue
      Else
        NewMinValue = minValue
        NewMaxValue = maxValue
        NewValue = value
      End If
      ValuePos = finBL.Runtime.NumberUtilities.RoundDecimal(100 * (NewValue / (NewMaxValue - NewMinValue)), 2)
    Else
      ' Ignore
      ValuePos = -1
    End If

    ' Create Score Chart
    Select Case scoreChartDiagramOptions.Style
      Case isefinScoreChartDiagramStyle.BarRedToGreen,
           isefinScoreChartDiagramStyle.BarRedToGreenCentrix,
           isefinScoreChartDiagramStyle.BarRedToGreenIllionBankStatements,
           isefinScoreChartDiagramStyle.BarRedToGreenVedaConnect
        ' ------------------
        ' Bar (Red to Green)
        ' ------------------
        ' Initialise
        sb.AppendFormat("<div style='box-sizing: border-box; width:{0};  max-width:{1}'>", scoreChartDiagramOptions.Width, scoreChartDiagramOptions.MaxWidth)

        ' Scale
        sb.Append("<div style='box-sizing: border-box; height:3em; position:relative; width:100%'>")
        ' Value
        If ValuePos = -1 Then
          ' Invalid
        ElseIf ValuePos > 50 Then
          ' Right-align
          sb.AppendFormat("<div style='box-sizing: border-box; position:absolute; font-size:2.5em; font-weight:bold; border-right:1px solid black; height:100%; right:{0}%; top:0'>{1}</div>", 100 - ValuePos, value)
        Else
          ' Left-align
          sb.AppendFormat("<div style='box-sizing: border-box; position:absolute; font-size:2.5em; font-weight:bold; border-left:1px solid black; height:100%; left:{0}%; top:0'>{1}</div>", ValuePos, value)
        End If
        ' Min/ Max
        sb.AppendFormat("<div style='box-sizing: border-box; position:absolute; font-size:0.9em; left:0; bottom:0'>{0}</div>", minValue)
        sb.AppendFormat("<div style='box-sizing: border-box; position:absolute; font-size:0.9em; right:0; bottom:0'>{0}</div>", maxValue)

        sb.Append("</div>")

        ' Bar (including vertical marker so value passes through)
        Select Case scoreChartDiagramOptions.Style
          Case isefinScoreChartDiagramStyle.BarRedToGreen, isefinScoreChartDiagramStyle.BarRedToGreenCentrix
            ImageData = "R0lGODlhQAABAIcAADznAEboAE/pAFnrAGLsAGvtAHXuAH7vAPcXAPccAPghAPgmAPgrAPkwAPk1APo6APo/APpEAPtJAPtOAPtTAPxYAPxdAP1iAP1nAP1sAP5xAP52AP57AIfwAJHyAJrzAKT0AK31ALb2AP+AAP+GAP+MAP+SAP+ZAP+fAP+lAP+qAP+wAP+2AP+8AMD3AMn5ANL6ANz7AP/CAP/IAP/OAP/UAP/ZAP/fAOX8AO/9AP/lAP/sAP/yAPj+AP/4AP79AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwEBAAAh+QQAAAAAACwAAAAAQAABAAAISwARJFCwgEEDBw8gRJAwgUIFCxcwZNCwgcMIEiVMnECRQsUKFi1kzKBRw8YNHTt4+PjRIweOGDBeuBARAsQHDx0OGChAYICAAAACAgA7AA=="
          Case isefinScoreChartDiagramStyle.BarRedToGreenVedaConnect
            ImageData = "R0lGODlhQAABAIcAABlqKB1tKCNyKSp3KTB8KjeBKj2GK0SLK0qQLFGVLFebLV6gLWSkLmupLnKvL3i0L3+5MOILEuIMEuQVEeUgEecrEOg2D+pBDutLDu1WDe5hDPBsC/F2C4a+MY7DM5fINZ/MN6fROa/WOrfbPPOBCvSMCfaXCPeiCPmsB/u3BtzeLsDgPtHlO/zCBf3JBfzKBvLQEufXIMjlQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwEBAAAh+QQAAAAAACwAAAAAQAABAAAIQwAjCJQwgUIFCxcwZNCwgQOJEiZOoEjRwoXFixZfwIihgoWMFSNEhADxwUMHCA8cNGCwQEECBAcMFCAwQEAAADhxBgQAOwA="
          Case isefinScoreChartDiagramStyle.BarRedToGreenIllionBankStatements
            ' Six-colour gradient staging through #FF3300, #FFB89A, #FFE3CD, #C6DE80, #93D687, #61CC94
            ' Achieved using Paint.NET plug-in at https://forums.getpaint.net/topic/8527-multi-color-gradient-v30-may-17-2018/
            ' Original image size 100x4px
            ' Image converted to Base64 using https://base64.guru/converter/encode/image
            ImageData = "R0lGODlhZAAEAHAAACwAAAAAZAAEAIb/NQD/OQD/PQD/QAD/RAD/SAD/TAD/UAD/VAD/WAD/WwD/XwD/YwD/ZwD/awD/bwD/cgD/dgD/egD/fgD/ggT/hw7/jBj/kSP/li3/mzf/oEH/pEz/qVb/r2D/tGr/uXX/vX//won/x5P/zJ3/0aj/1rL/27z/4Mb+48z748j54sT14sDy4r3w4rnt4bTq4bHn4a3l4anh4KXe4KHc4J3Z4JrW35XT35LR347N34rL3obI3oLG3oDD3YHA3YG+3YG83IK53IK224Kz24Ox24Ov2oOs2oSq2YSn2YSl2YWi2IWf2IWc14aa14aY14aV1oeT1oeQ1YiO1YmL1ImI1IqF04uD04uA0ox+0ox70Y150Y530I500I9yz5Bwz5FtzpFqzpJozZJmzZNjzJP/RQD/XADO34rI3oO024OY14eG04uB0ox+0o1jzJR80Y3t4bXo4a2f2IYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAH/4AAAQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2Nzg5Ojs8PT4/QEFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaW1xdXl9gYWJjgoRkh4kJZY2PkZOVl5mbnZ+ho6Wnqautr7GztW7lMqPjjC9gwoSgMYZMGTNnaaJNq6bGyho227p9CzeujbkB6BApYucIkiRKljBp4uQJlChSplCpYuUKlixatnDp4nUw2LBix5Ita9YkojRq1rCxccPNGzhxYjwOAplOEaOS71DKW1nPJb6Y+2i2ePMCDsCcA3n+8qmQoVAlcQycQTtKUWlGpxyjBgIAOw=="
          Case Else
            ' 1 pixel magenta
            ImageData = "R0lGODlhAQABAIcAAP8A/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwEBAAAh+QQAAAAAACwAAAAAAQABAAAIBAABBAQAOwA="
        End Select

        sb.AppendFormat("<div style='box-sizing: border-box; position:relative'>")
        If ValuePos = -1 Then
          ' Invalid
        ElseIf ValuePos > 50 Then
          ' Right-align
          sb.AppendFormat("<div style='box-sizing: border-box; position:absolute; border-right:1px solid black; height:{0}; right:{1}%'></div>", scoreChartDiagramOptions.Height, 100 - ValuePos)
        Else
          ' Left-align
          sb.AppendFormat("<div style='box-sizing: border-box; position:absolute; border-right:1px solid black; height:{0}; left:{1}%'></div>", scoreChartDiagramOptions.Height, ValuePos)
        End If
        sb.AppendFormat("<img src='data:image/gif;base64,{0}' style='display:inline-block; box-sizing: border-box; height:{1}; width:{2}; max-width:{3}; padding:0; margin:0; vertical-align:middle'/>", ImageData, scoreChartDiagramOptions.Height, scoreChartDiagramOptions.Width, scoreChartDiagramOptions.MaxWidth)
        sb.AppendFormat("</div>")

        ' TextAfter
        If Len(textAfter) <> 0 Then
          sb.AppendFormat("<div style='box-sizing: border-box; position:relative; font-size:0.9em; left:0; top:2px'>{0}</div>", textAfter)
        End If

        ' Finalise
        sb.AppendFormat("</div>")

      Case Else
        sb.AppendFormat("<p>Unhandled Score Chart Diagram Style '{0}'</p>", scoreChartDiagramOptions.Style.ToString())
    End Select

    Return sb.ToString()

  End Function

  ''' <summary>
  '''  Account Direct Debit Process Summary.
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method.
  ''' </param>
  ''' <param name="accountDirectDebit">
  '''  The Account Direct Debit Item to summarise.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used on the Process Direct Debits wizard.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables:
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''    <item><code>Payment</code><description>Payment details.</description></item>
  '''    <item><code>CombinedPayment</code><description>Combined Payment details.</description></item>
  '''    <item><code>Transactions</code><description>Transaction details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function AccountDirectDebit_Summary(callerScriptInfo As ISScriptExecutionInfo,
                                                         accountDirectDebit As finAccountDirectDebit,
                                                Optional includeActions As Boolean = True,
                                                Optional otherParameters As ISKeyValueList = Nothing) As ISSummaryTables

    ' #################################################################
    ' AccountDirectDebit_Summary
    '
    ' Version: 1.05 (24/03/2023)
    ' #################################################################
    ' Version        Date  User     Job       Description
    ' -------  ----------  -------  --------  -------------------------
    '    1.02  08/04/2021  ISS
    '    1.03  13/09/2021  ISS      J026906   Add Transactions Summary Table
    '    1.04  06/03/2023  ISS      J028808   Changes for Pre and Post Value scripting
    '    1.05  23/03/2023  ISS      J030626   Add ValueComments to Warnings
    '          24/03/2023  ISS      J030767   Added "Increased from" if the values had changed (previously said reduced from, even if the value had been increased)
    ' #################################################################

    Dim AccountTransaction As finAccountTransaction
    Dim CombinedAccountDirectDebit As finAccountDirectDebit
    Dim CombinedCount As Integer
    Dim CombinedFee As Decimal
    Dim CombinedValue As Decimal
    Dim SummaryTableCombinedPayment As ISSummaryTable
    Dim SummaryTableMain As ISSummaryTable
    Dim SummaryTablePayment As ISSummaryTable
    Dim SummaryTableTransactions As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise ByRef Parameters

    ' Get Constants

    ' Initialise
    If callerScriptInfo Is Nothing Then callerScriptInfo = finBL.CreateScriptExecutionInfo()
    If otherParameters Is Nothing Then otherParameters = finBL.CreateKeyValueList()
    SummaryTableMain = finBL.CreateSummaryTable()
    SummaryTablePayment = finBL.CreateSummaryTable()
    SummaryTableCombinedPayment = finBL.CreateSummaryTable()
    SummaryTableTransactions = finBL.CreateSummaryTable()
    SummaryTables = finBL.CreateSummaryTables()

    ' Main
    With SummaryTableMain
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = ""

      ' Columns
      .Columns.AddText(16).NoBreakChars = 16
      .Columns.AddText()

      ' Clear Warnings
      Warnings = ""

      With .Rows
        ' General
        With .AddCaptionText("Account:", accountDirectDebit.AccountId)
          .Cells(1).HyperlinkSetFormShow("Accounts", accountDirectDebit.AccountId)
        End With
        .AddCaptionText("Name:", accountDirectDebit.AccountName)
      End With

      ' Warnings
      .TextAfter = Warnings
    End With

    ' Payment
    With SummaryTablePayment
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = "Payment"

      ' Columns
      .Columns.AddText(16).NoBreakChars = 16
      .Columns.AddText()

      ' Clear Warnings
      Warnings = ""

      With .Rows
        ' Payment
        If accountDirectDebit.ValuePreScript = accountDirectDebit.ValuePostScript Then
          If accountDirectDebit.Value = accountDirectDebit.ValueOriginal Then
            .AddCaptionCurrency("Value:", accountDirectDebit.Value, True)
          ElseIf accountDirectDebit.Value < accountDirectDebit.ValueOriginal Then
            .AddCaptionWiki("Value:", String.Format("**{0} --!!Reduced from {1}!!--**", finBL.FormatCurrency(accountDirectDebit.Value, True), finBL.FormatCurrency(accountDirectDebit.ValueOriginal, True)))
          Else
            .AddCaptionWiki("Value:", String.Format("**{0} --!!Increased from {1}!!--**", finBL.FormatCurrency(accountDirectDebit.Value, True), finBL.FormatCurrency(accountDirectDebit.ValueOriginal, True)))
          End If
        Else
          ' Scripted Value 
          If accountDirectDebit.Value = accountDirectDebit.ValuePostScript Then
            .AddCaptionCurrency("Value:", accountDirectDebit.Value, True)
          ElseIf accountDirectDebit.Value < accountDirectDebit.ValuePostScript Then
            .AddCaptionWiki("Value:", String.Format("**{0} --!!Reduced from {1}!!--**", finBL.FormatCurrency(accountDirectDebit.Value, True), finBL.FormatCurrency(accountDirectDebit.ValuePostScript, True)))
          Else
            .AddCaptionWiki("Value:", String.Format("**{0} --!!Increased from {1}!!--**", finBL.FormatCurrency(accountDirectDebit.Value, True), finBL.FormatCurrency(accountDirectDebit.ValuePostScript, True)))
          End If
        End If
        If accountDirectDebit.FeeOriginal <> 0 Then
          If accountDirectDebit.Fee = accountDirectDebit.FeeOriginal Then
            .AddCaptionCurrency("Fee:", accountDirectDebit.Fee, True)
          ElseIf accountDirectDebit.Fee < accountDirectDebit.FeeOriginal Then
            .AddCaptionWiki("Fee:", String.Format("**{0} --!!Reduced from {1}!!--**", finBL.FormatCurrency(accountDirectDebit.Fee, True), finBL.FormatCurrency(accountDirectDebit.FeeOriginal, True)))
          Else
            .AddCaptionWiki("Fee:", String.Format("**{0} --!!Increased from {1}!!--**", finBL.FormatCurrency(accountDirectDebit.Fee, True), finBL.FormatCurrency(accountDirectDebit.FeeOriginal, True)))
          End If
          .AddCaptionCurrency("Net Value:", accountDirectDebit.Charge, True)
        End If
        Select Case accountDirectDebit.ValuePaymentAllocationMethod
          Case isefinAccountTransactionPaymentAllocationMethod.AccountDefault, isefinAccountTransactionPaymentAllocationMethod.Standard
          Case Else
            .AddCaptionText("Allocation:", accountDirectDebit.ValuePaymentAllocationMethodText)
        End Select
      End With

      ' Warning Messages
      With accountDirectDebit
        ' Value Adjustments
        If .Value <> .ValuePostScript Then
          ' Value manually changed
          If .Value = 0 Then
            Warnings &= "{{info|Value has been manually reduced to zero.}}"
            Warnings &= "{{warning|Payment Transaction will not be created.|True}}"
          Else
            Warnings &= "{{info|Value has been manually changed.}}"
          End If
        ElseIf .ValuePreScript <> .ValuePostScript Then
          ' Value changed by script
          If .Value = 0 Then
            Warnings &= "{{info|Nil Value.}}"
            Warnings &= "{{warning|Payment Transaction will not be created.|True}}"
          End If
        Else
          ' No script
          If .Value = 0 Then
            Warnings &= "{{info|Value reduced to zero.}}"
            Warnings &= "{{warning|Payment Transaction will not be created.|True}}"
          ElseIf .Value <> .ValueOriginal Then
            If .AccountResidualValue = 0 Then
              Warnings &= "{{info|Value reduced to Account's Balance.}}"
            Else
              Warnings &= "{{info|Value reduced to Account's Residual Value.}}"
            End If
          ElseIf .Value <> .ValueAdjusted Then
            Warnings &= "{{info|Direct Debit will take the Account into Credit.}}"
          End If
        End If

        ' Value Comments (from Script)
        If Len(.ValueComments) <> 0 Then
          Warnings &= "{{info|" & .ValueComments & "}}"
        End If

        ' Fee Adjustments
        If .Fee <> .FeeOriginal Then
          Warnings &= "{{warning|Fee reduced.}}"
        End If

        ' Invalid?
        If Len(.InvalidMessage) <> 0 Then
          If .Processed Then
            Warnings &= "{{info|" & .InvalidMessage & "}}"
          ElseIf .IsExportable Then
            Warnings &= "{{warning|" & .InvalidMessage & "}}"
          Else
            Warnings &= "{{warning|" & .InvalidMessage & "}}"
            Warnings &= "{{warning|CANNOT EXPORT PAYMENT.|True}}"
          End If
        End If
      End With

      ' Warnings
      .TextAfter = Warnings
    End With

    ' Combined Payment
    With SummaryTableCombinedPayment
      ' Initialise
      .TableClass = iseSummaryTableClass.Information
      .Caption = "Combined Payment"

      ' Columns
      .Columns.AddText(16).NoBreakChars = 16
      .Columns.AddText()

      ' Clear Warnings
      Warnings = ""

      If accountDirectDebit.IsExportable AndAlso accountDirectDebit.Include AndAlso accountDirectDebit.Combine Then
        ' Get Values
        CombinedCount = 0
        CombinedFee = 0
        CombinedValue = 0
        For Each CombinedAccountDirectDebit In accountDirectDebit.Parent
          ' Must be including and combining
          If CombinedAccountDirectDebit.IsExportable AndAlso CombinedAccountDirectDebit.Include AndAlso CombinedAccountDirectDebit.Combine Then
            ' Must be for the same Client and Payment Method etc
            If accountDirectDebit.ClientPk = CombinedAccountDirectDebit.ClientPk AndAlso accountDirectDebit.BankingDetails.PaymentMethodPk = CombinedAccountDirectDebit.BankingDetails.PaymentMethodPk Then
              If accountDirectDebit.BankingDetails.AccountSortCode = CombinedAccountDirectDebit.BankingDetails.AccountSortCode AndAlso accountDirectDebit.BankingDetails.AccountNumber = CombinedAccountDirectDebit.BankingDetails.AccountNumber AndAlso accountDirectDebit.BankingDetails.ExternalId = CombinedAccountDirectDebit.BankingDetails.ExternalId Then
                CombinedCount += 1
                CombinedFee += CombinedAccountDirectDebit.Fee
                CombinedValue += CombinedAccountDirectDebit.Value
              End If
            End If
          End If
        Next

        With .Rows
          ' Combined Payment
          If CombinedCount > 1 Then
            .AddCaptionCodeDescriptionWithFormShow("Main Client:", accountDirectDebit.ClientId, accountDirectDebit.ClientName, "Clients")
            .AddCaptionCurrency("Value:", CombinedValue, True)
            If CombinedFee <> 0 Then
              .AddCaptionCurrency("Fee:", CombinedFee, True)
              .AddCaptionCurrency("Net Value:", CombinedValue + CombinedFee, True)
            End If

            ' Warning Messages
            Warnings &= "{{info|" & CStr(CombinedCount) & " payments combined.}}"
          End If
        End With
      End If

      ' Warnings
      .TextAfter = Warnings
    End With

    ' Transactions
    With SummaryTableTransactions
      ' Initialise
      .TableClass = iseSummaryTableClass.TabularData
      .AutoStripe = True
      .Caption = "Transactions"
      .WidthHtml = "*"

      ' Columns
      With .Columns
        .AddDate("Date")
        .AddText("Type")
        .AddText("Reference")
        .AddCurrency("Value")
        .AddText("Notes")
      End With

      ' Add Accrual Rows
      For Each AccountTransaction In accountDirectDebit.AccountTransactions
        With .Rows.Add().Cells
          .AddDate(AccountTransaction.Date)
          .AddText(AccountTransaction.ScheduleTypeText)
          .AddText(AccountTransaction.Reference)
          .AddCurrency(AccountTransaction.DirectDebitValue, True)
          .AddText(AccountTransaction.Notes)
        End With
      Next
    End With

    ' Add Summary Tables
    SummaryTables.Add("Main", SummaryTableMain)
    If SummaryTablePayment.HasData Then SummaryTables.Add("Payment", SummaryTablePayment)
    If SummaryTableCombinedPayment.HasData Then SummaryTables.Add("CombinedPayment", SummaryTableCombinedPayment)
    If SummaryTableTransactions.HasData Then SummaryTables.Add("Transactions", SummaryTableTransactions)

    Return SummaryTables

  End Function

  ''' <summary>
  '''  Recent Actions Summary (Version 1.00, Last updated 26/04/2016).
  ''' </summary>
  ''' <param name="callerScriptInfo">
  '''  The Script Information of the Script calling this method. 
  ''' </param>
  ''' <param name="recentActions">
  '''  The Recent Actions to summarise.
  ''' </param>
  ''' <param name="maxDisplayRows">
  '''  The Maximum number of Rows to Display in supplemental tables (e.g., Client Accounts) before a 'Show Hidden' link is displayed.
  ''' </param>
  ''' <param name="includeActions">
  '''  Indicates whether to Include Actions with the Summary Tables.
  ''' </param>
  ''' <param name="otherParameters">
  '''  Can be used when customising Summary Page Blocks to pass other parameter to the Script.
  ''' </param>
  ''' <returns>
  '''  An ISSummaryTables object.
  ''' </returns>
  ''' <remarks>
  '''  <para>
  '''   Used in the Recent Actions report.
  '''  </para>
  '''  <para>
  '''   Returns the following Summary Tables (depending on the item type being summarised, additional tables may be included):
  '''   <list>
  '''    <item><code>Main</code><description>Main details.</description></item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from ScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  '''  <para>
  '''   The following Constants are used from callerScriptInfo:
  '''   <list>
  '''   <item>None</item>
  '''   </list>
  '''  </para>
  ''' </remarks>
  Public Overridable Function RecentActions_Summary(callerScriptInfo As ISScriptExecutionInfo,
                                                    recentActions As ISRecentActions,
                                                    maxDisplayRows As Integer,
                                                    includeActions As Boolean,
                                                    otherParameters As ISKeyValueList) As ISSummaryTables

    Dim RecentAction As ISRecentAction
    Dim SummaryTable As ISSummaryTable
    Dim SummaryTables As ISSummaryTables
    Dim Warnings As String

    ' Initialise
    SummaryTables = finBL.CreateSummaryTables()
    SummaryTable = finBL.CreateSummaryTable()

    ' Add Columns
    With SummaryTable
      .TableClass = iseSummaryTableClass.TabularData
      .AutoStripe = True

      If recentActions.Count = 0 Then
        .TextBefore = "{{info|There are no recent actions for User **" & finBL.Users.ItemByPkSafe(recentActions.UserPk).UserId & "**.}}"
      Else
        With .Columns
          .AddDateTime("Date")
          .AddText("Action", 12).NoBreakChars = 20
          .AddText("Source", 10).NoBreakChars = 20
          .AddCode("Code", 10)
          .AddBoolean(" ") ' Icon
          .AddText("Description")
          .AddText("Process", 12).NoBreakChars = 20
        End With

        ' Recent Actions
        For Each RecentAction In recentActions
          With .Rows.Add()
            ' Make today's Actions more apparent
            If RecentAction.ActionDate.Date <> finBL.TimeZoneFunctions.GetCurrentLocalDate() Then
              .RowClass = iseSummaryTableRowClass.Inactive
            End If

            With .Cells
              .AddDateTime(RecentAction.ActionDate)
              .AddText(finBL.Runtime.TextUtilities.SplitWordsAtCapitals(RecentAction.ActionType))
              .AddText(finBL.Runtime.TextUtilities.SplitWordsAtCapitals(RecentAction.SourceObjectType))

              ' Code (open associated form)
              Select Case UCase(RecentAction.SourceObjectType)
                Case "ACCOUNT"
                  ' Account
                  With .AddText(RecentAction.SourceId)
                    .HyperlinkSetFormShow("Accounts", CStr(RecentAction.SourceId))
                  End With

                Case "ACCOUNTAPP"
                  ' Account Application
                  With .AddText(RecentAction.SourceId)
                    .HyperlinkSetFormShow("AccountApps", CStr(RecentAction.SourceId))
                  End With

                Case "ACCOUNTLOG"
                  ' Account Log
                  With .AddText(RecentAction.SourceId)
                    .HyperlinkSetFormShow("AccountLog", CStr(RecentAction.SourcePk))
                  End With

                Case "ACCOUNTAPPLOG"
                  ' Account Application Log
                  With .AddText(RecentAction.SourceId)
                    .HyperlinkSetFormShow("AccountAppLog", CStr(RecentAction.SourcePk))
                  End With

                Case "CLIENTLOG"
                  ' Client Log
                  With .AddText(RecentAction.SourceId)
                    .HyperlinkSetFormShow("ClientLog", CStr(RecentAction.SourcePk))
                  End With

                Case "MAILBOXITEM"
                  ' Mailbox Item
                  With .AddText(RecentAction.SourceId)
                    .HyperlinkSetFormShow("MailboxItem", CStr(RecentAction.SourcePk))
                  End With

                Case "SECURITYSTMT"
                  ' Security Stmt
                  With .AddText(RecentAction.SourceId)
                    .HyperlinkSetFormShow("SecurityStmts", CStr(RecentAction.SourceId))
                  End With

                Case "SECURITYSTMTITEMLOG"
                  ' Security Stmt Item Log
                  With .AddText(RecentAction.SourceId)
                    .HyperlinkSetFormShow("SecurityStmtItemLog", CStr(RecentAction.SourcePk))
                  End With

                Case "SECURITYSTMTLOG"
                  ' Security Stmt Log
                  With .AddText(RecentAction.SourceId)
                    .HyperlinkSetFormShow("SecurityStmtLog", CStr(RecentAction.SourcePk))
                  End With

                Case "USERLOG"
                  ' User Log
                  With .AddText(RecentAction.SourceId)
                    .HyperlinkSetFormShow("UserLog", CStr(RecentAction.SourcePk))
                  End With

                Case "WORKFLOW"
                  ' Workflow
                  With .AddText(RecentAction.SourceId)
                    .HyperlinkSetFormShow("Workflows", CStr(RecentAction.SourceId))
                  End With

                Case Else
                  .AddText("Unknown Object Type")
              End Select

              ' Find in Task Manager (exclude certain types that will never appear in the Task Manager)
              Select Case UCase(RecentAction.SourceObjectType)
                Case ""
                  .AddText("")
                Case Else
                  With .AddText("{{icon|FindNext}}")
                    .HyperlinkSetFormAction("FindItem", "action=FindItem&type=" & RecentAction.SourceObjectType & "&pk=" & RecentAction.SourcePk, "TaskManager")
                  End With
              End Select
              .AddText(RecentAction.Description)
              .AddText(RecentAction.Process)
            End With
          End With
        Next

        ' Warning
        .TextAfter = Warnings
      End If
    End With

    ' Create and return collection
    SummaryTables = finBL.CreateSummaryTables()
    SummaryTables.Add("Main", SummaryTable)
    Return SummaryTables

  End Function

End Class