<?xml version="1.0" encoding="utf-8"?><finScript version="1.00" exportedUtcDate="2021-06-01T21:43:46.0000000"><CreatedUserId>Admin</CreatedUserId><CreatedUtcDate>2017-09-11T23:10:34.1780000</CreatedUtcDate><UpdatedUserId>Admin</UpdatedUserId><UpdatedUtcDate>2021-06-01T21:42:32.2420000</UpdatedUtcDate><ScriptId>WIDMDAA</ScriptId><Description>Account Applications Breakdown</Description><ScriptType>HtmlWidget</ScriptType><Active>true</Active><AllowUI>false</AllowUI><Category>Management Reports</Category><Code>' HtmlWidget_AccountAppsBreakdown
Option Explicit On
Option Strict On

' #################################################################
' Account Applications Breakdown Management Report HTML Widget
'
' Version: 1.08 (2/06/2021)
'
' Usage: System-supplied HTML Widget
' #################################################################

' Constants
Private Const PERIODS As String = "Today,Since Yesterday,7 Days,4 Weeks,3 Months,6 Months,1 Year,Forever"

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

' Other
Private mColumns As ISList
Private mColumnsBreakdown As ISList

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

  ' Assume Success
  Main = True

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

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

  ' Other Parameters
  With mCombinedParameters
    mColumns = .GetListFromGroupingList("Columns")
    mColumnsBreakdown = .GetListFromGroupingList("ColumnsBreakdown")
  End With
  If mColumns.Count = 0 Then mColumns.FromCsvString("Description,Open Count,Open Value,Accepted Count,Accepted Value,Declined Count,Declined Value,Unwanted Count,Unwanted Value")
  If mColumnsBreakdown.Count = 0 Then mColumnsBreakdown.FromCsvString("Application,Manager,Status,Sub Status,Type,Value,Created")

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

    Case "GetReportData"
      ' Get Report Data
      Main = GetReportData(returnValue)

    Case "GetBreakdownData"
      ' Get Breakdown Report Data
      Main = GetBreakdownData(returnValue)
  End Select

End Function

Private Function GetPage() As String

  Dim AllowBreakdown As Boolean
  Dim AutoShowBreakdown As Boolean
  Dim BasisList As ISCodeDescriptionList
  Dim CustomReportTitle As String
  Dim DefaultBasis As String
  Dim DefaultPeriod As String
  Dim Html As String
  Dim Layout As String

  ' Initialise
  Html = ScriptInfo.TemplateText

  ' Get Parameters
  With mCombinedParameters
    AllowBreakdown = .GetBoolean("AllowBreakdown", True)
    AutoShowBreakdown = .GetBoolean("AutoShowBreakdown", True)
    CustomReportTitle = .GetString("CustomReportTitle")
    DefaultBasis = .GetString("Basis")
    DefaultPeriod = .GetString("DefaultPeriod")
    Layout = .GetString("Layout", "Page")
  End With
  If Len(CustomReportTitle) = 0 Then CustomReportTitle = "Account Applications"
  If Len(DefaultBasis) = 0 Then DefaultBasis = "Application Status"
  If Len(DefaultPeriod) = 0 OrElse DefaultPeriod = "(Auto)" Then DefaultPeriod = GetLatestPeriodWithData()

  ' Build Basis List available to the User (this is licence-dependent)
  ' NOTE: As far a cusomising this Widget is concerned, the full list is defined as a Script parameter
  BasisList = finBL.Runtime.CreateCodeDescriptionList()
  With BasisList
    .Add("Status", "Status")
    .Add("Type", "Type")
    If finBL.Settings.AddOns.Branch Then .Add("Branch", "Branch")
    If finBL.Settings.AddOns.ExternalPartyBrokers AndAlso finBL.CurrentUserInformation.ExternalPartyType &lt;&gt; isefinExternalPartyType.Broker Then .Add("Broker", "Broker")
    If finBL.Settings.AddOns.ExternalPartyDealers AndAlso finBL.CurrentUserInformation.ExternalPartyType &lt;&gt; isefinExternalPartyType.Dealer Then .Add("Dealer", "Dealer")
    .Add("Manager", "Manager")
    If finBL.Settings.MonitorCategoryAUseAccountApp Then .Add("Monitor Category A", finBL.Settings.MonitorCategoryADescriptionResolved)
    If finBL.Settings.MonitorCategoryBUseAccountApp Then .Add("Monitor Category B", finBL.Settings.MonitorCategoryBDescriptionResolved)
    If finBL.Settings.MonitorCategoryCUseAccountApp Then .Add("Monitor Category C", finBL.Settings.MonitorCategoryCDescriptionResolved)
  End With

  ' Replace Tags
  Html = Replace(Html, "&lt;%[AllowBreakdown]%&gt;", LCase(CStr(AllowBreakdown)))
  Html = Replace(Html, "&lt;%[AutoShowBreakdown]%&gt;", LCase(CStr(AutoShowBreakdown)))
  Html = Replace(Html, "&lt;%[BasisList]%&gt;", BasisList.ToJsonString(False))
  Html = Replace(Html, "&lt;%[Columns]%&gt;", mColumns.ToJsonString())
  Html = Replace(Html, "&lt;%[ColumnsBreakdown]%&gt;", mColumnsBreakdown.ToJsonString())
  Html = Replace(Html, "&lt;%[CustomReportTitle]%&gt;", finBL.Runtime.HtmlUtilities.JavascriptEncode(CustomReportTitle, True))
  Html = Replace(Html, "&lt;%[DefaultBasis]%&gt;", DefaultBasis)
  Html = Replace(Html, "&lt;%[HasUserFilters]%&gt;", LCase(CStr(finBL.CurrentUserInformation.HasFilterAccount)))
  Html = Replace(Html, "&lt;%[Layout]%&gt;", Layout)
  Html = Replace(Html, "&lt;%[Periods]%&gt;", PERIODS)
  Html = Replace(Html, "&lt;%[Period]%&gt;", DefaultPeriod)

  Return Html

End Function

