' ObjectEvents_CreditBureauDefaults_Events
Option Explicit On
Option Strict On

' ####################################################################
' Credit Bureau Defaults Event Script

' Version: 1.18 (18/09/2023)

' Usage: Credit Bureau Defaults
' ####################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.16  20/05/2020  ISS                
'    1.17  18/10/2022  ISS      J028829   Add support for Archiving
'    1.18  18/09/2023  ISS      J032042   Removed extraneous code
' #################################################################

'#Const "ExcludeIfPreviouslyArchived",Boolean,True,"Indicates whether to add a new Default if there is a previous Default that has been Archived"

' "In Legal" is a special option that will use the Account's Balance rather than Overdue
'#Const "InLegalLedgerRange",String,,"Range of Ledgers to treat as in Legal."
'#Const "InLegalMonitorCategoryARange",String,,"Range of Monitor Category As to treat as in Legal."
'#Const "InLegalMonitorCategoryBRange",String,,"Range of Monitor Category Bs to treat as in Legal."
'#Const "InLegalMonitorCategoryCRange",String,,"Range of Monitor Category Cs to treat as in Legal."

' Constants
Private ExcludeIfPreviouslyArchived As Boolean = True
Private InLegalLedgerRange As ISRanges
Private InLegalMonitorCategoryARange As ISRanges
Private InLegalMonitorCategoryBRange As ISRanges
Private InLegalMonitorCategoryCRange As ISRanges

' Properties
Private ArchiveDate As Date

Public Function Main(eventId As String, ByRef eventHandled As Boolean, source As Object, sourceIndex As Integer, contextData1 As Object, contextData2 As Object, parameters As ISKeyValueList) As Boolean

  Dim CreditBureauDefault As finCreditBureauDefault
  Dim CreditBureauDefaults As finCreditBureauDefaults

  ' Assume Success
  Main = True

  ' Get Constants
  With ScriptInfo.Constants
    ExcludeIfPreviouslyArchived = .GetBoolean("ExcludeIfPreviouslyArchived", ExcludeIfPreviouslyArchived)
    InLegalLedgerRange = finBL.Runtime.CreateRanges(.GetString("InLegalLedgerRange"))
    InLegalMonitorCategoryARange = finBL.Runtime.CreateRanges(.GetString("InLegalMonitorCategoryARange"))
    InLegalMonitorCategoryBRange = finBL.Runtime.CreateRanges(.GetString("InLegalMonitorCategoryBRange"))
    InLegalMonitorCategoryCRange = finBL.Runtime.CreateRanges(.GetString("InLegalMonitorCategoryCRange"))
  End With

  ' Find Archive Date
  'ArchiveDate = finBL.TimeZoneFunctions.GetCurrentDatabaseDate().AddYears(-finBL.Settings.CreditBureauDefaultsMaximumYears)
  ArchiveDate = finBL.TimeZoneFunctions.GetCurrentDatabaseDate().AddYears(-5)
  
  ' Handle Events
  Select Case eventId
    Case "Refresh"
      ' Runs when the collection is being refreshed
      CreditBureauDefaults = DirectCast(source, finCreditBureauDefaults)

      ' Refresh Collection
      Main = Me.Refresh(CreditBureauDefaults)

    Case "RefreshItem"
      ' Runs when an item is refreshed
      CreditBureauDefault = DirectCast(contextData1, finCreditBureauDefault)

      ' Refresh Item
      Main = Me.RefreshItem(CreditBureauDefault, False, Nothing, 0)
  End Select

End Function

