<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2024-05-14T00:35:05.0000000">
    <CreatedUserId>Admin</CreatedUserId>
    <CreatedUtcDate>2019-07-16T03:21:54.0470000</CreatedUtcDate>
    <UpdatedUserId>Admin</UpdatedUserId>
    <UpdatedUtcDate>2024-05-14T00:34:50.9340000</UpdatedUtcDate>
    <ScriptId>UDASH</ScriptId>
    <Description>User Dashboard 1</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_UserDashboard1
Option Explicit On
Option Strict On

' #################################################################
' User Dashboard HTML Widget
'
' Version: 1.10 (14/05/2024)
'
' Usage: System-defined HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.04  16/01/2020  ISS                Update
'    1.05  11/05/2022  ISS      J028712   Removed obsoleted Functions
'    1.06  25/10/2022  ISS      J029700   Updated to use TM 2 functionality
'    1.07  14/08/2023  ISS      J030431   Ability to show all "Open" Accounts to Users in a specific Role
'    1.08  27/09/2023  ISS      J032117   'Quotes &amp; Applications' page in the 'DisplayPages' Parameter fixed
'          16/10/2023  ISS      J029702   Updated to use Apex charts instead of Google charts
'    1.09  06/12/2023  ISS      J032560   Visual glitch when first loaded
'          13/12/2023  ISS      J032631   Updated to clear all window timers
'    1.10  14/05/2024  ISS      J033476   JavaScript error in split() method in TasksRefreshInternal
' #################################################################

' Parameters
Private mOpenAccountsAllRoleId As String
Private mPollSeconds As Integer = 30
Private mRecentDays As Integer = 30
Private mTasksUpcomingDays As Integer = 7

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

' Other
Private mHostingContext As isefinHtmlWidgetHostingContext
Private mUserId As String
Private mUserPk As Integer

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

  ' Initialise
  mHostingContext = hostingContext

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

  ' Get Common Parameters
  With mCombinedParameters
    mOpenAccountsAllRoleId = .GetString("OpenAccountsAllRoleId", mOpenAccountsAllRoleId)
    mRecentDays = .GetInteger("RecentDays", mRecentDays)
    mTasksUpcomingDays = .GetInteger("TasksUpcomingDays", mTasksUpcomingDays)
  End With

  ' 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
  If finBL.Users.Exists(mUserId) Then  mUserPk = finBL.Users(mUserId).Pk

  ' Handle Events
  Select Case eventId
    Case ""
      ' Main event, i.e., return initial HTML content (excluding html and body tags)
      ' NOTE: Reslove templates so icons are displayed for the various sections
      returnValue = finBL.ResolveHtmlTemplates2(ScriptInfo.TemplateText, ScriptInfo.Target)

    Case "GetInitialisationInfo"
      ' Get Initialisation Information for this Widget
      Main = GetInitialisationInfo(returnValue)
  End Select

End Function

''' &lt;summary&gt;
'''  Get Initialisation Information required for this wizard.
''' &lt;/summary&gt;
Public Function GetInitialisationInfo(ByRef response As String) As Boolean

  Dim AccountAppTypeId As String
  Dim CurrentUserInformation As finCurrentUserInformation
  Dim DepositAccountTypeId As String
  Dim DisplayPages As ISList
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim HomeBoxes As ISList
  Dim ListMonitoredAccounts As List(Of MonitoredAccount)
  Dim ListOpenAccounts As List(Of OpenAccount)
  Dim ListQuoteAccounts As List(Of QuoteAccount)
  Dim ListRecent As List(Of RecentRecord)
  Dim ListWorkflows As List(Of Workflow)
  Dim LoanAccountTypeId As String
  Dim QuickButtons As ISList
  Dim QuickButtonActions As ISCodeDescriptionList
  Dim QuickQuoteScriptId As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Validate

  ' Get Parameters
  With mCombinedParameters
    AccountAppTypeId = .GetString("AccountAppTypeId")
    DepositAccountTypeId = .GetString("DepositAccountTypeId")
    LoanAccountTypeId = .GetString("LoanAccountTypeId")
    QuickQuoteScriptId = .GetString("QuickQuoteScriptId")

    DisplayPages = .GetListFromGroupingList("DisplayPages")
    If DisplayPages.Count = 0 Then DisplayPages.FromCsvString("Tasks Due,Upcoming Tasks,Quotes and Applications,Open Accounts,Monitored Accounts,Workflows")
    DisplayPages.FromCsvString(Replace(DisplayPages.ToCsvString(), " ", "")) ' Remove spaces for matching tabIds in JavaScript

    HomeBoxes = .GetListFromGroupingList("HomeBoxes")
    If HomeBoxes.Count = 0 Then HomeBoxes.FromCsvString("Tasks Due,Upcoming Tasks,Open Accounts,Quotes and Applications,Monitored Accounts A,Monitored Accounts B,Added Recently,Updated Recently")
    HomeBoxes.FromCsvString(Replace(HomeBoxes.ToCsvString(), " ", "")) ' Remove spaces for matching boxIds in JavaScript

    QuickButtons = .GetListFromGroupingList("QuickButtons")
    If QuickButtons.Count = 0 Then
      QuickButtons.Add("Quick Quote")
      If finBL.Settings.AddOns.AccountApplication AndAlso Len(AccountAppTypeId) &lt;&gt; 0 Then
        QuickButtons.Add("New Application")
      End If
      If Len(LoanAccountTypeId) &lt;&gt; 0 Then
        QuickButtons.Add("New Loan")
      End If
      If finBL.Settings.AddOns.DepositAccount AndAlso Len(DepositAccountTypeId) &lt;&gt; 0 Then
        QuickButtons.Add("New Deposit")
      End If
    End If
    QuickButtons.FromCsvString(Replace(QuickButtons.ToCsvString(), " ", "")) ' Remove spaces for matching buttonIds in JavaScript
  End With

  ' Initialise
  QuickButtonActions = finBL.Runtime.CreateCodeDescriptionList()

  ' Configuration and Licensing
  If Not finBL.Settings.AddOns.Workflow Then DisplayPages.Remove("Workflows")

  ' Get Initialisation Info
  If Success Then
    FormInitialisationInfo = New FormInitialisationInfo()
    With FormInitialisationInfo
      ' -------
      ' General
      ' -------
      If StrComp(mUserId, finBL.CurrentUser.UserId, CompareMethod.Text) = 0 Then
        CurrentUserInformation = finBL.CurrentUserInformation
      Else
        finBL.Users.ItemByPkSafe(mUserPk).GetCurrentUserInformation(CurrentUserInformation)
      End If

      .UserDetails = CurrentUserInformation.UserId
      If Len(CurrentUserInformation.ExternalPartyId) &lt;&gt; 0 Then .UserDetails &amp;= " (" &amp; CurrentUserInformation.ExternalParty.Name &amp; ")"
      .UserName = CurrentUserInformation.UserName
      If CurrentUserInformation.UserLevel = iseUserLevel.Administrator AndAlso CurrentUserInformation.UserName = "Administrator" Then
        .UserInitials = "ADMIN"
      Else
        .UserInitials = CurrentUserInformation.GetUserInitials()
      End If
      .Statistics = GetStatistics()

      ' -------------------------------------
      ' Pages (including data for Home Boxes)
      ' -------------------------------------
      If DisplayPages.Exists("TasksDue") OrElse HomeBoxes.Exists("TasksDue") Then
        GetTasksInternal(.Tasks, .TasksMaxSizeExceeded)
      End If

      If DisplayPages.Exists("UpcomingTasks") OrElse HomeBoxes.Exists("UpcomingTasks") Then
        'TODO:
        GetTasksUpcomingInternal(.TasksUpcoming, .TasksUpcomingMaxSizeExceeded)
      End If

      If DisplayPages.Exists("QuotesandApplications") OrElse HomeBoxes.Exists("QuotesandApplications") Then
        GetQuoteAccountsInternal(ListQuoteAccounts)
        .QuoteAccounts = ListQuoteAccounts
        If finBL.Settings.AddOns.AccountApplication  Then
          GetAccountAppsInternal(ListQuoteAccounts)
          .AccountApps = ListQuoteAccounts
        End If
      End If

      If DisplayPages.Exists("OpenAccounts") OrElse HomeBoxes.Exists("OpenAccounts") Then
        GetOpenAccountsInternal(ListOpenAccounts)
        .OpenAccounts = ListOpenAccounts
      End If

      If DisplayPages.Exists("MonitoredAccounts") OrElse HomeBoxes.Exists("MonitoredAccountsA") OrElse HomeBoxes.Exists("MonitoredAccountsB") OrElse HomeBoxes.Exists("MonitoredAccountsC") Then
        If finBL.Settings.MonitorCategoryAUse Then
          GetMonitoredAccountsInternal("A", ListMonitoredAccounts)
          .MonitoredAccountsA = ListMonitoredAccounts
        End If
        If finBL.Settings.MonitorCategoryBUse Then
          GetMonitoredAccountsInternal("B", ListMonitoredAccounts)
          .MonitoredAccountsB = ListMonitoredAccounts
        End If
        If finBL.Settings.MonitorCategoryCUse Then
          GetMonitoredAccountsInternal("C", ListMonitoredAccounts)
          .MonitoredAccountsC = ListMonitoredAccounts
        End If
      End If

      If finBL.Settings.AddOns.Workflow AndAlso DisplayPages.Exists("Workflows") Then
        GetWorkflowsInternal(ListWorkflows)
        .Workflows = ListWorkflows
      End If

      ' ----------
      ' Home Boxes
      ' ----------
      If HomeBoxes.Exists("AddedRecently") AndAlso .RecentlyAdded Is Nothing Then
        GetRecentlyAddedInternal(ListRecent)
        .RecentlyAdded = ListRecent
      End If

      If HomeBoxes.Exists("UpdatedRecently") AndAlso .RecentlyUpdated Is Nothing Then
        GetRecentlyUpdatedInternal(ListRecent)
        .RecentlyUpdated = ListRecent
      End If

      ' -------------
      ' Quick Buttons
      ' -------------
      If QuickButtons.Exists("QuickQuote") Then
        If Len(QuickQuoteScriptId) = 0 Then
          ' New Account wizard (in Quote Mode)
          QuickButtonActionsAdd(QuickButtonActions, "QuickQuote", "HtmlWidget:AccountNew", "{quoteMode:true}")
        Else
          QuickButtonActionsAdd(QuickButtonActions, "QuickQuote", QuickQuoteScriptId, "")
        End If
      End If

      If QuickButtons.Exists("NewApplication") AndAlso finBL.AccountAppTypes.Exists(AccountAppTypeId) Then
        With finBL.AccountAppTypes(AccountAppTypeId)
          ' Ensure Account Application can be created via an HTML Widget
          If Len(.HtmlWidgetScriptIdResolved(isefinAccountAppDataCaptureType.Creation)) &lt;&gt; 0 Then
            QuickButtonActionsAdd(QuickButtonActions, "NewApplication", .HtmlWidgetScriptIdResolved(isefinAccountAppDataCaptureType.Creation), "{accountAppTypeId: '" &amp; accountAppTypeId &amp; "'}")
          End If
        End With
      End If

      If QuickButtons.Exists("NewLoan") AndAlso finBL.AccountTypes.Exists(LoanAccountTypeId) Then
        QuickButtonActionsAdd(QuickButtonActions, "NewLoan", finBL.CloudConnectFunctions.GetAccountHtmlWidgetId(isefinCloudConnectAccountScriptType.HtmlWidgetAccountNew, False), "{accountType: '" &amp; LoanAccountTypeId &amp; "'}")
      End If

      If QuickButtons.Exists("NewDeposit") AndAlso finBL.AccountTypes.Exists(DepositAccountTypeId) Then
        QuickButtonActionsAdd(QuickButtonActions, "NewDeposit", finBL.CloudConnectFunctions.GetAccountHtmlWidgetId(isefinCloudConnectAccountScriptType.HtmlWidgetAccountNew, False), "{accountType: '" &amp; DepositAccountTypeId &amp; "'}")
      End If

      ' Configuration
      .AddOns_AccountApplication = finBL.Settings.AddOns.AccountApplication
      .CurrentDbDate = finBL.HtmlWidgetUtilities.GetJsonUtcDateTimeFromDatabaseDateTime(finBL.TimeZoneFunctions.GetCurrentDatabaseDate())
      .DisplayPages = DisplayPages.ToList()
      .HomeBoxes = HomeBoxes.ToList()
      .PollSeconds = mPollSeconds
      .QuickButtons = QuickButtons.ToList()
      .QuickButtonActions = QuickButtonActions.ToJsonObject()
      .TasksUpcomingDays = mTasksUpcomingDays
    End With
  End If

  ' Response
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(FormInitialisationInfo, response)
  End If

  Return Success

End Function

Private Sub QuickButtonActionsAdd(actions As ISCodeDescriptionList,
                                  code As String,
                                  htmlWidgetId As String,
                                  startupParametersJson As String)

  Dim AppShortcut As ISApplicationShortcut

  AppShortcut = finBL.CreateApplicationShortcutHtmlWidget(htmlWidgetId)
  If Len(startupParametersJson) &lt;&gt; 0 Then AppShortcut.Parameters.SetString("startupParametersJson", startupParametersJson)

  actions.Add(code, AppShortcut.ToUrlString(True))

End Sub

''' &lt;summary&gt;
'''  Get Open Accounts.
''' &lt;/summary&gt;
Public Function GetOpenAccounts(ByRef response As String) As Boolean

  Dim List As List(Of OpenAccount)

  If GetOpenAccountsInternal(List) Then
    Return finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(List, response)
  Else
    Return False
  End If

End Function

