<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2024-04-19T03:44:13.0000000">
    <CreatedUserId>Admin</CreatedUserId>
    <CreatedUtcDate>2023-05-24T20:43:03.0580000</CreatedUtcDate>
    <UpdatedUserId>Admin</UpdatedUserId>
    <UpdatedUtcDate>2024-04-19T03:43:31.8560000</UpdatedUtcDate>
    <ScriptId>HWTesting</ScriptId>
    <Description>Annual Commerce Commission Report (New Zealand)</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_CommerceCommission_Report_NZ
Option Explicit On
Option Strict On

' #################################################################
' Annual Commerce Commission Report (New Zealand)
'
' Version: 1.05 (19/04/2024)
'
' https://www.legislation.govt.nz/regulation/public/2004/0240/latest/LMS627791.html
' https://comcom.govt.nz/__data/assets/pdf_file/0020/311528/Annual-Returns-Guidance.pdf
' https://comcom.govt.nz/__data/assets/pdf_file/0020/311528/Annual-returns-guidance-June-2023.pdf
'
' NOTE: Uses Web Services Background Processes but can also work from desktop without Web Services
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.00  18/09/2023  ISS      J024090   Created
'    1.01  03/10/2023  ISS      J032085   Typo correction
'    1.02  04/10/2023  ISS      J032174   Freeze headings rows of report worksheets
'    1.03  03/04/2024  ISS      J033219   Corrected spelling error
'    1.04  11/04/2024  ISS      J033278   Credit Limit reported in 7.5 Sheet now shows highest Credit Limit, Removed HadSubsequentAdvances
'    1.05  19/04/2024  ISS      J033348   Removed unused variables
' #################################################################

' Constants

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

' Parameters
Private mEntity As finEntityRO
Private mPeriodStart As Date
Private mPeriodEnd As Date

' Properties
Private mAccountRecords As List(Of AccountRecord)
Private mExcelWorkbook As ISExcelWorkbook

' Other
Private mDesktopMode As Boolean
Private mProcessStatus As finHtmlWidgetBackgroundProcessStatus

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

  ' Assume Success
  Main = True

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

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

  ' Get Common Parameters
  With mCombinedParameters
    mDesktopMode = .GetBoolean("DesktopMode")
  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 "BackgroundProcess.Execute"
      ' Called by Web Services to execute a Background Process that was initially queued in the Widget's UI (via the Finish event)
      Main = BackgroundProcess_Execute(returnValue)

    Case "CancelBackgroundProcess"
      ' Cancel a Process
      Main = CancelBackgroundProcess(returnValue)

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

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

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

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

    Case "WizardValidate"
      ' Validate wizard page
      Main = WizardValidate(parametersJson, returnValue)

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

End Function

Private Function BackgroundProcess_Execute(ByRef returnValue As String) As Boolean
  
  Dim Cancelled As Boolean
  Dim obj As Object
  Dim ReportFileName As String
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters
  
  ' Assume Success
  Success = True
  
  ' Get Background Process
  ' NOTE: This is required to add events and to check to see if the User has attempted to cancel this process (if supported)
  mProcessStatus = DirectCast(ScriptInfo.ContextData.GetObject("ProcessStatus"), finHtmlWidgetBackgroundProcessStatus)
  
  ' Parse Parameters
  If finBL.Runtime.WebUtilities.DeserialiseJsonStringToObject(mParameters.ToSimpleJsonString(), GetType(WizardFinishParameters), obj) Then
    WizardFinishParameters = DirectCast(obj, WizardFinishParameters)
  Else
    Success = False
  End If
  
  ' Get Parameters
  mEntity = finBL.Entities.GetItem(WizardFinishParameters.EntityId)
  mPeriodStart = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(WizardFinishParameters.PeriodStart)
  mPeriodEnd = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(WizardFinishParameters.PeriodEnd)
  
  ' Initialise
  mAccountRecords = New List(Of AccountRecord)
  
  ' Notify
  If Success Then
    mProcessStatus.AddEvent_Information("Starting Report", String.Format("Entity '{0}', from {1} to {2}", mEntity.EntityId, finBL.FormatDateLong(mPeriodStart), finBL.FormatDateLong(mPeriodEnd)))
  End If

  ' Populate Account List
  If Success AndAlso Not Cancelled Then
    mProcessStatus.AddEvent_Information("Processing Accounts")
    Success = ProcessAccounts(Cancelled)
  End If

  ' ---------------------
  ' Create Excel Workbook
  ' ---------------------
  If Success AndAlso Not Cancelled Then
    mProcessStatus.AddEvent_Information("Creating Excel Workbook")
    Success = CreateWorkbook(ReportFileName)
  End If
  
  ' The above file has been saved to Downloads but, we can also attach it to any Success email
  If Success AndAlso Not Cancelled Then
    mProcessStatus.Attachments.Add(ReportFileName)
    
    ' Log location if in Desktop Mode so finPOWER Connect can prompt the User to open the file
    If mDesktopMode Then
      mProcessStatus.AddEvent_Information("Saved to " &amp; ReportFileName)
      
      mProcessStatus.OtherDetails.SetString("ReportFileName", ReportFileName)
    End If
  End If
  
  Return Success  
  
End Function

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

  Dim ProcessId As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

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

  Return Success

End Function

Private Function CreateWorkbook(ByRef reportFileName As String) As Boolean
  
  Dim FileExportPackageHandler As finwsFileExportPackageHandler    
  Dim Success As Boolean
  
  ' Assume Success
  Success = True
  
  ' Create the Excel Workbook and Worksheets
  mExcelWorkbook = finBL.CreateExcelWorkbook()

  ' Create Worksheets
  Me.CreateWorksheet7x1()
  Me.CreateWorksheet7x3()
  Me.CreateWorksheet7x4()
  Me.CreateWorksheet7x5()
  
  ' Accounts (raw data)
  Me.CreateWorksheetAccounts()
  
  ' Calculate Workbook
  mExcelWorkbook.Calculate()

  ' Create Export Package
  Success =  finBL.HtmlWidgetUtilities.CreateProcessFileExportPackageHandler(ScriptInfo.ScriptCaption, ScriptInfo.ScriptId, FileExportPackageHandler)
  
  ' Create a File Name for the Package
  If Success Then
    FileExportPackageHandler.CreateFileName(String.Format("CommerceCommission_AnnualReport_NZ_{0}.xlsx", finBL.TimeZoneFunctions.GetCurrentDatabaseDateTime().ToString("yyyyMMdd_HHmmss")))
    reportFileName = FileExportPackageHandler.GetFullFileName(0)
  End If
  
  ' Update Package Status
  If Success Then
    FileExportPackageHandler.StatusUpdateInProgress(0)
  End If
  
  ' Save the Excel file
  If Success Then
    Success = mExcelWorkbook.Save(reportFileName)
  End If
  
  ' Finalise
  If Success Then
    If FileExportPackageHandler.StatusUpdateComplete(mDesktopMode) Then
      ' Desktop finalise has removed the "Package_" prefix from the file names so we 
      If mDesktopMode Then
        reportFileName = FileExportPackageHandler.GetShortFileName(0)        
      End If
    Else
      Success = False
    End If
  ElseIf FileExportPackageHandler IsNot Nothing Then
    Success = FileExportPackageHandler.StatusUpdateFailed()
  End If
  
  Return Success
  