Private Function GetReportData(ByRef returnValue As String) As Boolean

  Dim Basis As String
  Dim Database As ISDatabaseBL
  Dim DataRow As DataRow
  Dim DateRange As ISDateRange
  Dim dt As DataTable
  Dim sqb As ISSelectQueryBuilder
  Dim Record As Record
  Dim Response As ReportResponse
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  Database = finBL.Database

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

  ' Initialise Response
  Response = New ReportResponse()
  With Response
    .Items = New List(Of Record)
  End With

  ' Validate
  If Success Then
  End If

  ' Build Query
  If Success Then
    sqb = Database.CreateSelectQueryBuilder()
    With sqb
      .Table = "AccountApp"
      If mColumns.Exists("Accepted Count") Then
        .Fields.AddFunction("Sum(" &amp; finBL.Database.SqlIif("[Status]=" &amp; isefinAccountAppStatus.Accepted, "1", "0", True) &amp; ")", "AcceptedCount")
      End If
      If mColumns.Exists("Accepted Value") Then
        .Fields.AddFunction("Sum(" &amp; finBL.Database.SqlIif("[Status]=" &amp; isefinAccountAppStatus.Accepted, "[TotalAdvances]", "0", True) &amp; ")", "AcceptedValue")
      End If
      If mColumns.Exists("Declined Count") Then
        .Fields.AddFunction("Sum(" &amp; finBL.Database.SqlIif("[Status]=" &amp; isefinAccountAppStatus.Declined, "1", "0", True) &amp; ")", "DeclinedCount")
      End If
      If mColumns.Exists("Declined Value") Then
        .Fields.AddFunction("Sum(" &amp; finBL.Database.SqlIif("[Status]=" &amp; isefinAccountAppStatus.Declined, "[PreferredLoanAmount]", "0", True) &amp; ")", "DeclinedValue")
      End If
      If mColumns.Exists("Complete Count") OrElse mColumns.Exists("Open Count") Then
        .Fields.AddFunction("Sum(" &amp; finBL.Database.SqlIif("[Status]=" &amp; isefinAccountAppStatus.Complete, "1", "0", True) &amp; ")", "CompleteCount")
      End If
      If mColumns.Exists("Complete Value") OrElse mColumns.Exists("Open Value") Then
        .Fields.AddFunction("Sum(" &amp; finBL.Database.SqlIif("[Status]=" &amp; isefinAccountAppStatus.Complete, "[TotalAdvances]", "0", True) &amp; ")", "CompleteValue")
      End If
      If mColumns.Exists("Incomplete Count") OrElse mColumns.Exists("Open Count") Then
        .Fields.AddFunction("Sum(" &amp; finBL.Database.SqlIif("[Status]=" &amp; isefinAccountAppStatus.Incomplete, "1", "0", True) &amp; ")", "IncompleteCount")
      End If
      If mColumns.Exists("Incomplete Value") OrElse mColumns.Exists("Open Value") Then
        .Fields.AddFunction("Sum(" &amp; finBL.Database.SqlIif("[Status]=" &amp; isefinAccountAppStatus.Incomplete, "[PreferredLoanAmount]", "0", True) &amp; ")", "IncompleteValue")
      End If
      If mColumns.Exists("Reviewing Count") OrElse mColumns.Exists("Open Count") Then
        .Fields.AddFunction("Sum(" &amp; finBL.Database.SqlIif("[Status]=" &amp; isefinAccountAppStatus.Reviewing, "1", "0", True) &amp; ")", "ReviewingCount")
      End If
      If mColumns.Exists("Reviewing Value") OrElse mColumns.Exists("Open Value") Then
        .Fields.AddFunction("Sum(" &amp; finBL.Database.SqlIif("[Status]=" &amp; isefinAccountAppStatus.Reviewing, "[PreferredLoanAmount]", "0", True) &amp; ")", "ReviewingValue")
      End If
      If mColumns.Exists("Unwanted Count") Then
        .Fields.AddFunction("Sum(" &amp; finBL.Database.SqlIif("[Status]=" &amp; isefinAccountAppStatus.Unwanted, "1", "0", True) &amp; ")", "UnwantedCount")
      End If
      If mColumns.Exists("Unwanted Value") Then
        .Fields.AddFunction("Sum(" &amp; finBL.Database.SqlIif("[Status]=" &amp; isefinAccountAppStatus.Unwanted, "[PreferredLoanAmount]", "0", True) &amp; ")", "UnwantedValue")
      End If

      ' SQL Where
      AppendSqlWhere(.SqlWhere, DateRange)

      ' Basis-Specific
      Select Case UCase(Basis)
        Case "STATUS"
          .Fields.Add("AccountApp.Status", "TypePk")
          .GroupByFields.Add("Status")

        Case "TYPE"
          .Fields.Add("AccountAppTypePk", "TypePk")
          .GroupByFields.Add("AccountAppTypePk")

        Case "BRANCH"
          .Fields.Add("BranchPk", "TypePk")
          .GroupByFields.Add("BranchPk")

        Case "BROKER"
          .Fields.Add("BrokerExPartyPk", "TypePk")
          .GroupByFields.Add("BrokerExPartyPk")

        Case "DEALER"
          .Fields.Add("DealerExPartyPk", "TypePk")
          .GroupByFields.Add("DealerExPartyPk")

        Case "MANAGER"
          .Fields.Add("AccountManagerUserPk", "TypePk")
          .GroupByFields.Add("AccountManagerUserPk")

        Case "MONITOR CATEGORY A"
          .Fields.Add("MonitorCatAPk", "TypePk")
          .GroupByFields.Add("MonitorCatAPk")

        Case "MONITOR CATEGORY B"
          .Fields.Add("MonitorCatBPk", "TypePk")
          .GroupByFields.Add("MonitorCatBPk")

        Case "MONITOR CATEGORY C"
          .Fields.Add("MonitorCatCPk", "TypePk")
          .GroupByFields.Add("MonitorCatCPk")
      End Select
    End With
  End If

  ' Execute Query and get Results
  If Success Then
    If sqb.ExecuteDataTable(dt) Then
      For Each DataRow In dt.Rows
        ' Create Record
        Record = New Record()

        ' General
        Record.Pk = Database.GetFieldInteger(DataRow!TypePk)
        If mColumns.Exists("Accepted Count") Then
          Record.AcceptedCount = Database.GetFieldInteger(DataRow!AcceptedCount)
        End If
        If mColumns.Exists("Accepted Value") Then
          Record.AcceptedValue = Database.GetFieldDecimal(DataRow!AcceptedValue)
        End If
        If mColumns.Exists("Declined Count") Then
          Record.DeclinedCount = Database.GetFieldInteger(DataRow!DeclinedCount)
        End If
        If mColumns.Exists("Declined Value") Then
          Record.DeclinedValue = Database.GetFieldDecimal(DataRow!DeclinedValue)
        End If
        If mColumns.Exists("Complete Count") OrElse mColumns.Exists("Open Count") Then
          Record.CompleteCount = Database.GetFieldInteger(DataRow!CompleteCount)
          Record.OpenCount += Record.CompleteCount
        End If
        If mColumns.Exists("Complete Value") OrElse mColumns.Exists("Open Value") Then
          Record.CompleteValue = Database.GetFieldDecimal(DataRow!CompleteValue)
          Record.OpenValue += Record.CompleteValue
        End If
        If mColumns.Exists("Incomplete Count") OrElse mColumns.Exists("Open Count") Then
          Record.IncompleteCount = Database.GetFieldInteger(DataRow!IncompleteCount)
          Record.OpenCount += Record.IncompleteCount
        End If
        If mColumns.Exists("Incomplete Value") OrElse mColumns.Exists("Open Value") Then
          Record.IncompleteValue = Database.GetFieldDecimal(DataRow!IncompleteValue)
          Record.OpenValue += Record.IncompleteValue
        End If
        If mColumns.Exists("Reviewing Count") OrElse mColumns.Exists("Open Count") Then
          Record.ReviewingCount = Database.GetFieldInteger(DataRow!ReviewingCount)
          Record.OpenCount += Record.ReviewingCount
        End If
        If mColumns.Exists("Reviewing Value") OrElse mColumns.Exists("Open Value") Then
          Record.ReviewingValue = Database.GetFieldDecimal(DataRow!ReviewingValue)
          Record.OpenValue += Record.ReviewingValue
        End If
        If mColumns.Exists("Unwanted Count") Then
          Record.UnwantedCount = Database.GetFieldInteger(DataRow!UnwantedCount)
        End If
        If mColumns.Exists("Unwanted Value") Then
          Record.UnwantedValue = Database.GetFieldDecimal(DataRow!UnwantedValue)
        End If

        ' Basis-Specific
        Select Case UCase(Basis)
          Case "STATUS"
            ' Reset Record
            Record.Code = DirectCast(Database.GetFieldEnum(DataRow!TypePk, GetType(isefinAccountAppStatus)), isefinAccountAppStatus).ToString()
            Record.Description = finBL.Enums.isefinAccountAppStatus_ToString(DirectCast(Database.GetFieldEnum(DataRow!TypePk, GetType(isefinAccountAppStatus)), isefinAccountAppStatus))

          Case "TYPE"
            With finBL.AccountAppTypes.ItemByPk(Database.GetFieldInteger(DataRow!TypePk))
              Record.Code = .AccountAppTypeId
              Record.Description = .Description
            End With

          Case "BRANCH"
            If Database.GetFieldInteger(DataRow!TypePk) = 0 Then
              Record.Code = ""
              Record.Description = "(No Branch)"
            Else
              With finBL.Branches.ItemByPk(Database.GetFieldInteger(DataRow!TypePk))
                Record.Code = .BranchId
                Record.Description = .Description
              End With
            End If

          Case "BROKER"
            If Database.GetFieldInteger(DataRow!TypePk) = 0 Then
              Record.Code = ""
              Record.Description = "(No Broker)"
            Else
              With finBL.ExternalParties.ItemByPk(Database.GetFieldInteger(DataRow!TypePk))
                Record.Code = .ExternalPartyId
                Record.Description = .Description
              End With
            End If

          Case "DEALER"
            If Database.GetFieldInteger(DataRow!TypePk) = 0 Then
              Record.Code = ""
              Record.Description = "(No Dealer)"
            Else
              With finBL.ExternalParties.ItemByPk(Database.GetFieldInteger(DataRow!TypePk))
                Record.Code = .ExternalPartyId
                Record.Description = .Description
              End With
            End If

          Case "MANAGER"
            If Database.GetFieldInteger(DataRow!TypePk) = 0 Then
              Record.Code = ""
              Record.Description = "(No Manager)"
            Else
              With finBL.Users.ItemByPkSafe(Database.GetFieldInteger(DataRow!TypePk))
                Record.Code = .UserId
                Record.Description = .Name
              End With
            End If

          Case "MONITOR CATEGORY A"
            If Database.GetFieldInteger(DataRow!TypePk) = 0 Then
              Record.Code = ""
              Record.Description = "(No " &amp; finBL.Settings.MonitorCategoryADescriptionResolved &amp; ")"
            Else
              With finBL.MonitorCategories.ItemByPk(Database.GetFieldInteger(DataRow!TypePk))
                Record.Code = .MonitorCategoryId
                Record.Description = .Description
              End With
            End If

          Case "MONITOR CATEGORY B"
            If Database.GetFieldInteger(DataRow!TypePk) = 0 Then
              Record.Code = ""
              Record.Description = "(No " &amp; finBL.Settings.MonitorCategoryBDescriptionResolved &amp; ")"
            Else
              With finBL.MonitorCategories.ItemByPk(Database.GetFieldInteger(DataRow!TypePk))
                Record.Code = .MonitorCategoryId
                Record.Description = .Description
              End With
            End If

          Case "MONITOR CATEGORY C"
            If Database.GetFieldInteger(DataRow!TypePk) = 0 Then
              Record.Code = ""
              Record.Description = "(No " &amp; finBL.Settings.MonitorCategoryCDescriptionResolved &amp; ")"
            Else
              With finBL.MonitorCategories.ItemByPk(Database.GetFieldInteger(DataRow!TypePk))
                Record.Code = .MonitorCategoryId
                Record.Description = .Description
              End With
            End If
        End Select

        ' Add
        Response.Items.Add(Record)
      Next
    Else
      Success = False
    End If
  End If

  ' Finalise Response
  If Success Then
    With Response
      If Not DateRange.HasValue() Then
        ' Forever
      ElseIf DateRange.ValueFrom &lt;&gt; Nothing AndAlso DateRange.ValueFrom.TimeOfDay &lt;&gt; Nothing Then
        ' Include time
        .FromDateText = "starting " &amp; finBL.FormatDateTimeLong(DateRange.ValueFrom, True)
        .ToDateText = finBL.FormatDateTimeLong(DateRange.ValueTo, True)
      Else
        ' Date only
        If DateRange.ValueFrom &lt;&gt; Nothing Then .FromDateText = "starting " &amp; finBL.FormatDateLong(DateRange.ValueFrom)
        If DateRange.ValueTo &lt;&gt; Nothing Then .ToDateText = "the end of " &amp; finBL.FormatDateLong(DateRange.ValueTo.AddDays(-1))
      End If
    End With
  End If

  ' Return a JSON Object
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(Response, returnValue)
  End If

  Return Success

End Function

