<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2025-08-06T21:51:34.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2025-04-29T01:14:12.9130000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2025-08-06T21:49:56.5000000</UpdatedUtcDate>
    <ScriptId>HWCCRE</ScriptId>
    <Description>Comprehensive Credit Report Export</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_CreditReportingExport
Option Explicit On
Option Strict On

' #################################################################
' Credit Report Export
'
' (C) Copyright Intersoft Systems Limited 2025
'
' Version: 1.00 (07/08/2025)
'
' Usage: System-defined HTML Widget
'
' NOTE: Uses Web Services Background Processes
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.00  07/08/2025  ISS      J033870   Created
' #################################################################

' Constants
Private Const FORM_KEY As String = "CreditReportingExport"

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

' Other
Private mDesktopMode As Boolean
Private mExistingExportBatchLimitDays As Integer
Private mIsRefreshing As Boolean
Private mProcessStatus As finHtmlWidgetBackgroundProcessStatus

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 Parameters
  With mCombinedParameters
    mDesktopMode = .GetBoolean("DesktopMode")
    mExistingExportBatchLimitDays = .GetInteger("ExistingExportBatchLimitDays")
  End With
  
  ' Override Parameters
  If mExistingExportBatchLimitDays &lt; 1 Then
    mExistingExportBatchLimitDays = 30
  End If  
  
  ' 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 wizard
      Main = Finish(parametersJson, returnValue)

    Case "GetBackgroundProcessStatus"
      ' Get Background Process Status
      Main = GetBackgroundProcessStatus(returnValue)

    Case "GetCurrentProcesses"
      ' Get Current Processes
      Main = GetCurrentProcesses(returnValue)

    Case "GetExistingExports"
      ' Get Existing Exports
      Main = GetExistingExports(returnValue)

    Case "GetInitialisationInfo"
      ' Get Initialisation Information required for this wizard
      Main = GetInitialisationInfo(returnValue)
      
    Case "RefreshBatchType"
      ' Refresh Batch Type
      Main = RefreshBatchType(returnValue)

    Case "WizardValidate"
      ' Validate wizard page
      Main = WizardValidate(parametersJson, 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 ExportBatchesJson As String
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim ProcessStatuses As List(Of finHtmlWidgetUtilities.JsonProcessStatusInformation)
  Dim ScriptPk As Integer
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  FormInitialisationInfo = New FormInitialisationInfo()

  ' Validate
  Success = finBL.HtmlWidgetUtilities.HasPermissionToViewFormKey(FORM_KEY)
  
  ' Find Script
  If Success Then
    If finBL.AccountFunctions.GetScriptPk(isefinAccountScriptType.EventCreditReporting, ScriptPk) Then
      If ScriptPk = 0 Then
        Success = False
        finBL.Error.ErrorBegin("Please define the Credit Reporting script under Tools, Global Settings, Accounts group, Scripts page.")
      End If
    Else
      Success = False
    End If
  End If  

  ' Existing Exports
  If Success Then
    Success = GetExistingExports(ExportBatchesJson)
  End If

  ' Get Form Initialisation Info
  If Success Then
    With FormInitialisationInfo
      ' Record

      ' General
      .ExportDate = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(finBL.Runtime.DateUtilities.EndOfPreviousMonth(finBL.TimeZoneFunctions.GetCurrentDatabaseDate))

      ' Permissions

      ' Configuration
      .DesktopMode = mDesktopMode
      .EmailWhenComplete = (finBL.CloudConnectFunctions.CloudConnectSettings.ProcessBackgroundEmailUserOnFinish AndAlso Len(finBL.CurrentUserInformation.Email) &lt;&gt; 0)
      .ExistingExportBatchLimitDays = mExistingExportBatchLimitDays
      .PromptOnCommit = finBL.CloudConnectFunctions.CloudConnectSettings.PromptOnCommit
      
      ' Collections
      .ExportBatchesJson = ExportBatchesJson
    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
  
  Return Success

End Function

''' &lt;summary&gt;
'''  Get Existing Exports.
''' &lt;/summary&gt;
Private Function GetExistingExports(ByRef returnValue As String) As Boolean
  
  Dim DescriptionField As String
  Dim dr As DataRow  
  Dim dv As DataView
  Dim FieldList As ISList
  Dim IdField As String
  Dim ReportExportItems As List(Of CreditReportExportItem)
  Dim Success As Boolean
  Dim ShowAllExisting As Boolean
  Dim sqlWhere As String
  
  ' Assume Success
  Success = True
  
  ' Initialise
  ReportExportItems = New List(Of CreditReportExportItem)
  
  ' Parameters
  With mCombinedParameters
    ShowAllExisting = .GetBoolean("ShowAllExisting")
  End With

  ' Limit to last x days
  If Not ShowAllExisting Then
    With finBL.Database.CreateSqlWhereBuilder()
      .AppendComparisonDate("CreditReportExport.CreatedUtcDate", "&gt;=", finBL.TimeZoneFunctions.GetCurrentUtcDateTimePrecise().AddDays(-mExistingExportBatchLimitDays))
      sqlWhere = .SqlWhere
    End With
  End If

  ' Get Export Items
  If finBL.Utilities.CreateDataViewFromStandardRange(isefinStandardRange.CreditReportingExportBatches, sqlWhere, True, iseCollectionDataViewTarget.DbCombo, dv, IdField, DescriptionField, FieldList) Then
    For Each dr In dv.Table.Rows
      ReportExportItems.Add(New CreditReportExportItem(dr)) 
    Next
    
    ' Sort
    ReportExportItems.Sort(AddressOf GetExistingExports_SortComparer)
  Else
    Success = False
  End If
  
  ' Serialise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(ReportExportItems, returnValue)
  End If
  
  Return Success
  
End Function

Private Function BackgroundProcess_Execute(ByRef returnValue As String) As Boolean
  
  Dim Cancelled As Boolean
  Dim CountExported As Integer
  Dim CreditReportExport As finCreditReportExport
  Dim CreditReportGenerate As finCreditReportGenerate
  Dim CloudFileName As String
  Dim Entity As finEntityRO
  Dim EventScriptReturnValue As Boolean
  Dim ExportFileName As String
  Dim ExportId As String
  Dim FileExportPackageHandler As finwsFileExportPackageHandler
  Dim ScriptPk As Integer
  Dim Success As Boolean
  Dim TemporaryFileName As String
  Dim WizardFinishParameters As WizardFinishParameters
  
  ' Assume Success
  Success = True
  
  ' 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)
  
  ' Notify
  mProcessStatus.AddEvent_Information("Starting Commit")
  
  ' Parameters
  Success = GetWizardFinishParameters(mParameters.ToSimpleJsonString(), WizardFinishParameters)
  
  ' Find Script
  If Success Then
    If finBL.AccountFunctions.GetScriptPk(isefinAccountScriptType.EventCreditReporting, ScriptPk) Then
      If ScriptPk = 0 Then
        Success = False
        finBL.Error.ErrorBegin("Please define the Credit Reporting script under Tools, Global Settings, Accounts group, Scripts page.")
      End If
    Else
      Success = False
    End If
  End If
  
  ' Export
  If Success Then
    If WizardFinishParameters.OptionReExportFile Then
      ' Re-Export
      ExportId = WizardFinishParameters.ExportId
      
      CreditReportExport = finBL.CreateCreditReportExport()
      If CreditReportExport.Load(ExportId) Then
        If CreditReportExport.Execute() Then
          CountExported = CreditReportExport.Accounts.Count
        Else
          Success = False
        End If
      Else
        Success = False
      End If
    Else
      Entity = finBL.Entities(WizardFinishParameters.EntityId)
      ExportId = String.Format("{0}.{1}", Entity.EntityId, Format(finBL.TimeZoneFunctions.GetCurrentDatabaseDateTime, "yyyyMMddhhmmss"))
      
      ' New Export
      Success = CreateCreditReportGenerate(WizardFinishParameters, CreditReportGenerate)
        
      ' Open Export
      If CreditReportGenerate.ExportOpen(WizardFinishParameters.EntityId, ExportId) Then
        ' Add Accounts, via Script
        If finBL.Scripts.ItemByPk(ScriptPk).ExecuteObjectEvents(EventScriptReturnValue, "ExportGenerate", True, CreditReportGenerate, -1, Nothing, Nothing, Nothing) Then
          Success = EventScriptReturnValue
        Else
          Success = False
        End If
        
        ' Always Close (ignore errors)
        CreditReportGenerate.ExportClose()
      Else 
        Success = False
      End If
      
      ' Export, don't fail using Success, use CountExported to determine whether anything was exported
      If Success Then
        CreditReportExport = finBL.CreateCreditReportExport()
        
        ' Set File Name. NOTE: The file name might have tags that get resolved in the CreditReportExport.Load function.
        ExportFileName = ""
        If Len(WizardFinishParameters.FileName) &lt;&gt; 0 Then
          ExportFileName = finBL.GetFileNameResolved(WizardFinishParameters.FileName)
        ElseIf Not WizardFinishParameters.FileExportFolder Then
          TemporaryFileName = finBL.Runtime.FileUtilities.GetTemporaryFileName("CreditReportExport", "xml")
          ExportFileName = TemporaryFileName
        End If         
        
        If CreditReportExport.Load(ExportId, ExportFileName) Then         
          If CreditReportExport.Execute() Then
            CountExported = CreditReportExport.Accounts.Count
          End If
        End If
      End If
    End If
  End If
  
  ' Validate
  If Success AndAlso CountExported = 0 Then
    If Not WizardFinishParameters.OptionReExportFile Then
      Success = False
      finBL.Error.ErrorBegin("Credit Report File was successfully generated, but failed to export.")
    End If
  End If
  
  ' Generate File
  If Success Then
    If CountExported &lt;&gt; 0 Then
      mProcessStatus.AddEvent_Information("Saving File")
      
      ' Create Export Package
      Success = finBL.HtmlWidgetUtilities.CreateProcessFileExportPackageHandler(ScriptInfo.ScriptCaption, ScriptInfo.ScriptId, FileExportPackageHandler)       
  
      If Success Then
        FileExportPackageHandler.CreateFileName(finBL.Runtime.FileUtilities.GetFileName(CreditReportExport.ExportInformation.ExportFileName))
        CloudFileName = FileExportPackageHandler.GetFullFileName(0)
        
        ' Update Package Status
        FileExportPackageHandler.StatusUpdateInProgress(0)
        
        ' Copy File in Export folder or temporary file to File Export Package Handler
        Success = finBL.Runtime.FileUtilities.CopyFile(CreditReportExport.ExportInformation.ExportFileName, CloudFileName)     
      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
            CloudFileName = FileExportPackageHandler.GetShortFileName(0)
          End If
        End If
      Else If FileExportPackageHandler IsNot Nothing Then
        Success = FileExportPackageHandler.StatusUpdateFailed()
      End If
    End If
  End If
  
  ' The above 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(CloudFileName)
    
    ' 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; CloudFileName)
      mProcessStatus.OtherDetails.SetString("ReportFileName", CloudFileName)
    End If
  End If  
  
  If Not Success Then
    ' Notify
    mProcessStatus.AddEvent_Error(finBL.Error.GetMessage(True, True, True))
  End If
  
  ' Always delete temporary files (ignore success)
  If Len(TemporaryFileName) &lt;&gt; 0 Then
    ' Ignore error
    finBL.Runtime.FileUtilities.DeleteFile(TemporaryFileName)
  End If
  
  Return Success
  
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;
'''  Creates a CreditReportGenerate
''' 
'''  NOTE: This is not required for a re-export. This function should only be used for new exports
''' &lt;/summary&gt;
''' &lt;param name="wizardFinishParameters"&gt;
'''  Wizard Finish Parameters.
''' &lt;/param&gt;
''' &lt;param name="CreditReportGenerate"&gt;
'''  The CreditReportGenerate which can be used to create a new CreditReportExport object.
''' &lt;/param&gt;
''' &lt;returns&gt;&lt;/returns&gt;
Private Function CreateCreditReportGenerate(wizardFinishParameters As WizardFinishParameters,
                                            ByRef creditReportGenerate As finCreditReportGenerate) As Boolean
  
  Dim Entity As finEntityRO              
  Dim Success As Boolean
  
  ' Assume Success
  Success = True
  
  ' Unpack
  With wizardFinishParameters
    Entity = finBL.Entities(.EntityId)
  End With
  
  ' Create the Export Generate
  creditReportGenerate = finBL.CreateCreditReportGenerate()
  With creditReportGenerate
    .Date = wizardFinishParameters.ExportDate
    If Entity.CreditReportingTestMode Then
      Select Case UCase(wizardFinishParameters.BatchType)
        Case "INITIAL" : .BatchType = isefinCreditReportingBatchType.TestInitial
        Case "CORRECTION" : .BatchType = isefinCreditReportingBatchType.TestCorrection
        Case Else : .BatchType = isefinCreditReportingBatchType.TestPeriodic
      End Select
    Else
      Select Case UCase(wizardFinishParameters.BatchType)
        Case "INITIAL" : .BatchType = isefinCreditReportingBatchType.Initial
        Case "CORRECTION" : .BatchType = isefinCreditReportingBatchType.Correction
        Case Else : .BatchType = isefinCreditReportingBatchType.Periodic
      End Select
    End If
    .EntityPk = Entity.Pk
  End With
  
  Return Success                            
                                            
End Function

''' &lt;summary&gt;
'''  Finish, i.e., Queue Background Process.
''' &lt;/summary&gt;
Private Function Finish(parametersJson As String,
                        ByRef returnValue As String) As Boolean

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

  ' Assume Success
  Success = True
  
  ' Initialise
  CompleteMessage = ""

  ' Get Wizard Finish Parameters
  Success = GetWizardFinishParameters(parametersJson, WizardFinishParameters)
  
  ' 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, mStartupParameters.ToSimpleJsonString(), ProcessId, mDesktopMode)
  End If
  
  ' Context-specific functionality
  If Success Then
    If mDesktopMode Then
      CompleteMessage = "Once complete, the file can be downloaded to this PC."
    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;= vbCrLf &amp; vbCrLf
      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

  ' Response
  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 Wizard Finish Parameters.
''' &lt;/summary&gt;
Private Function GetWizardFinishParameters(parametersJson As String,
                                           ByRef wizardFinishParameters As WizardFinishParameters) As Boolean

  Dim obj As Object
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

  Return Success

End Function                      

''' &lt;summary&gt;
'''  Get Batch Type List
'''  Also gets the default file name
''' &lt;/summary&gt;
Private Function RefreshBatchType(ByRef returnValue As String) As Boolean
                                  
  Dim DefaultBatchType As String
  Dim EntityId As String
  Dim List As ISList
  Dim Obj As Object
  Dim Success As Boolean
  
  ' Assume Success
  Success = True
  
  ' Initialise
  DefaultBatchType = ""
  List = finBL.Runtime.CreateList()  
  
  ' Parameters
  With mCombinedParameters
    EntityId = .GetString("EntityId")
  End With
  
  If finBL.Entities.Exists(EntityId) Then
    With finBL.Entities(EntityId)
      ' Get List      
      If .CreditReportingAllowBatchTypeInitial Then List.Add("Initial")
      If .CreditReportingAllowBatchTypePeriodic Then List.Add("Periodic")
      If .CreditReportingAllowBatchTypeCorrection Then List.Add("Correction")
    End With
    
    ' Get Default Value
    If List.Count = 1 Then
      DefaultBatchType = List(0)
    Else If List.Exists("Periodic") Then
      DefaultBatchType = "Periodic"
    End If
  End If
  
  ' Return Value
  obj = New With {
    .BatchTypeList = List.ToCsvString(),
    .DefaultBatchType = DefaultBatchType
  }
  
  ' Serialise
  Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(obj, returnValue)
  
  Return Success

End Function                                  

''' &lt;summary&gt;
'''  Validate a Wizard page.
''' &lt;/summary&gt;
''' &lt;param name="parametersJson"&gt;
'''  A JSON formatted object containing information required to validate a Wizard page.
''' &lt;/param&gt;
''' &lt;param name="returnValue"&gt;
'''  A JSON object; "true" if validation passed, otherwise, information as to why validation failed.
''' &lt;/param&gt;
Private Function WizardValidate(parametersJson As String,
                                ByRef returnValue As String) As Boolean

  Dim Data As Object
  Dim FailedControlId As String
  Dim FailedMessage As String
  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

  ' Get Wizard Finish Parameters
  Success = GetWizardFinishParameters(parametersJson, WizardFinishParameters)

  ' Validate Page
  If Success Then
    Select Case PageId
      Case "General"
        ' General
        Success = WizardValidate_General(WizardFinishParameters, Data)
        
      Case "ExportOptions"
        ' Export Options
        Success = WizardValidate_ExportOptions(WizardFinishParameters, Data)
        
    End Select
  End If

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

  Return Success

End Function

Private Function WizardValidate_General(wizardFinishParameters As WizardFinishParameters,
                                        ByRef data As Object) As Boolean
                                  
  Dim DefaultFilePath As String                                        
  Dim Success As Boolean
  
  ' Assume Success
  Success = True
  
  ' Validate
  ' (no validation)
  
  ' Get default file path
  DefaultFilePath = finBL.Entities(wizardFinishParameters.EntityId).CreditReportingExportFilename
  
  data = New With {
    .DefaultFilePath = DefaultFilePath
  }
  
  Return Success
                                        
End Function

Private Function WizardValidate_ExportOptions(wizardFinishParameters As WizardFinishParameters,
                                              ByRef data As Object) As Boolean

  Dim ConfirmList As ISList                                              
  Dim CreditReportGenerate As finCreditReportGenerate                                              
  Dim Success As Boolean
  
  ' Assume Success
  Success = True
  
  ' Get CreditReportGenerate
  Success = CreateCreditReportGenerate(wizardFinishParameters, CreditReportGenerate)
  
  ' Validate
  If CreditReportGenerate.ExportValidate(ConfirmList) Then
    If ConfirmList.Count &lt;&gt; 0 Then
      data = ConfirmList
    End If
  End If
  
  Return Success
                                              
End Function                                              

''' &lt;summary&gt;
'''  Existing Exports Sort Comparer.
''' &lt;/summary&gt;
Private Function GetExistingExports_SortComparer(x As CreditReportExportItem,
                                                 y As CreditReportExportItem) As Integer

  If x.CreatedUtcDate &lt; y.CreatedUtcDate Then
    Return 1
  ElseIf x.CreatedUtcDate &gt; y.CreatedUtcDate Then
    Return -1
  Else
    Return 0
  End If

End Function



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

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

  ' General
  Public ExportDate As Date  
  
  ' Permissions

  ' Configuration
  Public [ReadOnly] As Boolean
  Public AutoCommit As Boolean
  Public DesktopMode As Boolean
  Public EmailWhenComplete As Boolean
  Public ExistingExportBatchLimitDays As Integer
  Public PromptOnCommit As Boolean
  
  ' Collections
  Public ExportBatchesJson As String

End Class


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

  ' Parameters
  Public OptionCreateFile As Boolean
  Public OptionReExportFile As Boolean
  
  ' General
  Public EntityId As String
  Public BatchType As String
  Public ExportDate As Date

  ' Export
  Public FileDownload As Boolean
  Public FileExportFolder As Boolean
  Public FileLocation As Boolean
  Public FileName As String

  ' Re-Export
  Public ExportId As String

  ' Other
  Public ProcessId As String

End Class



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

  Public Data As Object
  Public FailedControlId As String
  Public FailedMessage 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;
'''  Export Item
''' &lt;/summary&gt;
Public Class CreditReportExportItem
  
  Public BatchDate As Date  
  Public BatchTypeText As String
  Public CreatedUser As String  
  Public CreatedUtcDate As Date    
  Public ExportId As String  
  Public EntityId As String
  
  Public Sub New(row As DataRow)
    
    With finBLShared.Database
      Me.BatchDate = finBLShared.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(.GetFieldDate(row("Date")))   
      Me.BatchTypeText = finBLShared.Enums.isefinCreditReportingBatchType_ToString(DirectCast(.GetFieldEnum(row("Type"), GetType(isefinCreditReportingBatchType)), isefinCreditReportingBatchType))   
      Me.CreatedUser = .GetFieldString(row("CreatedUser"))
      Me.CreatedUtcDate = finBLShared.HtmlWidgetUtilities.GetJsonUtcDateTimeFromDatabaseDateTime(finBLShared.TimeZoneFunctions.ConvertUtcToLocalDateTime(.GetFieldDate(row("CreatedUtcDate"))))
      Me.ExportId = .GetFieldString(row("CreditReportExportId"))      
      Me.EntityId = .GetFieldString(row("EntityId"))
    End With
  End Sub
End Class</Code>
    <Language>VisualBasic</Language>
    <Notes>System defined HTML Widget.

Used as a finPOWER Connect Cloud compatible version of the form "CreditReportExport".</Notes>
    <PermissionKeyExecute />
    <RunWithoutPrompts>false</RunWithoutPrompts>
    <TemplateText>&lt;style type="text/less"&gt;
/* Total Summary */
.value-summary {
  display:flex;
  flex-direction:row;

  .refresh-warning {
    padding-right:16px;
    color:red;
    font-weight:bold;
  }

  div {
    font-size:11px;

    &gt; b {
      font-size:14px;
    }
  }
}

/* Small device portrait */
@media screen and (max-width:640px) {
  .value-summary {
    flex-direction:column;
    font-size:12px;
  }
}
&lt;/style&gt;

&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="Drilldown to view the status of current and recent Credit Report Exports you have processed."&gt;Recent Credit Report Exports&lt;/li&gt;
        &lt;li tabId="General" tooltipText="Create new Credit Report Export or select an existing Credit Report Export to Re-Export or Download."&gt;General&lt;/li&gt;
        &lt;li tabId="ExportOptions" tooltipText="Enter Export Details."&gt;Export Details&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;div style="display:flex; flex-direction:column; position:absolute; top:0; left:0; right:0; bottom:0; padding:4px"&gt;
        &lt;div&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="lblOptionCreate"&gt;Create a new Comprehensive Credit Report Export&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;input id="chkOptionCreateFile" type="checkbox" /&gt;&lt;/th&gt;
            &lt;/tr&gt;

            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblOptionReExport"&gt;Re-Export a Comprehensive Credit Report File&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;input id="chkOptionReExportFile" type="checkbox" /&gt;&lt;/th&gt;
            &lt;/tr&gt;

            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblEntity"&gt;Select the Entity to Export&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="cboEntity"&gt;Entity:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="cboEntity" /&gt;&lt;/td&gt;
            &lt;/tr&gt;

            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblOptions"&gt;Export options&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="cboBatchType"&gt;Batch Type:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="cboBatchType" /&gt;&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="dateExportDate"&gt;Date:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="dateExportDate" /&gt;&lt;/td&gt;
            &lt;/tr&gt;

            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblComprehensiveCreditReportFiles"&gt;Comprehensive Credit Report Files&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;
          &lt;/table&gt;
        &lt;/div&gt;

        &lt;!-- Existing Credit Report Exports --&gt;
        &lt;div style="position:relative; flex-grow:1; max-width:1280px; margin-left:8px"&gt;
          &lt;div id="gridComprehensiveCreditReportFiles" class="is-dock-fill"&gt;&lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;

    &lt;!-- Export Options --&gt;
    &lt;div id="pageExportOptions"&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="lblFileName"&gt;Select the desired location and name of the file to export&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkFileDownload" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkFileLocation" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkFileExportFolder" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtFileName"&gt;File Name:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtFileName" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;div id="divFileName" class="is-info-text info small"&gt;&lt;/div&gt;&lt;/th&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;Commit&lt;/button&gt;
  &lt;/footer&gt;
&lt;/div&gt;

&lt;script&gt;
// Properties
var mRecord;
var mRecord_BackgroundProcessStatus;
var mRecord_CreditReportExports;
var mRecord_CurrentProcesses;
var mRecord_BatchInfo;

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

  //   General
  lblOptionCreate: null,
  chkOptionCreateFile: null,

  lblOptionReExport: null,
  chkOptionReExportFile: null,
  
  lblEntity: null,
  cboEntity: null,
  
  lblOptions: null,
  cboBatchType: null,
  dateExportDate: null,

  lblComprehensiveCreditReportFiles: null,
  gridComprehensiveCreditReportFiles: null,

  //   Export Options
  lblFileName: null,
  chkFileDownload: null,
  chkFileLocation: null,
  chkFileExportFolder: null,
  txtFileName: null,
  divFileName: null,

  //   Progress
  divProgress: null,
}