Function GetOpenAccountsInternal(ByRef accountsList As List(Of OpenAccount)) As Boolean

  Dim Database As ISDatabaseBL
  Dim DateMaturity As Date
  Dim DateOpened As Date
  Dim dr As IDataReader
  Dim IncludeAllAccounts As Boolean
  Dim sqb As ISSelectQueryBuilder
  Dim Success As Boolean
  Dim tempDate As Date

  ' Assume Success
  Success = True

  ' Initialise
  accountsList = New List(Of OpenAccount)
  Database = finBL.Database
  tempDate = finBL.TimeZoneFunctions.GetCurrentDatabaseDateTime()
  
  ' Include Accounts or all Users?
  If Len(mOpenAccountsAllRoleId) &lt;&gt; 0 Then
    If Not finBL.Users.ItemByPkSafe(mUserPk).IsInRole(mOpenAccountsAllRoleId, IncludeAllAccounts) Then
      ' Ignore Error (Accounts will be restricted to the current User)
    End If
  End If

  ' Build Query
  If Success Then
    sqb = finBL.Database.CreateSelectQueryBuilder()
    With sqb
      .Table = "Account"
      .Fields.AddList("AccountId,Name,DateOpened,AccountTypePk,DateMaturity,Balance,BalanceOverdue,DateReview")
      .TopLimit = 100

      ' SQL Where
      With .SqlWhere
        .AppendComparisonInteger("Status", "=", isefinAccountStatus.Open)

        If finBL.CurrentUserInformation.IsExternalUser Then
          ' User Filters (in the next block) will handle this
        ElseIf IncludeAllAccounts Then
          ' Do not limit Account Manager to Current User
        Else
          ' Account Manager is Current User
          .AppendComparisonInteger("AccountManagerUserPk", "=", mUserPk)
        End If

        ' User Filters
        .Append(finBL.CurrentUserInformation.FilterAccountSqlWhere)
      End With

      ' Order By
      .OrderByFields.Add("DateReview", True)
      .OrderByFields.Add("DateOpened", True)
    End With

    If sqb.ExecuteDisconnectedDataReader(dr) Then
      With dr
        Do While .Read()
          DateMaturity = Database.GetFieldDate(!DateMaturity)
          DateOpened = Database.GetFieldDate(!DateOpened)

          accountsList.Add(New OpenAccount(Database.GetFieldString(!AccountId),
                                            Database.GetFieldString(!Name),
                                            finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(DateOpened),
                                            finBL.AccountTypes.ItemByPk(Database.GetFieldInteger(!AccountTypePk)).AccountTypeId,
                                            finBL.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(DateMaturity),
                                            finBL.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(Database.GetFieldDate(!DateReview)),
                                            Database.GetFieldDecimal(!Balance),
                                            Database.GetFieldDecimal(!BalanceOverdue),
                                            DateMaturity &lt;&gt; Nothing AndAlso DateMaturity &gt; tempDate AndAlso (DateMaturity - tempDate).TotalDays &lt;= 7,
                                            DateOpened &lt;&gt; Nothing AndAlso DateOpened &lt;= tempDate AndAlso (tempDate - DateOpened).TotalDays &lt;= 7))
        Loop
      End With

      finBL.Database.DataReaderClose(dr)
    Else
      Success = False
    End If
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Open Accounts.
''' &lt;/summary&gt;
Public Function GetMonitoredAccounts(accountMonitorCategory As String,
                                     ByRef response As String) As Boolean

  Dim List As List(Of MonitoredAccount)

  If GetMonitoredAccountsInternal(accountMonitorCategory, List) Then
    Return finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(List, response)
  Else
    Return False
  End If

End Function

Function GetMonitoredAccountsInternal(accountMonitorCategory As String,
                                      ByRef accountsList As List(Of MonitoredAccount)) As Boolean

  Dim Database As ISDatabaseBL
  Dim dr As IDataReader
  Dim FieldName As String
  Dim FieldNameEntered As String
  Dim sqb As ISSelectQueryBuilder
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  accountsList = New List(Of MonitoredAccount)
  Database = finBL.Database
  FieldName = "MonitorCat" &amp; accountMonitorCategory &amp; "Pk"
  FieldNameEntered = "MonitorCat" &amp; accountMonitorCategory &amp; "EnteredDate"

  ' Build Query
  If Success Then
    sqb = finBL.Database.CreateSelectQueryBuilder()
    With sqb
      .Table = "Account"
      .TopLimit = finTaskManager2.MAX_FOLDER_SIZE
      .Fields.AddList("AccountId,Name,AccountTypePk," &amp; FieldName &amp; "," &amp; FieldNameEntered)

      ' SQL Where
      With .SqlWhere
        .AppendComparisonNotNull(FieldName)

        If finBL.CurrentUserInformation.IsExternalUser Then
          ' User Filters (in the next block) will handle this
        Else
          ' Account Manager
          .AppendComparisonInteger("AccountManagerUserPk", "=", mUserPk)
        End If

        ' User Filters
        .Append(finBL.CurrentUserInformation.FilterAccountSqlWhere)
      End With

      ' Order By
      .OrderByFields.Add("AccountId")
    End With

    If sqb.ExecuteDisconnectedDataReader(dr) Then
      With dr
        Do While .Read()
          accountsList.Add(New MonitoredAccount(Database.GetFieldString(!AccountId),
                                                Database.GetFieldString(!Name),
                                                finBL.AccountTypes.ItemByPk(Database.GetFieldInteger(!AccountTypePk)).AccountTypeId,
                                                finBL.MonitorCategories.ItemByPk(Database.GetFieldInteger(dr(FieldName))).MonitorCategoryId,
                                                finBL.HtmlWidgetUtilities.GetNullableJsonUtcDateTimeFromDatabaseDateTime(Database.GetFieldDate(dr(FieldNameEntered)))))
        Loop
      End With

      finBL.Database.DataReaderClose(dr)
    Else
      Success = False
    End If
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Quote Accounts.
''' &lt;/summary&gt;
Public Function GetQuoteAccounts(ByRef response As String) As Boolean

  Dim List As List(Of QuoteAccount)

  If GetQuoteAccountsInternal(List) Then
    Return finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(List, response)
  Else
    Return False
  End If

End Function

Function GetQuoteAccountsInternal(ByRef accountsList As List(Of QuoteAccount)) As Boolean

  Dim Database As ISDatabaseBL
  Dim dr As IDataReader
  Dim sqb As ISSelectQueryBuilder
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  accountsList = New List(Of QuoteAccount)
  Database = finBL.Database

  ' Build Query
  If Success Then
    sqb = finBL.Database.CreateSelectQueryBuilder()
    With sqb
      .Table = "Account"
      .TopLimit = finTaskManager2.MAX_FOLDER_SIZE
      .Fields.AddList("AccountId,Name,DateQuoted,DateReview,AccountTypePk")

      ' SQL Where
      With .SqlWhere
        .AppendComparisonInteger("Status", "=", isefinAccountStatus.Quote)

        If finBL.CurrentUserInformation.IsExternalUser Then
          ' User Filters (in the next block) will handle this
        Else
          ' Account Manager
          .AppendComparisonInteger("AccountManagerUserPk", "=", mUserPk)
        End If

        ' User Filters
        .Append(finBL.CurrentUserInformation.FilterAccountSqlWhere)
      End With
    End With

    If sqb.ExecuteDisconnectedDataReader(dr) Then
      With dr
        Do While .Read()
          accountsList.Add(New QuoteAccount(Database.GetFieldString(!AccountId),
                                            Database.GetFieldString(!Name),
                                            finBL.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(Database.GetFieldDateNullable(!DateQuoted)),
                                            finBL.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(Database.GetFieldDateNullable(!DateReview)),
                                            finBL.AccountTypes.ItemByPk(Database.GetFieldInteger(!AccountTypePk)).AccountTypeId))
        Loop
      End With

      finBL.Database.DataReaderClose(dr)
    Else
      Success = False
    End If
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Account Applications.
''' &lt;/summary&gt;
Public Function GetAccountApps(ByRef response As String) As Boolean

  Dim List As List(Of QuoteAccount)

  If GetAccountAppsInternal(List) Then
    Return finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(List, response)
  Else
    Return False
  End If

End Function

Function GetAccountAppsInternal(ByRef accountsList As List(Of QuoteAccount)) As Boolean

  Dim Database As ISDatabaseBL
  Dim dr As IDataReader
  Dim sqb As ISSelectQueryBuilder
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  accountsList = New List(Of QuoteAccount)
  Database = finBL.Database

  ' Build Query
  If Success Then
    sqb = finBL.Database.CreateSelectQueryBuilder()
    With sqb
      .Table = "AccountApp"
      .Fields.AddList("AccountAppId,Name,DateQuoted,DateReview,AccountAppTypePk")

      ' SQL Where
      With .SqlWhere
        .BlockBegin(iseSqlWhereBuilderNestedBlockType.OrBlock)
        .AppendComparisonInteger("Status", "=", isefinAccountAppStatus.Complete)
        .AppendComparisonInteger("Status", "=", isefinAccountAppStatus.Incomplete)
        .AppendComparisonInteger("Status", "=", isefinAccountAppStatus.Reviewing)
        .BlockEnd()

        If finBL.CurrentUserInformation.IsExternalUser Then
          ' User Filters (in the next block) will handle this
        Else
          ' Account Manager
          .AppendComparisonInteger("AccountManagerUserPk", "=", mUserPk)
        End If

        ' User Filters
        .Append(finBL.CurrentUserInformation.FilterAccountAppSqlWhere)
      End With
    End With

    If sqb.ExecuteDisconnectedDataReader(dr) Then
      With dr
        Do While .Read()
          accountsList.Add(New QuoteAccount(Database.GetFieldString(!AccountAppId),
                                            Database.GetFieldString(!Name),
                                            finBL.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(Database.GetFieldDateNullable(!DateQuoted)),
                                            finBL.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(Database.GetFieldDateNullable(!DateReview)),
                                            finBL.AccountAppTypes.ItemByPk(Database.GetFieldInteger(!AccountAppTypePk)).AccountAppTypeId))

        Loop
      End With

      finBL.Database.DataReaderClose(dr)
    Else
      Success = False
    End If
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Statistics.
''' &lt;/summary&gt;
Public Function GetStatistics() As Statistics

  Dim RecordCount As Integer
  Dim sqb As ISSelectQueryBuilder
  Dim Statistics As Statistics

  Statistics = New Statistics()

  ' -------------------
  ' Count Open Accounts
  ' -------------------
  sqb = CreateOpenAccountsSqlWhereQueryBuilder()
  With sqb
  End With
  If sqb.GetRecordCount(RecordCount) Then
    Statistics.CountOpenAccounts = RecordCount
  Else
    Statistics.CountOpenAccounts = -1
  End If

  ' ------------------------------
  ' Count Open Accounts for Review
  ' ------------------------------
  sqb = CreateOpenAccountsSqlWhereQueryBuilder()
  With sqb
    With .SqlWhere
      .AppendComparisonDateTime("DateReview", "&lt;=", finBL.TimeZoneFunctions.GetCurrentDatabaseDateTime())
    End With
  End With
  If sqb.GetRecordCount(RecordCount) Then
    Statistics.CountOpenAccountsForReview = RecordCount
  Else
    Statistics.CountOpenAccountsForReview = -1
  End If

  ' --------------------------------
  ' Count Open Accounts Closing Soon
  ' --------------------------------
  sqb = CreateOpenAccountsSqlWhereQueryBuilder()
  With sqb
    With .SqlWhere
      .AppendComparisonDateTime("DateMaturity", "&gt;=", finBL.TimeZoneFunctions.GetCurrentDatabaseDateTime())
      .AppendComparisonDateTime("DateMaturity", "&lt;=", finBL.TimeZoneFunctions.GetCurrentDatabaseDateTime().AddDays(7))
    End With
  End With
  If sqb.GetRecordCount(RecordCount) Then
    Statistics.CountOpenAccountsClosing = RecordCount
  Else
    Statistics.CountOpenAccountsClosing = -1
  End If

  ' -----------------------------------
  ' Count Open Accounts Opened Recently
  ' -----------------------------------
  sqb = CreateOpenAccountsSqlWhereQueryBuilder()
  With sqb
    With .SqlWhere
      .AppendComparisonDateTime("DateOpened", "&lt;=", finBL.TimeZoneFunctions.GetCurrentDatabaseDateTime())
      .AppendComparisonDateTime("DateOpened", "&gt;=", finBL.TimeZoneFunctions.GetCurrentDatabaseDateTime().AddDays(-7))
    End With
  End With
  If sqb.GetRecordCount(RecordCount) Then
    Statistics.CountOpenAccountsRecent = RecordCount
  Else
    Statistics.CountOpenAccountsRecent = -1
  End If

  ' --------------------------------------
  ' Other (not Statistics but common tags)
  ' --------------------------------------
  With Statistics
    .MonitorCategoryADescription = finBL.Settings.MonitorCategoryADescriptionResolved
    .MonitorCategoryBDescription = finBL.Settings.MonitorCategoryBDescriptionResolved
    .MonitorCategoryCDescription = finBL.Settings.MonitorCategoryCDescriptionResolved
  End With

  Return Statistics

End Function

Private Function CreateOpenAccountsSqlWhereQueryBuilder() As ISSelectQueryBuilder

  Dim sqb As ISSelectQueryBuilder

  sqb = finBL.Database.CreateSelectQueryBuilder()
  With sqb
    .Table = "Account"
    .TopLimit = finTaskManager2.MAX_FOLDER_SIZE

    ' SQL Where
    With .SqlWhere
      .AppendComparisonInteger("Status", "=", isefinAccountStatus.Open)

      If finBL.CurrentUserInformation.IsExternalUser Then
        ' User Filters (in the next block) will handle this
      Else
        ' Account Manager
        .AppendComparisonInteger("AccountManagerUserPk", "=", mUserPk)
      End If

      ' User Filters
      .Append(finBL.CurrentUserInformation.FilterAccountSqlWhere)
    End With
  End With

  Return sqb

End Function

