<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2022-05-11T00:31:20.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2018-04-13T00:56:05.1230000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2022-05-11T00:28:55.8270000</UpdatedUtcDate>
    <ScriptId>XEUA</ScriptId>
    <Description>External User Accounts &amp; Applications</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Category>Sample</Category>
    <Code>' HtmlWidget_ExternalUserAccounts
Option Explicit On
Option Strict On

' #################################################################
' External User Accounts and Applications HTML Widget
'
' Version: 1.04 (11/05/2022)
'
' Usage: System-defined HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.03  24/05/2018  ISS                Updated
'    1.04  11/05/2022  ISS      J028712   Removed obsoleted Functions
' #################################################################

' Objects
Private mCombinedParameters As ISKeyValueList
Private mParameters As ISKeyValueList
Private mStartupParameters As ISKeyValueList

' Other
Private mCurrentUserInformation As finCurrentUserInformation
Private mUserId As String

Public Function Main(eventId As String, parametersJson As String, startUpParametersJson As String, hostingContext As isefinHtmlWidgetHostingContext, requestInfo As finScriptRequestInfo, ByRef returnValue As String) As Boolean

  ' Assume Success
  Main = True

  ' Get Parameters
  mParameters = finBL.CreateKeyValueList()
  mParameters.FromSimpleJsonString(parametersJson)
  mStartupParameters = finBL.CreateKeyValueList()
  mStartupParameters.FromSimpleJsonString(startUpParametersJson)

  ' Get Combined Parameters (Startup Parameters updated with event Parameters)
  mCombinedParameters = mStartupParameters.Clone()
  mCombinedParameters.UpdateFromKeyValueList(mParameters, True)

  ' Tasks View Support
  With mCombinedParameters
    mUserId = .GetString("TasksUserId")
  End With
  If Len(mUserId) = 0 Then
    mUserId = finBL.CurrentUser.UserId
  ElseIf Not finBL.TaskManagerFunctions.CanViewUserInTaskManager(mUserId) Then
    ' Not Authorised to view this User in Tasks View
    mUserId = ""
  End If

  ' Handle Events
  Select Case eventId
    Case ""
      ' Main event, i.e., return initial HTML content (excluding html and body tags)
      returnValue = GetPage()

    Case "GetPageDetails"
      ' Get Page Details
      Main = GetPageDetails(parametersJson, returnValue)

    Case "GetAccountTasks"
      ' Get Account Tasks
      Main = GetAccountTasks(parametersJson, returnValue)

    Case "GetAccountAppTasks"
      ' Get Account Application Tasks
      Main = GetAccountAppTasks(parametersJson, returnValue)

    Case Else
      Main = False
      finBL.Error.ErrorBeginFormat("Unhandled Script event '{0}'.", eventId)
  End Select

End Function

Private Function GetPage() As String

  Dim AllowShowAll As Boolean
  Dim Html As String

  ' Initialise
  Html = ScriptInfo.TemplateText

  ' Allow Show All Users?
  If Len(mCombinedParameters.GetString("TasksUserId")) = 0 Then
    ' Not in Tasks View
    AllowShowAll = True
  Else
    ' In Tasks View so User already known
    AllowShowAll = False
  End If

  ' Replace Tags
  Html = Replace(Html, "&lt;%AllowShowAll%&gt;", LCase(AllowShowAll.ToString()))

  Return Html

End Function

Private Function GetPageDetails(parametersJson As String,
                                ByRef returnValue As String) As Boolean

  Dim Columns As ISList
  Dim HighlightRowsWithTasks As Boolean
  Dim IncludeAll As Boolean
  Dim Page As String
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  ' Get Parameters
  ' NOTE: Use the module mCombinedParameters since this contains Startup and event Parameters in a single Key/Value List
  With mCombinedParameters
    Columns = New ISList(.GetString("Columns"))
    Page = .GetString("Page")
    HighlightRowsWithTasks = .GetBoolean("HighlightRowsWithTasks")
    IncludeAll = .GetBoolean("IncludeAll")
  End With

  ' Validate
  If Success Then
  End If

  ' Get Current User Information
  If Len(mUserId) = 0 Then
    Success = False
    finBL.Error.ErrorBegin("No User specified.")
  Else
    Success = finBL.Users(mUserId).GetCurrentUserInformation(mCurrentUserInformation)
  End If

  ' Get Summary Tables
  If Success Then
    Select Case ucase(Page)
      Case "QUOTES", "CLOSED", "REJECTED"
        If finBL.Settings.AddOns.AccountApplication Then
          SummaryTable = GetSummaryTable_AccountApp(page, Columns, IncludeAll, HighlightRowsWithTasks)
          SummaryTable.Caption = "Applications"
          SummaryTables.Add("AccountApps", SummaryTable)
        End If

        SummaryTable = GetSummaryTable_Account(page, Columns, IncludeAll, HighlightRowsWithTasks)
        If finBL.Settings.AddOns.AccountApplication Then
          SummaryTable.Caption = "Accounts"
        End If
        SummaryTables.Add("Accounts", SummaryTable)

      Case "OPEN"
        SummaryTable = GetSummaryTable_Account(page, Columns, IncludeAll, HighlightRowsWithTasks)
        SummaryTables.Add("Accounts", SummaryTable)

      Case Else
        Success = False
        finBL.Error.ErrorBeginFormat("Page '{0}' not handled.", Page)
    End Select
  End If

  ' Finalise
  If Success Then
    returnValue = GetHtmlFromSummaryTables(SummaryTables)
  End If

  Return Success