// Form
var frmMain;
var tabWizard;

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

var cmdHistory;

// Other
var mAdvancedVisible = false;
var mComplete = false;
var mComplete_Information;
var mDefaultFilePath = ""
var mFromRecent = false;
var mMonitoringExisting = false;
var mProcessId;
var mShowAllExisting = false;

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

  // Controls
  //   General
  C.lblOptionCreate = widget.UI.Label("lblOptionCreate", {});
  C.chkOptionCreateFile = widget.UI.CheckBox("chkOptionCreateFile", {
    caption: "Create a new Export File?",
    captionWrap: true,
    cssClass: "is-radio-button",

    onChange: chkOption_Change,
  });

  C.lblOptionReExport = widget.UI.Label("lblOptionReExport", {});
  C.chkOptionReExportFile = widget.UI.CheckBox("chkOptionReExportFile", {
    caption: "Re-Export an existing File?",
    captionWrap: true,
    cssClass: "is-radio-button",

    onChange: chkOption_Change,
  });
  
  C.lblEntity = widget.UI.Label("lblEntity", {});
  C.cboEntity = widget.UI.DBCombo("cboEntity", {
    limitToList: true,
    allowBlank: false,
    
    onChange: cboEntity_Change
  });
  
  C.lblOptions = widget.UI.Label("lblOptions", {});
  C.cboBatchType = widget.UI.ComboBox("cboBatchType", {
    limitToList: true,
    allowBlank: false
  });
  C.dateExportDate = widget.UI.DateBox("dateExportDate", {});

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

  //   Export Options
  C.lblFileName = widget.UI.Label("lblFileName", {});
  C.chkFileDownload = widget.UI.RadioButton("chkFileDownload", {
    caption: "finPOWER Connect Cloud Download",
    captionWrap: true,

    onChange: FileLocation_Change,
  });
  C.chkFileLocation = widget.UI.RadioButton("chkFileLocation", {
    caption: "File Location",
    captionWrap: true,

    onChange: FileLocation_Change,
  });
  C.chkFileExportFolder = widget.UI.RadioButton("chkFileExportFolder", {
    caption: "Export Folder",
    captionWrap: true,

    onChange: FileLocation_Change,
  });
  C.txtFileName = widget.UI.TextBox("txtFileName", {
    allowBlank: false,
    maxLength: 255,
  });
  C.divFileName = $("#divFileName");

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

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

    onAction: gridCurrentProcesses_Action,
    onAfterRowActivate: gridCurrentProcesses_AfterRowActivate,
    onInitialiseRow: gridCurrentProcesses_InitialiseRow,
    onRowDrilldown: gridCurrentProcesses_RowDrilldown,
  });

  C.gridComprehensiveCreditReportFiles = widget.UI.Grid("gridComprehensiveCreditReportFiles", {
    allowCellSelect: false,
    allowMultiRowSelect: false,
    docked: true,
    showRowSelectors: true,
    stickyHeader: true,
    rowNumbering: true,

    onAction: gridComprehensiveCreditReportFiles_Action,
    onInitialiseRow: gridComprehensiveCreditReportFiles_InitialiseRow,
    onRowDrilldown: gridComprehensiveCreditReportFiles_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"); });

  // Handle Notifications
  widget.DisableCloseButton();
  widget.ActionNotificationHandle(Widget_NotificationHandler);

  // Reset
  Form_Reset();
});

