<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2024-09-19T23:34:19.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2024-09-18T23:20:48.6960000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2024-09-19T23:13:58.4630000</UpdatedUtcDate>
    <ScriptId>HWWTMF</ScriptId>
    <Description>Workflows Task Manager folder</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_TaskManagerFolder_Workflows
Option Explicit On
Option Strict On

' #################################################################
' Workflows Task Manager Folder
'
' (c) Copyright Intersoft Systems Limited 2022
'
' Version: 1.08 (20/09/2024)
'
' Usage: System-defined HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ---------- -------  --------  -------------------------
'    1.00  19/10/2022  ISS                Created
'    1.01  09/02/2023  ISS      J030430   Group By column support added
'          02/03/2023  ISS      J030566   Add Workflow action added
'          03/03/2023  ISS      J030565   Allocate User actions added
'          03/03/2023  ISS      J030563   Update Recall Date actions added
'          06/03/2023  ISS      J030564   Various communication actions added
'    1.03  21/03/2023  ISS      J030547   Updated to use widget.AccountTerminology and finBL.IsClientManagement
'          21/03/2023  ISS      J030639   Custom Summary Page support
'          22/03/2023  ISS      J030714   Incorrectly selecting rows for sorted grids after action
'    1.04  29/06/2023  ISS      J031371   Support for new FolderCountMessage and FolderCountDisableRefresh Script properties
'          06/07/2023  ISS      J031501   Option to allow Template Text caching
'          12/07/2023  ISS      J031552   Button to toggle preview pane added
'          31/07/2023  ISS      J029795   Added ability to customise grid columns
'          14/08/2023  ISS      J030020   Workflow grid now refreshes more reliably after action
'          13/09/2023  ISS      J032033   WorkflowId is now passed to all "FormAction" Application Shortcuts to avoid issues in desktop
'    1.05  27/09/2023  ISS      J031640   Toggle button to hide summary (PreviewPaneToggle) updated
'          17/10/2023  ISS      J032240   More chart types supported
'    1.06  10/05/2024  ISS      J033342   Allow all items to be loaded where permitted
'    1.07  15/07/2024  ISS      J033819   Cancelling "Allocate User" input clears Allocated User in desktop
'    1.08  12/09/2024  ISS      J034015   Allow a time to be entered when setting the Recall Date
'          19/09/2024  ISS      J034278   Added Date Opened and Date Created Columns
'          20/09/2024  ISS      J034292   Added action to set and clear Recall Immediately flag
' #################################################################

' Constants
Private Const FORM_KEY As String = "TaskManager"

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

' Standard Parameters
Private mDateAsAt As Date
Private mDateAsAtMnemonic As String
Private mFolderId As String
Private mLoadAll As Boolean
Private mUserId As String

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

  ' Assume Success
  Main = True

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

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

  ' Other Parameters
  With mCombinedParameters
    mDateAsAt = .GetDate("DateAsAt")
    mDateAsAtMnemonic = .GetString("DateAsAtMnemonic")
    mFolderId = .GetString("FolderId")
    mLoadAll = .GetBoolean("LoadAll")
    mUserId = .GetString("UserId")
  End With

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

    Case "GetInitialisationInfo"
      ' Get Initialisation Information required for this form
      Main = GetInitialisationInfo(returnValue)

    Case "GetItemPreview"
      ' Get Item Preview
      Main = GetItemPreview(returnValue)

    Case "PerformAction"
      ' Perform Action
      Main = PerformAction(returnValue)

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

