<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2022-09-23T00:23:21.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2022-09-22T23:45:29.8500000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2022-09-23T00:22:25.6400000</UpdatedUtcDate>
    <ScriptId>BTR</ScriptId>
    <Description>Account Bank Transaction Reverse</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_AccountBankTransactionReverse
Option Explicit On
Option Strict On

' #################################################################
' Account Bank Transaction Reverse wizard HTML Widget
'
' Version: 1.06 (23/09/2022)
'
' Usage: System-defined HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.04  30/07/2021  ISS                Updated
'    1.05  09/02/2022  ISS      J028245   Added support for Refund Reversal
'          16/02/2022  ISS      J028113   Reinstated support for Document generation
'    1.06  23/09/2022  ISS      J029639   Added support for "Id" Parameter
' #################################################################

' Constants
Private Const FORM_KEY As String = "AccountBankTransactionReverse"

' Common Parameters
Private mBankTransactionPk As Integer
Private mShowSummary As Boolean
Private mIsBankInterfaceReversal As Boolean

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

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

  ' Assume Success
  Main = True

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

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

  ' Get Common Parameters
  With mCombinedParameters    
    mBankTransactionPk = .GetInteger("BankTransactionPk")
    mShowSummary = .GetBoolean("ShowSummary")    
    
    If mBankTransactionPk = 0 AndAlso .GetInteger("Id") &lt;&gt; 0 Then
      mBankTransactionPk = .GetInteger("Id")
      mIsBankInterfaceReversal = True
    End If
  End With

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

    Case "Finish"
      ' Finish wizard
      Main = Finish(parametersJson, requestInfo, returnValue)

    Case "Form_ReschedulePayment_Change"
      ' Get updated Reschedule Payment information
      Main = Form_ReschedulePayment_Change(parametersJson, 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 Function

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

  Dim BankTransactionReverse As finBankTransactionReverse
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim Message As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Validate
  If mBankTransactionPk = 0 Then
    Success = False
    finBL.Error.ErrorBegin("Bank Transaction Pk not specified.")
  ElseIf mBankTransactionPk &lt; 0 Then
    Success = False
    finBL.Error.ErrorBeginFormat("Invalid Bank Transaction Pk {0}.", mBankTransactionPk)
  ElseIf finBL.Database.IsReadOnly Then
    Success = False
    finBL.Error.ErrorBegin("Access denied. Database is Read-Only.")
  End If

  ' Create Bank Transaction Reverse object
  If Success Then
    Success = CreateBankTransactionReverse(Nothing, BankTransactionReverse)
  End If

  ' Validate Bank Transaction
  If Success Then
    If Not BankTransactionReverse.BankTransactionView.CanReverse(Message) Then
      Success = False
      finBL.Error.ErrorBegin(Message)
    End If
  End If

  ' Get Initialisation Info
  If Success Then
    FormInitialisationInfo = New FormInitialisationInfo()
    With FormInitialisationInfo
      ' Account Properties
      .RecordId = BankTransactionReverse.BankTransactionView.AccountTransactions(0).AccountId
      .RecordDescription = BankTransactionReverse.BankTransactionView.AccountTransactions(0).AccountName

      ' Lists
      Select Case BankTransactionReverse.BankTransactionView.ElementType
        Case isefinElementType.Investment, isefinElementType.InvestmentAdditional, isefinElementType.PaymentReceived
          .ReasonInformationListId = "AccountPayReverseReason"
        Case isefinElementType.Refund, isefinElementType.Withdrawal
          .ReasonInformationListId = "AccountWdlReverseReason"
      End Select
      .WorkflowTypeFilter = finBL.HtmlWidgetUtilities.EncryptSql(finBL.WorkflowTypes.GetDataViewFilterAccounts())
      Success = GetDocuments(BankTransactionReverse, .Documents)

      If Success Then
        ' Reason
        If Len(.ReasonInformationListId) &lt;&gt; 0 AndAlso finBL.InformationLists.Exists(.ReasonInformationListId) Then
          .Reason = finBL.InformationLists(.ReasonInformationListId).DefaultValue
        End If

        ' General
        .BankTransactionPk = mBankTransactionPk
        .IsBankInterfaceReversal = mIsBankInterfaceReversal
        .FeeCharge = BankTransactionReverse.FeeCharge
        .FeeValue = BankTransactionReverse.FeeValue
        .Reference = BankTransactionReverse.TransactionReference
        .ReschedulePayment = BankTransactionReverse.ReschedulePayment
        .ReschedulePaymentDate = finBL.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(BankTransactionReverse.ReschedulePaymentDate)
        .ReversalDate = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(BankTransactionReverse.ReversalDate)
        .Value = -BankTransactionReverse.BankTransactionView.Value        
        
        ' Account Summary
        .BankTransactionSummaryHtml = finBL.SummaryPageFunctions.BankTransactionSummary(False, False, mBankTransactionPk, finBL.HtmlWidgetUtilities.CreateScriptContextData(ScriptInfo, FORM_KEY))

        ' Controls
        If BankTransactionReverse.BankTransactionView.Date &gt; finBL.TimeZoneFunctions.GetCurrentDatabaseDate Then
          .ReversalDateMinValue = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(.ReversalDate)
          .ReversalDateMaxValue = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(.ReversalDate)
        Else
          .ReversalDateMinValue = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(BankTransactionReverse.BankTransactionView.Date)
          .ReversalDateMaxValue = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(finBL.TimeZoneFunctions.GetCurrentDatabaseDate)
        End If

        ' Actions
        .DefaultPublishNow = finBL.Settings.AccountPaymentReverseDocumentPublishNow

        ' Advanced Sections
        .ShowDocumentSelection = mCombinedParameters.GetBoolean("ShowDocumentSelection", True)
        .ShowWorkflowSelection = mCombinedParameters.GetBoolean("ShowWorkflowSelection", True)

        ' Licence
        If Not finBL.Settings.AddOns.Workflow Then .ShowWorkflowSelection = False

        ' Configuration
        .DefaultDocumentCreate = BankTransactionReverse.DocumentCreate
        .DefaultDocumentId = BankTransactionReverse.DocumentId
        .DefaultWorkflowCreate = BankTransactionReverse.WorkflowCreate
        If BankTransactionReverse.WorkflowTypePk &lt;&gt; 0 Then
          .DefaultWorkflowTypeId = BankTransactionReverse.WorkflowTypeId
          .DefaultWorkflowTypeDescription = finBL.WorkflowTypes(BankTransactionReverse.WorkflowTypeId).Description
        End If
        .CanChangeFee = BankTransactionReverse.FeeAllowChange
        .PromptOnCommit = finBL.CloudConnectFunctions.CloudConnectSettings.PromptOnCommit
        .ShowFee = BankTransactionReverse.FeeElementPk &lt;&gt; 0
        .ShowReschedulePayment = BankTransactionReverse.ReschedulePaymentAllow
        .ShowSummary = mShowSummary

        ' Ensure Default Document &amp; Workflow Type are still active
        If Len(.DefaultDocumentId) &lt;&gt; 0 Then
          If finBL.Documents.Exists(.DefaultDocumentId) AndAlso finBL.Documents(.DefaultDocumentId).Active Then
            ' Ok
          Else
            .DefaultDocumentId = ""
          End If
        End If

        If Len(.DefaultWorkflowTypeId) &lt;&gt; 0 Then
          If finBL.WorkflowTypes.Exists(.DefaultWorkflowTypeId) AndAlso finBL.WorkflowTypes(.DefaultWorkflowTypeId).Active Then
            ' Ok
          Else
            .DefaultWorkflowTypeId = ""
            .DefaultWorkflowTypeDescription = ""
          End If
        End If

        ' Update Document / Workflow based upon configuration, licence and advanced settings
        ' Show Document
        If finBL.Settings.AccountPaymentReverseDocumentPk &lt;&gt; 0 AndAlso finBL.Documents.ExistsPk(finBL.Settings.AccountPaymentReverseDocumentPk) AndAlso finBL.Documents.ItemByPk(finBL.Settings.AccountPaymentReverseDocumentPk).Active Then
          .ShowDocument = True
        ElseIf .ShowDocumentSelection Then
          .ShowDocument = True
        Else
          .ShowDocument = False
        End If

        ' Show Workflow
        If Not finBL.Settings.AddOns.Workflow Then
          .ShowWorkflow = False
        ElseIf finBL.Settings.AccountPaymentReverseWorkflowTypePk &lt;&gt; 0 AndAlso finBL.WorkflowTypes.ExistsPk(finBL.Settings.AccountPaymentReverseWorkflowTypePk) AndAlso finBL.WorkflowTypes.ItemByPk(finBL.Settings.AccountPaymentReverseWorkflowTypePk).Active Then
          .ShowWorkflow = True
        ElseIf .ShowWorkflowSelection Then
          .ShowWorkflow = True
        Else
          .ShowWorkflow = False
        End If
      End If
    End With
  End If

  ' Response
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(FormInitialisationInfo, response)
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Create a finBankTransactionReverse object from Web Service properties.
''' &lt;/summary&gt;
''' &lt;returns&gt;
'''  A Boolean value indicating success.
''' &lt;/returns&gt;
Private Function CreateBankTransactionReverse(parameters As WizardFinishParameters,
                                              ByRef bankTransactionReverse As finBankTransactionReverse) As Boolean

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  bankTransactionReverse = finBL.CreateBankTransactionReverse()

  ' Load Bank Transaction Reverse
  If Success Then
    With bankTransactionReverse
      Success = .BankTransactionLoad(mBankTransactionPk)

      ' Update
      If Success AndAlso parameters IsNot Nothing Then
        ' General
        .ReversalDate = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(parameters.ReversalDate)
        .TransactionReference = parameters.Reference
        .Reason = parameters.Reason

        .FeeCharge = parameters.FeeCharge
        .FeeValue = parameters.FeeValue

        .ReschedulePayment = parameters.ReschedulePayment
        .ReschedulePaymentDate = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(parameters.ReschedulePaymentDate)

        If parameters.DocumentCreate Then
          .DocumentCreate = True
          .DocumentId = parameters.DocumentId
          .DocumentFeeCharge = parameters.DocumentChargeFee
        Else
          .DocumentCreate = False
        End If
        If parameters.WorkflowCreate AndAlso finBL.Settings.AddOns.Workflow Then
          .WorkflowCreate = True
          .WorkflowTypeId = parameters.WorkflowTypeId
        Else
          .WorkflowCreate = False
        End If
        If .DocumentCreate OrElse .WorkflowCreate Then
          .DocumentPublishNow = parameters.DocumentPublishNow
        End If
      End If
    End With
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Finish, i.e., Commit changes.
''' &lt;/summary&gt;
''' &lt;param name="parametersJson"&gt;
'''  A JSON formatted WizardFinishParameters object.
''' &lt;/param&gt;
Private Function Finish(parametersJson As String,
                        requestInfo As finScriptRequestInfo,
                        ByRef returnValue As String) As Boolean

  Dim BankTransactionReverse As finBankTransactionReverse
  Dim DocumentCannotPublishCount As Integer
  Dim DocumentLogPk As Integer
  Dim DocumentPublishFailedCount As Integer
  Dim DocumentPublishedCount As Integer
  Dim Information As String
  Dim Log As I_finLog
  Dim obj As Object
  Dim Success As Boolean
  Dim Warning As String
  Dim WizardFinishParameters As WizardFinishParameters
  Dim Workflow As finWorkflow
  Dim WorkflowPublishFailedCount As Integer
  Dim WorkflowPublishedCount As Integer

  ' Assume Success
  Success = True

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

  ' Create Bank Transaction Reverse object
  If Success Then
    Success = CreateBankTransactionReverse(WizardFinishParameters, BankTransactionReverse)
  End If

  ' Execute
  If Success Then
    Success = BankTransactionReverse.ExecuteCommit(, Warning)
  End If

  ' Publish Logs
  If Success Then
    If BankTransactionReverse.DocumentPublishNow AndAlso BankTransactionReverse.DocumentLogs IsNot Nothing Then
      ' Account Logs
      For Each Log In BankTransactionReverse.DocumentLogs
        If Log.DocumentPk &lt;&gt; 0 AndAlso (Log.PublishStatus = isefinLogPublishStatus.Open OrElse Log.PublishStatus = isefinLogPublishStatus.ToSend) Then
          If finBL.Documents.ItemByPk(Log.DocumentPk).SupportsUnattendedPublish Then
            ' Publish
            If Log.Publish(isefinLogPublishType.Publish, True) Then
              DocumentPublishedCount += 1
              If DocumentLogPk = 0 Then DocumentLogPk = Log.Pk
            Else
              DocumentPublishFailedCount += 1
            End If
          Else
            ' Cannot Publish Unattented
            DocumentCannotPublishCount += 1
          End If
        End If
      Next

      ' Workflow Logs
      ' NOTE: These will be new Workflows hence any unpublished Logs can be published
      If BankTransactionReverse.Workflows IsNot Nothing Then
        For Each Workflow In BankTransactionReverse.Workflows
          If Workflow.Publish(True, True) Then
            WorkflowPublishedCount += 1
          Else
            WorkflowPublishFailedCount += 1
          End If
        Next
      End If

      ' Information and Warnings
      If DocumentPublishedCount &lt;&gt; 0 Then
        If Len(Information) &lt;&gt; 0 Then Information &amp;= vbNewLine
        Select Case DocumentPublishedCount
          Case 1
            'Information &amp;= "1 Account Log was published"
            ' NOTE: If only one Log then the Log will be opened for viewing via DocumentLogPk
          Case Else
            Information &amp;= DocumentPublishedCount &amp; " Account Logs were published"
        End Select
      End If

      If DocumentPublishFailedCount &lt;&gt; 0 Then
        If Len(Warning) &lt;&gt; 0 Then Warning &amp;= vbNewLine
        Select Case DocumentPublishFailedCount
          Case 1
            Warning &amp;= "1 Account Log failed to publish"
          Case Else
            Warning &amp;= DocumentPublishFailedCount &amp; " Account Logs failed to publish"
        End Select
      End If

      If DocumentCannotPublishCount &lt;&gt; 0 Then
        If Len(Information) &lt;&gt; 0 Then Information &amp;= vbNewLine
        Select Case DocumentCannotPublishCount
          Case 1
            Information &amp;= "1 Account Log cannot be published from this interface"
          Case Else
            Information &amp;= DocumentCannotPublishCount &amp; " Account Logs cannot be published from this interface"
        End Select
      End If

      If WorkflowPublishFailedCount &lt;&gt; 0 Then
        If Len(Information) &lt;&gt; 0 Then Information &amp;= vbNewLine
        Select Case WorkflowPublishFailedCount
          Case 1
            Warning &amp;= "1 Workflow failed to publish one or more Logs"
          Case Else
            Warning &amp;= WorkflowPublishFailedCount &amp; " Workflows failed to publish one or more Logs"
        End Select
      End If
    ElseIf BankTransactionReverse.DocumentLogs IsNot Nothing Then
      ' Logs created but not configured to publish immediately
      Select Case BankTransactionReverse.DocumentLogs.Count
        Case 0
        Case 1
          If Len(Information) &lt;&gt; 0 Then Information &amp;= vbNewLine
          Information &amp;= "1 Account Log has been created but not yet published"
        Case Else
          If Len(Information) &lt;&gt; 0 Then Information &amp;= vbNewLine
            Information &amp;= BankTransactionReverse.DocumentLogs.Count &amp; " Account Logs have been created but not yet published"
      End Select
    End If
  End If

  ' Finalise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(New WizardFinishDetails(Information, Warning, DocumentLogPk), returnValue)
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Get updated Reschedule Payment Date.
''' &lt;/summary&gt;
Public Function Form_ReschedulePayment_Change(parametersJson As String,
                                              ByRef response As String) As Boolean

  Dim BankTransactionReverse As finBankTransactionReverse
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim obj As Object
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

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

  ' Create Bank Transaction Reverse object
  If Success Then
    Success = CreateBankTransactionReverse(WizardFinishParameters, BankTransactionReverse)

    ' Default Reschedule Payment Date
    BankTransactionReverse.ReschedulePaymentDateDefault()

    FormInitialisationInfo = New FormInitialisationInfo()
    With FormInitialisationInfo
      .ReschedulePaymentDate = finBL.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(BankTransactionReverse.ReschedulePaymentDate)
    End With
  End If

  ' Response
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(FormInitialisationInfo, response)
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Documents.
''' &lt;/summary&gt;
Private Function GetDocuments(bankTransactionReverse As finBankTransactionReverse,
                              ByRef documents As List(Of Document)) As Boolean

  Dim BankTransactionReverseDocuments As List(Of finDocumentRO)
  Dim Document As finDocumentRO
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  documents = New List(Of Document)

  ' Get Documents
  If bankTransactionReverse.GetDocuments(BankTransactionReverseDocuments) Then
    For Each Document In BankTransactionReverseDocuments
      documents.Add(New Document(Document))
    Next
  Else
    Success = False
  End If

  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 ConfirmList As List(Of String)
  Dim Data As Object
  Dim FailedControlId As String
  Dim FailedMessage As String
  Dim PageId As String
  Dim Success As Boolean

  ' 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

  ' Validate Page
  Select Case PageId
    Case "General"
      ' General
      If WizardValidate_General(parametersJson, ConfirmList) Then
        Data = ConfirmList
      Else
        Success = False
      End If
  End Select

  ' 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(parametersJson As String,
                                        ByRef confirmList As List(Of String)) As Boolean

  Dim BankTransactionReverse As finBankTransactionReverse
  Dim Message As String
  Dim obj As Object
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

  ' Initialise ByRef
  confirmList = New List(Of String)()

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

  ' Create Bank Transaction Reverse object
  If Success Then
    Success = CreateBankTransactionReverse(WizardFinishParameters, BankTransactionReverse)
  End If

  ' Warning
  If Success Then
    BankTransactionReverse.BankTransactionView.CanReverse(, Message)
    If Len(Message) &lt;&gt; 0 Then confirmList.Add(message)
  End If

  Return Success

