<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2024-07-09T01:55:50.0000000">
    <CreatedUserId>Admin</CreatedUserId>
    <CreatedUtcDate>2023-09-14T03:30:24.7980000</CreatedUtcDate>
    <UpdatedUserId>Admin</UpdatedUserId>
    <UpdatedUtcDate>2024-07-09T01:53:17.1570000</UpdatedUtcDate>
    <ScriptId>UAR</ScriptId>
    <Description>User Audit Report</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_UserAuditReport
Option Explicit On
Option Strict On

' #################################################################
' User Audit Report HTML Widget
'
' Version: 1.03 (09/07/2024)
'
' NOTE: Uses Web Services Background Processes but can also work 
'       from desktop without Web Services
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.00  11/10/2023  ISS      J031165   Created
'    1.01  26/10/2023  ISS      J032291   Added FORM_KEY &amp; permission check
'          31/10/2023  ISS      J031165   Added date range checks 
'    1.02  15/04/2024  ISS      J033255   Corrected casing in text prompts
'    1.03  09/07/2024  ISS      J033676   Fixed incorrect use of UTC dates
' #################################################################

' Constants
Private Const FORM_KEY As String = "UserAuditReport"

Private Const BackgroundColour_DeletedRow As String = "#FCF0F0"
Private Const BackgroundColour_Highlight As String = "#FAFF98"
Private Const BackgroundColour_InactiveRow As String = "#E8E8E8"
Private Const Highlight_CreatedDates As Boolean = True
Private Const Highlight_InactiveDates As Boolean = True
Private Const Highlight_DeletedDates As Boolean = True
Private Const Highlight_NeverLoggedIn As Boolean = True
Private Const Highlight_PasswordExpired As Boolean = True

' Common Parameters

' Objects
Private mCombinedParameters As ISKeyValueList
Private mExcelWorkbook As ISExcelWorkbook
Private mParameters As ISKeyValueList
Private mStartupParameters As ISKeyValueList
Private mUserItems As New List(Of UserItem)

' Properties
Private mDateAsAt As Date
Private mDesktopMode As Boolean
Private mExcludeNonHighlighted As Boolean
Private mFromDate As Date
Private mHighlightDateRange As Boolean
Private mIncludeActive As Boolean
Private mIncludeInactive As Boolean
Private mIncludeDeleted As Boolean
Private mNumberFormat_DateTime As String
Private mNumberFormat_Integer As String 
Private mProcessStatus As finHtmlWidgetBackgroundProcessStatus
Private mToDate As Date

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)

  ' Get Common Parameters
  With mCombinedParameters
    mDesktopMode = .GetBoolean("DesktopMode")
  End With
  
  ' Properties
  mNumberFormat_DateTime = finBL.DateFormatLong() &amp; " HH:mm"
  mNumberFormat_Integer = "#,##0"
  
  ' Validate
  Main = finBL.HtmlWidgetUtilities.HasPermissionToViewFormKey(FORM_KEY)
 
  If Main Then
    ' Handle Events
    Select Case eventId
      Case ""
        ' Main event, i.e., return initial HTML content (excluding html and body tags)
        returnValue = ScriptInfo.TemplateText
        
      Case "BackgroundProcess.Execute"
        '-----------------------------------------------------------------
        ' Called by Web Services to execute a Background Process that was 
        ' initially queued In the Widget's UI via the Finish event.
        '-----------------------------------------------------------------
        Main = BackgroundProcess_Execute(returnValue)
  
      Case "CancelBackgroundProcess"
        ' Cancel a Process
        Main = CancelBackgroundProcess(returnValue)
  
      Case "Finish"
        ' Finish
        Main = Finish(parametersJson, startupParametersJson, requestInfo, returnValue)
  
      Case "GetBackgroundProcessStatus"
        ' Get Background Process Status
        Main = GetBackgroundProcessStatus(returnValue)
  
      Case "GetCurrentProcesses"
        ' Get Current Processes
        Main = GetCurrentProcesses(returnValue)
  
      Case "GetInitialisationInfo"
        ' Get Initialisation Information required for this wizard
        Main = GetInitialisationInfo(returnValue)
  
      Case "WizardValidate"
        ' Validate wizard page
        Main = WizardValidate(parametersJson, returnValue)
  
      Case Else
        finBL.Error.ErrorBeginFormat("Unhandled event '{0}'.", eventId)
        Main = False
    End Select
  End If
End Function

''' &lt;summary&gt;
'''  Request that a Background Process is Cancelled.
''' &lt;/summary&gt;
Private Function CancelBackgroundProcess(ByRef returnValue As String) As Boolean

  Dim ProcessId As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Get Parameters
  ProcessId = mCombinedParameters.GetString("ProcessId")

  ' Request Cancel
  Success = finBL.HtmlWidgetUtilities.CancelBackgroundProcess(processId)

  Return Success

End Function

''' &lt;summary&gt;
'''  Run Background Process (Queued and run via Web Services).
''' &lt;/summary&gt;
Private Function Finish(parametersJson As String,
                        startupParametersJson As String,
                        requestInfo As finScriptRequestInfo,
                        ByRef returnValue As String) As Boolean

  Dim CompleteMessage As String
  Dim Data As Object
  Dim obj As Object
  Dim ProcessId As String
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

  ' Parse Parameters
  ' NOTE: Only required for validation purposes
  If finBL.Runtime.WebUtilities.DeserialiseJsonStringToObject(parametersJson, GetType(WizardFinishParameters), obj) Then
    WizardFinishParameters = DirectCast(obj, WizardFinishParameters)
  Else
    Success = False
  End If

  ' Validate
  If Success Then
    ' Not required
  End If
  
  ' Start Background Process
  If Success Then
    ' NOTE: If mDesktopMode is True then the desktop User Interface will handle this rather than Web Services Background Processes
    Success = finBL.HtmlWidgetUtilities.QueueBackgroundProcess_HtmlWidgetScript(ScriptInfo.ScriptId, parametersJson, startupParametersJson, ProcessId, mDesktopMode)    
  End If

  ' Context-specific functionality
  If Success Then
    If mDesktopMode Then
      CompleteMessage = "Once complete, the file can be downloaded to this computer."
    Else
      CompleteMessage = "Once complete, the file can be downloaded from the ""Downloads"" tab on the ""Processes &amp; Procedures"" page."
    End If
    If finBL.CloudConnectFunctions.CloudConnectSettings.ProcessBackgroundEmailUserOnFinish AndAlso Len(finBL.CurrentUserInformation.Email) &lt;&gt; 0 Then
      CompleteMessage &amp;= vbNewLine &amp; vbNewLine
      If finBL.Settings.CostCentreForceTestMode Then
        CompleteMessage &amp;= "WARNING: The file will not be emailed to you since Test mode is currently enforced."
      Else
        CompleteMessage &amp;= "The file will also be emailed to you at '" &amp; finBL.CurrentUserInformation.Email &amp; "'."
      End If
    End If
  End If
  
  ' Process Id
  If Success Then
    Data = New With {
      .ProcessId = ProcessId,
      .CompleteMessage = CompleteMessage,
      .DesktopMode = mDesktopMode
    }
  End If

  ' Finalise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(Data, returnValue)
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Background Process Status.
''' &lt;/summary&gt;
Private Function GetBackgroundProcessStatus(ByRef returnValue As String) As Boolean

  Dim LastEventId As String
  Dim ProcessId As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

  ' Get Background Processes Status including Events
  Success = finBL.HtmlWidgetUtilities.GetBackgroundProcessStatusIncludingEventsJson(processId, lastEventId, returnValue)

  Return Success

End Function

''' &lt;summary&gt;
'''  Get current and recent Background Processes that for this User (these  are also returned in GetInitialisationInfo).
''' &lt;/summary&gt;
Private Function GetCurrentProcesses(ByRef returnValue As String) As Boolean

  Dim ProcessStatuses As List(Of finHtmlWidgetUtilities.JsonProcessStatusInformation)
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Get current and recent Background Processes that for this User
  Success = finBL.HtmlWidgetUtilities.GetBackgroundProcessesJson_HtmlWidgetScript(ScriptInfo.ScriptId, True, ProcessStatuses)

  ' Response
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(ProcessStatuses, returnValue)
  End If

  Return Success

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 ProcessStatuses As List(Of finHtmlWidgetUtilities.JsonProcessStatusInformation)
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Validate
  
  ' Get Info
  If Success Then
    ' Form Initialisation Info
    If Success Then
      FormInitialisationInfo = New FormInitialisationInfo()
      With FormInitialisationInfo
        ' General
        ' Default start date: beginning of current year
        .FromDate =  finBLShared.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(New DateTime(finBLShared.TimeZoneFunctions.GetCurrentDatabaseDate().Year, 1, 1))
        .ToDate = finBLShared.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(finBLShared.TimeZoneFunctions.GetCurrentDatabaseDate())
        
        ' Configuration
        .DesktopMode = mDesktopMode
        .PromptOnCommit = finBL.CloudConnectFunctions.CloudConnectSettings.PromptOnCommit
        .ReadOnly = finBL.Database.IsReadOnly
      End With

      ' Get current and recent Background Processes for this User
      If finBL.HtmlWidgetUtilities.GetBackgroundProcessesJson_HtmlWidgetScript(ScriptInfo.ScriptId, True, ProcessStatuses) Then
        FormInitialisationInfo.CurrentProcesses = ProcessStatuses
      Else
        Success = False
      End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Validate wizard.
