<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2023-10-03T22:01:46.0000000">
    <CreatedUserId>Admin</CreatedUserId>
    <CreatedUtcDate>2023-01-18T22:04:58.0500000</CreatedUtcDate>
    <UpdatedUserId>Admin</UpdatedUserId>
    <UpdatedUtcDate>2023-10-03T20:56:00.0130000</UpdatedUtcDate>
    <ScriptId>AMLReportWidget</ScriptId>
    <Description>Annual AML/CFT Report (New Zealand)</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_AMLCFT_Report_NZ
Option Explicit On
Option Strict On

' #################################################################
' Annual AML/CFT Report (New Zealand)
'
' Version: 1.04 (04/10/2023)
'
' https://www.legislation.govt.nz/regulation/public/2017/0302/latest/DLM7502117.html#DLM7502117
' https://www.dia.govt.nz/AML-CFT-Annual-Report
'
' NOTE: Uses Web Services Background Processes but can also work from desktop without Web Services
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.00  31/05/2023  ISS      J030045   Created
'          22/05/2023  ISS      J031054   Element flag to control inclusion in report
'    1.01  29/06/2023  ISS      J031430   Code improvements
'    1.02  20/09/2023  ISS      J032074   Set script timeout to zero
'    1.03  03/10/2023  ISS      J032085   Typo correction
'    1.04  04/10/2023  ISS      J032174   Freeze headings rows of report worksheets
' #################################################################

' Constants

' Common Parameters

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

' Properties
Private mBranchPks As ISList
Private mEntityName As String
Private mIncludeGuarantors As Boolean
Private mPeriodStart As Date
Private mPeriodEnd As Date