End Function

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

  Dim FolderCountMessage As String
  Dim FolderCountDisableRefresh As Boolean
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim MaxSizeExceeded As Boolean
  Dim Success As Boolean
  Dim TaskManager As finTaskManager2
  Dim TaskManagerFolder As finTaskManagerFolder 
  Dim Workflows As List(Of finTaskManager2Workflow)
  Dim UserDataHeadings As List(Of finTaskManager2UserDataHeading)

  ' Assume Success
  Success = True

  ' Initialise
  FormInitialisationInfo = New FormInitialisationInfo()

  ' Create Task Manager
  If Len(mDateAsAtMnemonic) = 0 Then
    TaskManager = finBL.CreateTaskManager2FromDateAsAt(mUserId, mDateAsAt)
  Else
    TaskManager = finBL.CreateTaskManager2FromDateAsAtMnemonic(mUserId, mDateAsAtMnemonic)
  End If

    ' Load All Content?
  If mLoadAll AndAlso finBL.SettingsUser.TaskManagerAllowMaxFolderSizeOverride Then
    TaskManager.IgnoreMaxFolderSize = True
  End If

  ' Get Folder Content
  Success = TaskManager.GetWorkflows(mFolderId, Workflows, TaskManagerFolder, MaxSizeExceeded, UserDataHeadings, FolderCountMessage, FolderCountDisableRefresh)

  ' Get Form Initialisation Info
  If Success Then
    With FormInitialisationInfo
      ' Record
      .ReadOnly = finBL.Database.IsReadOnly      
      .DateAsAtText = TaskManager.DateAsAtText
      .FolderId = mFolderId
      .PersistId = TaskManager.UserId &amp; "|" &amp; mFolderId
      .ShowFolderCount = TaskManagerFolder.ShowFolderCount
      .ShowPreviewPane = TaskManagerFolder.ShowPreviewPane
      .TimeZoneDescription = finBL.Runtime.TimeZones(finBL.TimeZoneId).WindowsTimeZoneDisplayName
      .UserId = TaskManager.UserId
  
      ' Items
      .Items = Workflows
  
      ' User Data
      .UserDataHeadings = UserDataHeadings

      ' Columns
      .GroupByColumn = TaskManagerFolder.GroupByColumn
      .GroupByColumnHide = TaskManagerFolder.GroupByColumnHide
      If Len(TaskManagerFolder.Columns) &lt;&gt; 0 Then
        .Columns = Split(TaskManagerFolder.Columns, "|")
      End If

      ' Folder Count
      ' NOTE: Set regardless of the Folder's ShowFolderCount property which is designed to be used by the Task Manager Treeview
      .FolderCount = CStr(Workflows.Count)
      .FolderCountMessage = FolderCountMessage
      .FolderCountDisableRefresh = FolderCountDisableRefresh
      If MaxSizeExceeded Then
        .FolderCount &amp;= "+"
        .WarningMessage = "Maximum folder size exceeded. Grid will only show the first " &amp; TaskManager.MAX_FOLDER_SIZE_RESOLVED &amp; " items."
      End If
  
      ' Permissions
      If Not .ReadOnly Then
        .AllowWorkflowUserAllocate = finBL.CurrentUserInformation.IsWorkflowManager 
        .AllowWorkflowHoldUnhold = finBL.CurrentUser.Permissions.Allow("Workflow.Hold")
        .AllowWorkflowClose = finBL.CurrentUser.Permissions.Allow("Workflow.Close")
        .AllowWorkflowRecallDate = finBL.CurrentUser.Permissions.Allow("Workflow.RecallDate")
        .AllowWorkflowAddAccount = finBL.CurrentUser.Permissions.Allow("Account.Workflows.Add")
        .AllowWorkflowAddAccountApp = finBL.CurrentUser.Permissions.Allow("AccountApp.Workflows.Add")
        .AllowWorkflowAddClient = finBL.CurrentUser.Permissions.Allow("Client.Workflows.Add")
        
        .AllowLogAccount = finBL.CurrentUser.Permissions.Allow("Account.Logs.Add")
        .AllowLogAccountApp = finBL.CurrentUser.Permissions.Allow("AccountApp.Logs.Add")
        .AllowLogClient = finBL.CurrentUser.Permissions.Allow("Client.Logs.Add")

        .AllowDocumentAccount = finBL.CurrentUser.Permissions.Allow("Account.Logs.AddDocument")
        .AllowDocumentAccountApp = finBL.CurrentUser.Permissions.Allow("AccountApp.Logs.AddDocument")
        .AllowDocumentClient = finBL.CurrentUser.Permissions.Allow("Client.Logs.AddDocument")
        
        If finBL.CurrentUser.Permissions.Allow("Account.PaymentArrangementAdd") Then
          .AllowPaymentArrangement = True
        ElseIf finBL.CurrentUser.Permissions.Allow("Account.PaymentPromiseAdd") Then
          .AllowPaymentPromise = True
        End If
        .AllowMonitorCategoryAUpdate = finBL.Settings.MonitorCategoryAUse AndAlso finBL.CurrentUser.Permissions.Allow("Account.MonitorCategoryAUpdate")
        .AllowMonitorCategoryBUpdate = finBL.Settings.MonitorCategoryBUse AndAlso finBL.CurrentUser.Permissions.Allow("Account.MonitorCategoryBUpdate")
        .AllowMonitorCategoryCUpdate = finBL.Settings.MonitorCategoryCUse AndAlso finBL.CurrentUser.Permissions.Allow("Account.MonitorCategoryCUpdate")
      End If
      .AllowLoadAll = Not mLoadAll AndAlso MaxSizeExceeded AndAlso finBL.SettingsUser.TaskManagerAllowMaxFolderSizeOverride       
  
      ' Configuration
      .AllowPageVisualisation = True
      .IsClientManagement = finBL.IsClientManagement ' Internal use only
      .IsMessagingAvailable = finBL.Messaging.IsMessagingAvailable AndAlso finBL.Settings.SmsUseNewInterface
      If finBL.Settings.MonitorCategoryAUse Then .MonitorCategoryADescription = finBL.Settings.MonitorCategoryADescriptionResolved
      If finBL.Settings.MonitorCategoryBUse Then .MonitorCategoryBDescription = finBL.Settings.MonitorCategoryBDescriptionResolved
      If finBL.Settings.MonitorCategoryCUse Then .MonitorCategoryCDescription = finBL.Settings.MonitorCategoryCDescriptionResolved
    End With
  End If
  
  ' Serialise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(FormInitialisationInfo, returnValue)
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Get an HTML Summary of a row in the grid.
''' &lt;/summary&gt;
Private Function GetItemPreview(ByRef returnValue As String) As Boolean

  Dim Success As Boolean
  Dim TaskManager As finTaskManager2
  Dim TaskManagerFolder As finTaskManagerFolder  
  Dim UniqueId As String

  ' Assume Success
  Success = True

  ' Get Parameters
  With mCombinedParameters
    UniqueId = .GetString("UniqueId")
  End With

  ' Create Task Manager
  If Len(mDateAsAtMnemonic) = 0 Then
    TaskManager = finBL.CreateTaskManager2FromDateAsAt(mUserId, mDateAsAt)
  Else
    TaskManager = finBL.CreateTaskManager2FromDateAsAtMnemonic(mUserId, mDateAsAtMnemonic)
  End If

  ' Get Folder (in case it is configured to use a custom Summary Script)
  Success = TaskManager.GetTaskManagerFolder(mFolderId, TaskManagerFolder)

  ' Get HTML Summary
  If Success Then
    If Len(TaskManagerFolder.PreviewPaneSummaryScriptId) = 0 Then
      ' Default
      returnValue = TaskManager.GetItemPreviewFromUniqueId(UniqueId)
    Else
      ' Custom
      returnValue = TaskManager.GetCustomWorkflowPreviewFromUniqueId(UniqueId, TaskManagerFolder)
    End If
  End If
  
  ' Error
  If Not Success Then
    returnValue = finBL.GetHtmlErrorMessage(finBL.Error.Message)
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Perform Action.
''' &lt;/summary&gt;
Private Function PerformAction(ByRef returnValue As String) As Boolean

  Dim ActionId As String
  Dim ActionParametersJson As String
  Dim obj As Object
  Dim Success As Boolean
  Dim TaskManager As finTaskManager2
  Dim UniqueIds As ISList
  Dim Warnings As finWarnings

  ' Assume Success
  Success = True

  ' Get Parameters
  With mCombinedParameters
    ActionId = .GetString("ActionId")
    ActionParametersJson = .GetString("ActionParametersJson")
    UniqueIds =  .GetListFromJsonArray("UniqueIds")
  End With

  ' Create Task Manager
  If Len(mDateAsAtMnemonic) = 0 Then
    TaskManager = finBL.CreateTaskManager2FromDateAsAt(mUserId, mDateAsAt)
  Else
    TaskManager = finBL.CreateTaskManager2FromDateAsAtMnemonic(mUserId, mDateAsAtMnemonic)
  End If

  ' Perform Action
  Select Case ActionId
    Case Else
      Success = TaskManager.ActionItemsFromUniqueIdsList(ActionId, ActionParametersJson, UniqueIds, Warnings)
  End Select

  ' Response
  If success Then
    obj = New With {
      .Warnings = Warnings.ToStringList()
    }
  End If

  ' Serialise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(obj, returnValue)
  End If

  Return Success

End Function



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

  ' Record
  Public DateAsAtText As String
  Public FolderId As String
  Public PersistId As String
  Public ShowFolderCount As Boolean
  Public ShowPreviewPane As Boolean
  Public TimeZoneDescription As String
  Public UserId As String

  ' Items
  Public Items As List(Of finTaskManager2Workflow)

  ' Folder Count
  Public FolderCount As String
  Public FolderCountMessage As String
  Public FolderCountDisableRefresh As Boolean  
  Public WarningMessage As String
  
  ' User Data (Scripted)
  Public UserDataHeadings As List(Of finTaskManager2UserDataHeading)
  
  ' Columns
  Public GroupByColumn As String
  Public GroupByColumnHide As Boolean
  Public Columns As String()

  ' Permissions
  Public AllowLoadAll As Boolean
  Public AllowWorkflowUserAllocate As Boolean
  Public AllowWorkflowHoldUnhold As Boolean
  Public AllowWorkflowClose As Boolean
  Public AllowWorkflowRecallDate As Boolean
  Public AllowWorkflowAddAccount As Boolean
  Public AllowWorkflowAddAccountApp As Boolean
  Public AllowWorkflowAddClient As Boolean
  
  Public AllowLogAccount As Boolean
  Public AllowLogAccountApp As Boolean
  Public AllowLogClient As Boolean
  
  Public AllowDocumentAccount As Boolean
  Public AllowDocumentAccountApp As Boolean
  Public AllowDocumentClient As Boolean

  Public AllowMonitorCategoryAUpdate As Boolean
  Public AllowMonitorCategoryBUpdate As Boolean
  Public AllowMonitorCategoryCUpdate As Boolean
  Public AllowPaymentArrangement As Boolean
  Public AllowPaymentPromise As Boolean

  ' Configuration
  Public AllowPageVisualisation As Boolean
  Public IsClientManagement As Boolean
  Public IsMessagingAvailable As Boolean
  Public MonitorCategoryADescription As String
  Public MonitorCategoryBDescription As String
  Public MonitorCategoryCDescription As String
  Public [ReadOnly] As Boolean

  Public Sub New()
  End Sub

End Class</Code>
    <Language>VisualBasic</Language>
    <Notes>System defined HTML Widget.