End Function  

Private Function CreateWorksheet(worksheetName As String,
                                 ByRef Worksheet As ISExcelWorksheet) As Boolean

  Dim Success As Boolean
  
  ' Assume Success
  Success = True
  
  ' Initialise ByRef
  Worksheet = Nothing
  
  ' Create Worksheet
  If mExcelWorkbook.Worksheets.Add(worksheetName) Then
    Worksheet = mExcelWorkbook.Worksheets(worksheetName)
    If Worksheet Is Nothing Then Success = False
  Else
    Success = False
  End If 
  
  Return Success
  
End Function


Private Sub CreateWorksheet7x1()

  Dim AccountRecord As AccountRecord
  Dim AccountType As finAccountTypeRO
  Dim Count As Integer
  Dim RowIndex As Integer
  Dim Success As Boolean
  Dim Worksheet As ISExcelWorksheet

  ' Create Worksheet
  Success = CreateWorksheet("7.1 - Number of HCCCC", Worksheet) 

  ' Columns
  If Success Then
    With Worksheet.Columns
      With .Item(3).Style
        .HorizontalAlignment = iseExcelCellStyle_HorizontalAlignment.Right
      End With
    End With  
  End If
  
  ' Header Row
  If Success Then
    With Worksheet
      RowIndex = 1
      
      ' Bold
      .Rows(RowIndex).Style.Bold = True
      
      .Cell(1, RowIndex).SetString("Account Type")
      .Cell(2, RowIndex).SetString("Description")
      .Cell(3, RowIndex).SetString("Count")
    End With
  End If

  ' Add Rows
  If Success Then
    For Each AccountType In finBL.AccountTypes
      Select Case AccountType.AccountClass
        Case isefinAccountClass.LoanFR, isefinAccountClass.LoanFT, isefinAccountClass.LoanRC
          If AccountType.CreditType = isefinAccountCreditType.Consumer AndAlso AccountType.ConsumerRegulationType = isefinAccountConsumerRegulationType.NZ_HighCostConsumerCreditContract Then
            RowIndex += 1
            
            Count = 0
            For Each AccountRecord In mAccountRecords
              If AccountRecord.AccountTypeId = AccountType.AccountTypeId Then
                If AccountRecord.DateOpened &gt;= mPeriodStart Then Count += 1 
              End If  
            Next  
            
            With Worksheet
              .Cell(1, RowIndex).SetString(AccountType.AccountTypeId)
              .Cell(2, RowIndex).SetString(AccountType.Description)
              .Cell(3, RowIndex).SetInteger(Count)
            End With  
          End If  
        End Select    
    Next  
  End If
  
  ' Add Total Row 
  If Success AndAlso RowIndex &gt; 2 Then
    With Worksheet
      RowIndex += 1
  
      ' Bold
      .Rows(RowIndex).Style.Bold = True
  
      .Cell(1, RowIndex).SetString("Total")
      ' Add SUMs starting at row 2 because row 1 is the Header row
      .Cell(3, RowIndex).Formula = String.Format("=SUM(C2:C{0})", RowIndex - 1)
      
      ' Bold
      .Rows(RowIndex).Style.Bold = True
    End With  
  End If

  If Success Then
    ' Resize columns to fit
    Worksheet.Columns.Autofit()
    
    ' Freeze headings row
    Worksheet.FreezePanes(1, 0)
    
    ' Add Notes
    With Worksheet
      .Cell(1, RowIndex + 2).SetString(String.Format("Entity: {0} - {1}.", mEntity.EntityId, mEntity.Name))
      .Cell(1, RowIndex + 3).SetString(String.Format("Reporting period: {0} to {1}.", finBL.FormatDateLong(mPeriodStart), finBL.FormatDateLong(mPeriodEnd)))
      .Cell(1, RowIndex + 4).SetString("NOTE: does not take into account related Consumer Credit Accounts.")
    End With  
  End If

End Sub

Private Sub CreateWorksheet7x3()

  Dim AccountRecord As AccountRecord
  Dim AccountType As finAccountTypeRO
  Dim Count As Integer
  Dim RowIndex As Integer
  Dim Success As Boolean
  Dim Worksheet As ISExcelWorksheet

  ' Create Worksheet
  Success = CreateWorksheet("7.3 - Number of other CCC", Worksheet) 

  ' Columns
  If Success Then
    With Worksheet.Columns
      With .Item(3).Style
        .HorizontalAlignment = iseExcelCellStyle_HorizontalAlignment.Right
      End With
    End With  
  End If
    
  ' Header Row
  If Success Then
    With Worksheet
      RowIndex = 1
      
      ' Bold
      .Rows(RowIndex).Style.Bold = True
      
      .Cell(1, RowIndex).SetString("Account Type")
      .Cell(2, RowIndex).SetString("Description")
      .Cell(3, RowIndex).SetString("Count")
    End With
  End If

  ' Add Rows
  If Success Then
    For Each AccountType In finBL.AccountTypes
      Select Case AccountType.AccountClass
        Case isefinAccountClass.LoanFR, isefinAccountClass.LoanFT, isefinAccountClass.LoanRC
          If AccountType.CreditType = isefinAccountCreditType.Consumer AndAlso AccountType.ConsumerRegulationType &lt;&gt; isefinAccountConsumerRegulationType.NZ_HighCostConsumerCreditContract Then
            RowIndex += 1
            
            Count = 0
            For Each AccountRecord In mAccountRecords
              If AccountRecord.AccountTypeId = AccountType.AccountTypeId Then
                If AccountRecord.DateOpened &gt;= mPeriodStart Then Count += 1 
              End If  
            Next  
            
            With Worksheet
              .Cell(1, RowIndex).SetString(AccountType.AccountTypeId)
              .Cell(2, RowIndex).SetString(AccountType.Description)
              .Cell(3, RowIndex).SetInteger(Count)
            End With  
          End If  
      End Select
    Next  
  End If
  
  ' Add Total Row 
  If Success AndAlso RowIndex &gt; 2 Then
    With Worksheet
      RowIndex += 1
  
      ' Bold
      .Rows(RowIndex).Style.Bold = True
  
      .Cell(1, RowIndex).SetString("Total")
      ' Add SUMs starting at row 2 because row 1 is the Header row
      .Cell(3, RowIndex).Formula = String.Format("=SUM(C2:C{0})", RowIndex - 1)
      
      ' Bold
      .Rows(RowIndex).Style.Bold = True
    End With  
  End If

  If Success Then
    ' Resize columns to fit
    Worksheet.Columns.Autofit()
    
    ' Freeze headings row
    Worksheet.FreezePanes(1, 0)
    
    ' Add Notes
    With Worksheet
      .Cell(1, RowIndex + 2).SetString(String.Format("Entity: {0} - {1}.", mEntity.EntityId, mEntity.Name))
      .Cell(1, RowIndex + 3).SetString(String.Format("Reporting period: {0} to {1}.", finBL.FormatDateLong(mPeriodStart), finBL.FormatDateLong(mPeriodEnd)))
    End With  
  End If