Private Function Refresh(creditBureauDefaults As finCreditBureauDefaults) As Boolean

  Dim Account As finAccount
  Dim AccountClient As finAccountClient
  Dim AccountHistoryItem As finAccountHistoryItem
  Dim AccountPk As Integer
  Dim CreditBureauDefault As finCreditBureauDefault
  Dim DefaultDate As Date
  Dim dr As IDataReader
  Dim Include As Boolean
  Dim Overdue As Decimal
  Dim OverdueDays As Integer
  Dim sqb As ISSelectQueryBuilder
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Create Objects
  Account = finBL.CreateAccount()
  sqb = finBL.Database.CreateSelectQueryBuilder()

  ' Refresh existing Items
  If Success Then
    For Each CreditBureauDefault In creditBureauDefaults
      ' Refresh Item
      If Not Me.RefreshItem(CreditBureauDefault, False, Nothing, 0) Then
        Success = False
        Exit For
      End If
    Next
  End If

  ' Load New Items
  If Success Then
    ' Build Query
    With sqb
      .Clear
      .Table = "Account"
      .Fields.Add("Pk")
      With .SqlWhere
        .AppendComparisonInteger("Account.Status", "=", CInt(isefinAccountStatus.Open))
        .AppendComparisonIntegerBoolean("Account.SuspendCreditBureauDeflt", "=", False)

        .BlockBegin(iseSqlWhereBuilderNestedBlockType.OrBlock)

        ' Normal
        If finBL.Settings.CreditBureauDefaultsUseContractualOverdue Then
          .AppendComparisonDecimal("Account.BalanceOverdueC", ">=", finBL.Settings.CreditBureauDefaultsMinimumValue)
        Else
          .AppendComparisonDecimal("Account.BalanceOverdue", ">=", finBL.Settings.CreditBureauDefaultsMinimumValue)
        End If

        ' In Legal
        .BlockBegin(iseSqlWhereBuilderNestedBlockType.OrBlock)
        If InLegalLedgerRange.Count <> 0 Then .AppendRange("Account.Ledger", InLegalLedgerRange.ToRangeString())
        If InLegalMonitorCategoryARange.Count <> 0 Then .AppendRangeWithPk("Account.MonitorCatAPk", "MonitorCategory", "MonitorCategoryId", "MonitorCategory.Pk", InLegalMonitorCategoryARange.ToRangeString())
        If InLegalMonitorCategoryBRange.Count <> 0 Then .AppendRangeWithPk("Account.MonitorCatBPk", "MonitorCategory", "MonitorCategoryId", "MonitorCategory.Pk", InLegalMonitorCategoryBRange.ToRangeString())
        If InLegalMonitorCategoryCRange.Count <> 0 Then .AppendRangeWithPk("Account.MonitorCatCPk", "MonitorCategory", "MonitorCategoryId", "MonitorCategory.Pk", InLegalMonitorCategoryCRange.ToRangeString())
        .BlockEnd()

        .BlockEnd()

        ' Ranges
        creditBureauDefaults.UpdateSqlWhereBuilder(sqb.SqlWhere)
      End With
      .OrderByFields.AddList("Account.AccountId")
    End With

    ' Load
    If sqb.ExecuteDisconnectedDataReader(dr) Then
      With dr
        ' Loop through Accounts
        Do While .Read()
          ' Find Account
          AccountPk = finBL.Database.GetFieldInteger(dr!Pk)

          If creditBureauDefaults.ExistsAccountPk(AccountPk) Then
            ' Already exists, so ignore
          Else
            ' Load Account
            If Not Account.LoadPk(AccountPk) Then
              Success = False
              Exit Do
            End If

            ' Include?
            Include = True

            ' Enabled on Cost Centre?
            Select Case creditBureauDefaults.CreditBureauServiceId
              Case "CentrixNZ"
                Include = finBL.CostCentresResolved.ItemByBranchPk(Account.BranchPk).CentrixNZ.CreditEnquiryEnableConsumerDefaults
              Case "VedaXMLNZ"
                Include = finBL.CostCentresResolved.ItemByBranchPk(Account.BranchPk).EquifaxNZ.CreditEnquiryEnableConsumerDefaults
            End Select

            ' Service-specific checks
            If Include Then
              Select Case creditBureauDefaults.CreditBureauServiceId
                Case "CentrixNZ", "CreditReportingAU", "VedaXMLNZ"
                  ' Check has at least one Individual
                  Include = False
                  For Each AccountClient In Account.Clients
                    ' Individuals/ Sole Traders Only
                    Select Case AccountClient.RoleType
                      Case isefinAccountRoleType.Guarantor
                        If finBL.Settings.CreditBureauDefaultsIncludeGuarantors AndAlso (AccountClient.IsIndividual OrElse AccountClient.IsSoleTrader) Then
                          Include = True
                          Exit For
                        End If
                      Case isefinAccountRoleType.Owner
                        If AccountClient.IsIndividual OrElse AccountClient.IsSoleTrader Then
                          Include = True
                          Exit For
                        End If
                    End Select
                  Next
              End Select
            End If

            ' Test in already had an Archived Default (from any service)
            If Include AndAlso ExcludeIfPreviouslyArchived Then
              For Each AccountHistoryItem In Account.HistoryItems
                ' Must be a Credit Bureau Default Item that is "Complete"
                If AccountHistoryItem.HistoryType = isefinAccountHistoryType.CreditBureauDefault AndAlso AccountHistoryItem.Status = isefinAccountHistoryStatus.Complete Then
                  Select Case ucase(AccountHistoryItem.CreditBureauDefaultLastDefaultStatus)
                    Case "ARCHIVE"
                      Include = False
                  End Select
                End If  
              Next
            End If  

            ' Test Overdues
            If Include Then
              ' Get Overdue Days and Value
              If Me.GetOverduesForNewItem(account, Overdue, OverdueDays, DefaultDate) Then
                If Overdue <= 0 Then Include = False
              Else
                Success = False
                Exit Do
              End If
            End If
            
            ' Add new Default (but do not refresh since we will call RefreshItem passing in our already calculated values as an optimisation)
            If Include Then
              If creditBureauDefaults.AddAccount(Account.AccountId, CreditBureauDefault, False) Then
                If Not Me.RefreshItem(CreditBureauDefault, True, DefaultDate, Overdue) Then
                  Success = False
                  Exit Do
                End If
              Else
                Success = False
                Exit Do
              End If
            End If
          End If
        Loop
      End With
      finBL.Database.DataReaderClose(dr)
    Else
      Success = False
    End If
  End If

  ' Error
  If Not Success Then
    finBL.Error.ErrorExtend("Failed to refresh Credit Bureau Defaults.")
  End If

  ' Return Success
  Return Success

