<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2022-12-19T02:58:58.0000000">
    <CreatedUserId>Admin</CreatedUserId>
    <CreatedUtcDate>2021-08-26T00:52:01.0230000</CreatedUtcDate>
    <UpdatedUserId>Admin</UpdatedUserId>
    <UpdatedUtcDate>2022-12-19T02:57:11.3060000</UpdatedUtcDate>
    <ScriptId>SLD</ScriptId>
    <Description>Smart List handler for Task Manager</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_SmartList
Option Explicit On
Option Strict On

' #################################################################
' Smart List Handler for Task Manager 2
'
' Version: 1.01 (19/12/2022)
'
' Usage: System-defined HTML Widget
'
' This functionality duplicates functionality in finPOWER Connect Cloud
' isuserinterface_smartlist.js and Web Services ISSmartListController
'
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.00  03/05/2022  ISS      J027293   Created
'          07/06/2022  ISS      J028452   User Defined fields not retaining indexes
'    1.01  19/12/2022  ISS      J030208   Commented out unused variables
' #################################################################

' Constants
Private Const FORM_KEY As String = ""

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

' Standard Parameters
Private mDateAsAt As Date
Private mSmartListAllowParametersCustomise As Boolean
Private mSmartListColumns As String
Private mSmartListId As String
Private mSmartListParametersUserCustomisationJson As String
Private mSmartListStartupParametersJson As String
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")
    mSmartListAllowParametersCustomise = .GetBoolean("SmartListAllowParametersCustomise")
    mSmartListColumns = .GetString("SmartListColumns")
    mSmartListId = .GetString("SmartListId")
    mSmartListParametersUserCustomisationJson = .GetString("SmartListParametersUserCustomisationJson")
    mSmartListStartupParametersJson = .GetString("SmartListStartupParametersJson")
    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 "ExecuteRowAction"
      ' Execute Row Action
      Main = ExecuteRowAction(returnValue)

    Case "ExecuteSmartList"
      ' Execute Smart List
      Main = ExecuteSmartList(returnValue)

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

    Case "GetRowSummary"
      ' Get Row Summary
      Main = GetRowSummary(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 FormInitialisationInfo As FormInitialisationInfo
  Dim LogSeverity As finLogSeverityRO
  Dim Script As I_finScript
  Dim SmartListHandler As finSmartListHandler
  Dim Success As Boolean
'  Dim TaskManager As finTaskManager2
'  Dim TaskManagerFolder As finTaskManagerFolder

  ' Assume Success
  Success = True

  ' Initialise
  FormInitialisationInfo = New FormInitialisationInfo()

  ' Validate
  If Len(mSmartListId) = 0 Then
    Success = False
    finBL.Error.ErrorBegin("SmartListId not specified.")
  End If

  ' Create Smart List Handler
  If Success Then
    Success = CreateSmartListHandler(SmartListHandler, Script)
  End If

  ' Get Form Initialisation Info
  If Success Then
    With FormInitialisationInfo
      .ReadOnly = finBL.Database.IsReadOnly

      ' Record
      .DateAsAtText = finBL.FormatDateLong(mDateAsAt)
      .TimeZoneDescription = finBL.Runtime.TimeZones(finBL.TimeZoneId).WindowsTimeZoneDisplayName
      .UserId = mUserId

      ' Smart List Definition
      .AutoRun = True 'TODO:
      .Caption = Script.CaptionResolved
      '.Icon = Script.icon
      '.ParametersHideByDefault = 'TODO:
      '.System = 'TODO:
      'SmartListHandler.

      ' Smart List Parameters
      .Parameters = finBL.CreateWsParameters(SmartListHandler.Parameters)

      ' Permissions

      ' Global Collections
      For Each LogSeverity In finBL.LogSeverities
        .LogSeverities.Add(New LogSeverityInfo(LogSeverity))
      Next

      ' Configuration
      .ShowSummary = SmartListHandler.Parameters.GetBoolean("ShowSummary")
    End With
  End If

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

  Return Success

End Function

Private Function CreateSmartListHandler(ByRef smartListHandler As finSmartListHandler,
                                        ByRef script As I_finScript) As Boolean

  Dim SmartList As finScriptExecutable
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Get Script or system-defined Smart List
  SmartList = finBL.Scripts.GetSmartList(mSmartListId)
  If SmartList Is Nothing Then
    Success = False
    finBL.Error.ErrorBeginFormat("Script '{0}' not found.", mSmartListId)
  Else
    script = DirectCast(SmartList, I_finScript)
  End If

  ' Initialise Smart List Handler
  If Success Then
    smartListHandler = finBL.CreateSmartListHandler()
    If smartListHandler.Initialise(Script, isefinSmartListHostingContext.Desktop, , iseSummaryPageTarget.Form, mUserId, mDateAsAt) Then
      ' Configure from Task Manager Parameters
      Success = smartListHandler.ConfigureFromTaskManagerParameters(mSmartListStartupParametersJson, mSmartListColumns, mSmartListAllowParametersCustomise, mSmartListParametersUserCustomisationJson)
    Else
      Success = False
    End If
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Execute Smart List.
''' &lt;/summary&gt;
Private Function ExecuteSmartList(ByRef returnValue As String) As Boolean

  Dim ExecutionParameters As ISKeyValueList
  Dim ParametersJson As String
  Dim SmartListHandler As finSmartListHandler
  Dim SmartListResults As finSmartListHandler.jsonSmartListExecuteResults
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

  ' Create Smart List Handler
  If Success Then
    Success = CreateSmartListHandler(SmartListHandler, Nothing)
  End If

  ' Execute
  If Success Then
    ' Create Execution Parameters
    ExecutionParameters = finBL.CreateKeyValueList()
    ExecutionParameters.FromHtmlWidgetParametersJsonString(ParametersJson)

    ' Execute
    Success = SmartListHandler.Execute(ExecutionParameters)

    ' Get Results
    If Success Then
      SmartListResults = SmartListHandler.ToSmartListExecuteResultsJsonObject()
    End If
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Execute a Smart List Row Action.
''' &lt;/summary&gt;
Private Function ExecuteRowAction(ByRef returnValue As String) As Boolean

  Dim Action As finSmartListAction
  Dim ActionId As String
  Dim ParametersJson As String
  Dim Parameters As ISKeyValueList
  Dim Success As Boolean
  Dim SmartListHandler As finSmartListHandler
  Dim SummaryColumns As ISKeyValueList
  Dim SummaryColumnsJson As String

  ' Assume Success
  Success = True

  ' Get Parameters
  With mCombinedParameters
    ActionId = .GetString("ActionId")
    ParametersJson = .GetString("ParametersJson")
    SummaryColumnsJson = .GetString("SummaryColumnsJson")
  End With

  ' Create Smart List Handler
  If Success Then
    Success = CreateSmartListHandler(SmartListHandler, Nothing)
  End If

  ' Get Action
  If SmartListHandler.Actions.Exists(ActionId) Then
    Action = SmartListHandler.Actions(ActionId)
  Else
    Success = False
    finBL.Error.ErrorBeginFormat("Action '{0}' not found.", ActionId)
  End If

  ' Execute Action
  If Success Then
    ' Get Parameters
    Parameters = finBL.CreateKeyValueList()
    Parameters.FromHtmlWidgetParametersJsonString(parametersJson)

    ' Get Summary Columns (supplied as a JSON array which must be converted to an ISKeyValueList)
    SummaryColumns = SmartListHandler.SummaryColumnsJsonToKeyValueList(summaryColumnsJson)

    ' Execute
    Success = SmartListHandler.ExecuteRowAction(SummaryColumns, ActionId, Parameters)
  End If

  Return Success

End Function

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

  Dim SmartListHandler As finSmartListHandler
  Dim Success As Boolean
  Dim SummaryColumns As ISKeyValueList
  Dim SummaryColumnsJson As String

  ' Assume Success
  Success = True

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

  ' Create Smart List Handler
  If Success Then
    Success = CreateSmartListHandler(SmartListHandler, Nothing)
  End If

  ' Get Summary Columns (supplied as a JSON array which must be converted to an ISKeyValueList)
  If Success Then
    SummaryColumns = SmartListHandler.SummaryColumnsJsonToKeyValueList(summaryColumnsJson)
  End If

  ' Execute
  If Success Then
    If SmartListHandler.GetRowSummary(SummaryColumns, Nothing) Then
      returnValue = SmartListHandler.RowSummary
    Else
      Success = False
    End If
  End If

  ' Get HTML Summary
  'returnValue = TaskManager.GetRowSummaryFromUniqueId(UniqueId)

  Return Success

End Function



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

  ' Record
  Public DateAsAtText As String
  Public TimeZoneDescription As String
  Public UserId As String

  ' Smart List Definition
  Public AutoRun As Boolean
  Public Caption As String
  Public Icon As String
  Public Parameters As ISWsParameters
  Public ParametersHideByDetault As Boolean
  Public ScriptId As String
  Public System As String


  ' Permissions

  ' Global Collections
  Public LogSeverities As New List(Of LogSeverityInfo)

  ' Configuration
  Public [ReadOnly] As Boolean
  Public ShowSummary As Boolean

  Public Sub New()

    'Me.Columns = New List(Of String)

  End Sub

End Class


''' &lt;summary&gt;
'''  Log Severity information.
''' &lt;/summary&gt;
''' &lt;returns&gt;&lt;/returns&gt;
Public Class LogSeverityInfo

  Public LogSeverityId As String
  Public Description As String
  Public CompleteColourBackground As String
  Public OpenColourBackground As String

  Public Sub New(logSeverity As finLogSeverityRO)

    With logSeverity
      Me.LogSeverityId = .LogSeverityId
      Me.Description = .Description
      Me.CompleteColourBackground = .CompleteColourBackground
      Me.OpenColourBackground = .OpenColourBackground
    End With

  End Sub

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

Used to display Smart Lists in Task Manager 2.</Notes>
    <PermissionKeyExecute />
    <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;Smart List&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" style="flex-grow:0"&gt;
          &lt;div id="phParameters" style="display:block"&gt;&lt;/div&gt;
          &lt;button id="cmdRun" class="is-button small ok"&gt;Run&lt;/button&gt;
        &lt;/div&gt;
        &lt;div class="panel"&gt;
          &lt;div id="gridItems"&gt;&lt;/div&gt;
        &lt;/div&gt;
        &lt;div id="divSummary" 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;/div&gt;

&lt;/div&gt;

&lt;script&gt;
// Properties
var mRecord;
var mRecord_Items;
var mRecord_Parameters;
var mData;

// Global Collections
var mLogSeverities;

// Other
var mActiveRowUniqueId = "";
var mSelectedRowUniqueIds = [];

// Controls
var C = {
  // General
  phParameters: null,
  cmdRun: null,
  gridItems: null,
  divSummary: null,
  wbItems: null,
}

// Form
var frmMain;
var tabDetails;

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

  // Controls
  C.phParameters = widget.UI.ParametersHost("phParameters", {});
  C.cmdRun = $("#cmdRun");
  C.cmdRun.on("click", Form_ExecuteAction_Run);
  C.divSummary = $("#divSummary");
  C.wbItems = widget.UI.PreviewPane("wbItems", {
    applicationShortcutHandler: wbItems_ApplicationShortcutHandler,
  });

  // 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
  });

  // 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;
  mRecord_Parameters = null;
  mData = null;

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

  // Hide content
  frmMain.Visible(false);

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

  // Load Initialisation details
  widget.GetString("GetInitialisationInfo", {},
    // Success
    function (data) {
      mRecord = JSON.parse(data);
      mRecord_Parameters = mRecord.Parameters;

      // Global Collections
      mLogSeverities = mRecord.LogSeverities;

      // Give Collections ability to lookup by code
      widget.ArrayAllowLookupById(mLogSeverities, "LogSeverityId");

      // LogSeverities.GetHtmlIcon
      mLogSeverities.GetHtmlIcon = function (id, isInComplete) {
        var item = mLogSeverities.GetItem(id);

        if (item) {
          var s = item.LogSeverityId + ": " + item.Description;
          if (isInComplete) {
            return "&lt;div class='is-colour-block' style='background-color:" + item.OpenColourBackground + "' title='" + s + "'&gt;&lt;/div&gt;";
          }
          else {
            return "&lt;div class='is-colour-block' style='background-color:" + item.CompleteColourBackground + "' title='" + s + "'&gt;&lt;/div&gt;";
          }
        }
        else {
          return "";
        }
      };

      // Notify Task Manager to update Folder Count
      //widget.ParentNotify("UpdateTaskManagerFolderCount", { folderId: mRecord.FolderId, count: mRecord_Items.length });

      Fields_Load();

      // Auto-Run?
      if (mRecord.AutoRun) Form_ExecuteAction("Run");
    },

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

// ===========
// Fields Load
// ===========
function Fields_Load() {
  if (mRecord) {
    // Parameters
    C.phParameters.Initialise(mRecord_Parameters);

    // General
    //gridItems_Refresh();
  }

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

  // Update Controls

  // Update fields
  Fields_Update();

  // Refresh Tab
  tabDetails_Refresh(0);
}

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

  // Lists

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

    // Useful for support
    //tabDetails.TabTooltipText("General", "To end of day " + mRecord.DateAsAtText + " - " + mRecord.TimeZoneDescription + " - for user '" + mRecord.UserId + "'");

    // Hide Run button?
    var countVisible = 0;
    for (var i = 0; i &lt; mRecord_Parameters.length; i++) {
      if (mRecord_Parameters[i].Visible) countVisible += 1;
    }
    if (countVisible == 0) C.cmdRun.hide();
  }

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

  // Resize
  tabDetails_Resize();
}