End Sub

Private Sub CreateWorksheet7x4()

  Dim AccountRecord As AccountRecord
  Dim AccountType As finAccountTypeRO
  Dim CountAdditionalLoanAdvances As Integer
  Dim CountCreditLimitIncreases As Integer
  Dim CountLoanTransferIns As Integer
  Dim RowIndex As Integer
  Dim Success As Boolean
  Dim Worksheet As ISExcelWorksheet

  ' Create Worksheet
  Success = CreateWorksheet("7.4 - Material Changes", Worksheet) 

  ' Columns
  If Success Then
    With Worksheet.Columns
      With .Item(3).Style
        .HorizontalAlignment = iseExcelCellStyle_HorizontalAlignment.Right
      End With
      With .Item(4).Style
        .HorizontalAlignment = iseExcelCellStyle_HorizontalAlignment.Right
      End With
      With .Item(5).Style
        .HorizontalAlignment = iseExcelCellStyle_HorizontalAlignment.Right
      End With
      With .Item(6).Style
        .HorizontalAlignment = iseExcelCellStyle_HorizontalAlignment.Right
      End With
    End With  
  End If
    
  ' Header Row
  If Success Then
    With Worksheet
      RowIndex = 1
      
      ' Bold
      .Rows(RowIndex).Style.Bold = True

      .Cell(1, RowIndex).SetString("Account Type")
      .Cell(2, RowIndex).SetString("Description")
      .Cell(3, RowIndex).SetString("Credit Limit Changes")
      .Cell(4, RowIndex).SetString("Number of additional Advances")
      .Cell(5, RowIndex).SetString("Number of Transfer Ins")
      .Cell(6, RowIndex).SetString("Total")
    End With
  End If

  ' Add Rows
  If Success Then
    For Each AccountType In finBL.AccountTypes
      Select Case AccountType.AccountClass
        Case isefinAccountClass.LoanFR, isefinAccountClass.LoanFT, isefinAccountClass.LoanRC
          If AccountType.CreditType = isefinAccountCreditType.Consumer Then
            RowIndex += 1

            CountAdditionalLoanAdvances = 0
            CountCreditLimitIncreases = 0
            CountLoanTransferIns = 0
            For Each AccountRecord In mAccountRecords
              If AccountRecord.AccountTypeId = AccountType.AccountTypeId Then
                CountAdditionalLoanAdvances += AccountRecord.LoanAdvanceAdditionalCount
                CountCreditLimitIncreases += AccountRecord.CreditLimitIncreaseCount
                CountLoanTransferIns += AccountRecord.LoanTransferInCount
              End If  
            Next  
            
            With Worksheet
              .Cell(1, RowIndex).SetString(AccountType.AccountTypeId)
              .Cell(2, RowIndex).SetString(AccountType.Description)
              Select Case AccountType.AccountClass
                Case isefinAccountClass.LoanFR, isefinAccountClass.LoanFT
                  .Cell(4, RowIndex).SetInteger(CountAdditionalLoanAdvances)
                  .Cell(5, RowIndex).SetInteger(CountLoanTransferIns)
                Case isefinAccountClass.LoanRC
                  .Cell(3, RowIndex).SetInteger(CountCreditLimitIncreases)
              End Select  
              .Cell(6, RowIndex).Formula = String.Format("=SUM(C{0}:E{0})", RowIndex)
            End With  
          End If  
      End Select
    Next  
  End If
  
  ' Add Total Row 
  If Success AndAlso RowIndex &gt; 2 Then
    With Worksheet
      RowIndex += 1
  
      ' Bold
      .Rows(RowIndex).Style.Bold = True
  
      .Cell(1, RowIndex).SetString("Total")
      ' Add SUMs starting at row 2 because row 1 is the Header row
      .Cell(3, RowIndex).Formula = String.Format("=SUM(C2:C{0})", RowIndex - 1)
      .Cell(4, RowIndex).Formula = String.Format("=SUM(D2:D{0})", RowIndex - 1)
      .Cell(5, RowIndex).Formula = String.Format("=SUM(E2:E{0})", RowIndex - 1)
      .Cell(6, RowIndex).Formula = String.Format("=SUM(F2:F{0})", RowIndex - 1)
      
      ' Bold
      .Rows(RowIndex).Style.Bold = True
    End With  
  End If

  If Success Then
    ' Resize columns to fit
    Worksheet.Columns.Autofit()
    
    ' Freeze headings row
    Worksheet.FreezePanes(1, 0)
    
    ' Add Notes
    With Worksheet
      .Cell(1, RowIndex + 2).SetString(String.Format("Entity: {0} - {1}.", mEntity.EntityId, mEntity.Name))
      .Cell(1, RowIndex + 3).SetString(String.Format("Reporting period: {0} to {1}.", finBL.FormatDateLong(mPeriodStart), finBL.FormatDateLong(mPeriodEnd)))
    End With  
  End If

End Sub