End Function



''' &lt;summary&gt;
'''  Document.
''' &lt;/summary&gt;
Public Class Document

  Public DocumentId As String
  Public Description As String
  Public DocumentFeeText As String

  Public Sub New(document As finDocumentRO)

    With document
      Me.DocumentId = .DocumentId
      Me.Description = .Description

      If .ChargeFee AndAlso .Fee &lt;&gt; 0 Then
        Me.DocumentFeeText = String.Format("Charge Document Fee of {0}?", finBLShared.FormatCurrency(.Fee, True))
      End If
    End With

  End Sub

End Class



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

  ' Account Properties
  Public RecordId As String
  Public RecordDescription As String

  ' Properties
  Public BankTransactionPk As Integer
  Public IsBankInterfaceReversal As Boolean
  Public FeeCharge As Boolean
  Public FeeValue As Decimal
  Public Reason As String
  Public Reference As String
  Public ReschedulePayment As Boolean
  Public ReschedulePaymentDate As Date?
  Public ReversalDate As Date
  Public Value As Decimal

  ' Bank Transaction Summary
  Public BankTransactionSummaryHtml As String

  ' Lists
  Public ReasonInformationListId As String
  Public Documents As List(Of Document)
  Public WorkflowTypeFilter As String

  ' Configuration
  Public CanChangeFee As Boolean
  Public DefaultDocumentCreate As Boolean
  Public DefaultDocumentId As String
  Public DefaultPublishNow As Boolean
  Public DefaultWorkflowCreate As Boolean
  Public DefaultWorkflowTypeDescription As String
  Public DefaultWorkflowTypeId As String
  Public PromptOnCommit As Boolean
  Public ReversalDateMaxValue As Date
  Public ReversalDateMinValue As Date
  Public ShowDocument As Boolean
  Public ShowDocumentSelection As Boolean
  Public ShowFee As Boolean
  Public ShowReschedulePayment As Boolean
  Public ShowSummary As Boolean
  Public ShowWorkflow As Boolean
  Public ShowWorkflowSelection 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;
'''  Finish Parameters.
''' &lt;/summary&gt;
Public Class WizardFinishParameters

  ' General
  Public DocumentCreate As Boolean
  Public DocumentChargeFee As Boolean
  Public DocumentPublishNow As Boolean
  Public FeeCharge As Boolean
  Public FeeValue As Decimal
  Public Reason As String
  Public Reference As String
  Public ReschedulePayment As Boolean
  Public ReschedulePaymentDate As Date?
  Public ReversalDate As Date
  Public WorkflowCreate As Boolean
  Public DocumentId As String
  Public WorkflowTypeId As String

End Class

''' &lt;summary&gt;
'''  Finish details.
''' &lt;/summary&gt;
Public Class WizardFinishDetails

  ' General
  Public DocumentLogPk As Integer
  Public Information As String
  Public Warning As String

  Public Sub New(information As String,
                 warning As String,
                 documentLogPk As Integer)

    Me.Information = Information
    Me.Warning = warning
    Me.DocumentLogPk = documentLogPk

  End Sub

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