// ==========
// Form Reset
// ==========
function Form_Reset() {
  // Defaults
  C.chkOptionCreateFile.Value(true);
  C.chkOptionReExportFile.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_CreditReportExports = null;
  mRecord_CurrentProcesses = 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;
      mRecord_CreditReportExports = JSON.parse(mRecord.ExportBatchesJson);

      // Load Fields
      Fields_Load();

      // Notify if there are Current Processes
      var countCurrent = 0;
      var processIndex = -1;
      for (var i = 0; i &lt; mRecord_CurrentProcesses.length; i++) {
        var item = mRecord_CurrentProcesses[i];

        // Process
        if (mRecord.ProcessId &amp;&amp; mRecord.ProcessId == item.ProcessId) {
          processIndex = i;
        }

        // Status
        switch (item.Status) {
          case "Pending":
          case "PendingCommit":
          case "InProgress":
          case "InProgressRefreshComplete":
          case "InProgressCancelRequested":
            countCurrent += 1;
            break;
        }
      }
      if (processIndex != -1) {
        ViewExistingProcess(processIndex);
      }
      else if (countCurrent != 0) {
        tabWizard_Move(-1);
        widget.UI.MsgBoxInfo("There are existing incomplete Credit Report Transaction exports that you have started and are not yet complete.\n\nYou can review these or use the 'Next &gt;' button to begin a new instance of Credit Report Export.", { heading: "Credit Reports still Exporting", 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();
  }
  
  // General
  if (mRecord) {
    C.dateExportDate.Value(mRecord.ExportDate);
  }

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

  // Update Controls
  pageGeneral_Refresh();

  // Update fields
  Fields_Update();

  // Refresh Tab
  tabWizard_Refresh();
}

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

  if (mRecord) {
    // Lists
    C.cboEntity.RefreshFromStandardRange("Entities", "", false, "", "", null);
  }

  // Update Buttons
  if (mRecord) {
    tabWizard_UpdateButtons();
  }

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

  // Resize
  tabWizard_Resize();
}

// ======================================
// Updates Fields from Background Process
// ======================================
function Fields_Update_FromBackgroundProcess() {
  var service = "";

  // Reset
  C.chkOptionCreateFile.Value(false);
  C.chkOptionReExportFile.Value(false);

  // Refresh Page
  pageGeneral_Refresh();
  
  // Update Controls - must happen after pageGeneral_Refresh as this will try and reset them
  if (service) C.cboService.Text(service);
}

function tabWizard_Refresh(newTab) {
  // Moving forward onto tab, so Load information
  if (newTab &gt;= tabWizard.SelectedTabIndex()) {
    switch (tabWizard.GetTabIdByIndex(newTab)) {
      case "ExportOptions":
        pageExportOptions_Refresh();
        break;
    
      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;

      // Reset Objects
      mProcessId = null;
      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;
  }
}

// ========================
// Create Finish Parameters
// ========================
function CreateFinishParameters() {
  var params = {
    optionCreateFile: C.chkOptionCreateFile.Value(),
    optionReExportFile: C.chkOptionReExportFile.Value(),
  }

  // File
  if (C.chkOptionCreateFile.Value()) {
    params.ProcessId = mProcessId;
    params.EntityId = C.cboEntity.Text();
    params.BatchType = C.cboBatchType.Text();
    params.ExportDate = C.dateExportDate.Value();
  }

  // Items from Grid
  if (C.chkOptionReExportFile.Value()) {
    if (C.gridComprehensiveCreditReportFiles.ActiveDataRowListIndex() != -1) {
      var item = mRecord_CreditReportExports[C.gridComprehensiveCreditReportFiles.ActiveDataRowListIndex()];

      params.EntityId = item.EntityId;
      params.ExportId = item.ExportId;
    }
  }

  // File Export Options
  if (C.chkOptionCreateFile.Value() || C.chkOptionReExportFile.Value()) {
    params.FileDownload = C.chkFileDownload.Value();
    params.FileLocation = C.chkFileLocation.Value();
    params.FileExportFolder = C.chkFileExportFolder.Value();
    if (params.FileDownload || params.FileLocation) params.FileName = C.txtFileName.Text();
  }

  return params;
}

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

    case "RECENT":
      // Recent
      tabWizard_Refresh(tabWizard.GetTabIndexById("CurrentProcesses"));
      break;

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

// =============
// Finish Action
// =============
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 effect immediately.", {}, function () { Form_ExecuteAction_FinishStop(); }, null);
  }
  else {
    // Validate
    tabWizard_Validate(function () {
      // Confirmation Message
      var heading = "Run Comprehensive Credit Report Export";
      var message = "";

      // Build Message
      if (C.chkOptionReExportFile.Value()) {
        var ExportId = mRecord_CreditReportExports[C.gridComprehensiveCreditReportFiles.ActiveDataRowListIndex()].ExportId;
        message += "Are you sure you want to re-export Credit Report '" + ExportId + "'?";
      }
      else {
        message += "Are you sure you want to Export Credit Report?";
      }

      // Background Process
      message += "\n\nNOTE: This may take some time. You can close this form at any time and open it again to monitor progress.";

      // Confirm
      widget.UI.MsgBoxConfirm(message, 
                              {
                                heading: heading,
                                icon: "Report",
                                messageIsHtml: false
                              }, 
                              Form_ExecuteAction_FinishPost, 
                              null);
    });
  }
}

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

  // Clear Progress Page
  pageProgress_Refresh(true);

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

  // Create 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 (error) {
      // Show Error
      widget.UI.MsgBoxAlert(error);

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