Private Sub CreateWorksheet7x5()

  Dim AccountRecord As AccountRecord
  Dim AccountType As finAccountTypeRO
  Dim RowIndex As Integer
  Dim Success As Boolean
  Dim TotalLoanAdditionalAdvanceValue As Decimal
  Dim TotalLoanAdvance As Decimal
  Dim TotalLoanTransferInValue As Decimal
  Dim TotalCreditLimit As Decimal
  Dim Worksheet As ISExcelWorksheet

  ' Create Worksheet
  Success = CreateWorksheet("7.5 - Advances &amp; Credit Limits", Worksheet) 

  ' Columns
  If Success Then
    With Worksheet.Columns
      With .Item(3).Style
        .HorizontalAlignment = iseExcelCellStyle_HorizontalAlignment.Right
        .NumberFormat = finBL.CurrencyFormat()
      End With
      With .Item(4).Style
        .HorizontalAlignment = iseExcelCellStyle_HorizontalAlignment.Right
        .NumberFormat = finBL.CurrencyFormat()
      End With
      With .Item(5).Style
        .HorizontalAlignment = iseExcelCellStyle_HorizontalAlignment.Right
        .NumberFormat = finBL.CurrencyFormat()
      End With
    End With  
  End If
    
  ' Header Row
  If Success Then
    With Worksheet
      RowIndex = 1
      
      ' Bold
      .Rows(RowIndex).Style.Bold = True

      .Cell(1, RowIndex).SetString("Account Type")
      .Cell(2, RowIndex).SetString("Description")
      .Cell(3, RowIndex).SetString("Total Loan Advances")
      .Cell(4, RowIndex).SetString("Total Loan Advances (including Transfers In)")
      .Cell(5, RowIndex).SetString("Total Credit Limit")
    End With
  End If

  ' Add Rows
  If Success Then
    For Each AccountType In finBL.AccountTypes
      Select Case AccountType.AccountClass
        Case isefinAccountClass.LoanFR, isefinAccountClass.LoanFT, isefinAccountClass.LoanRC
          If AccountType.CreditType = isefinAccountCreditType.Consumer Then
            RowIndex += 1
            
            TotalLoanAdditionalAdvanceValue = 0
            TotalLoanAdvance = 0
            TotalLoanTransferInValue = 0
            TotalCreditLimit = 0
            For Each AccountRecord In mAccountRecords
              If AccountRecord.AccountTypeId = AccountType.AccountTypeId Then
                Select Case AccountType.AccountClass
                  Case isefinAccountClass.LoanRC
                    TotalCreditLimit += AccountRecord.CreditLimit
                    
                  Case Else
                    ' Opened in Period
                    If AccountRecord.DateOpened &gt;= mPeriodStart Then
                      TotalLoanAdvance += AccountRecord.LoanAdvance
                    End If                  
                    
                    ' Material Changes                
                    TotalLoanAdditionalAdvanceValue += AccountRecord.LoanAdvanceAdditionalValue
                    TotalLoanTransferInValue += AccountRecord.LoanTransferInValue
                End Select    
              End If  
            Next  
            
            With Worksheet
              .Cell(1, RowIndex).SetString(AccountType.AccountTypeId)
              .Cell(2, RowIndex).SetString(AccountType.Description)
              Select Case AccountType.AccountClass
                Case isefinAccountClass.LoanFR, isefinAccountClass.LoanFT
                  .Cell(3, RowIndex).SetDecimal(TotalLoanAdvance + TotalLoanAdditionalAdvanceValue)
                  .Cell(4, RowIndex).SetDecimal(TotalLoanAdvance + TotalLoanAdditionalAdvanceValue + TotalLoanTransferInValue)
                Case isefinAccountClass.LoanRC
                  .Cell(5, RowIndex).SetDecimal(TotalCreditLimit)
              End Select
            End With  
          End If  
      End Select
    Next  
  End If
  
  ' Add Total Row 
  If Success AndAlso RowIndex &gt; 2 Then
    With Worksheet
      RowIndex += 1
  
      ' Bold
      .Rows(RowIndex).Style.Bold = True
  
      .Cell(1, RowIndex).SetString("Total")
      ' Add SUMs starting at row 2 because row 1 is the Header row
      .Cell(3, RowIndex).Formula = String.Format("=SUM(C2:C{0})", RowIndex - 1)
      .Cell(4, RowIndex).Formula = String.Format("=SUM(D2:D{0})", RowIndex - 1)
      .Cell(5, RowIndex).Formula = String.Format("=SUM(E2:E{0})", RowIndex - 1)
      
      ' Bold
      .Rows(RowIndex).Style.Bold = True
    End With  
  End If

  If Success Then
    ' Resize columns to fit
    Worksheet.Columns.Autofit()
    
    ' Freeze headings row
    Worksheet.FreezePanes(1, 0)
    
    ' Add Notes
    With Worksheet
      .Cell(1, RowIndex + 2).SetString(String.Format("Entity: {0} - {1}.", mEntity.EntityId, mEntity.Name))
      .Cell(1, RowIndex + 3).SetString(String.Format("Reporting period: {0} to {1}.", finBL.FormatDateLong(mPeriodStart), finBL.FormatDateLong(mPeriodEnd)))
    End With  
  End If

End Sub