End Function

Private Function RefreshItem(creditBureauDefault As finCreditBureauDefault,
                             currentDetailsSupplied As Boolean,
                             currentDateOfDefault As Date,
                             currentDefault As Decimal) As Boolean

  Dim Success As Boolean

  ' Assume Success
  Success = True

  Select Case creditBureauDefault.CreditBureauServiceId
    Case "CentrixNZ"
      Success = RefreshItem_CentrixNZ(creditBureauDefault, currentDetailsSupplied, currentDateOfDefault, currentDefault)

    Case "CreditReportingAU"
      RefreshItem = RefreshItem_CreditReportingAU(creditBureauDefault, currentDetailsSupplied, currentDateOfDefault, currentDefault)

    Case "VedaXMLNZ"
      Success = RefreshItem_VedaXmlNZ(creditBureauDefault, currentDetailsSupplied, currentDateOfDefault, currentDefault)

    Case Else
      Success = False
      finBL.Error.ErrorBeginFormat("Credit Bureau Service '{0}' is not implemented in script '{1}'.", creditBureauDefault.CreditBureauServiceId, ScriptInfo.ScriptId)
  End Select

  ' Error
  If Not Success Then
    finBL.Error.ErrorExtend("Failed to refresh Credit Bureau Default item.")
  End If

  ' Return Success
  Return Success

End Function

