' General_LetterRules
'#Const "Threshold",Number,10,"Overdue balance threshold."
'#Const "R1Days",Number,2,"Overdue BUSINESS days for Reminder 1."
'#Const "PNDays",Number,5,"BUSINESS days since R1 for Pre-Possession Notice."
'#Const "RADays",Number,15,"CALENDAR days since PN for Repossession Authority."
Option Explicit On
Option Strict On

' #################################################################
' Overdue Processing Script for Letters

' Version: 1.02 (27/04/2016)

'This can be run as part Of Account Processes or on its own.
'
'Script assumes the following:
' 1. Monitor Categories exist: R1, PN, RA And HOLD
' 2. Documents exist: R1 (reminder 1), PN (Pre-Possession Notice), RA (Repossession Authority)
'
'Accounts will be processed if:
' 1. They are "Open".
' 2. Account Monitor Category A is not "HOLD"

' Processing Rules
'  Add your procesing code between these remarks.
    ' ###################
    ' Begin Overdue Rules
    ' ###################
    '
    ' #################
    ' End Overdue Rules
    ' #################
' #################################################################

' Set to True to NOT create Document Logs or change Monitor Categories
Private Const TestMode As Boolean = False

' Constants
Private Threshold As Integer
Private R1Days As Integer
Private PNDays As Integer
Private RADays As Integer