''' &lt;/summary&gt;
Private Function WizardValidate(parametersJson As String,
                                ByRef returnValue As String) As Boolean

  Dim ConfirmList As New List(Of String)
  Dim Data As Object
  Dim FailedControlId As String
  Dim FailedMessage As String
  Dim obj As Object
  Dim PageId As String
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

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

  ' Parse Parameters
  If finBL.Runtime.WebUtilities.DeserialiseJsonStringToObject(parametersJson, GetType(WizardFinishParameters), obj) Then
    WizardFinishParameters = DirectCast(obj, WizardFinishParameters)
  Else
    Success = False
  End If

  ' Validate
  If Success Then
    Select Case PageId
    End Select
  End If

  ' Serialise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(New WizardValidateResponse(Data, FailedMessage, FailedControlId), returnValue)
  End If

  Return Success

End Function


'==========================================================================
' Generate report: BackgroundProcess_Execute and supporting methods follow
'==========================================================================
''' &lt;summary&gt;
'''  Run the background task.
''' &lt;/summary&gt;
Private Function BackgroundProcess_Execute(ByRef returnValue As String) As Boolean
  
  Dim Cancelled As Boolean
  Dim FileExportPackageHandler As finwsFileExportPackageHandler    
  Dim obj As Object
  Dim ReportFileName As String
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters
  
  ' Assume Success
  Success = True

  '---------------------------------------------------
  ' Initialise
  '---------------------------------------------------
  ' Get Background Process
  ' NOTE: This is required to add events and to check to see if the User has attempted to cancel this process (if supported)
  mProcessStatus = DirectCast(ScriptInfo.ContextData.GetObject("ProcessStatus"), finHtmlWidgetBackgroundProcessStatus)

  ' Parse Parameters
  If finBL.Runtime.WebUtilities.DeserialiseJsonStringToObject(mParameters.ToSimpleJsonString(), GetType(WizardFinishParameters), obj) Then
    WizardFinishParameters = DirectCast(obj, WizardFinishParameters)
  Else
    Success = False
  End If
  
  If Success Then
    ' Get Parameters
    mIncludeActive = WizardFinishParameters.IncludeActive
    mIncludeInactive = WizardFinishParameters.IncludeInactive
    mIncludeDeleted = WizardFinishParameters.IncludeDeleted
    mFromDate = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(WizardFinishParameters.FromDate.Date)
    mToDate = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(WizardFinishParameters.ToDate.Date)
    mHighlightDateRange = WizardFinishParameters.HighlightDateRange
    mExcludeNonHighlighted = WizardFinishParameters.ExcludeNonHighlighted
    
    ' Initialise
    mDateAsAt = finBLShared.TimeZoneFunctions.GetCurrentUtcDateTime()
  End If
  
  '---------------------
  ' Get the report data 
  '---------------------
  ' Notify
  If Success Then
    mProcessStatus.AddEvent_Information("Starting Report", String.Format("From {0} to {1}", finBL.FormatDateLong(mFromDate), finBL.FormatDateLong(mToDate)))
  End If
  
  ' Get the report data
  If Success AndAlso Not Cancelled Then
    mProcessStatus.AddEvent_Information("Reading User data.")
    Success = ReadUserAuditData(Cancelled, WizardFinishParameters)
  End If

  '--------------------------
  ' Write the Excel workbook 
  '--------------------------
  ' Create the Workbook
  If Success AndAlso Not Cancelled Then
    mProcessStatus.AddEvent_Information("Creating workbook.")
    Success = CreateWorkbook(Cancelled)
  End If

  '-----------------------------------------
  ' Attach the workbook file to the process
  '-----------------------------------------
  If Success AndAlso Not Cancelled Then
    mProcessStatus.AddEvent_Information("Writing report file")

    ' Create Export Package
    Success = finBL.HtmlWidgetUtilities.CreateProcessFileExportPackageHandler(ScriptInfo.ScriptCaption, ScriptInfo.ScriptId, FileExportPackageHandler)
    
    ' Create a File Name for the Package
    If Success Then
      FileExportPackageHandler.CreateFileName(String.Format("UserAuditReport_{0}.xlsx", finBL.TimeZoneFunctions.GetCurrentDatabaseDateTime().ToString("yyyyMMdd_HHmmss")))
      ReportFileName = FileExportPackageHandler.GetFullFileName(0)
      
      ' Save the Workbook
      mExcelWorkbook.Save(ReportFileName)
    End If
    
    ' Update Package Status
    If Success Then
      FileExportPackageHandler.StatusUpdateInProgress(0)
    End If
    
    ' Finalise
    If Success Then
      If FileExportPackageHandler.StatusUpdateComplete(mDesktopMode) Then
        ' Desktop finalise has removed the "Package_" prefix from the file names
        If mDesktopMode Then
          reportFileName = FileExportPackageHandler.GetShortFileName(0)        
        End If
      Else
        Success = False
      End If
    ElseIf FileExportPackageHandler IsNot Nothing Then
      Success = FileExportPackageHandler.StatusUpdateFailed()
    End If
  
    ' The generated report file has been saved to Downloads but, we can also attach it to any Success email
    If Success AndAlso Not Cancelled Then
      mProcessStatus.Attachments.Add(ReportFileName)
      
      ' Log location if in Desktop Mode so finPOWER Connect can prompt the User to open the file
      If mDesktopMode Then
        mProcessStatus.AddEvent_Information("Saved to " &amp; ReportFileName)
        mProcessStatus.OtherDetails.SetString("ReportFileName", ReportFileName)
      End If
    End If
  End If
  
  Return Success  
  
End Function