Used as a finPOWER Connect Cloud compatible version of the form "AccountBankTransactionReverse".</Notes>
    <PermissionKeyExecute />
    <RunWithoutPrompts>false</RunWithoutPrompts>
    <TemplateText>&lt;div id="frmMain" class="is-widget-content" style="visibility:hidden"&gt;

  &lt;!-- Form Header --&gt;
  &lt;header&gt;
    &lt;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="Current"&gt;Current Transaction Details&lt;/li&gt;
        &lt;li tabId="General" tooltipText="Enter reversal details."&gt;Reverse Bank Transaction&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 --&gt;
    &lt;div id="pageCurrent"&gt;
      &lt;div id="wbBankTransactionSummary"&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:9em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblBankTransactionReverseDetails"&gt;Enter Reversal details&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateReversalDate"&gt;Date:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="dateReversalDate" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtReference"&gt;Reference:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtReference"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboReason"&gt;Reason:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboReason" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numValue"&gt;Value:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numValue"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr style="display:none"&gt;
          &lt;th&gt;&lt;label for="numFeeValue"&gt;Fee:&lt;/label&gt;&lt;/th&gt;
          &lt;td colspan="2"&gt;&lt;input id="numFeeValue"/&gt; &lt;input id="chkFeeCharge" type="checkbox" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblReschedulePayment"&gt;Reschedule Payment&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkReschedulePayment" type="checkbox"/&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th class="indent1"&gt;&lt;label for="dateReschedulePaymentDate"&gt;Date:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="dateReschedulePaymentDate"/&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblActions"&gt;Specify any actions to perform&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkActionDocument" type="checkbox"/&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th class="indent1"&gt;&lt;label for="cboActionDocument"&gt;Document:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboActionDocument" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2" class="indent1"&gt;&lt;input id="chkActionDocumentChargeFee" type="checkbox"/&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkActionWorkflow" type="checkbox"/&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th class="indent1"&gt;&lt;label for="cboActionWorkflow"&gt;Workflow:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboActionWorkflow" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkDocumentPublishNow" type="checkbox"/&gt;&lt;/th&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;

  &lt;/div&gt;


  &lt;!-- Form Footer --&gt;
  &lt;footer&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;