''' &lt;summary&gt;
'''  Get Tasks.
''' &lt;/summary&gt;
Public Function GetTasks(ByRef response As String) As Boolean

  Dim List As List(Of finTaskManager2Task)
  Dim MaxSizeExceeded As Boolean

  If GetTasksInternal(List, MaxSizeExceeded) Then
    Return finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(List, response)
  Else
    Return False
  End If

End Function

Function GetTasksInternal(ByRef tasks As List(Of finTaskManager2Task),
                          ByRef maxSizeExceeded As Boolean) As Boolean

  Dim Success As Boolean
  Dim Task As finTaskManager2Task
  Dim TaskManager As finTaskManager2

  ' Assume Success
  Success = True

  ' Initialise ByRef Parameters
  tasks = Nothing
  maxSizeExceeded = False
  
  ' Create Task Manager
  TaskManager = finBL.CreateTaskManager2FromDateAsAt(mUserId, finBL.TimeZoneFunctions.GetCurrentDatabaseDateTime())

  ' Get Tasks
  Success = TaskManager.GetTasks("System_Tasks", Tasks, Nothing, maxSizeExceeded)
  
  ' Tag with properties needed for categorisation and description  
  If Success Then
    For Each Task In tasks
      With Task
        ' NOTE: This date is a UTC representation (for client-side) so account for this!
        .Tag1 = Format(finBL.TimeZoneFunctions.ConvertUtcToDatabaseDateTime(CDate(.DateDue)), "ddd dd MMM yyyy")
        
        ' Descriptions (Main and Sub)
        If Len(.Subject) = 0 Then
          .Tag2 = .Name
          .Tag3 = .Code
        Else
          .Tag2 = .Subject
          .Tag3 = .Code &amp; ": " &amp; .Name
        End If
      End With
    Next
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Upcoming Tasks.
''' &lt;/summary&gt;
Public Function GetTasksUpcoming(ByRef response As String) As Boolean

  Dim List As List(Of finTaskManager2Task)
  Dim MaxSizeExceeded As Boolean

  If GetTasksInternal(List, MaxSizeExceeded) Then
    Return finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(List, response)
  Else
    Return False
  End If

End Function

Function GetTasksUpcomingInternal(ByRef tasks As List(Of finTaskManager2Task),
                                  ByRef maxSizeExceeded As Boolean) As Boolean

  Dim CurrentDate As Date
  Dim i As Integer
  Dim Success As Boolean
  Dim Task As finTaskManager2Task
  Dim TaskManager As finTaskManager2

  ' Assume Success
  Success = True

  ' Initialise ByRef Parameters
  tasks = Nothing
  maxSizeExceeded = False

  ' Initialise
  CurrentDate = finBL.TimeZoneFunctions.GetCurrentDatabaseDateTime()

  ' Create Task Manager
  TaskManager = finBL.CreateTaskManager2FromDateAsAt(mUserId, CurrentDate.AddDays(mTasksUpcomingDays))

  ' Get Tasks
  ' NOTE: This list will be inaccurate if maxSizeExceeded is returned as True!
  Success = TaskManager.GetTasks("System_Tasks", Tasks, Nothing, maxSizeExceeded)

  ' Remove Tasks not in range
  If Success Then
    For i = tasks.Count - 1 To 0 Step - 1
      Task = tasks(i)
      If CDate(Task.DateDue) &gt; CurrentDate Then
        ' Adjust Overdue Days (0 to -mTaskUpcomingDays)
        Task.OverdueDays = CInt((CurrentDate.Date - CDate(Task.DateDue).Date).TotalDays)
      Else
        ' Remove
        tasks.RemoveAt(i)
      End If
    Next
  End If
  
  ' Tag with properties needed for categorisation and description  
  If Success Then
    For Each Task In tasks
      With Task
        ' Category
        ' NOTE: This date is a UTC representation (for client-side) so account for this!
        .Tag1 = Format(finBL.TimeZoneFunctions.ConvertUtcToDatabaseDateTime(CDate(.DateDue)), "ddd dd MMM yyyy")
        
        ' Descriptions (Main and Sub)
        If Len(.Subject) = 0 Then
          .Tag2 = .Name
          .Tag3 = .Code
        Else
          .Tag2 = .Subject
          .Tag3 = .Code &amp; ": " &amp; .Name
        End If
      End With
    Next
  End If  

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Recently Added.
''' &lt;/summary&gt;
Public Function GetRecentlyAdded(ByRef response As String) As Boolean

  Dim List As List(Of RecentRecord)

  If GetRecentlyAddedInternal(List) Then
    Return finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(List, response)
  Else
    Return False
  End If

End Function

Function GetRecentlyAddedInternal(ByRef recentList As List(Of RecentRecord)) As Boolean

  Dim CurrentUserInformation As finCurrentUserInformation
  Dim dr As IDataReader
  Dim FilterAccountSqlWhere As String
  Dim FilterAccountAppSqlWhere As String
  Dim FilterClientSqlWhere As String
  Dim sqb As ISSelectQueryBuilder
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  recentList = New List(Of RecentRecord)
  sqb = finBL.Database.CreateSelectQueryBuilder()

  ' Multi-User Support (i.e., Allow Recent Records to be viewed for a different User)
  If Success Then
    If mUserId = finBL.CurrentUserInformation.UserId Then
      FilterAccountSqlWhere = finBL.CurrentUserInformation.FilterAccountSqlWhere
      FilterAccountAppSqlWhere = finBL.CurrentUserInformation.FilterAccountAppSqlWhere
      FilterClientSqlWhere = finBL.CurrentUserInformation.FilterClientSqlWhere
    Else
      ' Viewing for another User
      If finBL.Users(mUserId).GetCurrentUserInformation(CurrentUserInformation) Then
        FilterAccountSqlWhere = CurrentUserInformation.FilterAccountSqlWhere
        FilterAccountAppSqlWhere = CurrentUserInformation.FilterAccountAppSqlWhere
        FilterClientSqlWhere = CurrentUserInformation.FilterClientSqlWhere
      Else
        Success = False
      End If
    End If
  End If

  ' --------
  ' Accounts
  ' --------
  If Success Then
    With sqb
      .Clear()
      .Table = "Account"
      .TopLimit = 20
      .Fields.AddList("AccountId,Name,CreatedUtcDate")

      With .SqlWhere
        ' This User
        .AppendComparisonInteger("CreatedUserPk", "=", mUserPk)

        ' Reasonably Recent
        .AppendComparisonDateTime("CreatedUtcDate", "&gt;=", finBL.TimeZoneFunctions.GetCurrentUtcDateTime().AddDays(-mRecentDays))

        ' User Filters
        .Append(FilterAccountSqlWhere)
      End With

      .OrderByFields.Add("CreatedUtcDate", True)
    End With

    If sqb.ExecuteDisconnectedDataReader(dr) Then
      Do While dr.Read()
        recentList.Add(New RecentRecord("Account",
                                        "Account",
                                        finBL.Database.GetFieldString(dr!AccountId),
                                        finBL.Database.GetFieldString(dr!Name),
                                        finBL.Runtime.DateUtilities.CastToUtcDateTime((finBL.Database.GetFieldDate(dr!CreatedUtcDate)))))
      Loop
      finBL.Database.DataReaderClose(dr)
    Else
      Success = False
    End If
  End If

  ' --------------------
  ' Account Applications
  ' --------------------
  If Success AndAlso finBL.Settings.AddOns.AccountApplication Then
    With sqb
      .Clear()
      .Table = "AccountApp"
      .TopLimit = 20
      .Fields.AddList("AccountAppId,Name,CreatedUtcDate")

      With .SqlWhere
        ' This User
        .AppendComparisonInteger("CreatedUserPk", "=", mUserPk)

        ' Reasonably Recent
        .AppendComparisonDateTime("CreatedUtcDate", "&gt;=", finBL.TimeZoneFunctions.GetCurrentUtcDateTime().AddDays(-mRecentDays))

        ' User Filters
        .Append(FilterAccountAppSqlWhere)
      End With

      .OrderByFields.Add("CreatedUtcDate", True)
    End With

    If sqb.ExecuteDisconnectedDataReader(dr) Then
      Do While dr.Read()
        recentList.Add(New RecentRecord("AccountApp",
                                        "AccountApp",
                                        finBL.Database.GetFieldString(dr!AccountAppId),
                                        finBL.Database.GetFieldString(dr!Name),
                                        finBL.Runtime.DateUtilities.CastToUtcDateTime((finBL.Database.GetFieldDate(dr!CreatedUtcDate)))))
      Loop
      finBL.Database.DataReaderClose(dr)
    Else
      Success = False
    End If
  End If

  ' -------
  ' Clients
  ' -------
  If Success Then
    With sqb
      .Clear()
      .Table = "Client"
      .TopLimit = 20
      .Fields.AddList("ClientId,Name,CreatedUtcDate")

      With .SqlWhere
        ' This User
        .AppendComparisonInteger("CreatedUserPk", "=", mUserPk)

        ' Reasonably Recent
        .AppendComparisonDateTime("CreatedUtcDate", "&gt;=", finBL.TimeZoneFunctions.GetCurrentUtcDateTime().AddDays(-mRecentDays))

        ' User Filters
        .Append(FilterClientSqlWhere)
      End With

      .OrderByFields.Add("CreatedUtcDate", True)
    End With

    If sqb.ExecuteDisconnectedDataReader(dr) Then
      Do While dr.Read()
        recentList.Add(New RecentRecord("Client",
                                        "Client",
                                        finBL.Database.GetFieldString(dr!ClientId),
                                        finBL.Database.GetFieldString(dr!Name),
                                        finBL.Runtime.DateUtilities.CastToUtcDateTime((finBL.Database.GetFieldDate(dr!CreatedUtcDate)))))
      Loop
      finBL.Database.DataReaderClose(dr)
    Else
      Success = False
    End If
  End If

  ' Sort
  recentList.Sort(AddressOf RecentRecordSortComparer)

  Return Success

End Function

Private Function RecentRecordSortComparer(x As RecentRecord, y As RecentRecord) As Integer

  If x.Category = y.Category Then
    If x.Date &gt; y.Date Then
      Return -1
    ElseIf x.Date &lt; y.Date Then
      Return 1
    Else
      Return 0
    End If
  Else
    Return strComp(x.CategorySort, y.CategorySort)
  End If

End Function

''' &lt;summary&gt;
'''  Get Recently Updated.
''' &lt;/summary&gt;
Public Function GetRecentlyUpdated(ByRef response As String) As Boolean

  Dim List As List(Of RecentRecord)

  If GetRecentlyUpdatedInternal(List) Then
    Return finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(List, response)
  Else
    Return False
  End If

End Function

Function GetRecentlyUpdatedInternal(ByRef recentList As List(Of RecentRecord)) As Boolean

  Dim CurrentUserInformation As finCurrentUserInformation
  Dim dr As IDataReader
  Dim FilterAccountSqlWhere As String
  Dim FilterAccountAppSqlWhere As String
  Dim FilterClientSqlWhere As String
  Dim sqb As ISSelectQueryBuilder
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  recentList = New List(Of RecentRecord)
  sqb = finBL.Database.CreateSelectQueryBuilder()

  ' Multi-User Support (i.e., Allow Recent Records to be viewed for a different User)
  If Success Then
    If mUserId = finBL.CurrentUserInformation.UserId Then
      FilterAccountSqlWhere = finBL.CurrentUserInformation.FilterAccountSqlWhere
      FilterAccountAppSqlWhere = finBL.CurrentUserInformation.FilterAccountAppSqlWhere
      FilterClientSqlWhere = finBL.CurrentUserInformation.FilterClientSqlWhere
    Else
      ' Viewing for another User
      If finBL.Users(mUserId).GetCurrentUserInformation(CurrentUserInformation) Then
        FilterAccountSqlWhere = CurrentUserInformation.FilterAccountSqlWhere
        FilterAccountAppSqlWhere = CurrentUserInformation.FilterAccountAppSqlWhere
        FilterClientSqlWhere = CurrentUserInformation.FilterClientSqlWhere
      Else
        Success = False
      End If
    End If
  End If

  ' --------
  ' Accounts
  ' --------
  If Success Then
    With sqb
      .Clear()
      .Table = "Account"
      .TopLimit = 20
      .Fields.AddList("AccountId,Name,UpdatedUtcDate")

      With .SqlWhere
        ' This User
        .AppendComparisonInteger("UpdatedUserPk", "=", mUserPk)

        ' Reasonably Recent
        .AppendComparisonDateTime("UpdatedUtcDate", "&gt;=", finBL.TimeZoneFunctions.GetCurrentUtcDateTime().AddDays(-mRecentDays))

        ' User Filters
        .Append(FilterAccountSqlWhere)
      End With

      .OrderByFields.Add("UpdatedUtcDate", True)
    End With

    If sqb.ExecuteDisconnectedDataReader(dr) Then
      Do While dr.Read()
        recentList.Add(New RecentRecord("Account",
                                        "Account",
                                        finBL.Database.GetFieldString(dr!AccountId),
                                        finBL.Database.GetFieldString(dr!Name),
                                        finBL.Runtime.DateUtilities.CastToUtcDateTime((finBL.Database.GetFieldDate(dr!UpdatedUtcDate)))))
      Loop
      finBL.Database.DataReaderClose(dr)
    Else
      Success = False
    End If
  End If

  ' --------------------
  ' Account Applications
  ' --------------------
  If Success AndAlso finBL.Settings.AddOns.AccountApplication Then
    With sqb
      .Clear()
      .Table = "AccountApp"
      .TopLimit = 20
      .Fields.AddList("AccountAppId,Name,UpdatedUtcDate")

      With .SqlWhere
        ' This User
        .AppendComparisonInteger("UpdatedUserPk", "=", mUserPk)

        ' Reasonably Recent
        .AppendComparisonDateTime("UpdatedUtcDate", "&gt;=", finBL.TimeZoneFunctions.GetCurrentUtcDateTime().AddDays(-mRecentDays))

        ' User Filters
        .Append(FilterAccountAppSqlWhere)
      End With

      .OrderByFields.Add("UpdatedUtcDate", True)
    End With

    If sqb.ExecuteDisconnectedDataReader(dr) Then
      Do While dr.Read()
        recentList.Add(New RecentRecord("AccountApp",
                                        "AccountApp",
                                        finBL.Database.GetFieldString(dr!AccountAppId),
                                        finBL.Database.GetFieldString(dr!Name),
                                        finBL.Runtime.DateUtilities.CastToUtcDateTime((finBL.Database.GetFieldDate(dr!UpdatedUtcDate)))))
      Loop
      finBL.Database.DataReaderClose(dr)
    Else
      Success = False
    End If
  End If

  ' -------
  ' Clients
  ' -------
  If Success Then
    With sqb
      .Clear()
      .Table = "Client"
      .TopLimit = 20
      .Fields.AddList("ClientId,Name,UpdatedUtcDate")

      With .SqlWhere
        ' This User
        .AppendComparisonInteger("UpdatedUserPk", "=", mUserPk)

        ' Reasonably Recent
        .AppendComparisonDateTime("UpdatedUtcDate", "&gt;=", finBL.TimeZoneFunctions.GetCurrentUtcDateTime().AddDays(-mRecentDays))

        ' User Filters
        .Append(FilterClientSqlWhere)
      End With

      .OrderByFields.Add("UpdatedUtcDate", True)
    End With

    If sqb.ExecuteDisconnectedDataReader(dr) Then
      Do While dr.Read()
        recentList.Add(New RecentRecord("Client",
                                        "Client",
                                        finBL.Database.GetFieldString(dr!ClientId),
                                        finBL.Database.GetFieldString(dr!Name),
                                        finBL.Runtime.DateUtilities.CastToUtcDateTime((finBL.Database.GetFieldDate(dr!UpdatedUtcDate)))))
      Loop
      finBL.Database.DataReaderClose(dr)
    Else
      Success = False
    End If
  End If

  ' Sort
  recentList.Sort(AddressOf RecentRecordSortComparer)

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Workflows allocated to this User.
''' &lt;/summary&gt;
Public Function GetWorkflows(ByRef response As String) As Boolean

  Dim List As List(Of Workflow)

  If GetWorkflowsInternal(List) Then
    Return finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(List, response)
  Else
    Return False
  End If

End Function

Function GetWorkflowsInternal(ByRef workflowsList As List(Of Workflow)) As Boolean

  Dim Database As ISDatabaseBL
  Dim dr As IDataReader
  Dim sqb As ISSelectQueryBuilder
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  workflowsList = New List(Of Workflow)
  Database = finBL.Database

  ' Build Query
  If Success Then
    sqb = finBL.Database.CreateSelectQueryBuilder()
    With sqb
      .Table = "Workflow"
      .TopLimit = finTaskManager2.MAX_FOLDER_SIZE 
      .Fields.AddList("WorkflowId,Description,RecallDate,ReviewDate")

      ' SQL Where
      With .SqlWhere
        .AppendComparisonNull("ClosedDate")
        .AppendComparisonInteger("AllocatedUserPk", "=", mUserPk)

        ' Up for Review or Recalled
        .BlockBegin(iseSqlWhereBuilderNestedBlockType.OrBlock)

        .BlockBegin(iseSqlWhereBuilderNestedBlockType.AndBlock)
        .AppendComparisonNotNull("RecallUtcDate")
        .AppendComparisonDateTime("RecallUtcDate", "&lt;=", finBL.TimeZoneFunctions.GetCurrentUtcDateTime())
        .BlockEnd()

        .BlockBegin(iseSqlWhereBuilderNestedBlockType.AndBlock)
        .AppendComparisonNotNull("ReviewDate")
        .AppendComparisonDateTime("ReviewDate", "&lt;=", finBL.TimeZoneFunctions.GetCurrentDatabaseDateTime())
        .BlockEnd()

        .BlockEnd()
      End With
    End With

    If sqb.ExecuteDisconnectedDataReader(dr) Then
      With dr
        Do While .Read()
          workflowsList.Add(New Workflow(Database.GetFieldString(!WorkflowId),
                                         Database.GetFieldString(!Description),
                                         finBL.HtmlWidgetUtilities.GetNullableJsonUtcDateTimeFromDatabaseDateTime(Database.GetFieldDate(!RecallDate)),
                                         finBL.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(Database.GetFieldDate(!ReviewDate))))
        Loop
      End With

      finBL.Database.DataReaderClose(dr)
    Else
      Success = False
    End If
  End If

  Return Success

End Function



''' &lt;summary&gt;
'''  Widget Initialisation Information.
''' &lt;/summary&gt;
Public Class FormInitialisationInfo

  ' General
  Public UserDetails As String
  Public UserInitials As String
  Public UserName As String

  ' Collections etc
  Public AccountApps As Object
  Public MonitoredAccountsA As Object
  Public MonitoredAccountsB As Object
  Public MonitoredAccountsC As Object
  Public OpenAccounts As Object
  Public QuoteAccounts As Object
  Public Statistics As Object
  
  Public Tasks As List(Of finTaskManager2Task)
  Public TasksMaxSizeExceeded As Boolean
  
  Public TasksUpcoming As List(Of finTaskManager2Task)
  Public TasksUpcomingMaxSizeExceeded As Boolean
  
  Public RecentlyAdded As Object
  Public RecentlyUpdated As Object
  
  Public Workflows As Object

  ' Configuration
  Public AddOns_AccountApplication As Boolean
  Public CurrentDbDate As Date
  Public DisplayPages As List(Of String)
  Public HomeBoxes As List(Of String)
  Public PollSeconds As Integer
  Public QuickButtons As List(Of String)
  Public QuickButtonActions As Object
  Public TasksUpcomingDays As Integer