End Function

Private Function GetSummaryTable_Account(page As String,
                                         columns As ISList,
                                         includeAll As Boolean,
                                         highlightRowsWithTasks As Boolean) As ISSummaryTable

  Dim ClosedDays As Integer
  Dim Database As ISDatabaseBL
  Dim DateColumnDescription As String
  Dim DateColumnName As String
  Dim dr As IDataReader
  Dim MonitorCategory As finMonitorCategoryRO
  Dim ShowAccountType As Boolean
  Dim ShowBroker As Boolean
  Dim ShowDealer As Boolean
  Dim ShowEmployee As Boolean
  Dim ShowMonitorCategory As Boolean
  Dim ShowStatus As Boolean
  Dim ShowStatusIcon As Boolean
  Dim ShowTasks As Boolean
  Dim sqb As ISSelectQueryBuilder
  Dim Status As isefinAccountStatus
  Dim SummaryTable As ISSummaryTable
  Dim Success As Boolean
  Dim XPEmployeeFieldName As String
  Dim XPFieldName As String

  ' Assume Success
  Success = True

  ' Initialise
  Database = finBL.Database
  SummaryTable = finBL.CreateSummaryTable()

  ' Get Parameters
  ' NOTE: Use the module mCombinedParameters since this contains Startup and event Parameters in a single Key/Value List
  With mCombinedParameters
    ClosedDays = .GetInteger("ClosedDays")
  End With

  ' Determine External Party fields to use
  Select Case mCurrentUserInformation.ExternalPartyType
    Case isefinExternalPartyType.Broker
      XPFieldName = "BrokerExPartyPk"
      XPEmployeeFieldName = "BrokerExPartyEmployeePk"

    Case isefinExternalPartyType.Dealer
      XPFieldName = "DealerExPartyPk"
      XPEmployeeFieldName = "DealerExPartyEmployeePk"

    Case Else
      XPFieldName = "DealerExPartyPk"
      XPEmployeeFieldName = "DealerExPartyEmployeePk"
  End Select

  ' Determine Columns to Include
  ShowAccountType = columns.Exists("Account Type", True)
  ShowBroker = columns.Exists("Broker", True)
  ShowDealer = columns.Exists("Dealer", True)
  ShowEmployee = includeAll
  ShowMonitorCategory = columns.Exists("Monitor Category", True)
  ShowStatus = columns.Exists("Status", True)
  ShowStatusIcon = columns.Exists("Status Icon", True)
  ShowTasks = columns.Exists("Tasks", True)

  Select Case UCase(page)
    Case "QUOTES"
      DateColumnName = "DateQuoted"
      DateColumnDescription = "Quoted"

    Case "OPEN"
      DateColumnName = "DateOpened"
      DateColumnDescription = "Opened"

    Case "CLOSED", "REJECTED"
      DateColumnName = "DateClosed"
      DateColumnDescription = "Closed"
  End Select

  ' Build Query
  If Success Then
    sqb = Database.CreateSelectQueryBuilder()
    With sqb
      .Table = "Account"
      .Fields.AddList("Account.Pk,Account.AccountId,Account.AccountTypePk,Account.BrokerExPartyPk,Account.DateClosed,Account.DateOpened,Account.DateQuoted,Account.DealerExPartyPk,Account.MonitorCatAPk,Account.Name,Account.Status")
      If ShowTasks Then
        With .Fields.AddSubQuery("TaskCount").SubQueryBuilder
          .Table = "AccountLog"
          .Fields.AddCount()

          With .SqlWhere
            .AppendComparisonField("Account.Pk", "=", "AccountLog.AccountPk")
            .AppendComparisonNotNull("ActionUtcDate")
            .AppendComparisonNull("ActionCompleteUtcDate")
          End With
        End With
      End If

      ' SQL Where
      With .SqlWhere
        ' Page-Specific
        Select Case UCase(page)
          Case "QUOTES"
            ' ------
            ' Quotes
            ' ------
            .AppendComparisonInteger("Account.Status", "=", isefinAccountStatus.Quote)

          Case "OPEN"
            ' ----
            ' Open
            ' ----
            .AppendComparisonInteger("Account.Status", "=", isefinAccountStatus.Open)

          Case "REJECTED"
            ' --------
            ' Rejected
            ' --------
            .BlockBegin(iseSqlWhereBuilderNestedBlockType.OrBlock)
            .AppendComparisonInteger("Account.Status", "=", isefinAccountStatus.Unwanted)
            .AppendComparisonInteger("Account.Status", "=", isefinAccountStatus.Declined)
            .BlockEnd()

            ' Closed in past 30 days only
            .AppendComparisonDate("Account.DateClosed", "&gt;=", finBL.TimeZoneFunctions.GetCurrentDatabaseDate().AddDays(-ClosedDays))

          Case "CLOSED"
            ' ------
            ' Closed
            ' ------
            .BlockBegin(iseSqlWhereBuilderNestedBlockType.OrBlock)
            .AppendComparisonInteger("Account.Status", "=", isefinAccountStatus.Closed)
            .AppendComparisonInteger("Account.Status", "=", isefinAccountStatus.ClosedPending)
            .BlockEnd()

            ' Closed in past 30 days only
            .AppendComparisonDate("Account.DateClosed", "&gt;=", finBL.TimeZoneFunctions.GetCurrentDatabaseDate().AddDays(-ClosedDays))

          Case Else
            Success = False
            finBL.Error.ErrorBeginFormat("Unhandled Account Page '{0}'.", Page)
        End Select

        ' Restrict to External Party
        If mCurrentUserInformation.IsExternalUser Then
          ' External Party
          .AppendComparisonInteger(XPFieldName, "=", mCurrentUserInformation.ExternalPartyPk)

          ' Current Employee only
          If Not includeAll Then .AppendComparisonInteger(XPEmployeeFieldName, "=", mCurrentUserInformation.ExternalPartyEmployeePk)
        End If

        ' User Filters
        .Append(mCurrentUserInformation.FilterAccountSqlWhere)
      End With

      ' Employee User
      If Len(XPEmployeeFieldName) &lt;&gt; 0 Then
        Select Case mCurrentUserInformation.ExternalPartyType
          Case isefinExternalPartyType.Broker
            ' Broker
            .Fields.Add("ClientEmployment.ClientEmploymentId")
            .Joins.Add("ClientEmployment", "ClientEmployment.Pk", "Account.BrokerExPartyEmployeePk", iseSelectQueryJoinType.Left)

          Case isefinExternalPartyType.Dealer
            ' Dealer
            .Fields.Add("ClientEmployment.ClientEmploymentId")
            .Joins.Add("ClientEmployment", "ClientEmployment.Pk", "Account.DealerExPartyEmployeePk", iseSelectQueryJoinType.Left)

          Case Else
            ' None
            .Fields.Add("ClientEmployment.ClientEmploymentId")
            .Joins.Add("ClientEmployment", "ClientEmployment.Pk", "Account.DealerExPartyEmployeePk", iseSelectQueryJoinType.Left)
        End Select
      End If

      ' Order By
      With .OrderByFields
        .Add("Account.CreatedUtcDate")
      End With
    End With
  End If

  ' Execute Query and get Results
  If Success Then
    If sqb.ExecuteDisconnectedDataReader(dr) Then
      ' Initialise Summary Table
      With SummaryTable
        .TableClass = iseSummaryTableClass.TabularData
        .AutoStripe = True

        With .Columns
          If ShowStatusIcon Then.AddBoolean(" ") ' Icon
          .AddDate(DateColumnDescription)
          If ShowEmployee Then .AddCode("Employee", 5)
          .AddCode("Code", 5)
          .AddText("Name")
          If ShowAccountType Then .AddCode("Type", 5)
          If ShowDealer Then .AddCode("Dealer", 5)
          If ShowBroker Then .AddCode("Broker", 5)
          If ShowStatus Then .AddCode("Status", 10)
          If ShowMonitorCategory Then .AddCode("Monitor", 5)
          If ShowTasks Then .AddInteger("Tasks", 3)
        End With

        ' Add Rows
        Do While dr.Read()
          ' Initialise
          Status = DirectCast(Database.GetFieldEnum(dr!Status, GetType(isefinAccountStatus)), isefinAccountStatus)

          With .Rows.Add()
            ' Row Class
            If ShowTasks AndAlso HighlightRowsWithTasks AndAlso Database.GetFieldInteger(dr!TaskCount) &lt;&gt; 0 Then
              .BackgroundColour = "yellow"
            End If

            With .Cells
              If ShowStatusIcon Then
                .AddText("{{icon|AccountStatus_" &amp; Status.ToString() &amp; "|" &amp; finBL.Enums.isefinAccountStatus_ToString(Status) &amp; "}}")
              End If

              .AddDate(Database.GetFieldUtcDate(dr(DateColumnName)))

              If ShowEmployee Then .AddText(Database.GetFieldString(dr!ClientEmploymentId))

              With .AddText(Database.GetFieldString(dr!AccountId))
                .HyperlinkSetFormShow("Accounts", Database.GetFieldString(dr!AccountId))
              End With
              .AddText(Database.GetFieldString(dr!Name))

              If ShowAccountType Then .AddText(finBL.AccountTypes.ItemByPk(Database.GetFieldInteger(dr!AccountTypePk)).AccountTypeId)

              If ShowDealer Then
                If Database.GetFieldInteger(dr!DealerExPartyPk) = 0 Then
                  .AddText("")
                Else
                  .AddText(finBL.ExternalParties.ItemByPk(Database.GetFieldInteger(dr!DealerExPartyPk)).ExternalPartyId)
                End If
              End If

              If ShowBroker Then
                If Database.GetFieldInteger(dr!BrokerExPartyPk) = 0 Then
                  .AddText("")
                Else
                  .AddText(finBL.ExternalParties.ItemByPk(Database.GetFieldInteger(dr!BrokerExPartyPk)).ExternalPartyId)
                End If
              End If

              If ShowStatus Then .AddText(finBL.Enums.isefinAccountStatus_ToString(DirectCast(Database.GetFieldEnum(dr!Status, GetType(isefinAccountStatus)), isefinAccountStatus)))

              If ShowMonitorCategory Then
                If Database.GetFieldInteger(dr!MonitorCatAPk) = 0 Then
                  .AddText("")
                Else
                  MonitorCategory = finBL.MonitorCategories.ItemByPk(Database.GetFieldInteger(dr!MonitorCatAPk))
                  .AddText("{{colourblock|" &amp; MonitorCategory.ColourBackground &amp; "}} " &amp; MonitorCategory.MonitorCategoryId)
                End If
              End If

              If ShowTasks Then
                If Database.GetFieldInteger(dr!TaskCount) = 0 Then
                  .AddText("")
                Else
                  With .AddInteger(Database.GetFieldInteger(dr!TaskCount))
                    .Hyperlink = "javascript:ShowAccountTasks(" &amp; Database.GetFieldInteger(dr!Pk) &amp; ")"
                  End With
                End If
              End If
            End With
          End With
        Loop
        Database.DataReaderClose(dr)
      End With
    Else
      Success = False
    End If
  End If

  ' Error?
  If Not Success Then
    SummaryTable.TextBefore = "{{error|" &amp; finBL.Error.Message &amp; "}}"
  End If

  Return SummaryTable