Private Sub CreateWorksheetAccounts()

  Dim AccountRecord As AccountRecord
  Dim RowIndex As Integer
  Dim Success As Boolean
  Dim Worksheet As ISExcelWorksheet

  ' Create Worksheet
  Success = CreateWorksheet("Account data", Worksheet) 
  
  ' Columns
  If Success Then
    With Worksheet.Columns
      With .Item(3).Style
        .HorizontalAlignment = iseExcelCellStyle_HorizontalAlignment.Left
      End With
      With .Item(4).Style
        .HorizontalAlignment = iseExcelCellStyle_HorizontalAlignment.Left
      End With
      With .Item(5).Style
        .HorizontalAlignment = iseExcelCellStyle_HorizontalAlignment.Right
        .NumberFormat = finBL.DateFormatLong()
      End With
      With .Item(6).Style
        .HorizontalAlignment = iseExcelCellStyle_HorizontalAlignment.Right
        .NumberFormat = finBL.DateFormatLong()
      End With
      With .Item(7).Style
        .HorizontalAlignment = iseExcelCellStyle_HorizontalAlignment.Right
        .NumberFormat = finBL.CurrencyFormat()
      End With
      With .Item(8).Style
        .HorizontalAlignment = iseExcelCellStyle_HorizontalAlignment.Left
      End With
      With .Item(9).Style
        .HorizontalAlignment = iseExcelCellStyle_HorizontalAlignment.Right
      End With
      With .Item(10).Style
        .HorizontalAlignment = iseExcelCellStyle_HorizontalAlignment.Right
        .NumberFormat = finBL.CurrencyFormat()
      End With
      With .Item(11).Style
        .HorizontalAlignment = iseExcelCellStyle_HorizontalAlignment.Right
      End With
      With .Item(12).Style
        .HorizontalAlignment = iseExcelCellStyle_HorizontalAlignment.Right
        .NumberFormat = finBL.CurrencyFormat()
      End With
      With .Item(13).Style
        .HorizontalAlignment = iseExcelCellStyle_HorizontalAlignment.Right
        .NumberFormat = finBL.CurrencyFormat()
      End With
      With .Item(14).Style
        .HorizontalAlignment = iseExcelCellStyle_HorizontalAlignment.Right
      End With
      With .Item(15).Style
        .HorizontalAlignment = iseExcelCellStyle_HorizontalAlignment.Right
        .NumberFormat = finBL.CurrencyFormat()
      End With
    End With  
  End If
    
  ' Header Row
  If Success Then
    With Worksheet
      RowIndex = 1
      
      ' Bold
      .Rows(RowIndex).Style.Bold = True
      
      .Cell(1, RowIndex).SetString("Account")
      .Cell(2, RowIndex).SetString("Account Type")
      .Cell(3, RowIndex).SetString("Revolving Credit")
      .Cell(4, RowIndex).SetString("High Cost")
      .Cell(5, RowIndex).SetString("Date Opened")
      .Cell(6, RowIndex).SetString("Date Closed")
      .Cell(7, RowIndex).SetString("Loan Advance")
      .Cell(8, RowIndex).SetString("Additional Loan Advance Count")
      .Cell(9, RowIndex).SetString("Additional Loan Advance Value")
      .Cell(10, RowIndex).SetString("Loan Transfer In Count")
      .Cell(11, RowIndex).SetString("Loan Transfer In Value")
      .Cell(12, RowIndex).SetString("Credit Limit")
      .Cell(13, RowIndex).SetString("Credit Limit Increase Count")
      .Cell(14, RowIndex).SetString("Credit Limit Increase Value")
    End With
  End If

  ' Add Rows
  If Success Then
    For Each AccountRecord In mAccountRecords
      RowIndex += 1
      
      With Worksheet
        .Cell(1, RowIndex).SetString(AccountRecord.AccountId)
        .Cell(2, RowIndex).SetString(AccountRecord.AccountTypeId)
        If AccountRecord.IsRevolvingCreditLoan Then .Cell(3, RowIndex).SetBoolean(True)
        If AccountRecord.IsHighCostLoan Then .Cell(4, RowIndex).SetBoolean(True)
        .Cell(5, RowIndex).SetDate(AccountRecord.DateOpened)
        If AccountRecord.DateClosed = Nothing Then
          .Cell(6, RowIndex).Style.NumberFormat = ""
          .Cell(6, RowIndex).SetString("")
        Else
          .Cell(6, RowIndex).SetDate(AccountRecord.DateClosed)
        End If  
        If AccountRecord.IsRevolvingCreditLoan Then
          .Cell(12, RowIndex).SetDecimal(AccountRecord.CreditLimit)
          .Cell(13, RowIndex).SetInteger(AccountRecord.CreditLimitIncreaseCount)
          .Cell(14, RowIndex).SetDecimal(AccountRecord.CreditLimitIncreaseValue)
        Else
          .Cell(7, RowIndex).SetDecimal(AccountRecord.LoanAdvance)
          .Cell(8, RowIndex).SetInteger(accountRecord.LoanAdvanceAdditionalCount)
          .Cell(9, RowIndex).SetDecimal(AccountRecord.LoanAdvanceAdditionalValue)
          .Cell(10, RowIndex).SetInteger(accountRecord.LoanTransferInCount)
          .Cell(11, RowIndex).SetDecimal(AccountRecord.LoanTransferInValue)
        End If
      End With
    Next  
  End If

  If Success Then
    ' Resize columns to fit
    Worksheet.Columns.Autofit()
    
    ' Freeze headings row
    Worksheet.FreezePanes(1, 0)
    
    ' Add Notes
    With Worksheet
      .Cell(1, RowIndex + 2).SetString(String.Format("Entity: {0} - {1}.", mEntity.EntityId, mEntity.Name))
      .Cell(1, RowIndex + 3).SetString(String.Format("Reporting period: {0} to {1}.", finBL.FormatDateLong(mPeriodStart), finBL.FormatDateLong(mPeriodEnd)))
    End With  
  End If
  
End Sub

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

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

  ' Assume Success
  Success = True

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

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

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

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

  Return Success

End Function

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

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

  ' Assume Success
  Success = True

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

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

  Return Success

End Function

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

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

  ' Assume Success
  Success = True

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

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

  Return Success

End Function

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

  Dim Entity As finEntityRO
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim PeriodStartDate As Date
  Dim ProcessStatuses As List(Of finHtmlWidgetUtilities.JsonProcessStatusInformation)
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Validate

  If Success Then
    ' Form Initialisation Info
    If Success Then
      FormInitialisationInfo = New FormInitialisationInfo()
      With FormInitialisationInfo
        ' General
        If finBL.Branches.Exists(finBL.SettingsUser.DefaultClientBranchIdResolved) Then
          .EntityId = finBL.Branches(finBL.SettingsUser.DefaultClientBranchIdResolved).EntityId
        Else
          .EntityId = ""
        End If
        
        ' Global Collections
        For Each Entity In finBL.Entities 
          .Entities.Add(New EntityInfo(Entity))
        Next

        ' Default date range - most recent complete reporting year (APRIL-MARCH)
        PeriodStartDate = New DateTime(DateTime.Now.Year, 4, 1)
        If PeriodStartDate &gt; DateTime.Now Then
          PeriodStartDate = PeriodStartDate.AddYears(-2)
        Else
          PeriodStartDate = PeriodStartDate.AddYears(-1)
        End If  
        .PeriodStart = finBLShared.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(PeriodStartDate)
        .PeriodEnd = finBLShared.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(PeriodStartDate.AddYears(1).AddDays(-1))
        
        ' Configuration
        .DesktopMode = mDesktopMode
        .PromptOnCommit = finBL.CloudConnectFunctions.CloudConnectSettings.PromptOnCommit
        .ReadOnly = finBL.Database.IsReadOnly
      End With

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

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

  Return Success

End Function