Private Sub AppendSqlWhere(swb As ISSqlWhereBuilder,
                           ByRef dateRange As ISDateRange)

  Dim AccountAppStatuses As String
  Dim SqlWhere As String

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

    If .GetString("Period") = "Custom" Then
      ' Custom  Dates
      dateRange = New ISDateRange(.GetDate("FromDate"), .GetDate("ToDate"))
    Else
      ' Named Range
      dateRange = GetDateRangeFromPeriod(.GetString("Period"))
    End If
  End With

  ' Update SQL Where
  With swb
    ' Account Application Status
    .AppendEnumRangeUsingStringConverter("AccountApp.Status", AccountAppStatuses, AddressOf finBL.Enums.isefinAccountAppStatus_FromStringToInt)

    ' Date Range
    .AppendDateRangeLocalToUtc("AccountApp.CreatedUtcDate", DateRange, False)

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

    ' Custom SQL Where Parameter
    If Len(SqlWhere) &lt;&gt; 0 Then .Append(SqlWhere)
  End With

End Sub

Private Function GetBreakdownData(ByRef returnValue As String) As Boolean

  Dim AllowBreakdown As Boolean
  Dim AppStatus As isefinAccountAppStatus
  Dim Basis As String
  Dim BreakdownPk As Integer
  Dim Database As ISDatabaseBL
  Dim DataRow As DataRow
  Dim dt As DataTable
  Dim sqb As ISSelectQueryBuilder
  Dim Record As BreakdownRecord
  Dim Response As List(Of BreakdownRecord)
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  Database = finBL.Database

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

  ' Initialise Response
  Response = New List(Of BreakdownRecord)

  ' Validate
  If Success Then
    If Not AllowBreakdown Then
      Success = False
      finBL.Error.ErrorBegin("Breakdowns are disabled for this Widget.")
    End If
  End If

  ' Build Query
  If Success Then
    sqb = Database.CreateSelectQueryBuilder()
    With sqb
      .Table = "AccountApp"
      .Fields.AddList("Pk,AccountAppId,AccountAppTypePk,AccountManagerUserPk,PreferredLoanAmount,TotalAdvances,CreatedUtcDate,MonitorCatAPk,MonitorCatBPk,MonitorCatCPk,Name,Status,StatusSub")

      ' SQL Where
      With .SqlWhere
        ' General
        AppendSqlWhere(sqb.SqlWhere, Nothing)

        ' Breakdown-Specific
        Select Case UCase(Basis)
          Case "STATUS"
            If BreakdownPk = 99 Then
              .BlockBegin(iseSqlWhereBuilderNestedBlockType.OrBlock)
              .AppendComparisonInteger("Status", "=", isefinAccountAppStatus.Complete)
              .AppendComparisonInteger("Status", "=", isefinAccountAppStatus.Incomplete)
              .AppendComparisonInteger("Status", "=", isefinAccountAppStatus.Reviewing)
              .BlockEnd()
            Else
              .AppendComparisonInteger("Status", "=", BreakdownPk)
            End If

          Case "TYPE"
            .AppendComparisonInteger("AccountAppTypePk", "=", BreakdownPk)

          Case "BRANCH"
            .AppendComparisonInteger("BranchPk", "=", BreakdownPk)

          Case "BROKER"
            If BreakdownPk = 0 Then
              .AppendComparisonNull("BrokerExPartyPk")
            Else
              .AppendComparisonInteger("BrokerExPartyPk", "=", BreakdownPk)
            End If

          Case "DEALER"
            If BreakdownPk = 0 Then
              .AppendComparisonNull("DealerExPartyPk")
            Else
              .AppendComparisonInteger("DealerExPartyPk", "=", BreakdownPk)
            End If

          Case "MANAGER"
            If BreakdownPk = 0 Then
              .AppendComparisonNull("AccountManagerUserPk")
            Else
              .AppendComparisonInteger("AccountManagerUserPk", "=", BreakdownPk)
            End If

          Case "MONITOR CATEGORY A"
            If BreakdownPk = 0 Then
              .AppendComparisonNull("MonitorCatAPk")
            Else
              .AppendComparisonInteger("MonitorCatAPk", "=", BreakdownPk)
            End If

          Case "MONITOR CATEGORY B"
            If BreakdownPk = 0 Then
              .AppendComparisonNull("MonitorCatBPk")
            Else
              .AppendComparisonInteger("MonitorCatBPk", "=", BreakdownPk)
            End If

          Case "MONITOR CATEGORY C"
            If BreakdownPk = 0 Then
              .AppendComparisonNull("MonitorCatCPk")
            Else
              .AppendComparisonInteger("MonitorCatCPk", "=", BreakdownPk)
            End If
        End Select
      End With

      ' Order By
      .OrderByFields.AddList("Status,CreatedUtcDate")
    End With
  End If

  ' Execute Query and get Results
  If Success Then
     If sqb.ExecuteDataTable(dt) Then
      For Each DataRow In dt.Rows
        ' Create Record
        Record = New BreakdownRecord()
        AppStatus = DirectCast(Database.GetFieldEnum(DataRow!Status, GetType(isefinAccountAppStatus)), isefinAccountAppStatus)

        ' General
        Record.Pk = Database.GetFieldInteger(DataRow!Pk)
        Record.AccountAppId = Database.GetFieldString(DataRow!AccountAppId)
        Record.Name = Database.GetFieldString(DataRow!Name)
        Record.Status = finBL.Enums.isefinAccountAppStatus_ToString(AppStatus)
        Record.SubStatus = Database.GetFieldString(DataRow!StatusSub)
        With finBL.AccountAppTypes.ItemByPk(Database.GetFieldInteger(DataRow!AccountAppTypePk))
          Record.Type = .AccountAppTypeId
        End With
        Record.DateCreated = finBL.HtmlWidgetUtilities.GetJsonUtcDateTimeFromDatabaseDateTime(finBL.TimeZoneFunctions.ConvertUtcToLocalDateTime(Database.GetFieldDate(DataRow!CreatedUtcDate)))

        ' Application Amount
        Select AppStatus
          Case isefinAccountAppStatus.Accepted
            Record.Value = Database.GetFieldDecimal(DataRow!TotalAdvances)
          Case Else
            Record.Value = Database.GetFieldDecimal(DataRow!PreferredLoanAmount)
        End Select

        ' Allocated Manager
        If Database.GetFieldInteger(DataRow!AccountManagerUserPk) &lt;&gt; 0 Then
          Record.Manager = finBL.Users.ItemByPkSafe(Database.GetFieldInteger(DataRow!AccountManagerUserPk)).UserId
        Else
          Record.Manager = ""
        End If

        ' Add
        Response.Add(Record)
      Next
    Else
      Success = False
    End If
  End If

  ' Return a JSON Object
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(Response, returnValue)
  End If

  Return Success

End Function

' Helper Functions
Public Function GetDateRangeFromPeriod(period As String) As ISDateRange

  Dim DateRange As ISDateRange
  Dim Today As DateTime

  ' Initialise
  Today = finBL.TimeZoneFunctions.GetCurrentDatabaseDate()

  Select Case period
    Case "Today"
      DateRange = New ISDateRange(Today, Today.AddDays(1))

    Case "Since Yesterday"
      DateRange = New ISDateRange(Today.AddDays(-1), Today.AddDays(1))

    Case "7 Days"
      DateRange = New ISDateRange(Today.AddDays(-6), Today.AddDays(1))

    Case "4 Weeks"
      DateRange = New ISDateRange(Today.AddDays(-27), Today.AddDays(1))

    Case "3 Months"
      DateRange = New ISDateRange(Today.AddMonths(-3).AddDays(1), Today.AddDays(1))

    Case "6 Months"
      DateRange = New ISDateRange(Today.AddMonths(-6).AddDays(1), Today.AddDays(1))

    Case "1 Year"
      DateRange = New ISDateRange(Today.AddYears(-1).AddDays(1), Today.AddDays(1))

    Case "Forever"
      DateRange = New ISDateRange()

    Case Else
      finBL.Trace.WriteWarning("Unhandled Date Range.")
  End Select

  Return DateRange

End Function

Private Function GetLatestPeriodWithData() As String

  Dim AccountAppStatuses As String
  Dim sqb As ISSelectQueryBuilder
  Dim tempDate As Date

  ' Initialise
  AccountAppStatuses = mCombinedParameters.GetString("AccountAppStatuses")

  sqb = finBL.Database.CreateSelectQueryBuilder()
  With sqb
    .Table = "AccountApp"
    .Fields.AddMax("CreatedUtcDate")

    ' SQL Where
    With .SqlWhere
      ' Account Application Status
      .AppendEnumRangeUsingStringConverter("AccountApp.Status", AccountAppStatuses, AddressOf finBL.Enums.isefinAccountAppStatus_FromStringToInt)

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

    ' Execute
    If .GetScalarDate(tempDate) AndAlso tempDate &lt;&gt; Nothing Then
      Return GetPeriodFromDate(tempDate)
    Else
      ' Ignore
    End If
  End With

  Return "Today"

End Function

Public Function GetPeriodFromDate(d As Date) As String

  Dim List As ISList
  Dim s As String

  ' Initialise
  List = New ISList(PERIODS)

  ' Scan Periods
  For Each s In List
    Select Case s
      Case "Forever"
        ' Ignore

      Case Else
        If GetDateRangeFromPeriod(s).IsValueInRange(d) Then
          ' Found
          Return s
        End If
    End Select
  Next

  Return "Today"

End Function


' Classes
Public Class ReportResponse

  Public FromDateText As String
  Public ToDateText As String
  Public Items As List(Of Record)

End Class

Public Class Record

  Public Pk As Integer
  Public Code As String
  Public Description As String

  Public AcceptedCount As Integer
  Public AcceptedValue As Decimal
  Public CompleteCount As Integer
  Public CompleteValue As Decimal
  Public DeclinedCount As Integer
  Public DeclinedValue As Decimal
  Public IncompleteCount As Integer
  Public IncompleteValue As Decimal
  Public OpenCount As Integer
  Public OpenValue As Decimal
  Public ReviewingCount As Integer
  Public ReviewingValue As Decimal
  Public UnwantedCount As Integer
  Public UnwantedValue As Decimal