End Function

Private Function GetSummaryTable_AccountApp(page As String,
                                            columns As ISList,
                                            includeAll As Boolean,
                                            highlightRowsWithTasks As Boolean) As ISSummaryTable

  Dim ClosedDays As Integer
  Dim Database As ISDatabaseBL
  Dim DateColumnDescription As String
  Dim DateColumnName As String
  Dim dr As IDataReader
  Dim MonitorCategory As finMonitorCategoryRO
  Dim ShowAccountType As Boolean
  Dim ShowBroker As Boolean
  Dim ShowDateAndTime As Boolean
  Dim ShowDealer As Boolean
  Dim ShowEmployee As Boolean
  Dim ShowMonitorCategory As Boolean
  Dim ShowStatus As Boolean
  Dim ShowStatusIcon As Boolean
  Dim ShowStatusSub As Boolean
  Dim ShowTasks As Boolean
  Dim sqb As ISSelectQueryBuilder
  Dim Status As isefinAccountAppStatus
  Dim SummaryTable As ISSummaryTable
  Dim Success As Boolean
  Dim XPEmployeeFieldName As String
  Dim XPFieldName As String

  ' Assume Success
  Success = True

  ' Initialise
  Database = finBL.Database
  SummaryTable = finBL.CreateSummaryTable()

  ' Get Parameters
  ' NOTE: Use the module mCombinedParameters since this contains Startup and event Parameters in a single Key/Value List
  With mCombinedParameters
    ClosedDays = .GetInteger("ClosedDays")
  End With

  ' Determine External Party fields to use
  Select Case mCurrentUserInformation.ExternalPartyType
    Case isefinExternalPartyType.Broker
      XPFieldName = "BrokerExPartyPk"
      XPEmployeeFieldName = "BrokerExPartyEmployeePk"

    Case isefinExternalPartyType.Dealer
      XPFieldName = "DealerExPartyPk"
      XPEmployeeFieldName = "DealerExPartyEmployeePk"

    Case Else
      XPFieldName = "DealerExPartyPk"
      XPEmployeeFieldName = "DealerExPartyEmployeePk"
  End Select

  ' Determine Columns to Include
  ShowAccountType = columns.Exists("Account Type", True)
  ShowBroker = columns.Exists("Broker", True)
  ShowDateAndTime = columns.Exists("Date and Time", True)
  ShowDealer = columns.Exists("Dealer", True)
  ShowEmployee = includeAll
  ShowMonitorCategory = columns.Exists("Monitor Category", True)
  ShowStatus = columns.Exists("Status", True)
  ShowStatusIcon = columns.Exists("Status Icon", True)
  ShowStatusSub = columns.Exists("Sub Status", True)
  ShowTasks = columns.Exists("Tasks", True)

  Select Case UCase(page)
    Case "QUOTES"
      DateColumnName = "Date"
      DateColumnDescription = "Date"

    Case "CLOSED", "REJECTED"
      DateColumnName = "DateClosed"
      DateColumnDescription = "Closed"
  End Select

  ' Build Query
  If Success Then
    sqb = Database.CreateSelectQueryBuilder()
    With sqb
      .Table = "AccountApp"
      .Fields.AddList("AccountApp.Pk,AccountApp.AccountAppId,AccountApp.AccountAppTypePk,AccountApp.BrokerExPartyPk,AccountApp.DateClosed,AccountApp.DealerExPartyPk,AccountApp.CreatedUtcDate,AccountApp.MonitorCatAPk,AccountApp.Name,AccountApp.Status,AccountApp.StatusSub")
      If ShowTasks Then
        With .Fields.AddSubQuery("TaskCount").SubQueryBuilder
          .Table = "AccountAppLog"
          .Fields.AddCount()

          With .SqlWhere
            .AppendComparisonField("AccountApp.Pk", "=", "AccountAppLog.AccountAppPk")
            .AppendComparisonNotNull("ActionUtcDate")
            .AppendComparisonNull("ActionCompleteUtcDate")
          End With
        End With
      End If

      ' SQL Where
      With .SqlWhere
        ' Page-Specific
        Select Case UCase(page)
          Case "QUOTES"
            ' ------
            ' Quotes
            ' ------
            .BlockBegin(iseSqlWhereBuilderNestedBlockType.OrBlock)
            .AppendComparisonInteger("AccountApp.Status", "=", isefinAccountAppStatus.Incomplete)
            .AppendComparisonInteger("AccountApp.Status", "=", isefinAccountAppStatus.Complete)
            .AppendComparisonInteger("AccountApp.Status", "=", isefinAccountAppStatus.Reviewing)
            .BlockEnd()

          Case "REJECTED"
            ' --------
            ' Rejected
            ' --------
            .BlockBegin(iseSqlWhereBuilderNestedBlockType.OrBlock)
            .AppendComparisonInteger("AccountApp.Status", "=", isefinAccountAppStatus.Declined)
            .AppendComparisonInteger("AccountApp.Status", "=", isefinAccountAppStatus.Unwanted)
            .BlockEnd()

            ' Closed in past 30 days only
            .AppendComparisonDate("AccountApp.DateClosed", "&gt;=", finBL.TimeZoneFunctions.GetCurrentDatabaseDate().AddDays(-ClosedDays))

          Case "CLOSED"
            ' ------
            ' Closed
            ' ------
            .AppendComparisonInteger("AccountApp.Status", "=", isefinAccountAppStatus.Accepted)

            ' Closed in past 30 days only
            .AppendComparisonDate("AccountApp.DateClosed", "&gt;=", finBL.TimeZoneFunctions.GetCurrentDatabaseDate().AddDays(-ClosedDays))

          Case Else
            Success = False
            finBL.Error.ErrorBeginFormat("Unhandled Account Application Page '{0}'.", Page)
        End Select

        ' Restrict to External Party
        If mCurrentUserInformation.IsExternalUser Then
          ' External Party
          .AppendComparisonInteger(XPFieldName, "=", mCurrentUserInformation.ExternalPartyPk)

          ' Current Employee only
          If Not includeAll Then .AppendComparisonInteger(XPEmployeeFieldName, "=", mCurrentUserInformation.ExternalPartyEmployeePk)
        End If

        ' User Filters
        .Append(mCurrentUserInformation.FilterAccountAppSqlWhere)
      End With

      ' Employee User
      If Len(XPEmployeeFieldName) &lt;&gt; 0 Then
        Select Case mCurrentUserInformation.ExternalPartyType
          Case isefinExternalPartyType.Broker
            ' Broker
            .Fields.Add("ClientEmployment.ClientEmploymentId")
            .Joins.Add("ClientEmployment", "ClientEmployment.Pk", "AccountApp.BrokerExPartyEmployeePk", iseSelectQueryJoinType.Left)

          Case isefinExternalPartyType.Dealer
            ' Dealer
            .Fields.Add("ClientEmployment.ClientEmploymentId")
            .Joins.Add("ClientEmployment", "ClientEmployment.Pk", "AccountApp.DealerExPartyEmployeePk", iseSelectQueryJoinType.Left)

          Case Else
            ' None
            .Fields.Add("ClientEmployment.ClientEmploymentId")
            .Joins.Add("ClientEmployment", "ClientEmployment.Pk", "AccountApp.DealerExPartyEmployeePk", iseSelectQueryJoinType.Left)
        End Select
      End If

      ' Order By
      With .OrderByFields
        .Add("AccountApp.CreatedUtcDate")
      End With
    End With
  End If

  ' Execute Query and get Results
  If Success Then
    If sqb.ExecuteDisconnectedDataReader(dr) Then
      ' Initialise Summary Table
      With SummaryTable
        .TableClass = iseSummaryTableClass.TabularData
        .AutoStripe = True

        With .Columns
          If ShowStatusIcon Then.AddBoolean(" ") ' Icon
          If ShowDateAndTime AndAlso DateColumnName = "Date" Then
            .AddDateTime("Date")
          Else
            .AddDate(DateColumnDescription)
          End If
          If ShowEmployee Then .AddCode("Employee", 5)
          .AddCode("Code", 5)
          .AddText("Name")
          If ShowAccountType Then .AddCode("Type", 5)
          If ShowDealer Then .AddCode("Dealer", 5)
          If ShowBroker Then .AddCode("Broker", 5)
          If ShowStatus Then .AddCode("Status", 10)
          If ShowStatusSub Then .AddCode("Sub-Status", 10)
          If ShowMonitorCategory Then .AddCode("Monitor", 5)
          If ShowTasks Then .AddInteger("Tasks", 3)
        End With

        ' Add Rows
        Do While dr.Read()
          ' Initialise
          Status = DirectCast(Database.GetFieldEnum(dr!Status, GetType(isefinAccountAppStatus)), isefinAccountAppStatus)

          With .Rows.Add()
            ' Row Class
            If ShowTasks AndAlso HighlightRowsWithTasks AndAlso Database.GetFieldInteger(dr!TaskCount) &lt;&gt; 0 Then
              .BackgroundColour = "yellow"
            End If

            With .Cells
              If ShowStatusIcon Then
                .AddText("{{icon|AccountApp_Status" &amp; Status.ToString() &amp; "|" &amp; finBL.Enums.isefinAccountAppStatus_ToString(Status) &amp; "}}")
              End If

              If ShowDateAndTime AndAlso DateColumnName = "Date" Then
                .AddDateTime(finBL.TimeZoneFunctions.ConvertUtcToDatabaseDateTime(Database.GetFieldUtcDate(dr!CreatedUtcDate)))
              Else
                If DateColumnName = "Date" Then
                  .AddDate(finBL.TimeZoneFunctions.ConvertUtcToDatabaseDateTime(Database.GetFieldUtcDate(dr!CreatedUtcDate)))
                Else
                  .AddDate(finBL.TimeZoneFunctions.ConvertUtcToDatabaseDateTime(Database.GetFieldDate(dr(DateColumnName))))
                End If
              End If

              If ShowEmployee Then .AddText(Database.GetFieldString(dr!ClientEmploymentId))

              With .AddText(Database.GetFieldString(dr!AccountAppId))
                .HyperlinkSetFormShow("AccountApps", Database.GetFieldString(dr!AccountAppId))
              End With
              .AddText(Database.GetFieldString(dr!Name))

              If ShowAccountType Then .AddText(finBL.AccountAppTypes.ItemByPk(Database.GetFieldInteger(dr!AccountAppTypePk)).AccountAppTypeId)

              If ShowDealer Then
                If Database.GetFieldInteger(dr!DealerExPartyPk) = 0 Then
                  .AddText("")
                Else
                  .AddText(finBL.ExternalParties.ItemByPk(Database.GetFieldInteger(dr!DealerExPartyPk)).ExternalPartyId)
                End If
              End If

              If ShowBroker Then
                If Database.GetFieldInteger(dr!BrokerExPartyPk) = 0 Then
                  .AddText("")
                Else
                  .AddText(finBL.ExternalParties.ItemByPk(Database.GetFieldInteger(dr!BrokerExPartyPk)).ExternalPartyId)
                End If
              End If

              If ShowStatus Then .AddText(finBL.Enums.isefinAccountAppStatus_ToString(DirectCast(Database.GetFieldEnum(dr!Status, GetType(isefinAccountAppStatus)), isefinAccountAppStatus)))
              If ShowStatusSub Then .AddText(Database.GetFieldString(dr!StatusSub))

              If ShowMonitorCategory Then
                If Database.GetFieldInteger(dr!MonitorCatAPk) = 0 Then
                  .AddText("")
                Else
                  MonitorCategory = finBL.MonitorCategories.ItemByPk(Database.GetFieldInteger(dr!MonitorCatAPk))
                  .AddText("{{colourblock|" &amp; MonitorCategory.ColourBackground &amp; "}} " &amp; MonitorCategory.MonitorCategoryId)
                End If
              End If

              If ShowTasks Then
                If Database.GetFieldInteger(dr!TaskCount) = 0 Then
                  .AddText("")
                Else
                  With .AddInteger(Database.GetFieldInteger(dr!TaskCount))
                    .Hyperlink = "javascript:ShowAccountAppTasks(" &amp; Database.GetFieldInteger(dr!Pk) &amp; ")"
                  End With
                End If
              End If
            End With
          End With
        Loop
        Database.DataReaderClose(dr)
      End With
    Else
      Success = False
    End If
  End If

  ' Error?
  If Not Success Then
    SummaryTable.TextBefore = "{{error|" &amp; finBL.Error.Message &amp; "}}"
  End If

  Return SummaryTable