Private Function RefreshItem_CentrixNZ(creditBureauDefault As finCreditBureauDefault,
                                       currentDetailsSupplied As Boolean,
                                       currentDateOfDefault As Date,
                                       currentDefault As Decimal) As Boolean

  Dim AccountTransaction As finAccountTransaction
  Dim DefaultDate As Date
  Dim Overdue As Decimal
  Dim OverdueDays As Integer
  Dim Success As Boolean
  Dim UnclearedFunds As Decimal

  ' Assume Success
  Success = True

  ' Update Item
  With creditBureauDefault
    If .IsNew Then
      ' New Item
      If currentDetailsSupplied Then
        ' Update with supplied details (Script optimisation)
        .CurrentDateOfDefault = currentDateOfDefault
        .CurrentDefault = currentDefault
      Else
        ' Get Overdue Days and Value
        If Me.GetOverduesForNewItem(.Account, Overdue, OverdueDays, DefaultDate) Then
          ' Update
          .CurrentDateOfDefault = DefaultDate
          .CurrentDefault = Overdue
        Else
          Success = False
        End If
      End If

      If Success Then
        ' Status
        If .CurrentDefault <= 0 Then
          .CurrentDefaultStatus = ""
        Else
          .CurrentDefaultStatus = "ACTV"

          ' Default Account Type
          Select Case .Account.AccountTypeId
            ' Add code for specific Account Types as required
            Case Else
              Select Case .Account.AccountType.AccountClass
                Case isefinAccountClass.LoanRC
                  .CurrentDefaultAccountType = "REVG"
                Case Else
                  .CurrentDefaultAccountType = "LOAN"
              End Select
          End Select
        End If
      End If
    ElseIf .IsCurrentStatusClosing Then
      ' Closing Item so do nothing
    Else
      ' Existing Item
      If .IsLoaded Then
        ' Default is LOADED with Credit Bureau
        If .OriginalDateOfDefault <= ArchiveDate Then
          ' Archive
          .CurrentDefaultStatus = "ARCHIVE" ' "ARCHIVE (more than 5 years old)" - special status
        Else  
          ' Get Current Overdue Value and Uncleared Funds
          If Me.IsInLegal(.Account) Then
            Success = .Account.GetBalance(Overdue, finBL.TimeZoneFunctions.GetCurrentDatabaseDate())
          Else
            Success = .Account.GetBalanceOverdue(Overdue, finBL.TimeZoneFunctions.GetCurrentDatabaseDate())
          End If
          If Success Then Success = .Account.GetUnclearedFunds2(UnclearedFunds, finBL.TimeZoneFunctions.GetCurrentDatabaseDate())

          If Success Then
            Select Case .CurrentDefaultStatus
              Case "ACTV", "PAYG"
                ' Active/ Paying
                If (Overdue + UnclearedFunds) <= 0 Then
                  ' Paid
                  .CurrentDefault = 0
                  .CurrentDefaultStatus = "PAID"
                Else
                  ' Update Overdue
                  .CurrentDefault = Overdue
  
                  ' Check if made payment or payment due since the last Default update
                  If .LastDateExported <> Nothing Then
                    For Each AccountTransaction In .Account.Transactions
                      If (AccountTransaction.ReversePk = 0 AndAlso AccountTransaction.NegativePaymentReversePk = 0) AndAlso AccountTransaction.Date > creditBureauDefault.LastDateExported Then
                        If AccountTransaction.ElementType = isefinElementType.PaymentReceived And AccountTransaction.Value < 0 Then
                          ' Payment made, so set to 'Paying'
                          .CurrentDefaultStatus = "PAYG"
                          Exit For
                        ElseIf AccountTransaction.ElementType = isefinElementType.PaymentDue Then
                          ' Payment due, so set back to 'Active'
                          .CurrentDefaultStatus = "ACTV"
                        End If
                      End If
                    Next
                  End If
                End If
          
              Case "SOFA"
                ' Scheme of Arrangement
                If (Overdue + UnclearedFunds) <= 0 Then
                  ' Paid
                  .CurrentDefault = 0
                  .CurrentDefaultStatus = "PAID"
                Else
                  ' Update Overdue
                  .CurrentDefault = Overdue
                End If
  
              Case Else
                If (Overdue + UnclearedFunds) <= 0 Then
                  ' Paid
                  .CurrentDefault = 0
                  .CurrentDefaultStatus = "PAID"
                End If
            End Select
          End If
        End If  
      Else
        ' Default is NOT LOADED with the Credit Bureau
        If Me.GetOverduesForNewItem(.Account, Overdue, OverdueDays, DefaultDate) Then
          ' Update
          If Overdue <= 0 Then
            .CurrentDefault = 0
            .CurrentDefaultStatus = "CAND"
          Else
            .CurrentDateOfDefault = DefaultDate
            .CurrentDefault = Overdue
            .CurrentDefaultStatus = "ACTV"
          End If
        Else
          Success = False
        End If
      End If
    End If
  End With

  ' Return Success
  Return Success