// Properties
var mRecord;

// Controls
var C = {
  // Current
  wbBankTransactionSummary: null,

  // General
  lblBankTransactionReverseDetails: null,
  dateReversalDate: null,
  txtReference: null,
  cboReason: null,
  numValue: null,
  numFeeValue: null,
  chkFeeCharge: null,

  lblReschedulePayment: null,
  chkReschedulePayment: null,
  dateReschedulePaymentDate: null,

  lblActions: null,
  chkActionDocument: null,
  cboActionDocument: null,
  chkActionDocumentChargeFee: null,
  chkActionWorkflow: null,
  cboActionWorkflow: null,
  chkDocumentPublishNow: null,
}

// Form
var frmMain;
var tabWizard;

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

// Other
var mDocument;

// ==========
// Initialise
// ==========
$(function () {
  // Mobile optimisations
  var currencyWidth = "20em";
  $(window).resize(Form_Resize);

  // --------
  // Controls
  // --------
  //   Current
  C.wbBankTransactionSummary = widget.UI.PreviewPane("wbBankTransactionSummary", {});

  //   General
  C.lblBankTransactionReverseDetails = widget.UI.Label("lblBankTransactionReverseDetails", {});
  C.dateReversalDate = widget.UI.DateBox("dateReversalDate", {
    allowBlank: false,
  });
  C.txtReference = widget.UI.TextBox("txtReference", {
    allowBlank: false,
    maxLength: 20,
  });
  C.cboReason = widget.UI.InformationListComboBox("cboReason", {
    allowBlank: false,
    maxLength: 50,
  });
  C.numValue = widget.UI.NumberBox("numValue", {
    decimals: -1,
    minValue: -999999999999,
    maxValue: 999999999999,
    readOnly: true,
  });
  C.numFeeValue = widget.UI.NumberBox("numFeeValue", {
    allowBlank: false,
    minValue: 0,
    maxValue: 9999999,
  });
  C.chkFeeCharge = widget.UI.CheckBox("chkFeeCharge", {
    caption: "Charge Fee?",

    onChange: chkFeeCharge_Change,
  });

  C.lblReschedulePayment = widget.UI.Label("lblReschedulePayment", {});
  C.chkReschedulePayment = widget.UI.CheckBox("chkReschedulePayment", {
    caption: "Reschedule Payment?",

    onChange: chkReschedulePayment_Change,
  });
  C.dateReschedulePaymentDate = widget.UI.DateBox("dateReschedulePaymentDate", {
    allowBlank: false,
  });

  C.lblActions = widget.UI.Label("lblActions", {});
  C.chkActionDocument = widget.UI.CheckBox("chkActionDocument", {
    caption: "Send Document?",

    onChange: chkAction_Change,
  });
  C.cboActionDocument = widget.UI.DBCombo("cboActionDocument", {
    allowBlank: false,
    limitToList: true,

    onChange: cboActionDocument_Change,
  });
  C.chkActionDocumentChargeFee = widget.UI.CheckBox("chkActionDocumentChargeFee", {});
  C.chkActionWorkflow = widget.UI.CheckBox("chkActionWorkflow", {
    caption: "Start Workflow?",

    onChange: chkAction_Change,
  });
  C.cboActionWorkflow = widget.UI.DBCombo("cboActionWorkflow", {
    allowBlank: false,
    limitToList: true,

    onChange: cboActionWorkflow_Change,
  });
  C.chkDocumentPublishNow = widget.UI.CheckBox("chkDocumentPublishNow", {
    caption: "Publish Document and/ or Workflow documents now?",
  });

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

  // Reset
  Form_Reset();
});