Private Function ProcessAccount(accountPk As Integer) As Boolean
  
  Dim Account As finAccount
  Dim AccountHistoryItem As finAccountHistoryItem
  Dim AccountRecord As AccountRecord
  Dim AccountTransaction As finAccountTransaction
  Dim CreditLimit As Decimal
  Dim CreditLimitIncreaseCount As Integer
  Dim CreditLimitIncreaseValue As Decimal
  Dim CreditLimitMaximum As Decimal
  Dim LoanAdvanceValue As Decimal
  Dim LoanAdvanceAdditionalCount As Integer
  Dim LoanAdvanceAdditionalValue As Decimal
  Dim LoanTransferInCount As Integer
  Dim LoanTransferInValue As Decimal
  Dim Success As Boolean
   
  ' Assume Success
  Success = True
  
  ' Create Objects
  Account = finBL.CreateAccount()
  
  ' Load Account
  If Account.LoadPk(accountPk) Then
    ' Create AccountRecord with key details 
    AccountRecord = New AccountRecord()
    With AccountRecord
      .AccountId = Account.AccountId
      .AccountTypeId = Account.AccountTypeId
      .DateOpened = Account.DateOpened
      .DateClosed = Account.DateClosed
      
      If Account.AccountClass = isefinAccountClass.LoanRC Then
        ' REVOLVING CREDIT LOAN
        .IsRevolvingCreditLoan = True
        .IsHighCostLoan = False ' A HCCCC cannot be a Revolving Credit Loan
        
        ' Calculate Credit Limit, including Increases during the Period
        CreditLimit = 0
        CreditLimitIncreaseCount = 0
        CreditLimitIncreaseValue = 0
        CreditLimitMaximum = 0
        For Each AccountHistoryItem In Account.HistoryItems
          If AccountHistoryItem.Date &gt; mPeriodEnd Then
            ' Quit
            Exit For
          ElseIf AccountHistoryItem.HistoryType = isefinAccountHistoryType.CreditLimitChange AndAlso AccountHistoryItem.Status = isefinAccountHistoryStatus.Complete Then
            If UCase(AccountHistoryItem.Reference) = "OPENING" Then
              ' Ignore Opening Credit Limit
            ElseIf AccountHistoryItem.Date &lt; mPeriodStart Then
              ' Too early
            Else  
              ' Has the Credit Limit been increased?
              If AccountHistoryItem.CreditLimit1 &gt; CreditLimit Then 
                CreditLimitIncreaseCount += 1
                CreditLimitIncreaseValue += (AccountHistoryItem.CreditLimit1 - CreditLimit)
              End If  
            End If  
            
            CreditLimit = AccountHistoryItem.CreditLimit1
            If CreditLimit &gt; CreditLimitMaximum Then CreditLimitMaximum = CreditLimit
          End If
        Next
        .CreditLimit = CreditLimitMaximum
        .CreditLimitIncreaseCount = CreditLimitIncreaseCount
        .CreditLimitIncreaseValue = CreditLimitIncreaseValue
      Else
        ' FIXED TERM LOAN
        .IsRevolvingCreditLoan = False
        .IsHighCostLoan = (Account.AccountType.ConsumerRegulationType = isefinAccountConsumerRegulationType.NZ_HighCostConsumerCreditContract)
        
        ' Calculate Advances
        LoanAdvanceValue = 0
        LoanAdvanceAdditionalCount = 0
        LoanAdvanceAdditionalValue = 0
        LoanTransferInCount = 0
        LoanTransferInValue = 0
        For Each AccountTransaction In Account.Transactions
          If AccountTransaction.Date &gt; mPeriodEnd Then
            ' Quit
            Exit For
          ElseIf AccountTransaction.Date &lt; mPeriodStart Then
            ' Too early
          ElseIf AccountTransaction.ReversePk &lt;&gt; 0 Then
            ' Reversed
          Else
            Select Case AccountTransaction.Source 
              Case isefinTransactionSource.Disbursement
                ' Disbursement - Ignore
              Case Else
                Select Case AccountTransaction.ElementType
                  Case isefinElementType.Advance, isefinElementType.Deposit, isefinElementType.Refinance, isefinElementType.Withdrawal
                    If account.DateOpened = AccountTransaction.Date Then
                      ' Opening
                      LoanAdvanceValue += AccountTransaction.Value
                    Else
                      ' Additional - must be a Debit
                      If AccountTransaction.Value &gt; 0 Then  
                        LoanAdvanceAdditionalCount += 1 
                        LoanAdvanceAdditionalValue += AccountTransaction.Value
                      End If  
                    End If  
                  
                  Case isefinElementType.Transfer
                    ' Must be a Debit
                    If AccountTransaction.Value &gt; 0 Then  
                      LoanTransferInCount += 1 
                      LoanTransferInValue += AccountTransaction.Value
                    End If
                End Select  
              End Select    
          End If
        Next
        .LoanAdvance = LoanAdvanceValue
        .LoanAdvanceAdditionalCount = LoanAdvanceAdditionalCount
        .LoanAdvanceAdditionalValue = LoanAdvanceAdditionalValue
        .LoanTransferInCount = LoanTransferInCount
        .LoanTransferInValue = LoanTransferInValue
      End If  
      
      ' Related High Cost
      ' NOT IMPLEMENTED
    End With
    
    ' Add to collection
    mAccountRecords.Add(AccountRecord)
  Else
    Success = False
  End If
  
  Return Success
  
End Function

Private Function ProcessAccounts(ByRef cancelled As Boolean) As Boolean

  Dim dr As IDataReader
  Dim Row As Integer
  Dim RowCount As Integer
  Dim sqb As ISSelectQueryBuilder
  Dim Success As Boolean
  
  ' Assume Success
  Success = True
  
  ' Initialise
  mAccountRecords.Clear()
  
  ' Query database for Accounts open in the period
  sqb = finBL.Database.CreateSelectQueryBuilder()
  With sqb
    .Table = "Account"
    .Fields.Add("Account.Pk")
    With .SqlWhere
      ' Loans only
      .BlockBegin(iseSqlWhereBuilderNestedBlockType.OrBlock)
      .AppendComparisonInteger("Account.AccountClass", "=", isefinAccountClass.LoanFR)
      .AppendComparisonInteger("Account.AccountClass", "=", isefinAccountClass.LoanFT)
      .AppendComparisonInteger("Account.AccountClass", "=", isefinAccountClass.LoanRC)
      .BlockEnd()
      
      ' Consumer Types only
      .AppendRange("Account.AccountTypePk", finBL.AccountTypes.GetAccountTypePksListCreditTypeConsumer(False).ToCsvString(), iseRangeDataType.Integer)
            
      ' Status
      .BlockBegin(iseSqlWhereBuilderNestedBlockType.OrBlock)
      .AppendComparisonInteger("Account.Status", "=", isefinAccountStatus.Open)
      .AppendComparisonInteger("Account.Status", "=", isefinAccountStatus.Closed)
      .AppendComparisonInteger("Account.Status", "=", isefinAccountStatus.ClosedPending)
      .BlockEnd()

      ' Must be open between Report Start and End dates
      .AppendComparisonDate("Account.DateOpened", "&lt;=", mPeriodEnd)
      .BlockBegin(iseSqlWhereBuilderNestedBlockType.OrBlock)
      .AppendComparisonNull("Account.DateClosed")
      .AppendComparisonDate("Account.DateClosed", "&gt;=", mPeriodStart)
      .BlockEnd()

      ' Limit to Entity
      If finBL.Branches.GetBranchPksListFromEntityPk(mEntity.Pk).Count = 0 Then
        ' Force empty result set
        .AppendComparisonInteger("Account.BranchPk", "=", -1)
      Else
        .AppendRange("Account.BranchPk", finBL.Branches.GetBranchPksListFromEntityPk(mEntity.Pk).ToCsvString(), iseRangeDataType.Integer)
      End If  
    End With
    .OrderByFields.Add("Account.AccountId")
  End With

  If sqb.ExecuteDisconnectedDataReader(dr, RowCount, finBL.Settings.DatabaseTimeoutSecondsLong) Then
    Do While dr.Read()
      ' Update Row
      Row += 1
      
      ' Notify Percentage Complete
      mProcessStatus.NotifyProgress(Row / RowCount * 100, "Processing Accounts")
      
      ' Cancelled by User?
      If mProcessStatus.IsCancelRequested() Then
        cancelled = True
        mProcessStatus.NotifyCancelled()
        Exit Do
      End If

      ' Create an Account Record
      If Not ProcessAccount(finBL.Database.GetFieldInteger(dr!Pk)) Then
        Success = False
        Exit Do
      End If
    Loop
    
    finBL.Database.DataReaderClose(dr)
  Else
    Success = False
  End If  
  
  ' Sort
  'mAccountRecords.Sort(New AccountRecordComparer())
  
  Return Success
  