function Form_ExecuteAction_FinishStop() {
  // Continue
  widget.GetString("CancelBackgroundProcess", { ProcessId: mProcessId },
    function (data) {
      widget.UI.MsgBoxInfo("The process has been requested to stop.");
    },

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

function Form_ExecuteAction_GetBackgroundProcessStatus() {
  // Params
  var params = {
    processId: mProcessId,
    lastEventId: mLastEventId
  }

  // Continue
  widget.GetString("GetBackgroundProcessStatus", params,
    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("Credit Report Export was sucessfully 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("Credit Report Export 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 Credit Report Exports, 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);
    }
  );
}

// ===========
// pageGeneral
// ===========
function pageGeneral_Refresh() {
  // Hide all controls
  C.lblEntity.VisibleRow(false);
  C.cboEntity.VisibleRow(false);
  C.lblOptions.VisibleRow(false);
  C.cboBatchType.VisibleRow(false);
  C.dateExportDate.VisibleRow(false);
  
  C.lblComprehensiveCreditReportFiles.VisibleRow(false);
  C.gridComprehensiveCreditReportFiles.Visible(false);  

  // Show Controls
  if (C.chkOptionCreateFile.Value()) {
    C.lblEntity.VisibleRow(true);
    C.cboEntity.VisibleRow(true);
    C.lblOptions.VisibleRow(true);
    C.cboBatchType.VisibleRow(true);
    C.dateExportDate.VisibleRow(true);
  }
  else if(C.chkOptionReExportFile.Value()) {
    C.lblComprehensiveCreditReportFiles.VisibleRow(true);
    C.gridComprehensiveCreditReportFiles.Visible(true);

    // Update Grid
    gridComprehensiveCreditReportFiles_Refresh();
  }

  // Update Buttons
  tabWizard_UpdateButtons();
}

// =================
// pageExportOptions
// =================
function pageExportOptions_Refresh() {
  C.chkFileDownload.Value(!mRecord.DesktopMode);
  C.chkFileLocation.Value(mRecord.DesktopMode);
  C.chkFileExportFolder.Value(false);
  
  // Default to file name set on the Entity
  if (mDefaultFilePath) {
    C.txtFileName.Text(mDefaultFilePath);
  }

  // Update Controls
  FileLocation_Change();
}

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

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

function Form_Resize() {
  // General

  // Tab
  tabWizard_Resize();
}

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

    // Actions
    C.gridCurrentProcesses.Actions().Define([{ actionId: "Cancel", caption: "Cancel", tooltipText: "Cancel the selected 'Refresh Complete' row", icon: "Trash" }]);
  }

  // Determine if Actions should be visible
  var found = false;
  for (var i = 0; i &lt; mRecord_CurrentProcesses.length; i++) {
    var item = mRecord_CurrentProcesses[i];

    if (item.Status == "InProgressRefreshComplete") {
      found = true;
      break;
    }
  }
  C.gridCurrentProcesses.Actions().SetVisible("Cancel", found);

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

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