End Class

Public Class BreakdownRecord

  Public Pk As Integer
  Public AccountAppId As String
  Public Name As String
  Public Manager As String
  Public DateCreated As Date
  Public Status As String
  Public SubStatus As String
  Public Type As String
  Public Value As Decimal

End Class</Code><Language>VisualBasic</Language><Notes>System defined HTML Widget to provide a sample Management Dashboard that shows a breakdown of Account Applications by various different basis.</Notes><PermissionKeyExecute /><RunWithoutPrompts>false</RunWithoutPrompts><TemplateText>&lt;head&gt;
&lt;!--Load Google Charts API--&gt;
&lt;script type="text/javascript" src="https://www.google.com/jsapi"&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;

&lt;div id="divReport" class="is-widget-content" style="display:none"&gt;

  &lt;div id="divHeading"&gt;
    &lt;h1 id="lblMainTitle"&gt;Account Applications&lt;/h1&gt;

    &lt;div id="blActions"&gt;&lt;/div&gt;
    &lt;div id="divCustomPeriod" style="display:none; margin-top:4px; margin-bottom:4px"&gt;
      &lt;input id="dateFromDate"/&gt;
      &lt;label for="dateToDate"&gt; &lt;small&gt;to&lt;/small&gt; &lt;/label&gt;&lt;input id="dateToDate"/&gt;
      &lt;button id="cmdRunCustom" class="is-button small"&gt;Run&lt;/button&gt;
    &lt;/div&gt;
  &lt;/div&gt;

  &lt;div id="divMain" style="max-width:1400px;"&gt;
    &lt;table id="gridItems" class="is-grid is-widget-report" style="width:100%"&gt;
      &lt;thead&gt;
        &lt;tr&gt;
          &lt;th key="ShowBreakdown" data-type="drilldown" style="width:20px" drilldown-glyph="breakdown"&gt;&lt;/th&gt;
          &lt;th key="Code" caption="Code" data-type="html" sortable="true" style="width:8em"&gt;&lt;input id="cboBasis"/&gt;&lt;/th&gt;
        &lt;/tr&gt;
      &lt;/thead&gt;
    &lt;/table&gt;
  &lt;/div&gt;


  &lt;div id="divChart" style="position:relative"&gt;
    &lt;div id="blChartActions"&gt;&lt;/div&gt;
    &lt;div id="divCharts"&gt;
      &lt;div id="divChartMain"&gt;&lt;div id="chrtMain"&gt;&lt;/div&gt;&lt;/div&gt;
      &lt;div id="divChartOverallCount"&gt;&lt;div id="chrtOverallCount"&gt;&lt;/div&gt;&lt;/div&gt;
      &lt;div id="divChartOverallValue"&gt;&lt;div id="chrtOverallValue"&gt;&lt;/div&gt;&lt;/div&gt;
      &lt;div id="divChartOverallCountPercent"&gt;&lt;div id="chrtOverallCountPercent"&gt;&lt;/div&gt;&lt;/div&gt;
      &lt;div id="divChartOverallValuePercent"&gt;&lt;div id="chrtOverallValuePercent"&gt;&lt;/div&gt;&lt;/div&gt;
      &lt;div id="divChartBreakdown"&gt;&lt;div id="chrtBreakdown"&gt;&lt;/div&gt;&lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;


  &lt;div id="divBreakdown" style="clear:both; display:none; padding-top:8px"&gt;

    &lt;h2 id="lblBreakdownTitle"&gt;&lt;/h2&gt;

    &lt;div id="divBreakdownTable"&gt;
      &lt;table id="gridBreakdown" class="is-grid is-widget-report" style="width:auto"&gt;
      &lt;/table&gt;
    &lt;/div&gt;
  &lt;/div&gt;

&lt;/div&gt;


&lt;script&gt;
// Server-side information
var mAllowBreakdown = &lt;%[AllowBreakdown]%&gt;;
var mAutoShowBreakdown = &lt;%[AutoShowBreakdown]%&gt;;
var mBasisList = &lt;%[BasisList]%&gt;;
var mColumns = &lt;%[Columns]%&gt;;
var mColumnsBreakdown = &lt;%[ColumnsBreakdown]%&gt;;
var mCustomReportTitle = &lt;%[CustomReportTitle]%&gt;;
var mHasUserFilters = &lt;%[HasUserFilters]%&gt;;
var mLayout = "&lt;%[Layout]%&gt;";
var mPeriods = "&lt;%[Periods]%&gt;".split(",");
var mPeriod = "&lt;%[Period]%&gt;";
var mDefaultBasis = "&lt;%[DefaultBasis]%&gt;";

// Controls
var C = {
  // Main
  blActions: null,
  dateFromDate: null,
  dateToDate: null,

  lblMainTitle: null,

  cboBasis: null,
  gridItems: null,

  // Charts
  divCharts: null,
  divChart: null,
  blChartActions: null,

  divChartMain: null,
  chrtMain: null,

  divChartOverallCount: null,
  chrtOverallCount: null,
  divChartOverallValue: null,
  chrtOverallValue: null,
  divChartOverallCountPercent: null,
  chrtOverallCountPercent: null,
  divChartOverallValuePercent: null,
  chrtOverallValuePercent: null,

  divChartBreakdown: null,
  chrtBreakdown: null,

  // Breakdown
  lblBreakdownTitle: null,
  divBreakdown: null,
  gridBreakdown: null,
}

var mResultsMain = null;
var mResultsMainFiltered = null;
var mResultsBreakdown = null;
var mUpdateChartsPanelTimer;

var mBasisDescription;
var mBasis;
var mBreakdownIndex = -1;
var mMainChartFieldId;
var mBreakdownChartFieldId;

var mChartColoursMain = ["#3366cc","#dc3912","#ff9900","#109618","#990099","#0099c6","#dd4477","#66aa00","#b82e2e","#316395","#994499","#22aa99","#aaaa11","#6633cc","#e67300","#8b0707","#651067","#329262","#5574a6","#3b3eac","#b77322","#16d620","#b91383","#f4359e","#9c5935","#a9c413","#2a778d","#668d1c","#bea413","#0c5922","#743411"];
var mChartDataMain, mChartOptionsMain;
var mChartsZoomed = false;
var mChartTitleMain = "";
var mChartTitleSub = "";

// Load the Visualization API and the corechart package.
google.charts.load("current", {"packages":["corechart", "bar"]});