function tabDetails_Refresh(newTab) {
  // Moving forward onto tab, so Load information
  if (newTab &gt;= tabDetails.SelectedTabIndex()) {
    switch (tabDetails.GetTabIdByIndex(newTab)) {
      case "General":

        break;

      default:
        break;
    }
  }

  // Make Tab it
  tabDetails.SelectedTabIndex(newTab);

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

  // Tweak fields

  // 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()) {
    case "RUN":
      // Run
      Form_ExecuteAction_Run();
      break;

    default:
      window.alert("Form_ExecuteAction: Unhandled action '" + actionId + "'");
      break;
  }
}

function Form_ExecuteAction_Run() {
  // Validate Parameters

  // Get Parameters
  var parametersJson = "";
  if (mRecord_Parameters) {
    parametersJson = JSON.stringify(C.phParameters.GetParameterValuesWithTypes());
  }
  //var params = { parametersJson: parametersJson, highDpi: $Runtime.IsHighDpi() };
  var params = { parametersJson: parametersJson };

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

  // Execute
  widget.GetString("ExecuteSmartList", params,
    function (data) {
      mData = JSON.parse(data);

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

      // Refresh Grid
      gridItems_Refresh();

      // Focus
      C.phParameters.Focus();
    },

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

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

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;
  }
}