' Other
Private mAccounts As List(Of AccountRecord)
Private mChannels As List(Of ChannelRecord)
Private mClients As List(Of ClientRecord)
Private mClientTypes As List(Of ClientTypeRecord)
Private mClientTypeIdsUsed As List(Of String)
Private mDesktopMode As Boolean
Private mProcessStatus As finHtmlWidgetBackgroundProcessStatus
Private mTransactionRecords As List(Of TransactionRecord)

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 Entity As finEntityRO
  Dim EntityId As String
  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
  EntityId = WizardFinishParameters.EntityId 
  mPeriodStart = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(WizardFinishParameters.PeriodStart)
  mPeriodEnd = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(WizardFinishParameters.PeriodEnd)
  mIncludeGuarantors = WizardFinishParameters.IncludeGuarantors
  
  ' Initialise
  mAccounts = New List(Of AccountRecord)
  mChannels = New List(Of ChannelRecord)
  mClients = New List(Of ClientRecord)
  mClientTypeIdsUsed = New List(Of String)
  mClientTypes = New List(Of ClientTypeRecord)
  mTransactionRecords = New List(Of TransactionRecord)
  
  ' Get Entity and Entity's Branches
  Entity = finBL.Entities.GetItem(EntityId)
  mEntityName = Entity.EntityId &amp; " - " &amp; Entity.Name
  mBranchPks = finBL.Branches.GetBranchPksListFromEntityPk(Entity.Pk)
  
  ' Notify
  If Success Then
    mProcessStatus.AddEvent_Information("Starting Report", String.Format("Entity '{0}', from {1} to {2}", EntityId, finBL.FormatDateLong(mPeriodStart), finBL.FormatDateLong(mPeriodEnd)))
  End If

  ' Get the Accounts that have Transactions in range
  If Success AndAlso Not Cancelled Then
    mProcessStatus.AddEvent_Information("Processing Accounts")
    Success = ProcessAccounts(Cancelled)
  End If

  ' Get the Clients that own the Accounts
  If Success AndAlso Not Cancelled Then
    mProcessStatus.AddEvent_Information("Processing Clients")
    Success = ProcessClients(Cancelled)
  End If

  ' Summarise Clients by Client Type
  If Success AndAlso Not Cancelled Then
    mProcessStatus.AddEvent_Information("Processing Client Types")
    Success = ProcessClientTypes(Cancelled)
  End If
  
  ' Summarise Clients by Channel
  If Success AndAlso Not Cancelled Then
    mProcessStatus.AddEvent_Information("Processing Channels")
    Success = ProcessChannels(Cancelled)
  End If

  ' Get the Transaction summary values
  ' NOTE: requires mAccounts set by ProcessAccounts()  
  If Success AndAlso Not Cancelled Then
    mProcessStatus.AddEvent_Information("Calculating Summaries")
    Success = ProcessTransactions(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 CountClients(clientTypeId As String,
                              resident As Boolean) As Integer

  Dim Count As Integer
  Dim ClientRecord As ClientRecord

  ' Count the number of ClientRecords that match the criteria supplied in function parameters
  For Each ClientRecord In mClients
    If ClientRecord.ClientTypeId = clientTypeId AndAlso ClientRecord.Resident = resident Then
      Count += 1
    ElseIf ClientRecord.ClientTypeId &gt; clientTypeId Then
      ' The list is sorted by ClientTypeId so we can exit the loop once we move past the requested ClientTypeId
      Exit For
    End If
  Next
  
  Return Count
  
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()

  ' 6. Products and Services (Transactions)
  Me.CreateWorksheet6x1()
  Me.CreateWorksheet6x2()
  
  ' 7. Customers (Clients)
  Me.CreateWorksheet7()
  
  ' 8. Channels (Account Sources)
  Me.CreateWorksheet8()
  
  ' Accounts (raw data)
  Me.CreateWorksheetRawAccounts()
  
  ' Clients (raw data)
  Me.CreateWorksheetRawClients()
  
  ' 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("AML_CFT_Report_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
    End If
  Else
    Success = False
  End If 
  
  Return Success
  
End Function

Private Sub CreateWorksheet6x1()
  
  Dim Success As Boolean
  Dim TransactionRecord As TransactionRecord
  Dim RowIndex As Integer
  Dim Worksheet As ISExcelWorksheet
  
  ' Create Worksheet
  Success = CreateWorksheet("6.1 - Transaction Values", Worksheet) 

  ' Columns
  If Success Then
    With Worksheet.Columns
      .Item(6).Style.HorizontalAlignment = iseExcelCellStyle_HorizontalAlignment.Right
      With .Item(7).Style
        .HorizontalAlignment = iseExcelCellStyle_HorizontalAlignment.Right
        .NumberFormat = finBL.CurrencyFormat(False)
      End With
      With .Item(8).Style
        .HorizontalAlignment = iseExcelCellStyle_HorizontalAlignment.Right
        .NumberFormat = finBL.CurrencyFormat(False)
      End With
      .Item(9).Style.HorizontalAlignment = iseExcelCellStyle_HorizontalAlignment.Right
      With .Item(10).Style
        .HorizontalAlignment = iseExcelCellStyle_HorizontalAlignment.Right
        .NumberFormat = finBL.CurrencyFormat(False)
      End With
      With .Item(11).Style
        .HorizontalAlignment = iseExcelCellStyle_HorizontalAlignment.Right
        .NumberFormat = finBL.CurrencyFormat(False)
      End With
      .Item(12).Style.HorizontalAlignment = iseExcelCellStyle_HorizontalAlignment.Right
      With .Item(13).Style
        .HorizontalAlignment = iseExcelCellStyle_HorizontalAlignment.Right
        .NumberFormat = finBL.CurrencyFormat(False)
      End With
      With .Item(14).Style
        .HorizontalAlignment = iseExcelCellStyle_HorizontalAlignment.Right
        .NumberFormat = finBL.CurrencyFormat(False)
      End With
    End With  
  End If
    
  ' Header Row
  If Success Then
    RowIndex = 1
    With Worksheet
      ' Bold
      .Rows(RowIndex).Style.Bold = True
      
      .Cell(1, RowIndex).SetString("Account Type")
      .Cell(2, RowIndex).SetString("Account Type Description")
      .Cell(3, RowIndex).SetString("Element")
      .Cell(4, RowIndex).SetString("Element Description")
      .Cell(5, RowIndex).SetString("Element Type")
      .Cell(6, RowIndex).SetString("Count")
      .Cell(7, RowIndex).SetString("Debit")
      .Cell(8, RowIndex).SetString("Credit")
      .Cell(9, RowIndex).SetString("Reversals Count")
      .Cell(10, RowIndex).SetString("Reversals Debit")
      .Cell(11, RowIndex).SetString("Reversals Credit")
      .Cell(12, RowIndex).SetString("Net Count")
      .Cell(13, RowIndex).SetString("Net Debit")
      .Cell(14, RowIndex).SetString("Net Credit")
    End With
  End If

  ' Add Rows
  If Success Then
    For Each TransactionRecord In mTransactionRecords
      Select Case TransactionRecord.ElementType
        Case isefinElementType.PaymentReceived, isefinElementType.Withdrawal, isefinElementType.Refund, isefinElementType.Investment, isefinElementType.InvestmentAdditional, isefinElementType.InterestPayout
          RowIndex += 1
          
          With Worksheet
            .Cell(1, RowIndex).SetString(TransactionRecord.AccountTypeId)
            .Cell(2, RowIndex).SetString(finBL.AccountTypes(TransactionRecord.AccountTypeId).Description)
            .Cell(3, RowIndex).SetString(TransactionRecord.ElementId)
            .Cell(4, RowIndex).SetString(finBL.Elements(TransactionRecord.ElementId).Description)
            .Cell(5, RowIndex).SetString(finBL.Elements(TransactionRecord.ElementId).ElementTypeText)
            .Cell(6, RowIndex).SetInteger(TransactionRecord.Count)
            .Cell(7, RowIndex).SetDecimal(TransactionRecord.Debit)
            .Cell(8, RowIndex).SetDecimal(TransactionRecord.Credit)
            .Cell(9, RowIndex).SetInteger(TransactionRecord.ReverseCount)
            .Cell(10, RowIndex).SetDecimal(TransactionRecord.ReverseDebit)
            .Cell(11, RowIndex).SetDecimal(TransactionRecord.ReverseCredit)
            .Cell(12, RowIndex).SetInteger(TransactionRecord.Count - TransactionRecord.ReverseCount)
            .Cell(13, RowIndex).SetDecimal(TransactionRecord.Debit - TransactionRecord.ReverseDebit)
            .Cell(14, RowIndex).SetDecimal(TransactionRecord.Credit - TransactionRecord.ReverseCredit)
          End With
      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
  
      ' Add SUMs starting at row 2 because row 1 is the Header row
      .Cell(1, RowIndex).SetString("Total")
      .Cell(6, RowIndex).Formula = String.Format("=SUM(F2:F{0})", RowIndex - 1)
      .Cell(7, RowIndex).Formula = String.Format("=SUM(G2:G{0})", RowIndex - 1)
      .Cell(8, RowIndex).Formula = String.Format("=SUM(H2:H{0})", RowIndex - 1)
      .Cell(9, RowIndex).Formula = String.Format("=SUM(I2:I{0})", RowIndex - 1)
      .Cell(10, RowIndex).Formula = String.Format("=SUM(J2:J{0})", RowIndex - 1)
      .Cell(11, RowIndex).Formula = String.Format("=SUM(K2:K{0})", RowIndex - 1)
      .Cell(12, RowIndex).Formula = String.Format("=SUM(L2:L{0})", RowIndex - 1)
      .Cell(13, RowIndex).Formula = String.Format("=SUM(M2:M{0})", RowIndex - 1)
      .Cell(14, RowIndex).Formula = String.Format("=SUM(N2:N{0})", RowIndex - 1)
    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}.", mEntityName))
      .Cell(1, RowIndex + 3).SetString(String.Format("Reporting period {0} to {1}.", finBL.FormatDateLong(mPeriodStart), finBL.FormatDateLong(mPeriodEnd)))
      .Cell(1, RowIndex + 4).SetString("Based upon Account Transaction Information.")
    End With  
  End If