// ==========
// Reset Form
// ==========
function Form_Reset() {
  // Defaults
  mDocument = null;

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

  // Resize
  Form_Resize();

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

// ===========
// Load Record
// ===========
function Record_Load() {
  // Initialise
  mRecord = 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);

      // Give Collections ability To lookup by code
      widget.ArrayAllowLookupById(mRecord.Documents, "DocumentId");

      // Load
      Fields_Load();
    },

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

// ===========
// Load Fields
// ===========
function Fields_Load() {
  if (mRecord) {
    // Current
    C.wbBankTransactionSummary.SetContent(mRecord.BankTransactionSummaryHtml, false);

    // General
    C.dateReversalDate.Value(mRecord.ReversalDate);
    C.txtReference.Text(mRecord.Reference);
    C.cboReason.Text(mRecord.Reason);
    C.numValue.Value(mRecord.Value);
    C.numFeeValue.Value(mRecord.FeeValue);
    C.chkFeeCharge.Value(mRecord.FeeCharge);

    C.chkReschedulePayment.Value(mRecord.ReschedulePayment);
    C.dateReschedulePaymentDate.Value(mRecord.ReschedulePaymentDate);

    C.chkActionDocument.Value(mRecord.DefaultDocumentCreate);
    C.cboActionDocument.Text(mRecord.DefaultDocumentId);
    C.chkActionDocumentChargeFee.Value(true);
    C.chkActionWorkflow.Value(mRecord.DefaultWorkflowCreate);
    C.cboActionWorkflow.Text(mRecord.DefaultWorkflowTypeId);
    C.chkDocumentPublishNow.Value(mRecord.DefaultPublishNow);
  }

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

  // Update Controls

  // Update fields
  Fields_Update();

  // Refresh Tab
  tabWizard_Refresh();
}