End Function

Private Function GetAccountTasks(parametersJson As String,
                                 ByRef returnValue As String) As Boolean

  Dim Account As finAccount
  Dim Log As finLogRO
  Dim Pk As Integer
  Dim Success As Boolean
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Assume Success
  Success = True

  ' Initialise
  SummaryTable = finBL.CreateSummaryTable()
  SummaryTables = finBL.CreateSummaryTables()
  SummaryTables.Add("Main", SummaryTable)

  ' Get Parameters
  ' NOTE: Use the module mCombinedParameters since this contains Startup and event Parameters in a single Key/Value List
  With mCombinedParameters
    Pk = .GetInteger("Pk")
  End With

  ' Validate
  If Success Then
  End If

  ' Load Account
  If Success Then
    Account = finBL.CreateAccount()
    Success = Account.LoadPk(pk)
  End If

  ' Create Summary Table to display outstanding Tasks
  If Success Then
    With SummaryTable
      .TableClass = iseSummaryTableClass.TabularData
      .AutoStripe = True

      ' Columns
      With .Columns
        .AddBoolean("!") ' Log Severity Icon
        .AddDateTime("Date")
        .AddText("Subject")
        .AddText("Notes").MaxDisplayChars = 100
      End With

      ' Add Rows
      For Each Log In Account.Logs
        If Log.ActionUtcDate &lt;&gt; Nothing AndAlso Log.ActionCompleteUtcDate = Nothing Then
          With .Rows.Add()
            With .Cells()
              If Log.LogSeverityPk = 0 Then
                .AddText("")
              Else
                .AddText("{{colourblock|" &amp; Log.LogSeverity.OpenColourBackground &amp; "|" &amp; Log.LogSeverity.LogSeverityId &amp; ": " &amp; log.LogSeverity.Description &amp; "}}")
              End If

              .AddDateTime(Log.LogTzDate)

              With .AddText(Log.Subject)
                Select Case Log.LogClass
                  Case isefinLogClass.Account
                    .HyperlinkSetFormShow("AccountLog", CStr(Log.Pk))
                  Case isefinLogClass.AccountApp
                    .HyperlinkSetFormShow("AccountAppLog", CStr(Log.Pk))
                End Select
              End With

              .AddText(Log.NotesResolved)
            End With
          End With
        End If
      Next
    End With

    ' Finalise
    returnValue = GetHtmlFromSummaryTables(SummaryTables)
  End If

  Return Success