function gridCurrentProcesses_Action(actionId) {
  var item = mRecord_CurrentProcesses[C.gridCurrentProcesses.ActiveDataRowListIndex()];

  switch (actionId.toUpperCase()) {
    case "CANCEL":
      // Cancel
      CancelRefreshCompleteBackgroundProcess(item.ProcessId, false, pageCurrentProcesses_Refresh);
      break;

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

function gridCurrentProcesses_AfterRowActivate(e) {
  // Refresh Buttons
  gridCurrentProcesses_RefreshButtons();
}

function gridCurrentProcesses_RefreshButtons() {
  if (C.gridCurrentProcesses.ActiveDataRowListIndex() == -1) {
    C.gridCurrentProcesses.Actions().SetEnabled("Cancel", false);
  }
  else {
    var item = mRecord_CurrentProcesses[C.gridCurrentProcesses.ActiveDataRowListIndex()];
    C.gridCurrentProcesses.Actions().SetEnabled("Cancel", item.Status == "InProgressRefreshComplete");
  }

  C.gridCurrentProcesses.RefreshButtons();
}

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":
    case "InProgressRefreshComplete":
      e.row.bold = true;
      break;
  }
}

function gridCurrentProcesses_RowDrilldown(e) {
  ViewExistingProcess(e.row.listIndex);
}

