<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2024-01-31T20:26:52.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2023-09-13T02:36:29.0420000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2024-01-31T20:26:32.8590000</UpdatedUtcDate>
    <ScriptId>BAUR</ScriptId>
    <Description>Bank Account Usage Report</Description>
    <ScriptType>GeneralUserInterface</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' Script_BankAccountUsageReport.xml
Option Explicit On
Option Strict On
' #################################################################
' Report Accounts and Clients where the same Bank Account or Credit Card Number is used
' 
' BETA Version: 1.00 (01/02/2024)
' 
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.00  01/02/2024  ISS                Created
' #################################################################

' Properties
Private mAccountNumberRecords As SortedList(Of String, AccountNumberRecord)
Private mCancelled As Boolean
Private mExcelWorkbook As ISExcelWorkbook

Private mExcludeAccountNumbers As ISList

Private mIncludeBankAccounts As Boolean
Private mIncludeCreditCards As Boolean

Private mIncludeClients As Boolean
Private mIncludeClientsClosedBankAccounts As Boolean

Private mIncludeAccounts As Boolean
Private mIncludeAccountsBankingDetails As Boolean
Private mIncludeAccountsBankTransactions As Boolean
Private mIncludeAccountsBankTransactionsDatedFrom As Date
Private mIncludeAccountsClosed As Boolean
Private mIncludeAccountsDisbursements As Boolean
Private mIncludeAccountsStandardTransactions As Boolean

Public Function Main(userInterface As ISUserInterfaceBL, reports As ISfinReports, parameters As ISKeyValueList) As Boolean

Dim AccountNumber As String
Dim BankAccount As finBankAccountRO
Dim BankingDetails As finBankingDetails
Dim FileName As String
Dim strTemp As String

  ' Assume Success
  Main = True
  
  ' Initialise
  mCancelled = False

  ' Parameters
  With parameters
    mIncludeBankAccounts = .GetBoolean("IncludeBankAccounts")
    mIncludeCreditCards = .GetBoolean("IncludeCreditCards")
    
    mIncludeClients = .GetBoolean("IncludeClients")
    mIncludeClientsClosedBankAccounts = .GetBoolean("IncludeClientsClosedBankAccounts")
    
    mIncludeAccounts = .GetBoolean("IncludeAccounts")
    mIncludeAccountsBankingDetails = .GetBoolean("IncludeAccountsBankingDetails")
    mIncludeAccountsBankTransactions = .GetBoolean("IncludeAccountsBankTransactions")
    mIncludeAccountsBankTransactionsDatedFrom = .GetDate("IncludeAccountsBankTransactionsDatedFrom")
    mIncludeAccountsClosed = .GetBoolean("IncludeAccountsClosed")
    mIncludeAccountsDisbursements = .GetBoolean("IncludeAccountsDisbursements")
    mIncludeAccountsStandardTransactions = .GetBoolean("IncludeAccountsStandardTransactions")
  End With

  ' Validate
  If Len(finBL.CurrentUserInformation.FilterClientSqlWhere) &lt;&gt; 0 Then
    Main = False
    finBL.Error.ErrorBegin("User has Client filters.")
  ElseIf Len(finBL.CurrentUserInformation.FilterAccountSqlWhere) &lt;&gt; 0 Then
    Main = False
    finBL.Error.ErrorBegin("User has Account filters.")
  ElseIf Not(mIncludeBankAccounts OrElse mIncludeCreditCards) Then
    Main = False
    finBL.Error.ErrorBegin("Either Bank Accounts or Credit Cards must be included.")
  End If  
  
  ' BETA Warning
  If Main Then
    strTemp = "This is a BETA script. Please use with caution and check results." &amp; vbNewLine &amp; vbNewline
    strTemp &amp;= "Click OK to continue."
    Select Case userInterface.MsgBoxEx(strTemp, MessageBoxButtons.OKCancel, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2)
      Case MsgBoxResult.Ok
      Case Else
        Main = False
        finBL.Error.ErrorBegin("Cancelled by User.")
    End Select
  End If
  
  ' Excluded Bank Accounts
  If Main Then
    mExcludeAccountNumbers = finBL.Runtime.CreateList()
    
    ' Add Bank Accounts
    If mIncludeBankAccounts Then
      For Each BankAccount In finBL.BankAccounts
        BankingDetails = BankAccount.ToBankingDetails()

        If finBL.CurrentCountry.ValidateBankAccount(BankingDetails, "") Then
          If finBL.CurrentCountry.SupportsBankSortCode Then
            finBL.CurrentCountry.ValidateBankAccountSortCode(bankingdetails, "")
            AccountNumber = bankingDetails.AccountSortCode &amp; " " &amp; bankingDetails.AccountNumber
          Else
            AccountNumber = bankingDetails.AccountNumber
          End If
        Else
          ' Invalid Account Number
          If finBL.CurrentCountry.SupportsBankSortCode Then
            AccountNumber = Replace(Replace(bankingDetails.AccountSortCode, " ", ""), "-", "") &amp; " " &amp; Replace(Replace(bankingDetails.AccountNumber, " ", ""), "-", "")
          Else
            AccountNumber = Replace(Replace(bankingDetails.AccountNumber, " ", ""), "-", "")
          End If
        End If  
  
        mExcludeAccountNumbers.Add(AccountNumber, True)
      Next
    End If
    
    '###########################################################################
    '###########################################################################
    ' Add any special Bank Account Numbers here
    '###########################################################################
    '###########################################################################
  End If
    
  ' Create Data
  If Main Then
    finBL.StatusProcessBegin("Bank Account Match", "", True)
    
    Main = Me.CreateData()
    If Main Then Main = Me.CreateData_Match()

    finBL.StatusProcessEnd()
  End If
    
  ' Create Workbook
  If Main Then
    FileName = String.format("AccountNumbers_{0}_{1}.xlsx", Format(now,"yyyyMMdd"), Format(now,"HHmmss"))
    
    Main = Me.CreateWorkbook(FileName)
  End If
  
  ' Open Workbook
  If Main Then
    finBL.OpenAssociatedApplication(FileName)
  End If  
  