End Function

Private Function RefreshItem_CreditReportingAU(creditBureauDefault As finCreditBureauDefault,
                                               currentDetailsSupplied As Boolean,
                                               currentDateOfDefault As Date,
                                               currentDefault As Decimal) As Boolean

  Dim DefaultDate As Date
  Dim Overdue As Decimal
  Dim OverdueDays As Integer
  Dim Success As Boolean
  Dim UnclearedFunds As Decimal

  ' Assume Success
  Success = True

  ' Update Item
  With creditBureauDefault
    If .IsNew Then
      ' New Item
      If currentDetailsSupplied Then
        ' Update with supplied details (Script optimisation)
        .CurrentDateOfDefault = currentDateOfDefault
        .CurrentDefault = currentDefault
      Else
        ' Get Overdue Days and Value
        If GetOverduesForNewItem(.Account, Overdue, OverdueDays, DefaultDate) Then
          ' Update
          .CurrentDateOfDefault = DefaultDate
          .CurrentDefault = Overdue
        Else
          Success = False
        End If
      End If

      If Success Then
        ' Status
        If .CurrentDefault <= 0 Then
          .CurrentDefaultStatus = ""
        Else
          .CurrentDefaultStatus = "O" ' Outstanding

          ' Default Account Type
          If finBL.CreditBureau.Services("CreditReportingAU").CodeTables("AccountTypes").Exists(.AccountType.CreditReportingAccountType) Then
            .CurrentDefaultAccountType = .AccountType.CreditReportingAccountType
          Else
            Select Case .Account.AccountTypeId
              Case Else
                Select Case .Account.AccountType.AccountClass
                  Case isefinAccountClass.LoanRC
                    .CurrentDefaultAccountType = "PR"
                  Case Else
                    .CurrentDefaultAccountType = "PF"
                End Select
            End Select
          End If
        End If
      End If
    ElseIf .IsCurrentStatusClosing Then
      ' Closing Item so do nothing
    Else
      ' Existing Item
      ' Get Current Overdue Value and Uncleared Funds
      If Me.IsInLegal(.Account) Then
        Success = .Account.GetBalance(Overdue, finBL.TimeZoneFunctions.GetCurrentDatabaseDate())
      Else
        Success = .Account.GetBalanceOverdue(Overdue, finBL.TimeZoneFunctions.GetCurrentDatabaseDate())
      End If
      If Success Then Success = .Account.GetUnclearedFunds2(UnclearedFunds, finBL.TimeZoneFunctions.GetCurrentDatabaseDate())

      Select Case .CurrentDefaultStatus
        Case "O"
          ' Outstanding
          If (Overdue + UnclearedFunds) <= 0 Then
            ' Paid
            .CurrentDefault = 0
            .CurrentDefaultStatus = "C" ' Complete
          Else
            ' Update Overdue
            .CurrentDefault = Overdue
          End If
        Case Else
          If (Overdue + UnclearedFunds) <= 0 Then
            ' Paid
            .CurrentDefault = 0
            .CurrentDefaultStatus = "C" ' Complete
          End If
      End Select
    End If
  End With

  ' Return Success
  Return Success

End Function

