<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2022-09-21T01:20:43.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2015-08-25T02:09:41.0000000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2022-09-21T01:20:32.3450000</UpdatedUtcDate>
    <ScriptId>AP.HISTRAT</ScriptId>
    <Description>Account History Rating update</Description>
    <ScriptType>ObjectEvents</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Category />
    <Code>' Script_AccountProcesses_AccountHistoryRatingUpdate.xml
Option Explicit On
Option Strict On

' #################################################################
' Update Account History Rating
' 
' Version: 1.07 (21/09/2022)
'
' Remarks
' -------
' Use in Account Processes as a Pre Script
' 
' WARNING: Sample Script, please ensure this script fits your purposes before using.
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.06  24/12/2020  ISS
'    1.07  21/09/2022  ISS      J029586   Fixed compilation warnings
' #################################################################

'#Const "Calendar",String,"","Calendar to use with DaysDelay to ignore non-Business days."
'#Const "DaysDelay",Integer,3,"Number of Calendar days after End of Month before processing History."
'#Const "DaysGrace",Integer,0,"Number of days overdue before an Account is shown as Overdue."

' Constants
Private Calendar As String = ""
Private DaysDelay As Integer = 3
Private DaysGrace As Integer = 0

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 Account As finAccount
  Dim AccountProcesses As finAccountProcesses
  Dim AccountTransaction As finAccountTransaction
  Dim AccountType As finAccountTypeRO
  Dim AccountTypes As String
  Dim dr As IDataReader
  Dim HistoryRating As String
  Dim HistoryRatingCharacter As String
  Dim HistoryRatingUpdatedDate As Date
  Dim Include As Boolean
  Dim NextDate As Date
  Dim Ok As Boolean
  Dim OverdueDays As Integer
  Dim ProcessToDate As Date
  Dim sqb As ISSelectQueryBuilder

  ' Assume Success
  Main = True

  ' Get Constants
  With ScriptInfo.Constants
    Calendar = .GetString("Calendar", Calendar)
    DaysDelay = .GetInteger("DaysDelay", DaysDelay)
    DaysGrace = .GetInteger("DaysGrace", DaysGrace)
  End With

  ' Initialise
  AccountProcesses = DirectCast(source, finAccountProcesses)

  ' Handle Events
  Select Case eventId
    Case "AccountProcessesPre"
      ' Account Processes is starting. Return False to abort

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

      ' Date to Process to
      If Len(Calendar) = 0 Then
        ProcessToDate = finBL.Runtime.DateUtilities.EndOfPreviousMonth(finBL.TimeZoneFunctions.GetCurrentDatabaseDate().AddDays(1 - DaysDelay))
      ElseIf finBL.Calendars.Exists(Calendar) Then
        ProcessToDate = finBL.Runtime.DateUtilities.EndOfPreviousMonth(finBL.Calendars(Calendar).GetPastBusinessDay(finBL.TimeZoneFunctions.GetCurrentDatabaseDate(), DaysDelay))
      Else
        Main = False
        finBL.Error.ErrorBeginFormat("Invalid Calendar '{0}'.", Calendar)
      End If

      If Main Then
        ' Notify User
        AccountProcesses.NotifyProgress(0, String.Format("Updating Account History Ratings to {0}", finBL.FormatDateLong(ProcessToDate)))

        With sqb
          .Table = "Account"
          .Fields.AddList("Account.Pk")

          With .SqlWhere
            ' Limit to Open Accounts, or Closed after the Process To Date
            .BlockBegin(iseSqlWhereBuilderNestedBlockType.OrBlock)
            .AppendComparisonInteger("Account.Status", "=", CInt(isefinAccountStatus.Open))
            .BlockBegin(iseSqlWhereBuilderNestedBlockType.AndBlock)
            .BlockBegin(iseSqlWhereBuilderNestedBlockType.OrBlock)
            .AppendComparisonInteger("Account.Status", "=", CInt(isefinAccountStatus.Closed))
            .AppendComparisonInteger("Account.Status", "=", CInt(isefinAccountStatus.ClosedPending))
            .BlockEnd
            .AppendComparisonDate("Account.DateClosed", "&gt;", ProcessToDate)
            .BlockEnd
            .BlockEnd

            ' Limit to Account Types that show History Rating information
            AccountTypes = ""
            For Each AccountType In finBL.AccountTypes
              If AccountType.ShowHistoryRating Then
                ' Also limit to Account Types that support Overdues
                Include = True
                Select Case AccountType.AccountClass
                  Case isefinAccountClass.LoanFR, isefinAccountClass.LoanFT, isefinAccountClass.LoanRC
                  Case Else
                    Include = False
                End Select

                If Include Then
                  If Len(AccountTypes) &lt;&gt; 0 Then AccountTypes &amp;= ","
                  AccountTypes &amp;= CStr(AccountType.Pk)
                End If
              End If
            Next
            If Len(AccountTypes) = 0 Then
              ' No valid Account Types - so make sure we don't return any records
              .AppendComparisonNull("Account.AccountTypePk")
            Else
              .AppendRange("Account.AccountTypePk", AccountTypes, iseRangeDataType.Long)
            End If

            ' Filter to include Accounts that need updating
            .BlockBegin(iseSqlWhereBuilderNestedBlockType.OrBlock)
            ' Last History Updated Date
            .BlockBegin(iseSqlWhereBuilderNestedBlockType.OrBlock)
            .AppendComparisonNull("Account.HistoryUpdatedDate")
            .AppendComparisonDate("Account.HistoryUpdatedDate", "&lt;", ProcessToDate)
            .BlockEnd()
            ' Include where Backdated
            .BlockBegin(iseSqlWhereBuilderNestedBlockType.AndBlock)
            .AppendComparisonNotNull("Account.DateBackdatedTo")
            .AppendComparisonField("Account.DateBackdatedTo", "&lt;=", "HistoryUpdatedDate")
            .BlockEnd()
            .BlockEnd()
          End With

          ' Add Account Processes Filters
          accountprocesses.UpdateSqlWhereBuilder(sqb.SqlWhere)

          ' Joins for Ranges specified in Account Processes
          If Len(AccountProcesses.RangeClientGroups) &lt;&gt; 0 OrElse Len(AccountProcesses.RangeClientTypes) &lt;&gt; 0 Then
            .Joins.Add("Client", "Client.Pk", "Account.ClientPk", iseSelectQueryJoinType.Inner)
          End If

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

        ' Execute Query
        If sqb.ExecuteDisconnectedDataReader(dr, 0, ScriptInfo.TimeoutSeconds) Then
          Do While dr.Read
            ' Load Account
            If Not Account.LoadPk(finBL.Database.GetFieldInteger(dr!Pk)) Then
              Main = False
              Exit Do
            End If

            ' Show Progress
            AccountProcesses.NotifyProgress(0, String.Format("  Account {0}", Account.AccountId))

            ' Initialise
            HistoryRating = Account.HistoryRating
            HistoryRatingUpdatedDate = Account.HistoryRatingUpdatedDate
            Ok = True

            If HistoryRatingUpdatedDate = Nothing Then
              ' First History Rating
              HistoryRating = ""
              HistoryRatingUpdatedDate = finBL.Runtime.DateUtilities.EndOfPreviousMonth(Account.DateOpened.AddDays(1))

              ' Ignore Account if it does not have Transactions that affect Overdue
              Ok = False
              For Each AccountTransaction In Account.Transactions
                If AccountTransaction.Overdue &lt;&gt; 0 Then
                  Ok = True
                  Exit For
                End If
              Next
            ElseIf Account.DateBackdatedTo &lt;&gt; Nothing Then
              ' Backdated
              Do Until HistoryRatingUpdatedDate &lt; Account.DateBackdatedTo OrElse HistoryRatingUpdatedDate &lt; Account.DateOpened
                ' Undo one Month
                If Len(HistoryRating) &lt;&gt; 0 Then HistoryRating = Mid(HistoryRating, 2)
                HistoryRatingUpdatedDate = finBL.Runtime.DateUtilities.EndOfPreviousMonth(HistoryRatingUpdatedDate)
              Loop
            End If

            If Ok Then
              Do
                ' Next History Date
                NextDate = finBL.Runtime.DateUtilities.EndOfNextMonth(HistoryRatingUpdatedDate)

                ' Quit?
                If NextDate &gt; ProcessToDate Then Exit Do

                ' Quit if we are passing the date backdated to, Account Calculations need to run before we can process these months
                If Account.DateBackdatedTo &lt;&gt; Nothing AndAlso NextDate &gt;= Account.DateBackdatedTo Then Exit Do

                ' Update HistoryRatingUpdatedDate
                HistoryRatingUpdatedDate = NextDate

                ' Calculate Overdue Days
                If Not Account.GetOverdueDays(OverdueDays, HistoryRatingUpdatedDate, True) Then
                  Main = False
                  Exit Do
                End If

                ' Update History Rating
                Select Case OverdueDays
                  Case Is &lt;= DaysGrace : HistoryRatingCharacter = "0"
                  Case Is &lt; 30 : HistoryRatingCharacter = "1"
                  Case Is &lt; 60 : HistoryRatingCharacter = "2"
                  Case Is &lt; 90 : HistoryRatingCharacter = "3"
                  Case Is &lt; 120 : HistoryRatingCharacter = "4"
                  Case Is &lt; 150 : HistoryRatingCharacter = "5"
                  Case Is &lt; 180 : HistoryRatingCharacter = "6"
                  Case Else : HistoryRatingCharacter = "X"
                End Select
                HistoryRating = Left(HistoryRatingCharacter &amp; HistoryRating, 36)
              Loop
              If Not Main Then Exit Do

              ' Update Account
              If HistoryRatingUpdatedDate &lt;&gt; Account.HistoryRatingUpdatedDate OrElse HistoryRating &lt;&gt; Account.HistoryRating Then
                If Not finBL.AccountFunctions.AccountHistoryRatingUpdatePk(Account.Pk, HistoryRating, HistoryRatingUpdatedDate) Then
                  Main = False
                  Exit Do
                End If
              End If
            End If
          Loop
          finBL.Database.DataReaderClose(dr)
        Else
          Main = False
        End If
      End If

  End Select

  ' Error
  If Not Main Then
    finBL.Error.ErrorExtendFormat("Failed to run script '{0}'.", ScriptInfo.ScriptId)
  End If