End Class


Public Class Process

  ' Properties
  Public ProcessId As String
  Public Title As String
  Public Icon As String

  Public Sub New(process As finCloudConnectProcess)

    With process
      Me.ProcessId = .ProcessId
      Me.Title = .Title
      Me.Icon = .Icon
    End With

  End Sub

End Class



Public Class RecentRecord

  ' Properties
  Public Category As String
  Public CategorySort As String
  Public FormKey As String
  Public Icon As String
  Public Id As String
  Public Name As String
  Public [Date] As Date

  Public Sub New(formKey As String,
                 icon As String,
                 id As String,
                 name As String,
                 [date] As Date)

    With Me
      ' General
      Me.FormKey = formKey
      Me.Icon = icon
      Me.Id = id
      Me.Name = name
      Me.Date = [date]

      ' Category
      Select Case Me.FormKey
        Case "Account", "AccountApp"
          Me.Category = "Accounts &amp; Applications"
          Me.CategorySort = "A"

        Case "Client"
          Me.Category = "Client"
          Me.CategorySort = "F"

        Case Else
          Me.Category = "Other"
          Me.CategorySort = "P"
      End Select
    End With

  End Sub

End Class


Public Class QuoteAccount

  Public AccountId As String
  Public AccountTypeId As String
  Public DateQuoted As Date?
  Public DateReview As Date?
  Public Name As String

  Public Sub New(accountId As String,
                 name As String,
                 dateQuoted As Date?,
                 dateReview As Date?,
                 accountTypeId As String)

    With Me
      .AccountId = accountId
      .Name = name
      .DateQuoted = dateQuoted
      .DateReview = dateReview
      .AccountTypeId = accountTypeId
    End With

  End Sub

End Class


Public Class OpenAccount

  Public AccountId As String
  Public AccountTypeId As String
  Public DateMaturity As Date?
  Public DateOpened As Date
  Public DateReview As Date?
  Public Name As String
  Public Balance As Decimal
  Public BalanceOverdue As Decimal
  Public ClosingSoon As Boolean
  Public OpenedRecently As Boolean

  Public Sub New(accountId As String,
                 name As String,
                 dateOpened As Date,
                 accountTypeId As String,
                 dateMaturity As Date?,
                 dateReview As Date?,
                 balance As Decimal,
                 balanceOverdue As Decimal,
                 closingSoon As Boolean,
                 openedRecently As Boolean)

    With Me
      .AccountId = accountId
      .Name = name
      .DateOpened = dateOpened
      .AccountTypeId = accountTypeId
      .DateMaturity = dateMaturity
      .DateReview = dateReview
      .Balance = balance
      .BalanceOverdue = balanceOverdue
      .ClosingSoon = closingSoon
      .OpenedRecently = openedRecently
    End With

  End Sub

End Class


Public Class MonitoredAccount

  Public AccountId As String
  Public AccountTypeId As String
  Public DateEntered As Date?
  Public MonitorCategoryId As String
  Public Name As String

  Public Sub New(accountId As String,
                 name As String,
                 accountTypeId As String,
                 monitorCategoryId As String,
                 dateEntered As Date?)

    With Me
      .AccountId = accountId
      .Name = name
      .AccountTypeId = accountTypeId
      .MonitorCategoryId = monitorCategoryId
      .DateEntered = dateEntered
    End With

  End Sub

End Class


Public Class Workflow

  Public WorkflowId As String
  Public Description As String
  Public RecallDate As Date?
  Public ReviewDate As Date?

  Public Sub New(workflowId As String,
                 description As String,
                 recallDate As Date?,
                 reviewDate As Date?)

    With Me
      .WorkflowId = workflowId
      .Description = description
      .RecallDate = recallDate
      .ReviewDate = reviewDate
    End With

  End Sub

End Class


Public Class Statistics

  Public CountOpenAccounts As Integer
  Public CountOpenAccountsForReview As Integer
  Public CountOpenAccountsClosing As Integer
  Public CountOpenAccountsRecent As Integer

  ' Other Common
  Public MonitorCategoryADescription As String
  Public MonitorCategoryBDescription As String
  Public MonitorCategoryCDescription As String

End Class</Code>
    <Language>VisualBasic</Language>
    <Notes>System defined HTML Widget to display information about the current User.</Notes>
    <PermissionKeyExecute />
    <ReferenceLinq>false</ReferenceLinq>
    <RunWithoutPrompts>false</RunWithoutPrompts>
    <TemplateText>&lt;head&gt;

&lt;style type="text/less"&gt;
  @SECTION_WIDTH: 310px;
  @SECTION_SPACING: 6px;
  
  /* Layout */
  #frmMain {
    background-color:#eeeeee;
    display:flex;
    flex-direction:column;

    &gt; h1 {
      color:@MainColourForeground !important;
      flex-grow:0;
      font-weight:normal;
      margin:0;
      padding:8px 4px 4px 12px;
    }
  }

  /* Top Bar (page tabs) */
  div.top {
    background-color:white;
    box-shadow:2px 2px 2px rgba(0,0,0,0.15);
    position:absolute;
    top:0;
    left:0;
    right:0;
    height:64px;
    z-index:1;

    &gt; ul {
      list-style:none;
      display:flex;
      margin:0;
      padding:0;
      position:absolue;
      top:0;
      left:0;
      right:0;
      bottom:0;

      &gt; li {
        border-right:1px solid rgba(0,0,0,0.1);
        border-top:12px solid white;
        border-bottom:12px solid white;
        cursor:pointer;
        display:block;
        flex-grow:1;
        height:64px;
        margin:0;
        padding:0;
        text-align:center;
        transition:all 0.1s;

        &gt; div.caption {
          color:rgba(0,0,0,0.5);
          font-size:11px;
        }

        &gt; div.value {
          font-size:18px;
          font-weight:bold;
        }

        &amp;.selected {
          background-color:@ContrastColourBackground;
          color:@ContrastColourForeground;
          border-color:@ContrastColourBackground !important;

          &gt; div.caption {
            color:rgba(255,255,255,0.7);
          }
        }
      }
    }
  }

  /* Content (pages) */
  div.pages {
    top:64px;
    bottom:0;
    left:0;
    right:0;
    overflow:auto;
    position:absolute;
  }

  /* Page Header */
  div.page-header {
    display:flex;
    flex-wrap:wrap;
    justify-content:center;
    padding:8px;

    &gt; button {
      background-color:darkcyan;
      border:2px solid rgba(255,255,255,0.4);
      border-radius:8px;
      color:white;
      cursor:pointer;
      font-size:16px;
      font-weight:normal;
      padding:16px;
      margin:8px 8px 0 8px;
      max-width:240px;
      min-width:100px;
      width:25%;

      &amp;:hover {
        background-color:lighten(darkcyan,5%);
      }
    }

    &gt; div.chart-container {
      border:2px solid red;
      border-radius:8px;
      margin:0 8px 0 8px;
    }
  }

  /* Page Body */
  div.page-body {
    display:flex;
    justify-content:center;

    /* Page Section */
    &gt; div.page-section {
      display:flex;
      flex-wrap:wrap;
      justify-content:center;

      max-width:1800px;

      div.square {
        background-color:white;
        border:1px solid rgba(0,0,0,0.1);
        border-radius:8px;
        box-shadow:2px 2px 2px rgba(0,0,0,0.1);
        display:flex;
        flex-direction:column;
        height: @SECTION_WIDTH;
        margin: @SECTION_SPACING;
        padding:4px;
        width: @SECTION_WIDTH;
        transition:background-color 0.2s;

        &amp;:hover {
          border:1px solid rgba(0,0,0,0.2);
          box-shadow:2px 2px 2px rgba(0,0,0,0.2);
          background-color:rgba(0,0,0,0.01);
        }

        a {
          text-decoration:none;
        }

        h1, h3 {
          color:@ContrastColourBackground !important;
          font-size:24px;
          margin:0;
          text-align:center;
        }

        h2, h4 {
          color:rgba(0,0,0,0.6);
          font-size:14px;
          font-weight:bold;
          margin:2px 0 0 0;
          text-align:center;
        }

        h3 {
          font-size:18px;
        }

        h4 {
          font-size:12px;
          margin-bottom:12px;
        }

        div.content.chart {
          height:100%;
        }

        div.content:not(.chart) {
          margin-top:8px;
          overflow:auto;
        }
      }
    }
  }

  /* Records List (e.g., recent) */
  ul.records-list {
    display:flex;
    flex-wrap:wrap;
    list-style:none;
    padding:0;
    margin:0;

    &gt; li {
      background-color:#fafafa;
      border-radius:8px;
      border:1px solid rgba(0,0,0,0.1);
      margin:2px;
      padding:4px;
      width:50%;
      max-width:48%;
      max-height:58px;
      overflow-y:hidden;

      &amp;:hover {
        background-color:#3E82B3;
        box-shadow:2px 2px 2px rgba(0,0,0,0.1);

        &gt; a {
          color:white !important;

          &gt; div.sub {
            color:rgba(255,255,255,0.6);
          }
        }
      }

      &gt; a {
        color:rgba(0,0,0,0.8);
        display:block;
        position:relative;
        text-decoration:none;

        &gt; span:last-of-type {
          display:block;
          font-size:11px;
        }

        &gt; div.sub {
          color:rgba(0,0,0,0.6);
          font-size:10px !important;
          line-height:20px;
          position:absolute;
          top:0;
          right:0;
        }
      }

      img {
        display:block;
        width:16px;
        height:16px;
        vertical-align:middle;
      }
    }
  }

  /* Rows */
  span.row-review {
    background-color:#f0f0ff;
    border-radius:8px;
    border:1px solid rgba(0,0,0,0.1);
    padding:1px 4px 1px 4px;
  }
  tr.row-review &gt; td {
    background-color:#f0f0ff;
  }

  span.row-closing {
    background-color:#ffeedd;
    border-radius:8px;
    border:1px solid rgba(0,0,0,0.1);
    padding:1px 4px 1px 4px;
  }
  tr.row-closing &gt; td {
    background-color:#ffeedd;
  }

  span.row-recent {
    background-color:#eeffee;
    border-radius:8px;
    border:1px solid rgba(0,0,0,0.1);
    padding:1px 4px 1px 4px;
  }
  tr.row-recent &gt; td {
    background-color:#eeffee;
  }

  /* Sections */
  div.sections {
    display:flex;
    flex-direction:row;
    height:100%;
    min-height:100%;
    justify-content:center;

    /* Section */
    div.section {
      background-color:white;
      border:1px solid rgba(0,0,0,0.1);
      border:1px solid @MainColourBackground;
      border-radius:4px;
      display:flex;
      flex-direction:column;
      flex-grow:1;
      min-width:320px;
      max-width:1100px;
      margin:8px;
      position:relative;

      &gt; h1 {
        padding:8px;
        font-size:14px;
        margin:0;
        display:block;
        border-bottom:1px solid rgba(0,0,0,0.2);
        color:@MainColourBackground;
        flex-grow:0;
        line-height:32px;
        transition:all 0.2s;

        &gt; small {
          font-weight:normal;
          font-size:10px;
          color:rgba(0,0,0,0.6);
        }
      }

      &gt; div.content {
        flex-grow:1;
        font-size:13px;
        overflow:auto;
        position:relative;
        -webkit-overflow-scrolling:touch;
      }
    }
  }

  /* Calendar List */
  ul.calendar {
    list-style:none;
    padding:0;
    margin:0;
    -webkit-overflow-scrolling:touch;

    &gt; li {
      border-bottom:1px solid rgba(0,0,0,0.1);
      font-size:14px;
      display:flex;
      margin:0;
      padding:0;

      &gt; div.category {
        flex-grow:0;
        color:@MainColourBackground;
        padding:8px;
        vertical-align:top;
        max-height:120px;
        width:100px;
        text-align:center;
        position:sticky;
        position:-webkit-sticky;
        top:0;

        span {
          display:block;
          font-weight:bold;
          padding:0;
        }

        span:nth-child(1) { // Weekday
          color:rgba(0,0,0,0.35);
          font-size:12px;
        }

        span:nth-child(2) { // Day
          font-size:18px;
        }

        span:nth-child(3) { // Month
          font-size:16px;
        }

        span:nth-child(4) { // Year
          color:rgba(0,0,0,0.35);
          font-size:11px;
        }

        span:nth-child(5) { // Overdue Days
          color:red;
          font-size:9px;
          font-weight:normal;
          padding:4px;

          &amp;:after {
            content: " days ago";
          }
        }
      }

      &gt; ul {
        flex-grow:1;
        list-style:none;
        padding:0;
        margin:0;

        &gt; li {
          border-bottom:1px solid rgba(0,0,0,0.1);
          font-weight:normal;
          padding:8px;
          position:relative;

          &amp;:last-child {
            border-bottom:none;
          }

          /* Task details */
          a {
            color:rgba(0,0,0,0.65);
            display:block;
            display:block;
            font-size:12px;
            text-decoration:none;

            &gt; h1 {
             margin:0;
             padding:0;
             font-size:14px;
             font-weight:bold;
             color:@ContrastColourBackground;
             word-break:break-all;
            }

            &gt; div.sub-type {
              color:rgba(0,0,0,0.6);
              font-size:12px;
            }

            &gt; div.sub {
              color:rgba(0,0,0,0.9);
              font-size:12px;
            }

            &amp;:hover {
              h1 {
                text-shadow:2px 2px rgba(0,0,0,0.1);
              }
            }
          }
        }
      }
    }
  }

  /* Responsive */
  @media screen and (max-width:680px)
  {
    div.value {
      font-size:14px !important;
    }

    .extra {
      display:none;
    }

    /* Page Header */
    div.page-header {
      padding:4px;

      &gt; button {
        font-size:13px;
        margin:4px 2px 0 0;
        padding:8px 2px 8px 2px;
        width:31%;
      }
    }

    /* Page Body */
    div.page-body {
      /* Page Section */
      &gt; div.page-section {
        div.square {
          width:100%;
          margin:4px;

          div.chart {
            text-align:center;

            &gt; div {
              display:inline-block;
            }
          }
        }
      }
    }


    div.sections {
      flex-direction:column;
      padding:4px;
    }

    div.section {
      max-width:100% !important;
      margin:0 0 8px 0 !important;
      width:100% !important;
    }
  }