End Function  

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

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

  ' Assume Success
  Success = True

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

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

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

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

  Return Success

End Function


''' &lt;summary&gt;
'''  Account Record.
''' &lt;/summary&gt;
Public Class AccountRecord

  Public AccountId As String
  Public AccountTypeId As String
  Public LoanAdvanceAdditionalCount As Integer
  Public LoanAdvanceAdditionalValue As Decimal
  Public LoanTransferInCount As Integer
  Public LoanTransferInValue As Decimal
  Public CreditLimit As Decimal
  Public CreditLimitIncreaseCount As Integer
  Public CreditLimitIncreaseValue As Decimal
  Public DateClosed As Date
  Public DateOpened As Date
  Public LoanAdvance As Decimal
  Public IsHighCostLoan As Boolean
  Public IsRevolvingCreditLoan As Boolean

End Class

''' &lt;summary&gt;
'''  Account Record Comparer.
''' &lt;/summary&gt;
Public Class AccountRecordComparer: Implements IComparer (Of AccountRecord)

  Public Function Compare(a As AccountRecord, b As AccountRecord) As Integer Implements IComparer(Of AccountRecord).Compare

    Dim Result As Integer

    ' Sort by AccountTypeId
    Result = a.AccountTypeId.CompareTo(b.AccountTypeId)

    ' Then by DateOpened
    If Result = 0 Then
      Result = a.DateOpened.Compareto(b.DateOpened)  
    End If

    Return Result

  End Function  

End Class