End Sub

Private Sub CreateWorksheet6x2()
  
  Dim IncludeElements As List(Of String)
  Dim Success As Boolean
  Dim TransactionRecord As TransactionRecord
  Dim RowIndex As Integer
  Dim Worksheet As ISExcelWorksheet

  ' Create Worksheet
  Success = CreateWorksheet("6.2 - Revenue", Worksheet) 

  ' Get list of ElementIDs to include
  IncludeElements = GetIncludedElements()
  
  ' Columns
  If Success Then 
    With Worksheet.Columns
      With .Item(6).Style
        .HorizontalAlignment = iseExcelCellStyle_HorizontalAlignment.Right
        .NumberFormat = finBL.CurrencyFormat(False)
      End With
      With .Item(7).Style
        .HorizontalAlignment = iseExcelCellStyle_HorizontalAlignment.Right
        .NumberFormat = finBL.CurrencyFormat(False)
      End With
    End With  
  End If
    
  ' Header Row
  If Success Then 
    RowIndex = 1
    With Worksheet
      ' Bold
      .Rows(RowIndex).Style.Bold = True
      
      .Cell(1, RowIndex).SetString("Account Type")
      .Cell(2, RowIndex).SetString("Account Type Description")
      .Cell(3, RowIndex).SetString("Element")
      .Cell(4, RowIndex).SetString("Element Description")
      .Cell(5, RowIndex).SetString("Element Type")
      .Cell(6, RowIndex).SetString("Debit")
      .Cell(7, RowIndex).SetString("Credit")
    End With
  End If

  ' Add Rows
  If Success Then 
    For Each TransactionRecord In mTransactionRecords
      If IncludeElements.Contains(TransactionRecord.ElementId) Then                
        RowIndex += 1
        
        With Worksheet
          .Cell(1, RowIndex).SetString(TransactionRecord.AccountTypeId)
          .Cell(2, RowIndex).SetString(finBL.AccountTypes(TransactionRecord.AccountTypeId).Description)
          .Cell(3, RowIndex).SetString(TransactionRecord.ElementId)
          .Cell(4, RowIndex).SetString(finBL.Elements(TransactionRecord.ElementId).Description)
          .Cell(5, RowIndex).SetString(finBL.Elements(TransactionRecord.ElementId).ElementTypeText)
          .Cell(6, RowIndex).SetDecimal(TransactionRecord.Debit - TransactionRecord.ReverseDebit)
          .Cell(7, RowIndex).SetDecimal(TransactionRecord.Credit - TransactionRecord.ReverseCredit)
        End With
      End If
    Next  
  End If
  
  ' Add Total Row 
  If Success AndAlso RowIndex &gt; 2 Then
    With Worksheet
      RowIndex += 1
  
      ' Bold
      .Rows(RowIndex).Style.Bold = True
  
      ' Add SUMs starting at row 2 because row 1 is the Header row
      .Cell(1, RowIndex).SetString("Total")
      .Cell(6, RowIndex).Formula = String.Format("=SUM(F2:F{0})", RowIndex - 1)
      .Cell(7, RowIndex).Formula = String.Format("=SUM(G2:G{0})", RowIndex - 1)
    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}.", mEntityName))
      .Cell(1, RowIndex + 3).SetString(String.Format("Reporting period {0} to {1}.", finBL.FormatDateLong(mPeriodStart), finBL.FormatDateLong(mPeriodEnd)))
      .Cell(1, RowIndex + 4).SetString("Based upon Account Transaction Information.")
    End With  
  End If