// ===========
// Save Fields
// ===========
function Fields_Save() {
  // Not used by this wizard since there is no concept of updating an object behind the wizard
}

// =============
// Update Fields
// =============
function Fields_Update() {
  // Update Buttons
  tabWizard_UpdateButtons();

  // Lists etc
  if (mRecord) {
    C.dateReversalDate.MinValue(mRecord.ReversalDateMinValue);
    C.dateReversalDate.MaxValue(mRecord.ReversalDateMaxValue);
    C.cboReason.SetComboFromInformationList(mRecord.ReasonInformationListId, false, null, false);
    C.cboActionDocument.RefreshFromCollection(mRecord.Documents, "DocumentId", "Description");
    C.cboActionWorkflow.RefreshFromStandardRange("WorkflowTypes", mRecord.WorkflowTypeFilter, false);
  }

  // Content
  if (mRecord) {
    C.numFeeValue.VisibleRow(mRecord.ShowFee);
    C.chkFeeCharge.VisibleRow(mRecord.ShowFee);
    C.lblReschedulePayment.VisibleRow(mRecord.ShowReschedulePayment);
    C.chkReschedulePayment.VisibleRow(mRecord.ShowReschedulePayment);
    C.dateReschedulePaymentDate.VisibleRow(mRecord.ShowReschedulePayment);

    // Captions and Headings
    if (mRecord.ShowDocument &amp;&amp; mRecord.ShowWorkflow) {
      // Ok
    }
    else if (mRecord.ShowDocument) {
      C.chkDocumentPublishNow.Caption("Publish now?");
    }
    else if (mRecord.ShowWorkflow) {
      C.chkDocumentPublishNow.Caption("Publish Workflow documents now?");
    }
    else {
      C.lblActions.VisibleRow(false);
    }

    // Documents
    if (!mRecord.ShowDocument) {
      C.chkActionDocument.VisibleRow(false);
    }

    // Workflows
    if (!mRecord.ShowWorkflow) {
      C.chkActionWorkflow.VisibleRow(false);
    }

    chkAction_Change();
    cboActionDocument_Change();
    cboActionWorkflow_Change();
    chkFeeCharge_Change();
    chkReschedulePayment_Change();
  }

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

  // Show Summary
  if (mRecord &amp;&amp; mRecord.ShowSummary) {
    Form_ExecuteAction("Summary");
  }

  // Resize Tab
  tabWizard_Resize();
}

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

  // Tab
  tabWizard_Resize();
}

// ==============
// Wizard Buttons
// ==============
function tabWizard_Cancel() {
  if (widget.CanClose()) {
    widget.Close();
  }
  else {
    widget.Reset();
  }
}

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

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

