<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2022-05-11T00:39:31.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2021-11-09T22:09:10.5000000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2022-05-11T00:39:01.3170000</UpdatedUtcDate>
    <ScriptId>CDU</ScriptId>
    <Description>Centrix Commercial Data Upload</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Category />
    <Code>' HtmlWidget_CentrixNZ_CommercialDataUpload
Option Explicit On
Option Strict On

' #################################################################
' Centrix (New Zealand) Commercial Data Upload
'
' Version: 1.02 (11/05/2022)
'
' Usage: System-defined HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.00  15/06/2021  ISS                Created
'    1.01  04/02/2022  ISS      J028216   Added filters
'    1.02  11/05/2022  ISS      J028712   Removed obsoleted Functions
' #################################################################

' Constants
'#const "FTPFolder",String,"","The folder where the Centrix Commercial Data Upload Files are sent to Centrix from (ignored if running outside of finPOWER Connect Desktop)."

' Script Constants
Private FTPFolder As String = ""

' Constants
Private Const BATCH_SIZE As Integer = 100
Private Const FORM_KEY As String = "CentrixCommercialDataUpload"

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

' Parameters
Private mExcludeAccountTypes As String
Private mExcludeBranches As String
Private mExcludeDepartments As String
Private mExcludeAccountLedgers As String