End Sub

Private Function GetIncludedElements() As List(Of String)
  
  Dim Element As finElementRO
  Dim Result As List(Of String)
  
  Result = New List(Of String)
  
  For Each Element In finBL.Elements
    If Element.AmlRevenue Then
      Result.Add(Element.ElementId)
    End If
  Next 
  
  Return Result
  
End Function


Private Sub CreateWorksheet7()

  Dim ClientTypeRecord As ClientTypeRecord
  Dim RowIndex As Integer
  Dim Success As Boolean
  Dim TotalsRow As Integer
  Dim Worksheet As ISExcelWorksheet

  ' Create Worksheet
  Success = CreateWorksheet("7 - Customers", Worksheet) 

  ' Columns
  If Success Then
    With Worksheet.Columns
      With .Item(4).Style
        .HorizontalAlignment = iseExcelCellStyle_HorizontalAlignment.Right
      End With
      With .Item(5).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("Client Type")
      .Cell(2, RowIndex).SetString("Description")
      .Cell(3, RowIndex).SetString("Resident")
      .Cell(4, RowIndex).SetString("Count")
      .Cell(5, RowIndex).SetString("Percent")
    End With
  End If

  ' Figure out what row the totals will be in
  TotalsRow = mClientTypes.Count + 2

  ' Add Rows
  If Success Then
    For Each ClientTypeRecord In mClientTypes
      RowIndex += 1
      
      With Worksheet
        .Cell(1, RowIndex).SetString(clientTypeRecord.ClientTypeId)
        .Cell(2, RowIndex).SetString(clientTypeRecord.Description)
        If clientTypeRecord.Resident Then
          .Cell(3, RowIndex).SetString("Resident")
        Else
          .Cell(3, RowIndex).SetString("Non-Resident")
        End If
        .Cell(4, RowIndex).SetInteger(clientTypeRecord.Count)
        With .Cell(5, RowIndex)
          .Formula = String.Format("=D{0} / D${1}", RowIndex, TotalsRow)
          .Style.NumberFormat = "0.0%"
        End With
      End With
    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(4, RowIndex).Formula = String.Format("=SUM(D2:D{0})", RowIndex - 1)
      With .Cell(5, RowIndex)
        .Formula = String.Format("=SUM(E2:E{0})", RowIndex - 1)
        .Style.NumberFormat = "0.0%"
      End With
      
      ' 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}.", mEntityName))
      .Cell(1, RowIndex + 3).SetString(String.Format("Reporting period {0} to {1}.", finBL.FormatDateLong(mPeriodStart), finBL.FormatDateLong(mPeriodEnd)))
      .Cell(1, RowIndex + 4).SetString(String.Format("'Customers' are Account Owners{0}.", If(mIncludeGuarantors, " and Guarantors", "" )))
      .Cell(1, RowIndex + 5).SetString("Based upon Client Type information.")
End With  
  End If

End Sub

Private Sub CreateWorksheet8()

  Dim ChannelRecord As ChannelRecord
  Dim RowIndex As Integer
  Dim Success As Boolean
  Dim TotalsRow As Integer
  Dim Worksheet As ISExcelWorksheet

  ' Create Worksheet
  Success = CreateWorksheet("8 - Channels", Worksheet) 
  
  ' Columns
  If Success Then
    With Worksheet.Columns
      With .Item(2).Style
        .HorizontalAlignment = iseExcelCellStyle_HorizontalAlignment.Right
      End With
      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("Method")
      .Cell(2, RowIndex).SetString("Count")
      .Cell(3, RowIndex).SetString("Percent")
    End With
  End If
  
  ' Figure out what row the totals will be in
  TotalsRow = mChannels.Count + 2

  ' Add Rows
  If Success Then
    For Each ChannelRecord In mChannels
      RowIndex += 1
      
      With Worksheet
        .Cell(1, RowIndex).SetString(ChannelRecord.Method)
        .Cell(2, RowIndex).SetInteger(ChannelRecord.Count)
        With .Cell(3, RowIndex)
          .Formula = String.Format("=B{0} / B${1}", RowIndex, TotalsRow)
          .Style.NumberFormat = "0.0%"
        End With
      End With
    Next  
  End If
  
  ' Add Total Row 
  If Success AndAlso RowIndex &gt; 1 Then
    With Worksheet
      RowIndex += 1
  
      ' Bold
      .Rows(RowIndex).Style.Bold = True
  
      .Cell(1, RowIndex).SetString("Total")
      .Cell(2, RowIndex).Formula = String.Format("=SUM(B2:B{0})", RowIndex - 1)
      With .Cell(3, RowIndex)
        .Formula = String.Format("=SUM(C2:C{0})", RowIndex - 1)
        .Style.NumberFormat = "0.0%"
      End With
      
      ' Bold
      .Rows(RowIndex).Style.Bold = True
    End With  
  End If

  ' 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}.", mEntityName))
    .Cell(1, RowIndex + 3).SetString(String.Format("Reporting period {0} to {1}.", finBL.FormatDateLong(mPeriodStart), finBL.FormatDateLong(mPeriodEnd)))
    .Cell(1, RowIndex + 4).SetString(String.Format("Based upon information stored in Account Source from Account Owners{0}.", If(mIncludeGuarantors, " and Guarantors", "" )))
  End With  