// ==========
// Resize Tab
// ==========
function tabWizard_Resize() {
  switch (tabWizard.SelectedTabId()) {
    case "Current":
      C.wbBankTransactionSummary.ResizeFromParent();
      break;

    case "General":
      C.txtReference.WidthResizeFromParent();
      C.cboReason.WidthResizeFromParent();
      break;

    default:
      break;
  }
}

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

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

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

  // Tweak fields

  // Update Heading
  switch (tabWizard.SelectedTabId()) {
    case "Current":
      frmMain.RefreshHeading(tabWizard.TabCaption(tabWizard.SelectedTabId()), "Transaction for Account '" + mRecord.RecordId + "', " + mRecord.RecordDescription + ".");
      break;

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

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

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

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

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

    switch (tabWizard.SelectedTabId()) {
      case "General":
        // 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
  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 &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();
}

// =================
// Execute an Action
// =================
function Form_ExecuteAction(actionId) {
  switch (actionId.toUpperCase()) {
    case "FINISH":
      // Finish
      Form_ExecuteAction_Finish();
      break;

    case "SUMMARY":
      // Show Summary page
      tabWizard_Refresh(0);
      break;

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

// =============
// Finish Action
// =============
function Form_ExecuteAction_Finish() {
  // Validate
  tabWizard_Validate(function () {
    if (mRecord.PromptOnCommit) {
      // Confirm
      var heading = "Reverse Bank Transaction";
      var message = "Are you sure you want to reverse this Bank Transaction?";

      widget.UI.MsgBoxConfirm(message, { heading: heading }, function () { Form_ExecuteAction_FinishPost(); }, null);
    }
    else {
      // Commit without prompting
      Form_ExecuteAction_FinishPost();
    }
  });
}

function Form_ExecuteAction_FinishPost() {
  // Disable Form
  widget.UI.Block("Committing, please wait...");

  // Create Parameters
  var params = CreateFinishParameters();

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

      // Unblock
      if (data.Warning || data.Information) widget.UI.Unblock();

      // Finalise
      if (data.Warning &amp;&amp; data.Information) {
        widget.UI.MsgBoxAlert("The Bank Transaction was successfully reversed but the following warning was given:\n\n" + data.Warning + "\n\nThe following information was also given:\n\n" + data.Information, {}, function () { Form_ExecuteAction_FinishPost_Finalise(data); });
      }
      else if (data.Warning) {
        widget.UI.MsgBoxAlert("The Bank Transaction was successfully reversed but the following warning was given:\n\n" + data.Warning, {}, Form_ExecuteAction_FinishPost_Finalise);
      }
      else if (data.Information) {
        widget.UI.MsgBoxInfo("The Bank Transaction was successfully reversed but the following information was given:\n\n" + data.Information, {}, function () { Form_ExecuteAction_FinishPost_Finalise(data); } );
      }
      else {
        Form_ExecuteAction_FinishPost_Finalise(data);
      }
    },

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

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

function Form_ExecuteAction_FinishPost_Finalise(data) {
  // Notify Clients
  widget.ActionNotificationSend("BankTransactions.Refresh", { bankTransactionPk: mRecord.BankTransactionPk }, null, true);
  
  // If Bank Interface Reversal, likely there is a modal window between the Accounts form and the reversal so two-levels of refreshing is required  
  if (mRecord.IsBankInterfaceReversal) {
    widget.ActionNotificationSend("AccountRefresh", { accountId: mRecord.RecordId }, null, true);
  }  

  // Close Form
  widget.Close();

  // Refresh Parent (to show updated details)
  widget.RefreshParent();

  // Show Document Log
  if (data.DocumentLogPk) {
    widget.ExecuteApplicationShortcutUrl("app://FormShow?form=AccountLog&amp;id=" + data.DocumentLogPk + "&amp;page=Document");
  }
}

// ========================
// Create Finish Parameters
// ========================
function CreateFinishParameters() {
  var params = {
   ReversalDate: C.dateReversalDate.Value(),
   Reference: C.txtReference.Text(),
   Reason: C.cboReason.Text(),
   FeeValue: C.numFeeValue.Value(),
   FeeCharge: C.chkFeeCharge.Value(),
   ReschedulePayment: C.chkReschedulePayment.Value(),
   ReschedulePaymentDate: C.dateReschedulePaymentDate.Value(),
   DocumentCreate: C.chkActionDocument.Value(),
   WorkflowCreate: C.chkActionWorkflow.Value(),
   DocumentPublishNow: C.chkDocumentPublishNow.Value(),
  }

  // Document
  if (C.chkActionDocument.Value()) {
    params.DocumentId = C.cboActionDocument.Text();

    if (mDocument &amp;&amp; mDocument.DocumentFeeText) {
      params.DocumentChargeFee = C.chkActionDocumentChargeFee.Value();
    }
  }

  // Workflow
  if (mRecord.ShowWorkflow &amp;&amp; C.chkActionWorkflow.Value()) {
    params.WorkflowTypeId = C.cboActionWorkflow.Text();
  }

  return params;
}

// =================
// cboActionDocument
// =================
function cboActionDocument_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Reset
  C.chkActionDocument.Caption("Send Document?");
  C.chkActionDocumentChargeFee.VisibleRow(false);

  // Get Selected Document
  mDocument = mRecord.Documents.GetItem(C.cboActionDocument.Text());

  // Handle Document
  if (mDocument) {
    C.chkActionDocument.Caption("Send '" + mDocument.Description + "' Document?");
    if (mDocument.DocumentFeeText &amp;&amp; C.chkActionDocument.Value()) {
      C.chkActionDocumentChargeFee.Caption(mDocument.DocumentFeeText);
      C.chkActionDocumentChargeFee.VisibleRow(true);
    }
  }
}

// =================
// cboActionWorkflow
// =================
function cboActionWorkflow_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Reset
  C.chkActionWorkflow.Caption("Start Workflow?");

  // Update Workflow Text
  // NOTE: As GetDescription() is asynchronously called it may not populate correctly when initially loading the form, therefore use value only once when loading the first time
  var description = "";
  if (mRecord.DefaultWorkflowTypeDescription) {
    description = mRecord.DefaultWorkflowTypeDescription;
    mRecord.DefaultWorkflowTypeDescription = null;
  }
  else {
    description = C.cboActionWorkflow.GetDescription();
  }

  // Set Caption
  if (C.cboActionWorkflow.Text()) {
    C.chkActionWorkflow.Caption("Start '" + description + "' Workflow?");
  }
}

// =========
// chkAction
// =========
function chkAction_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Update Visibility of Publish Now Checkbox
  var visible = (C.chkActionDocument.Value() || (C.chkActionWorkflow.Value() &amp;&amp; mRecord.ShowWorkflow));
  C.chkDocumentPublishNow.VisibleRow(visible);

  // Other control visibility
  C.cboActionDocument.VisibleRow(visible &amp;&amp; C.chkActionDocument.Value() &amp;&amp; mRecord.ShowDocument &amp;&amp; mRecord.ShowDocumentSelection);
  C.cboActionWorkflow.VisibleRow(visible &amp;&amp; C.chkActionWorkflow.Value() &amp;&amp; mRecord.ShowWorkflow &amp;&amp; mRecord.ShowWorkflowSelection);

  // Refresh Document
  cboActionDocument_Change();
}