''' &lt;summary&gt;
''' Get user information from database and set flags
''' &lt;/summary&gt;
Private Function ReadUserAuditData(ByRef cancelled As Boolean,
                                   parameters As WizardFinishParameters) As Boolean

  Dim Include As Boolean
  Dim Success As Boolean
  Dim UserItem As UserItem
  Dim User As finUser
  Dim UserRO As finUserRO
  
  ' Assume success  
  Success = True
  
  ' Create Objects
  User = finBL.CreateUser()
  
  For Each UserRO In finBL.Users
    If UserRO.Deleted Then
      Include = mIncludeDeleted
    ElseIf Not UserRO.Active Then
      Include = mIncludeInactive
    Else
      Include = mIncludeActive
    End If 
    
    If Include Then
      UserItem = New UserItem()
      UserItem.UserId = UserRO.UserId
      UserItem.Name = UserRO.Name
      UserItem.UserPolicyId = UserRO.UserPolicyId
      UserItem.UserGroupId = UserRO.UserGroupId
      UserItem.Active = UserRO.Active
      UserItem.Deleted = UserRO.Deleted
      UserItem.EmailAddress = UserRO.Email
      
      If User.Load(UserRO.UserId) Then
        UserItem.CreatedUtcDate = User.CreatedUtcDate
        UserItem.LastLoginUtcDate = User.LastLoginUtcDate
        UserItem.UpdatedUtcDate = User.UpdatedUtcDate
        If UserItem.LastLoginUtcDate = Nothing Then
          UserItem.DaysSinceLastLogin = Nothing
          UserItem.DaysNeverLoggedIn = DaysSince(UserItem.CreatedUtcDate)
        Else
          UserItem.DaysSinceLastLogin = DaysSince(UserItem.LastLoginUtcDate)
          UserItem.DaysNeverLoggedIn = Nothing
        End If
        
        If Not UserItem.Active AndAlso Not UserRO.Deleted Then
          UserItem.InactiveUtcDate = User.InactiveUtcDate
        Else
          UserItem.InactiveUtcDate = Nothing
        End If 
        
        If UserItem.Active Then
          UserItem.PasswordUtcDate = User.PasswordUtcDate
          UserItem.DaysSincePasswordChange = DaysSince(UserItem.PasswordUtcDate)
          UserItem.PasswordExpiryUtcDate = User.PasswordExpiryUtcDate
          If UserItem.PasswordExpiryUtcDate = Nothing OrElse UserItem.PasswordExpiryUtcDate &gt;= mDateAsAt Then
            UserItem.DaysSincePasswordExpiry = Nothing
          Else
            UserItem.DaysSincePasswordExpiry = DaysSince(UserItem.PasswordExpiryUtcDate)
          End If
          UserItem.DeletedUtcDate = Nothing
        Else 
          ' Inactive or Deleted
          UserItem.PasswordUtcDate = Nothing
          UserItem.DaysSincePasswordChange = Nothing
          UserItem.PasswordExpiryUtcDate = Nothing
          UserItem.DaysSincePasswordExpiry = Nothing
          If UserItem.Deleted Then
            UserItem.DeletedUtcDate = User.DeletedUtcDate
          Else
            UserItem.DeletedUtcDate = Nothing
          End If
        End If    
      Else
        UserItem.Message = "Failed to load User object."
      End If
      
      ' Check if User has had notable activity and set formatting flags
      UserItem.FlagCreatedDate = parameters.HighlightDateRange AndAlso Highlight_CreatedDates AndAlso InRange(UserItem.CreatedUtcDate)
      UserItem.FlagInactiveDate = parameters.HighlightDateRange AndAlso Highlight_InactiveDates AndAlso Not UserItem.Active AndAlso Not UserItem.Deleted AndAlso InRange(UserItem.InactiveUtcDate)
      UserItem.FlagDeletedDate = parameters.HighlightDateRange AndAlso Highlight_DeletedDates AndAlso UserItem.Deleted AndAlso InRange(UserItem.DeletedUtcDate)
      If UserItem.Active AndAlso Not UserItem.Deleted Then
        UserItem.FlagLastLoginDate = parameters.HighlightDateRange AndAlso Highlight_NeverLoggedIn AndAlso UserItem.LastLoginUtcDate = Nothing
        UserItem.FlagPasswordExpiryDate = parameters.HighlightDateRange AndAlso Highlight_PasswordExpired AndAlso UserItem.PasswordExpiryUtcDate &lt;&gt; Nothing AndAlso UserItem.PasswordExpiryUtcDate &lt; mDateAsAt
      End If
    
      ' Exclude Users not flagged if ExcludeNonHighlighted parameter is true
      If mExcludeNonHighlighted Then      
        Include = UserItem.IsFlagged
      End If
      
      ' Add item to report data collection
      If Include Then
        mUserItems.Add(UserItem)
      End If
    End If
  Next

  Return Success

End Function

''' &lt;summary&gt;
''' Create an Excel workbook, and write the report data to a worksheet
''' &lt;/summary&gt;
Private Function CreateWorkbook(ByRef cancelled As Boolean) As Boolean

  Dim Success As Boolean
    
  ' Assume success
  Success = True
  
  ' Create the Excel workbook
  mExcelWorkbook = finBL.CreateExcelWorkbook()
  If mExcelWorkbook Is Nothing Then
    Success = False
  End If

  ' Create User Audit Report Worksheet
  If Success Then
    CreateWorksheetAuditReport(cancelled)
  End If
  
  Return Success

End Function