Used to display a "Workflow" type Task Manager folder.</Notes>
    <PermissionKeyExecute />
    <ReferenceLinq>false</ReferenceLinq>
    <RunWithoutPrompts>false</RunWithoutPrompts>
    <TemplateText>&lt;div id="frmMain" class="is-widget-content" style="visibility:hidden"&gt;

  &lt;!-- Form Header --&gt;
  &lt;header&gt;
    &lt;!-- Tabs --&gt;
    &lt;div id="tabDetails" class="is-tabs"&gt;
      &lt;ul&gt;
        &lt;li tabId="General"&gt;Workflows&lt;/li&gt;
        &lt;li tabId="Visualisation" icon="Chart"&gt;Visualisation&lt;/li&gt;
      &lt;ul&gt;
    &lt;/div&gt;
  &lt;/header&gt;


  &lt;!-- Pages --&gt;
  &lt;div class="is-widget-form-body"&gt;

    &lt;!-- General --&gt;
    &lt;div id="pageGeneral"&gt;
      &lt;div class="is-dock-fill is-split-container split5050"&gt;
        &lt;div class="panel"&gt;
          &lt;div id="gridItems"&gt;&lt;/div&gt;
        &lt;/div&gt;
        &lt;div id="pnlItems" class="panel"&gt;
          &lt;div id="wbItems" class="is-dock-fill"&gt;&lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;



    &lt;!-- Visualisation --&gt;
    &lt;div id="pageVisualisation"&gt;
      &lt;div class="is-dock-fill"&gt;
        &lt;div id="gvVisualiser" class="is-dock-fill"&gt;&lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;

  &lt;/div&gt;

&lt;/div&gt;

&lt;script&gt;
// Properties
var mRecord;
var mRecord_Items;
var mFolderInfo;

// Other
var mActiveRowUniqueId = "";    // Only used when the 'Refresh' button is clicked
var mLastWorkflowFormAction = "";
var mPreviewPaneVisible = true;
var mSelectedRowDetails = [];   // Used to retain selected rows after action is performed

// Controls
var C = {
  // General
  gridItems: null,
  pnlItems: null,
  wbItems: null,

  // Visualisation
  gvVisualiser: null,
}

// Form
var frmMain;
var tabDetails;

// Other
var mLoadAll = false;

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

  // Controls
  //   General
  C.pnlItems = $("#pnlItems");
  C.wbItems = widget.UI.PreviewPane("wbItems", {
    applicationShortcutHandler: wbItems_ApplicationShortcutHandler,
  });

  //   Visualisation
  // NOTE: GridVisualiser must be created after Grid

  // Grids
  C.gridItems = widget.UI.Grid("gridItems", {
    allowMultiRowSelect: true,
    docked: true,
    rowNumbering: true,
    showSearchBox: true,
    showRowSelectors: true,
    stickyHeader: true,
    rowNumbering: true,

    onAction: gridItems_Action,
    onAfterRowActivate: gridItems_AfterRowActivate,
    onInitialiseRow: gridItems_InitialiseRow,
    onSelectedRowsChanged: gridItems_SelectedRowsChanged
  });

  // Grid Visualiser
  C.gvVisualiser = widget.UI.Charts.ApexCharts.GridVisualiser("gvVisualiser", C.gridItems, {});

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

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

// Handle Notifications
  widget.ActionNotificationHandle(Widget_NotificationHandler);

  // Reset
  Form_Reset();
});

// ==========
// Form Reset
// ==========
function Form_Reset() {
  // Defaults
  C.gridItems.SearchClear();

  // Set Tab
  tabDetails.SelectedTabId("General");

  // Resize
  Form_Resize();

  // Load Record (i.e., initialise wizard)
  Record_Load();
}