''' &lt;summary&gt;
'''  Entity Information.
''' &lt;/summary&gt;
Public Class EntityInfo

  Public EntityId As String

  Public Sub New(entity As finEntityRO)
    
    With entity
      Me.EntityId = .EntityId 
    End With
    
  End Sub

End Class


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

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

  ' Details
  Public EntityId As String

  ' Global Collections
  Public Entities As New List(Of EntityInfo)

  ' Default date range
  Public PeriodStart As Date
  Public PeriodEnd As Date
  
  ' Configuration
  Public DesktopMode As Boolean
  Public PromptOnCommit As Boolean
  Public [ReadOnly] As Boolean

End Class


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

  Public EntityId As String
  Public PeriodStart As Date
  Public PeriodEnd As Date
  
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>This report is intended to assist users to complete Annual Reporting requirements mandated by New Zealand Legislation.

https://www.legislation.govt.nz/regulation/public/2004/0240/latest/LMS627791.html
https://comcom.govt.nz/__data/assets/pdf_file/0020/311528/Annual-returns-guidance-June-2023.pdf</Notes>
    <PermissionKeyExecute />
    <ReferenceLinq>false</ReferenceLinq>
    <RunWithoutPrompts>false</RunWithoutPrompts>
    <TemplateText>&lt;div id="frmMain" class="is-widget-content" style="visibility:hidden"&gt;

  &lt;!-- Form Header --&gt;
  &lt;header&gt;
    &lt;div class="header"&gt;&lt;/div&gt;
    &lt;div class="summary"&gt;&lt;/div&gt;
    &lt;!-- Tabs --&gt;
    &lt;div id="tabWizard" class="is-tabs"&gt;
      &lt;ul&gt;
        &lt;li tabId="CurrentProcesses" tooltipText="Drilldown to view the status of current and recent Reports that you have run."&gt;Recent Annual Commerce Commission Reports&lt;/li&gt;
        &lt;li tabId="General" tooltipText="Enter report options."&gt;Report Options&lt;/li&gt;
        &lt;li tabId="Progress" tooltipText="Processing progress."&gt;Progress&lt;/li&gt;
      &lt;ul&gt;
    &lt;/div&gt;
  &lt;/header&gt;

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


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

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="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 Date range&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="datePeriodStart"&gt;From:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="datePeriodStart" /&gt; to &lt;input id="datePeriodEnd" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;td colspan="2" style="padding-top:12px"&gt;
            &lt;div class="is-info-text info"&gt;
              &lt;h2&gt;Annual Commerce Commission Report&lt;/h2&gt;
              &lt;p&gt;This report can be used to assist completing the Annual Report as required by the Commerce Commission.&lt;/p&gt;
              &lt;p&gt;Details can be found on the &lt;a href="https://comcom.govt.nz/business/business-consultations/annual-returns-guidance" target="_blank"&gt;Commerce Commission New Zealand website under Annual returns guidance&lt;/a&gt;.&lt;/p&gt;
              &lt;p&gt;&lt;b&gt;WARNING: You should carefully review the Report for accuracy and not rely on the information without doing your assessment.&lt;/b&gt;&lt;/p&gt;
              &lt;/br&gt;
              &lt;p&gt;&lt;b&gt;DISCLAIMER: It is your responsibility to make sure this Report is fit for purpose and you should seek independent professional advice from sources such as Lawyers, Accountants and Government Agencies before completing your Report.&lt;/b&gt;&lt;/p&gt;
            &lt;/div&gt;
          &lt;/td&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;


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

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

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

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

// Global Collections
var mEntities;

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

  //   General
  lblEntity: null,
  cboEntity: null,
  
  lblDateRange: null,
  datePeriodStart: null,
  datePeriodEnd: null,

  //   Progress
  divProgress: null,
}

// Form
var frmMain;
var tabWizard;

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

var cmdHistory;

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


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

  // Controls
  //   General
  C.lblEntity = widget.UI.Label("lblEntity", {});
  C.cboEntity = widget.UI.DBCombo("cboEntity", {
    allowBlank: false,
    limitToList: true,
    width: widget.UI.FIELD_WIDTH_CODE_10,
    
    onChange: cboEntity_Change
  });

  C.lblDateRange = widget.UI.Label("lblDateRange", {});
  C.datePeriodStart = widget.UI.DateBox("datePeriodStart", {
    allowBlank: false,
  });
  C.datePeriodEnd = widget.UI.DateBox("datePeriodEnd", {
    allowBlank: false,
  });

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

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

    onInitialiseRow: gridCurrentProcesses_InitialiseRow,
    onRowDrilldown: gridCurrentProcesses_RowDrilldown,
  });

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

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

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

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

  // Reset Form
  Form_Reset();
});

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

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

  // Resize
  Form_Resize();

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

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

  // Hide content
  frmMain.Visible(false);

  // Block UI
  widget.UI.Block("Initialising, please wait...");

  // Load Initialisation details
  widget.GetString("GetInitialisationInfo", {},
    // Success
    function (data) {
      mRecord = JSON.parse(data);
      mRecord_CurrentProcesses = mRecord.CurrentProcesses;

      // Global Collections
      mEntities = mRecord.Entities;

      // Give Collections ability to lookup by code
      widget.ArrayAllowLookupById(mEntities, "EntityId");

      // Load Fields
      Fields_Load();

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

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

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

    // General
    C.cboEntity.Text(mRecord.EntityId);    
    
    // Date Range - most recent complete reporting year
    C.datePeriodStart.Value(mRecord.PeriodStart);
    C.datePeriodEnd.Value(mRecord.PeriodEnd);

  }

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

  // Update Controls
  if (mRecord) {
  }

  // Update fields
  Fields_Update();

  // Refresh Tab
  tabWizard_Refresh();
}

// ========================
// Create Finish Parameters
// ========================
function CreateFinishParameters() {
  var params = {
    entityId: C.cboEntity.Text(),
    periodStart: C.datePeriodStart.Value(),
    periodEnd: C.datePeriodEnd.Value(),
  }

  return params;
}

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

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

  // Controls
  if (mRecord) {
    cboEntity_Change();
  }

  // Update Buttons
  tabWizard_UpdateButtons();

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

  // Resize Tab
  tabWizard_Resize();
}

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

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

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

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

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

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

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

  // Clear Progress Page
  pageProgress_Refresh(true);

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

  // Get Parameters
  var params = CreateFinishParameters();

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

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

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

      // Update Wizard Buttons
      tabWizard_UpdateButtons();

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

      // Refresh Progress
      pageProgress_Refresh();

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

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

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

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

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

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

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

      // Update Status
      mRecord_BackgroundProcessStatus = data;

      // Refresh Progress
      pageProgress_Refresh();

      // Status
      var Status = mRecord_BackgroundProcessStatus.Status;

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

          // Update Wizard Buttons
          tabWizard_UpdateButtons();

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

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

          // Update Wizard Buttons
          tabWizard_UpdateButtons();

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

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

          // Update Wizard Buttons
          tabWizard_UpdateButtons();

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

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

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

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

      // Abort Execution
      mRecord_BackgroundProcessStatus = null;

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

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

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

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

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

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

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

      // Update Wizard Buttons
      tabWizard_UpdateButtons();

      // Refresh Grid
      gridCurrentProcesses_Refresh();
    },

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

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

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

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

  // Stop button valid?
  tabWizard_UpdateButtons()

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

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

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

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

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

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

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

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

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

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

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

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

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

  // Start monitoring
  Form_ExecuteAction_GetBackgroundProcessStatus();
}

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

  // Tab
  tabWizard_Resize();
}

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

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

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

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

function tabWizard_MovePost(direction) {
  var Ok = true;

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

    do {
      newTab += direction;

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

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

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

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

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

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

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

    default:
      break;
  }

  // Tweak fields

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

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

  // Resize Wizard
  tabWizard_Resize();

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

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

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

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

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

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

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

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

  // Recent Page exceptions
  if (mFromRecent) {
    cmdHistory.prop("disabled", false);

    cmdBack.prop("disabled", true);
    cmdNext.prop("disabled", true);
    cmdFinish.prop("disabled", true);
  }

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

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

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

  // Other client-side validation
  if (Ok) {
    switch (tabWizard.SelectedTabId()) {
      case "General":
        // Check date range sanity
        var periodStart = C.datePeriodStart.Value();
        var periodEnd = C.datePeriodEnd.Value();
        if (widget.CompareDates(periodStart, periodEnd) != -1) {
          Ok = false;
          window.alert("Please check start and end date are valid dates and that start date is before end date.");
        }
        break;

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

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

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

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

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

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

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

  // Parse Data
  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()) {
    }

    // Callback
    validCallback();
  }
}

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

  // Enable form
  frmMain.FormEnable();
}

// =========
// cboEntity
// =========
function cboEntity_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  // Get Entity
  var entity = mEntities.GetItem(C.cboEntity.Text());
  if (entity) {
  }
}
&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>0</TimeoutSeconds>
    <UniqueId>c5ighL0wDkKVDpaGPN+hDw</UniqueId>
    <AllowRefresh>false</AllowRefresh>
    <Caption />
    <HtmlWidgetAllowInitialEventCaching>false</HtmlWidgetAllowInitialEventCaching>
    <HtmlWidgetMaxHeight>640</HtmlWidgetMaxHeight>
    <HtmlWidgetMaxWidth>800</HtmlWidgetMaxWidth>
    <HtmlWidgetNeverApplyStyling>false</HtmlWidgetNeverApplyStyling>
    <HtmlWidgetResourceChartsApex>false</HtmlWidgetResourceChartsApex>
    <HtmlWidgetResourceCssSummaryPage2>false</HtmlWidgetResourceCssSummaryPage2>
    <HtmlWidgetResourceCssWidget>true</HtmlWidgetResourceCssWidget>
    <HtmlWidgetResourceJQuery>true</HtmlWidgetResourceJQuery>
    <HtmlWidgetResourceJQueryVersion />
    <HtmlWidgetSpecialEventGetFolderCount>false</HtmlWidgetSpecialEventGetFolderCount>
    <HtmlWidgetSpecialEventShowAsSummaryPage>false</HtmlWidgetSpecialEventShowAsSummaryPage>
    <HtmlWidgetSummaryPageObjectType>None</HtmlWidgetSummaryPageObjectType>
    <Icon />
    <RestrictedOriginsListEnabled>false</RestrictedOriginsListEnabled>
    <RunAsAdministrator>false</RunAsAdministrator>
    <WebServiceName />
    <WebServiceAllowAnonymous>false</WebServiceAllowAnonymous>
    <WebServiceSendDebugInformation>false</WebServiceSendDebugInformation>
    <ShowInMenu>None</ShowInMenu>
    <ParametersType>Custom</ParametersType>
    <Parameters>
      <ISParameterDefs version="1.00">
        <Parameters>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>TESTING</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="DesktopMode" type="Boolean">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>False</Value>
            <Visible>true</Visible>
          </Parameter>
        </Parameters>
      </ISParameterDefs>
    </Parameters>
  </finScript>