&lt;/style&gt;

&lt;/head&gt;
&lt;body&gt;

&lt;div id="frmMain" class="is-widget-content is-no-select" style="visibility:hidden"&gt;

  &lt;!-- Tabs --&gt;
  &lt;div id="tabGeneral" class="top"&gt;
    &lt;ul&gt;
      &lt;li tabId="Main" class="main is-sel"&gt;&lt;div id="divMainValue" class="value"&gt;&lt;/div&gt;&lt;div id="divMainSub" class="caption extra"&gt;&lt;/div&gt;&lt;/li&gt;
      &lt;li tabId="TasksDue" class="is-sel"&gt;&lt;div class="value" data-value="taskscount"&gt;&lt;/div&gt;&lt;div class="caption"&gt;Tasks&lt;span class="extra"&gt; Due&lt;/span&gt;&lt;/div&gt;&lt;/li&gt;
      &lt;li tabId="UpcomingTasks"&gt;&lt;div class="value" data-value="tasksupcomingcount"&gt;&lt;/div&gt;&lt;div class="caption"&gt;Upcoming&lt;span class="extra"&gt; Tasks&lt;/span&gt;&lt;/div&gt;&lt;/li&gt;
      &lt;li tabId="QuotesandApplications"&gt;&lt;div class="value" data-value="quotescount"&gt;&lt;/div&gt;&lt;div class="caption"&gt;Quotes&lt;span class="extra"&gt; &amp;amp; Applications&lt;/span&gt;&lt;/div&gt;&lt;/li&gt;
      &lt;li tabId="OpenAccounts"&gt;&lt;div class="value" id="divOpenAccountsCount"&gt;&lt;/div&gt;&lt;div class="caption"&gt;Open&lt;span class="extra"&gt; Accounts&lt;/span&gt;&lt;/div&gt;&lt;/li&gt;
      &lt;li tabId="MonitoredAccounts"&gt;&lt;div class="value" id="divMonitoredAccountsCount"&gt;&lt;/div&gt;&lt;div class="caption"&gt;Monitored&lt;span class="extra"&gt; Accounts&lt;/span&gt;&lt;/div&gt;&lt;/li&gt;
      &lt;li tabId="Workflows"&gt;&lt;div class="value" id="divWorkflowsCount"&gt;&lt;/div&gt;&lt;div class="caption"&gt;Workflows&lt;/div&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/div&gt;


  &lt;!-- Pages --&gt;
  &lt;div class="pages"&gt;

    &lt;!-- General --&gt;
    &lt;div id="pageMain"&gt;

      &lt;!-- Quick Buttons --&gt;
      &lt;div class="page-header"&gt;
        &lt;button buttonId="QuickQuote"&gt;Quick Quote&lt;/button&gt;
        &lt;button buttonId="NewApplication"&gt;New Application&lt;/button&gt;
        &lt;button buttonId="NewLoan"&gt;New Loan&lt;/button&gt;
        &lt;button buttonId="NewDeposit"&gt;New Deposit&lt;/button&gt;
        &lt;button buttonId="NewClient"&gt;New Client&lt;/button&gt;
      &lt;/div&gt;

      &lt;!-- Home Boxes --&gt;
      &lt;div class="page-body"&gt;
        &lt;div class="page-section"&gt;
          &lt;!-- Tasks Due --&gt;
          &lt;div boxId="TasksDue" class="square"&gt;
            &lt;div class="content chart"&gt;
               &lt;a href="javascript:tabGeneral.SelectedTabId('TasksDue')"&gt;
                &lt;h1 data-value="taskscount"&gt;&lt;/h1&gt;
                &lt;h2&gt;Tasks Due&lt;/h2&gt;
              &lt;/a&gt;
              &lt;div id="chrtTasks"&gt;&lt;/div&gt;
            &lt;/div&gt;
          &lt;/div&gt;

          &lt;!-- Upcoming Tasks --&gt;
          &lt;div boxId="UpcomingTasks" class="square"&gt;
            &lt;div class="content chart"&gt;
              &lt;a href="javascript:tabGeneral.SelectedTabId('UpcomingTasks')"&gt;
                &lt;h1 data-value="tasksupcomingcount"&gt;&lt;/h1&gt;
                &lt;h2&gt;Upcoming Tasks&lt;/h2&gt;
              &lt;/a&gt;
              &lt;div id="chrtTasksUpcoming"&gt;&lt;/div&gt;
            &lt;/div&gt;
          &lt;/div&gt;

          &lt;!-- Open Accounts --&gt;
          &lt;div boxId="OpenAccounts" class="square"&gt;
            &lt;a href="javascript:tabGeneral.SelectedTabId('OpenAccounts')"&gt;
              &lt;h1 data-value="countopenaccounts"&gt;&lt;/h1&gt;
              &lt;h2&gt;Open Accounts&lt;/h2&gt;
              &lt;div class="content"&gt;
                &lt;h3 data-value="countopenaccountsforreview"&gt;&lt;/h3&gt;
                &lt;h4&gt;To &lt;span class="row-review"&gt;Review&lt;/span&gt;&lt;/h4&gt;

                &lt;h3 data-value="countopenaccountsrecent"&gt;&lt;/h3&gt;
                &lt;h4&gt;&lt;span class="row-recent"&gt;Opened&lt;/span&gt; in past 7 days&lt;/h4&gt;

                &lt;h3 data-value="countopenaccountsclosing"&gt;&lt;/h3&gt;
                &lt;h4&gt;&lt;span class="row-closing"&gt;Closing&lt;/span&gt; within 7 days&lt;/h4&gt;

              &lt;/div&gt;
            &lt;/a&gt;
          &lt;/div&gt;

          &lt;!-- Quotes &amp; Applications --&gt;
          &lt;div boxId="QuotesandApplications" class="square"&gt;
            &lt;div class="content chart"&gt;
              &lt;a href="javascript:tabGeneral.SelectedTabId('QuotesandApplications')"&gt;
                &lt;h1 data-value="quotescount"&gt;&lt;/h1&gt;
                &lt;h2&gt;Quotes &amp;amp; Applications&lt;/h2&gt;
              &lt;/a&gt;
              &lt;div id="chrtQuotes"&gt;&lt;/div&gt;
            &lt;/div&gt;
          &lt;/div&gt;

          &lt;!-- Monitored Accounts A --&gt;
          &lt;div boxId="MonitoredAccountsA" class="square"&gt;
            &lt;div class="content chart"&gt;
              &lt;a href="javascript:tabGeneral.SelectedTabId('MonitoredAccounts')"&gt;
                &lt;h1 id="hMonitoredAccounts0Count"&gt;&lt;/h1&gt;
                &lt;h2 data-value="monitorcategoryadescription"&gt;&lt;/h2&gt;
              &lt;/a&gt;
              &lt;div id="chrtMonitoredAccounts0"&gt;&lt;/div&gt;
            &lt;/div&gt;
          &lt;/div&gt;

          &lt;!-- Monitored Accounts B --&gt;
          &lt;div boxId="MonitoredAccountsB" class="square"&gt;
            &lt;div class="content chart"&gt;
              &lt;a href="javascript:tabGeneral.SelectedTabId('MonitoredAccounts')"&gt;
                &lt;h1 id="hMonitoredAccounts1Count"&gt;&lt;/h1&gt;
                &lt;h2 data-value="monitorcategorybdescription"&gt;&lt;/h2&gt;
              &lt;/a&gt;
              &lt;div id="chrtMonitoredAccounts1"&gt;&lt;/div&gt;
            &lt;/div&gt;
          &lt;/div&gt;

          &lt;!-- Monitored Accounts C --&gt;
          &lt;div boxId="MonitoredAccountsC" class="square"&gt;
            &lt;div class="content chart"&gt;
              &lt;a href="javascript:tabGeneral.SelectedTabId('MonitoredAccounts')"&gt;
                &lt;h1 id="hMonitoredAccounts2Count"&gt;&lt;/h1&gt;
                &lt;h2 data-value="monitorcategorycdescription"&gt;&lt;/h2&gt;
              &lt;/a&gt;
              &lt;div id="chrtMonitoredAccounts2"&gt;&lt;/div&gt;
            &lt;/div&gt;
          &lt;/div&gt;

          &lt;!-- Added Recently --&gt;
          &lt;div boxId="AddedRecently" class="square"&gt;
            &lt;h1 data-value="recentlyaddedcount"&gt;&lt;/h1&gt;
            &lt;h2&gt;Added Recently&lt;/h2&gt;
            &lt;div class="content" id="divRecentlyAdded"&gt;
              &lt;ul class="records-list"&gt;&lt;/ul&gt;
            &lt;/div&gt;
          &lt;/div&gt;

          &lt;!-- Updated Recently --&gt;
          &lt;div boxId="UpdatedRecently" class="square"&gt;
            &lt;h1 data-value="recentlyupdatedcount"&gt;&lt;/h1&gt;
            &lt;h2&gt;Updated Recently&lt;/h2&gt;
            &lt;div class="content" id="divRecentlyUpdated"&gt;
              &lt;ul class="records-list"&gt;&lt;/ul&gt;
            &lt;/div&gt;
          &lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;


    &lt;!-- Tasks Due --&gt;
    &lt;div id="pageTasksDue"&gt;
      &lt;div class="sections"&gt;
        &lt;div id="divTasks" class="section"&gt;
          &lt;h1&gt;Tasks &lt;button onclick="widget.ExecuteApplicationShortcutUrl('app://formshow?form=UserLog');" class="is-button flat is-symbol-plus" style="float:right"&gt;&lt;/button&gt;&lt;/h1&gt;
          &lt;div class="content"&gt;&lt;ul class="calendar is-dock-fill"&gt;&lt;/ul&gt;&lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;


    &lt;!-- Upcoming Tasks --&gt;
    &lt;div id="pageUpcomingTasks"&gt;
      &lt;div class="sections"&gt;
        &lt;div id="divTasksUpcoming" class="section"&gt;
          &lt;h1&gt;Tasks Due within &lt;span&gt;X&lt;/span&gt; Days &lt;button onclick="widget.ExecuteApplicationShortcutUrl('app://formshow?form=UserLog');" class="is-button flat is-symbol-plus" style="float:right"&gt;&lt;/button&gt;&lt;/h1&gt;
          &lt;div class="content"&gt;&lt;ul class="calendar is-dock-fill"&gt;&lt;/ul&gt;&lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;


    &lt;!-- Quotes &amp; Applications --&gt;
    &lt;div id="pageQuotesandApplications"&gt;
      &lt;div class="sections"&gt;
        &lt;div id="divAccountQuotes" class="section"&gt;
          &lt;h1&gt;Quotes&lt;/h1&gt;
          &lt;div class="content"&gt;&lt;div id="gridQuotes"&gt;&lt;/div&gt;&lt;/div&gt;
        &lt;/div&gt;

        &lt;div id="divAccountApplications" class="section"&gt;
          &lt;h1&gt;Applications&lt;/h1&gt;
          &lt;div class="content"&gt;&lt;div id="gridAccountApps"&gt;&lt;/div&gt;&lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;


    &lt;!-- Open Accounts --&gt;
    &lt;div id="pageOpenAccounts"&gt;
      &lt;div class="sections"&gt;
        &lt;div id="divAccountsOpen" class="section"&gt;
          &lt;h1&gt;Open Accounts&lt;/h1&gt;
          &lt;div class="content"&gt;&lt;div id="gridOpenAccounts"&gt;&lt;/div&gt;&lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;


    &lt;!-- Monitored Accounts --&gt;
    &lt;div id="pageMonitoredAccounts"&gt;
      &lt;div class="sections"&gt;
        &lt;div id="divMonitoredAccounts0" class="section"&gt;
          &lt;h1 data-value="monitorcategoryadescription"&gt;&lt;/h1&gt;
          &lt;div class="content"&gt;&lt;div id="gridMonitoredAccountsA"&gt;&lt;/div&gt;&lt;/div&gt;
        &lt;/div&gt;

        &lt;div id="divMonitoredAccounts1" class="section"&gt;
          &lt;h1 data-value="monitorcategorybdescription"&gt;&lt;/h1&gt;
          &lt;div class="content"&gt;&lt;div id="gridMonitoredAccountsB"&gt;&lt;/div&gt;&lt;/div&gt;
        &lt;/div&gt;

        &lt;div id="divMonitoredAccounts2" class="section"&gt;
          &lt;h1 data-value="monitorcategorycdescription"&gt;&lt;/h1&gt;
          &lt;div class="content"&gt;&lt;div id="gridMonitoredAccountsC"&gt;&lt;/div&gt;&lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;


    &lt;!-- Workflows --&gt;
    &lt;div id="pageWorkflows"&gt;
      &lt;div class="sections"&gt;
        &lt;div id="divWorkflows" class="section"&gt;
          &lt;h1&gt;Workflows&lt;/h1&gt;
          &lt;div class="content"&gt;&lt;div id="gridWorkflows"&gt;&lt;/div&gt;&lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;

  &lt;/div&gt;