End Function

Private Function CreateData() As Boolean
  
  Dim Account As finAccount
  Dim AccountBankingDetail As finAccountBankingDetail
  Dim AccountDisbursement As finAccountDisbursement
  Dim AccountStdTran As finAccountStdTran
  Dim AccountTransaction As finAccountTransaction
  Dim Client As finClient
  Dim ClientBankAccount As finClientBankAccount
  Dim dr As IDataReader
  Dim Include As Boolean
  Dim RowCount As Integer
  Dim RowIndex As Integer
  Dim sqb As ISSelectQueryBuilder
  Dim sqbsub As ISSelectQueryBuilder
  Dim Success As Boolean
  
  ' Assume Success
  Success = True
  
  ' Initialise
  mAccountNumberRecords = New SortedList(Of String, AccountNumberRecord)

  ' CLIENTS
  If Success AndAlso mIncludeClients Then
    ' Create Objects
    Client = finBL.CreateClient()
    
    ' Progress
    finBL.StatusProcess(0, "Retrieving Client Banking details", mCancelled)

    If Success And (Not mCancelled) Then
      sqbsub = finBL.Database.CreateSelectQueryBuilder()
      With sqbsub
        .Clear()
        .Table = "ClientBankAccount"
        .Fields.AddAsterisk()
        .SqlWhere.AppendComparisonField("Client.Pk", "=", "ClientBankAccount.ClientPk")
      End With

      sqb = finBL.Database.CreateSelectQueryBuilder()
      With sqb
        .Clear()
        .Table = "Client"
        .Fields.Add("Pk")
        .SqlWhere.AppendExists(sqbsub)
        .OrderByFields.Add("ClientId")
      
      	If .ExecuteDisconnectedDataReader(dr, RowCount, 0) Then
          RowIndex = 0
          Do While dr.Read
            RowIndex += 1
            finBL.StatusProcess(RowIndex / RowCount * 100, "", mCancelled)
            If mCancelled Then Exit Do

            If Client.LoadPk(finBL.Database.GetFieldInteger(dr!Pk)) Then
              For Each ClientBankAccount In Client.BankAccounts
                If mIncludeClientsClosedBankAccounts OrElse (Not ClientBankAccount.AccountClosed) Then
                  Me.CreateData_Add(ClientBankAccount.ToBankingDetails(), Client.ClientId, "")
                End If    
              Next   
            Else
              Success = False
              Exit Do
            End If 
          Loop
          finBL.Database.DataReaderClose(dr)
        Else
          Success = False
        End If  
      End With
    End If
  End If  
  
  ' ACCOUNTS
  If Success And (Not mCancelled) AndAlso mIncludeAccounts Then
    ' Create Objects
    Account = finBL.CreateAccount()
    
    ' Progress
    finBL.StatusProcess(0, "Retrieving Account Banking details", mCancelled)
    
    If Success And (Not mCancelled) Then
      sqb = finBL.Database.CreateSelectQueryBuilder()
      With sqb
        .Clear()
        .Table = "Account"
        .Fields.Add("Pk")
        With .SqlWhere
          ' Ignore Disbursement Accounts
          .AppendComparisonInteger("Account.AccountClass", "&lt;&gt;", isefinAccountClass.Disbursement)
          
          ' Status
          .BlockBegin(iseSqlWhereBuilderNestedBlockType.OrBlock)
          .AppendComparisonInteger("Account.Status", "=", isefinAccountStatus.Quote)
          .AppendComparisonInteger("Account.Status", "=", isefinAccountStatus.Open)
          .AppendComparisonInteger("Account.Status", "=", isefinAccountStatus.ClosedPending)
          If mIncludeAccountsClosed Then
            .AppendComparisonInteger("Account.Status", "=", isefinAccountStatus.Closed)
          End If
          .BlockEnd()
        End With
        .OrderByFields.Add("AccountId")
      
      	If .ExecuteDisconnectedDataReader(dr, RowCount, 0) Then
          RowIndex = 0
          Do While dr.Read
            RowIndex += 1
            finBL.StatusProcess(RowIndex / RowCount * 100, "", mCancelled)
            If mCancelled Then Exit Do
  
            If Account.LoadPk(finBL.Database.GetFieldInteger(dr!Pk)) Then
              ' Banking Details
              If mIncludeAccountsBankingDetails Then
                For Each AccountBankingDetail In Account.BankingDetails
                  Me.CreateData_Account(AccountBankingDetail.BankingDetails, Account)
                Next
              End If  
              
              ' Standard Transactions (Payments)
              If mIncludeAccountsStandardTransactions Then
                For Each AccountStdTran In Account.StandardTransactions
                  Select Case AccountStdTran.ElementType 
                    Case isefinElementType.PaymentReceived
                      Include = Not AccountStdTran.IsComplete
                    Case Else
                      Include = False
                  End Select    
  
                  If Include Then
                    Me.CreateData_Account(AccountStdTran.BankingDetails, Account)
                  End If  
                Next  
              End If  
              
              ' Disbursements
              If mIncludeAccountsDisbursements Then
                For Each AccountDisbursement In Account.Disbursements
                  If AccountDisbursement.PayeeType = isefinDisbursementPayeeType.Account Then
                    Me.CreateData_Account(AccountDisbursement.BankingDetails, Account)
                  End If  
                Next   
              End If  
              
              ' Bank Transactions
              If mIncludeAccountsBankTransactions Then
                For Each AccountTransaction In Account.Transactions
                  If AccountTransaction.BankTransactionPk &lt;&gt; 0 AndAlso AccountTransaction.Date &gt;= mIncludeAccountsBankTransactionsDatedFrom Then
                    Me.CreateData_Account(AccountTransaction.BankTransactionView.BankingDetails, Account)
                  End If  
                Next  
              End If
            Else
              Success = False
              Exit Do
            End If
          Loop
          finBL.Database.DataReaderClose(dr)
        Else
          Success = False
        End If  
      End With
    End If
  End If  
  
  Return Success
  