End Function

Private Function GetAccountAppTasks(parametersJson As String,
                                    ByRef returnValue As String) As Boolean

  Dim AccountApp As finAccountApp
  Dim Log As finLogRO
  Dim Pk As Integer
  Dim Success As Boolean
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Assume Success
  Success = True

  ' Initialise
  SummaryTable = finBL.CreateSummaryTable()
  SummaryTables = finBL.CreateSummaryTables()
  SummaryTables.Add("Main", SummaryTable)

  ' Get Parameters
  ' NOTE: Use the module mCombinedParameters since this contains Startup and event Parameters in a single Key/Value List
  With mCombinedParameters
    Pk = .GetInteger("Pk")
  End With

  ' Validate
  If Success Then
  End If

  ' Load Account Application
  If Success Then
    AccountApp = finBL.CreateAccountApp()
    Success = AccountApp.LoadPk(pk)
  End If

  ' Create Summary Table to display outstanding Tasks
  If Success Then
    With SummaryTable
      .TableClass = iseSummaryTableClass.TabularData
      .AutoStripe = True

      ' Columns
      With .Columns
        .AddBoolean("!") ' Log Severity Icon
        .AddDateTime("Date")
        .AddText("Subject")
        .AddText("Notes").MaxDisplayChars = 100
      End With

      ' Add Rows
      For Each Log In AccountApp.Logs
        If Log.ActionUtcDate &lt;&gt; Nothing AndAlso Log.ActionCompleteUtcDate = Nothing Then
          With .Rows.Add()
            With .Cells()
              If Log.LogSeverityPk = 0 Then
                .AddText("")
              Else
                .AddText("{{colourblock|" &amp; Log.LogSeverity.OpenColourBackground &amp; "|" &amp; Log.LogSeverity.LogSeverityId &amp; ": " &amp; log.LogSeverity.Description &amp; "}}")
              End If

              .AddDateTime(Log.LogTzDate)

              With .AddText(Log.Subject)
                Select Case Log.LogClass
                  Case isefinLogClass.AccountApp
                    .HyperlinkSetFormShow("AccountAppLog", CStr(Log.Pk))
                  Case isefinLogClass.Client
                    .HyperlinkSetFormShow("ClientLog", CStr(Log.Pk))
                End Select
              End With

              .AddText(Log.NotesResolved)
            End With
          End With
        End If
      Next
    End With

    ' Finalise
    returnValue = GetHtmlFromSummaryTables(SummaryTables)
  End If

  Return Success