// Initialise
$(function () {
  // ----------------
  // Dashboard Layout
  // ----------------
  var stickyHeader = false;
  if (mLayout == "Dashboard" &amp;&amp; !widget.UI.IsSmallMobileBrowser()) {
    // Create Dashboard
    stickyHeader = true;
    var DashboardLayout = widget.UI.DashboardLayout("divReport", {});

    DashboardLayout.AddHeading("divHeading");
    DashboardLayout.AddColumn({ width: "50%"}, [
      { element: "divMain" }
    ]);
    DashboardLayout.AddColumn({ width: "50%", maxWidth: "720px", minWidth: "320px"}, [
      {
        element: "divChart",
        maxHeight: "360px",
        zoomable: true,
        onZoomIn: function() { mChartsZoomed = true; UpdateChartsPanel(); },
        onZoomOut: function() { mChartsZoomed = false; UpdateChartsPanel(); }
      },
      { element: "divBreakdown", headingElement: "lblBreakdownTitle", visible: mAllowBreakdown },
    ]);

    // Additional Dashboard formatting
    $("#blChartActions").css({ "margin-left": "4px" });
    $("#divCharts").css({ position: "absolute", top: "38px", left: "4px", right: 0, bottom: 0, "overflow-x": "hidden", "overflow-y":"auto" });
  }

  // --------
  // Controls
  // --------
  C.blActions = widget.UI.ButtonList("blActions", {
    style: "actions",
    onChange: blActions_Change
  });

  C.dateFromDate = widget.UI.DateBox("dateFromDate", {});
  C.dateToDate = widget.UI.DateBox("dateToDate", {});

  C.lblMainTitle = widget.UI.Label("lblMainTitle", {});

  C.cboBasis = widget.UI.ComboBox("cboBasis", {
    limitToList: true,
    width: "10em",

    onChange: cboBasis_Change,
  });
  C.cboBasis.ListFromCollection(mBasisList, "Description");
  C.cboBasis.Text(mDefaultBasis);

  C.divCharts = $("#divCharts");
  C.divChart = $("#divChart");
  C.blChartActions = widget.UI.ButtonList("blChartActions", {
    style: "actions",
    size: "normal",
    onChange: blChartActions_Change
  });

  C.divChartMain = $("#divChartMain");
  C.divChartOverallCount = $("#divChartOverallCount");
  C.divChartOverallValue = $("#divChartOverallValue");
  C.divChartOverallCountPercent = $("#divChartOverallCountPercent");
  C.divChartOverallValuePercent = $("#divChartOverallValuePercent");
  C.divChartBreakdown = $("#divChartBreakdown");

  C.lblBreakdownTitle = widget.UI.Label("lblBreakdownTitle", {});
  C.divBreakdown = $("#divBreakdown");

  // Initialise Grids
  C.gridItems = widget.UI.Grid("gridItems", {
    style: "report",
    stickyHeader: stickyHeader,

    showRowSelectors: true,
    allowMultiRowSelect: true,

    onInitialiseRow: gridItems_InitialiseRow,
    onAfterRowActivate: gridItems_AfterRowActivate,
    onColumnSelect: gridItems_ColumnSelect,
    onAfterColumnSort: gridItems_AfterColumnSort,
    onRowDrilldown: gridItems_RowDrilldown,
    onSelectedRowsChanged: gridItems_SelectedRowsChanged,
  });

  C.gridBreakdown = widget.UI.Grid("gridBreakdown", {
    style: "",
    stickyHeader: stickyHeader,
    groupByColumns:"Status",

    onInitialiseRow: gridBreakdown_InitialiseRow,
    onColumnSelect: gridBreakdown_ColumnSelect,
  });

  // Mandatory Main Grid columns
  C.gridItems.ColumnVisible("ShowBreakdown", mAllowBreakdown &amp;&amp; !mAutoShowBreakdown);

  // Add optional Main Grid columns
  for(var i = 0; i &lt; mColumns.length; i++) {
    switch(mColumns[i].toUpperCase()) {
      case "DESCRIPTION":
        C.gridItems.AddColumnString("Description",{caption: "Description", sortable: true});
        break;

      case "OPEN COUNT":
        C.gridItems.AddColumnInteger("OpenCount",{caption: "&lt;html&gt;&lt;span style='border-bottom:2px solid blue'&gt;Count&lt;/span&gt;", selectable: true, sortable: true, summary: "sum", captionChart: "Open #", colourChart: "blue"});
        if (!mMainChartFieldId) mMainChartFieldId = "OpenCount";
        break;

      case "OPEN VALUE":
        C.gridItems.AddColumnCurrency("OpenValue",{caption: "&lt;html&gt;&lt;span style='border-bottom:2px solid blue'&gt;Value&lt;/span&gt;", selectable: true, sortable: true, summary: "$sum", captionChart: "Open " + widget.CurrencySymbol(), colourChart: "blue"});
        if (!mMainChartFieldId) mMainChartFieldId = "OpenValue";
        break;

      case "COMPLETE COUNT":
        C.gridItems.AddColumnInteger("CompleteCount",{caption: "&lt;html&gt;&lt;span style='border-bottom:2px solid #FF55FF'&gt;Count&lt;/span&gt;", selectable: true, sortable: true, summary: "sum", captionChart: "Complete #", colourChart: "#FF55FF"});
        if (!mMainChartFieldId) mMainChartFieldId = "CompleteCount";
        break;

      case "COMPLETE VALUE":
        C.gridItems.AddColumnCurrency("CompleteValue",{caption: "&lt;html&gt;&lt;span style='border-bottom:2px solid #FF55FF'&gt;Value&lt;/span&gt;", selectable: true, sortable: true, summary: "$sum", captionChart: "Complete " + widget.CurrencySymbol(), colourChart: "#FF55FF"});
        if (!mMainChartFieldId) mMainChartFieldId = "CompleteValue";
        break;

      case "INCOMPLETE COUNT":
        C.gridItems.AddColumnInteger("IncompleteCount",{caption: "&lt;html&gt;&lt;span style='border-bottom:2px solid #BB00FF'&gt;Count&lt;/span&gt;", selectable: true, sortable: true, summary: "sum", captionChart: "Incomplete #", colourChart: "#BB00FF"});
        if (!mMainChartFieldId) mMainChartFieldId = "IncompleteCount";
        break;

      case "INCOMPLETE VALUE":
        C.gridItems.AddColumnCurrency("IncompleteValue",{caption: "&lt;html&gt;&lt;span style='border-bottom:2px solid #BB00FF'&gt;Value&lt;/span&gt;", selectable: true, sortable: true, summary: "$sum", captionChart: "Incomplete " + widget.CurrencySymbol(), colourChart: "#BB00FF"});
        if (!mMainChartFieldId) mMainChartFieldId = "IncompleteValue";
        break;

      case "REVIEWING COUNT":
        C.gridItems.AddColumnInteger("ReviewingCount",{caption: "&lt;html&gt;&lt;span style='border-bottom:2px solid #EE44BB'&gt;Count&lt;/span&gt;", selectable: true, sortable: true, summary: "sum", captionChart: "Reviewing #", colourChart: "#EE44BB"});
        if (!mMainChartFieldId) mMainChartFieldId = "ReviewingCount";
        break;

      case "REVIEWING VALUE":
        C.gridItems.AddColumnCurrency("ReviewingValue",{caption: "&lt;html&gt;&lt;span style='border-bottom:2px solid #EE44BB'&gt;Value&lt;/span&gt;", selectable: true, sortable: true, summary: "$sum", captionChart: "Reviewing " + widget.CurrencySymbol(), colourChart: "#EE44BB"});
        if (!mMainChartFieldId) mMainChartFieldId = "ReviewingValue";
        break;

      case "ACCEPTED COUNT":
        C.gridItems.AddColumnInteger("AcceptedCount",{caption: "&lt;html&gt;&lt;span style='border-bottom:2px solid lime'&gt;Count&lt;/span&gt;", selectable: true, sortable: true, summary: "sum", captionChart: "Accepted #", colourChart: "lime"});
        if (!mMainChartFieldId) mMainChartFieldId = "AcceptedCount";
        break;

      case "ACCEPTED VALUE":
        C.gridItems.AddColumnCurrency("AcceptedValue",{caption: "&lt;html&gt;&lt;span style='border-bottom:2px solid lime'&gt;Value&lt;/span&gt;", selectable: true, sortable: true, summary: "$sum", captionChart: "Accepted " + widget.CurrencySymbol(), colourChart: "lime"});
        if (!mMainChartFieldId) mMainChartFieldId = "AcceptedValue";
        break;

      case "DECLINED COUNT":
        C.gridItems.AddColumnInteger("DeclinedCount",{caption: "&lt;html&gt;&lt;span style='border-bottom:2px solid red'&gt;Count&lt;/span&gt;", selectable: true, sortable: true, summary: "sum", captionChart: "Declined #", colourChart: "red"});
        if (!mMainChartFieldId) mMainChartFieldId = "DeclinedCount";
        break;

      case "DECLINED VALUE":
        C.gridItems.AddColumnCurrency("DeclinedValue",{caption: "&lt;html&gt;&lt;span style='border-bottom:2px solid red'&gt;Value&lt;/span&gt;", selectable: true, sortable: true, summary: "$sum", captionChart: "Declined " + widget.CurrencySymbol(), colourChart: "red"});
        if (!mMainChartFieldId) mMainChartFieldId = "DeclinedValue";
        break;

      case "UNWANTED COUNT":
        C.gridItems.AddColumnInteger("UnwantedCount",{caption: "&lt;html&gt;&lt;span style='border-bottom:2px solid gold'&gt;Count&lt;/span&gt;", selectable: true, sortable: true, summary: "sum", captionChart: "Unwanted #", colourChart: "gold"});
        if (!mMainChartFieldId) mMainChartFieldId = "UnwantedCount";
        break;

      case "UNWANTED VALUE":
        C.gridItems.AddColumnCurrency("UnwantedValue",{caption: "&lt;html&gt;&lt;span style='border-bottom:2px solid gold'&gt;Value&lt;/span&gt;", selectable: true, sortable: true, summary: "$sum", captionChart: "Unwanted " + widget.CurrencySymbol(), colourChart: "gold"});
        if (!mMainChartFieldId) mMainChartFieldId = "UnwantedValue";
        break;
    }
  }
  if (mMainChartFieldId) C.gridItems.SelectedColumnKey(mMainChartFieldId);

  C.gridItems.MergeColumnHeaders("OpenCount,OpenValue","Open");
  C.gridItems.MergeColumnHeaders("CompleteCount,CompleteValue","Complete");
  C.gridItems.MergeColumnHeaders("IncompleteCount,IncompleteValue","Incomplete");
  C.gridItems.MergeColumnHeaders("ReviewingCount,ReviewingValue","Reviewing");
  C.gridItems.MergeColumnHeaders("AcceptedCount,AcceptedValue","Accepted");
  C.gridItems.MergeColumnHeaders("DeclinedCount,DeclinedValue","Declined");
  C.gridItems.MergeColumnHeaders("UnwantedCount,UnwantedValue","Unwanted");

  // Add Breakdown Grid columns
  C.gridBreakdown.AddColumnCode("AccountAppId",{caption: "Application", sortable: true, summary: "count"});
  C.gridBreakdown.AddColumnString("Name",{caption: "Name", sortable: true});
  C.gridBreakdown.AddColumnCode("Manager",{caption: "Manager", sortable: true, selectable: true, summary: "count"});
  C.gridBreakdown.AddColumnString("Status",{caption: "Status", sortable: true, selectable: true});
  C.gridBreakdown.AddColumnString("SubStatus",{caption: "Sub Status", sortable: true, selectable: true});
  C.gridBreakdown.AddColumnCode("Type",{caption: "Type", sortable: true, selectable: true});
  C.gridBreakdown.AddColumnCurrency("Value",{caption: "Value", sortable: true, summary: "$sum"});
  C.gridBreakdown.AddColumnDate("DateCreated",{caption: "Created", sortable: true});
  mBreakdownChartFieldId = "Manager";
  C.gridBreakdown.SelectedColumnKey(mBreakdownChartFieldId);

  // Show only specified Breakdown columns
  C.gridBreakdown.SortColumnsByArray(mColumnsBreakdown, true);

  // Define Action buttons
  var buttons = [];
  for(var i = 0; i &lt; mPeriods.length; i++) {
    var period = mPeriods[i];
    buttons.push({ id: period, caption: period });
  }
  buttons.push({ id: "Custom", caption: "Custom" });
  C.blActions.ButtonsDefine(buttons);
  $("#cmdRunCustom").click(RunMain);

  // Define Chart Action buttons
  var chartButtons = [];
  chartButtons.push({ id: "Selected", caption: "Selected" });
  chartButtons.push({ id: "OverallCount", caption: "Count" });
  chartButtons.push({ id: "OverallValue", caption: "Value" });
  chartButtons.push({ id: "OverallCountPercent", caption: "Count (%)" });
  chartButtons.push({ id: "OverallValuePercent", caption: "Value (%)" });
  if (mBreakdownChartFieldId) {
    chartButtons.push({ id: "BreakdownSelected", caption: "Breakdown", visible: false });
  }
  else {
    // No chartable columns for breakdown grid
  }
  C.blChartActions.ButtonsDefine(chartButtons);
  C.blChartActions.SelectedItemId("Selected");

  // Refresh
  PeriodUpdate(mPeriod, true);

  // Set a callback to run when the Google Visualization API is loaded
  google.charts.setOnLoadCallback(RunMain);

  // Resize charts when window resized
  $(window).resize(function() { UpdateChartsPanel(true); });

  // Finalise
  $(".is-widget-content").show();
});