End Function

Private Sub CreateData_Account(bankingDetails As finBankingDetails,
                               account As finAccount)
                               
  Dim AccountClient As finAccountClient
                               
  For Each AccountClient In account.Clients
    If AccountClient.IsOwner Then
      Me.CreateData_Add(bankingDetails, AccountClient.ClientId, account.AccountId)
    End If  
  Next              

End Sub                           

Private Sub CreateData_Add(bankingDetails As finBankingDetails,
                           clientId As String,
                           accountId As String)
  
  Dim AccountNumber As String
  Dim AccountNumberRecord As AccountNumberRecord
  Dim AccountNumberClientAccountRecord As AccountNumberClientAccountRecord
  Dim Index As Integer

  ' Find Bank Account Number
  Select Case bankingDetails.PaymentTypeCategory
    Case isefinPaymentTypeCategory.Bank, isefinPaymentTypeCategory.Split, isefinPaymentTypeCategory.ZeptoNZ
      If mIncludeBankAccounts Then
        ' Account Number
        If finBL.CurrentCountry.ValidateBankAccount(BankingDetails, "") Then
          If finBL.CurrentCountry.SupportsBankSortCode Then
            finBL.CurrentCountry.ValidateBankAccountSortCode(bankingdetails, "")
            AccountNumber = bankingDetails.AccountSortCode &amp; " " &amp; bankingDetails.AccountNumber
          Else
            AccountNumber = bankingDetails.AccountNumber
          End If
        Else
          ' Invalid Account Number
          If finBL.CurrentCountry.SupportsBankSortCode Then
            AccountNumber = Replace(Replace(bankingDetails.AccountSortCode, " ", ""), "-", "") &amp; " " &amp; Replace(Replace(bankingDetails.AccountNumber, " ", ""), "-", "")
          Else
            AccountNumber = Replace(Replace(bankingDetails.AccountNumber, " ", ""), "-", "")
          End If
        End If  
      Else
        AccountNumber = ""
      End If
    
    Case isefinPaymentTypeCategory.CreditCard
      If mIncludeCreditCards Then
        ' Account Number
        If finBL.BankingFunctions.ValidateCreditCardNumberFromBankingDetails(bankingDetails, "") Then
          AccountNumber = bankingDetails.AccountNumber
        Else
          AccountNumber = Replace(Replace(bankingDetails.AccountNumber, " ", ""), "-", "")
        End If
      Else
        AccountNumber = ""
      End If  
      
    Case Else
      AccountNumber = ""
  End Select

  ' Exclude?
  If Len(AccountNumber) &lt;&gt; 0 AndAlso mExcludeAccountNumbers IsNot Nothing AndAlso mExcludeAccountNumbers.Exists(AccountNumber) Then
    AccountNumber = ""
  End If  
    
  ' Add Bank Account Number
  If Len(AccountNumber) &lt;&gt; 0 Then
    ' Find existing Item
    If mAccountNumberRecords.ContainsKey(AccountNumber) Then
      AccountNumberRecord = mAccountNumberRecords.Item(AccountNumber)
    End If
    
    ' Add new Bank Account?
    If AccountNumberRecord Is Nothing Then
      AccountNumberRecord = New AccountNumberRecord()
      With AccountNumberRecord
        .AccountNumber = AccountNumber
        .ClientAccounts = New List(Of AccountNumberClientAccountRecord)
      End With  
      mAccountNumberRecords.Add(AccountNumber, AccountNumberRecord)
    End If  
  
    ' Append Account and Client Ids
    With AccountNumberRecord
      AccountNumberClientAccountRecord = New AccountNumberClientAccountRecord()
      With AccountNumberClientAccountRecord
        .AccountId = accountId
        .ClientId = clientId
      End With  

      ' Insert Item
      For Index = 0 To AccountNumberRecord.ClientAccounts.Count - 1
        Select Case StrComp(AccountNumberRecord.ClientAccounts(Index).ClientId, AccountNumberClientAccountRecord.ClientId) 
          Case -1
          Case 0
            ' Match, so check Account
            Select Case StrComp(AccountNumberRecord.ClientAccounts(Index).AccountId, AccountNumberClientAccountRecord.AccountId) 
              Case -1
              Case 0
                ' Found
                Index = -1
                Exit For
              Case 1
                Exit For
            End Select
          Case 1
            Exit For
        End Select
      Next  

      ' Add?
      If Index &gt;= 0 Then
        AccountNumberRecord.ClientAccounts.Insert(Index, AccountNumberClientAccountRecord)
      End If  
    End With  
  End If  
  