End Function

Private Function GetHtmlFromSummaryTables(summaryTables As ISSummaryTables) As String

  Dim sb As finHtmlSummaryPage2StringBuilder

  sb = finBL.CreateHtmlSummaryPage2StringBuilder()
  With sb
    .Initialise(iseSummaryPageTarget.WebInternal, False, False, True)

    .HtmlHeaderBegin()
    .HtmlHeaderEnd()

    .SummaryTablesAppend(SummaryTables)

    .HtmlFinalise()
  End With

  Return sb.ToString(True)

End Function</Code>
    <Language>VisualBasic</Language>
    <Notes>System defined HTML Widget to list Accounts and Applications for the current External User.

Supports being used in the Tasks View.</Notes>
    <PermissionKeyExecute />
    <RunWithoutPrompts>false</RunWithoutPrompts>
    <TemplateText>&lt;div id="frmMain" class="is-widget-content"&gt;

  &lt;!-- Form Header --&gt;
  &lt;header&gt;
    &lt;!-- Tabs --&gt;
    &lt;div id="tabDetails" class="is-tabs"&gt;
      &lt;ul&gt;
        &lt;li tabId="Quotes"&gt;Quotes&lt;/li&gt;
        &lt;li tabId="Open"&gt;Open&lt;/li&gt;
        &lt;li tabId="Rejected"&gt;Rejected&lt;/li&gt;
        &lt;li tabId="Closed"&gt;Closed&lt;/li&gt;
      &lt;ul&gt;
    &lt;/div&gt;
  &lt;/header&gt;


  &lt;!-- Pages --&gt;
  &lt;div class="is-widget-form-body"&gt;
    &lt;!-- Quotes --&gt;
    &lt;div id="pageQuotes" class="is-tab-page"&gt;&lt;/div&gt;


    &lt;!-- Open --&gt;
    &lt;div id="pageOpen" class="is-tab-page"&gt;&lt;/div&gt;


    &lt;!-- Rejected --&gt;
    &lt;div id="pageRejected" class="is-tab-page"&gt;&lt;/div&gt;


    &lt;!-- Closed --&gt;
    &lt;div id="pageClosed" class="is-tab-page"&gt;&lt;/div&gt;
  &lt;/div&gt;


  &lt;!-- Form Footer --&gt;
  &lt;footer&gt;
    &lt;button id="cmdShowAll" class="is-button" style="display:none"&gt;Show All Employees&lt;/button&gt;
    &lt;button id="cmdRefresh" class="is-button ok"&gt;Refresh&lt;/button&gt;
  &lt;/footer&gt;