// ===============
// Run Main Report
// ===============
function RunMain() {
  var params = {};

  // Can we run?
  var basisIndex = C.cboBasis.ListIndex();
  if (basisIndex == -1) return;

  // Initialise
  mResultsBreakdown = null;
  C.divBreakdown.hide();
  C.lblBreakdownTitle.Visible(false);
  C.gridItems.Sort("");

  // Update title
  mBasis = mBasisList[basisIndex].Code;
  mBasisDescription = C.cboBasis.Text();

  // Create parameters
  params.basis = mBasis;
  params.period = mPeriod;
  if(mPeriod == "Custom") {
    if(C.dateFromDate.Value() || C.dateToDate.Value()){
      params.fromDate = C.dateFromDate.Value();
      params.toDate = C.dateToDate.Value();
    }
    else {
      widget.UI.MsgBoxAlert("Please enter a valid date in the from and to fields.");
      C.dateFromDate.Focus();
      return;
    }
  }

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

  // Get Report Results
  widget.GetString("GetReportData", params, RunMain_Done, Run_Fail);
}

function RunMain_Done(data) {
  // Parse Main Results
  var dataParsed = JSON.parse(data);
  mResultsMain = dataParsed.Items;
  mResultsMainFiltered = mResultsMain;
  var fromDate = dataParsed.FromDateText;
  var toDate = dataParsed.ToDateText;

  // Bind grid
  C.gridItems.VirtualDataRefresh(mResultsMain);

  // Update title
  var title = mCustomReportTitle + " by &lt;span class='parameter'&gt;" + widget.UI.HtmlEncode(mBasisDescription) + "&lt;/span&gt; &lt;small&gt;for period&lt;/small&gt; ";
  mChartTitleMain = mCustomReportTitle + " by " + mBasisDescription;
  mChartTitleSub = "for period ";
  switch(mPeriod) {
    case "Custom":
      if (fromDate &amp;&amp; toDate) {
        title += "&lt;span class='parameter'&gt;" + fromDate + "&lt;/span&gt; &lt;small&gt;to&lt;/small&gt; &lt;span class='parameter'&gt;" + toDate + "&lt;/span&gt;";
        mChartTitleSub += fromDate + " to " + toDate;
      }
      else {
        if (fromDate) {
          title += "&lt;small&gt;from&lt;/small&gt; &lt;span class='parameter'&gt; " + fromDate + "&lt;/span&gt;";
          mChartTitleSub += " from " + fromDate;
        }
        if (toDate) {
          title += "&lt;small&gt;to&lt;/small&gt; &lt;span class='parameter'&gt; " + toDate + "&lt;/span&gt;";
          mChartTitleSub += " to " + toDate;
        }
      }
      C.lblMainTitle.TooltipText("");
      break;

    case "Forever":
      title += "&lt;span class='parameter'&gt;" + mPeriod + "&lt;/span&gt;";
      mChartTitleSub += mPeriod;
      C.lblMainTitle.TooltipText("");
      break;

    default:
      title += "&lt;span class='parameter'&gt;" + mPeriod + "&lt;/span&gt;";
      mChartTitleSub += mPeriod + " (" + fromDate + " to " + toDate + ")";
      C.lblMainTitle.TooltipText("For the period " + fromDate + " to " + toDate);
      break;
  }
  if (mHasUserFilters) title += "&lt;div class='is-info-text warning small'&gt;User Filters have been applied to the results&lt;/div&gt;";
  C.lblMainTitle.Html(title);

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

  // Create Charts
  mBreakdownIndex = -1;
  UpdateChartsPanel();
}