''' &lt;summary&gt;
''' Create a worksheet in the workbook for the report
''' &lt;/summary&gt;
Private Function CreateWorksheetAuditReport(ByRef cancelled As Boolean) As Boolean
  
  Dim Success As Boolean
  Dim Worksheet As ISExcelWorksheet
    
  ' Assume success
  Success = True
  
  ' Create Worksheet
  If mExcelWorkbook.Worksheets.Add("User Audit Report") Then
    Worksheet = mExcelWorkbook.Worksheets("User Audit Report")
    If Worksheet Is Nothing Then Success = False
  Else
    Success = False
  End If 

  ' Columns
  If Success Then
    With Worksheet
      ' Date created
      With .Columns.Item(6).Style
        .HorizontalAlignment = iseExcelCellStyle_HorizontalAlignment.Right
        .NumberFormat = mNumberFormat_DateTime
      End With
  
      ' Last updated date
      With .Columns.Item(7).Style
        .HorizontalAlignment = iseExcelCellStyle_HorizontalAlignment.Right
        .NumberFormat = mNumberFormat_DateTime
      End With
  
      ' Status flag
      .Columns.Item(8).Style.HorizontalAlignment = iseExcelCellStyle_HorizontalAlignment.Center
      
      ' Inactive date
      With .Columns.Item(9).Style
        .HorizontalAlignment = iseExcelCellStyle_HorizontalAlignment.Right
        .NumberFormat = mNumberFormat_DateTime
      End With
  
      ' Date deleted
      With .Columns.Item(10).Style
        .HorizontalAlignment = iseExcelCellStyle_HorizontalAlignment.Right
        .NumberFormat = mNumberFormat_DateTime
      End With
  
      ' Last log-in date
      With .Columns.Item(11).Style
        .HorizontalAlignment = iseExcelCellStyle_HorizontalAlignment.Right
        .NumberFormat = mNumberFormat_DateTime
      End With
  
      ' Days since last log-in
      With .Columns.Item(12).Style
        .HorizontalAlignment = iseExcelCellStyle_HorizontalAlignment.Right
        .NumberFormat = mNumberFormat_Integer
      End With
  
      ' Days never logged in    
      With .Columns.Item(13).Style
        .HorizontalAlignment = iseExcelCellStyle_HorizontalAlignment.Right
        .NumberFormat = mNumberFormat_Integer
      End With
      
      ' Date password last changed
      With .Columns.Item(14).Style
        .HorizontalAlignment = iseExcelCellStyle_HorizontalAlignment.Right
        .NumberFormat = mNumberFormat_DateTime
      End With
  
      ' Days since password last changed
      With .Columns.Item(15).Style
        .HorizontalAlignment = iseExcelCellStyle_HorizontalAlignment.Right
        .NumberFormat = mNumberFormat_Integer
      End With
  
      ' Password expiry date
      With .Columns.Item(16).Style
        .HorizontalAlignment = iseExcelCellStyle_HorizontalAlignment.Right
        .NumberFormat = mNumberFormat_DateTime
      End With
  
      ' Days since password expiry
      With .Columns.Item(17).Style
        .HorizontalAlignment = iseExcelCellStyle_HorizontalAlignment.Right
        .NumberFormat = mNumberFormat_Integer
      End With
    End With
  End If
    
  ' Header Row
  If Success Then
    With Worksheet
      .Cell(1, 1).SetString("User Id")
      .Cell(2, 1).SetString("Name")
      .Cell(3, 1).SetString("Email Address")
      .Cell(4, 1).SetString("User Policy")
      .Cell(5, 1).SetString("User Group")
      .Cell(6, 1).SetString("Created Date")
      .Cell(7, 1).SetString("Last Updated")
      .Cell(8, 1).SetString("Status")
      .Cell(9, 1).SetString("Inactive Date")
      .Cell(10, 1).SetString("Deleted Date")
      .Cell(11, 1).SetString("Last Login Date")
      .Cell(12, 1).SetString("Days since Last Login")
      .Cell(13, 1).SetString("Days Never Logged In")
      .Cell(14, 1).SetString("Password Change Date")
      .Cell(15, 1).SetString("Days since Password changed")
      .Cell(16, 1).SetString("Password Expiry Date")
      .Cell(17, 1).SetString("Days since Password Expiry")
      ' Message in column 18 - no heading
      
      .Rows(1).Style.Bold = True
      
      ' Freeze header row
      .FreezePanes(1, 0)
    End With
  End If
  
  ' Data Rows
  If Success Then
    Success = CreateWorksheetAuditReportDataRows(Worksheet)
  End If
  
  Return Success
  
End Function

''' &lt;summary&gt;
''' Write the User Audit data to the worksheet, formatting cells as required by parameters
''' &lt;/summary&gt;
Private Function CreateWorksheetAuditReportDataRows(Worksheet As ISExcelWorksheet) As Boolean
  
  Dim List As ISList
  Dim RowIndex As Integer
  Dim Success As Boolean
  Dim UserItem As UserItem
  
  RowIndex = 1
  For Each UserItem In mUserItems
    RowIndex += 1
    
    With Worksheet
      ' Background Colour
      If UserItem.Deleted Then
        .Rows.Item(RowIndex).Style.BackgroundColour = BackgroundColour_DeletedRow
      ElseIf Not UserItem.Active Then
        .Rows.Item(RowIndex).Style.BackgroundColour = BackgroundColour_InactiveRow
      End If  
      
      ' User Id
      .Cell(1, RowIndex).SetString(UserItem.UserId)
      
      ' Name
      .Cell(2, RowIndex).SetString(UserItem.Name)
      
      ' Email address
      .Cell(3, RowIndex).SetString(UserItem.EmailAddress)
      
      ' User policy Id
      .Cell(4, RowIndex).SetString(UserItem.UserPolicyId)
      
      ' User group Id
      .Cell(5, RowIndex).SetString(UserItem.UserGroupId)
      
      ' Date created
      .Cell(6, RowIndex).SetDate(ConvertFromUtcDate(UserItem.CreatedUtcDate))
      If UserItem.FlagCreatedDate Then CellHighlight(.Cell(6, RowIndex))
      
      ' Last updated date
      CellSetDateOrEmpty(.Cell(7, RowIndex), ConvertFromUtcDate(UserItem.UpdatedUtcDate))

      ' Status
      .Cell(8, RowIndex).SetString(UserItem.Status)
      
      ' Inactive date
      CellSetDateOrEmpty(.Cell(9, RowIndex), ConvertFromUtcDate(UserItem.InactiveUtcDate))
      If UserItem.FlagInactiveDate Then CellHighlight(.Cell(9, RowIndex))
      
      ' Date deleted
      CellSetDateOrEmpty(.Cell(10, RowIndex), ConvertFromUtcDate(UserItem.DeletedUtcDate))
      If UserItem.FlagDeletedDate Then CellHighlight(.Cell(10, RowIndex))
      
      ' Last log-in date
      If UserItem.LastLoginUtcDate = Nothing Then
        .Cell(11, RowIndex).SetString("NEVER")
      Else
        .Cell(11, RowIndex).SetDate(ConvertFromUtcDate(UserItem.LastLoginUtcDate))
      End If  
      If UserItem.FlagLastLoginDate Then CellHighlight(.Cell(11, RowIndex))
      
      ' Days since last log-in
      CellSetLongOrEmpty(.Cell(12, RowIndex), UserItem.DaysSinceLastLogin)
        
      ' Days never logged in
      If UserItem.Active Then
        CellSetLongOrEmpty(.Cell(13, RowIndex), UserItem.DaysNeverLoggedIn)
      End If    
      
      ' Date password last changed
      If UserItem.Active Then
        CellSetDateOrEmpty(.Cell(14, RowIndex), ConvertFromUtcDate(UserItem.PasswordUtcDate))
      End If
    
      ' Days since password last changed
      If UserItem.Active Then
        CellSetLongOrEmpty(.Cell(15, RowIndex), UserItem.DaysSincePasswordChange)
      End If
        
      ' Password expiry date
      CellSetDateOrEmpty(.Cell(16, RowIndex), ConvertFromUtcDate(UserItem.PasswordExpiryUtcDate))
      If UserItem.FlagPasswordExpiryDate Then CellHighlight(.Cell(16, RowIndex))

      ' Days since password expiry
      CellSetLongOrEmpty(.Cell(17, RowIndex), UserItem.DaysSincePasswordExpiry)

      ' Messages
      .Cell(18, RowIndex).SetString(UserItem.Message)
    End With
  Next  
  
  ' Resize columns to fit
  Worksheet.Columns.Autofit()

  ' Add Notes
  With Worksheet
    RowIndex += 2
    
    .Cell(1, RowIndex).SetString(String.Format("Report Date: {0}.", finBL.FormatDateTimeLong(ConvertFromUtcDate(mDateAsAt)))): RowIndex += 1

    List = finBL.Runtime.CreateList()
    If mIncludeActive Then List.Add("Active")
    If mIncludeInactive Then List.Add("Inactive")
    If mIncludeDeleted Then List.Add("Deleted")
    .Cell(1, RowIndex).SetString(String.format("Include {0} Users.", List.ToCsvString())): RowIndex += 1
    
    If mHighlightDateRange Then
      .Cell(1, RowIndex).SetString(String.Format("Highlighted items in date range {0} to {1}.", finBL.FormatDateLong(mFromDate), finBL.FormatDateLong(mToDate))): RowIndex += 1
      If mExcludeNonHighlighted Then
        .Cell(1, RowIndex).SetString("Users with no highlighted items are excluded from the report."): RowIndex += 1
      End If 
    End If
  End With  
  
  ' Calculate totals
  mExcelWorkbook.Calculate()
  
  Return Success
  
End Function

'-----------------------------------
' Private helper functions and subs
'-----------------------------------

''' &lt;summary&gt;
''' Sets the specified backgound colour, and bolds the text
''' &lt;/summary&gt;
Private Sub CellHighlight(cell As ISExcelCell, 
                 Optional bold As Boolean = True)
                          
  With cell.Style
    .BackgroundColour = BackgroundColour_Highlight
    .Bold = bold
  End With 
  
End Sub

''' &lt;summary&gt;
''' Sets a cell value to an date value if it has a value.
''' &lt;/summary&gt;
Private Sub CellSetDateOrEmpty(cell As ISExcelCell, 
                               dateValue As Date)
                              
  If dateValue &lt;&gt; Nothing Then
    cell.SetDate(dateValue)
  End If
  
End Sub