// ==================================
// gridComprehensiveCreditReportFiles
// ==================================
function gridComprehensiveCreditReportFiles_Refresh() {
  var showNotes = false;

  // Show / Hide Columns
  for (var i = 0; i &lt; mRecord_CreditReportExports.length; i++) {
    var item = mRecord_CreditReportExports[i];

    // Warnings
    if (item.Notes) showNotes = true;
  }

  // Add Columns
  C.gridComprehensiveCreditReportFiles.ClearColumns();
  C.gridComprehensiveCreditReportFiles.AddColumnCode("EntityId", { caption: "Entity", sortable: true });
  C.gridComprehensiveCreditReportFiles.AddColumnString("ExportId", { caption: "Export Id", sortable: true, width: widget.UI.FIELD_WIDTH_CODE_25 });
  C.gridComprehensiveCreditReportFiles.AddColumnString("BatchTypeText", { caption: "Type", sortable: true });
  C.gridComprehensiveCreditReportFiles.AddColumnDate("BatchDate", { caption: "Date", sortable: true });
  C.gridComprehensiveCreditReportFiles.AddColumnString("CreatedUser", { caption: "Creator", sortable: true });
  C.gridComprehensiveCreditReportFiles.AddColumnDateTime("CreatedUtcDate", { caption: "Created", sortable: true });

  // Actions
  C.gridComprehensiveCreditReportFiles.Actions().Define([{ actionId: "ShowAll", caption: "Show all? (If not toggled, only Exports created in the last " + mRecord.ExistingExportBatchLimitDays + " days will be shown)", checked: mShowAllExisting }]);

  // Refresh
  // NOTE: Retain active row when selecting different export options
  C.gridComprehensiveCreditReportFiles.VirtualDataRefresh(mRecord_CreditReportExports, true);

  // Select first row
  C.gridComprehensiveCreditReportFiles.ActivateFirstDataRow(true);
}