Public Function Main(parameters As ISKeyValueList) As Boolean

  Dim Account As finAccount
  Dim AccountProcesses As finAccountProcesses
  Dim DateAsAt As Date
  Dim dr As IDataReader
  Dim sqb As ISSelectQueryBuilder

  ' Assume Success
  Main = True

  ' Get Parameters
  If parameters.Exists("AccountProcesses") Then
    ' Run from Account Processes
    AccountProcesses = DirectCast(parameters.GetObject("AccountProcesses"), finAccountProcesses)

    ' Skip and exit (but don't error) if not running Transaction Processes
    If Not AccountProcesses.LoanInterestAndFeeTransactionsProcess Then
      AccountProcesses.NotifyProgress(0,String.Format("Script '{0}' was not run since Transactions are not being processed.", ScriptInfo.ScriptId))
      Exit Function
    End If

    ' Use Transactions Process to Date
    DateAsAt = AccountProcesses.LoanInterestAndFeeTransactionsProcessToDate
  Else
    ' Run as a General Script
    DateAsAt = parameters.GetDate("DateAsAt")
  End If

  ' Get Constants
  Threshold = ScriptInfo.Constants.GetInteger("Threshold", 10)
  R1Days = ScriptInfo.Constants.GetInteger("R1Days", 2)
  PNDays = ScriptInfo.Constants.GetInteger("PNDays", 5)
  RADays = ScriptInfo.Constants.GetInteger("RADays", 15)

  ' Validate
  If finBL.Settings.AddOns.Workflow Then
    Main = False
    finBL.Error.ErrorBegin("This Script should not be run if licensed for Workflows.")
  ElseIf Threshold < 0 Then
    Main = False
    finBL.Error.ErrorBegin("Threshold Script constant cannot be less than zero.")
  ElseIf R1Days < 0 Then
    Main = False
    finBL.Error.ErrorBegin("R1Days Script constant cannot be less than zero.")
  ElseIf PNDays < 0 Then
    Main = False
    finBL.Error.ErrorBegin("PNDays Script constant cannot be less than zero.")
  ElseIf RADays < 0 Then
    Main = False
    finBL.Error.ErrorBegin("RADays Script constant cannot be less than zero.")
  ElseIf Not finBL.Documents.Exists("R1") Then
    Main = False
    finBL.Error.ErrorBegin("There is no R1, 'Reminder 1' Document set up.")
  ElseIf Not finBL.Documents.Exists("PN") Then
    Main = False
    finBL.Error.ErrorBegin("There is no PN, 'Pre-Possession Notice' Document set up.")
  ElseIf Not finBL.Documents.Exists("RA") Then
    Main = False
    finBL.Error.ErrorBegin("There is no RA, 'Repossession Authority' Document set up.")
  ElseIf Not finBL.MonitorCategories.Exists("R1") Then
    Main = False
    finBL.Error.ErrorBegin("There is no R1, 'Reminder 1' Monitor Category set up.")
  ElseIf Not finBL.MonitorCategories.Exists("PN") Then
    Main = False
    finBL.Error.ErrorBegin("There is no PN, 'Pre-Possession Notice' Monitor Category set up.")
  ElseIf Not finBL.MonitorCategories.Exists("RA") Then
    Main = False
    finBL.Error.ErrorBegin("There is no RA, 'Repossession Authority' Monitor Category set up.")
  ElseIf Not finBL.MonitorCategories.Exists("HOLD") Then
    Main = False
    finBL.Error.ErrorBegin("There is no HOLD, 'On Hold' Monitor Category set up.")
  ElseIf dateAsAt = Nothing Then
    Main = False
    finBL.Error.ErrorBegin("'Date As At' not specified.")
  End If

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

    ' Create Query
    With sqb
      .Clear()
      .Table = "Account"
      .Fields.AddList("Pk,AccountId")

      ' SQL Where
      With .SqlWhere
        ' Open Loans
        .AppendComparisonInteger("Status", "=", isefinAccountStatus.Open)
        .BlockBegin(iseSqlWhereBuilderNestedBlockType.OrBlock)
        .AppendComparisonInteger("AccountClass", "=", isefinAccountClass.LoanFT)
        .AppendComparisonInteger("AccountClass", "=", isefinAccountClass.LoanFR)
        .AppendComparisonInteger("AccountClass", "=", isefinAccountClass.LoanRC)
        .BlockEnd()

        ' Ignore if currently 'On Hold'
        .BlockBegin(iseSqlWhereBuilderNestedBlockType.OrBlock)
        .AppendComparisonNull("MonitorCatAPk")
        .AppendComparisonInteger("MonitorCatAPk", "<>", finBL.MonitorCategories("HOLD").Pk)
        .BlockEnd

        If AccountProcesses Is Nothing Then
          ' User Filters
          .Append(finBL.CurrentUserInformation.FilterAccountSqlWhere)
        Else
          ' Ranges and User Filters specified in Account Processes
          AccountProcesses.UpdateSqlWhereBuilder(sqb.SqlWhere)
        End If
      End With

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

    ' Execute Query
    If sqb.ExecuteDataReader(dr) Then
      With dr
        Do While .Read()
          ' Show Progress (if run from Account Processes)
          If AccountProcesses IsNot Nothing Then AccountProcesses.NotifyProgress(0, String.Format("  Account {0}", !AccountId))

          ' Load Account
          If Not Account.LoadPk(finBL.Database.GetFieldInteger(!Pk)) Then
            Main = False
            Exit Do
          End If

          ' Process Account
          If Not Process_Account(Account, DateAsAt) Then
            Main = False
            Exit Do
          End If

          ' Show Progress (if run from Account Processes)
          If AccountProcesses IsNot Nothing Then AccountProcesses.NotifyProgress(100,"")
        Loop
      End With
      finBL.Database.DataReaderClose(dr)
    Else
      Main = False
    End If
  End If

  ' Show Error
  If AccountProcesses IsNot Nothing AndAlso (Not Main) Then
    AccountProcesses.NotifyProgress(0, "  " & finbl.Error.Message)
    AccountProcesses.Errors.Add("", "Script '" & ScriptInfo.ScriptId & "': " & finbl.Error.Message)
  End If

End Function