&lt;/div&gt;



&lt;script&gt;
// Constants
var CHART_WIDTH = 222;
var CHART_HEIGHT = 178;
var OVERDUE_BREAKS = [0, 1, 2, 3, 7, 14, 30];

// Properties
var mRecord;
var mRecord_AccountApps;
var mRecord_MonitoredAccountsA;
var mRecord_MonitoredAccountsB;
var mRecord_MonitoredAccountsC;
var mRecord_OpenAccounts;
var mRecord_QuoteAccounts;
var mRecord_RecentlyAdded;
var mRecord_RecentlyUpdated;
var mRecord_Statistics;
var mRecord_Tasks;
var mRecord_TasksUpcoming;
var mRecord_Workflows;

// Controls
var C = {
  gridQuotes: null,
  gridAccountApps: null,
  gridOpenAccounts: null,
  gridMonitoredAccountsA: null,
  gridMonitoredAccountsB: null,
  gridMonitoredAccountsC: null,
  gridWorkflows: null,
}

// Form
var frmMain;
var tabGeneral;

// Other
var mRefreshTimer;

// Charts
var mMonitoredAccountsCharts = {};
var mMonitoredAccountsChartOptions = {};

var mQuotesChart;
var mQuotesChartOptions;

var mTasksChart;
var mTasksChartOptions;

var mTasksUpcomingChart;
var mTasksUpcomingChartOptions;

// Other
var mMobile = widget.UI.IsSmallMobileBrowser();


// ==========
// Initialise
// ==========
$(function () {
  // Mobile optimisations
  $(window).resize(Form_Resize);

  // --------
  // Controls
  // --------

  // Grids
  C.gridQuotes = widget.UI.Grid("gridQuotes", {
    docked: true,

    onInitialiseRow: gridQuotes_InitialiseRow,
    onRowDrilldown: gridQuotes_RowDrilldown,
  });
  C.gridAccountApps = widget.UI.Grid("gridAccountApps", {
    docked: true,

    onInitialiseRow: gridAccountApps_InitialiseRow,
    onRowDrilldown: gridAccountApps_RowDrilldown,
  });
  C.gridOpenAccounts = widget.UI.Grid("gridOpenAccounts", {
    docked: true,

    onInitialiseRow: gridOpenAccounts_InitialiseRow,
    onRowDrilldown: gridOpenAccounts_RowDrilldown,
  });
  C.gridMonitoredAccountsA = widget.UI.Grid("gridMonitoredAccountsA", {
    docked: true,

    onInitialiseRow: function (e) { gridMonitoredAccounts_InitialiseRow(0, e); },
    onRowDrilldown: function (e) { gridMonitoredAccounts_RowDrilldown(0, e); },
  });
  C.gridMonitoredAccountsB = widget.UI.Grid("gridMonitoredAccountsB", {
    docked: true,

    onInitialiseRow: function (e) { gridMonitoredAccounts_InitialiseRow(1, e); },
    onRowDrilldown: function (e) { gridMonitoredAccounts_RowDrilldown(1, e); },
  });
  C.gridMonitoredAccountsC = widget.UI.Grid("gridMonitoredAccountsC", {
    docked: true,

    onInitialiseRow: function (e) { gridMonitoredAccounts_InitialiseRow(2, e); },
    onRowDrilldown: function (e) { gridMonitoredAccounts_RowDrilldown(2, e); },
  });
  C.gridWorkflows = widget.UI.Grid("gridWorkflows", {
    docked: true,

    onInitialiseRow: gridWorkflows_InitialiseRow,
    onRowDrilldown: gridWorkflows_RowDrilldown,
  });

  // Create Widget form
  // NOTE: Hide by default for a cleaner startup
  frmMain = new widget.UI.Form("frmMain", { visible: false });

  // Create Tabs
  tabGeneral = new widget.UI.Tabs("tabGeneral", { style: "custom" });

  // Quick Buttons
  $("button[buttonId]").click(function () { QuickButton($(this).attr("buttonId")); });

  // Handle Notifications
  widget.ActionNotificationHandle(Widget_NotificationHandler);

  // Handle Reset
  //widget.ResetHandle(Widget_ResetHandler);
  
  // Reset
  Form_Reset();
});

// ==========
// Reset Form
// ==========
function Form_Reset() {
  // Hide content
  frmMain.Visible(false);

  // Block UI
  widget.UI.Block("Initialising, please wait...");

  // Load Record
  Record_Load();
}

// ===========
// Load Record
// ===========
function Record_Load() {
  // Unauthenticated (i.e., signed out)
  if (!widget.IsAuthenticated()) {
    // Reset timer, get out of here and retry again in 30 seconds
    mRefreshTimer = window.setTimeout(function () {
      window.clearTimeout(mRefreshTimer);
      mRefreshTimer = null;
      
      Record_Load();
    }, 30000);
    return;
  }

  // Initialise
  mRecord = null;
  mRecord_AccountApps = null;
  mRecord_MonitoredAccountsA = null;
  mRecord_MonitoredAccountsB = null;
  mRecord_MonitoredAccountsC = null;
  mRecord_OpenAccounts = null;
  mRecord_QuoteAccounts = null;
  mRecord_RecentlyAdded = null;
  mRecord_RecentlyUpdated = null;
  mRecord_Statistics = null;
  mRecord_Tasks = null;
  mRecord_TasksUpcoming = null;
  mRecord_Workflows = null;

  // Clear refresh timer
  if (mRefreshTimer) {
    window.clearTimeout(mRefreshTimer);
    mRefreshTimer = null;
  }

  // Load Initialisation details
  var params = {};
  widget.GetString("GetInitialisationInfo", params,
    // Success
    function (data) {
      mRecord = JSON.parse(data);
      mRecord_AccountApps = mRecord.AccountApps;
      mRecord_MonitoredAccountsA = mRecord.MonitoredAccountsA;
      mRecord_MonitoredAccountsB = mRecord.MonitoredAccountsB;
      mRecord_MonitoredAccountsC = mRecord.MonitoredAccountsC;
      mRecord_OpenAccounts = mRecord.OpenAccounts;
      mRecord_QuoteAccounts = mRecord.QuoteAccounts;
      mRecord_RecentlyAdded = mRecord.RecentlyAdded;
      mRecord_RecentlyUpdated = mRecord.RecentlyUpdated;
      mRecord_Statistics = mRecord.Statistics;
      mRecord_Tasks = mRecord.Tasks;
      mRecord_TasksUpcoming = mRecord.TasksUpcoming;
      mRecord_Workflows = mRecord.Workflows;

      Fields_Load();
    },

    // Fail
    function (message) {
      widget.UI.MsgBoxAlert("fail: " + message);
      Fields_Load();
    }
  );
}