// =========
// gridItems
// =========
function gridItems_Action(actionId, specialParams, fileData) {
  // Non-Smart-List Actions
  switch (actionId) {
    case "Refresh":
      // Refresh
      Form_ExecuteAction_Run();
      return;
  }

  // Initialise
  var actions = mData.Actions;
  var grid = C.gridItems;

  // Get Action
  var action;
  for (var i = 0; i &lt; actions.length; i++) {
    if (actions[i].Id == actionId) {
      action = actions[i];
      break;
    }
  }
  if (!action) return;

  // Certain Actions (e.g., changing flag colours) may present an intermediate popup, the result of which is then passed as param
  if (!specialParams &amp;&amp; !fileData &amp;&amp; action.SpecialType) {
    switch (action.SpecialType) {
      case "FileUpload":
        // File Upload
        window.alert("File Upload not yet handled!");
//        var o = {};
//        $UI.GetFilesForUpload("Select Document to Upload", o, function (files) {
//          // Attach files
//          var fileData = [];
//          var doneCount = 0;
//          for (var i = 0; i &lt; files.length; i++) {
//            var r = new FileReader();
//            var f = files[i];
//            r.readAsDataURL(f);
//
//            r.onload = (function (f2) {
//              return function (e) {
//                doneCount += 1;
//                fileData.push({ name: f2.name, data: e.target.result });
//                if (doneCount === files.length) {
//                  // Initiate Upload
//                  grid_Action(actionId, {}, fileData);
//                }
//              }
//            })(f);
//          }
//        });
        return;

      case "FlagList":
        // Flag List
        widget.UI.SelectFlagColour(JSON.parse(action.ParametersJson).List, {}, function (colour) { gridItems_Action(actionId, { colour: colour }); })
        return;

      case "UserList":
        // User List
        window.alert("User List not yet handled!");
        //$UI.SelectUser(JSON.parse(action.ParametersJson).Title, {}, function (userId) { gridItems_Action(actionId, { userId: userId }); });
        return;

      default:
        window.alert("SpecialType '" + action.SpecialType + "' not handled.");
        return;
    }
  }

  // Save special parameters and file data to action (e.g., flag colour)
  if (specialParams) {
    action.SpecialParams = specialParams;
  }
  else {
    action.SpecialParams = null;
  }
  if (fileData) {
    action.FileData = fileData;
  }
  else {
    action.FileData = null;
  }

  // Get selected rows (including the active row if no selected rows but ignoring expired rows)
  var rows = grid.GetSelectedRowIndexes(true, true);
  if (rows.length === 0) return;

  // Prompt?
  var prompt = action.Prompt || (rows.length &gt; 1 &amp;&amp; action.PromptIfMultiple);
  if (prompt) {
    // Confirm
    ConfirmAction(action, rows, function () { gridItems_Action_Perform(action, rows) });
  }
  else {
    // Action
    gridItems_Action_Perform(action, rows);
  }
}