Private Function Process_Account(account As finAccount, _
                                 dateAsAt As Date) As Boolean

  Dim AccountLog As finAccountLog
  Dim AccountMonitorCategoryChange As finAccountMonitorCategoryChange
  Dim AccountOverdues As finAccountOverdues
  Dim Calendar As finCalendarRO
  Dim Days As Integer
  Dim DocumentId As String
  Dim MonitorCategoryId As String
  Dim Overdue As Decimal

  ' Assume Success
  Process_Account = True

  ' Load Overdues
  AccountOverdues = finBL.CreateAccountOverdues()
  Process_Account = AccountOverdues.LoadFromAccount(account, False, DateAsAt)

  ' Process
  If Process_Account Then
    ' Get Calendar (for calculating business days)
    Calendar = account.Entity.CalendarWorking

    ' Get Overdues Details
    If accountoverdues.Count = 0 Then
      Days = 0
      Overdue = 0
    Else
      Days = Calendar.GetBusinessDaysDiff(AccountOverdues(0).Date, dateAsAt)
      Overdue = accountoverdues.TotalOverdue
    End If

    ' Information for Test mode
    If TestMode Then
      finBL.DebugPrint(String.Format("Account {0}, overdue {1}, {2} days", account.AccountId, format(Overdue,finbl.CurrencyFormat(True)), Days))
    End If

    ' ###################
    ' Begin Overdue Rules
    ' ###################
    If Len(account.MonitorCategoryAId) = 0 Then
      ' Not currently tracked as Overdue
      If Overdue > 0 AndAlso Days >= R1Days AndAlso Overdue >= Threshold Then
        ' Reminder 1
        MonitorCategoryId = "R1"
        DocumentId = "R1"
      End If
    ElseIf overdue < Threshold Then
      ' Take out of Monitoring
      If Len(account.MonitorCategoryAId) = 0 Then
        MonitorCategoryId = ""
      Else
        MonitorCategoryId = "-"
      End If
      DocumentId = ""
    ElseIf UCase(account.MonitorCategoryAId) = "R1" AndAlso Calendar.GetBusinessDaysDiff(account.MonitorCategoryAUpdatedDate, dateAsAt) >= PNDays Then
      ' Pre-Possession Notice
      MonitorCategoryId = "PN"
      DocumentId = "PN"
    ElseIf UCase(account.MonitorCategoryAId) = "PN" AndAlso DateDiff(DateInterval.Day, account.MonitorCategoryAUpdatedDate, dateAsAt) >= RADays Then
      ' Repossession Authority (based on calendar rather than business days)
      MonitorCategoryId = "RA"
      DocumentId = "RA"
    End If
    ' #################
    ' End Overdue Rules
    ' #################

    If Len(MonitorCategoryId) <> 0 OrElse Len(DocumentId) <> 0 Then
      ' Begin Transaction
      finBL.Database.TransactionBegin()

      ' Set Monitor Category
      If Process_Account AndAlso Len(MonitorCategoryId) <> 0 Then
        ' Debug Information
        If TestMode Then
          If MonitorCategoryId = "-" Then
            finBL.DebugPrint(String.Format("Account '{0}' is moving out of monitoring", account.AccountId))
          Else
            finBL.DebugPrint(String.Format("Account '{0}' is moving to Monitor Category '{1}'", account.AccountId, MonitorCategoryId))
          End If
        End If

        ' Update Monitor Category
        If Not TestMode Then
          AccountMonitorCategoryChange = finBL.CreateAccountMonitorCategoryChange()
          With AccountMonitorCategoryChange
            Process_Account = .AccountLoadPk(account.Pk)

            If Process_Account Then
              .DateEffective = dateAsAt
              .MonitorCategoryAUpdate = True
              If MonitorCategoryId = "-" Then
                .MonitorCategoryAId = ""
              Else
                .MonitorCategoryAId = MonitorCategoryId
              End If

              Process_Account = .ExecuteCommit()
            End If
          End With
        End If
      End If

      ' Create Document
      If Process_Account AndAlso Len(DocumentId) <> 0 Then
        ' Debug Information
        If TestMode Then
          finBL.DebugPrint(String.Format("Account '{0}' is being sent Document '{1}'", account.AccountId, DocumentId))
        End If

        ' Create Document
        If Not TestMode Then
          AccountLog = finBL.CreateAccountLog()
          With AccountLog
            .AccountPk = account.Pk
            .LogType = isefinLogType.Document
            .DocumentId = DocumentId
            .LogDate = dateAsAt
            .PublishOnDate = .LogDate
            .PublishStatus = isefinLogPublishStatus.ToSend
            .Subject = "Outgoing Document"
            .AccountDataSet(dateAsAt, account)

            Process_Account = .Save()
          End With
        End If
      End If

      ' Commit/ Rollback Transaction
      If Process_Account Then
        finBL.Database.TransactionCommit()
      Else
        finBL.Database.TransactionRollback()
      End If
    End If
  End If

End Function