' Other
Private mDateBreakdown(7) As Date

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

  ' Assume Success
  Main = True

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

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

  ' Parameters
  With mCombinedParameters
    mExcludeAccountTypes = .GetString("ExcludeAccountTypes")
    mExcludeBranches = .GetString("ExcludeBranches")
    mExcludeDepartments = .GetString("ExcludeDepartments")
    mExcludeAccountLedgers = .GetString("ExcludeAccountLedgers")
  End With

  ' Script Constants
  With ScriptInfo.Constants
    FTPFolder = .GetString("FTPFolder")
  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
      Main = Finish(returnValue)

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

    Case "Finish_ProcessBatch"
      ' Process next batch
      Main = Finish_ProcessBatch(parametersJson, Nothing, 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;
'''  Finish
''' &lt;/summary&gt;
Private Function Finish(ByRef returnValue As String) As Boolean

  Dim CostCentreResolved As finCostCentreResolved
  Dim DateCreated As Date
  Dim DateFrom As Date
  Dim DateTo As Date
  Dim dr As IDataReader
  Dim EntityId As String
  Dim FileExportPackageHandler As finwsFileExportPackageHandler
  Dim Filename As String
  Dim sqb As ISSelectQueryBuilder
  Dim sqbSub As ISSelectQueryBuilder
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

  ' Initialise
  DateCreated = finBL.TimeZoneFunctions.GetCurrentDatabaseDateTime()
  sqb = finBL.Database.CreateSelectQueryBuilder()
  sqbSub = finBL.Database.CreateSelectQueryBuilder()

  ' Parameters
  With mCombinedParameters
    DateFrom = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(.GetDate("DateFrom"))
    DateTo = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(.GetDate("DateTo"))
    EntityId = .GetString("EntityId")
  End With

  ' Get Cost Centre
  Success = GetCostCentreResolved(EntityId, CostCentreResolved)

  ' Create Export Package
  If Success Then
    If finBL.HtmlWidgetUtilities.CreateProcessFileExportPackageHandler("Centrix Commercial Data Upload", ScriptInfo.ScriptId, FileExportPackageHandler) Then
      ' Centrix requires a specific naming convention
      Filename = CostCentreResolved.CentrixNZ.SubscriberId &amp; "_[YMD]_[HMS].xml"
      FileName = finBL.Runtime.FileUtilities.FileNameResolved(FileName, DateCreated)
      FileName = finBL.Runtime.FileUtilities.GetFileNameResolved(finBL.SettingsUser.ExportDataFolderResolved, FileName)

      ' Create a File Name for the Package
      FileName = FileExportPackageHandler.CreateFileName(FileName)

      ' Update Package Status
      FileExportPackageHandler.StatusUpdateInProgress(0)
    Else
      Success = False
    End If
  End If

  If Success Then
    ' Build query to retrieve Accounts
    With sqb
      .Table = "Account"
      .Fields.Add("Account.Pk")
      With .SqlWhere
        ' Must belong to Entity
        .AppendRange("Account.BranchPk", finBL.Branches.GetBranchPksListFromEntitiesRange(EntityId).ToCsvString(), iseRangeDataType.Integer)

        ' Must be Loan Account
        .BlockBegin(iseSqlWhereBuilderNestedBlockType.OrBlock)
        .AppendComparisonInteger("Account.AccountClass", "=", isefinAccountClass.LoanFR)
        .AppendComparisonInteger("Account.AccountClass", "=", isefinAccountClass.LoanFT)
        .AppendComparisonInteger("Account.AccountClass", "=", isefinAccountClass.LoanRC)
        .BlockEnd()

        ' Comprehensive Credit Reporting is not suspended
        .AppendComparisonIntegerBoolean("SuspendCreditReporting", "=", False)

        ' Must be Commercial Credit Type
        .AppendRange("Account.AccountTypePk", finBL.AccountTypes.GetAccountTypePksListCreditTypeCommercial.ToCsvString(), iseRangeDataType.Integer)

        ' Must be Open between From/ To Dates, i.e. Account must be opened on/before To Date and closed not before From Date
        .BlockBegin(iseSqlWhereBuilderNestedBlockType.AndBlock)
        .BlockBegin(iseSqlWhereBuilderNestedBlockType.OrBlock)
        .AppendComparisonInteger("Account.Status", "=", isefinAccountStatus.Open)
        .AppendComparisonInteger("Account.Status", "=", isefinAccountStatus.ClosedPending)
        .AppendComparisonInteger("Account.Status", "=", isefinAccountStatus.Closed)
        .BlockEnd()
        .AppendComparisonDate("Account.DateOpened", "&lt;=", DateTo)
        .BlockBegin(iseSqlWhereBuilderNestedBlockType.OrBlock)
        .AppendComparisonNull("Account.DateClosed")
        .AppendComparisonDate("Account.DateClosed", "&gt;", DateFrom)
        .BlockEnd()
        .BlockEnd()

        ' Excluded Ranges
        If Len(mExcludeAccountLedgers) &lt;&gt; 0 Then
          .BlockBegin(iseSqlWhereBuilderNestedBlockType.OrBlock)
          .AppendComparisonNull("Account.Ledger")
          .AppendRange("Account.Ledger", mExcludeAccountLedgers, iseRangeDataType.String, True)
          .BlockEnd()
        End If
        If Len(mExcludeAccountTypes) &lt;&gt; 0 Then .AppendRangeWithPk("Account.AccountTypePk", "AccountType", "AccountTypeId", "Pk", mExcludeAccountTypes, iseRangeDataType.String, True)
        If Len(mExcludeBranches) &lt;&gt; 0 Then .AppendRangeWithPk("Account.BranchPk", "Branch", "BranchId", "Pk", mExcludeBranches, iseRangeDataType.String, True)
        If Len(mExcludeDepartments) &lt;&gt; 0 Then .AppendRangeWithPk("Account.DepartmentPk", "Department", "DepartmentId", "Pk", mExcludeDepartments, iseRangeDataType.String, True)

        ' Only where there is at least one Owner Client who is an Organisation/ Sole Trader
        With sqbSub
          .Table = "Client"
          .Fields.AddConstant("*")
          With .SqlWhere
            .AppendComparisonField("AccountClient.AccountPk", "=", "Account.Pk")
            .AppendComparisonInteger("AccountClient.RoleType", "=", isefinAccountRoleType.Owner)
            .AppendRange("Client.ClientTypePk", finBL.ClientTypes.GetOrganisationPksList(True).ToCsvString(), iseRangeDataType.Integer)
          End With
          .Joins.Add("AccountClient", "AccountClient.ClientPk", "Client.Pk", iseSelectQueryJoinType.Inner)
        End With
        .AppendExists(sqbSub)
      End With

      ' Order By
      .OrderByFields.Add("Account.Pk")
    End With

  ' Execute Query
    If sqb.ExecuteDisconnectedDataReader(dr) Then
      ' Configure list of Accounts
      WizardFinishParameters = New WizardFinishParameters()
      With WizardFinishParameters
        .DateTo = DateTo
        .PackageStatusFilename = FileExportPackageHandler.GetStatusFileNameFull(True)
        .ProcessingCompleted = False
        .ProgressMessage = "Initialising"

        ' Get Accounts for processing
        Do While dr.Read()
          .ProcessAccounts.Add(New ProcessAccount(finBL.Database.GetFieldInteger(dr!Pk)))
        Loop
      End With
    Else
      Success = False
    End If

    ' Close DataReader
    finBL.Database.DataReaderClose(dr)
  End If

  ' Process First Batch
  If Success Then
    If WizardFinishParameters.ProcessAccounts.Count = 0 Then
      Success = False
      finBL.Error.ErrorBegin("There are no Accounts to include in the export with the specified Parameters.")
    Else
      ' Write XML Header
      Success = WriteXmlHeader(Filename, CostCentreResolved.CentrixNZ.SubscriberId, DateCreated)

      ' First Batch of Accounts
      If Success Then
        Success = Finish_ProcessBatch("", WizardFinishParameters, returnValue)
      End If
    End If
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Get a Resolved Cost Centre for the provided Entity.
''' &lt;/summary&gt;
Private Function GetCostCentreResolved(entityId As String,
                                       ByRef costCentreResolved As finCostCentreResolved) As Boolean

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Validate Entity
  If Not finBL.Entities.Exists(entityId) Then
    Success = False
    finBL.Error.ErrorBeginFormat("Invalid Entity, '{0}'", entityId)
  End If

  ' Get Cost Centre
  If Success Then
    costCentreResolved = finBL.CostCentresResolved.ItemByEntityPk(finBL.Entities(entityId).Pk)
  End If

  ' Validate Cost Centre
  If Not CostCentreResolved.CentrixNZ.CreditEnquiryEnableCreditEnquiry Then
    Success = False
    finBL.Error.ErrorBeginFormat("Centrix Credit Enquiries on Cost Centre '{0}' are not enabled.")
  ElseIf Len(CostCentreResolved.CentrixNZ.SubscriberId) = 0 Then
    Success = False
    finBL.Error.ErrorBeginFormat("Centrix Subscriber Id on Cost Centre '{0}' not defined.")
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Process a Batch of Accounts.
''' &lt;/summary&gt;
Private Function Finish_ProcessBatch(parametersJson As String,
                                     wizardFinishParameters As WizardFinishParameters,
                               ByRef returnValue As String) As Boolean

  Dim BatchLimitReached As Boolean
  Dim CountProcessed As Integer
  Dim FileExportPackageHandler As finwsFileExportPackageHandler
  Dim FileMoveFailed As Boolean
  Dim Filename As String
  Dim FinalFilename As String
  Dim i As Integer
  Dim MoveSourceFile As String
  Dim obj As Object
  Dim ProcessAccount As ProcessAccount
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

  ' Get Export Package Handler
  If Success Then
    If finBL.HtmlWidgetUtilities.GetFileExportPackageHandler(wizardFinishParameters.PackageStatusFilename, FileExportPackageHandler) Then
      ' Package contains a single file
      Filename = FileExportPackageHandler.GetFullFileName(0)
    Else
      Success = False
    End If
  End If

  ' Initialise Date Breakdown
  If Success Then
    mDateBreakDown(0) = wizardFinishParameters.DateTo
    mDateBreakDown(1) = wizardFinishParameters.DateTo.AddDays(-1)
    mDateBreakDown(2) = wizardFinishParameters.DateTo.AddDays(-30)
    mDateBreakDown(3) = wizardFinishParameters.DateTo.AddDays(-60)
    mDateBreakDown(4) = wizardFinishParameters.DateTo.AddDays(-90)
    mDateBreakDown(5) = wizardFinishParameters.DateTo.AddDays(-120)
    mDateBreakDown(6) = wizardFinishParameters.DateTo.AddDays(-150)
    mDateBreakDown(7) = wizardFinishParameters.DateTo.AddDays(-180)
  End If

  ' Process Accounts
  If Success Then
    For Each ProcessAccount In wizardFinishParameters.ProcessAccounts
      With ProcessAccount
        If Not .Processed Then
          i += 1

          ' Process Account
          If Finish_ProcessAccount(.AccountPk, Filename, wizardFinishParameters.DateTo) Then
            .Processed = True
          Else
            Success = False
            Exit For
          End If
        End If

        ' Batch Handling
        If i &gt;= BATCH_SIZE Then
          BatchLimitReached = True
          Exit For
        End If
      End With

      CountProcessed += 1
    Next

    ' Progress
    If Success Then
      With wizardFinishParameters
        If BatchLimitReached Then
          ' Update User Interface message
          .SetProgressMessage()

          ' Update Package Status
          FileExportPackageHandler.StatusUpdateInProgress((CountProcessed / wizardFinishParameters.ProcessAccounts.Count) * 100)
        Else
          ' Write Footer
          Success = WriteXmlFooter(Filename)

          ' Update Package Status
          FileExportPackageHandler.StatusUpdateComplete()

          ' Process Complete
          If Success Then
            .ProcessingCompleted = True
            .ProgressMessage = "Exporting 100% Complete"
            .CompleteMessage = "Centrix Commercial Data Upload data successfully exported to the following file:" &amp; vbNewLine &amp; FileExportPackageHandler.FileNames(0) &amp; vbNewLine &amp; vbNewLine

            ' Final Filename (could be export directory, or may be about to be moved below)
            FinalFilename = FileExportPackageHandler.GetStatusFileNameFull(False)

            ' Move file to specified location
            If Len(FTPFolder) &lt;&gt; 0 AndAlso FileExportPackageHandler.DesktopExport Then
              If Right(FTPFolder, 1) &lt;&gt; System.IO.Path.DirectorySeparatorChar Then FTPFolder &amp;= System.IO.Path.DirectorySeparatorChar

              ' The Source File with Resolved Filename
              MoveSourceFile = finBL.Runtime.FileUtilities.GetFileFolder(FileExportPackageHandler.GetFullFileName(0)) &amp; System.IO.Path.DirectorySeparatorChar &amp; FileExportPackageHandler.FileNames(0)

              ' Move
              If finBL.Runtime.FileUtilities.MoveFile(MoveSourceFile, FTPFolder &amp; FileExportPackageHandler.FileNames(0)) Then
                FinalFilename = FTPFolder &amp; FileExportPackageHandler.FileNames(0)
              Else
                FileMoveFailed = True
              End If
            End If

            ' Context-specific functionality
            If FileExportPackageHandler.DesktopExport Then
              .CompleteApplicationShortcut = finBL.CreateApplicationShortcutExternal(finBL.Runtime.FileUtilities.GetFileFolder(FinalFilename)).ToUrlString(True)

              If FileMoveFailed Then
                .CompleteMessage &amp;= "Warning: Could not copy file to " &amp; FTPFolder &amp; ". It has been exported to your finPOWER Connect Export Folder." &amp; vbNewLine &amp; vbNewLine
              End If
              .CompleteMessage &amp;= "Click OK to open the Export Folder where the file has been saved."
            Else
              .CompleteMessage &amp;= "The file can be downloaded from the ""Downloads"" tab on the ""Processes &amp; Procedures"" page."
            End If
          End If
        End If
      End With
    End If
  End If

  ' Update Package Status (this will update files on desktop)
  If Not Success Then
    If Not FileExportPackageHandler.StatusUpdateFailed() Then
      ' Ignore errors
    End If
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Write the XML Header.
''' &lt;/summary&gt;
Private Function WriteXmlHeader(filename As String,
                                subscriberId As String,
                                dateCreated As Date) As Boolean

  Dim Success As Boolean
  Dim xml As String

  ' Assume Success
  Success = True

  ' Header Elements
  xml &amp;= "&lt;?xml version=""1.0"" encoding=""UTF-8""?&gt;" &amp; vbNewLine
  xml &amp;= "&lt;PositiveCommercialBureauUpload&gt;" &amp; vbNewLine
  xml &amp;= "&lt;SubscriberCode&gt;" &amp; subscriberId &amp; "&lt;/SubscriberCode&gt;" &amp; vbNewLine
  xml &amp;= "&lt;SnapshotDate&gt;" &amp; Format(dateCreated, "yyyyMMdd") &amp; "&lt;/SnapshotDate&gt;" &amp; vbNewLine
  xml &amp;= "&lt;SnapshotTime&gt;" &amp; Format(dateCreated, "HHmmss") &amp; "&lt;/SnapshotTime&gt;" &amp; vbNewLine
  xml &amp;= "&lt;Accounts&gt;" &amp; vbNewLine

  ' Write to file
  Success = finBL.Runtime.FileUtilities.WriteTextFile(filename, xml)

  Return Success

End Function


''' &lt;summary&gt;
'''  Write the XML Footer.
''' &lt;/summary&gt;
Private Function WriteXmlFooter(filename As String) As Boolean

  Dim Success As Boolean
  Dim xml As String

  ' Assume Success
  Success = True

  ' Footer Elements
  xml = "&lt;/Accounts&gt;" &amp; vbNewLine
  xml &amp;= "&lt;/PositiveCommercialBureauUpload&gt;"

  ' Write to file
  Success = finBL.Runtime.FileUtilities.AppendTextFile(filename, xml, False)

  Return Success

End Function

''' &lt;summary&gt;
'''  Process an Account.
''' &lt;/summary&gt;
Private Function Finish_ProcessAccount(accountPk As Integer,
                                       filename As String,
                                       dateTo As Date) As Boolean

  Dim Account As finAccount
  Dim AccountClient As finAccountClient
  Dim AccountOverdue As finAccountOverdue
  Dim AccountOverdues As finAccountOverdues
  Dim AgedAmount As Decimal
  Dim AddressCurrent As ISAddressDetails
  Dim AddressMailing As ISAddressDetails
  Dim CreditLimit As Decimal
  Dim i As Integer
  Dim LastPaymentAmount As Decimal
  Dim LastPaymentDate As Date
  Dim PaymentCycleFreqPA As Double
  Dim Success As Boolean
  Dim XmlBuilder As ISXmlBuilder

  ' Assume Success
  Success = True

  ' Initialise
  Account = finBL.CreateAccount()
  AccountOverdues = finBL.CreateAccountOverdues()
  XmlBuilder = finBL.Runtime.CreateXmlBuilder()

  ' Process Account
  If Account.LoadPk(accountPk) Then
    XmlBuilder.ElementOpen("Account")
    XmlBuilder.WriteElementString("AccountId", Account.AccountId)
    XmlBuilder.WriteElementString("AccountStartDate", Format(Account.DateOpened, "yyyyMMdd"))
    If Account.Status &lt;&gt; isefinAccountStatus.Open Then
      XmlBuilder.WriteElementString("AccountEndDate", Format(Account.DateClosed, "yyyyMMdd"))
    End If

    ' Process Owner Clients where Organisation or Sole Trader
    XmlBuilder.ElementOpen("AccountHolders")
    For Each AccountClient In Account.Clients
      If AccountClient.IsOwner AndAlso (AccountClient.IsOrganisation OrElse AccountClient.IsSoleTrader) Then
        ' Get Addresses
        AddressCurrent = AccountClient.Client.ContactAddresses.GetCurrentPhysicalAddress()
        If AddressCurrent.HasValue Then
          AddressMailing = AccountClient.Client.ContactAddresses.GetCurrentPostalAddress()
        Else
          AddressCurrent = AccountClient.Client.ContactAddresses.GetCurrentPostalAddress()
        End If
        XmlBuilder.ElementOpen("AccountHolder")
        XmlBuilder.WriteElementString("AccountHolderId", AccountClient.ClientId)

        ' Names
        XmlBuilder.ElementOpen("Names")
        Me.InsertName(XmlBuilder, "R", AccountClient.Client.LegalNameResolved)
        If AccountClient.Client.LegalName &lt;&gt; AccountClient.Client.Name Then
          Me.InsertName(XmlBuilder, "T", AccountClient.Client.Name)
        End If
        XmlBuilder.ElementClose("Names")

        XmlBuilder.WriteElementString("CompanyNumber", AccountClient.Client.OrganisationNumber, False)
        XmlBuilder.WriteElementString("NZBN", AccountClient.Client.BusinessNumber, False)

        ' Adresses
        If AddressCurrent.HasValue OrElse (AddressMailing IsNot Nothing AndAlso AddressMailing.HasValue) Then
          XmlBuilder.ElementOpen("Addresses")
          Me.InsertAddress(XmlBuilder, "C", AddressCurrent)
          Me.InsertAddress(XmlBuilder, "M", AddressMailing)
          XmlBuilder.ElementClose("Addresses")
        End If

        XmlBuilder.WriteElementString("Email", AccountClient.Client.ContactMethods.GetCurrentEmail.Value, False)
        XmlBuilder.WriteElementString("Website", AccountClient.Client.ContactMethods.GetCurrentWebsite.Value, False)
        XmlBuilder.ElementClose("AccountHolder")
      End If
    Next
    XmlBuilder.ElementClose("AccountHolders")

    ' Account Information
    Select Case Account.AccountClass
      Case isefinAccountClass.LoanRC
        XmlBuilder.WriteElementString("CreditType", "R")
      Case Else
        XmlBuilder.WriteElementString("CreditType", "F")
    End Select
    If Account.AccountType.CreditLimitCount &lt;&gt; 0 Then
      Account.GetCreditLimits(dateTo, CreditLimit, 0, 0)
      XmlBuilder.WriteElementDecimal("CreditLimit", finBL.CurrencyRound(CreditLimit))
    End If

    ' Aged Balances
    XmlBuilder.ElementOpen("AgedBalances")
    If AccountOverdues.LoadFromAccount(Account, False, dateTo) Then
      If AccountOverdues.TotalOverdue &lt;= 0 Then
        ' Nil/ Credit Balance
        XmlBuilder.ElementOpen("AgedBalance")
        XmlBuilder.WriteElementString("Period", "0")
        XmlBuilder.WriteElementDecimal("Amount", finBL.CurrencyRound(0))
        XmlBuilder.ElementClose("AgedBalance")
      Else
        For i = 0 To 7
          AgedAmount = 0
          For Each AccountOverdue In AccountOverdues
            If i = 7 Then
              If AccountOverdue.Date &lt;= mDateBreakdown(7) Then
                AgedAmount += AccountOverdue.ValueDue
              End If
            Else
              If AccountOverdue.Date &lt;= mDateBreakdown(i) AndAlso AccountOverdue.Date &gt; mDateBreakdown(i + 1) Then
                AgedAmount += AccountOverdue.ValueDue
              End If
            End If
          Next

          XmlBuilder.ElementOpen("AgedBalance")
          If i = 7 Then
            XmlBuilder.WriteElementString("Period", "X")
          Else
            XmlBuilder.WriteElementString("Period", CStr(i))
          End If
          XmlBuilder.WriteElementDecimal("Amount", finBL.CurrencyRound(AgedAmount))
          XmlBuilder.ElementClose("AgedBalance")
        Next i
      End If
    Else
      XmlBuilder.ElementOpen("AgedBalance")
      XmlBuilder.WriteElementString("Period", "U")
      XmlBuilder.WriteElementDecimal("Amount", finBL.CurrencyRound(0))
      XmlBuilder.ElementClose("AgedBalance")
    End If
    XmlBuilder.ElementClose("AgedBalances")

    ' Payment Frequency
    Select Case Account.AccountClass
      Case isefinAccountClass.LoanRC
        PaymentCycleFreqPA = finBL.Utilities.DateCycleGetFreqPA(Account.Calculation.StatementCycle)
      Case Else
        PaymentCycleFreqPA = Account.Calculation.PaymentCycleFreqPA
    End Select
    Select Case PaymentCycleFreqPA
      Case 1: XmlBuilder.WriteElementString("PaymentFrequency", "Y")
      Case 2: XmlBuilder.WriteElementString("PaymentFrequency", "H")
      Case 4: XmlBuilder.WriteElementString("PaymentFrequency", "Q")
      Case 12: XmlBuilder.WriteElementString("PaymentFrequency", "M")
      Case 26: XmlBuilder.WriteElementString("PaymentFrequency", "F")
      Case 52: XmlBuilder.WriteElementString("PaymentFrequency", "W")
      Case Else: XmlBuilder.WriteElementString("PaymentFrequency", "V")
    End Select

    ' Last Payment
    If Account.GetLastPayment(LastPaymentDate, LastPaymentAmount, dateTo) AndAlso LastPaymentDate &lt;&gt; Nothing Then
      XmlBuilder.WriteElementString("LastPaymentDate", Format(LastPaymentDate, "yyyyMMdd"))
      XmlBuilder.WriteElementDecimal("LastPaymentAmount", finBL.CurrencyRound(LastPaymentAmount))
    End If

    XmlBuilder.ElementClose("Account")

    ' Export
    If Success Then
      Success = finBL.Runtime.FileUtilities.AppendTextFile(filename, XmlBuilder.ToXmlString(False), True)
    End If
  Else
    Success = False
  End If

  Return Success

End Function

Private Sub InsertAddress(xmlBuilder As ISXmlBuilder,
                          addressType As String,
                          address As ISAddressDetails)

  Dim Country As String

  If Address IsNot Nothing AndAlso Address.HasValue Then
    ' Find Country
    If Len(address.Country) = 0 Then
      Country = "NZL"
    Else
      Country = finBL.CreditBureau.Services("CentrixNZ").CodeTables("CountryCodes").GetCodeFromDescription(address.Country)
    End If

    With xmlBuilder
      .ElementOpen("Address")
      .WriteElementString("AddressType", addressType)
      If Len(address.PropertyName) = 0 Then
        .WriteElementString("AddressLine1", address.StreetAddressFull)
        '.WriteElementString("AddressLine2", "")
      Else
        .WriteElementString("AddressLine1", address.PropertyName)
        .WriteElementString("AddressLine2", address.StreetAddressFull)
      End If
      .WriteElementString("Suburb", Address.Suburb, False)
      .WriteElementString("TownCity", Address.City)
      .WriteElementString("Country", Country, False)
      .WriteElementString("Postcode", Address.Postcode, False)
      .ElementClose("Address")
    End With
  End If

End Sub

Private Sub InsertName(xmlBuilder As ISXmlBuilder,
                       nameType As String,
                       nameValue As String)

  If Len(nameValue) &lt;&gt; 0 Then
    With XmlBuilder
      .ElementOpen("Name")
      .WriteElementString("NameType", nameType)
      .WriteElementString("NameValue", nameValue)
      .ElementClose("Name")
    End With
  End If

End Sub

''' &lt;summary&gt;
'''  Get Initialisation Information.
''' &lt;/summary&gt;
Private Function GetInitialisationInfo(ByRef returnValue As String) As Boolean

  Dim DateTo As Date
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim Success As Boolean
  Dim EntityFilter As String
  Dim ValidEntityCount As Integer
  Dim DefaultEntityId As String

  ' Assume Success
  Success = True

  ' Parameters

  ' Initialise
  FormInitialisationInfo = New FormInitialisationInfo()

  ' Get Entity details
  EntityFilter = GetEntityFilter(DefaultEntityId, ValidEntityCount)

  ' Validate
  If finBL.CountryCode &lt;&gt; "NZ" Then
    Success = False
    finBL.Error.ErrorBegin("The Centrix Commercial Data Upload is only available in NZ databases.")
  ElseIf finBL.AccountTypes.GetAccountTypePksListCreditTypeCommercial.Count = 0 Then
    Success = False
    finBL.Error.ErrorBegin("There are no 'Commercial' Account Types to Report upon.")
  ElseIf Len(FTPFolder) &lt;&gt; 0 AndAlso Not finBL.Runtime.FileUtilities.FolderExists(FTPFolder) Then
    Success = False
    finBL.Error.ErrorBeginFormat("FTP folder '{0}' does not exist.", FTPFolder)
  ElseIf ValidEntityCount = 0 Then
    Success = False
    finBL.Error.ErrorBegin("All Entities have been excluded from the Centrix Commercial Data Upload.")
  End If

  ' Build Object
  If Success Then
    With FormInitialisationInfo
      ' Default Entity
      .EntityId = DefaultEntityId

      ' Override Entity if there is only a single Entity
      If ValidEntityCount = 1 Then
        .EntityName = finBL.Entities(.EntityId).Name
      End If

      ' Record
      DateTo = finBL.Runtime.DateUtilities.EndOfPreviousMonth(finBL.TimeZoneFunctions.GetCurrentDatabaseDate())
      .DateFrom = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(New DateTime(DateTo.Year, DateTo.Month, 1))
      .DateTo = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(DateTo)

      ' Excluded details
      If mCombinedParameters.GetBoolean("ShowExcluded") Then
        If Len(mExcludeAccountLedgers) &lt;&gt; 0 OrElse Len(mExcludeAccountTypes) &lt;&gt; 0 OrElse Len(mExcludeBranches) &lt;&gt; 0 OrElse Len(mExcludeDepartments) &lt;&gt; 0 Then
          .InformationText = "The Centrix Commercial Data Upload will automatically &lt;b&gt;exclude&lt;/b&gt; the following:"

          .InformationText &amp;= "&lt;ul&gt;"
          If Len(mExcludeAccountTypes) &lt;&gt; 0 Then .InformationText &amp;= "&lt;li&gt;Account Types: &lt;b&gt;" &amp; finBL.HtmlEncode(mExcludeAccountTypes) &amp; "&lt;/b&gt;&lt;/li&gt;"
          If Len(mExcludeBranches) &lt;&gt; 0 Then .InformationText &amp;= "&lt;li&gt;Branches: &lt;b&gt;" &amp; finBL.HtmlEncode(mExcludeBranches) &amp; "&lt;/b&gt;&lt;/li&gt;"
          If Len(mExcludeDepartments) &lt;&gt; 0 Then .InformationText &amp;= "&lt;li&gt;Departments: &lt;b&gt;" &amp; finBL.HtmlEncode(mExcludeDepartments) &amp; "&lt;/b&gt;&lt;/li&gt;"
          If Len(mExcludeAccountLedgers) &lt;&gt; 0 Then .InformationText &amp;= "&lt;li&gt;Account Ledgers: &lt;b&gt;" &amp; finBL.HtmlEncode(mExcludeAccountLedgers) &amp; "&lt;/b&gt;&lt;/li&gt;"
          .InformationText &amp;= "&lt;/ul&gt;"
        End If
      End If

      ' Configuration
      .EntityFilter = EntityFilter

      ' Form Heading
      .FormHeading = ScriptInfo.ScriptCaption
      If Len(.FormHeading) = 0 Then .FormHeading = "Centrix Commercial Data Upload"
    End With
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Entity Filter.
''' &lt;/summary&gt;
Private Function GetEntityFilter(ByRef defaultEntityId As String,
                                 ByRef validEntityCount As Integer) As String

  Dim BranchRange As ISRanges
  Dim BranchRO As finBranchRO
  Dim EntityList As ISList
  Dim sqlWhere As ISSqlWhereBuilder
  Dim EntityId As String

  ' Initialise
  EntityList = New ISList()
  sqlWhere = finBL.Database.CreateSqlWhereBuilder()

  ' Get Branch Range to exclude
  BranchRange = finBL.Runtime.CreateRanges(mExcludeBranches)

  ' Determine Entities
  For Each BranchRO In finBL.Branches
    If BranchRange.IsValueInRange(BranchRO.BranchId) AndAlso Len(mExcludeBranches) &lt;&gt; 0 Then
      ' Exclude Branch
    Else
      EntityList.Add(CStr(BranchRO.EntityPk), True)
    End If
  Next

  ' Default Entity
  If finBL.SettingsUser.DefaultClientBranchPkResolved &lt;&gt; 0 Then
    EntityId = finBL.Branches.ItemByPk(finBL.SettingsUser.DefaultClientBranchPkResolved).EntityId

    If Len(EntityId) &lt;&gt; 0 AndAlso EntityList.Exists(CStr(finBL.Entities(EntityId).Pk), True) Then
      defaultEntityId = EntityId
    End If
  End If

  ' Valid Entity Count
  validEntityCount = EntityList.Count
  If Len(defaultEntityId) = 0 AndAlso validEntityCount = 1 Then
    defaultEntityId = finBL.Entities.ItemByPk(CInt(EntityList(0))).EntityId
  End If

  ' SQL Where
  With sqlWhere
    .AppendIn("Pk", EntityList.ToCsvString())
  End With

  Return sqlWhere.SqlWhere

End Function

''' &lt;summary&gt;
'''  Validate a Wizard page.
''' &lt;/summary&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 strTemp As String
  Dim Success As Boolean
  Dim EntityId As String
  Dim DateTo As Date
  Dim CostCentreResolved As finCostCentreResolved

  ' 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
    DateTo = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(.GetDate("DateTo"))
    EntityId = .GetString("EntityId")
    PageId = .GetString("PageId")
  End With

  ' Validate Page
  Select Case PageId
    Case "General"
      ' General
      ' Get Cost Centre
      Success = GetCostCentreResolved(EntityId, CostCentreResolved)

      ' Generate Confirmation Message
      If Success Then
        strTemp = "Centrix Commercial Data Upload file will be generated using the following details:" &amp; vbNewLine &amp; vbNewLine
        strTemp &amp;= String.Format("Entity: {0}, '{1}'", EntityId, finBL.Entities(EntityId).Name) &amp; vbNewLine
        strTemp &amp;= "Subscriber: " &amp; CostCentreResolved.CentrixNZ.SubscriberId &amp; vbNewLine
        strTemp &amp;= "Date to: " &amp; finBL.FormatDateLong(DateTo) &amp; vbNewLine &amp; vbNewLine
        strTemp &amp;= "Continue?"

        Data = strTemp
      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



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

  ' Record
  Public DateFrom As Date
  Public DateTo As Date
  Public EntityId As String
  Public EntityName As String
  Public InformationText As String

  ' Configuration
  Public EntityFilter As String
  Public FormHeading As String

End Class



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

  Public CompleteApplicationShortcut As String
  Public CompleteMessage As String
  Public DateTo As Date
  Public PackageStatusFilename As String
  Public ProcessAccounts As New List(Of ProcessAccount)
  Public ProcessingCompleted As Boolean
  Public ProgressMessage As String

  ''' &lt;summary&gt;
  '''  Set Progress Message.
  ''' &lt;/summary&gt;
  Public Sub SetProgressMessage()

    Dim CountComplete As Integer
    Dim ProcessAccount As ProcessAccount

    ' Count Completed Items
    CountComplete = 0
    For Each ProcessAccount In Me.ProcessAccounts
      If ProcessAccount.Processed Then
        CountComplete += 1
      End If
    Next

    ' Progress Message
    If Me.ProcessAccounts.Count &lt;&gt; 0 Then
      Me.ProgressMessage = String.Format("Exporting {0} Complete", finBLShared.FormatPercentage(CountComplete / Me.ProcessAccounts.Count, 0, False))
    Else
      Me.ProgressMessage = "Exporting 100% Complete"
    End If

  End Sub

End Class



''' &lt;summary&gt;
'''  Account to Process
''' &lt;/summary&gt;
Public Class ProcessAccount

  Public AccountPk As Integer
  Public Processed As Boolean

  Public Sub New()
  End Sub

  Public Sub New(accountPk As Integer)

    Me.AccountPk = accountPk
    Me.Processed = False

  End Sub

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</Code>
    <Language>VisualBasic</Language>
    <Notes>System defined HTML Widget.

Used to create a "Centrix (New Zealand)" Commercial Data Upload Export file.

Includes Accounts where:
* Account belongs to Entity selected
* Account Type's Credit Type is "Commercial"
* Comprehensive Credit Reporting is not suspended
* Includes at least one owner Client that is an Organisation or Sole Trader
* Account was open on the To date, or closed between From and To dates (inclusive).
* Only owner Clients of the Account are included if they are an Organisation or Sole Trader</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="General" tooltipText="Select export options."&gt;Centrix Commercial Data Upload&lt;/li&gt;
      &lt;ul&gt;
    &lt;/div&gt;
  &lt;/header&gt;

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

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

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblEntity"&gt;Select the Entity&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="lblDateRange"&gt;Specify a Period to include in the Export&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateFrom"&gt;From:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="dateFrom" /&gt;&amp;nbsp;&amp;nbsp;to&amp;nbsp;&amp;nbsp;&lt;input id="dateTo" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;td colspan="2"&gt;&lt;div id="divRangeInformation" class="is-info-text info small" style="display:none"&gt;&lt;/div&gt;&lt;/td&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;
// Record
var mRecord;

// Controls
var C = {
  lblEntity: null,
  cboEntity: null,

  lblDateRange: null,
  dateFrom: null,
  dateTo: null,
  divRangeInformation: null,
}

// Form
var frmMain;
var tabWizard;

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

// Other
var mConfirmation;

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

  // Controls
  C.lblEntity = widget.UI.Label("lblEntity", {});
  C.cboEntity = widget.UI.DBCombo("cboEntity", {
    allowBlank: false,
    limitToList: true,
    maxLength: 5,
    width: widget.UI.FIELD_WIDTH_CODE_5,
  });

  C.lblDateRange = widget.UI.Label("lblDateRange", {
    tooltipText: "Accounts closed on or after the 'From' date will be included in the export.",
  });
  C.dateFrom = widget.UI.DateBox("dateFrom", {
    allowBlank: false,
  });
  C.dateTo = widget.UI.DateBox("dateTo", {
    allowBlank: false,
  });
  C.divRangeInformation = $("#divRangeInformation");

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

// ==========
// Form Reset
// ==========
function Form_Reset() {
  // Defaults

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

  // Resize
  Form_Resize();

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

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

    // Fail
    function (message) {
      // Unblock
      widget.UI.Unblock();

      // Special case - close HTML Widget on error
      widget.UI.MsgBoxAlert("fail: " + message, {}, tabWizard_Cancel);
    }
  );
}

