<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2022-05-10T23:37:17.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2017-08-10T02:39:42.9100000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2022-05-10T23:36:26.6600000</UpdatedUtcDate>
    <ScriptId>XACC</ScriptId>
    <Description>Accounts Widget</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Category />
    <Code>' HtmlWidget_Accounts
Option Explicit On
Option Strict On

' #################################################################
' Accounts HTML Widget
'
' Version: 2.02 (11/05/2022)
'
' Usage: System-defined HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    2.01  09/01/2018  ISS                Updated
'    2.02  11/05/2022  ISS      J028712   Removed obsoleted Functions
' #################################################################

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

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)

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

    Case "GetRecords"
      ' Get Records
      Main = GetRecords(returnValue)

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

End Function

Private Function GetPage() As String

  Dim AlwaysShowTabCaptions As Boolean
  Dim Html As String
  Dim List As ISList
  Dim n As Integer
  Dim PagesJson As String
  Dim s As String

  ' Initialise
  Html = ScriptInfo.TemplateText

  ' Get Parameters
  AlwaysShowTabCaptions = mCombinedParameters.GetBoolean("AlwaysShowTabCaptions")

  ' Pages Configuration
  PagesJson = "["

  List = mStartupParameters.GetList("Pages", "", "|")
  If List.Count = 0 Then List.FromDelimitedString("Bookmarked|Recent|Review")
  For Each s In List
    n = instr(s, ";")
    If n &lt;&gt; 0 Then s = Left(s, n - 1)

    Select Case UCase(s)
      Case "ALL"
        If AlwaysShowTabCaptions Then
          PagesJson &amp;= "{ tabId: 'All', caption: 'All' },"
        Else
          PagesJson &amp;= "{ tabId: 'All', caption: 'All' },"
        End If

      Case "BOOKMARKED"
        If AlwaysShowTabCaptions Then
          PagesJson &amp;= "{ tabId: 'Bookmarked', caption: 'Bookmarked' },"
        Else
          PagesJson &amp;= "{ tabId: 'Bookmarked', caption: 'Bookmarked', symbol: 'Bookmark' },"
        End If

      Case "RECENT"
        If AlwaysShowTabCaptions Then
          PagesJson &amp;= "{ tabId: 'Recent', caption: 'Recent' },"
        Else
          PagesJson &amp;= "{ tabId: 'Recent', caption: 'Recent', symbol: 'Recent' },"
        End If

      Case "REVIEW"
        PagesJson &amp;= "{ tabId: 'Review', caption: 'Review' },"
    End Select
  Next

  PagesJson &amp;= "]"

  Html = replace(Html, "&lt;%[Pages]%&gt;", PagesJson)

  Return Html

End Function

Private Function GetRecords(ByRef returnValue As String) As Boolean

  Dim Page As String
  Dim Records As New List(Of Record)
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

  ' Get Records
  Select Case UCase(page)
    Case "ALL"
      Success = GetRecords_All(Records)

    Case "BOOKMARKED"
      Success = GetRecords_Bookmarked(Records)

    Case "REVIEW"
      Success = GetRecords_Review(Records)

    Case "RECENT"
      Success = GetRecords_Recent(Records)

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

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

  Return Success

End Function

Private Function GetRecords_All(ByRef records As List(Of Record)) As Boolean

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

  ' Assume Success
  Success = True

  ' Initialise
  sqb = finBL.Database.CreateSelectQueryBuilder()
  With sqb
      .Table = "Account"
      .TopLimit = 101
      .Fields.AddList("AccountId,Name,Status")

      With .SqlWhere
        .AppendComparisonNull("DateClosed")

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

      .OrderByFields.Add("AccountId")
  End With

  ' Get Records
  If sqb.ExecuteDisconnectedDataReader(dr) Then
    Do While dr.Read()
      records.Add(New Record(finBL.Database.GetFieldString(dr!AccountId),
                             finBL.Database.GetFieldString(dr!Name),
                             Nothing,
                             finBL.Enums.isefinAccountStatus_FromIntToString(finBL.Database.GetFieldInteger(dr!Status))))
    Loop
    finBL.Database.DataReaderClose(dr)
  Else
    Success = False
  End If

  ' Limit to a maximum of 100 Accounts?
  If Success AndAlso records.Count &gt; 100 Then
    records.Clear()
    records.Add(New Record("~", "More than 100 Accounts available. Use 'Search' to locate Accounts.", Nothing, ""))
  End If

  Return Success

End Function