// ===========
// Load Fields
// ===========
function Fields_Load() {
  if (mRecord) {
    // Show/ Hide Pages
    tabGeneral.TabVisible("TasksDue", mRecord.DisplayPages.includes("TasksDue"));
    tabGeneral.TabVisible("UpcomingTasks", mRecord.DisplayPages.includes("UpcomingTasks"));
    tabGeneral.TabVisible("QuotesAndApplications", mRecord.DisplayPages.includes("QuotesandApplications"));
    tabGeneral.TabVisible("OpenAccounts", mRecord.DisplayPages.includes("OpenAccounts"));
    tabGeneral.TabVisible("MonitoredAccounts", mRecord.DisplayPages.includes("MonitoredAccounts"));
    tabGeneral.TabVisible("Workflows", mRecord.DisplayPages.includes("Workflows"));

    // Order Pages
    for (var i = 0; i &lt; mRecord.DisplayPages.length; i++) {
      var s = mRecord.DisplayPages[i];
      $("li[tabId='" + s + "']").css("order", i);
    }

    // Show/ Hide and Order Quick Buttons
    $("div.page-header &gt; button").hide();
    for (var i = 0; i &lt; mRecord.QuickButtons.length; i++) {
      var s = mRecord.QuickButtons[i];
      var e = $("button[buttonId='" + s + "']");
      e.css("order", i);
      e.show();
    }

    // Show/ Hide and Order Home Boxes
    $("div.square").hide();
    for (var i = 0; i &lt; mRecord.HomeBoxes.length; i++) {
      var s = mRecord.HomeBoxes[i];
      var e = $("div[boxId='" + s + "']");
      e.css("order", i);
      e.show();
    }

    // General
    if (mMobile) {
      $("#divMainValue").text(mRecord.UserInitials);
    }
    else {
      $("#divMainValue").text(mRecord.UserName);
    }
    $("#divMainSub").text(mRecord.UserDetails);

    // Statistics (and other common tags)
    if (mRecord_Statistics) {
      for (k in mRecord_Statistics) {
        $("*[data-value='" + k.toLowerCase() + "']").text(mRecord_Statistics[k]);
      }
    }

    // Refresh Pages and Home Boxes
    AccountAppsRefresh();
    OpenAccountsRefresh();
    MonitoredAccountsRefresh();
    QuoteAccountsRefresh();
    RecentRecordsRefresh(false);
    RecentRecordsRefresh(true);
    TasksRefresh();
    TasksUpcomingRefresh();
    WorkflowsRefresh();

    // Refresh Charts
    MonitoredAccountsRefreshChart(0); // A
    MonitoredAccountsRefreshChart(1); // B
    MonitoredAccountsRefreshChart(2); // C
    QuotesRefreshChart();
    TasksRefreshChart();
    TasksUpcomingRefreshChart();
    
    // Poll
    if (mRecord.PollSeconds &gt; 0) {
      mRefreshTimer = window.setTimeout(function () {
        window.clearTimeout(mRefreshTimer);
        mRefreshTimer = null;

        Record_Load();
      }, mRecord.PollSeconds * 1000);
    }
  }

  // Show content
  frmMain.Visible(mRecord != null);

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

// ===========
// Resize Form
// ===========
function Form_Resize() {
  // Tab
  //tabWizard_Resize();
}

// ======================
// Quote Accounts Section
// ======================
function QuoteAccountsRefresh() {
  if (!mRecord_QuoteAccounts) return;

  // Summary
  var count = mRecord_QuoteAccounts.length;
  if (mRecord_AccountApps) count += mRecord_AccountApps.length
  $("*[data-value='quotescount']").text(count);

  // Initialise Grid
  if (C.gridQuotes.ColumnCount() == 0) {
    C.gridQuotes.AddColumnCode("AccountId", {caption: "ID", width: widget.UI.FIELD_WIDTH_CODE_5, sortable: true});
    C.gridQuotes.AddColumnString("Name", {caption: "Name", sortable: true});
    C.gridQuotes.AddColumnCode("AccountTypeId", {caption: "Type", width: widget.UI.FIELD_WIDTH_CODE_5, sortable: true});
    C.gridQuotes.AddColumnDate("DateQuoted", {caption: "Quoted", sortable: true});
    C.gridQuotes.AddColumnDate("DateReview", {caption: "Review", sortable: true});
  }

  // Bind
  C.gridQuotes.VirtualDataRefresh(mRecord_QuoteAccounts);
}

function gridQuotes_InitialiseRow(e) {
  var item = mRecord_QuoteAccounts[e.row.listIndex];

  // Automatic data binding
  e.row.AutoBind(item);

  // Hyperlink AccountId
  e.row.cells.AccountId.hyperlink = "app://formshow?form=Accounts&amp;id=" + item.AccountId;

  // Styling
  e.row.cells.Name.small = mMobile
  if (item.DateReview) {
    e.row.bold = true;
  }
  else {
    e.row.bold = false;
  }
}

function gridQuotes_RowDrilldown() {
  var item = mRecord_QuoteAccounts[C.gridQuotes.ActiveDataRowListIndex()];

  // View Account
  widget.ExecuteApplicationShortcutUrl("app://formshow?form=Accounts&amp;id=" + item.AccountId)
}

// ============================
// Account Applications Section
// ============================
function AccountAppsRefresh() {
  if (!mRecord_AccountApps) return;

  // Summary
  var count = mRecord_AccountApps.length;
  if (mRecord_QuoteAccounts) count += mRecord_QuoteAccounts.length
  $("#divQuotesAndApplicationsCount").text(count);

  // Initialise Grid
  if (C.gridAccountApps.ColumnCount() == 0) {
    C.gridAccountApps.AddColumnCode("AccountId", {caption: "ID", width: widget.UI.FIELD_WIDTH_CODE_5, sortable: true});
    C.gridAccountApps.AddColumnString("Name", {caption: "Name", sortable: true});
    C.gridAccountApps.AddColumnCode("AccountTypeId", {caption: "Type", width: widget.UI.FIELD_WIDTH_CODE_5, sortable: true});
    C.gridAccountApps.AddColumnDate("DateQuoted", {caption: "Quoted", sortable: true});
    C.gridAccountApps.AddColumnDate("DateReview", {caption: "Review", sortable: true});
  }

  // Bind
  C.gridAccountApps.VirtualDataRefresh(mRecord_AccountApps);
}

function gridAccountApps_InitialiseRow(e) {
  var item = mRecord_AccountApps[e.row.listIndex];

  // Automatic data binding
  e.row.AutoBind(item);

  // Hyperlink AccountId
  e.row.cells.AccountId.hyperlink = "app://formshow?form=AccountApps&amp;id=" + item.AccountId;

  // Styling
  e.row.cells.Name.small = mMobile
  if (item.DateReview) {
    e.row.bold = true;
  }
  else {
    e.row.bold = false;
  }
}

function gridAccountApps_RowDrilldown() {
  var item = mRecord_AccountApps[C.gridAccountApps.ActiveDataRowListIndex()];

  // View Account
  widget.ExecuteApplicationShortcutUrl("app://formshow?form=AccountApps&amp;id=" + item.AccountId)
}

// =====================
// Open Accounts Section
// =====================
function OpenAccountsRefresh() {
  if (!mRecord_OpenAccounts) return;

  // Summary
  var h = $("#divOpenAccountsCount");
  if (mRecord_OpenAccounts.length == 100) {
    h.text(mRecord_OpenAccounts.length + "+");
  }
  else {
    h.text(mRecord_OpenAccounts.length);
  }

  // Section heading
  h = $("#divAccountsOpen &gt; h1");
  if (mRecord_OpenAccounts.length == 100) {
    h.html("Open Accounts &lt;small&gt;(100 limit)&lt;/small&gt;");
  }
  else {
    h.text("Open Accounts");
  }

  // Initialise Grid
  if (C.gridOpenAccounts.ColumnCount() == 0) {
    C.gridOpenAccounts.AddColumnCode("AccountId", {caption: "ID", width: widget.UI.FIELD_WIDTH_CODE_5, sortable: true});
    C.gridOpenAccounts.AddColumnString("Name", {caption: "Name", sortable: true});
    C.gridOpenAccounts.AddColumnCode("AccountTypeId", {caption: "Type", width: widget.UI.FIELD_WIDTH_CODE_5, sortable: true});
    C.gridOpenAccounts.AddColumnDate("DateOpened", {caption: "Opened", sortable: true});
    C.gridOpenAccounts.AddColumnDate("DateMaturity", {caption: "Matures", sortable: true});
    C.gridOpenAccounts.AddColumnCurrency("Balance", {caption: "Balance", sortable: true});
    C.gridOpenAccounts.AddColumnCurrency("BalanceOverdue", {caption: "Overdue", sortable: true, blankIfZero: true});
    C.gridOpenAccounts.AddColumnDate("DateReview", {caption: "Review", sortable: true});
  }

  // Bind
  C.gridOpenAccounts.VirtualDataRefresh(mRecord_OpenAccounts);
}

function gridOpenAccounts_InitialiseRow(e) {
  var item = mRecord_OpenAccounts[e.row.listIndex];

  // Automatic data binding
  e.row.AutoBind(item);

  // Hyperlink AccountId
  e.row.cells.AccountId.hyperlink = "app://formshow?form=Accounts&amp;id=" + item.AccountId;

  // Styling
  e.row.cells.Name.small = mMobile;
  if (item.OpenedRecently) e.row.cssClass = "row-recent";
  if (item.ClosingSoon) e.row.cssClass = "row-closing";
  if (item.DateReview) {
    e.row.bold = true;
    e.row.cssClass = "row-review";
  }
  else {
    e.row.bold = false;
  }
}

function gridOpenAccounts_RowDrilldown() {
  var item = mRecord_OpenAccounts[C.gridOpenAccounts.ActiveDataRowListIndex()];

  // View Account
  widget.ExecuteApplicationShortcutUrl("app://formshow?form=Accounts&amp;id=" + item.AccountId)
}

// ==========================
// Monitored Accounts Section
// ==========================
function MonitoredAccountsRefresh() {
  if (!mRecord_MonitoredAccountsA &amp;&amp; !mRecord_MonitoredAccountsB &amp;&amp; !mRecord_MonitoredAccountsC) return;

  // Summary
  var count = "";
  var sep = " &lt;span style='color:rgba(0,0,0,0.25);font-weight:normal'&gt;|&lt;/span&gt; ";
  for (var i = 0; i &lt; 3; i++) {
    var records = GetMonitoredAccounts(i);
    if (records) {
      if (count) count += sep;
      count += records.length;
    }
  }
  $("#divMonitoredAccountsCount").html(count);

  // Grids
  for (var i = 0; i &lt; 3; i++) {
    var grid = GetMonitoredAccountsGrid(i);
    var records = GetMonitoredAccounts(i);

    if (records) {
      if (grid.ColumnCount() == 0) {
        grid.AddColumnCode("AccountId", {caption: "ID", width: widget.UI.FIELD_WIDTH_CODE_5, sortable: true});
        grid.AddColumnString("Name", {caption: "Name", sortable: true});
        grid.AddColumnCode("MonitorCategoryId", {caption: "Category", width: widget.UI.FIELD_WIDTH_CODE_5, sortable: true});
        grid.AddColumnDate("DateEntered", {caption: "Entered", sortable: true});
      }

      // Bind
      grid.VirtualDataRefresh(records);
    }
    else {
      // Monitor Category not used
      $("#divMonitoredAccounts" + i).hide();
    }
  }
}

function gridMonitoredAccounts_InitialiseRow(accountMonitorCategoryIndex, e) {
  var item = GetMonitoredAccounts(accountMonitorCategoryIndex)[e.row.listIndex];

  // Automatic data binding
  e.row.AutoBind(item);

  // Hyperlink AccountId
  e.row.cells.AccountId.hyperlink = "app://formshow?form=Accounts&amp;id=" + item.AccountId;

  // Styling
  e.row.cells.Name.small = mMobile;
}

function gridMonitoredAccounts_RowDrilldown(accountMonitorCategoryIndex) {
  var item = mRecord_MonitoredAccounts[C.gridMonitoredAccounts.ActiveDataRowListIndex()];

  // View Account
  widget.ExecuteApplicationShortcutUrl("app://formshow?form=Accounts&amp;id=" + item.AccountId)
}

function GetMonitoredAccountsGrid(accountMonitorCategoryIndex) {
  switch(accountMonitorCategoryIndex) {
    case 0:
      return C.gridMonitoredAccountsA;
    case 1:
      return C.gridMonitoredAccountsB;
    case 2:
      return C.gridMonitoredAccountsC;
  }
}

function GetMonitoredAccounts(accountMonitorCategoryIndex) {
  switch(accountMonitorCategoryIndex) {
    case 0:
      return mRecord_MonitoredAccountsA;
    case 1:
      return mRecord_MonitoredAccountsB;
    case 2:
      return mRecord_MonitoredAccountsC;
  }
}

// =============
// Tasks Section
// =============
function TasksRefresh() {
  if (!mRecord_Tasks) return;

  // Summary
  $("*[data-value='taskscount']").text(mRecord_Tasks.length);

  // Create List
  TasksRefreshInternal($("#divTasks div.content &gt; ul"), mRecord_Tasks);
}

function TasksRefreshInternal(ul, items) {
  // Initialise
  ul.children().remove();

  // Generate List
  var lastCategory = "";
  var ul2;
  for (var i = 0; i &lt; items.length; i++) {
    var item = items[i];
    item.Category = item.Tag1;
    item.Description = item.Tag2;
    item.DescriptionSub = item.Tag3;

    // New Category (i.e., calendar date)?
    if (lastCategory != item.Category) {
      // Split D, M, Y
      var arrTemp = (item.Category + "").split(" ");
      var liCat = $("&lt;li&gt;&lt;/li&gt;");
      var divCat = $("&lt;div class='category'&gt;&lt;/div&gt;");

      for(var j = 0; j &lt; arrTemp.length; j++) {
        divCat.append("&lt;span&gt;" + arrTemp[j] + "&lt;/span&gt;");
      }

      // Overdue Days
      if (item.OverdueDays &gt;= 0) {
        divCat.append("&lt;span&gt;" + item.OverdueDays + "&lt;/span&gt;");
      }

      liCat.append(divCat);
      ul2 = $("&lt;ul&gt;&lt;/ul&gt;");
      liCat.append(ul2);
      ul.append(liCat);
      lastCategory = item.Category;
    }

    // Item
    var li = $("&lt;li&gt;&lt;/li&gt;");
    var a = $("&lt;a&gt;&lt;/a&gt;");
    a.append("&lt;h1&gt;" + widget.UI.HtmlEncode(item.Description) + "&lt;/h1&gt;");
    if (item.TaskApplicationShortcutUrl) {
      a.attr("href", item.TaskApplicationShortcutUrl);
    }
    else if (item.CodeApplicationShortcutUrl) {
      a.attr("href", item.CodeApplicationShortcutUrl);
    }
    a.append("&lt;div class='sub-type'&gt;" + widget.UI.HtmlEncode(item.TaskTypeText) + "&lt;/div&gt;");
    if (item.DescriptionSub) {
      a.append("&lt;div class='sub'&gt;" + widget.UI.HtmlEncode(item.DescriptionSub) + "&lt;/div&gt;");
    }
    li.append(a);

    ul2.append(li);
  }
}

// ======================
// Tasks Upcoming Section
// ======================
function TasksUpcomingRefresh() {
  if (!mRecord_TasksUpcoming) return;

  // Summary
  $("*[data-value='tasksupcomingcount']").text(mRecord_TasksUpcoming.length);
  $("#divTasksUpcoming h1 &gt; span").text(mRecord.TasksUpcomingDays);

  // Create List
  TasksRefreshInternal($("#divTasksUpcoming div.content &gt; ul"), mRecord_TasksUpcoming);
}

// ================================
// Recently Added/ Updated Sections
// ================================
function RecentRecordsRefresh(recentlyUpdated) {
  var items;
  var div, ul;

  if (recentlyUpdated) {
    if (!mRecord_RecentlyUpdated) return;

    items = mRecord_RecentlyUpdated;
    div = $("#divRecentlyUpdated");
    $("*[data-value='recentlyupdatedcount']").text(items.length);

  }
  else {
    if (!mRecord_RecentlyAdded) return;

    items = mRecord_RecentlyAdded;
    ul = $("#divRecentlyAdded ul");
    div = $("#divRecentlyAdded");
    $("*[data-value='recentlyaddedcount']").text(items.length);
  }
  ul = $("ul", div);

  // Initialise
  ul.children().remove();

  // Generate List
  for (var i = 0; i &lt; items.length; i++) {
    var item = items[i];

    // Item
    var li = $("&lt;li&gt;&lt;/li&gt;");
    var a = $("&lt;a&gt;&lt;/a&gt;");
    var img = $("&lt;img/&gt;");
    var code = $("&lt;span&gt;&lt;/span&gt;");
    var name = $("&lt;span&gt;&lt;/span&gt;");

    a.attr("href", "app://FormShow?form=" + item.FormKey + "&amp;id=" + item.Id);

    img.attr("src", widget.GetIconUrl(item.Icon))
    code.text(item.Id);
    name.text(item.Name);

    a.append(img);
    a.append(code);
    a.append(name);
    li.append(a);
    a.append("&lt;div class='sub'&gt;" + widget.FormatDate(item.Date) + "&lt;/div&gt;");

    ul.append(li);
  }
}

// ===========
// Tasks Chart
// ===========
function TasksRefreshChart() {
  // Ref:
  //   https://apexcharts.com/docs/chart-types/pie-donut/
  //   https://apexcharts.com/docs/options/legend/
  
  // Anything to chart?
  if (!mRecord_Tasks || mRecord_Tasks.length == 0) {
    $("#chrtTasks").hide();
    return;
  }
  
  // Initialise (series, labels and colours)
  // NOTE: Usually we would let the chart use its own colours
  var series = [];
  var labels = [];
  var colours = [];
  
  for (var i = 0; i &lt; OVERDUE_BREAKS.length; i++) {
    var od = OVERDUE_BREAKS[i];

    series.push(0);
    if (i == 0) {
      labels.push("Due");
      colours.push("#32CD32"); // Lime Green
    }
    else if (i == OVERDUE_BREAKS.length - 1) {
      labels.push(od + "-");
      colours.push("#FF0000"); // Red
    }
    else {
      labels.push("-" + od);
      colours.push("#FF8C00"); // Dark Orange
    }
  }

  // Update data
  for (var i = 0; i &lt; mRecord_Tasks.length; i++) {
    var item = mRecord_Tasks[i];

    // Increment correct overdue group
    for (var j = OVERDUE_BREAKS.length - 1; j &gt;= 0; j--) {
      var od = OVERDUE_BREAKS[j];
      if (item.OverdueDays &gt;= od) {
        series[j] += 1;
        break;
      }
    }
  }

  // Bar charts require an XY series (we have created labels and series for compatibility with pie charts)
  var seriesXY = widget.UI.Charts.ApexCharts.CreateXYSeries(labels, series, colours);
  
  // Draw
  $("#chrtTasks").show();
  
  var options = {
    legend: { show: true, position: "bottom", height: 18, fontSize: "9px" },
  
    series: [ 
      { 
        name: "Tasks",
        data: seriesXY
      },
    ],
    
    //series: series,
    //labels: labels,
    //colors: colours,
  }
  
  if (!mTasksChart) {
    mTasksChart = widget.UI.Charts.ApexCharts.ColumnChart("chrtTasks", options);
    mTasksChart.render();
  }
  else {
    mTasksChart.updateOptions(options);  
  }
}

// ====================
// Tasks Upcoming Chart
// ====================
function TasksUpcomingRefreshChart() {
  // Ref:
  //   https://apexcharts.com/docs/chart-types/pie-donut/
  //   https://apexcharts.com/docs/options/legend/

  // Anything to chart?
  if (!mRecord_TasksUpcoming || mRecord_TasksUpcoming.length == 0) {
    $("#chrtTasksUpcoming").hide();
    return;
  }

  // Initialise (series and labels)
  var series = [];
  var labels = [];
  
  for (var i = 0; i &lt; mRecord.TasksUpcomingDays; i++) {
    labels.push("+" + (i+1));
    series.push(0);
  }
  
  // Update data
  for (var i = 0; i &lt; mRecord_TasksUpcoming.length; i++) {
    var item = mRecord_TasksUpcoming[i];

    // Increment correct day (OverdueDays will be zero or negative)
    series[0 + Math.abs(item.OverdueDays)] += 1;
  }
  
  // Bar charts require an XY series (we have created labels and series for compatibility with pie charts)
  var seriesXY = widget.UI.Charts.ApexCharts.CreateXYSeries(labels, series);

  // Draw
  $("#chrtTasksUpcoming").show();
  
  var options = {
    legend: { show: true, position: "bottom", height: 18, fontSize: "9px" },
  
    series: [ 
      { 
        name: "Tasks",
        data: seriesXY
      },
    ],
    
    //series: series,
    //labels: labels,
  }

  if (!mTasksUpcomingChart) {
    mTasksUpcomingChart = widget.UI.Charts.ApexCharts.ColumnChart("chrtTasksUpcoming", options);
    mTasksUpcomingChart.render();
  }
  else {
    mTasksUpcomingChart.updateOptions(options);  
  }
}

// =================
// Workflows Section
// =================
function WorkflowsRefresh() {
  if (!mRecord_Workflows) return;

  // Summary
  $("#divWorkflowsCount").text(mRecord_Workflows.length);

  // Initialise Grid
  if (C.gridWorkflows.ColumnCount() == 0) {
    C.gridWorkflows.AddColumnCode("WorkflowId", {caption: "ID", width: widget.UI.FIELD_WIDTH_CODE_5, sortable: true});
    C.gridWorkflows.AddColumnString("Description", {caption: "Description", sortable: true});
    C.gridWorkflows.AddColumnDateTime("RecallDate", {caption: "Recalled", sortable: true});
    C.gridWorkflows.AddColumnDate("ReviewDate", {caption: "Review", sortable: true});
  }

  // Bind
  C.gridWorkflows.VirtualDataRefresh(mRecord_Workflows);
}

function gridWorkflows_InitialiseRow(e) {
  var item = mRecord_Workflows[e.row.listIndex];

  // Automatic data binding
  e.row.AutoBind(item);

  // Hyperlink WorkflowId
  e.row.cells.WorkflowId.hyperlink = "app://formshow?form=Workflows&amp;id=" + item.WorkflowId;

  // Styling
  e.row.cells.Description.small = mMobile;
}

function gridWorkflows_RowDrilldown() {
  var item = mRecord_Workflows[C.gridWorkflows.ActiveDataRowListIndex()];

  // View Workflow
  widget.ExecuteApplicationShortcutUrl("app://formshow?form=Workflows&amp;id=" + item.WorkflowId)
}

// ============
// Quotes Chart
// ============
function QuotesRefreshChart() {
  // Ref:
  //   https://apexcharts.com/docs/chart-types/pie-donut/
  //   https://apexcharts.com/docs/options/legend/

  // Anything to chart?
  if (!mRecord_QuoteAccounts || mRecord_QuoteAccounts.length == 0) {
    $("#chrtQuotes").hide();
    return;
  }

  // Initialise (series and labels)
  var series = [];
  var labels = [];
  
  // Create data
  for (var k = 0; k &lt; 2; k++) {
    var ds = (k == 0 ? mRecord_QuoteAccounts : mRecord_AccountApps);

    if (ds &amp;&amp; ds.length &gt; 0) {
      for (var i = 0; i &lt; ds.length; i++) {
        var item = ds[i];
        var found = false;

        for (var j = 0; j &lt; labels.length; j++) {
          if (labels[j] == item.AccountTypeId) {
            found = true;
            series[j] += 1;
            break;
          }
        }
        if (!found) {
          series.push(1);
          labels.push(item.AccountTypeId);
        }
      }
    }
  }
  
  // Draw
  $("#chrtQuotes").show();
  
  var options = {
    legend: { show: true, position: "bottom", height: 18, fontSize: "9px" },
  
    series: series,
    labels: labels,
  }
  
  if (!mQuotesChart) {
    mQuotesChart = widget.UI.Charts.ApexCharts.PieChart("chrtQuotes", options);
    mQuotesChart.render();
  }
  else {
    mQuotesChart.updateOptions(options);  
  }
}

// ========================
// Monitored Accounts Chart
//// ========================
function MonitoredAccountsRefreshChart(accountMonitorCategoryIndex) {
  // Ref:
  //   https://apexcharts.com/docs/chart-types/pie-donut/
  //   https://apexcharts.com/docs/options/legend/

  // Decide on records and chart
  var records = GetMonitoredAccounts(accountMonitorCategoryIndex);
  var chart = mMonitoredAccountsCharts[accountMonitorCategoryIndex];
  var chartDiv = $("#chrtMonitoredAccounts" + accountMonitorCategoryIndex);

  // Anything to chart?
  if (!records || records.length == 0) {
    chartDiv.hide();
    return;
  }
  
  // Title
  $("#hMonitoredAccounts" + accountMonitorCategoryIndex + "Count").text(records.length);

// Initialise (series and labels)
  var series = [];
  var labels = [];
  
  // Create data
  for (var i = 0; i &lt; records.length; i++) {
    var item = records[i];
    var found = false;

    for (var j = 0; j &lt; labels.length; j++) {
      if (labels[j] == item.MonitorCategoryId) {
        found = true;
        series[j] += 1;
        break;
      }
    }
    if (!found) {
      series.push(1);
      labels.push(item.MonitorCategoryId);
    }
  }  
  
  // Draw
  chartDiv.show();
  
  var options = {
    legend: { show: true, position: "bottom", height: 18, fontSize: "9px" },
  
    series: series,
    labels: labels,
  }

  if (!chart) {
    chart = widget.UI.Charts.ApexCharts.PieChart(chartDiv, options);
    chart.render();
    
    mMonitoredAccountsCharts[accountMonitorCategoryIndex] = chart;    
  }
  else {
    chart.updateOptions(options);  
  }
}

// ====================
// Quick Button Handler
// ====================
function QuickButton(buttonId) {
  var action;

  for (var i = 0; i &lt; mRecord.QuickButtonActions.length; i++) {
    var a = mRecord.QuickButtonActions[i];

    if (buttonId == a.Code) {
      action = a.Description;
      break;
    }
  }

  if (action) {
    widget.ExecuteApplicationShortcutUrl(action);
  }
  else {
    window.alert("Unhandled Quick Button '" + buttonId + "'.");
  }
}

// ====================
// Notification Handler
// ====================
function Widget_NotificationHandler(actionId, data) {
  // Assume any notification MAY require a refresh of this Widget but avoid multiple refreshes in quick succession
  if (mRefreshTimer) window.clearTimeout(mRefreshTimer);
  mRefreshTimer = window.setTimeout(function() {
    window.clearTimeout(mRefreshTimer);
    mRefreshTimer = null;
  
    Record_Load();
  }, 1000);
}

// =============
// Reset Handler
// =============
function Widget_ResetHandler() {
  Record_Load();
}
&lt;/script&gt;

&lt;/body&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>lVisi-WPR0idtT6cD5gGog</UniqueId>
    <AllowRefresh>true</AllowRefresh>
    <Caption>User Dashboard</Caption>
    <HtmlWidgetAllowInitialEventCaching>false</HtmlWidgetAllowInitialEventCaching>
    <HtmlWidgetMaxHeight>0</HtmlWidgetMaxHeight>
    <HtmlWidgetMaxWidth>0</HtmlWidgetMaxWidth>
    <HtmlWidgetNeverApplyStyling>true</HtmlWidgetNeverApplyStyling>
    <HtmlWidgetResourceChartsApex>true</HtmlWidgetResourceChartsApex>
    <HtmlWidgetResourceCssSummaryPage2>false</HtmlWidgetResourceCssSummaryPage2>
    <HtmlWidgetResourceCssWidget>true</HtmlWidgetResourceCssWidget>
    <HtmlWidgetResourceJQuery>true</HtmlWidgetResourceJQuery>
    <HtmlWidgetResourceJQueryVersion />
    <HtmlWidgetSpecialEventGetFolderCount>false</HtmlWidgetSpecialEventGetFolderCount>
    <HtmlWidgetSpecialEventShowAsSummaryPage>false</HtmlWidgetSpecialEventShowAsSummaryPage>
    <HtmlWidgetSummaryPageObjectType>None</HtmlWidgetSummaryPageObjectType>
    <Icon />
    <RestrictedOriginsListEnabled>false</RestrictedOriginsListEnabled>
    <RunAsAdministrator>false</RunAsAdministrator>
    <WebServiceName />
    <WebServiceAllowAnonymous>false</WebServiceAllowAnonymous>
    <WebServiceSendDebugInformation>false</WebServiceSendDebugInformation>
    <ShowInMenu>None</ShowInMenu>
    <ParametersType>Custom</ParametersType>
    <Parameters>
      <ISParameterDefs version="1.00">
        <Parameters>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>Specify tabs to show.</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText>The default behaviour is for all pages to be displayed. To customise, move pages from the left column to the right to display the page, and all pages which remain on the left will be hidden.</TooltipText>
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="DisplayPages" type="GroupingList">
            <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>Tasks Due,Upcoming Tasks,Quotes and Applications,Open Accounts,Monitored Accounts,Workflows</List>
            <GroupingListShowPageBreakButton>false</GroupingListShowPageBreakButton>
            <NoIndent>true</NoIndent>
          </Parameter>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>Specify quick buttons to show on the main page.</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText>The default behaviour is for all buttons to be displayed. To customise, move buttons from the left column to the right to display the button, and all buttons which remain on the left will be hidden.</TooltipText>
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="QuickButtons" type="GroupingList">
            <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>Quick Quote,New Application,New Loan,New Deposit</List>
            <GroupingListShowPageBreakButton>false</GroupingListShowPageBreakButton>
            <NoIndent>true</NoIndent>
          </Parameter>
          <Parameter name="QuickQuoteScriptId" type="Range">
            <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>
            <LimitToList>false</LimitToList>
            <MaxLength>10</MaxLength>
            <RangeSingle>true</RangeSingle>
            <RangeType>Standard</RangeType>
            <RangeLookupSource>Scripts</RangeLookupSource>
            <RangeLookupSqlWhere>ScriptTypeText='html widget'</RangeLookupSqlWhere>
          </Parameter>
          <Parameter name="AccountAppTypeId" type="Range">
            <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>
            <LimitToList>false</LimitToList>
            <MaxLength>10</MaxLength>
            <RangeSingle>true</RangeSingle>
            <RangeType>Standard</RangeType>
            <RangeLookupSource>AccountAppTypes</RangeLookupSource>
            <RangeLookupSqlWhere />
          </Parameter>
          <Parameter name="LoanAccountTypeId" type="Range">
            <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>
            <LimitToList>false</LimitToList>
            <MaxLength>10</MaxLength>
            <RangeSingle>true</RangeSingle>
            <RangeType>Standard</RangeType>
            <RangeLookupSource>AccountTypes</RangeLookupSource>
            <RangeLookupSqlWhere />
          </Parameter>
          <Parameter name="DepositAccountTypeId" type="Range">
            <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>
            <LimitToList>false</LimitToList>
            <MaxLength>10</MaxLength>
            <RangeSingle>true</RangeSingle>
            <RangeType>Standard</RangeType>
            <RangeLookupSource>AccountTypes</RangeLookupSource>
            <RangeLookupSqlWhere />
          </Parameter>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>Specify boxes to show on the main page.</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText>The default behaviour is for all boxes to be displayed. To customise, move boxes from the left column to the right to display the box, and all boxes which remain on the left will be hidden.</TooltipText>
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="HomeBoxes" type="GroupingList">
            <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>Tasks Due,Upcoming Tasks,Open Accounts,Quotes &amp; Applications,Monitored Accounts A,Monitored Accounts B,Monitored Accounts C,Added Recently,Updated Recently</List>
            <GroupingListShowPageBreakButton>false</GroupingListShowPageBreakButton>
            <NoIndent>true</NoIndent>
          </Parameter>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>Other options.</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="RecentDays" 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>10</Value>
            <Visible>true</Visible>
            <DecimalPlaces>0</DecimalPlaces>
            <GroupDigits>true</GroupDigits>
            <MaxValue />
            <MinValue />
            <NumberSpecialType>None</NumberSpecialType>
            <SpinChange>1</SpinChange>
          </Parameter>
          <Parameter name="TasksUpcomingDays" 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>7</Value>
            <Visible>true</Visible>
            <DecimalPlaces>0</DecimalPlaces>
            <GroupDigits>true</GroupDigits>
            <MaxValue />
            <MinValue />
            <NumberSpecialType>None</NumberSpecialType>
            <SpinChange>1</SpinChange>
          </Parameter>
          <Parameter name="OpenAccountsAllRoleId" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText>Specify a Role which, if a User belongs to, will show all "Open" Accounts rather than just those where the current User is the Manager.</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.Roles</List>
            <LimitToList>false</LimitToList>
            <MaxLength>10</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>Tasks View and Task Manager 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>