End Sub

Private Sub CreateWorksheetRawAccounts()

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

  ' Create Worksheet
  Success = CreateWorksheet("Accounts (raw data)", Worksheet) 
  
  ' Columns
  If Success Then
    With Worksheet.Columns
      With .Item(5).Style
        .HorizontalAlignment = iseExcelCellStyle_HorizontalAlignment.Right
        .NumberFormat = finBL.DateFormatLong()
      End With
      With .Item(7).Style
        .HorizontalAlignment = iseExcelCellStyle_HorizontalAlignment.Right
        .NumberFormat = finBL.DateFormatLong()
      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("Client")
      .Cell(3, RowIndex).SetString("Client Type")
      .Cell(4, RowIndex).SetString("Resident")
      .Cell(5, RowIndex).SetString("Date Opened")
      .Cell(6, RowIndex).SetString("Source")
      .Cell(7, RowIndex).SetString("Date Closed")
    End With
  End If

  ' Add Rows
  If Success Then
    For Each AccountRecord In mAccounts
      RowIndex += 1
      
      With Worksheet
        .Cell(1, RowIndex).SetString(accountRecord.AccountId)
        .Cell(2, RowIndex).SetString(accountRecord.ClientId)
        .Cell(3, RowIndex).SetString(accountRecord.ClientTypeId)
        If accountRecord.Resident Then
          .Cell(4, RowIndex).SetString("Resident")
        Else
          .Cell(4, RowIndex).SetString("Non-Resident")
        End If    
        .Cell(5, RowIndex).SetDate(accountRecord.DateOpened)
        .Cell(6, RowIndex).SetString(accountRecord.Source)
        If accountRecord.DateClosed = Nothing Then
          .Cell(7, RowIndex).SetString("")
          .Cell(7, RowIndex).Style.NumberFormat = ""
        Else
          .Cell(7, RowIndex).SetDate(accountRecord.DateClosed)
        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}.", mEntityName))
      .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 CreateWorksheetRawClients()

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

  ' Create Worksheet
  Success = CreateWorksheet("Clients (raw data)", Worksheet) 
  
  If Success Then
    ' Columns
    With Worksheet.Columns
      With .Item(4).Style
        .HorizontalAlignment = iseExcelCellStyle_HorizontalAlignment.Right
      End With
      With .Item(5).Style
        .HorizontalAlignment = iseExcelCellStyle_HorizontalAlignment.Right
        .NumberFormat = finBL.DateFormatLong()
      End With
    End With 
  End If
    
  ' Header Row
  If Success Then
    With Worksheet
      RowIndex = 1
      
      ' Bold
      .Rows(1).Style.Bold = True
      
      .Cell(1, RowIndex).SetString("Client")
      .Cell(2, RowIndex).SetString("Client Type")
      .Cell(3, RowIndex).SetString("Resident")
      .Cell(4, RowIndex).SetString("Accounts")
      .Cell(5, RowIndex).SetString("Earliest Opened")
      .Cell(6, RowIndex).SetString("Earliest Source")
    End With
  End If

  ' Add Rows
  If Success Then
    For Each ClientRecord In mClients
      RowIndex += 1
      
      With Worksheet
        .Cell(1, RowIndex).SetString(clientRecord.ClientId)
        .Cell(2, RowIndex).SetString(clientRecord.ClientTypeId)
        If clientRecord.Resident Then
          .Cell(3, RowIndex).SetString("Resident")
        Else
          .Cell(3, RowIndex).SetString("Non-Resident")
        End If    
        .Cell(4, RowIndex).SetInteger(clientRecord.AccountCount)
        .Cell(5, RowIndex).SetDate(clientRecord.EarliestDateOpened)
        .Cell(6, RowIndex).SetString(ClientRecord.EarliestSource)
      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}.", mEntityName))
      .Cell(1, RowIndex + 3).SetString(String.Format("Reporting period {0} to {1}.", finBL.FormatDateLong(mPeriodStart), finBL.FormatDateLong(mPeriodEnd)))
      .Cell(1, RowIndex + 4).SetString(String.Format("Clients are Account Owners{0}.", If(mIncludeGuarantors, " and Guarantors", "" )))
    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 (JULY-JUNE)
        PeriodStartDate = New DateTime(DateTime.Now.Year, 7, 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 AccountClient As finAccountClient
  Dim AccountRecord As AccountRecord
  Dim Success As Boolean
   
  ' Assume Success
  Success = True
  
  ' Create Objects
  Account = finBL.CreateAccount()
  
  ' Load Account
  If Account.LoadPk(accountPk) Then
    For Each AccountClient In Account.Clients
      ' Process Owners. If IncludeGuarantors is selected, also include Guarantors.
      If AccountClient.IsOwner OrElse (AccountClient.IsGuarantor AndAlso mIncludeGuarantors) Then
        ' Create AccountRecord with key details 
        AccountRecord = New AccountRecord()
        With AccountRecord
          .AccountId = Account.AccountId
          .ClientId = AccountClient.ClientId       
          .ClientTypeId = AccountClient.ClientTypeId
          .DateClosed = Account.DateClosed
          .DateOpened = Account.DateOpened
          .Resident = finBL.TaxCategories(AccountClient.ClientTaxCategoryId).Resident
          .Source = Account.Source
          .IsMainClient = (Account.Clients(0).ClientPk = AccountClient.ClientPk)
        End With
        
        ' Add to collection
        mAccounts.Add(AccountRecord)
      End If
    Next
  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
  mClients.Clear()
  
  ' Query database for Accounts open in the period
  sqb = finBL.Database.CreateSelectQueryBuilder()
  With sqb
    .Table = "Account"
    .Fields.Add("Account.Pk")
    
    With .SqlWhere
      ' Status, ignore Declined and Unwanted
      .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 mBranchPks.Count = 0 Then
        ' Force empty result set
        .AppendComparisonInteger("Account.BranchPk", "=", -1)
      Else
        .AppendRange("Account.BranchPk", mBranchPks.ToCsvString(), iseRangeDataType.Integer)
      End If  
    End With
  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  
  
  Return Success
  
End Function  

Private Function ProcessChannels(ByRef cancelled As Boolean) As Boolean
  
  Dim ChannelRecord As ChannelRecord
  Dim ClientRecord As ClientRecord
  Dim Found As Boolean
  Dim Method As String
  Dim Row As Integer
  Dim RowCount As Integer
  Dim Success As Boolean
  
  ' Assume Success
  Success = True

  RowCount = mClients.Count
  
  For Each ClientRecord In mClients
    ' Update Row
    Row += 1

    ' Notify Percentage Complete
    mProcessStatus.NotifyProgress(Row / RowCount * 100, "Processing Channels")
    
    ' Cancelled by User?
    If mProcessStatus.IsCancelRequested() Then
      cancelled = True
      mProcessStatus.NotifyCancelled()
      Exit For
    End If

    ' Is this a new Client?
    If ClientRecord.EarliestDateOpened &gt;= mPeriodStart Then
      ' Find Method
      Method = ClientRecord.EarliestSource
      If Len(Method) = 0 Then Method = "(not stated)"
        
      ' Find Channel Record
      Found = False
      For Each ChannelRecord In mChannels
        If StrComp(ChannelRecord.Method, Method, CompareMethod.Text) = 0 Then
          Found = True
          Exit For
        End If
      Next  
      If Not Found Then
        ChannelRecord = New ChannelRecord(Method)
        mChannels.Add(ChannelRecord)
      End If

      ' Update Count
      ChannelRecord.Count += 1
    End If  
  Next  

  ' Sort
  mChannels.Sort(New ChannelRecordComparer())

  Return Success
  
End Function

Private Function ProcessClients(ByRef cancelled As Boolean) As Boolean
  
  Dim Account As AccountRecord
  Dim Client As ClientRecord
  Dim LastClientId As String
  Dim Row As Integer
  Dim RowCount As Integer
  Dim Success As Boolean
  
  ' Assume Success
  Success = True
  
  ' Initialise
  mClientTypeIdsUsed.Clear()
  
  ' Sort Accounts
  mAccounts.Sort(New AccountRecordComparer())
  
  RowCount = mAccounts.Count
  
  ' Work through the list to remove duplicates and find min/max dates
  LastClientId = ""
  For Each Account In mAccounts
    ' Update Row
    Row += 1
    
    ' Notify Percentage Complete
    mProcessStatus.NotifyProgress(Row / RowCount * 100, "Processing Clients")
    
    ' Cancelled by User?
    If mProcessStatus.IsCancelRequested() Then
      cancelled = True
      mProcessStatus.NotifyCancelled()
      Exit For
    End If

    If Account.ClientId = LastClientId Then
      ' Update Earliest Account?
      If Account.DateOpened &lt; Client.EarliestDateOpened Then
        Client.EarliestDateOpened = Account.DateOpened
        Client.EarliestSource = Account.Source
      End If  
    Else
      ' Create ClientRecord with key details
      Client = New ClientRecord(Account.ClientId, Account.ClientTypeId, Account.Resident)
      With Client
        .EarliestDateOpened = Account.DateOpened
        .EarliestSource = Account.Source
      End With
      
      ' Add to collection
      mClients.Add(Client)
      
      ' Remember ClientId so we can detect when it changes
      LastClientId = Account.ClientId
    End If
    
    ' Update Count of Accounts
    Client.AccountCount += 1

    ' Store the ClientTypeIds that are used so that even Inactive ClientTypes can be found and reported later
    If Not mClientTypeIdsUsed.Contains(Account.ClientTypeId) Then
      mClientTypeIdsUsed.Add(Account.ClientTypeId) 
    End If
  Next

  Return Success
  
End Function

Private Function ProcessClientTypes(ByRef cancelled As Boolean) As Boolean
  
  Dim ClientTypeRecord As ClientTypeRecord
  Dim ClientType As finClientTypeRO
  Dim Row As Integer
  Dim RowCount As Integer
  Dim Success As Boolean
  
  ' Assume Success
  Success = True

  RowCount = finBL.ClientTypes.Count
  
  ' Build results array
  For Each ClientType In finBL.ClientTypes
    ' Update Row
    Row += 1

    ' Notify Percentage Complete
    mProcessStatus.NotifyProgress(Row / RowCount * 100, "Processing Client Types")
    
    ' Cancelled by User?
    If mProcessStatus.IsCancelRequested() Then
      cancelled = True
      mProcessStatus.NotifyCancelled()
      Exit For
    End If
    
    ' Choose all active ClientTypes, plus any inactive ones that are referenced in the report data
    If ClientType.Active OrElse mClientTypeIdsUsed.Contains(ClientType.ClientTypeId) Then
      ' Create a ClientTypeRecord for Residents
      ClientTypeRecord = New ClientTypeRecord()
      With ClientTypeRecord
        .ClientTypeId = ClientType.ClientTypeId
        .Description = ClientType.Description
        .Resident = True
        .Count = CountClients(.ClientTypeId, .Resident)
        .Active = ClientType.Active
      End With
      mClientTypes.Add(ClientTypeRecord)
      
      ' Create a ClientTypeRecord for Non-Residents - but only add if there are some
      ClientTypeRecord = New ClientTypeRecord()
      With ClientTypeRecord
        .ClientTypeId = ClientType.ClientTypeId
        .Description = ClientType.Description
        .Resident = False
        .Count = CountClients(.ClientTypeId, .Resident)
        .Active = ClientType.Active
      End With
      If ClientTypeRecord.Count &lt;&gt; 0 Then
        mClientTypes.Add(ClientTypeRecord)
      End If
    End If
  Next  

  Return Success
  
End Function

Private Function ProcessTransactions(ByRef cancelled As Boolean) As Boolean

  Dim Account As finAccount
  Dim AccountRecord As AccountRecord
  Dim AccountTransaction As finAccountTransaction
  Dim Found As Boolean
  Dim Row As Integer
  Dim RowCount As Integer
  Dim Success As Boolean
  Dim TransactionRecord As TransactionRecord

  ' Assume Success
  Success = True

  ' Create Objects
  Account = finBL.CreateAccount()

  RowCount = mAccounts.Count

  For Each AccountRecord In mAccounts
    ' Update Row
    Row += 1
    
    ' Notify Percentage Complete
    mProcessStatus.NotifyProgress(Row / RowCount * 100, "Processing Elements")
    
    ' Cancelled by User?
    If mProcessStatus.IsCancelRequested() Then
      cancelled = True
      mProcessStatus.NotifyCancelled()
      Exit For
    End If

    If AccountRecord.IsMainClient Then
      If Account.Load(AccountRecord.AccountId) Then
        For Each AccountTransaction In Account.Transactions
          If AccountTransaction.Date &lt; mPeriodStart Then
            ' Ignore, as prior to period
          ElseIf AccountTransaction.Date &gt; mPeriodEnd Then
            ' Past end of period
            Exit For
          ElseIf AccountTransaction.Value &lt;&gt; 0 Then
            ' Find Transaction Record
            Found = False
            For Each TransactionRecord In mTransactionRecords
              If TransactionRecord.AccountTypeId = Account.AccountTypeId AndAlso TransactionRecord.ElementId = AccountTransaction.ElementId Then
                Found = True
                Exit For
              End If
            Next
            If Not Found Then
              TransactionRecord = New TransactionRecord(Account.AccountTypeId, AccountTransaction.ElementId)
              mTransactionRecords.Add(TransactionRecord)
            End If
    
            With TransactionRecord
              If AccountTransaction.Value &lt; 0 Then
                If AccountTransaction.ReversePk = 0 AndAlso AccountTransaction.NegativePaymentReversePk = 0 Then
                  .Count += 1
                  .Credit -= AccountTransaction.Value
                Else
                  .ReverseCount += 1
                  .ReverseCredit -= AccountTransaction.Value
                End If
              Else
                If AccountTransaction.ReversePk = 0 AndAlso AccountTransaction.NegativePaymentReversePk = 0 Then
                  .Count += 1
                  .Debit += AccountTransaction.Value
                Else
                  .ReverseCount += 1
                  .ReverseDebit += AccountTransaction.Value
                End If
              End If
            End With
          End If
        Next
      End If
    End If
  Next
  
  ' Sort
  mTransactionRecords.Sort(New TransactionRecordComparer())
  
  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 ClientId As String
  Public ClientTypeId As String
  Public DateClosed As Date
  Public DateOpened As Date
  Public Resident As Boolean
  Public Source As String
  Public IsMainClient 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 ClientTypeId
    Result = a.ClientTypeId.CompareTo(b.ClientTypeId)

    ' Then by ClientId
    If Result = 0 Then
      Result = a.ClientId.CompareTo(b.ClientId)
    End If

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

    Return Result

  End Function  

End Class


''' &lt;summary&gt;
'''  Channel Record.
''' &lt;/summary&gt;
Public Class ChannelRecord

  Public ReadOnly Method As String
  Public Count As Integer

  Public Sub New(method As String)
  
    Me.Method = method

  End Sub  

End Class

''' &lt;summary&gt;
'''  Channel Record Comparer.
''' &lt;/summary&gt;
Public Class ChannelRecordComparer: Implements IComparer (Of ChannelRecord)

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

    Dim Result As Integer
    
    ' Sort by Method
    Result = a.Method.CompareTo(b.Method)

    Return Result

  End Function  

End Class

''' &lt;summary&gt;
'''  Client Record.
''' &lt;/summary&gt;
Public Class ClientRecord

  Public ReadOnly ClientId As String
  Public ReadOnly ClientTypeId As String
  Public ReadOnly Resident As Boolean
  Public AccountCount As Integer
  Public EarliestDateOpened As Date
  Public EarliestSource As String

  Public Sub New(clientId As String,
                 clientTypeId As String,
                 resident As Boolean)
  
    Me.ClientId = clientId
    Me.ClientTypeId = clientTypeId
    Me.Resident = resident
    
    AccountCount = 0
    EarliestDateOpened = Nothing
    EarliestSource = ""

  End Sub  

End Class


''' &lt;summary&gt;
'''  Client Type Record.
''' &lt;/summary&gt;
Public Class ClientTypeRecord

  Public ClientTypeId As String
  Public Description As String
  Public Resident As Boolean
  Public Count As Integer
  Public Active As Boolean

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;
'''  Transaction Record.
''' &lt;/summary&gt;
Public Class TransactionRecord

  Public ReadOnly AccountTypeId As String
  Public ReadOnly ElementId As String
  Public ReadOnly ElementType As isefinElementType
  Public Count As Integer
  Public Debit As Decimal
  Public Credit As Decimal
  Public ReverseCount As Integer
  Public ReverseDebit As Decimal
  Public ReverseCredit As Decimal

  Public Sub New(accountTypeId As String, elementId As String)
  
    Me.AccountTypeId = accountTypeId
    Me.ElementId = elementId
    Me.ElementType = finBLShared.Elements(Me.ElementId).ElementType

  End Sub  

End Class

''' &lt;summary&gt;
'''  Transaction Record Comparer.
''' &lt;/summary&gt;
Public Class TransactionRecordComparer: Implements IComparer (Of TransactionRecord)

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

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

    ' Then by ElementType
    If Result = 0 Then
      Result = a.ElementType.CompareTo(b.ElementType)
    End If

    ' Then by ElementId
    If Result = 0 Then
      Result = a.ElementId.CompareTo(b.ElementId)
    End If

    Return Result

  End Function  

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
  Public IncludeGuarantors As Boolean
  
End Class


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

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

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

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

  End Sub

End Class
</Code>
    <Language>VisualBasic</Language>
    <Notes>This report is intended to assist users to complete reporting requirements mandated by New Zealand Legislation. The requirements are defined in Schedule 2 of the Anti-Money Laundering and Countering Financing Of Terrorism (Requirements And Compliance) Amendment Regulations 2017.

ref. https://www.legislation.govt.nz/regulation/public/2017/0302/latest/DLM7502117.html#DLM7502117

The report provides information that can be used to complete Sections 6.1, 6.2, 7.1-7.5, and 8.1 of the Schedule.</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 Annual AML/CFT Reports that you have run."&gt;Recent Annual AML/CFT Reports&lt;/li&gt;
        &lt;li tabId="General" tooltipText="Enter report options."&gt;Annual AML/CFT 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;th colspan="2"&gt;&lt;label id="lblIncludeGuarantors"&gt;Other Options&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkIncludeGuarantors" type="checkbox"/&gt;&lt;/th&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;p&gt;&lt;b&gt;Annual AML/CFT Report&lt;/b&gt;&lt;/p&gt;
              &lt;p&gt;This report can be used to assist completing some sections of the Annual Anti-Money Laundering and Countering Financing of Terrorism (AML/CFT) Report as required by the Department of Internal Affairs.&lt;/p&gt;
              &lt;p&gt;Details can be found on the &lt;a href="https://www.dia.govt.nz/AML-CFT-Annual-Report" target="_blank"&gt;New Zealand Department of Internal Affairs website&lt;/a&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 the Annual AML/CFT 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,

  chkIncludeGuarantors: 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,
  });

  C.chkIncludeGuarantors = widget.UI.CheckBox("chkIncludeGuarantors", {
    caption: "Include Guarantors as Customers?",
  });

  // 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(),
    includeGuarantors: C.chkIncludeGuarantors.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 AML/CFT Report (New Zealand)";
        var message = "&lt;p&gt;Are you sure you want to run this report?&lt;/p&gt;";
//        message += "&lt;ul&gt;";
//        message += "&lt;li&gt;Bank Account: &lt;b&gt;" + widget.UI.HtmlEncode(C.cboBankAccount.Text()) + "&lt;/b&gt;, &lt;b&gt;" + widget.UI.HtmlEncode(C.cboBankAccount.GetDescription()) + "&lt;/b&gt;&lt;/li&gt;";
//        message += "&lt;/ul&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>
    <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>