End Function</Code>
    <Language>VisualBasic</Language>
    <Notes>Run as part of Account Processes. It needs to be configured under Global Settings, Accounts group, Scripts "AccountProcessesPre".

This will update Account History Rating information based upon 30 day overdue slots.

"0" = Prepaid or not overdue
"1" = Less than 30 days overdue
"2" = Less than 60 days overdue
"3" = Less than 90 days overdue
"4" = Less than 120 days overdue
"5" = Less than 150 days overdue
"6" = Less than 180 days overdue
"X" = 180 days or more overdue</Notes>
    <PermissionKeyExecute />
    <RunWithoutPrompts>false</RunWithoutPrompts>
    <TemplateText />
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>628mHNMklUaBIQiUCYkpyw</UniqueId>
    <RunAsAdministrator>false</RunAsAdministrator>
    <TargetObjectType>AccountProcesses</TargetObjectType>
    <ParametersType>None</ParametersType>
    <Constants>
      <ISScriptConstants version="1.00">
        <ScriptConstant name="Calendar" constantType="String">
          <Notes>Calendar to use with DaysDelay to ignore non-Business days.</Notes>
          <Value />
          <Encrypt>false</Encrypt>
        </ScriptConstant>
        <ScriptConstant name="DaysDelay" constantType="Integer">
          <Notes>Number of Calendar days after End of Month before processing History.</Notes>
          <Value>3</Value>
        </ScriptConstant>
        <ScriptConstant name="DaysGrace" constantType="Integer">
          <Notes>Number of days overdue before an Account is shown as Overdue.</Notes>
          <Value>0</Value>
        </ScriptConstant>
      </ISScriptConstants>
    </Constants>
  </finScript>