Private Function RefreshItem_VedaXmlNZ(creditBureauDefault As finCreditBureauDefault,
                                       currentDetailsSupplied As Boolean,
                                       currentDateOfDefault As Date,
                                       currentDefault As Decimal) As Boolean

  Dim AccountTransaction As finAccountTransaction
  Dim DefaultDate As Date
  Dim Overdue As Decimal
  Dim OverdueDays As Integer
  Dim Success As Boolean
  Dim UnclearedFunds As Decimal

  ' Assume Success
  Success = True

  ' Update Item
  With creditBureauDefault
    If .IsNew Then
      ' New Item
      If currentDetailsSupplied Then
        ' Update with supplied details (Script optimisation)
        .CurrentDateOfDefault = currentDateOfDefault
        .CurrentDefault = currentDefault
      Else
        ' Get Overdue Days and Value
        If Me.GetOverduesForNewItem(.Account, Overdue, OverdueDays, DefaultDate) Then
          ' Update
          .CurrentDateOfDefault = DefaultDate
          .CurrentDefault = Overdue
        Else
          Success = False
        End If
      End If

      If Success Then
        ' Status
        If .CurrentDefault <= 0 Then
          .CurrentDefaultStatus = ""
        Else
          .CurrentDefaultStatus = "10" ' "Payment Default"

          ' Default Account Type
          Select Case .Account.AccountTypeId
            ' Add code for specific Account Types as required
            Case Else
              .CurrentDefaultAccountType = "LC"
          End Select
        End If
      End If
    ElseIf .IsCurrentStatusClosing Then
      ' Closing Item so do nothing
    Else
      ' Existing Item
      If .IsLoaded Then
        ' Default is LOADED with Credit Bureau
        If .OriginalDateOfDefault <= ArchiveDate Then
          ' Archive
          .CurrentDefaultStatus = "ARCHIVE" ' "ARCHIVE (more than 5 years old)" - special status
        Else  
          ' Get Current Overdue Value and Uncleared Funds
          If Me.IsInLegal(.Account) Then
            Success = .Account.GetBalance(Overdue, finBL.TimeZoneFunctions.GetCurrentDatabaseDate())
          Else
            Success = .Account.GetBalanceOverdue(Overdue, finBL.TimeZoneFunctions.GetCurrentDatabaseDate())
          End If
          If Success Then Success = .Account.GetUnclearedFunds2(UnclearedFunds, finBL.TimeZoneFunctions.GetCurrentDatabaseDate())
  
          If Success Then
            Select Case .CurrentDefaultStatus
              Case "07", "10" ' "Paying by Instalments", "Payment Default"
                ' Default/ Paying
                If (Overdue + UnclearedFunds) <= 0 Then
                  ' Paid
                  .CurrentDefault = 0
                  .CurrentDefaultStatus = "06" ' "Paid"
                Else
                  ' Update Overdue
                  .CurrentDefault = Overdue
  
                  ' Check if made payment or payment due since the last Default update
                  If .LastDateExported <> Nothing Then
                    For Each AccountTransaction In .Account.Transactions
                      If (AccountTransaction.ReversePk = 0 AndAlso AccountTransaction.NegativePaymentReversePk = 0) AndAlso AccountTransaction.Date > creditBureauDefault.LastDateExported Then
                        If AccountTransaction.ElementType = isefinElementType.PaymentReceived And AccountTransaction.Value < 0 Then
                          ' Payment made, so set to 'Paying'
                          .CurrentDefaultStatus = "07" ' "PAYG"
                          Exit For
                        ElseIf AccountTransaction.ElementType = isefinElementType.PaymentDue Then
                          ' Payment due, so set back to 'Default'
                          .CurrentDefaultStatus = "10" ' "DFLT"
                        End If
                      End If
                    Next
                  End If
                End If
  
              Case "15", "SOA" ' "Scheme of Arrangement"
                ' Scheme of Arrangement
                If (Overdue + UnclearedFunds) <= 0 Then
                  ' Paid
                  .CurrentDefault = 0
                  .CurrentDefaultStatus = "06" ' "Paid"
                Else
                  ' Update Overdue
                  .CurrentDefault = Overdue
                End If
  
              Case Else
                If (Overdue + UnclearedFunds) <= 0 Then
                  ' Paid
                  .CurrentDefault = 0
                  .CurrentDefaultStatus = "06" ' "Paid"
                End If
            End Select
          End If  
        End If
      Else
        ' Default is NOT LOADED with the Credit Bureau
        If Me.GetOverduesForNewItem(.Account, Overdue, OverdueDays, DefaultDate) Then
          ' Update
          If Overdue <= 0 Then
            .CurrentDefault = 0
            .CurrentDefaultStatus = "06" ' "Paid"
          Else
            .CurrentDateOfDefault = DefaultDate
            .CurrentDefault = Overdue
            .CurrentDefaultStatus = "10" ' "Payment Default"
          End If
        Else
          Success = False
        End If
      End If
    End If
  End With

  ' Return Success
  Return Success