&lt;/div&gt;


&lt;script&gt;
// Server-side information
var mAllowShowAll = &lt;%AllowShowAll%&gt;;

// Form
var frmMain;
var tabDetails;

// Elements
var cmdShowAll;

// Other
var mShowAll = false;


// Initialise
$(function () {
  // Create Widget form
  frmMain = new widget.UI.Form("frmMain", { captionWidth: "9em", textboxWidth: "20em"});

  // Create Tabs
  tabDetails = new widget.UI.Tabs("tabDetails", {style: "normal", onSelectedTabChanged: function () { RefreshCurrentPage(false); }});

  // Handle Buttons
  $("#cmdRefresh").click(function () { RefreshCurrentPage(true); });
  if (mAllowShowAll) {
    cmdShowAll = $("#cmdShowAll");
    cmdShowAll.fadeIn();
    cmdShowAll.click(function () { ShowAllToggle(); });
  }

  // Refresh
  RefreshCurrentPage(true);
});

// ====================
// Refresh Current Page
// ====================
function RefreshCurrentPage(forceRefresh) {
  // Get Page
  var page = $("#page" + tabDetails.SelectedTabId());

  // Refresh?
  if (!forceRefresh &amp;&amp; page.html()) return;

  // Clear content
  page.html("Refreshing...");

  // Block UI
  widget.UI.Block("Please wait...");

  // Create parameters
  var params = { page: tabDetails.SelectedTabId(), includeAll: mShowAll };

  // Get Page Details
  widget.GetString("GetPageDetails",
                   params,
                   function(data) { RefreshCurrentPage_Done(data, page); },
                   function(data) { RefreshCurrentPage_Fail(data, page); });
}