function gridItems_Action_Perform(action, rows) {
  // Block UI
  widget.UI.Block("Actioning, please wait...");

  // Action rows
  gridItems_Action_PerformItem(action, rows, 0);
}

function gridItems_Action_PerformItem(action, rows, index) {
  // Initialise
  var clientSide = false;
  var data = mData;

  // -----------
  // Client-Side
  // -----------
  // Certain Actions (e.g., showing a Form) are client-side only
  switch (action.ActionType) {
    case "RowFormOpen":
      // Show a Form
      window.alert("TODO: RowFormOpen");
//      clientSide = true;
//      var params = JSON.parse(action.ParametersJson);
//      var id = GetRowValue(rows, index, params.IdField);
//
//      // Resolve Tags in other parameters, e.g., [AccountId]
//      var otherParams = params.ParametersJson ? JSON.parse(params.ParametersJson) : {};
//      for (var key in otherParams) {
//        var value = otherParams[key];
//        if (value.startsWith("[") &amp;&amp; value.endsWith("]")) {
//          // Replace with field value
//          var row = rows[index];
//          value = value.substr(1, value.length - 2);
//          var field = GetRowValue(rows, index, value);
//          if (field === null) {
//            console.warn("Smart List row action as replaceable parameter [" + value + "] but no corresponding field was found in the row data.");
//          }
//          else {
//            otherParams[key] = field;
//          }
//        }
//      }
//
//      $App.FormOpen(params.Form, id, otherParams);
      break;
  }
  if (clientSide) {
    // Process next
    if (index &lt; rows.length - 1) {
      gridItems_Action_PerformItem(action, rows, index + 1);
    }
    else {
      // Refresh buttons
      gridItems_RefreshButtons();

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

  // -----------
  // Server-side
  // -----------
  // Update message
  widget.UI.Block("Actioning item " + (index + 1) + " of " + rows.length + ", please wait...");

  // Create Parameters (must include Summary Columns in addition to Action Parameters
  var item = data.DataView[rows[index]];
  var o = {};
  o.actionId = action.Id;
  o.summaryColumnsJson = JSON.stringify(data.DataView.GetSummaryColumns(rows[index]));
  o.parametersJson = action.ParametersJson;
  o.target = "WebInternal";
  o.highDpi = widget.IsHighDpi();

  // Extend JSON Parameters with any special on-the-fly parameters or file data (e.g., Flag Colour)
  var fileData;
  if (action.SpecialParams) {
    var p = JSON.parse(o.parametersJson);
    if (!p) p = {};
    p = $.extend({}, action.SpecialParams, p);
    o.parametersJson = JSON.stringify(p);
  }
  if (action.FileData) {
    fileData = action.FileData;
    action.FileData = null;
  }

  // Action row
  widget.UploadFiles("ExecuteRowAction", o, fileData,
    function (data) {
      gridItems_Action_PerformItem_Done(data, action, rows, index);

      // Process next
      if (index &lt; rows.length - 1) {
        gridItems_Action_PerformItem(action, rows, index + 1);
      }
      else {
        // Refresh buttons
        gridItems_RefreshButtons();

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

    function (error) {
      // Failed
      gridItems_Action_PerformItem_Failed(error, action, rows, index);

      // Process next
      if (index &lt; rows.length - 1) {
        gridItems_Action_PerformItem(action, rows, index + 1);
      }
      else {
        // Refresh buttons
        gridItems_RefreshButtons();

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

function gridItems_Action_PerformItem_Done(data, action, rows, index) {
  // Success
  C.gridItems.SetRowSelectorIcon(rows[index], "Check", "Item processed. Refresh grid to view updated details.");

  // Invalidate row preview
  if (mData.ShowSummary) {
    // Remove from cache
    C.wbItems.CacheRemove(mData.DataView.GetCacheKey(rows[index]));

    // Preview now?
    if (rows[index] === C.gridItems.ActiveDataRowIndex()) {
      wbItems_Preview();
    }
  }
}

function gridItems_Action_PerformItem_Failed(error, action, rows, index) {
  // Failed
  C.gridItems.SetRowSelectorIcon(rows[index], "Error", error);
}

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

  // Refresh Buttons
  gridItems_RefreshButtons();
}

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

function gridItems_RefreshButtons() {
  var actions = mData.Actions;
  if (!actions) return;

  // Get selected rows (including the active row if no selected rows but ignoring expired rows)
  var rows = C.gridItems.GetSelectedRowIndexes(true, true);

  // Disable/ Enable Actions
  for (var i = 0; i &lt; actions.length; i++) {
    var a = actions[i];

    if (!a.AllowMultiple &amp;&amp; rows.length &gt; 1) {
      // Doesn't allow multiple
      C.gridItems.Actions().SetEnabled(a.Id, false);
    }
    else {
      // Only enable actions available in ALL selected rows
      var enabled = (rows.length !== 0);

      if (a.Row &amp;&amp; mRowActionsColumnIndex !== -1) {
        for (var j = 0; j &lt; rows.length; j++) {
          var item = mData.DataView[rows[j]];
          var rowActions = item[mRowActionsColumnIndex];
          if (rowActions.indexOf(a.Mn) === -1) {
            enabled = false;
            break;
          }
        }
      }

      C.gridItems.Actions().SetEnabled(a.Id, enabled);
    }
  }

  C.gridItems.RefreshButtons();
}

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

  // Update cells
  for (var i = 0; i &lt; mData.Columns.length; i++) {
    // Initialise
    var c = mData.Columns[i];

    // Value
    var value = c.DataSourceIndex == -1 ? "?" : item[c.DataSourceIndex];

    // Special?
    switch (c.SpecialType) {
      case "ClientStatus":
        // Client Status
        var icon = "";
        var tooltip = "";

        if (item[i]) {
          switch (value) {
            case 0:
              break;

            case 5:
              icon = "ClientStatus_Excellent";
              tooltip = "Excellent";
              break;

            case 10:
              icon = "ClientStatus_Good";
              tooltip = "Good";
              break;

            case 20:
              icon = "ClientStatus_Caution";
              tooltip = "Caution";
              break;

            case 30:
              icon = "ClientStatus_Bad";
              tooltip = "Bad";
              break;

            case 40:
              icon = "ClientStatus_Adverse";
              tooltip = "Adverse";
              break;

            case 45:
              icon = "ClientStatus_Bankrupt";
              tooltip = "Bankrupt";
              break;
          }

          e.row.cells[c.Id].value = icon;
          e.row.cells[c.Id].tooltipText = tooltip;
        }
        break;

      case "ColourFlag":
        // Colour Flag
        if (item[i]) {
          e.row.cells[c.Id].value = "Flag[" + value + "]";
          e.row.cells[c.Id].tooltipText = value;
        }
        break;

      case "LogSeverityIcon":
        // Log Severity Icon
        e.row.cells[c.Id].value = mLogSeverities.GetHtmlIcon(value, true);
        break;

      default:
        e.row.cells[c.Id].value = value;
        break;
    }

    // Small
    if (c.Small) e.row.cells[c.Id].small = true;

    // Cell hyperlink
    if (c.FormKey) {
      // Form Key specified
      var id = value;
      var formKey = c.FormKey;

      // Resolve Form Key from another field
      if ($.isNumeric(formKey)) {
        var index = parseInt(formKey);
        formKey = item[index];
      }

      if (id) {
        e.row.cells[c.Id].hyperlink = "app://formshow?form=" + formKey + "&amp;id=" + encodeURI(id);
      }
    }
    else {
      // Automatic based on field name
      var recordType = null;
      if (c.Id.endsWith("ClientId")) {
        recordType = "Client";
      }
      else if (c.Id.endsWith("AccountId")) {
        recordType = "Account";
      }
      else if (c.Id.endsWith("AccountAppId")) {
        recordType = "AccountApp";
      }
      else if (c.Id.endsWith("WorkflowId")) {
        recordType = "Workflow";
      }
      if (recordType) {
        e.row.cells[c.Id].hyperlink = "app://formshow?form=" + recordType + "&amp;id=" + encodeURI(item[i]);
      }
    }
  }

}

function gridItems_Refresh() {

  // Add Columns
  C.gridItems.ClearColumns();

  for (var i = 0; i &lt; mData.Columns.length; i++) {
    var c = mData.Columns[i];

    // Width (convert from characters to ems - ignored by some date types)
    var w = "";
    if (c.Width &amp;&amp; c.Width !== -1) {
      w = c.Width + "em";
    }

    // Special
    if (c.Id === "RowActions") {
      mRowActionsColumnIndex = c.DataSourceIndex;
    }

    switch (c.DataType) {
      case "Drilldown":
        // Drilldown
        C.gridItems.AddColumnDrilldown("Drilldown", { drilldownHideIfBlank: true });
        break;

      case "Code":
      case "String":
        // Code and String
        if (c.DataType === "Code" &amp;&amp; !w) w = "6em";

        switch (c.SpecialType) {
          case "ColourBlock":
          case "ColourFlag":
            C.gridItems.AddColumnIcon(c.Id, { caption: c.Caption, visible: c.Visible, backgroundColour: c.BackgroundColour, foregroundColour: c.ForegroundColour, sortable: true });
            break;

          case "LogSeverityIcon":
            C.gridItems.AddColumnHtml(c.Id, { caption: c.Caption, align: "center", width: "16px", visible: c.Visible, backgroundColour: c.BackgroundColour, foregroundColour: c.ForegroundColour, sortable: true });
            break;

          default:
            C.gridItems.AddColumnString(c.Id, { caption: c.Caption, visible: c.Visible, width: w, backgroundColour: c.BackgroundColour, foregroundColour: c.ForegroundColour, sortable: true });
            break;
        }
        break;

      case "Currency":
        // Currency
        C.gridItems.AddColumnCurrency(c.Id, { caption: c.Caption, visible: c.Visible, width: w, backgroundColour: c.BackgroundColour, foregroundColour: c.ForegroundColour, sortable: true });
        break;

      case "Date":
        // Date
        C.gridItems.AddColumnDate(c.Id, { caption: c.Caption, visible: c.Visible, backgroundColour: c.BackgroundColour, foregroundColour: c.ForegroundColour, sortable: true });
        break;

      case "DateTime":
        // Date and Time
        C.gridItems.AddColumnDateTime(c.Id, { caption: c.Caption, visible: c.Visible, backgroundColour: c.BackgroundColour, foregroundColour: c.ForegroundColour, sortable: true });
        break;

      case "Integer":
        // Integer
        switch (c.SpecialType) {
          case "ClientStatus":
            C.gridItems.AddColumnIcon(c.Id, { caption: c.Caption, visible: c.Visible, backgroundColour: c.BackgroundColour, foregroundColour: c.ForegroundColour, sortable: true });
            break;

          default:
            C.gridItems.AddColumnInteger(c.Id, { caption: c.Caption, visible: c.Visible, width: w, backgroundColour: c.BackgroundColour, foregroundColour: c.ForegroundColour, sortable: true });
            break;
        }
        break;

      case "Hidden":
        // Hidden
        C.gridItems.AddColumnString(c.Id, { caption: c.Caption, visible: false });
        break;

      default:
        console.warn("Unhandled Smart List Column Date Type '" + c.DataType + "'.");
        C.gridItems.AddColumnString(c.Id, { caption: c.Caption, visible: c.Visible });
        break;
    }
  }

  // Actions
  var actions = [];
  actions.push({ actionId: "Refresh", tooltipText:"Refresh", icon: "Refresh" });
  if (mData.Actions.length != 0) {
    actions.push({});
    for (var i = 0; i &lt; mData.Actions.length; i++) {
      var a = mData.Actions[i];

      if (a.Row) {
        // Grid Action
        switch (a.ActionType) {
          case "RowRefreshNotification":
            // Notification
            // NOTE: Form_ExecuteActionNotification
            break;

          default:
            actions.push({ actionId: a.Id, caption: a.Caption, tooltipText: a.Description, icon: a.Icon });
            break;
        }
      }
      else {
        // Other Action
        window.alert("Non-grid-based Actions not yet supported.");
      }
    }
  }

/*
  if (!mRecord.ReadOnly) {
    if (mRecord.AllowAddLog || mRecord.AllowAddWorkflow) {
      actions.push({});
      if (mRecord.AllowAddLog) actions.push({ actionId: "LogAdd", icon: "Log|Add", tooltipText: "Add a Log" });
      if (mRecord.AllowAddWorkflow) actions.push({ actionId: "WorkflowAdd", icon: "Workflow|Add", tooltipText: "Create a new Workflow" });
    }

    actions.push({});
    actions.push({ actionId: "CompleteTask", icon: "Check", tooltipText: "Complete task" });
    actions.push({ actionId: "Postpone1D", icon: "Date_Plus1", tooltipText: "Move task forward by 1 day" });
    actions.push({ actionId: "Postpone1W", icon: "Date_Plus7", tooltipText: "Move task forward by 1 week" });
    actions.push({ actionId: "Postpone2W", icon: "Date_Plus14", tooltipText: "Move task forward by 2 weeks" });
    actions.push({ actionId: "Postpone1M", icon: "Date_PlusM", tooltipText: "Move task forward by 1 month" });
    actions.push({ actionId: "Postpone1Y", icon: "Date_PlusY", tooltipText: "Move task forward by 1 year" });

    actions.push({});
    actions.push({ actionId: "UserDelegate", icon: "User_Delegate", tooltipText: "Delegate task to User" });
    actions.push({ actionId: "UserUndelegate", icon: "User|Clear", tooltipText: "Clear delegated User" });
  }
*/
  C.gridItems.Actions().Define(actions);

  // Give the collection ability to supply an array of summary column values
  // NOTE: Required regardless of whether a Preview Panel is showing since this is also required for actioning rows
  mData.DataView.GetSummaryColumns = function (index) {
    var item = mData.DataView[index];
    var cols = widget.ArrayFromCsvString(mData.SummaryColumns.toUpperCase());
    var summaryColumns = [];

    for (var i = 0; i &lt; cols.length; i++) {
      for (var j = 0; j &lt; mData.Columns.length; j++) {
        if (mData.Columns[j].Id.toUpperCase() === cols[i]) {
          summaryColumns.push(item[mData.Columns[j].DataSourceIndex]);
          break;
        }
      }
    }

    return summaryColumns;
  };

  // Give collection ability to form a unique cache key and preview parameters for the Web Service
  mData.DataView.GetCacheKey = function (index) {
    if (mData &amp;&amp; mData.DataView &amp;&amp; mData.DataView.GetSummaryColumns) {
      return JSON.stringify(mData.DataView.GetSummaryColumns(index));
    }
    else {
      // Just in case!
      return "";
    }
  };

  // Show Preview Panel?
  // NOTE: Do not use jQuery show and hide since these remove the 'flex' layout
  if (mData.ShowSummary) {
    C.divSummary.css("display", "flex");
  }
  else {
    C.divSummary.css("display", "none");
  }

  // Give collection ability to return details needed to fetch a preview
  mData.DataView.GetPreviewFetchParameters = function (index) {
    var o = {};
    if (index !== -1) {
      var item = mData.DataView[index];

      o.summaryColumnsJson = JSON.stringify(mData.DataView.GetSummaryColumns(index));
      o.target = "WebInternal";
      //o.highDpi = $Runtime.IsHighDpi();
    }
    return o;
  };

  // Refresh
  C.gridItems.VirtualDataRefresh(mData.DataView);

//  // 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 (mSelectedRowUniqueIds.length != 0) {
//    var indexes = [];
//
//    for (var i = 0; i &lt; mRecord_Items.length; i++) {
//      if (mSelectedRowUniqueIds.includes(mRecord_Items[i].UniqueId)) {
//        indexes.push(i);
//      }
//    }
//
//    C.gridItems.SetSelectedRowIndexes(indexes);
//    mSelectedRowUniqueIds = [];
//  }

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

// =======
// wbItems
// =======
function wbItems_Preview() {
  C.wbItems.PreviewFromGridCollection(C.gridItems, mData.DataView, "GetRowSummary");
}

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);
  }
  else {
    widget.ExecuteApplicationShortcutUrl(applicationShortcutUrl);
  }
}
&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>a6xyJRC7dk60az75--uw7Q</UniqueId>
    <AllowRefresh>true</AllowRefresh>
    <Caption />
    <HtmlWidgetMaxHeight>0</HtmlWidgetMaxHeight>
    <HtmlWidgetMaxWidth>1200</HtmlWidgetMaxWidth>
    <HtmlWidgetNeverApplyStyling>false</HtmlWidgetNeverApplyStyling>
    <HtmlWidgetResourceChartsApex>false</HtmlWidgetResourceChartsApex>
    <HtmlWidgetResourceCssSummaryPage2>false</HtmlWidgetResourceCssSummaryPage2>
    <HtmlWidgetResourceCssWidget>true</HtmlWidgetResourceCssWidget>
    <HtmlWidgetResourceJQuery>true</HtmlWidgetResourceJQuery>
    <HtmlWidgetResourceJQueryVersion />
    <HtmlWidgetSpecialEventGetFolderCount>false</HtmlWidgetSpecialEventGetFolderCount>
    <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="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>0</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="SmartListId" 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.SmartLists</List>
            <LimitToList>false</LimitToList>
            <MaxLength>50</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="SmartListStartupParametersJson" type="Text">
            <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>
            <MaxLength>0</MaxLength>
            <Rows>8</Rows>
          </Parameter>
          <Parameter name="SmartListColumns" type="Text">
            <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>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="SmartListAllowParametersCustomise" type="Boolean">
            <BlankTip />
            <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>False</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="SmartListParametersUserCustomisationJson" type="Text">
            <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>
            <MaxLength>0</MaxLength>
            <Rows>8</Rows>
          </Parameter>
        </Parameters>
      </ISParameterDefs>
    </Parameters>
  </finScript>