// ============
// chkFeeCharge
// ============
function chkFeeCharge_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Update Controls
  if (mRecord.CanChangeFee) {
    C.numFeeValue.ReadOnly(!C.chkFeeCharge.Value());
  }
  else {
    C.numFeeValue.ReadOnly(true);
  }
  chkReschedulePayment_RefreshLabel();
}

// ====================
// chkReschedulePayment
// ====================
function chkReschedulePayment_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Update Controls
  C.dateReschedulePaymentDate.ReadOnly(!C.chkReschedulePayment.Value());
  chkReschedulePayment_RefreshLabel();

  // Refresh Form
  if (C.chkReschedulePayment.Value()) {
    var params = CreateFinishParameters();

    widget.GetString("Form_ReschedulePayment_Change", params,
      function(data) {
        Form_ReschedulePayment_Change(data);
      },
      Payment_Change_Fail);
  }
  else {
    // Clear date
    C.dateReschedulePaymentDate.Value(null);
    chkReschedulePayment_RefreshLabel();
  }
}

function chkReschedulePayment_RefreshLabel() {
  if(C.chkReschedulePayment.Value()) {
    if (C.chkFeeCharge.Value()) {
      C.chkReschedulePayment.Caption("Reschedule Payment (including fee) of " + widget.FormatCurrency(C.numValue.Value() + C.numFeeValue.Value(), true) + "?");
    }
    else {
      C.chkReschedulePayment.Caption("Reschedule Payment?");
    }
  }
  else {
   C.chkReschedulePayment.Caption("Reschedule Payment?");
  }
}

function Form_ReschedulePayment_Change(data) {

  if (data) {
    // Parse
    var o = JSON.parse(data);

    // Update mRecord
    mRecord.ReschedulePaymentDate = o.ReschedulePaymentDate;

    // Update Controls
    C.dateReschedulePaymentDate.Value(mRecord.ReschedulePaymentDate);
    chkReschedulePayment_RefreshLabel();
  }
}

function Payment_Change_Fail(data) {
  widget.UI.MsgBoxAlert(data);
}

&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>ImKC+a6CDEeLqS3AL1js2Q</UniqueId>
    <AllowRefresh>true</AllowRefresh>
    <Caption />
    <HtmlWidgetMaxHeight>1200</HtmlWidgetMaxHeight>
    <HtmlWidgetMaxWidth>800</HtmlWidgetMaxWidth>
    <HtmlWidgetNeverApplyStyling>false</HtmlWidgetNeverApplyStyling>
    <HtmlWidgetResourceChartsApex>false</HtmlWidgetResourceChartsApex>
    <HtmlWidgetResourceCssSummaryPage2>false</HtmlWidgetResourceCssSummaryPage2>
    <HtmlWidgetResourceCssWidget>true</HtmlWidgetResourceCssWidget>
    <HtmlWidgetResourceJQuery>true</HtmlWidgetResourceJQuery>
    <HtmlWidgetResourceJQueryVersion />
    <HtmlWidgetSpecialEventGetFolderCount>false</HtmlWidgetSpecialEventGetFolderCount>
    <Icon />
    <RestrictedOriginsListEnabled>false</RestrictedOriginsListEnabled>
    <RunAsAdministrator>false</RunAsAdministrator>
    <WebServiceName />
    <WebServiceAllowAnonymous>false</WebServiceAllowAnonymous>
    <WebServiceSendDebugInformation>false</WebServiceSendDebugInformation>
    <ShowInMenu>None</ShowInMenu>
    <ParametersType>Custom</ParametersType>
    <Parameters>
      <ISParameterDefs version="1.00">
        <Parameters>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>Form options.</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="ShowDocumentSelection" 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>True</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="ShowSummary" type="Boolean">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>False</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="ShowWorkflowSelection" 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>True</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>TESTING</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText>These are the Parameters required by this HTML Widget to function correctly.
They are listed here for testing purposes only.</TooltipText>
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="BankTransactionPk" 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>
        </Parameters>
      </ISParameterDefs>
    </Parameters>
  </finScript>