''' &lt;summary&gt;
''' Sets a cell value to a long value if it has a value.
''' &lt;/summary&gt;
Private Sub CellSetLongOrEmpty(cell As ISExcelCell, 
                               longValue As Long?) 
                                  
  If longValue.HasValue Then 
    cell.SetLong(longValue.Value)
  End If
  
End Sub

Private Function ConvertFromUtcDate(dateValue As Date) As Date
  
  If dateValue = Nothing Then 
    Return Nothing
  Else
    Return finBL.TimeZoneFunctions.ConvertUtcToDatabaseDateTime(dateValue)    
  End If
  
End Function

''' &lt;summary&gt;
'''  Returns TRUE if the Date is within the range: mFromDate (inclusive) to mToDate (exclusive).
''' &lt;/summary&gt;
Private Function InRange(checkDate As Date) As Boolean

  Return checkDate &lt;&gt; Nothing AndAlso checkDate &gt;= mFromDate.Date AndAlso checkDate &lt; mToDate.Date

End Function

''' &lt;summary&gt;
'''  Returns the number of days since the Report date.
''' &lt;/summary&gt;
Private Function DaysSince(checkDate As Date) As Long

  Return DateDiff(DateInterval.Day, checkDate, mDateAsAt)
  
End Function


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

  ' Current Processes
  Public CurrentProcesses As New List(Of finHtmlWidgetUtilities.JsonProcessStatusInformation)

  ' Default date range
  Public FromDate As Date
  Public ToDate As Date
  
  ' Configuration
  Public DesktopMode As Boolean
  Public PromptOnCommit As Boolean
  Public [ReadOnly] As Boolean

End Class

''' &lt;summary&gt;
'''  Wizard Finish Parameters.
''' &lt;/summary&gt;
Public Class WizardFinishParameters

  Public IncludeActive As Boolean
  Public IncludeInactive As Boolean
  Public IncludeDeleted As Boolean
  Public HighlightDateRange As Boolean
  Public FromDate As Date
  Public ToDate As Date
  Public ExcludeNonHighlighted As Boolean

End Class