function gridComprehensiveCreditReportFiles_InitialiseRow(e) {
  var item = mRecord_CreditReportExports[e.row.listIndex];

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

function gridComprehensiveCreditReportFiles_Action(actionId) {
  switch (actionId.toUpperCase()) {
    case "SHOWALL":
      mShowAllExisting = !mShowAllExisting;
      
      // Block UI
      widget.UI.Block("Initialising, please wait...");
      
      // Params
      var params = {
        showAllExisting: mShowAllExisting
      }
      
      // Get Data
      widget.GetString("GetExistingExports", params, function(data) {  
        // Parse
        if (data) mRecord_CreditReportExports = JSON.parse(data);
        
        // Refresh Grid
        gridComprehensiveCreditReportFiles_Refresh();
        
        // Unblock UI
        widget.UI.Unblock();
      },      
      function(errorMessage) {
        // Unblock UI
        widget.UI.Unblock();
      
        // Error
        widget.UI.MsgBoxAlert(errorMessage);
      });
      break;
  }
}

function gridComprehensiveCreditReportFiles_RowDrilldown(e) {
  if (C.chkOptionReExportFile.Value()) {
    tabWizard_Move(1);
  }
}


// ==========
// Tab Wizard
// ==========
function tabWizard_Cancel() {
  // Executing?
  if (mComplete) {
    tabWizard_Cancel_Post();
  }
  else if (mRecord_BackgroundProcessStatus &amp;&amp; !mMonitoringExisting) {
    // Still Running
    widget.UI.MsgBoxConfirm("Credit Report Export 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_Save() {
  // Block UI
  widget.UI.Block("Saving, please wait...");

  // Parameters
  var params = CreateFinishParameters();

  // Update Refresh Data
  widget.GetString("UpdateRefreshData", params, tabWizard_Cancel_Post, function(errorMessage) {
    // Unblock
    widget.UI.Unblock();

    // Error
    widget.UI.MsgBoxAlert(errorMessage);
  });
}

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

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)) {
        case "ExportOptions":
          found = (C.chkOptionCreateFile.Value() || C.chkOptionReExportFile.Value());
          break;

        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_Resize() {
  switch (tabWizard.SelectedTabId()) {
    case "General":
      C.cboEntity.WidthResizeFromParent();
      break;

    default:
      break;
  }
}

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

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

  // Never allow moving back from Progress page
  if (tabWizard.SelectedTabId() == "Progress") cmdBack.prop("disabled", true);

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

  // Re-Export
  if (C.chkOptionReExportFile.Value() &amp;&amp; tabWizard.SelectedTabId() == "ExportOptions") {
    cmdNext.prop("disabled", true);
    cmdFinish.prop("disabled", false);
  }
}

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

  // Other client-side validation
  if (Ok) {
    switch (tabWizard.SelectedTabId()) {
      case "General":
        // Has server-side validation
        break;

      case "ExportOptions":
        if (C.chkFileLocation.Value()) {
          if (C.txtFileName.Text().indexOf("/") == -1 &amp;&amp; C.txtFileName.Text().indexOf("\\") == -1) {
            Ok = false;
            widget.UI.MsgBoxAlert("A full file name including folder must be specified.");
          }
        }
        break;

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

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

    switch (tabWizard.SelectedTabId()) {
      case "General":
      case "ExportOptions":
        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
  var o = {};
  
  if (data) o = JSON.parse(data);

  if (o.FailedMessage) {
    // -----------------
    // Validation failed
    // -----------------
    var o = JSON.parse(data);
    widget.UI.MsgBoxAlert(o.FailedMessage);
    if (o.FailedControlId) $("#" + o.FailedControlId).focus();
  }
  else {
    // ---------------------
    // Validation successful
    // ---------------------
    // Validation could pass back additional information, e.g., to use in tabWizard_Refresh
    switch (tabWizard.SelectedTabId()) {
      case "General":
        // General      
        if (o.Data.DefaultFilePath) {
          // Set the default file path
          mDefaultFilePath = o.Data.DefaultFilePath;
        }          
        if (o.Data.ConfirmList &amp;&amp; o.Data.ConfirmList.length != 0) {
          // Confirm warnings
          widget.UI.MsgBoxConfirmList("To continue, please approve the following:",
                                      o.Data.ConfirmList,
                                      {
                                        heading: "Additional Confirmation",
                                        icon: "Warning",
                                      },
                                      function () { validCallback(); },
                                      null);

          // Allow callbacks to continue
          return;
        };      
        break;
      
      case "ExportOptions":
        // Export Options
        if (o.Data &amp;&amp; o.Data.length != 0) {
          // Confirm warnings
          widget.UI.MsgBoxConfirmList("To continue, please approve the following:",
                                      o.Data,
                                      {
                                        heading: "Additional Confirmation",
                                        icon: "Warning",
                                      },
                                      function () { validCallback(); },
                                      null);

          // Allow callbacks to continue
          return;
        };      
        break;
    }

    // Callback
    validCallback();
  }
}

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

  // Enable form
  frmMain.FormEnable();
}

// ==========================================
// Cancel Refresh Complete Background Process
// ==========================================
function CancelRefreshCompleteBackgroundProcess(processId, noPrompt, callback, cancelCallback) {
  if (noPrompt) {
    // Cancel immediately
    CancelRefreshCompleteBackgroundProcess_Execute(processId, callback);
  }
  else {
    // Prompt
    widget.UI.MsgBoxConfirm("Are you sure you want to cancel this Background Process?", {},
      function() {
        CancelRefreshCompleteBackgroundProcess_Execute(processId, callback);
      },

      cancelCallback
    );
  };
}

function CancelRefreshCompleteBackgroundProcess_Execute(processId, callback) {
  // Block
  widget.UI.Block("Cancelling Background Process, please wait...");

  // Params
  var params = {
    processId: processId,
  }

  widget.GetString("CancelBackgroundProcess", params, function() { callback(); }, function(errorMessage) {
    // Unblock UI
    widget.UI.Unblock();

    // Error
    widget.UI.MsgBoxAlert(errorMessage);
  });
}

// ===================================
// View an existing Background Process
// ===================================
function ViewExistingProcess(itemIndex) {
  var item = mRecord_CurrentProcesses[itemIndex];
  var Ok = true;

  // NOTE: This Widget is Single phase - it doesn't have a refresh phase.

  if (Ok) {
    // Set Information from Process
    mProcessId = item.ProcessId;

    // Status-dependant
    switch (item.Status) {
      default:
        mFromRecent = true;
        mMonitoringExisting = true;

        // Switch to Progress Page
        tabWizard_Refresh(tabWizard.GetTabIndexById("Progress"));
        pageProgress_Refresh(true);

        // Start monitoring
        Form_ExecuteAction_GetBackgroundProcessStatus();
        break;
    }
  }
}

// ==================
// Options Checkboxes
// ==================
function chkOption_Change(sender, e) {
  C.chkOptionCreateFile.Value(sender == C.chkOptionCreateFile);
  C.chkOptionReExportFile.Value(sender == C.chkOptionReExportFile);

  // Refresh Page
  pageGeneral_Refresh();
}

// ======
// Entity
// ======
function cboEntity_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  // Block
  widget.UI.Block();
  
  var params = {
    EntityId: C.cboEntity.Text()
  };

  // Refresh BatchType list
  widget.GetString("RefreshBatchType", params, function(data) {      
      // Unblock
      widget.UI.Unblock();
      
      // Parse
      if (data) {
        mRecord_BatchInfo = JSON.parse(data);
      }
      
      if (mRecord_BatchInfo) {
        C.cboBatchType.ListFromCsvString(mRecord_BatchInfo.BatchTypeList);
        C.cboBatchType.Text(mRecord_BatchInfo.DefaultBatchType);
      }
    }, 
    function(errorMessage) {
      // Unblock
      widget.UI.Unblock();
      
      // Error
      widget.UI.MsgBoxAlert(errorMessage);
    }
  );  
}

// ====================
// File Location Change
// ====================
function FileLocation_Change(sender, e) {
  if (sender &amp;&amp; e) {
    C.chkFileDownload.Value(sender == C.chkFileDownload);
    C.chkFileLocation.Value(sender == C.chkFileLocation);
    C.chkFileExportFolder.Value(sender == C.chkFileExportFolder);
  }

  // Reset Controls
  C.txtFileName.ReadOnly(false);

  // Update Controls and Set Message
  var message = "";
  if (C.chkFileDownload.Value()) {
    message = "Only a File Name (without folder information) is required. If a folder has been specified, it will be ignored.";
  }
  else if(C.chkFileLocation.Value()) {
    message = "A full File Name (including folder) is required and must be available on the server.";
  }
  else if(C.chkFileExportFolder.Value()) {
    C.txtFileName.ReadOnly(true);
    
    // Default to folder defined on Entity. 
    if (mDefaultFilePath) {
      C.txtFileName.Text(mDefaultFilePath);
    }
    message = "A file name will automatically be generated. The file will be saved in the finPOWER export folder."
  }

  // Default file name button enabled status should match the text box
  C.txtFileName.Buttons().Visible(!C.txtFileName.ReadOnly());

  // Show message
  if (message) {
    C.divFileName.html(message);
    C.divFileName.show();
  }
  else {
    C.divFileName.hide();
  }
}


// ====================
// Notification Handler
// ====================
function Widget_NotificationHandler(actionId, data) {
  switch(actionId.toUpperCase()) {
    case "FORMCLOSE":
      // Closing Form
      tabWizard_Cancel();
      break;

    default:
      break;
  }
}

&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <UniqueId>1NRx5mEvKUu3uFPkfRrteQ</UniqueId>
    <AllowRefresh>true</AllowRefresh>
    <Caption />
    <HtmlWidgetAllowInitialEventCaching>false</HtmlWidgetAllowInitialEventCaching>
    <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>
    <HtmlWidgetSpecialEventShowAsSummaryPage>false</HtmlWidgetSpecialEventShowAsSummaryPage>
    <HtmlWidgetSummaryPageObjectType>None</HtmlWidgetSummaryPageObjectType>
    <Icon>CreditReporting</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>Form options.</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="ExistingExportBatchLimitDays" type="Number">
            <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>
            <DecimalPlaces>0</DecimalPlaces>
            <GroupDigits>true</GroupDigits>
            <MaxValue />
            <MinValue />
            <NumberSpecialType>None</NumberSpecialType>
            <SpinChange>1</SpinChange>
          </Parameter>
          <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>