// ===========
// Fields Load
// ===========
function Fields_Load() {
  var strTemp = "";

  if (mRecord) {
    // General
    C.cboEntity.Text(mRecord.EntityId);
    C.dateFrom.Value(mRecord.DateFrom);
    C.dateTo.Value(mRecord.DateTo);
  }

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

  // Update Controls

  // Update fields
  Fields_Update();

  // Refresh Tab
  tabWizard_Refresh(0);
}

// =============
// Fields Update
// =============
function Fields_Update() {
  // Heading
  if (mRecord) {
    widget.SetHeading(mRecord.FormHeading);
  }

  // Information Lists

  // Lists
  if (mRecord) {
    if (mRecord.EntityName) {
      C.cboEntity.ReadOnly(true);
      C.cboEntity.RefreshUnbound(mRecord.EntityId, mRecord.EntityName);
    }
    else {
      C.cboEntity.RefreshFromStandardRange("Entities", mRecord.EntityFilter);
    }
  }

  // Controls
  if(mRecord) {
    // Display Range Information
    if (mRecord.InformationText) {
      C.divRangeInformation.html(mRecord.InformationText);
      C.divRangeInformation.show();
    }
  }

  // Update Buttons
  tabWizard_UpdateButtons();

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

  // Resize Tab
  tabWizard_Resize();
}