// ===========
// Record Load
// ===========
function Record_Load() {
  // Initialise
  mRecord = null;
  mRecord_Items = null;

  // Clear cached summary pages
  C.wbItems.CacheClear();

  // Hide content
  frmMain.Visible(false);

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

  // Load Initialisation details
  widget.GetString("GetInitialisationInfo", { loadAll: mLoadAll },
    // Success
    function (data) {
      mRecord = JSON.parse(data);
      mRecord_Items = mRecord.Items;

      // Page Permissions
      if (!mRecord.AllowPageVisualisation) tabDetails.TabVisible("Visualisation", false);

      // Notify Task Manager to update Folder Count
      if (mRecord.ShowFolderCount &amp;&amp; !mRecord.FolderCountDisableRefresh) {
        widget.ParentNotify("UpdateTaskManagerFolderCount", { folderId: mRecord.FolderId, count: mRecord.FolderCount });
      }

      // Custom filter message
      if (mRecord.FolderCountMessage) {
        C.gridItems.CustomFilterMessage(mRecord.FolderCountMessage);
      }

      Fields_Load();
    },

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

// ===========
// Fields Load
// ===========
function Fields_Load() {
  if (mRecord) {
    // General
    gridItems_Refresh();
  }

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

  // Update Controls

  // Update fields
  Fields_Update();

  // Refresh Tab
  tabDetails_Refresh();
}

// =============
// Fields Update
// =============
function Fields_Update() {
  // Information Lists

  // Lists

  // Controls
  if(mRecord) {
    if (tabDetails.TabCountVisible() &lt; 2) tabDetails.Style("wizard");

    // Useful for support
    mFolderInfo = "To end of day " + mRecord.DateAsAtText + " - " + mRecord.TimeZoneDescription + " - for user '" + mRecord.UserId + "'";
    tabDetails.TabTooltipText("General", mFolderInfo);
    
    // Preview Pane
    if (mRecord.ShowPreviewPane) {
      C.pnlItems.show();
    }
    else {
      C.pnlItems.hide();
    }
  }

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

  // Resize
  tabDetails_Resize();
}

function tabDetails_Refresh() {
   // Load details
  switch (tabDetails.SelectedTabId()) {
    case "General":
      break;

    case "Visualisation":
      gvVisualiser_Refresh();
      break;

    default:
      break;
  }

  // Update Heading
  switch (tabDetails.SelectedTabId()) {
    default:
      frmMain.RefreshHeading(tabDetails.TabCaption(tabDetails.SelectedTabId()), tabDetails.TabTooltipText(tabDetails.SelectedTabId()));
      break;
  }

  // Resize
  tabDetails_Resize();

  // Focus
  switch (tabDetails.SelectedTabId()) {
    default:
      tabDetails.FocusFirst();
      break;
  }
}

function tabDetails_Resize() {
  switch (tabDetails.SelectedTabId()) {
    case "General":
      break;

    default:
      break;
  }
}

// =================
// Execute an Action
// =================
function Form_ExecuteAction(actionId) {
  switch (actionId.toUpperCase()) {
    default:
      window.alert(mViewName + ".Form_ExecuteAction: Unhandled action '" + actionId + "'");
      break;
  }
}

function Form_Resize() {
  // General

  // Tab
  tabDetails_Resize();
}

// ====================
// Notification Handler
// ====================
function Widget_NotificationHandler(actionId, data) {
  switch(actionId) {
    case "Refresh":
      // Refresh
      // NOTE: This can be called from the Task Manager to refresh this folder
      gridItems_Action("Refresh");
      break;

    case "WorkflowRefresh":
      // Refresh Workflow (e.g., if an action has been invoked and completed from the summary page)
      if (typeof data === "string") data = JSON.parse(data);

      // Get Workflow Id (account for upper/lowercase)
      var workflowId = data ? data.workflowId || data.WorkflowId : "";

      if (data &amp;&amp; workflowId &amp;&amp; mRecord_Items) {
        // See if Workflow Id exists
        for (var i = 0; i &lt; mRecord_Items.length; i++) {
          var item = mRecord_Items[i];
          if (item.WorkflowId == workflowId) {
            // Grid refresh required?
            // NOTE: We have no way of knowing what has been updated hence assume a refresh is required
            var refreshGrid = true;
            
            if (refreshGrid) {
              // Refresh entire grid
              gridItems_Action("Refresh");
            }
            else {
              // Remove summary page from cache
              C.wbItems.CacheRemove(item.UniqueId);

              // Update preview
              if (i == C.gridItems.ActiveDataRowListIndex()) wbItems_Preview();
            }
            break;
          }
        }
      }
      break;
  }

  // Clear refresh optimisation clue
  mLastWorkflowFormAction = "";
}

// =========
// gridItems
// =========
function gridItems_Action(actionId) {
  var item;
  var targetId;
  var targetType;
  var actionParametersJson = "";
  if (C.gridItems.ActiveDataRowListIndex() != -1) {
    item = mRecord_Items[C.gridItems.ActiveDataRowListIndex()];
    targetId = item.TargetId;
    targetType = item.TargetType;
  }
  
  // Get selected rows (including the active row if no selected rows)
  mSelectedRowDetails = C.gridItems.GetSelectedRowDetailsFromUniqueProperty("UniqueId", true);

  switch (actionId.toUpperCase()) {
    case "REFRESH":
      // Retain active row only
      if (C.gridItems.ActiveDataRowListIndex() != -1) {
        mActiveRowUniqueId = item.UniqueId;
      }
      mSelectedRowDetails = [];
      Form_Reset();
      break;
      
    case "LOADALL":
      // Load All
      widget.UI.MsgBoxConfirm("Load ALL items into the grid?\n\nWARNING: This may cause performance or memory issues.", { icon: "Grid|Download", heading: "Load ALL Items" },
        function () {
          mLoadAll = true;
          Form_Reset();
        });
      break;
      
  case "ACTIONCOMMUNICATIONINCOMING":
      // Incoming Communication (Log)
      switch (targetType) {
        case "Account":
          widget.ExecuteApplicationShortcutUrl("app://formshow?form=IncomingCommunication&amp;id=" + encodeURIComponent(targetId) + "&amp;workflowPk=" + item.WorkflowPk);
          break;

        case "AccountApp":
          widget.ExecuteApplicationShortcutUrl("app://formshow?form=IncomingCommunication&amp;id=" + encodeURIComponent(targetId) + "&amp;workflowPk=" + item.WorkflowPk);
          break;

        case "Client":
          widget.ExecuteApplicationShortcutUrl("app://formshow?form=IncomingCommunication&amp;id=" + encodeURIComponent(targetId) + "&amp;workflowPk=" + item.WorkflowPk);
          break;
      }
      break;

  case "ACTIONCOMMUNICATIONOUTGOING":
      // Outgoing Communication (Log)
      switch (targetType) {
        case "Account":
          widget.ExecuteApplicationShortcutUrl("app://formshow?form=OutgoingCommunication&amp;id=" + encodeURIComponent(targetId) + "&amp;workflowPk=" + item.WorkflowPk);
          break;

        case "AccountApp":
          widget.ExecuteApplicationShortcutUrl("app://formshow?form=OutgoingCommunication&amp;id=" + encodeURIComponent(targetId) + "&amp;workflowPk=" + item.WorkflowPk);
          break;

        case "Client":
          widget.ExecuteApplicationShortcutUrl("app://formshow?form=OutgoingCommunication&amp;id=" + encodeURIComponent(targetId) + "&amp;workflowPk=" + item.WorkflowPk);
          break;
      }
      break;

  case "ACTIONDOCUMENT":
      // Send Document
      widget.ExecuteApplicationShortcutUrl("app://formshow?form=DocumentCreate&amp;type=" + targetType + "&amp;id=" + encodeURIComponent(targetId) + "&amp;workflowPk=" + item.WorkflowPk);
      break;

  case "ACTIONEMAIL":
      // Send Email
      widget.ExecuteApplicationShortcutUrl("app://formshow?form=EmailMessage&amp;type=" + targetType + "&amp;id=" + encodeURIComponent(targetId) + "&amp;workflowPk=" + item.WorkflowPk);
      break;

    case "ACTIONLOG":
      // Add a Log
      switch (targetType) {
        case "Account":
          widget.ExecuteApplicationShortcutUrl("app://formshow?form=AccountLog&amp;accountId=" + encodeURIComponent(targetId) + "&amp;workflowId=" + encodeURIComponent(item.WorkflowId));
          break;

        case "AccountApp":
          widget.ExecuteApplicationShortcutUrl("app://formshow?form=AccountAppLog&amp;accountAppId=" + encodeURIComponent(targetId) + "&amp;workflowId=" + encodeURIComponent(item.WorkflowId));
          break;

        case "Client":
          widget.ExecuteApplicationShortcutUrl("app://formshow?form=ClientLog&amp;clientId=" + encodeURIComponent(targetId) + "&amp;workflowId=" + encodeURIComponent(item.WorkflowId));
          break;
      }
      break;

  case "ACTIONSMS":
      // Send SMS
      widget.ExecuteApplicationShortcutUrl("app://formshow?form=SmsMessage&amp;type=" + targetType + "&amp;id=" + encodeURIComponent(targetId) + "&amp;workflowPk=" + item.WorkflowPk);
      break;

    case "MONITORCATEGORYAEDIT":
    case "MONITORCATEGORYBEDIT":
    case "MONITORCATEGORYCEDIT":
      // Edit Monitor Category
      var monitorCategory = actionId.substr(15, 1);
      widget.ExecuteApplicationShortcutUrl("app://formshow?form=AccountMonitorCategoryChange&amp;id=" + encodeURIComponent(targetId) + "&amp;accountMonitorCategory=" + monitorCategory);
      break;

    case "PAYMENTARRANGEMENT":
      // Payment Arrangement
      widget.ExecuteApplicationShortcutUrl("app://formshow?form=AccountPaymentArrangementAdd&amp;id=" + encodeURIComponent(targetId));
      break;

    case "PAYMENTPROMISE":
      // Payment Promise
      widget.ExecuteApplicationShortcutUrl("app://formshow?form=AccountPaymentPromiseAdd&amp;id=" + encodeURIComponent(targetId));
      break;

    case "PREVIEWPANETOGGLE":
      // Toggle Preview Pane
      mPreviewPaneVisible = !mPreviewPaneVisible;
      if (mPreviewPaneVisible) {
        C.pnlItems.show();
      }
      else {
        C.pnlItems.hide();
      }
      gridItems_RefreshButtons();
      break;

    case "WORKFLOWADD":
      // Add Workflow
      wbItems_ApplicationShortcutHandler("app://formshow?form=WorkflowNew&amp;type=" + targetType + "&amp;id=" + encodeURIComponent(targetId));
      break;

    case "WORKFLOWCLOSE":
      // Close Workflow
      wbItems_ApplicationShortcutHandler("app://formshow?form=WorkflowClose&amp;id=" + encodeURIComponent(item.WorkflowId));
      break;

    case "WORKFLOWHOLD":
      // Hold Workflow
      // NOTE: This can be handled as a global form action and we specify both Workflow and WorkflowId for backward compatibility
      wbItems_ApplicationShortcutHandler("app://formaction?action=WorkflowHold&amp;workflowid=" + encodeURIComponent(item.WorkflowId) + "&amp;workflow=" + encodeURIComponent(item.WorkflowId));
      break;

    case "WORKFLOWUNHOLD":
      // Unhold Workflow
      // NOTE: This can be handled as a global form action and we specify both Workflow and WorkflowId for backward compatibility
      wbItems_ApplicationShortcutHandler("app://formaction?action=WorkflowUnhold&amp;workflowid="  + encodeURIComponent(item.WorkflowId) + "&amp;workflow=" + encodeURIComponent(item.WorkflowId));
      break;

    default:
      // Get Unique Ids of selected rows
      var uniqueIds = [];
      var canActionCount = 0;
      for (var i = 0; i &lt; mSelectedRowDetails.length; i++) {
        var row = mSelectedRowDetails[i];
        var item = mRecord_Items[row.listIndex];
        uniqueIds.push(row.value);

        // Can this action be performed on this row?
        switch(actionId) {
          case "UpdateFlag":
            canActionCount += 1
            break;
            
          case "WorkflowUserAllocate":
          case "WorkflowUserClear":
            canActionCount += 1
            break;
            
          case "WorkflowRecallDate":
          case "WorkflowRecallDateClear":
          case "WorkflowRecallImmediately":
            canActionCount += 1
            break;
        }
      }

      // Confirm
      var msg = "", title = "", prompt = true;
      switch (actionId) {
        case "UpdateFlag":
          // Prompt for Flag Colour
          widget.UI.SelectFlagColour(null, {},
            function (colour) {
              gridItems_Action_Perform(actionId, uniqueIds, colour);
            }
          );
          return;
          
        case "WorkflowRecallDate":
          // Prompt for Recall Period
          var list = [];
          list.push({ caption: "Other...", key: "Other", icon: "Calendar" });          
          list.push({ caption: "1 day", key: "1d", icon: "Calendar" });
          list.push({ caption: "2 days", key: "2d", icon: "Calendar" });
          list.push({ caption: "3 days", key: "3d", icon: "Calendar" });
          list.push({ caption: "4 days", key: "4d", icon: "Calendar" });
          list.push({ caption: "5 days", key: "5d", icon: "Calendar" });
          list.push({ caption: "6 days", key: "6d", icon: "Calendar" });
          list.push({ caption: "1 week", key: "1w", icon: "Calendar" });
          list.push({ caption: "2 weeks", key: "2w", icon: "Calendar" });
          list.push({ caption: "1 month", key: "1m", icon: "Calendar" });
          widget.UI.MsgBoxList("", list, { title: "Update Recall Date", showClose: true, closeOnEscape: true },
            function (value) {
              if (value == "Other") {
                // Prompt for date
                widget.UI.GetInputDateTime("Enter a Recall Date for the selected Workflow(s).", {},
                  function (value, timeZoneId) {
                    gridItems_Action_Perform(actionId, uniqueIds, JSON.stringify({ value: value, timeZoneId: timeZoneId}));
                  }
                );
              }
              else {
                gridItems_Action_Perform(actionId, uniqueIds, value);
              }
            }
          );
          return;

        case "WorkflowUserAllocate":
          // Prompt for User
          widget.UI.Forms.ShowRangeLookupFromStandardRange("Users", "", { sqlWhere: "Active=True", rangeSingle: true },
            function (userId) {
              if (userId) gridItems_Action_Perform(actionId, uniqueIds, userId);
            }
          );
          return;

        case "WorkflowRecallDateClear":
          // No prompt
          prompt = false;
          break;
          
        case "WorkflowRecallImmediately":
          // Prompt for Action
          var list = [];
          list.push({ caption: "Clear Recall Immediately", key: "WorkflowRecallImmediatelyClear", icon: "Clear" });
          list.push({ caption: "Set Recall Immediately", key: "WorkflowRecallImmediatelySet", icon: "Review" });
          widget.UI.MsgBoxList("", list, { title: "Update Recall Immediately", showClose: true, closeOnEscape: true },
            function (value) { gridItems_Action_Perform(value, uniqueIds, {}); }
          );
          return;

        default:
          title = widget.SplitWordsAtCapitals(actionId);
      }

      switch (mSelectedRowDetails.length) {
        case 1:
          msg += "&lt;p&gt;Perform this action for the &lt;b&gt;1&lt;/b&gt; selected item?&lt;/p&gt;";
          break;

        default:
          msg += "&lt;p&gt;Perform this action for the &lt;b&gt;" + mSelectedRowDetails.length + "&lt;/b&gt; selected items?&lt;/p&gt;";
      }

      if (canActionCount == 0) {
        msg = "&lt;p style='color:red'&gt;&lt;b&gt;WARNING:&lt;/b&gt; This action cannot be performed on any of the selected items.&lt;/p&gt;";
        widget.UI.MsgBoxAlert(msg, { heading: title, messageIsHtml: true });
      }
      else if(prompt) {
        // Confirm action
        if (canActionCount != mSelectedRowDetails.length) {
          msg += "&lt;p style='color:red'&gt;&lt;b&gt;WARNING:&lt;/b&gt; This action can only be performed on &lt;b&gt;" + canActionCount + "&lt;/b&gt; of the &lt;b&gt;" + mSelectedRowDetails.length + "&lt;/b&gt; selected items.&lt;/p&gt;";
        }
        widget.UI.MsgBoxConfirm(msg, { heading: title, messageIsHtml: true }, function () { gridItems_Action_Perform(actionId, uniqueIds, actionParametersJson); });
      }
      else {
        // No confirmation required
        gridItems_Action_Perform(actionId, uniqueIds, actionParametersJson);
      }
      break;
  }
}

function gridItems_Action_Perform(actionId, uniqueIds, actionParametersJson) {
  // Block UI
  widget.UI.Block("Performing action, please wait...");

  // Action
  widget.GetString("PerformAction", { actionId: actionId, uniqueIds: uniqueIds, actionParametersJson: actionParametersJson },
   function (data) {
    // Parse
    data = JSON.parse(data);

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

    // Load and refresh grid
    Record_Load();

    // Warnings
    if (data.Warnings) {
      widget.UI.MsgBoxAlert(data.Warnings);
    }
   },

   function (error) {
    // Unblock UI
    widget.UI.Unblock();

    widget.UI.MsgBoxAlert(error);
   }
  );
}

function gridItems_AfterRowActivate(e) {
  // Preview
  wbItems_Preview();

  // Refresh Buttons
  gridItems_RefreshButtons();
}

function gridItems_SelectedRowsChanged(e) {
  // Refresh Buttons
  gridItems_RefreshButtons();
}

function gridItems_RefreshButtons() {
  var rows = C.gridItems.GetSelectedRowIndexes(true, true);
  var singleRowActive = C.gridItems.ActiveDataRowListIndex() != -1 &amp;&amp; rows.length == 1;
  var singleActiveItem = C.gridItems.ActiveDataRowListIndex() != -1 &amp;&amp; rows.length == 1 ? mRecord_Items[C.gridItems.ActiveDataRowListIndex()] : null;
  var targetId;
  var targetType;
  if (singleActiveItem) {
    targetId = singleActiveItem.TargetId;
    targetType = singleActiveItem.TargetType;
  }

  // Find actions that can be performed on selected rows
  var canDelete = false, canHold = false, canPending = false, canApprove = false, canCancel = false, canReverse = false;
  for (var i = 0; i &lt; rows.length; i++) {
    var item = mRecord_Items[rows[i]];
    //if (item.CanApprove) canApprove = true;
    //if (item.CanCancel) canCancel = true;
  }

  // Update action states
  C.gridItems.Actions().SetEnabled("UpdateFlag", rows.length != 0);
  
  C.gridItems.Actions().SetEnabled("WorkflowRecallDate", rows.length != 0);
  C.gridItems.Actions().SetEnabled("WorkflowRecallDateClear", rows.length != 0);
  C.gridItems.Actions().SetEnabled("WorkflowRecallImmediately", rows.length != 0);
  
  C.gridItems.Actions().SetEnabled("WorkflowUserAllocate", rows.length != 0);
  C.gridItems.Actions().SetEnabled("WorkflowUserClear", rows.length != 0);
  
  C.gridItems.Actions().SetEnabled("WorkflowHold", singleActiveItem &amp;&amp; singleActiveItem.Status != "OnHold");
  C.gridItems.Actions().SetEnabled("WorkflowUnhold", singleActiveItem &amp;&amp; singleActiveItem.Status == "OnHold");
  
  C.gridItems.Actions().SetEnabled("WorkflowClose", singleActiveItem);
  
  // Type-specific
  if (singleActiveItem) {
    switch (targetType) {
      case "Account":
        C.gridItems.Actions().SetEnabled("WorkflowAdd", mRecord.AllowWorkflowAddAccount);
        
        C.gridItems.Actions().SetEnabled("ActionLog", mRecord.AllowLogAccount);
        C.gridItems.Actions().SetEnabled("ActionCommunicationIncoming", mRecord.AllowLogAccount);
        C.gridItems.Actions().SetEnabled("ActionCommunicationOutgoing", mRecord.AllowLogAccount);
        C.gridItems.Actions().SetEnabled("ActionDocument", mRecord.AllowDocumentAccount);
        C.gridItems.Actions().SetEnabled("ActionEmail", true);
        C.gridItems.Actions().SetEnabled("ActionSms", true);
        break;
        
      case "AccountApp":
        C.gridItems.Actions().SetEnabled("WorkflowAdd",  mRecord.AllowWorkflowAddAccountApp);
        
        C.gridItems.Actions().SetEnabled("ActionLog", mRecord.AllowLogAccountApp);
        C.gridItems.Actions().SetEnabled("ActionCommunicationIncoming", mRecord.AllowLogAccountApp);
        C.gridItems.Actions().SetEnabled("ActionCommunicationOutgoing", mRecord.AllowLogAccountApp);
        C.gridItems.Actions().SetEnabled("ActionDocument", mRecord.AllowDocumentAccountApp);
        C.gridItems.Actions().SetEnabled("ActionEmail", true);
        C.gridItems.Actions().SetEnabled("ActionSms", true);
        break;        
        
      case "Client":
        C.gridItems.Actions().SetEnabled("WorkflowAdd",  mRecord.AllowWorkflowAddClient);
        
        C.gridItems.Actions().SetEnabled("ActionLog", mRecord.AllowLogClient);
        C.gridItems.Actions().SetEnabled("ActionCommunicationIncoming", mRecord.AllowLogClient);
        C.gridItems.Actions().SetEnabled("ActionCommunicationOutgoing", mRecord.AllowLogClient);
        C.gridItems.Actions().SetEnabled("ActionDocument", mRecord.AllowDocumentClient);
        C.gridItems.Actions().SetEnabled("ActionEmail", true);
        C.gridItems.Actions().SetEnabled("ActionSms", true);
        break;    
        
      default:
        C.gridItems.Actions().SetEnabled("WorkflowAdd", false);
        
        C.gridItems.Actions().SetEnabled("ActionLog", false);
        C.gridItems.Actions().SetEnabled("ActionCommunicationIncoming", false);
        C.gridItems.Actions().SetEnabled("ActionCommunicationOutgoing", false);
        C.gridItems.Actions().SetEnabled("ActionDocument", false);
        C.gridItems.Actions().SetEnabled("ActionEmail", false);
        C.gridItems.Actions().SetEnabled("ActionSms", false);
        break;    
    }
  }
  else {
    C.gridItems.Actions().SetEnabled("WorkflowAdd",  false);
    
    C.gridItems.Actions().SetEnabled("ActionLog",  false);
    C.gridItems.Actions().SetEnabled("ActionCommunicationIncoming",  false);
    C.gridItems.Actions().SetEnabled("ActionCommunicationOutgoing",  false);
    C.gridItems.Actions().SetEnabled("ActionDocument",  false);
    C.gridItems.Actions().SetEnabled("ActionEmail",  false);
    C.gridItems.Actions().SetEnabled("ActionSms",  false);
  }

  // Account-specific
  C.gridItems.Actions().SetEnabled("PaymentArrangement", singleActiveItem &amp;&amp; singleActiveItem.TargetType == "Account" &amp;&amp; singleActiveItem.TargetStatus == "Open");
  C.gridItems.Actions().SetEnabled("PaymentPromise", singleActiveItem &amp;&amp; singleActiveItem.TargetType == "Account" &amp;&amp; singleActiveItem.TargetStatus == "Open");

  C.gridItems.Actions().SetEnabled("MonitorCategoryAEdit", singleRowActive &amp;&amp; singleActiveItem.TargetType == "Account");
  C.gridItems.Actions().SetEnabled("MonitorCategoryBEdit", singleRowActive &amp;&amp; singleActiveItem.TargetType == "Account");
  C.gridItems.Actions().SetEnabled("MonitorCategoryCEdit", singleRowActive &amp;&amp; singleActiveItem.TargetType == "Account");

  //   Application-specific
    
  C.gridItems.Actions().SetChecked("PreviewPaneToggle", !mPreviewPaneVisible);

  C.gridItems.RefreshButtons();
}

function gridItems_InitialiseRow(e) {
  var item = mRecord_Items[e.row.listIndex];

  // Update cells
  e.row.AutoBind(item);
  
  // Update User Data cells
  e.row.AutoBindTaskManager2UserData(item);

  // Other
  e.row.cells.DateCreatedDateTime.value = item.DateCreated;
  e.row.cells.DateOpenedDateTime.value = item.DateOpened;  
  e.row.cells.TargetTypeIcon.value = item.TargetType;

  // Tooltip
  e.row.cells.InfoStatusIcon.tooltipText = item.InfoStatusText;

  // Cell hyperlinks
  e.row.cells.TargetId.hyperlink = "app://formshow?form=" + item.TargetType + "&amp;id=" + encodeURI(item.TargetId);
  e.row.cells.WorkflowId.hyperlink = "app://formshow?form=Workflows&amp;id=" + encodeURI(item.WorkflowId);

  // Styles
  e.row.cells.TargetDescription.small = true;
  e.row.cells.Description.small = true;
}

function gridItems_Refresh() {

  var hasAccounts = false;
  var hasAccountApps = false;
  var hasClients = false;
  var hasReviewDate = false;

  // Determine which columns should be included
  for(var i = 0; i &lt; mRecord_Items.length; i++) {
    var item = mRecord_Items[i];

    if (item.TargetType == "Account") hasAccounts = true;
    if (item.TargetType == "AccountApp") hasAccountApps = true;
    if (item.TargetType == "Client") hasClients = true;
    
    if (item.ReviewDate) hasReviewDate = true;
  }

  // Add Columns
  // NOTE: Columns may be added but not shown for exporting and visualisation purposes
  C.gridItems.ClearColumns();
  C.gridItems.AddColumnIcon("InfoStatusIcon", { caption: "", sortable: true, autoHideBelowScreenWidth: 800 });
  C.gridItems.AddColumnColourFlag("FlagColour", { caption: "", sortable: true });
  C.gridItems.AddColumnString("TargetType", { caption: "Target Type", visible: false });
  C.gridItems.AddColumnIcon("TargetTypeIcon", { caption: "", autoHideBelowScreenWidth: 800 });
  C.gridItems.AddColumnCode("TargetId", { caption: "Target", sortable: true });
  C.gridItems.AddColumnString("TargetDescription", { caption: "Name", sortable: true, autoHideBelowScreenWidth: 800 });
  C.gridItems.AddColumnCode("WorkflowId", { caption: "Workflow", sortable: true, autoHideBelowScreenWidth: 1300 });
  C.gridItems.AddColumnString("Description", { caption: "Description", sortable: true, autoHideBelowScreenWidth: 1200 });
  C.gridItems.AddColumnCode("WorkflowTypeId", { caption: "Type", sortable: true, autoHideBelowScreenWidth: 1300 });
  C.gridItems.AddColumnDate("DateCreated", { caption: "Date Created", sortable: true, visible: false });
  C.gridItems.AddColumnDateTime("DateCreatedDateTime", { caption: "Date Created", sortable: true });
  C.gridItems.AddColumnDate("DateOpened", { caption: "Date Opened", sortable: true, visible: false });
  C.gridItems.AddColumnDateTime("DateOpenedDateTime", { caption: "Date Opened", sortable: true, visible: false });  
  C.gridItems.AddColumnDate("RecallDate", { caption: "Recall", sortable: true, autoHideBelowScreenWidth: 800 });
  C.gridItems.AddColumnDate("ReviewDate", { caption: "Review", sortable: true, visible: hasReviewDate, autoHideBelowScreenWidth: 800 });
  C.gridItems.AddColumnCode("AllocatedUserId", { caption: "Allocated", sortable: true, autoHideBelowScreenWidth: 1300 });  

  if (hasAccounts) {
    // Account-specific
    C.gridItems.AddColumnCurrency("Balance", { caption: "Balance", sortable: true, visible: !mRecord.IsClientManagement });
    C.gridItems.AddColumnCurrency("BalanceOverdue", { caption: "Overdue", sortable: true, visible: !mRecord.IsClientManagement });
    C.gridItems.AddColumnInteger("OverdueDays", { caption: "O/D", sortable: true, visible: !mRecord.IsClientManagement });
    C.gridItems.AddColumnCurrency("BalanceOverdueContractual", { caption: "Contractual", sortable: true, visible: !mRecord.IsClientManagement });
    C.gridItems.AddColumnInteger("OverdueDaysContractual", { caption: "C O/D", sortable: true, visible: !mRecord.IsClientManagement });
    
    // Required for visualisation only
    C.gridItems.AddColumnCode("AccountTypeId", { caption: "Account Type", visible: false });
  }

  if (hasAccountApps) {
    // Account Application-specific
    
    // Required for visualisation only
    C.gridItems.AddColumnCode("AccountAppTypeId", { caption: "Application Type", visible: false });
  }

  if (hasClients) {
    // Client-specific
  }

  // User Data
  if (mRecord.UserDataHeadings &amp;&amp; mRecord.UserDataHeadings.length != 0) {
    for (var i = 0; i &lt; mRecord.UserDataHeadings.length; i++) {
      var heading = mRecord.UserDataHeadings[i];
      
      if (heading.Caption === null) {
        // Ignore
      }
      else {
        C.gridItems.AddColumnFromTaskManager2UserDataHeading(heading);
      }
    }
  }

  // Group By Column
  if (mRecord.GroupByColumn) {
    C.gridItems.GroupByColumnsUpdate(mRecord.GroupByColumn);
    if (mRecord.GroupByColumnHide) C.gridItems.ColumnVisible(mRecord.GroupByColumn, false);
  }

  // Columns to display
  if (mRecord.Columns) {
    C.gridItems.SortColumnsByArray(mRecord.Columns, false, true);
  }

  // Warning
  if (mRecord.WarningMessage) {
    widget.UI.ShowNotification("Warning", mRecord.WarningMessage, "", "Folder Limit Exceeded");
  }

  // Actions
  var actions = [];
  actions.push({ actionId: "Refresh", tooltipText:"Refresh", icon: "Refresh" });

  if (!mRecord.ReadOnly) {
    actions.push({});
    actions.push({ actionId: "UpdateFlag", tooltipText:"Update flag colour", icon: "Flag[darkred]" });
    
    if (mRecord.AllowWorkflowRecallDate) {
      actions.push({});
      actions.push({ actionId: "WorkflowRecallDate", icon: "Calendar", tooltipText: "Update Recall Date", caption: "Recall" });
      actions.push({ actionId: "WorkflowRecallDateClear", icon: "Calendar|Clear", tooltipText: "Clear Recall Date" });
      actions.push({ actionId: "WorkflowRecallImmediately", icon: "Review", tooltipText: "Recall immediately" });
    }

    actions.push({});
    actions.push({ actionId: "ActionLog", icon: "Log_Add", tooltipText: "Add Log" });
    actions.push({ actionId: "ActionCommunicationIncoming", icon: "Communication_Incoming", tooltipText: "Add Incomming Communication Log" });
    actions.push({ actionId: "ActionCommunicationOutgoing", icon: "Communication_Outgoing", tooltipText: "Add Outgoing Communication Log" });
    actions.push({ actionId: "ActionDocument", icon: "Document", tooltipText: "Send Document" });
    actions.push({ actionId: "ActionEmail", icon: "Email", tooltipText: "Send Email" });
    if (mRecord.IsMessagingAvailable) {
      actions.push({ actionId: "ActionSms", icon: "Sms", tooltipText: "Send SMS" });    
    }

    if (mRecord.AllowWorkflowUserAllocate) {
      actions.push({});
      actions.push({ actionId: "WorkflowUserAllocate", icon: "User_Delegate", tooltipText: "Allocate User", caption: "User" });
      actions.push({ actionId: "WorkflowUserClear", icon: "User|Clear", tooltipText: "Clear allocated User" });
    }
    
    if (mRecord.AllowWorkflowHoldUnhold) {
      actions.push({});
      actions.push({ actionId: "WorkflowHold", tooltipText:"Hold Workflow", icon: "Hold" });
      actions.push({ actionId: "WorkflowUnhold", tooltipText:"Unhold Workflow", icon: "Hold_Clear" });
    }
    if (mRecord.AllowWorkflowClose || mRecord.AllowWorkflowAddAccount || mRecord.AllowWorkflowAddAccountApp || mRecord.AllowWorkflowAddClient) {
      actions.push({});
      if (mRecord.AllowWorkflowClose) actions.push({ actionId: "WorkflowClose", tooltipText:"Close Workflow", icon: "Workflow_Close" });
      if (mRecord.AllowWorkflowAddAccount || mRecord.AllowWorkflowAddAccountApp || mRecord.AllowWorkflowAddClient) actions.push({ actionId: "WorkflowAdd", tooltipText:"Add New Workflow", icon: "Workflow_Add" });
    }

    if (hasAccounts) {
      // Account-specific
      if (!mRecord.IsClientManagement &amp;&amp; (mRecord.AllowPaymentArrangement || mRecord.AllowPaymentPromise)) {
        actions.push({});
        if (mRecord.AllowPaymentArrangement) actions.push({ actionId: "PaymentArrangement", icon: "PaymentArrangement", tooltipText: "Make a Payment Arrangement" });
        if (mRecord.AllowPaymentPromise) actions.push({ actionId: "PaymentPromise", icon: "PaymentArrangement", tooltipText: "Make a Payment Promise" });
      }

      if (mRecord.AllowMonitorCategoryAUpdate || mRecord.AllowMonitorCategoryBUpdate || mRecord.AllowMonitorCategoryCUpdate) {
        actions.push({});
        if (mRecord.AllowMonitorCategoryAUpdate) actions.push({ actionId: "MonitorCategoryAEdit", icon: "MonitorCategory", caption: mRecord.MonitorCategoryADescription });
        if (mRecord.AllowMonitorCategoryBUpdate) actions.push({ actionId: "MonitorCategoryBEdit", icon: "MonitorCategory", caption: mRecord.MonitorCategoryBDescription });
        if (mRecord.AllowMonitorCategoryCUpdate) actions.push({ actionId: "MonitorCategoryCEdit", icon: "MonitorCategory", caption: mRecord.MonitorCategoryCDescription });
      }
    }

    if (hasAccountApps) {
      // Account Application-specific
    }

    if (hasClients) {
      // Client-specific
    }
  }
  
  if (mRecord.ShowPreviewPane) {
    actions.push({});
    actions.push({ actionId: "PreviewPaneToggle", icon: "Form_PreviewPane|ArrowDown", tooltipText: "Show or hide summary", checked: !mPreviewPaneVisible });
  }
  
  if (mRecord.AllowLoadAll) {
    actions.push({});
    actions.push({ actionId: "LoadAll", icon: "Grid|Download", caption: "Load ALL Items" });
  }
  
  C.gridItems.Actions().Define(actions);

  // Give collection ability to form a unique cache key and preview parameters for the Widget
  mRecord_Items.GetCacheKey = function (index) {
    var item = mRecord_Items[index];
    return item.UniqueId;
  };
  mRecord_Items.GetPreviewFetchParameters = function (index) {
    var item = mRecord_Items[index];
    var o = {};

    o.uniqueId = item.UniqueId;
    o.target = "WebInternal";
    o.highDpi = widget.IsHighDpi();

    return o;
  };

  // Refresh
  C.gridItems.VirtualDataRefresh(mRecord_Items, false, { retainSelectedRows: false });

  // Activate First Row
  if (mActiveRowUniqueId) {
    for (var i = 0; i &lt; mRecord_Items.length; i++) {
      if (mRecord_Items[i].UniqueId == mActiveRowUniqueId) {
        C.gridItems.ActiveDataRowListIndex(i);
        break;
      }
    }

    mActiveRowUniqueId = "";
  }
  else {
    C.gridItems.ActivateFirstDataRow();
  }

  // Select Rows
  if (mSelectedRowDetails &amp;&amp; mSelectedRowDetails.length != 0) {
    C.gridItems.SetSelectedRowDetailsFromUniqueProperty("UniqueId", mSelectedRowDetails, true);
    mSelectedRowDetails = [];
  }

  // Refresh buttons (the next section will do this)
  gridItems_RefreshButtons();
}

// =======
// wbItems
// =======
function wbItems_Preview() {
  C.wbItems.PreviewFromGridCollection(C.gridItems, mRecord_Items, "GetItemPreview");
}

function wbItems_ApplicationShortcutHandler(applicationShortcutUrl) {
  if (applicationShortcutUrl.toUpperCase().startsWith("APP://FORMACTION")) {
    // Send to the global form action handler (i.e., this form does not handle it but it can be handled centrally)
    widget.ExecuteApplicationShortcutUrl(applicationShortcutUrl, true);

    // Record what this action was (we can optimise grid refreshes in Form_ExecuteAction using this information since actions such as 'Hold' and 'Unhold' will block the UI)
    mLastWorkflowFormAction = applicationShortcutUrl.toUpperCase();
  }
  else {
    widget.ExecuteApplicationShortcutUrl(applicationShortcutUrl);
  }
}

// ============
// gvVisualiser
// ============
function gvVisualiser_Refresh(hasAccounts, hasAccountApps, hasClients) {
  var hasAccounts = false;
  var hasAccountApps = false;
  var hasClients = false;
  var targetTypes = 0;

  // Determine which special visualisations should be included
  for(var i = 0; i &lt; mRecord_Items.length; i++) {
    var item = mRecord_Items[i];

    if (!hasAccounts &amp;&amp; item.TargetType == "Account") {
      hasAccounts = true;
      targetTypes += 1;
    }
    if (!hasAccountApps &amp;&amp; item.TargetType == "AccountApp") {
      hasAccountApps = true;
      targetTypes += 1;
    }
    if (!hasClients &amp;&amp; item.TargetType == "Client") {
      hasClients = true;
      targetTypes += 1;
    }
  }

  // Define pre-set visualisations
  var visualisations = [];
  visualisations.push({ caption: "By Flag Colour", chartType: "Pie", seriesColumn: "FlagColour", labelColumn: "FlagColour" });
  if (targetTypes &gt; 1) {
    visualisations.push({ caption: "By Target Type", chartType: "Pie", seriesColumn: "TargetType", labelColumn: "TargetType" });
  }
  visualisations.push({ caption: "By Workflow Type", chartType: "Pie", seriesColumn: "WorkflowTypeId", labelColumn: "WorkflowTypeId", default: true });
  if (hasAccounts) {
    visualisations.push({ caption: "By Account Type", chartType: "Pie", seriesColumn: "AccountTypeId", labelColumn: "AccountTypeId" });
  }
  if (hasAccountApps) {
    visualisations.push({ caption: "By Account Application Type", chartType: "Pie", seriesColumn: "AccountAppTypeId", labelColumn: "AccountAppTypeId" });
  }

  // Options
  var options = {
    persistId: mRecord.PersistId, // Specifying this means that the User's selections will be retained between sessions (on the device) where possible
    visualisations: visualisations,
    allowCustomVisualisation: true, // i.e., allow a simple column/ chart combination
    title: "Workflows",
    subTitle: mFolderInfo,
  };

  // Refresh (options will extend options used when this control was created so only need to specify data-specific options here)
  C.gvVisualiser.Refresh(options);
}
&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>lTQXGbfVZk2GIsCK391HdQ</UniqueId>
    <AllowRefresh>true</AllowRefresh>
    <Caption />
    <HtmlWidgetAllowInitialEventCaching>true</HtmlWidgetAllowInitialEventCaching>
    <HtmlWidgetMaxHeight>0</HtmlWidgetMaxHeight>
    <HtmlWidgetMaxWidth>1200</HtmlWidgetMaxWidth>
    <HtmlWidgetNeverApplyStyling>false</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>TESTING</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText>These are the Parameters required by this HTML Widget to function correctly.
They are listed here for testing purposes only.</TooltipText>
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="FolderId" 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>System_Workflows_All,System_Workflows_All_Account,System_Workflows_All_Client</List>
            <LimitToList>false</LimitToList>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="UserId" 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>20</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="DateAsAt" type="Date">
            <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>
            <IncludeTime>false</IncludeTime>
            <MaxValue />
            <MinValue />
          </Parameter>
          <Parameter name="DateAsAtMnemonic" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText>This can be used as an alternative to 'DateAsAt' to provide a relative Date As At.</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>,EOW,EOM,EOM+1,D-7,D-1,D+1,D+7</List>
            <LimitToList>false</LimitToList>
            <MaxLength>10</MaxLength>
            <Rows>1</Rows>
          </Parameter>
        </Parameters>
      </ISParameterDefs>
    </Parameters>
  </finScript>