Private Function GetRecords_Bookmarked(ByRef records As List(Of Record)) As Boolean

  Dim RecordList As ISRecordList
  Dim RecordListItem As ISRecordListItem
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Get Bookmarks
  If finBL.TaskManagerFunctions.UserBookmarkedRecordsListLoad(RecordList, True, "Account") Then
    ' Add Records
    For Each RecordListItem In RecordList
      With RecordListItem
        records.Add(New Record(.Id, .Description))
      End With
    Next
  Else
    Success = False
  End If

  Return Success

End Function

Private Function GetRecords_Recent(ByRef records As List(Of Record)) As Boolean

  Dim RecordList As ISRecordList
  Dim RecordListItem As ISRecordListItem
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Get Bookmarks
  If finBL.WebServiceFunctions.UserRecentlyViewedRecordsListLoad(RecordList, True, "Account") Then
    ' Add Records
    For Each RecordListItem In RecordList
      With RecordListItem
        records.Add(New Record(.Id, .Description))
      End With
    Next
  Else
    Success = False
  End If

  Return Success

End Function

Private Function GetRecords_Review(ByRef records As List(Of Record)) As Boolean

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

  ' Assume Success
  Success = True

  ' Initialise
  sqb = finBL.Database.CreateSelectQueryBuilder()
  With sqb
      .Table = "Account"
      .Fields.AddList("AccountId,Name,DateReview,Status")

      With .SqlWhere
        .AppendComparisonInteger("AccountManagerUserPk", "=", finBL.CurrentUserInformation.UserPk)
        .AppendComparisonNotNull("DateReview")
        .AppendComparisonDate("DateReview", "&lt;=", finBL.TimeZoneFunctions.GetCurrentUserDate())

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

      .OrderByFields.Add("DateReview")
  End With

  ' Get Records
  If sqb.ExecuteDisconnectedDataReader(dr) Then
    Do While dr.Read()
      records.Add(New Record(finBL.Database.GetFieldString(dr!AccountId),
                             finBL.Database.GetFieldString(dr!Name),
                             finBL.Database.GetFieldDate(dr!DateReview),
                             finBL.Enums.isefinAccountStatus_FromIntToString(finBL.Database.GetFieldInteger(dr!Status))))
    Loop
    finBL.Database.DataReaderClose(dr)
  Else
    Success = False
  End If

  Return Success

End Function


Public Class Record

  Public Code As String
  Public DateReview As Date
  Public Description As String
  Public Status As String

  Public Sub New(code As String,
                 description As String,
                 Optional dateReview As Date = Nothing,
                 Optional status As String = "")

    With Me
      .Code = code
      .Description = description
      .DateReview = dateReview
      .Status = status
    End With

  End Sub

End Class</Code>
    <Language>VisualBasic</Language>
    <Notes>System defined HTML Widget to show details of a User's Accounts.</Notes>
    <PermissionKeyExecute />
    <RunWithoutPrompts>false</RunWithoutPrompts>
    <TemplateText>&lt;div class="is-widget-content is-widget-form is-summarypage-2"&gt;

  &lt;!-- Form Header --&gt;
  &lt;div class="is-widget-form-header"&gt;
    &lt;!-- Tabs --&gt;
    &lt;div id="tabDetails" class="is-tabs"&gt;
    &lt;/div&gt;
  &lt;/div&gt;


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

&lt;/div&gt;



&lt;script&gt;
// Server-side information
var mTabs = &lt;%[Pages]%&gt;;

// Other
var mResults = {};

// Tabs
var tabDetails;

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

  // Dynamically create Tabs and Pages
  tabDetails.RefreshFromArray(mTabs);

  // Handle Notifications
  widget.ActionNotificationHandle(Widget_NotificationHandler);

  // Handle Reset
  widget.ResetHandle(Widget_ResetHandler);

  // Refresh
  RefreshCurrentPage(true);
});