function Run_Fail(errorMessage) {
  window.alert(errorMessage);

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

// ====================
// Run Breakdown Report
// ====================
function RunBreakdown(index) {
  var params = {};

  // Disabled?
  if (!mAllowBreakdown) return;

  // Already showing?
  if (index == mBreakdownIndex) return;

  // Initialise
  mBreakdownIndex = index;
  if (mBreakdownIndex == -1) {
    C.divBreakdown.hide();
    C.lblBreakdownTitle.Visible(false);
  }
  else {
    C.divBreakdown.show();
    C.lblBreakdownTitle.Visible(true);
  }

  // Recreate chart to explode pie segment
  CreatePieChart(mResultsMain, mResultsMainFiltered, "chrtMain", "Main", mMainChartFieldId, mBreakdownIndex);

  // Showing breakdown?
  if (mBreakdownIndex == -1) return;

  // Highlight selected row
  C.gridItems.ActiveDataRowListIndex(index);

  // Create parameters
  params.basis = mBasis;
  params.breakdownPk = mResultsMain[index].Pk;
  params.period = mPeriod;
  if(mPeriod == "Custom") {
    if(C.dateFromDate.Value() || C.dateToDate.Value()){
      params.fromDate = C.dateFromDate.Value();
      params.toDate = C.dateToDate.Value();
    }
    else {
      widget.UI.MsgBoxAlert("Please enter a valid date in the from and to fields.");
      C.dateFromDate.Value().Focus();
      return;
    }
  }

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

  // Get Report Results
  widget.GetString("GetBreakdownData", params, RunBreakdown_Done, Run_Fail);
}

function RunBreakdown_Done(data) {
  // Parse Breakdown Results
  mResultsBreakdown = JSON.parse(data);

  // Bind grid
  C.gridBreakdown.VirtualDataRefresh(mResultsBreakdown);

  // Can we run?
  var basisIndex = C.cboBasis.ListIndex();
  if (basisIndex == -1) return;
  mBasis = mBasisList[C.cboBasis.ListIndex()].Code;

  // Update title
  if (mResultsMain[mBreakdownIndex].Code) {
    // Main title
    var title = mResultsMain[mBreakdownIndex].Code;
    if (mResultsMain[mBreakdownIndex].Code != mResultsMain[mBreakdownIndex].Description) {
      title += ", " + mResultsMain[mBreakdownIndex].Description;
    }

    // Finalise
    C.lblBreakdownTitle.Text(title);
  }
  else {
    C.lblBreakdownTitle.Text("(No " + mBasisDescription + ")");
  }

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

  // Show and scroll into view
  C.divBreakdown.show();
  C.lblBreakdownTitle.Visible(true);
  widget.UI.ScrollToTop("divBreakdown");

  // Update Breakdown Chart
  blChartActions_Change();
}

// =========
// gridItems
// =========
function gridItems_InitialiseRow(e) {
  var item = mResultsMain[e.row.listIndex];

  // Auto-populate cell values from object
  e.row.AutoBind(item);

  // Legend for code cell
  item._listIndex = e.row.listIndex;
  item._legendColour = mChartColoursMain[e.row.listIndex % mChartColoursMain.length];
  e.row.cells.Code.value = "&lt;nobr&gt;&lt;span class='legend' style='background-color:" + item._legendColour + "'&gt;&lt;/span&gt;" + widget.UI.HtmlEncode(item.Code) + "&lt;/nobr&gt;";
  e.row.cells.Code.sortValue = item.Code;

//  // Columns
//  if (e.row.cells.Description != undefined) e.row.cells.Description.value = item.Description;
//  if (e.row.cells.OpenCount != undefined) e.row.cells.OpenCount.value = item.OpenCount;
//  if (e.row.cells.OpenValue != undefined) e.row.cells.OpenValue.value = item.OpenValue;
//  if (e.row.cells.CompleteCount != undefined) e.row.cells.CompleteCount.value = item.CompleteCount;
//  if (e.row.cells.CompleteValue != undefined) e.row.cells.CompleteValue.value = item.CompleteValue;
//  if (e.row.cells.IncompleteCount != undefined) e.row.cells.IncompleteCount.value = item.IncompleteCount;
//  if (e.row.cells.IncompleteValue != undefined) e.row.cells.IncompleteValue.value = item.IncompleteValue;
//  if (e.row.cells.ReviewingCount != undefined) e.row.cells.ReviewingCount.value = item.ReviewingCount;
//  if (e.row.cells.ReviewingValue != undefined) e.row.cells.ReviewingValue.value = item.ReviewingValue;
//  if (e.row.cells.AcceptedCount != undefined) e.row.cells.AcceptedCount.value = item.AcceptedCount;
//  if (e.row.cells.AcceptedValue != undefined) e.row.cells.AcceptedValue.value = item.AcceptedValue;
//  if (e.row.cells.DeclinedCount != undefined) e.row.cells.DeclinedCount.value = item.DeclinedCount;
//  if (e.row.cells.DeclinedValue != undefined) e.row.cells.DeclinedValue.value = item.DeclinedValue;
//  if (e.row.cells.UnwantedCount != undefined) e.row.cells.UnwantedCount.value = item.UnwantedCount;
//  if (e.row.cells.UnwantedValue != undefined) e.row.cells.UnwantedValue.value = item.UnwantedValue;

  // Cell styles
  if (e.row.cells.Description != undefined) e.row.cells.Description.small = true;
}

function gridItems_AfterRowActivate() {
  if (mAutoShowBreakdown) {
    // Run breakdown and explode segment
    RunBreakdown(C.gridItems.ActiveDataRowListIndex());
  }
  else {
    // Explode segment but do not run breakdown
    CreatePieChart(mResultsMain, mResultsMainFiltered, "chrtMain", "Main", mMainChartFieldId, C.gridItems.ActiveDataRowListIndex());
  }
}

function gridItems_ColumnSelect() {
  mMainChartFieldId = C.gridItems.SelectedColumnKey();

  // Show chart for column
  C.blChartActions.SelectedItemId("Selected");
  blChartActions_Change();
}

function gridItems_AfterColumnSort() {
  // Get filtered data and redraw charts to account for new sort order
  UpdateChartsPanel();
}

function gridItems_RowDrilldown(e) {
  RunBreakdown(e.row.listIndex);
}

function gridItems_SelectedRowsChanged(e) {
  // Update charts
  UpdateChartsPanel(true);
}

// =============
// gridBreakdown
// =============
function gridBreakdown_InitialiseRow(e) {
  var item = mResultsBreakdown[e.row.listIndex];

  // Auto-populate cell values from object
  e.row.AutoBind(item);

  // Hyperlink code
  e.row.cells.AccountAppId.hyperlink = "app://FormShow?form=AccountApp&amp;id=" + encodeURI(item.AccountAppId);
}

function gridBreakdown_ColumnSelect() {
  mBreakdownChartFieldId = C.gridBreakdown.SelectedColumnKey();

  // Show chart for column
  C.blChartActions.SelectedItemId("BreakdownSelected");
  blChartActions_Change();
}

// =========
// blActions
// =========
function blActions_Change(sender, e) {
  PeriodUpdate(C.blActions.SelectedItemId());
}

// ==============
// blChartActions
// ==============
function blChartActions_Change(sender, e) {
  // Hide all charts
  C.divChartMain.hide();
  C.divChartOverallCount.hide();
  C.divChartOverallValue.hide();
  C.divChartOverallCountPercent.hide();
  C.divChartOverallValuePercent.hide();
  C.divChartBreakdown.hide();

  // Update Chart action captions
  var c = C.gridItems.SelectedColumn();
  if (c) {
    C.blChartActions.ButtonCaption("Selected", "&lt;HTML&gt;&lt;span style='border-bottom:2px solid " + c.colourChart + "'&gt;" + widget.UI.HtmlEncode(c.captionChart) + "&lt;/span&gt;");
  }
  var c = C.gridBreakdown.SelectedColumn();
  if (c &amp;&amp; mResultsBreakdown) {
    C.blChartActions.ButtonCaption("BreakdownSelected", "Breakdown (" + c.caption + ")");
    C.blChartActions.ButtonVisible("BreakdownSelected", true);
  }
  else {
    C.blChartActions.ButtonVisible("BreakdownSelected", false);
    if (C.blChartActions.SelectedItemId() == "BreakdownSelected") {
      C.blChartActions.SelectedItemId("Selected", false);
    }
  }

  // Create and show selected chart (create each time to force a redraw)
  // NOTE: Add slight delay to avoid resize issues
  window.setTimeout(function () {
    switch(C.blChartActions.SelectedItemId()) {
      case "Selected":
        // Main (Selected) Pie Chart
        C.divChartMain.show();
        CreatePieChart(mResultsMain, mResultsMainFiltered, "chrtMain", "Main", mMainChartFieldId, mBreakdownIndex);
        break;

      case "OverallCount":
        // Overall Count Bar Chart
        C.divChartOverallCount.show();
        CreateBarChart(mResultsMain, mResultsMainFiltered, "chrtOverallCount", "Count");
        break;

      case "OverallValue":
        // Overall Value Bar Chart
        C.divChartOverallValue.show();
        CreateBarChart(mResultsMain, mResultsMainFiltered, "chrtOverallValue", "Value");
        break;

      case "OverallCountPercent":
        // Overall Count (%) Bar Chart
        C.divChartOverallCountPercent.show();
        CreateBarChart(mResultsMain, mResultsMainFiltered, "chrtOverallCountPercent", "Count", true);
        break;

      case "OverallValuePercent":
        // Overall Value (%) Bar Chart
        C.divChartOverallValuePercent.show();
        CreateBarChart(mResultsMain, mResultsMainFiltered, "chrtOverallValuePercent", "Value", true);
        break;

      case "BreakdownSelected":
        // Breakdown (Selected) Pie Chart
        var chartData = [];

        for (var i = 0; i &lt; mResultsBreakdown.length; i++) {
          var item = mResultsBreakdown[i];
          var code = item[mBreakdownChartFieldId] || "";

          // Add/ locate record
          var record = null;
          for (var j = 0; j &lt; chartData.length; j++) {
            if (chartData[j].Code == code) {
              record = chartData[j];
              record.Value += 1;
              break;
            }
          }
          if (!record) {
            record = { Code: code, Value: 1 };
            chartData.push(record);
          }
        }

        C.divChartBreakdown.show();
        CreatePieChart(chartData, chartData, "chrtBreakdown", "Breakdown", "Value", -999);
        break;
    }
  }
  , 100);
}

// ================
// Create Pie Chart
// ================
function CreatePieChart(records, recordsFiltered, chartDivId, chartKey, fieldId, explodeSegmentListIndex) {
  // Initialise
  var chartDiv = $("#" + chartDivId);
  var chart = C["chrt" + chartKey];

  // Can we create a chart?
  if (recordsFiltered &amp;&amp; recordsFiltered.length != 0) {
    chartDiv.show();
  }
  else {
    chartDiv.hide();
    return;
  }

  // Create the data table
  var data = new google.visualization.DataTable();
  data.addColumn("string", "Code");
  data.addColumn("number", "Value");
  for(var i = 0; i &lt; recordsFiltered.length; i++) {
    data.addRow([recordsFiltered[i].Code, recordsFiltered[i][fieldId]]);
  }

  // Create slices array so we can colour and explode slices
  var slices = [];
  for(var i = 0; i &lt; recordsFiltered.length; i++) {
    var item = recordsFiltered[i];

    var slice = { color: item._legendColour, _listIndex: item._listIndex };
    slices.push(slice);

    // Explode slice?
    if (item._listIndex == explodeSegmentListIndex) slice.offset = 0.1;
  }

  // Chart options
  var options = {title: "",
                 legend: {position: "right"},
                 chartArea: {width: "95%", height: "95%", left: 24, top: 0},
                 is3D: false,
                 slices: slices};

  // Zoomed chart options
  if (mChartsZoomed) {
    // Title and Legend
    var tabCaption = C.blChartActions.GetButtonCaptionText(C.blChartActions.SelectedItemId());
    options.title = mChartTitleMain + ": " + tabCaption + "\n" + mChartTitleSub;
    if (records.length != recordsFiltered.length) options.title += " (filtered)";
    options.titleTextStyle = {fontName: "arial black", fontSize: 22, bold: false};

    // Size
    options.width = window.innerWidth - 24;
    options.height= window.innerHeight - 24;
    options.chartArea.top = 80;
  }
  else {
    // Size
    if (mLayout == "Dashboard" &amp;&amp; !widget.UI.IsSmallMobileBrowser()) {
      // Dashboard
      options.width = C.divCharts.innerHeight() + 100;
      options.height = C.divCharts.innerHeight() - 20;
    }
    else {
      // Page
      options.width = 400;
      options.height = 300;
    }
  }

  // Draw chart
  if (!chart) {
    chart = new google.visualization.PieChart(chartDiv[0]);
  }
  else {
    google.visualization.events.removeListener(chart._listener);
  }
  C["chrt" + chartKey] = chart;
  chart.draw(data, options);

  // Allow segment click to show breakdown
  if (explodeSegmentListIndex == -999) {
    // Not supported, e.g., charting breakdown data
  }
  else {
    chart._listener = google.visualization.events.addListener(C.chrtMain, "select", function () {
      var sliceIndex = chart.getSelection()[0].row;

      if (sliceIndex != null) {
        // Get real list index of segment record
        var listIndex = slices[sliceIndex]._listIndex;

        if (mAutoShowBreakdown) {
          // Run breakdown and explode segment
          RunBreakdown(listIndex);
        }
        else {
          // Select row (also explodes segment)
          C.gridItems.ActiveDataRowListIndex(listIndex);
        }
      }
    });
  }
}

// ==========================================================================
// Create Bar Chart (either Count or Value based), optionally as a percentage
// ==========================================================================
function CreateBarChart(records, recordsFiltered, chartDivId, chartBasis, percentage) {
  // Initialise
  var chartKey = chartBasis + (percentage ? "Percent" : "");
  var chart = C["chrtOverall" + chartKey];
  var chartDiv = C["divChartOverall" + chartKey];
  var dt = [];

  // Create data table header row
  // NOTE: Assumes text column names match the key (once spaces are removed) which also matches the property on each data row
  var headerRow = [mBasisDescription];
  var dataKeys = [];
  var series = {};
  var seriesCounter = 0;

  for(var i = 0; i &lt; mColumns.length; i++) {
    var key = mColumns[i].replace(/\s+/g, "");
    var c = C.gridItems.GetColumnByKey(key);

    if (c &amp;&amp; key.endsWith(chartBasis)) {
      dataKeys.push(key);
      headerRow.push(c.captionChart);
      series[seriesCounter] = { color: c.colourChart };
      seriesCounter += 1;
    }
  }
  dt.push(headerRow);

  // Add data rows
  for (var j = 0; j &lt; recordsFiltered.length; j++) {
    var item = recordsFiltered[j];
    var row = [item.Code];
    var rowTotal = 0;

    for (var i = 0; i &lt; dataKeys.length; i++) {
      var key = dataKeys[i];
      row.push(item[key]);
      rowTotal += item[key];
    }

    // Percentage (Google Material Charts do not currently natively support this)
    if (percentage) {
      var factor = 100.0 / rowTotal;
      var newTotal = 0;
      for(var i = 1; i &lt; row.length; i++) {
        row[i] *= factor;
        newTotal += row[i];
      }

      // Handle rounding issues
      if (newTotal != 100) {
        row[row.length - 1] += (newTotal - 100);
      }
    }

    dt.push(row);
  }

  // Finalise data table
  var data = new google.visualization.arrayToDataTable(dt);

  // Chart options
  var options = { title: "",
                  legend: {position: "top"},
                  bars: "horizontal",
                  height: 100 + (recordsFiltered.length * 20),
                  width: chartDiv.innerWidth() - 20,
                  isStacked: true,
                  series: series,
                  hAxis: { title: "", format: (chartBasis == "Value" ? "decimal" : "#"), textStyle: {fontSize: 10}},
                  vAxes: { 0: { title: chartBasis + (percentage ? " (%)": ""), viewWindow: { }, textStyle: {fontSize: 10.5}}},
                };

  // Zoomed chart options
  if (mChartsZoomed) {
    var tabCaption = C.blChartActions.ButtonCaption(C.blChartActions.SelectedItemId());
    options.title = mChartTitleMain + ": " + tabCaption;
    if (records.length != recordsFiltered.length) options.title += " (filtered)";
    options.subtitle = mChartTitleSub;
    options.titleTextStyle = { fontName: "arial black", fontSize: 22, bold: false };
    options.height += 100;
  }

  // Draw chart
  if (!chart) {
    chart = new google.charts.Bar(chartDiv[0]);
  }
  else {
    google.visualization.events.removeListener(chart._listener);
  }
  C["chrtOverall" + chartKey] = chart;
  chart.draw(data, google.charts.Bar.convertOptions(options));

  // Allow bar segment click to highlight record in main grid
  chart._listener = google.visualization.events.addListener(chart, "select", function () {
    var index = chart.getSelection()[0].row;

    if (index != null) {
      C.gridItems.ActiveDataRowListIndex(recordsFiltered[index]._listIndex);
    }
  });
}

// ================
// Helper Functions
// ================
function PeriodUpdate(period, holdRun) {
  // Initialise
  mPeriod = period;

  // Set selected action (but do not fire events)
  C.blActions.SelectedItemId(period, true);

  // Update Chart actions (but do not fire events)
  if (C.blChartActions.SelectedItemIndex() == -1) {
    C.blChartActions.SelectedItemId("Overall", true);
  }

  // Run
  if(period == "Custom") {
    $("#divCustomPeriod").show();
    mResultsMain = [];
  }
  else {
    $("#divCustomPeriod").hide();
    if (!holdRun) RunMain();
  }
}

function UpdateChartsPanel(delay) {
  // Initialise
  if (mUpdateChartsPanelTimer) {
    window.clearTimeout(mUpdateChartsPanelTimer);
    mUpdateChartsPanelTimer = null;
  }

  // Update
  if (delay) {
    mUpdateChartsPanelTimer = window.setTimeout(UpdateChartsPanel_Done, 750);
  }
  else {
    UpdateChartsPanel_Done();
  }

  // Controls
  C.blChartActions.Visible(!mChartsZoomed);
  if (mChartsZoomed) {
    C.divChart.css({position: "absolute", top: 0, left: 0, right:0, bottom: 0});
    C.divChart.css({"margin-top": "-" + C.blChartActions.Element().outerHeight() + "px"});
  }
  else {
    C.divChart.css({position: "static"});
    C.divChart.css({"margin-top": 0});
  }
}

function UpdateChartsPanel_Done() {
  // Initialise
  mUpdateChartsPanelTimer = null;

  // Get filtered results
  mResultsMainFiltered = C.gridItems.GetVirtualDataForSelectedRows(true);

  // Redraw charts
  blChartActions_Change();
}

// ========
// cboBasis
// ========
function cboBasis_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Re-run report
  RunMain();
}
&lt;/script&gt;