End Function

Private Function GetOverduesForNewItem(account As finAccount,
                                       ByRef overdue As Decimal,
                                       ByRef overdueDays As Integer,
                                       ByRef defaultDate As Date) As Boolean

  Dim AccountOverdues As finAccountOverdues
  Dim DateAsAt As Date
  Dim Include As Boolean
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise ByRef
  defaultDate = Nothing
  overdue = 0
  overdueDays = 0

  ' Initialise
  DateAsAt = finBL.TimeZoneFunctions.GetCurrentDatabaseDate()

  ' Check for Account being "In Legal"
  If Me.IsInLegal(account) Then
    ' In Legal - so use Balance
    DefaultDate = DateAsAt.AddDays(-finBL.Settings.CreditBureauDefaultsMinimumDays)
    Success = account.GetBalance(Overdue, DateAsAt)
    OverdueDays = CInt(DateDiff(DateInterval.Day, DefaultDate, DateAsAt))
  Else
    ' Normal - so use Overdue

    ' Get Overdues
    AccountOverdues = finBL.CreateAccountOverdues()
    If AccountOverdues.LoadFromAccount(account, finBL.Settings.CreditBureauDefaultsUseContractualOverdue, DateAsAt, False) Then
      ' Apply threshold. Use the Minimum Value to push all old and small overdues together
      AccountOverdues.ApplySmallBalanceThreshold(finBL.Settings.CreditBureauDefaultsMinimumValue)

      If AccountOverdues.Count <> 0 Then
        DefaultDate = AccountOverdues(0).Date
        Overdue = AccountOverdues.TotalOverdue
        OverdueDays = CInt(DateDiff(DateInterval.Day, DefaultDate, DateAsAt))
      End If
    Else
      Success = False
    End If
  End If
    
  ' Check Thresholds
  If Success Then
    If DefaultDate <= DateAsAt.AddYears(-finBL.Settings.CreditBureauDefaultsMaximumYears) Then
      Include = False
    ElseIf OverdueDays < finBL.Settings.CreditBureauDefaultsMinimumDays Then
      Include = False
    ElseIf Overdue < finBL.Settings.CreditBureauDefaultsMinimumValue Then
      Include = False
    Else
      Include = True
    End If

    ' Clear Values
    If Not Include Then
      defaultDate = Nothing
      overdue = 0
      overdueDays = 0
    End If
  End If

  ' Return Success
  Return Success

End Function

Private Function IsInLegal(account As finAccount) As Boolean

  ' Ledger
  If InLegalLedgerRange.Count <> 0 Then
    If InLegalLedgerRange.IsValueInRange(account.Ledger) Then Return True
  End If

  ' Monitor Category A
  If InLegalMonitorCategoryARange.Count <> 0 Then
    If InLegalMonitorCategoryARange.IsValueInRange(account.MonitorCategoryAId) Then Return True
  End If

  ' Monitor Category B
  If InLegalMonitorCategoryBRange.Count <> 0 Then
    If InLegalMonitorCategoryBRange.IsValueInRange(account.MonitorCategoryBId) Then Return True
  End If

  ' Monitor Category C
  If InLegalMonitorCategoryCRange.Count <> 0 Then
    If InLegalMonitorCategoryCRange.IsValueInRange(account.MonitorCategoryCId) Then Return True
  End If

  Return False

End Function