''' &lt;summary&gt;
'''  Validation details.
''' &lt;/summary&gt;
Public Class WizardValidateResponse

  Public Data As Object
  Public FailedMessage As String
  Public FailedControlId As String

  Public Sub New(data As Object,
                 failedMessage As String,
                 failedControlId As String)

    Me.Data = data
    Me.FailedMessage = failedMessage
    Me.FailedControlId = failedControlId

  End Sub

End Class

''' &lt;summary&gt;
'''  Details about Users to appear in the report.
'''  Flag settings to use when rendering User data.
''' &lt;/summary&gt;
Public Class UserItem
  
  ' User and UserRO fields
  Public UserId As String
  Public Name As String
  Public EmailAddress As String
  Public UserPolicyId As String
  Public UserGroupId As String
  Public Active As Boolean
  Public InactiveUtcDate As Date
  Public Deleted As Boolean
  Public DeletedUtcDate As Date
  Public CreatedUtcDate As Date
  Public DaysNeverLoggedIn As Long?
  Public LastLoginUtcDate As Date
  Public DaysSinceLastLogin As Long?
  Public PasswordUtcDate As Date
  Public DaysSincePasswordChange As Long?
  Public PasswordExpiryUtcDate As Date
  Public DaysSincePasswordExpiry As Long?
  Public UpdatedUtcDate As Date
  Public Message As String

  ' Formatting flags
  Public FlagCreatedDate As Boolean
  Public FlagInactiveDate As Boolean
  Public FlagDeletedDate As Boolean
  Public FlagLastLoginDate As Boolean
  Public FlagPasswordExpiryDate As Boolean
  
  Public ReadOnly Property IsFlagged As Boolean
    Get
      Return FlagCreatedDate OrElse FlagInactiveDate OrElse FlagDeletedDate OrElse FlagLastLoginDate OrElse FlagPasswordExpiryDate
    End Get
  End Property
  
  Public ReadOnly Property Status As String
    Get
      If Active Then
        Return String.Empty
      Else If Deleted Then
        Return "DELETED"
      Else
        Return "INACTIVE"
      End If
    End Get
  End Property
  
End Class
</Code>
    <Language>VisualBasic</Language>
    <Notes>HTML Widget with background process to create an Excel worksheet containing a Audit report of User changes.

The report is a list of all Users in the database. It can be limited to a list of Users created, deactivated or deleted during a specified date range.

Selection can be further filtered including some or all of: active users, inactive users, deleted users.

Certain items are highlighted, such as Users whose password has expired.</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;div class="header"&gt;&lt;/div&gt;
    &lt;div class="summary"&gt;&lt;/div&gt;
    &lt;!-- Tabs --&gt;
    &lt;div id="tabWizard" class="is-tabs"&gt;
      &lt;ul&gt;
        &lt;li tabId="CurrentProcesses" tooltipText="Drill down to view the status of current and recent User Audit Reports that you have run."&gt;Recent Reports&lt;/li&gt;
        &lt;li tabId="General" tooltipText="Enter report options."&gt;User Audit Report&lt;/li&gt;
        &lt;li tabId="Progress" tooltipText="Processing progress."&gt;Progress&lt;/li&gt;
      &lt;ul&gt;
    &lt;/div&gt;
  &lt;/header&gt;

  &lt;!-- Pages --&gt;
  &lt;div class="is-widget-form-body"&gt;
    &lt;!-- Current Processes --&gt;
    &lt;div id="pageCurrentProcesses"&gt;
      &lt;div id="gridCurrentProcesses"&gt;&lt;/div&gt;
    &lt;/div&gt;

    &lt;!-- General --&gt;
    &lt;div id="pageGeneral"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:8em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblStatusSelectionOptions"&gt;Status Selection options&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkIncludeActive" type="checkbox"/&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkIncludeInactive" type="checkbox"/&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkIncludeDeleted" type="checkbox"/&gt;&lt;/th&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblHighlightDateRange"&gt;Highlight Date Range&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkHighlightDateRange" type="checkbox"/&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;td class="indent1" colspan="2"&gt;
            &lt;label for="dateFrom"&gt;From:&lt;/label&gt;
            &lt;input id="dateFrom" /&gt; 
            &lt;label for="dateTo"&gt;&amp;nbsp;to&amp;nbsp;&lt;/label&gt;
            &lt;input id="dateTo" /&gt; 
          &lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;td class="indent1" colspan="2"&gt;
            &lt;input id="chkExcludeNonHighlighted" type="checkbox"/&gt;
          &lt;/td&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;

    &lt;!-- Progress --&gt;
    &lt;div id="pageProgress" style="display:flex"&gt;
      &lt;div id="divProgress" class="progress-events"&gt;&lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;

  &lt;!-- Form Footer --&gt;
  &lt;footer&gt;
    &lt;button id="cmdHistory" class="is-button" style="float:left"&gt;Recent&lt;/button&gt;

    &lt;button id="cmdCancel" class="is-button"&gt;Cancel&lt;/button&gt;
    &lt;button id="cmdBack" class="is-button"&gt;&amp;lt; Back&lt;/button&gt;
    &lt;button id="cmdNext" class="is-button"&gt;Next &amp;gt;&lt;/button&gt;
    &lt;button id="cmdFinish" class="is-button ok"&gt;Finish&lt;/button&gt;  &lt;/footer&gt;
&lt;/div&gt;

&lt;script&gt;
// Record
var mRecord;
var mRecord_BackgroundProcessStatus;
var mRecord_CurrentProcesses;

// Global Collections
var mEntities;

// Controls
var C = {
  // Current Processes
  gridCurrentProcesses: null,

  // General
  chkIncludeActive: null,
  chkIncludeInactive: null,
  chkIncludeDeleted: null,
  chkHighlightDateRange: null,
  dateFrom: null,
  dateTo: null,
  chkExcludeNonHighlighted: null,
  
  // Progress
  divProgress: null,
}

// Form
var frmMain;
var tabWizard;

// Wizard Buttons
var cmdCancel;
var cmdBack;
var cmdNext;
var cmdFinish;

var cmdHistory;

// Other
var mComplete = false;
var mComplete_Information;
var mFromRecent = false;
var mLastEventId = "";
var mLastProcessStatus = "";
var mMonitoringExisting = false;
var mProcessId;

// Initialise
$(function() {

  // Mobile optimisations
  $(window).resize(Form_Resize);
  // Controls
  //   General
  C.lblStatusSelectionOptions = widget.UI.Label("lblStatusSelectionOptions", {
    tooltipText: "Choose whether to include or exclude active Users, inactive Users, and deleted Users in the report. You must select at least one.",
  });
  C.chkIncludeActive = widget.UI.CheckBox("chkIncludeActive", {
    caption: "Include active Users?",
  });
  C.chkIncludeInactive = widget.UI.CheckBox("chkIncludeInactive", {
    caption: "Include inactive Users?",
  });
  C.chkIncludeDeleted = widget.UI.CheckBox("chkIncludeDeleted", {
    caption: "Include deleted Users?",
  });

  C.lblHighlightDateRange = widget.UI.Label("lblHighlightDateRange", {
    tooltipText: "You can specify a date range to use when creating the report. Key items that occurred within the range will be highlighted, such as creation dates and password expiry dates. You can also choose to exclude Users that do not have any highlighted items.",
  });
  C.chkHighlightDateRange = widget.UI.CheckBox("chkHighlightDateRange", {
    caption: "Highlight Users within Date Range?",
    onChange: chkHighlightDateRange_Change,
  });
  C.dateFrom = widget.UI.DateBox("dateFrom", {
    allowBlank: false,
  });
  C.dateTo = widget.UI.DateBox("dateTo", {
    allowBlank: false,
  });
  C.chkExcludeNonHighlighted = widget.UI.CheckBox("chkExcludeNonHighlighted", {
    caption: "Exclude Users without highlighted events?",
  });

  // Progress
  C.divProgress = $("#divProgress");

  // Grids
  C.gridCurrentProcesses = widget.UI.Grid("gridCurrentProcesses", {
    docked: true,
    stickyHeader: true,
    rowNumbering: true,

    onInitialiseRow: gridCurrentProcesses_InitialiseRow,
    onRowDrilldown: gridCurrentProcesses_RowDrilldown,
  });

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

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

  // Handle Wizard Buttons
  cmdCancel = $("#cmdCancel");
  cmdBack = $("#cmdBack");
  cmdNext = $("#cmdNext");
  cmdFinish = $("#cmdFinish");
  cmdCancel.click(tabWizard_Cancel);
  cmdBack.click(function() { tabWizard_Move(-1); });
  cmdNext.click(function() { tabWizard_Move(1); });
  cmdFinish.click(function() { Form_ExecuteAction("Finish"); });

  cmdHistory = $("#cmdHistory");
  cmdHistory.click(function() { Form_ExecuteAction("Recent"); });

  // Reset Form
  Form_Reset();
});

// ==========
// Form Reset
// ==========
function Form_Reset() {
  // Defaults
  C.chkIncludeActive.Value(true);
  C.chkIncludeInactive.Value(true);
  C.chkIncludeDeleted.Value(true);
  
  C.chkHighlightDateRange.Value(true);
  C.chkExcludeNonHighlighted.Value(false);
  
  // Set Tab
  tabWizard.SelectedTabId("General");

  // Resize
  Form_Resize();

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

// ===========
// Record Load
// ===========
function Record_Load() {
  // Initialise
  mRecord = null;
  mRecord_BackgroundProcessStatus = null;
  mRecord_CurrentProcesses = null;
  mComplete_Information = null;

  // 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_CurrentProcesses = mRecord.CurrentProcesses;

      // Load Fields
      Fields_Load();

      // Notify if there are Current Processes
      var countCurrent = 0;
      for (var i = 0; i &lt; mRecord_CurrentProcesses.length; i++) {
        switch (mRecord_CurrentProcesses[i].Status) {
          case "Pending":
          case "InProgress":
          case "InProgressCancelRequested":
            countCurrent += 1;
        }
      }
      if (countCurrent != 0) {
        tabWizard_Move(-1);
        widget.UI.MsgBoxInfo("There are existing Reports that you have run that are not yet complete.\n\nReview and optionally monitor these or use the 'Next &gt;' button to run a new Report.", { heading: "Report Still Running", icon: "MonitorCategory"} );
      }
    },

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

// ===========
// Fields Load
// ===========
function Fields_Load() {
  if (mRecord) {
    // Current Processes
    // NOTE: Bind here since this is the first page
    gridCurrentProcesses_Refresh();

    // Date Range
    C.dateFrom.Value(mRecord.FromDate);
    C.dateTo.Value(mRecord.ToDate);
  }

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

  // Update Controls
  if (mRecord) {
  }

  // Update fields
  Fields_Update();

  // Refresh Tab
  tabWizard_Refresh();
}

// ========================
// Create Finish Parameters
// ========================
function CreateFinishParameters() {
  var params = {
    includeActive: C.chkIncludeActive.Value(),
    includeInactive: C.chkIncludeInactive.Value(),
    includeDeleted: C.chkIncludeDeleted.Value(),
    highlightDateRange: C.chkHighlightDateRange.Value(),
    fromDate: C.dateFrom.Value(),
    toDate: C.dateTo.Value(),
    excludeNonHighlighted: C.chkExcludeNonHighlighted.Value(),
  }

  return params;
}

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

  // Lists
  if (mRecord) {
  }

  // Controls
  if (mRecord) {
  }

  // Update Buttons
  tabWizard_UpdateButtons();

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

  // Resize Tab
  tabWizard_Resize();
}

// =================
// Execute an Action
// =================
function Form_ExecuteAction(actionId) {
  switch (actionId.toUpperCase()) {
    case "FINISH":
      // Finish
      if (mRecord.ReadOnly || mComplete) {
        tabWizard_Cancel();
      }
      else {
        Form_ExecuteAction_Finish();
      }
      break;

    case "RECENT":
      // Recent
      tabWizard_Refresh(0);
      break;

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

function Form_ExecuteAction_Finish() {
  if (cmdFinish.text() == "Stop") {
    // Stop Process?
    widget.UI.MsgBoxConfirm("Are you sure you want to stop this process?\n\nNOTE: This may not take affect immediately.", {}, function () { Form_ExecuteAction_FinishStop(); }, null);
  }
  else {
    // Validate
    tabWizard_Validate(function() {
      if (true) { //mRecord.PromptOnCommit) {
        // Confirm (ignore setting since prompt contains summary information we always want to show)
        var heading = "Run Report";
        var message = "&lt;p&gt;Are you sure you want to run this report?&lt;/p&gt;";

        // Background Process
        message += "&lt;p&gt;NOTE: You can close this form and any time and open it again to monitor the status of this process.&lt;/p&gt;";

        // Confirm
        widget.UI.MsgBoxConfirm(message, {
            heading: heading,
            icon: "Report",
            messageIsHtml: true,
          },
          Form_ExecuteAction_FinishPost,
          null);
      }
      else {
        // Commit without prompting
        Form_ExecuteAction_FinishPost();
      }
    });
  }
}

function Form_ExecuteAction_FinishPost() {
  // Running new process
  mComplete_Information = null;
  mMonitoringExisting = false;  

  // Clear Progress Page
  pageProgress_Refresh(true);

  // Disable Form
  widget.UI.Block("Starting Report, please wait...");

  // Get Parameters
  var params = CreateFinishParameters();

  // Finish
  widget.GetString("Finish", params,
    function (data) {
    
      // Parse
      data = JSON.parse(data);

      // Set Tab
      tabWizard.SelectedTabId("Progress");
      tabWizard_Refresh();

      // Save Status
      mProcessId = data.ProcessId;
      mRecord_BackgroundProcessStatus = data;

      // Update Wizard Buttons
      tabWizard_UpdateButtons();

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

      // Refresh Progress
      pageProgress_Refresh();

      // Poll Background Process
      window.setTimeout(Form_ExecuteAction_GetBackgroundProcessStatus, 3500);

      // Notify
      if (data.DesktopMode) {
        // Do nothing
      }
      else {
        widget.UI.MsgBoxInfo("The Report has been started.\n\n" + data.CompleteMessage);
      }
    },

    function (data) {
      // Show Error
      widget.UI.MsgBoxAlert(data);

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

function Form_ExecuteAction_FinishStop() {
  // Continue
  widget.GetString("CancelBackgroundProcess", { processId: mProcessId },
    function (data) {
      widget.UI.MsgBoxInfo("A request to cancel the process has been sent.");
    },

    function (error) {
      // Show Error
      widget.UI.MsgBoxAlert(error);
    }
  );
}

function Form_ExecuteAction_GetBackgroundProcessStatus() {
  // Continue
  widget.GetString("GetBackgroundProcessStatus", { processId: mProcessId, lastEventId: mLastEventId },
    function (data) {
      data = JSON.parse(data);

      // Update Status
      mRecord_BackgroundProcessStatus = data;

      // Refresh Progress
      pageProgress_Refresh();

      // Status
      var Status = mRecord_BackgroundProcessStatus.Status;

      // Handle Status
      switch(Status) {
        case "Cancelled":
          // Cancelled
          mRecord_BackgroundProcessStatus = null;

          // Update Wizard Buttons
          tabWizard_UpdateButtons();

          // Notify
          widget.UI.MsgBoxInfo("Report was successfully cancelled.");
          break;

        case "Complete":
        case "CompleteWithErrors":
        case "CompleteWithWarnings":
          // Complete
          mComplete = true;
          if (mRecord_BackgroundProcessStatus.OtherDetailsJson) mComplete_Information = JSON.parse(mRecord_BackgroundProcessStatus.OtherDetailsJson);
          mRecord_BackgroundProcessStatus = null;

          // Update Wizard Buttons
          tabWizard_UpdateButtons();

          // Notify
          var message = "Report is " + widget.SplitWordsAtCapitals(Status, true, true) + ".";          
          if (Status == "Complete" &amp;&amp; mRecord.DesktopMode &amp;&amp; mComplete_Information &amp;&amp; mComplete_Information.ReportFileName) {
            // Show Report (desktop only)?
            message += "\n\nOpen the Report now?";
            
            widget.UI.MsgBoxConfirm(message, { captionOk: "Yes", captionCancel: "No" },
              function () {
                // Close
                widget.Close();
        
                // Show Report
                widget.ExecuteApplicationShortcutUrl("app://External?file=" + encodeURIComponent(mComplete_Information.ReportFileName));
              }
            );
          }
          else {
            widget.UI.MsgBoxInfo(message, {}, Form_ExecuteAction_GetBackgroundProcessStatus_Complete_Post);
          }
          break;

        case "Failed":
          // Failed
          mRecord_BackgroundProcessStatus = null;

          // Update Wizard Buttons
          tabWizard_UpdateButtons();

          // Notify
          widget.UI.MsgBoxAlert("Report failed to complete.");
          break;

        default:
          // Continue Polling
          window.setTimeout(Form_ExecuteAction_GetBackgroundProcessStatus, 2500);

          // Prevent finPOWER Connect Cloud UI signing the User out
          widget.NotifyBusy();
      }
    },

    function (error) {
      // Show Error
      widget.UI.MsgBoxAlert(error);

      // Abort Execution
      mRecord_BackgroundProcessStatus = null;

      // Update Wizard Buttons
      tabWizard_UpdateButtons();
    }
  );
}

function Form_ExecuteAction_GetBackgroundProcessStatus_Complete_Post() {
  // Show Report (desktop only)?
  if (mComplete_Information &amp;&amp; mRecord.DesktopMode) {
    widget.UI.MsgBoxConfirm("Would you like to open the report (" + mComplete_Information.ReportFileName + ") now?", { captionOk: "Yes", captionCancel: "No" },
      function () {
        // Close
        widget.Close();

        // Show Report
        widget.ExecuteApplicationShortcutUrl("app://External?file=" + encodeURIComponent(mComplete_Information.ReportFileName));
      }
    );
  }
}

// ====================
// pageCurrentProcesses
// ====================
function pageCurrentProcesses_Refresh() {
  // Reset flags
  mComplete = false;

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

  // Fetch
  widget.GetString("GetCurrentProcesses", {},
    function (data) {
      // Parse
      mRecord_CurrentProcesses = JSON.parse(data);

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

      // Update Wizard Buttons
      tabWizard_UpdateButtons();

      // Refresh Grid
      gridCurrentProcesses_Refresh();
    },

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

      // Show Error
      widget.UI.MsgBoxAlert(error);
    }
  );
}

// ============
// pageProgress
// ============
function pageProgress_Refresh(clear) {
  if (clear) {    
    mLastProcessStatus = "";
    mLastEventId = "";
    mRecord_BackgroundProcessStatus = null;
    mRecord_CurrentProcesses = null;
  }
  else if (mRecord_BackgroundProcessStatus) {
    // Retrieve Last Process Status
    mLastProcessStatus = mRecord_BackgroundProcessStatus.StatusText;
  }

  // Build Progress
  mLastEventId = widget.UI.BuildBackgroundProcessProgress(C.divProgress, clear, mRecord_BackgroundProcessStatus, mLastEventId);

  // Stop button valid?
  tabWizard_UpdateButtons()

  // Update Heading
  if (tabWizard.SelectedTabId() == "Progress") {
    if (mLastProcessStatus &amp;&amp; mLastProcessStatus.length != 0) {
      frmMain.RefreshHeading(mLastProcessStatus, "Processing progress.");
    }
    else {
      frmMain.RefreshHeading("Progress", "Processing progress.");
    }
  }
}

// ====================
// gridCurrentProcesses
// ====================
function gridCurrentProcesses_Refresh() {
  // Add Columns
  if (C.gridCurrentProcesses.ColumnCount() == 0) {
    C.gridCurrentProcesses.AddColumnDrilldown();
    C.gridCurrentProcesses.AddColumnString("StatusText", { caption: "Status" });
    C.gridCurrentProcesses.AddColumnDateTime("CreatedDate", { caption: "Started" });
  }

  // Refresh
  C.gridCurrentProcesses.VirtualDataRefresh(mRecord_CurrentProcesses);

  // Activate no rows
  C.gridCurrentProcesses.ActiveDataRowIndex(-1);
}

function gridCurrentProcesses_InitialiseRow(e) {
  var item = mRecord_CurrentProcesses[e.row.listIndex];

  // Update cells
  e.row.AutoBind(item);

  // Styles
  switch(item.Status) {
    case "Complete":
      e.row.cells.StatusText.colour = "green";
      break;

    case "CompleteWithErrors":
      e.row.cells.StatusText.colour = "darkred";
      break;

    case "CompleteWithWarnings":
      e.row.cells.StatusText.colour = "orange";
      break;

    case "Failed":
      e.row.cells.StatusText.colour = "red";
      break;

    case "Pending":
    case "InProgress":
    case "InProgressCancelRequested":
      e.row.bold = true;
      break;
  }
}

function gridCurrentProcesses_RowDrilldown(e) {
  var item = mRecord_CurrentProcesses[e.row.listIndex];

  // Switch to Progress Page
  mFromRecent = true;
  mMonitoringExisting = true;
  mProcessId = item.ProcessId;
  tabWizard_Refresh(2);
  pageProgress_Refresh(true);

  // Start monitoring
  Form_ExecuteAction_GetBackgroundProcessStatus();
}

// ===========
// Form Resize
// ===========
function Form_Resize() {
  // General

  // Tab
  tabWizard_Resize();
}

// ==========
// Tab Wizard
// ==========
function tabWizard_Cancel() {
  // Executing?
  if (mComplete) {
    tabWizard_Cancel_Post();
  }
  else if (mRecord_BackgroundProcessStatus &amp;&amp; !mMonitoringExisting) {
    widget.UI.MsgBoxConfirm("Report is still running.\n\nThis will continue to run and you can re-open this form at any time to check on its status.\n\n\Close this form?", {}, tabWizard_Cancel_Post);
  }
  else {
    tabWizard_Cancel_Post();
  }
}

function tabWizard_Cancel_Post() {
  if (widget.CanClose()) {
    widget.Close();
  }
  else {
    widget.Reset();
  }
}

// ===========
// Wizard Move
// ===========
function tabWizard_Move(direction) {
  var Ok;

  // Validate
  if (direction &gt; 0) {
    tabWizard_Validate(function () { tabWizard_MovePost(direction); });
  }
  else {
    // Can always move backwards
    tabWizard_MovePost(direction);
  }
}

function tabWizard_MovePost(direction) {
  var Ok = true;

  // Find Next Tab to Move To
  if (Ok) {
    var found = false;
    var newTab = tabWizard.SelectedTabIndex();

    do {
      newTab += direction;

      switch (tabWizard.GetTabIdByIndex(newTab)) {
        default:
          found = true;
          break;
      }

      // Found?
      if (found) {
        break;
      }
      else if (newTab == tabWizard.TabCount() - 1) {
        // Just in case!
        widget.UI.MsgBoxAlert("tabWizard_MovePost: Tab not handled!");
        break;
      }
    }
    while (true);

    // Refresh the New Tab
    tabWizard_Refresh(newTab);
  }
}

function tabWizard_Refresh(newTab) {
  // Moving forward onto tab, so Load information
  if (newTab &gt;= tabWizard.SelectedTabIndex()) {
    switch (tabWizard.GetTabIdByIndex(newTab)) {
      default:
        break;
    }
  }

  // Always Refresh Current Processes, even when moving back
  if (newTab == 0) {
    if (!mRecord_CurrentProcesses) pageCurrentProcesses_Refresh();
  }

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

  // Special
  switch(tabWizard.SelectedTabId()) {
    case "CurrentProcesses":
      // Reset from recent flag
      mFromRecent = false;
      break;

    default:
      break;
  }

  // Tweak fields

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

  // Back, Next command buttons valid?
  tabWizard_UpdateButtons();

  // Resize Wizard
  tabWizard_Resize();

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

function tabWizard_Resize() {
  switch (tabWizard.SelectedTabId()) {
    default:
      break;
  }
}

function tabWizard_UpdateButtons() {
  // Back, Next Buttons?
  if (tabWizard.TabCount() == 1) {
    cmdBack.hide();
    cmdNext.hide();
  }
  else {
    var tabIndex = tabWizard.SelectedTabIndex();

    // Back and Next Buttons?
    cmdBack.prop("disabled", tabIndex &lt; 1);
    cmdNext.prop("disabled", tabIndex &gt;= tabWizard.TabCount() - 2);
  }

  // Finish Button
  //if (tabWizard.TabCount() != 1) cmdFinish.prop("disabled", !cmdNext.prop("disabled"));

  // Page Exceptions
  if (mRecord_BackgroundProcessStatus) {
    cmdNext.prop("disabled", tabIndex &gt;= tabWizard.TabCount() - 1);
    cmdBack.prop("disabled", true);
    cmdHistory.prop("disabled", true);

    switch(mRecord_BackgroundProcessStatus.Status) {
      case "Pending":
      case "InProgress":
        cmdFinish.text("Stop");
        cmdFinish.prop("disabled", false);
        cmdFinish.addClass("negative");
        break;

      default:
        cmdFinish.text("Process");
        cmdFinish.prop("disabled", true);
        cmdFinish.removeClass("negative");
    }
  }
  else {
    cmdFinish.text("Process");
    cmdFinish.prop("disabled", !cmdNext.prop("disabled"));
    cmdHistory.prop("disabled", false);
  }

  // Recent Page exceptions
  if (mFromRecent) {
    cmdHistory.prop("disabled", false);
    cmdBack.prop("disabled", true);
    cmdNext.prop("disabled", true);
    cmdFinish.prop("disabled", true);
  }

  if (mComplete) {
    // Complete, i.e., Finish now closes the wizard
    cmdFinish.text("Close");
    cmdFinish.prop("disabled", false);

    // Allow viewing recent list
    cmdHistory.prop("disabled", false);
  }
}

function tabWizard_Validate(validCallback) {
  // Validate
  var Ok = tabWizard.Validate(true);

  // Other client-side validation
  if (Ok) {
    switch (tabWizard.SelectedTabId()) {
      case "General":
        // Must choose at least one
        if (!C.chkIncludeActive.Value() &amp;&amp; !C.chkIncludeInactive.Value() &amp;&amp; !C.chkIncludeDeleted.Value()) {
          widget.UI.MsgBoxAlert("You must choose at least one of: 'Include active users?', 'Include inactive users?', or 'Include deleted users?'."); 
          Ok = false;
        }
        // Date range check
        if (C.chkHighlightDateRange.Value()) {
          if (widget.CompareDates(C.dateFrom.Value(), C.dateTo.Value()) != -1) {
            Ok = false;
            widget.UI.MsgBoxAlert("Please check that start and end date are valid dates and that start date is before end date.");
          }
        }
        break;

      default:
        // No validation
        validCallback();
        return;
    }
  }

  // Server-side validation
  if (Ok) {
    var params;

    switch (tabWizard.SelectedTabId()) {
      case "General":
        var params = CreateFinishParameters();
        break;
    }

    if (params) {
      // Disable Form
      frmMain.FormDisable("Validating");

      // Extend parameters
      params.pageId = tabWizard.SelectedTabId();

      // Call WizardValidate method in Script
      widget.GetString("WizardValidate",
                       params,
                       function (data) { tabWizard_ValidatePost(validCallback, data); },
                       tabWizard_ValidateFail);
    }
    else {
      // No server-side validation
      validCallback();
    }
  }
}

function tabWizard_ValidatePost(validCallback, data) {
  // Enable form
  frmMain.FormEnable();

  // Parse Data
  if (data) {
    var o =  JSON.parse(data);
    if (o.FailedMessage) {
      // -----------------
      // Validation failed
      // -----------------
      widget.UI.MsgBoxAlert(o.FailedMessage);
      if (o.FailedControlId) $("#" + o.FailedControlId).focus();
    }
    else {
      // --------------------
      // Validation succeeded
      // --------------------
      // Validation could pass back additional information, e.g., to use in tabWizard_Refresh
      switch (tabWizard.SelectedTabId()) {
      }
  
      // Callback
      validCallback();
    }
  }
}

function tabWizard_ValidateFail(errorMessage)
{
  widget.UI.MsgBoxAlert(errorMessage);

  // Enable form
  frmMain.FormEnable();
}

function chkHighlightDateRange_Change() {
  var show = C.chkHighlightDateRange.Value();
  C.dateFrom.VisibleRow(show);
  C.chkExcludeNonHighlighted.VisibleRow(show);
}
&lt;/script&gt;
</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>0</TimeoutSeconds>
    <UniqueId>sWF37GRMLkqxXkuhhPYLvg</UniqueId>
    <AllowRefresh>false</AllowRefresh>
    <Caption />
    <HtmlWidgetAllowInitialEventCaching>false</HtmlWidgetAllowInitialEventCaching>
    <HtmlWidgetMaxHeight>640</HtmlWidgetMaxHeight>
    <HtmlWidgetMaxWidth>800</HtmlWidgetMaxWidth>
    <HtmlWidgetNeverApplyStyling>false</HtmlWidgetNeverApplyStyling>
    <HtmlWidgetResourceChartsApex>false</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 />
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="DesktopMode" 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>
        </Parameters>
      </ISParameterDefs>
    </Parameters>
  </finScript>