End Sub  

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

  ' Create Worksheets
  Me.CreateWorksheetData()
  Me.CreateWorksheetRaw()
  
  ' Calculate Workbook
  If Success Then
    mExcelWorkbook.Calculate()
  End If  

  ' Save the Excel file
  If Success Then
    Success = mExcelWorkbook.Save(fileName)
  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 CreateWorksheetData()

  Dim AccountNumberRecord As AccountNumberRecord
  Dim RowIndex As Integer
  Dim s As String
  Dim Success As Boolean
  Dim Worksheet As ISExcelWorksheet

  ' Create Worksheet
  Success = CreateWorksheet("Data", 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
      With .Item(4).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("Bank Account")
      .Cell(2, RowIndex).SetString("Clients")
      .Cell(3, RowIndex).SetString("Accounts")
      .Cell(4, RowIndex).SetString("Matches")
    End With
  End If

  ' Add Rows
  If Success Then
    For Each AccountNumberRecord In mAccountNumberRecords.Values
      RowIndex += 1
      
      With Worksheet
        ' Highlight Row
        If AccountNumberRecord.MatchTop &gt; 1 Then
          .Rows(RowIndex).Style.Bold = True 
          .Rows(RowIndex).Style.BackgroundColour = "#f0f0f0"
        End If  
        
        .Cell(1, RowIndex).SetString(AccountNumberRecord.AccountNumber)
        .Cell(2, RowIndex).SetInteger(AccountNumberRecord.CountClients)
        .Cell(3, RowIndex).SetInteger(AccountNumberRecord.CountAccounts)
        .Cell(4, RowIndex).SetInteger(AccountNumberRecord.MatchTop)
      End With  
    Next  
  End If
  
  If Success Then
    ' Resize columns to fit
    Worksheet.Columns.Autofit()
    
    ' Add Notes
    With Worksheet
      RowIndex += 1
      If mCancelled Then
        RowIndex += 1: .Cell(1, RowIndex).SetString("REPORT CANCELLED BY USER. The data may contain partial results.")
        RowIndex += 1
      End If  
      
      If mIncludeBankAccounts Then
        If mIncludeCreditCards Then
          RowIndex += 1: .Cell(1, RowIndex).SetString("Reviewed Bank Accounts and Credit Cards.")
        Else
          RowIndex += 1: .Cell(1, RowIndex).SetString("Reviewed Bank Accounts.")
        End If  
      ElseIf mIncludeCreditCards Then
        RowIndex += 1: .Cell(1, RowIndex).SetString("Reviewed Credit Cards.")
      End If  
      
      If mIncludeClients Then
        RowIndex += 1: .Cell(1, RowIndex ).SetString("Include Clients.")
        If mIncludeClientsClosedBankAccounts Then RowIndex += 1: .Cell(1, RowIndex).SetString("  Include Closed Bank Accounts.")
      End If  
      If mIncludeAccounts Then
        RowIndex += 1: .Cell(1, RowIndex ).SetString("Include Accounts.")
        If mIncludeAccountsClosed Then RowIndex += 1: .Cell(1, RowIndex).SetString(" Include Closed Accounts.")
        If mIncludeAccountsBankingDetails Then RowIndex += 1: .Cell(1, RowIndex).SetString("  Include Banking Details.")
        If mIncludeAccountsBankTransactions Then 
          RowIndex += 1
          If mIncludeAccountsBankTransactionsDatedFrom = Nothing Then
            .Cell(1, RowIndex).SetString("  Include Bank Transactions.")
          Else
            .Cell(1, RowIndex).SetString(String.Format("  Include Bank Transactions (from {0}).", finBL.FormatDateLong(mIncludeAccountsBankTransactionsDatedFrom)))
          End If  
        End If  
        If mIncludeAccountsDisbursements Then RowIndex += 1: .Cell(1, RowIndex).SetString("  Include Disbursements.")
        If mIncludeAccountsStandardTransactions Then RowIndex += 1: .Cell(1, RowIndex).SetString("  Include Standard Transactions.")
      End If  
      If mExcludeAccountNumbers.Count &lt;&gt; 0 Then
        RowIndex += 1: .Cell(1, RowIndex).SetString("Excluding Bank Accounts:")
        For Each s In mExcludeAccountNumbers
          RowIndex += 1: .Cell(1, RowIndex).SetString("  " &amp; s)
        Next   
      End If  
    End With  
  End If

End Sub

Private Sub CreateWorksheetRaw()

  Dim AccountNumberRecord As AccountNumberRecord
  Dim AccountNumberClientAccountRecord As AccountNumberClientAccountRecord
  Dim LastMatch As String
  Dim OddRow As Boolean
  Dim RowIndex As Integer
  Dim Success As Boolean
  Dim Worksheet As ISExcelWorksheet

  ' Create Worksheet
  Success = CreateWorksheet("Raw Data", Worksheet) 

  ' Columns
  If Success Then
    With Worksheet.Columns
      With .Item(4).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("Bank Account")
      .Cell(2, RowIndex).SetString("Client")
      .Cell(3, RowIndex).SetString("Account")
      .Cell(4, RowIndex).SetString("Match")
    End With
  End If

  ' Add Rows
  If Success Then
    LastMatch = ""
    OddRow = True
    
    For Each AccountNumberRecord In mAccountNumberRecords.Values
      For Each AccountNumberClientAccountRecord In AccountNumberRecord.ClientAccounts
        RowIndex += 1
        
        With Worksheet
          ' Odd Row background
          If LastMatch &lt;&gt; AccountNumberRecord.AccountNumber Then
            LastMatch = AccountNumberRecord.AccountNumber
            OddRow = Not OddRow
          End If  
          If OddRow Then .Rows(RowIndex).Style.BackgroundColour = "#f0f0f0"

          .Cell(1, RowIndex).SetString(AccountNumberRecord.AccountNumber)
          .Cell(2, RowIndex).SetString(AccountNumberClientAccountRecord.ClientId)
          .Cell(3, RowIndex).SetString(AccountNumberClientAccountRecord.AccountId)
          .Cell(4, RowIndex).SetInteger(AccountNumberClientAccountRecord.Match)
        End With  
      Next  
    Next  
  End If
  
  If Success Then
    ' Resize columns to fit
    Worksheet.Columns.Autofit()
  End If

End Sub

Private Function CreateData_Match() As Boolean
  
  Dim AccountNumberRecord As AccountNumberRecord
  Dim i As Integer
  Dim Index As Integer
  Dim j As Integer
  Dim j1 As Integer
  Dim j2 As Integer
  Dim j3 As Integer
  Dim k1 As Integer
  Dim k2 As Integer
  Dim CountUpdated As Integer
  Dim Match As Integer
  Dim Success As Boolean
  
  ' Assume Success
  Success = True
  
  finBL.StatusProcess(0, "Matching Bank Accounts")

  If Success Then
    Index = 0
    For Each AccountNumberRecord In mAccountNumberRecords.Values
      Index += 1
      finBL.StatusProcess(Index / mAccountNumberRecords.Count * 100, "")

      Match = 0
      Do
        ' Next Pass
        Match += 1
        
        ' Find first Item, and range of Items still to process
        j1 = -1
        j2 = -1
        For i = 0 To AccountNumberRecord.ClientAccounts.Count - 1
          If AccountNumberRecord.ClientAccounts(i).Match = 0 Then 
            If j1 = -1 Then
              j1 = i
            ElseIf j2 = -1 Then  
              j2 = i  
            End If  
            j3 = i
          End If  
        Next
        
        ' Quit?
        If j1 = -1 Then Exit Do
          
        ' Set first Item
        AccountNumberRecord.ClientAccounts(j1).Match = Match
        
        ' Quit - if no more Items to match
        If j2 = -1 Then Exit Do

        ' Limit search bounds
        k1 = j1
        k2 = j1
          
        ' Update Related Items
        Do
          CountUpdated = 0
          
          For i = j2 To j3
            If AccountNumberRecord.ClientAccounts(i).Match = 0 Then
              'For j = 0 To AccountNumberRecord.ClientAccounts.Count - 1
              For j = k1 To k2
                If AccountNumberRecord.ClientAccounts(j).Match = Match Then
                  ' Do either Account or Client match?
                  If AccountNumberRecord.ClientAccounts(i).ClientId = AccountNumberRecord.ClientAccounts(j).ClientId Then
                    CountUpdated += 1
                    If k2 &lt; i Then k2 = i
                    AccountNumberRecord.ClientAccounts(i).Match = Match
                    Exit For
                  ElseIf Len(AccountNumberRecord.ClientAccounts(i).AccountId) &lt;&gt; 0 AndAlso AccountNumberRecord.ClientAccounts(i).AccountId = AccountNumberRecord.ClientAccounts(j).AccountId Then
                    CountUpdated += 1
                    If k2 &lt; i Then k2 = i
                    AccountNumberRecord.ClientAccounts(i).Match = Match
                    Exit For
                  End If   
                End If  
              Next   
            End If  
          Next
          
          If CountUpdated = 0 Then Exit Do
        Loop  
      Loop
    Next  
  End If  

  finBL.StatusProcess(100, "Matching Bank Accounts")

  Return Success
  
End Function

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

  Public AccountNumber As String
  Public ClientAccounts As List(Of AccountNumberClientAccountRecord)
  
  Public ReadOnly Property CountAccounts() As Integer
    Get
      Dim List As ISList
      
      List = finBLShared.Runtime.CreateList()
      For Each AccountNumberClientAccountRecord As AccountNumberClientAccountRecord In ClientAccounts
        If Len(AccountNumberClientAccountRecord.AccountId) &lt;&gt; 0 Then List.Add(AccountNumberClientAccountRecord.AccountId, True)
      Next
      
      Return List.Count()
    End Get
  End Property  
  
  Public ReadOnly Property CountClients() As Integer
    Get
      Dim List As ISList
      
      List = finBLShared.Runtime.CreateList()
      For Each AccountNumberClientAccountRecord As AccountNumberClientAccountRecord In ClientAccounts
        If Len(AccountNumberClientAccountRecord.ClientId) &lt;&gt; 0 Then List.Add(AccountNumberClientAccountRecord.ClientId, True)
      Next
      
      Return List.Count()
    End Get
  End Property  
  
  Public ReadOnly Property MatchTop() As Integer
    Get
      MatchTop = 0
      For Each AccountNumberClientAccountRecord As AccountNumberClientAccountRecord In ClientAccounts
        If MatchTop &lt; AccountNumberClientAccountRecord.Match Then 
          MatchTop = AccountNumberClientAccountRecord.Match
        End If  
      Next
    End Get
  End Property  

End Class

Public Class AccountNumberClientAccountRecord
  
  Public ClientId As String
  Public AccountId As String
  Public Match As Integer
  
End Class</Code>
    <Language>VisualBasic</Language>
    <Notes>This is a BETA script. Please use with caution and check results.

Reports Accounts and Clients where the same Bank Account or Credit Card Number is used - which may indicate fraud.

It tries to ignore scenarios where a Bank Account is used on multiple Accounts, where one or more Clients are common between the Accounts.</Notes>
    <PermissionKeyExecute />
    <ReferenceLinq>false</ReferenceLinq>
    <RunWithoutPrompts>false</RunWithoutPrompts>
    <TemplateText />
    <TemplateTextBookmarks />
    <TimeoutSeconds>600</TimeoutSeconds>
    <UniqueId>Uz2RMyI7O0yJPykdNaoWGA</UniqueId>
    <AllowSaveLoadParametersOnExecute>true</AllowSaveLoadParametersOnExecute>
    <RunAsAdministrator>false</RunAsAdministrator>
    <ShowInMenu>None</ShowInMenu>
    <ParametersType>Custom</ParametersType>
    <Parameters>
      <ISParameterDefs version="1.00">
        <Parameters>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>Options.</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="IncludeBankAccounts" type="Boolean">
            <BlankTip />
            <Caption>Include Bank Accounts?</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>True</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="IncludeCreditCards" type="Boolean">
            <BlankTip />
            <Caption>Include Credit Cards?</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>True</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>Client Options.</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="IncludeClients" type="Boolean">
            <BlankTip />
            <Caption>Include Clients?</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>True</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="IncludeClientsClosedBankAccounts" type="Boolean">
            <BlankTip />
            <Caption>Include Closed Bank Accounts?</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>1</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>False</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>Account Options.</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="IncludeAccounts" type="Boolean">
            <BlankTip />
            <Caption>Include Accounts?</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>True</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="IncludeAccountsBankingDetails" type="Boolean">
            <BlankTip />
            <Caption>Include Banking Details?</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>1</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>True</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="IncludeAccountsBankTransactions" type="Boolean">
            <BlankTip />
            <Caption>Include Bank Transactions?</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>1</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>True</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="IncludeAccountsBankTransactionsDatedFrom" type="Date">
            <BlankTip />
            <Caption>Dated From</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression>DateAdd("Y", -1, Now())</DefaultValueExpression>
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>2</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <IncludeTime>false</IncludeTime>
            <MaxValue />
            <MinValue />
          </Parameter>
          <Parameter name="IncludeAccountsClosed" type="Boolean">
            <BlankTip />
            <Caption>Include closed Accounts?</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>1</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>False</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="IncludeAccountsDisbursements" type="Boolean">
            <BlankTip />
            <Caption>Include Disbursements?</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>1</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>True</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="IncludeAccountsStandardTransactions" type="Boolean">
            <BlankTip />
            <Caption>Include Standard Transactions?</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>1</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>True</Value>
            <Visible>true</Visible>
          </Parameter>
        </Parameters>
      </ISParameterDefs>
    </Parameters>
  </finScript>