// ====================
// Refresh Current Page
// ====================
function RefreshCurrentPage(forceRefresh) {
  // Initialise
  var page = tabDetails.SelectedTabId();

  // Force Refresh?
  if (forceRefresh) mResults[page] = undefined;

  // Requires Refresh?
  if (mResults[page] != undefined) return;

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

  // Create parameters
  var params = { page: page };

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

function RefreshCurrentPage_Done(data, page) {
  // Parse
  mResults[page] = JSON.parse(data);

  // Get Tab
  var tab = tabDetails.Tabs(page);

  // Get/ Create Grid
  var grid = tab.grid;
  if (!grid) {
    // Show Column Headers?
    var showColumnHeaders = true;
    switch(page.toUpperCase()) {
      case "BOOKMARKED":
      case "RECENT":
        showColumnHeaders = false;
        break;
    }

    // Add grid
    var e = $("&lt;div style='width:100%'&gt;&lt;/div&gt;");
    tab.pageElement.append(e);
    grid = widget.UI.Grid(e, {
      showColumnHeaders: showColumnHeaders,
      style: "",
      stickyHeader: true,
      onInitialiseRow: function(e) { Grid_InitialiseRow(page, e); },
    });
    grid.AddColumnCode("Code", { caption: "Account", sortable: true });
    grid.AddColumnString("Description", { caption: "Name", sortable: true });
    switch(page.toUpperCase()) {
      case "ALL":
        // All
        grid.AddColumnString("Status", { caption: "Status", width:"10em", sortable: true });
        break;

      case "REVIEW":
        // Review
        grid.AddColumnString("Status", { caption: "Status", width:"10em", sortable: true });
        grid.AddColumnDate("DateReview", { caption: "Review", sortable: true });
        break;
    }

    // Cache grid
    tab.grid = grid;
  }

  // Warning?
  if (mResults[page].length == 1 &amp;&amp; mResults[page][0].Code == "~") {
    grid.Visible(false);
    window.alert(mResults[page][0].Description);
  }
  else {
    // Refresh Grid
    grid.Visible(true);
    grid.VirtualDataRefresh(mResults[page]);
  }

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

function RefreshCurrentPage_Fail(data, page) {
  widget.UI.MsgBoxAlert(data);

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

function Grid_InitialiseRow(page, e) {
  var item = mResults[page][e.row.listIndex];

  e.row.cells.Code.value = item.Code;
  e.row.cells.Description.value = item.Description;
  if (e.row.cells.DateReview) e.row.cells.DateReview.value = item.DateReview;
  if (e.row.cells.Status) e.row.cells.Status.value = item.Status;

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

// =============
// Reset Handler
// =============
function Widget_ResetHandler() {
  // Clear Results
  mResults = {};

  // Refresh
  RefreshCurrentPage(true);
}

// ====================
// Notification Handler
// ====================
function Widget_NotificationHandler(actionId, data) {
  switch(actionId) {
    case "BookmarkAdded":
    case "BookmarkDeleted":
    case "RecordViewed":
      if (data &amp;&amp; data.type == "Account") {
        widget.ResetScheduled(true, 5);
      }
      break;
  }
}
&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>sAHLTXr3I0iGNy+cfi8nBA</UniqueId>
    <AllowRefresh>true</AllowRefresh>
    <Caption>Accounts</Caption>
    <HtmlWidgetMaxHeight>0</HtmlWidgetMaxHeight>
    <HtmlWidgetMaxWidth>0</HtmlWidgetMaxWidth>
    <HtmlWidgetNeverApplyStyling>false</HtmlWidgetNeverApplyStyling>
    <HtmlWidgetResourceCssSummaryPage2>true</HtmlWidgetResourceCssSummaryPage2>
    <HtmlWidgetResourceCssWidget>true</HtmlWidgetResourceCssWidget>
    <HtmlWidgetResourceJQuery>true</HtmlWidgetResourceJQuery>
    <HtmlWidgetResourceJQueryVersion />
    <HtmlWidgetSpecialEventGetFolderCount>false</HtmlWidgetSpecialEventGetFolderCount>
    <Icon />
    <RestrictedOriginsListEnabled>false</RestrictedOriginsListEnabled>
    <RunAsAdministrator>false</RunAsAdministrator>
    <WebServiceName />
    <WebServiceAllowAnonymous>false</WebServiceAllowAnonymous>
    <WebServiceSendDebugInformation>false</WebServiceSendDebugInformation>
    <ShowInMenu>None</ShowInMenu>
    <ParametersType>Custom</ParametersType>
    <Parameters>
      <ISParameterDefs version="1.00">
        <Parameters>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>Options.</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="AlwaysShowTabCaptions" type="Boolean">
            <BlankTip />
            <Caption>Always show Tab captions (instead of icons)?</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="" type="SectionStart">
            <BlankTip />
            <Caption>Optionally, customise Pages to show.</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="Pages" type="GroupingList">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <List>Bookmarked,Recent,Review,All</List>
            <GroupingListShowPageBreakButton>false</GroupingListShowPageBreakButton>
            <NoIndent>true</NoIndent>
          </Parameter>
        </Parameters>
      </ISParameterDefs>
    </Parameters>
  </finScript>