// ========================
// Create Finish Parameters
// ========================
function CreateFinishParameters() {
  var params = {
    entityId: C.cboEntity.Text(),
    dateFrom: C.dateFrom.Value(),
    dateTo: C.dateTo.Value(),
  }

  return params;
}

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

  // Tab
  tabWizard_Resize();
}

// =================
// Execute an Action
// =================
function Form_ExecuteAction(actionId) {
  switch (actionId.toUpperCase()) {
    case "CANCEL":
      // Cancel
      tabWizard_Cancel();
      break;

    case "FINISH":
      // Finish
      Form_ExecuteAction_Finish();
      break;

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

// =============
// Finish Action
// =============
function Form_ExecuteAction_Finish() {
  // Validate
  tabWizard_Validate(function () {
    if (mConfirmation) {
      widget.UI.MsgBoxConfirm(mConfirmation, {}, Form_ExecuteAction_FinishPost, null);
    }
    else {
      widget.UI.MsgBoxConfirm("Are you sure you want to generate the Centrix Commercial Data Upload file?", {}, Form_ExecuteAction_FinishPost, null);
    }
  });
}

function Form_ExecuteAction_FinishPost(moveAction) {
  // Hide From
  frmMain.Visible(false);

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

  // Create Parameters
  var params = CreateFinishParameters();

  // Finish
  widget.GetString("Finish", params,
    function (data) {
      // Continue Processing
      Form_ExecuteAction_FinishPost_Process(data);
    },

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

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

      // Show form
      frmMain.Visible(true);
    }
  );
}

function Form_ExecuteAction_FinishPost_Process(data) {
  // Parse
  data = JSON.parse(data);

  // Process Complete?
  if (data.ProcessingCompleted) {
    // Show form
    frmMain.Visible(true);

    // Unblock
    widget.UI.Unblock();

    // Message box and close
    widget.UI.MsgBoxInfo(data.CompleteMessage, {}, function() {
      // Launch Application Shortcut
      if (data.CompleteApplicationShortcut) {
        widget.ExecuteApplicationShortcutUrl(data.CompleteApplicationShortcut);
      }

      // Close
      tabWizard_Cancel();
    });
  }
  else {
    // Update Block Message
    widget.UI.Block(data.ProgressMessage);

    // Process next batch
    widget.GetString("Finish_ProcessBatch", data, Form_ExecuteAction_FinishPost_Process, function(errorMessage) {
      // Show form
      frmMain.Visible(true);

      // Unblock
      widget.UI.Unblock();

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

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

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

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

  // Tweak fields

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

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

  // Resize Wizard
  tabWizard_Resize();

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

function tabWizard_Resize() {
  switch (tabWizard.SelectedTabId()) {
    case "General":
      C.cboEntity.WidthResizeFromParent();
      break;

    default:
      break;
  }
}

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

  // Other client-side validation
  if (Ok) {
    switch (tabWizard.SelectedTabId()) {
      case "General":
        if (C.dateFrom.Value() &gt; C.dateTo.Value()) {
          Ok = false;
          widget.UI.MsgBoxAlert("Date From must be earlier than or on Date To.");
        }
        break;

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

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

    switch (tabWizard.SelectedTabId()) {
      case "General":
        params = {
          entityId: C.cboEntity.Text(),
          dateTo: C.dateTo.Value(),
        }
        break;

      default:
        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 &amp;&amp; o.Data) {
          mConfirmation = o.Data;
        }
        else {
          mConfirmation = null;
        }
        break;
    }

    // Callback
    validCallback();
  }
}

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

  // Enable form
  frmMain.FormEnable();
}

function tabWizard_UpdateButtons() {
  var tabIndex = tabWizard.SelectedTabIndex();

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

  // Tweaks
  cmdFinish.html("Export");
}
&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>8dXfNo6qBEu7Rv0eNCyT3Q</UniqueId>
    <AllowRefresh>true</AllowRefresh>
    <Caption />
    <HtmlWidgetMaxHeight>700</HtmlWidgetMaxHeight>
    <HtmlWidgetMaxWidth>700</HtmlWidgetMaxWidth>
    <HtmlWidgetNeverApplyStyling>false</HtmlWidgetNeverApplyStyling>
    <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>Set default values to exclude records.</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText>Set rules for exclusion as the default values for the below. This will allow these settings to be applied to all Users running the Centrix Commercial Data Upload.
Do not use the not (!) Range operator, as this will result in the record being included rather than excluded.</TooltipText>
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="ShowExcluded" type="Boolean">
            <BlankTip />
            <Caption>Show excluded details?</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="ExcludeAccountTypes" type="Range">
            <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>
            <Rows>1</Rows>
            <RangeSingle>false</RangeSingle>
            <RangeType>Standard</RangeType>
            <RangeLookupSource>AccountTypes</RangeLookupSource>
            <RangeLookupSqlWhere />
          </Parameter>
          <Parameter name="ExcludeBranches" type="Range">
            <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>
            <Rows>1</Rows>
            <RangeSingle>false</RangeSingle>
            <RangeType>Standard</RangeType>
            <RangeLookupSource>Branches</RangeLookupSource>
            <RangeLookupSqlWhere />
          </Parameter>
          <Parameter name="ExcludeDepartments" type="Range">
            <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>
            <Rows>1</Rows>
            <RangeSingle>false</RangeSingle>
            <RangeType>Standard</RangeType>
            <RangeLookupSource>Departments</RangeLookupSource>
            <RangeLookupSqlWhere />
          </Parameter>
          <Parameter name="ExcludeAccountLedgers" type="Range">
            <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>
            <Rows>1</Rows>
            <RangeSingle>false</RangeSingle>
            <RangeType>Standard</RangeType>
            <RangeLookupSource>AccountLedgers</RangeLookupSource>
            <RangeLookupSqlWhere />
          </Parameter>
        </Parameters>
      </ISParameterDefs>
    </Parameters>
    <Constants>
      <ISScriptConstants version="1.00">
        <ScriptConstant name="FTPFolder" constantType="String">
          <Notes>The folder where the Centrix Commercial Data Upload Files are sent to Centrix from (ignored if running outside of finPOWER Connect Desktop).</Notes>
          <Value />
          <Encrypt>false</Encrypt>
        </ScriptConstant>
      </ISScriptConstants>
    </Constants>
  </finScript>