function RefreshCurrentPage_Done(data, page) {
  page.html(data);

  // Unblock UI
  widget.UI.Unblock();
}

function RefreshCurrentPage_Fail(data, page) {
  page.html(data);

  // Unblock UI
  widget.UI.Unblock();
}

// ===============
// Toggle Show All
// ===============
function ShowAllToggle() {
  mShowAll = !mShowAll;
  if (mShowAll) {
    cmdShowAll.text("Hide All Employees");
  }
  else {
    cmdShowAll.text("Show All Employees");
  }

  // Invalidate all pages
  $(".is-tab-page").html("");

  // Refresh Page
  RefreshCurrentPage(true);
}

// ===============================================================
// Show Account Tasks (called when clicking link in Summary Table)
// ===============================================================
function ShowAccountTasks(pk) {
  // Get Task Details
  widget.GetString("GetAccountTasks", { pk: pk}, ShowAccountTasks_Done, ShowAccountTasks_Fail);
}

function ShowAccountTasks_Done(data) {
  // Use Application Shortcut to show Popup
  widget.ExecuteApplicationShortcutUrl("app://HtmlShow?title=Task Summary&amp;html=" + encodeURIComponent(data));
}

function ShowAccountTasks_Fail(errorMessage) {
  window.alert(errorMessage)
}

// ===========================================================================
// Show Account Application Tasks (called when clicking link in Summary Table)
// ===========================================================================
function ShowAccountAppTasks(pk) {
  // Get Task Details
  widget.GetString("GetAccountAppTasks", { pk: pk}, ShowAccountAppTasks_Done, ShowAccountAppTasks_Fail);
}

function ShowAccountAppTasks_Done(data) {
  // Use Application Shortcut to show Popup
  widget.ExecuteApplicationShortcutUrl("app://HtmlShow?title=Task Summary&amp;html=" + encodeURIComponent(data));
}

function ShowAccountAppTasks_Fail(errorMessage) {
  window.alert(errorMessage)
}
&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>-t+PZDaZpkaVC4B3YxnCLg</UniqueId>
    <AllowRefresh>true</AllowRefresh>
    <Caption>Applications &amp; Accounts</Caption>
    <HtmlWidgetMaxHeight>0</HtmlWidgetMaxHeight>
    <HtmlWidgetMaxWidth>0</HtmlWidgetMaxWidth>
    <HtmlWidgetNeverApplyStyling>false</HtmlWidgetNeverApplyStyling>
    <HtmlWidgetResourceCssSummaryPage2>true</HtmlWidgetResourceCssSummaryPage2>
    <HtmlWidgetResourceCssWidget>true</HtmlWidgetResourceCssWidget>
    <HtmlWidgetResourceJQuery>true</HtmlWidgetResourceJQuery>
    <HtmlWidgetResourceJQueryVersion />
    <HtmlWidgetSpecialEventGetFolderCount>false</HtmlWidgetSpecialEventGetFolderCount>
    <Icon />
    <RestrictedOriginsListEnabled>false</RestrictedOriginsListEnabled>
    <RunAsAdministrator>false</RunAsAdministrator>
    <WebServiceName />
    <WebServiceAllowAnonymous>false</WebServiceAllowAnonymous>
    <WebServiceSendDebugInformation>true</WebServiceSendDebugInformation>
    <ShowInMenu>None</ShowInMenu>
    <ParametersType>Custom</ParametersType>
    <Parameters>
      <ISParameterDefs version="1.00">
        <Parameters>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>Specify optional Columns to include.</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="Columns" type="CheckList">
            <BlankTip />
            <Caption>Columns</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Status,Monitor Category,Tasks</Value>
            <Visible>true</Visible>
            <List>Status Icon,Date and Time,Account Type,Broker,Dealer,Account Manager,Status,Sub Status,Monitor Category,Tasks</List>
            <LimitToList>true</LimitToList>
            <MaxLength>0</MaxLength>
            <Rows>8</Rows>
          </Parameter>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>Specify other display options.</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="HighlightRowsWithTasks" type="Boolean">
            <BlankTip />
            <Caption>Highlight rows with Tasks?</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>True</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="ClosedDays" type="Number">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>30</Value>
            <Visible>true</Visible>
            <DecimalPlaces>0</DecimalPlaces>
            <GroupDigits>true</GroupDigits>
            <MaxValue>365</MaxValue>
            <MinValue>1</MinValue>
            <NumberSpecialType>None</NumberSpecialType>
            <SpinChange>1</SpinChange>
          </Parameter>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>Tasks View support.</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="TasksUserId" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <List>RANGE.Users</List>
            <LimitToList>false</LimitToList>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
        </Parameters>
      </ISParameterDefs>
    </Parameters>
  </finScript>