&lt;/body&gt;</TemplateText><TemplateTextBookmarks /><TimeoutSeconds>60</TimeoutSeconds><UniqueId>NLtDCTb8vUyiltP7OF0olg</UniqueId><AllowRefresh>true</AllowRefresh><Caption>Account Applications Breakdown</Caption><HtmlWidgetMaxHeight>1200</HtmlWidgetMaxHeight><HtmlWidgetMaxWidth>1200</HtmlWidgetMaxWidth><HtmlWidgetNeverApplyStyling>false</HtmlWidgetNeverApplyStyling><HtmlWidgetResourceCssSummaryPage2>true</HtmlWidgetResourceCssSummaryPage2><HtmlWidgetResourceCssWidget>true</HtmlWidgetResourceCssWidget><HtmlWidgetResourceJQuery>true</HtmlWidgetResourceJQuery><HtmlWidgetResourceJQueryVersion /><Icon /><JavaScriptDebugger>None</JavaScriptDebugger><RestrictedOriginsListEnabled>false</RestrictedOriginsListEnabled><RunAsAdministrator>false</RunAsAdministrator><WebServiceName /><WebServiceAllowAnonymous>false</WebServiceAllowAnonymous><WebServiceSendDebugInformation>true</WebServiceSendDebugInformation><ShowInMenu>None</ShowInMenu><ParametersType>Custom</ParametersType><Parameters><ISParameterDefs version="1.00"><Parameters><Parameter name="" type="SectionStart"><BlankTip /><Caption>Select the default reporting Basis and Period and Statuses to include.</Caption><StandaloneOnly>false</StandaloneOnly><TooltipText>If a Default Period of '(Auto)' is selected, an attempt will be made to choose from Periods list based on the date of the latest Account Application.</TooltipText><SectionColumns>1</SectionColumns><Visible>true</Visible></Parameter><Parameter name="Basis" 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>Status</Value><Visible>true</Visible><List>Status,Type,Branch,Broker,Dealer,Manager</List><LimitToList>true</LimitToList><MaxLength>20</MaxLength><Rows>1</Rows></Parameter><Parameter name="DefaultPeriod" type="List"><BlankTip /><Caption>Default Period</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>(Auto)</Value><Visible>true</Visible><List>(Auto),Today,Since Yesterday,7 Days,4 Weeks,3 Months,6 Months,1 Year,Forever</List><LimitToList>true</LimitToList><MaxLength>0</MaxLength><Rows>1</Rows></Parameter><Parameter name="AccountAppStatuses" type="CheckList"><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>Incomplete,Reviewing,Complete,Accepted,Declined,Unwanted</Value><Visible>true</Visible><List>Incomplete,Reviewing,Complete,Accepted,Declined,Unwanted</List><LimitToList>true</LimitToList><MaxLength>0</MaxLength><Rows>8</Rows></Parameter><Parameter name="" type="SectionStart"><BlankTip /><Caption>Other options.</Caption><StandaloneOnly>false</StandaloneOnly><TooltipText>On small mobile devices, "Page" layout will always be used.</TooltipText><SectionColumns>1</SectionColumns><Visible>true</Visible></Parameter><Parameter name="Layout" type="List"><BlankTip /><Caption>Report Layout</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>Dashboard</Value><Visible>true</Visible><List>Dashboard,Page</List><LimitToList>true</LimitToList><MaxLength>10</MaxLength><Rows>1</Rows></Parameter><Parameter name="AllowBreakdown" type="Boolean"><BlankTip /><Caption>Allow User to show a Breakdown?</Caption><StandaloneOnly>false</StandaloneOnly><TooltipText /><DefaultValueExpression /><Enabled>true</Enabled><HideDescription>false</HideDescription><IndentLevel>0</IndentLevel><NonPersistable>false</NonPersistable><ReadOnly>false</ReadOnly><ReadOnly2>false</ReadOnly2><Value>True</Value><Visible>true</Visible></Parameter><Parameter name="AutoShowBreakdown" type="Boolean"><BlankTip /><Caption>Automatically show Breakdown when selecting a row?</Caption><StandaloneOnly>false</StandaloneOnly><TooltipText /><DefaultValueExpression /><Enabled>true</Enabled><HideDescription>false</HideDescription><IndentLevel>1</IndentLevel><NonPersistable>false</NonPersistable><ReadOnly>false</ReadOnly><ReadOnly2>false</ReadOnly2><Value>False</Value><Visible>true</Visible></Parameter><Parameter name="" type="SectionStart"><BlankTip /><Caption>Optionally, customise Columns to show.</Caption><StandaloneOnly>false</StandaloneOnly><TooltipText /><SectionColumns>1</SectionColumns><Visible>true</Visible></Parameter><Parameter name="Columns" 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>Description,Open Count,Open Value,Complete Count,Complete Value,Incomplete Count,Incomplete Value,Reviewing Count,Reviewing Value,Accepted Count,Accepted Value,Declined Count,Declined Value,Unwanted Count,Unwanted Value</List><GroupingListShowPageBreakButton>false</GroupingListShowPageBreakButton><NoIndent>true</NoIndent></Parameter><Parameter name="" type="SectionStart"><BlankTip /><Caption>Optionally, customise Columns to show in the Breakdown</Caption><StandaloneOnly>false</StandaloneOnly><TooltipText /><SectionColumns>1</SectionColumns><Visible>true</Visible></Parameter><Parameter name="ColumnsBreakdown" 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>Application,Name,Manager,Status,Sub Status,Type,Value,Created</List><GroupingListShowPageBreakButton>false</GroupingListShowPageBreakButton><NoIndent>true</NoIndent></Parameter><Parameter name="" type="SectionStart"><BlankTip /><Caption>Specify advanced customisation details.</Caption><StandaloneOnly>false</StandaloneOnly><TooltipText>An SQL Where Clause can be specified to filter both main and breakdown results.
Always prefix with the table name, e.g.:
[AccountApp].[Name] Like 'A%'</TooltipText><SectionColumns>1</SectionColumns><Visible>true</Visible></Parameter><Parameter name="SqlWhere" type="Text"><BlankTip /><Caption>SQL Where Clause</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><MaxLength>0</MaxLength><Rows>3</Rows></Parameter><Parameter name="CustomReportTitle" type="Text"><BlankTip /><Caption>Custom Report Title</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><MaxLength>0</MaxLength><Rows>1</Rows></Parameter></Parameters></ISParameterDefs></Parameters></finScript>