<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2024-02-28T20:53:14.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2012-10-01T20:10:40.0000000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2024-02-28T20:48:30.5330000</UpdatedUtcDate>
    <ScriptId>AP.PAPROM</ScriptId>
    <Description>Process Payment Arrangement Promises</Description>
    <ScriptType>General</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' Script_AccountProcesses_PaymentArrangementPromises.xml
Option Explicit On
Option Strict On

' #################################################################
' Process Payment Arrangement Promise Transactions
' 
' Version: 2.07 (22/02/2024)
'
' Remarks
' -------
' Promise Due transactions will be flagged as Passed or Failed by comparing the actual overdue and the expected overdue
' Expected Overdue = Overdue at the time of the Arrangement less Promise Dues for the arrangement plus any extra Due Immediately transactions
' The FailedCount is the number of consecutive failed promises, If FailedCount &gt; BrokenCount then the promise is deemed to be broken
' Function Process_BrokenPromise contains extra processing for a broken promise
'          Process_FinalPass contains extra processing for the final promise with Pass
'          Process_FinalFail contains extra processing for the final promise with a Fail or Broken
'
' finPOWER Connect Configuration
' ------------------------------
' Script Type: General
' Options    : Show when running Account Processes
'              Run by Default
'
' Parameters - only applicable when script NOT running from Account Processes
' ----------
' DateAsAt = Processing Date
' Accounts = Range of Accounts to include
' 
' WARNING: Sample Script, please ensure this script fits your purposes before using.
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.00  02/07/2012  IS.JR              Created
'    1.01  15/08/2012  IS.JR              Updated calls to AccountTransactionFunctions.UpdatePromiseStatus to use "timestamp" parameter
'    1.02  28/08/2012  IS.JR              Incorrectly including Payments when adjusting expected Overdue
'    1.03  01/10/2012  IS.VH              Added SQL Join for Account Processes Client Type and Client Group Filters
'    1.04  04/12/2012  IS.VH    KB#10769  Account Range parameter wasn't working and Client join fixed.
'    2.00  22/08/2013  IS.JR    KB#11319  Better handling of scenarios where payment due on date of Arrangement.
'    2.01  08/10/2014  IS.JR    KB#12306  Updated to use AccountProcesses.LoanInterestAndFeeTransactionsProcess/ToDate properties.
'    2.02  06/03/2017  IS.JR    KB#14376  Updated to set Broken Promise Account Log's "Owner User" to Account's Manager.
'    2.03  18/05/2017  IS.JR    KB#14583  Issue with Grace Days causing unexpected failure.
'    2.04  30/05/2017  IS.JR    KB#14605  Added IncludeDefaultInterestFeesInOverdueAdjustment and IncludeManualTransactionsInOverdueAdjustment constants.
'    2.05  16/07/2021  IS.AM              Replaced obsoleted GetUnclearedFunds with GetUnclearedFunds2
'    2.06  21/09/2022  ISS      J029586   Fixed compilation warnings
'    2.07  22/02/2024  IS.LR              Handle PaymentRegularMissUntilDate 
'                                         Change to Uncleared funds calculation 
'                                         Make DateAsAt a module variable so can be used in any function
'                                         Test that a transaction has not been reversed when looking at OverdueAdjustments
' #################################################################

'#Const "GraceDays",Integer,2,"Promise will be checked once this many days have elapsed"
'#Const "BrokenCount",Integer,2,"Promise will be deemed Broken after this number of consecutive fails"
'#Const "BrokenPromiseLogSubject",String,"Broken Promise","Log subject used when creating a new Account Log when Promise broken, blank=do not add Log"
'#Const "FinalPassPromiseLogSubject",String,"Promised Completed (Pass)","Log subject used when creating a new Account Log when Promise is completed and passed, blank=do not add Log"
'#Const "IncludeDefaultInterestFeesInOverdueAdjustment",Boolean,False,"Include Default Interest/Fees in expected Overdue?"
'#Const "IncludeManualTransactionsInOverdueAdjustment",Boolean,False,"Include manual Transactions in expected Overdue?"

' Constants
Private BrokenCount As Integer = 2
Private BrokenPromiseLogSubject As String = "Broken Promise"
Private FinalPassPromiseLogSubject As String = "Promised Completed (Pass)"
Private GraceDays As Integer = 2
Private IncludeDefaultInterestFeesInOverdueAdjustment As Boolean = False
Private IncludeManualTransactionsInOverdueAdjustment As Boolean = False

' Module Variables
 Private mDateAsAt As Date

Public Function Main(ByVal parameters As ISKeyValueList) As Boolean

  Dim Account As finAccount
  Dim AccountId As String
  Dim AccountProcesses As finAccountProcesses
  Dim Accounts As String
  Dim dr As IDataReader
  Dim sqb As ISSelectQueryBuilder
  Dim TransactionAccountPayArrangePk As Integer
  Dim TransactionDate As Date
  Dim TransactionPk As Integer
  Dim TransactionPromiseValue As Decimal
  Dim TransactionTimestamp As Integer

  ' Assume Success
  Main = True

  ' Get Constants
  With ScriptInfo.Constants
    BrokenCount = .GetInteger("BrokenCount", BrokenCount)
    BrokenPromiseLogSubject = .GetString("BrokenPromiseLogSubject", BrokenPromiseLogSubject)
    FinalPassPromiseLogSubject = .GetString("FinalPassPromiseLogSubject", FinalPassPromiseLogSubject)
    GraceDays = .GetInteger("GraceDays", GraceDays)
    IncludeDefaultInterestFeesInOverdueAdjustment = .GetBoolean("IncludeDefaultInterestFeesInOverdueAdjustment", IncludeDefaultInterestFeesInOverdueAdjustment)
    IncludeManualTransactionsInOverdueAdjustment = .GetBoolean("IncludeManualTransactionsInOverdueAdjustment", IncludeManualTransactionsInOverdueAdjustment)
  End With

  ' 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
    mDateAsAt = AccountProcesses.LoanInterestAndFeeTransactionsProcessToDate.Date
  Else
    ' Run as a General Script
    Accounts = parameters.GetString("Accounts", "")
    mDateAsAt = parameters.GetDate("DateAsAt", finBL.TimeZoneFunctions.GetCurrentDatabaseDate).Date
  End If

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

  ' Main Query
  With sqb
    .Clear()
    .Table = "Account"
    .Joins.Add("AccountTransaction","Account.Pk","AccountTransaction.AccountPk",iseSelectQueryJoinType.Inner)
    .Fields.AddList("Account.AccountId")
    .Fields.AddList("AccountTransaction.Pk,AccountTransaction.Timestamp,AccountTransaction.Date,AccountTransaction.PromiseValue,AccountTransaction.AccountPayArrangePk")

    ' SQL Where
    With .SqlWhere
      ' Open Loans
      .AppendComparisonInteger("Account.Status", "=", CInt(isefinAccountStatus.Open))

      ' Filter to relevant Account Transactions
      .AppendComparisonNotNull("AccountTransaction.AccountPayArrangePK")
      .AppendComparisonInteger("AccountTransaction.PromiseStatus", "=", CInt(isefinTransactionPromiseStatus.Pending))
      .AppendComparisonDate("AccountTransaction.Date", "&lt;", mDateAsAt)

      If AccountProcesses Is Nothing Then
        ' User Filters
        .Append(finBL.CurrentUserInformation.FilterAccountSqlWhere)
        .AppendRange("Account.AccountId", Accounts, iseRangeDataType.String)
      Else
        ' Ranges and User Filters specified in Account Processes
        AccountProcesses.UpdateSqlWhereBuilder(sqb.SqlWhere)
      End If
    End With

    ' Joins for Ranges specified in Account Processes
    If AccountProcesses IsNot Nothing Then
      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
    End If

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

  ' Execute Query
  If sqb.ExecuteDisconnectedDataReader(dr, 0, ScriptInfo.TimeoutSeconds) Then
    With dr
      Do While .Read
        ' Get Query Fields
        AccountId = finBL.Database.GetFieldString(!AccountId)
        TransactionAccountPayArrangePk = finBL.Database.GetFieldInteger(!AccountPayArrangePk)
        TransactionDate = finBL.Database.GetFieldDate(!Date)
        TransactionPk = finBL.Database.GetFieldInteger(!Pk)
        TransactionPromiseValue = finBL.Database.GetFieldDecimal(!PromiseValue)
        TransactionTimestamp = finBL.Database.GetFieldInteger(!Timestamp)

        ' 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.Load(AccountId, True)
          Main = False
          Exit Do
        End If

        ' Check Grace Business Days
        If mDateAsAt &gt;= Account.Entity.CalendarBanking.GetFutureBusinessDay(TransactionDate, GraceDays) Then
          ' Process Account Transaction
          If Not Process_PromiseDue(Account, TransactionPk, TransactionTimestamp, TransactionAccountPayArrangePk, TransactionDate, TransactionPromiseValue) Then
            Main = False
            Exit Do
          End If
        End If
      Loop
    End With
    finBL.Database.DataReaderClose(dr)
  Else
    Main = False
  End If

  ' Final Progress
  If AccountProcesses IsNot Nothing Then
    If Main Then
      AccountProcesses.NotifyProgress(100, "")
    Else
      AccountProcesses.NotifyProgress(0, "  " &amp; finbl.Error.Message)
      AccountProcesses.Errors.Add("", "Script '" &amp; ScriptInfo.ScriptId &amp; "': " &amp; finbl.Error.Message(True, True))
    End If
  End If

End Function

'########################
' Process the Promise Due
'########################
Private Function Process_PromiseDue(ByVal account As finAccount, _
                                    ByVal accountTransactionPk As Integer, _
                                    ByVal accountTransactionTimestamp As Integer, _
                                    ByVal accountPayArrangePk As Integer, _
                                    ByVal promiseDate As Date, _
                                    ByVal promiseValue As Decimal) As Boolean

  Dim AccountPayArrangement As finAccountPayArrangement
  Dim AccountTransaction As finAccountTransaction
  Dim FailCount As Integer
  Dim OverdueActual As Decimal
  Dim OverdueAdjustment As Decimal
  Dim OverdueExpected As Decimal
  Dim PromiseGraceDate As Date
  Dim UnclearedFunds As Decimal

  ' Assume Success
  Process_PromiseDue = True

  With account
    ' Find date that Promise may be accepted until, ie apply the grace days
    PromiseGraceDate = account.Entity.CalendarBanking.GetFutureBusinessDay(promiseDate, GraceDays)

    ' Get overdue as at end of grace days
    Process_PromiseDue = .GetBalanceOverdue(OverdueActual, PromiseGraceDate)

    If Process_PromiseDue Then
      For Each AccountPayArrangement In account.PaymentArrangements
        With AccountPayArrangement
          If .Pk = AccountPayArrangePk Then
            ' Begin Transaction
            finBL.Database.TransactionBegin()

            ' Only process if the Arrangement is current
            If .IsCurrent Then
              ' OverdueExpected is the Overdue (and due today) at the time of the Payment Arrangement, less any Promises, plus any extra fees
              OverdueExpected = .BalanceOverdue + .BalanceOverdueToday

              ' Deduct this Promise
              OverdueExpected -= finBL.Database.GetFieldDecimal(promiseValue)

              ' Subtract other Promises and add any new Overdues
              For Each AccountTransaction In account.Transactions
                With AccountTransaction
                  ' Quit 
                  If .Date &gt; PromiseGraceDate Then Exit For
                    
                  ' Only process if not reversed
                  If .ReversePk = 0 AndAlso .NegativePaymentReversePk = 0 Then  
                    If .AccountPayArrangePk = accountPayArrangePk Then
                      If .Pk = AccountTransactionPk Then
                        ' This is the current Promise, so ignore
                      Else
                        ' Deduct previous Promises
                        If .Date &lt;= promiseDate Then
                          OverdueExpected -= .PromiseValue
                        End If
  
                        Select Case .PromiseStatus
                          Case isefinTransactionPromiseStatus.Fail, isefinTransactionPromiseStatus.Broken
                            ' Previous fail
                            FailCount += 1
                          Case Else
                            ' Previous pass (or cancel) - Reset counter
                            FailCount = 0
                        End Select
                      End If
                    Else
                      ' Expected Overdue Adjustments
                      If .Date &gt;= AccountPayArrangement.ArrangementDate AndAlso .ElementType &lt;&gt; isefinElementType.PaymentReceived Then
                        ' Adjust for Direct Debit
                        Select Case AccountTransaction.DirectDebitStatus
                          Case isefinTransactionDirectDebitStatus.Processed
                            ' If Direct Debit Processed we shouldn't adjust
                            OverdueAdjustment = .Overdue - .DirectDebitValue
                          Case Else
                            OverdueAdjustment = .Overdue
                        End Select
  
                        Select Case .ScheduleType
                          Case isefinAccountCalcScheduleType.DefaultInterest, isefinAccountCalcScheduleType.DefaultFee
                            ' Default Interest/ Fees
                            If IncludeDefaultInterestFeesInOverdueAdjustment Then
                              OverdueExpected += OverdueAdjustment
                            End If
  
                          Case isefinAccountCalcScheduleType.Transaction
                            ' Manual Transaction
                            If IncludeManualTransactionsInOverdueAdjustment Then
                              OverdueExpected += OverdueAdjustment
                            End If
                            
                          Case isefinAccountCalcScheduleType.PaymentDue
                            ' Expected Missed Regular Payments Due
                            If AccountPayArrangement.PaymentRegularMissUntilDate &lt;&gt; Nothing AndAlso .Date &lt;= AccountPayArrangement.PaymentRegularMissUntilDate Then
                              OverdueExpected += OverdueAdjustment
                            End If
                        End Select
                      End If
                    End If
                  End If
                End With
              Next
              
              ' Test if Overdue is higher than expected
              If OverdueActual &gt; OverdueExpected Then
                ' Failure
                FailCount += 1

                ' If Promise failed x times, set the overall Promise as broken and escalate
                If FailCount &gt;= BrokenCount Then
                  ' Break this Promise
                  Process_PromiseDue = finbl.AccountTransactionFunctions.UpdatePromiseStatus(accountTransactionPk, isefinTransactionPromiseStatus.Broken, accountTransactionTimestamp)

                  ' Extra Processing
                  If Process_PromiseDue Then
                    Process_PromiseDue = Process_BrokenPromise(Account, AccountPayArrangement, promiseDate)
                  End If
                Else
                  ' Fail this Promise
                  Process_PromiseDue = finbl.AccountTransactionFunctions.UpdatePromiseStatus(accountTransactionPk, isefinTransactionPromiseStatus.Fail, accountTransactionTimestamp)
                End If

                ' Additional processing on Fail of Last promise
                If Process_PromiseDue AndAlso Not .Payments.HasUnprocessedPromises Then
                  If FailCount &gt;= BrokenCount Then
                    Process_PromiseDue = Process_FinalFail(Account, AccountPayArrangement, promiseDate, "Broken")
                  Else
                    Process_PromiseDue = Process_FinalFail(Account, AccountPayArrangement, promiseDate, "Fail")
                  End If
                End If
              Else
                ' Promise was paid, but only set as 'Pass' if there are no applicable uncleared payments
                
                ' Find value of "still" uncleared funds from transactions that are dated on or before PromiseGraceDate and STILL uncleared as at DateAsAt
                UnclearedFunds = 0
                For Each AccountTransaction In account.Transactions
                  With AccountTransaction
                    ' Quit after Grace date
                    If .Date &gt; PromiseGraceDate Then Exit For
                      
                    ' Must not be reversed, Incoming and Negative
                    If .ReversePk = 0 AndAlso .NegativePaymentReversePk = 0 AndAlso .Value &lt; 0 Then
                      ' Check Uncleared Date against DateAsAt to see if the transaction is still uncleared
                      If .DateCleared &lt;&gt; Nothing AndAlso .DateCleared &gt; mDateAsAt Then
                        UnclearedFunds -= .Value
                      End If
                    End If
                  End With
                Next
                
                ' Recheck Overdue Actual against Overdue Expected taking into account Uncleared Funds
                If finBL.CurrencyRound(OverdueActual + UnclearedFunds) &lt;= OverdueExpected Then 
                  ' Pass this Promise
                  Process_PromiseDue = finbl.AccountTransactionFunctions.UpdatePromiseStatus(accountTransactionPk, isefinTransactionPromiseStatus.Pass, accountTransactionTimestamp)

                  ' Additional processing on Pass of Last promise
                  If Process_PromiseDue AndAlso Not .Payments.HasUnprocessedPromises Then
                    Process_PromiseDue = Process_FinalPass(Account, AccountPayArrangement, promiseDate)
                  End If
                End If
              End If
            Else
              ' Payment Arrangement has been replaced by another, flag the promise as "Cancelled"
              Process_PromiseDue = finbl.AccountTransactionFunctions.UpdatePromiseStatus(accountTransactionPk, isefinTransactionPromiseStatus.Cancelled, accountTransactionTimestamp)
            End If

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

            Exit For
          End If
        End With
      Next
    End If
  End With

End Function

'################################
' Extra Actions on Broken Promise
'################################
Private Function Process_BrokenPromise(ByVal account As finAccount, _
                                       ByVal accountPayArrangement As finAccountPayArrangement, _
                                       ByVal promiseDate As Date) As Boolean

  Dim AccountLog As finAccountLog
  Dim Workflow As finWorkflow

  ' Assume Success
  Process_BrokenPromise = True

  ' Update Workflow if Payment Arrangement linked to a Workflow
  If Process_BrokenPromise Then
    If accountPayArrangement.WorkflowPk &lt;&gt; 0 Then
      Workflow = finBL.CreateWorkflow()
      With Workflow
        ' Load Workflow
        Process_BrokenPromise = .LoadPk(accountPayArrangement.WorkflowPk)

        If Process_BrokenPromise Then
          If .Status = isefinWorkflowStatus.Closed Then
            ' Workflow is closed, no action possible
          Else
            ' Set for immediate Recall
            If Process_BrokenPromise AndAlso (Not .RecallImmediate) Then
              If finBL.WorkflowFunctions.WorkflowRecallImmediateSet(.Pk) Then
                ' Refresh Workflow to update values
                .Refresh
              Else
                Process_BrokenPromise = False
              End If
            End If

            ' If On Hold remove Hold
            If Process_BrokenPromise And .Status = isefinWorkflowStatus.OnHold Then
              If finBL.WorkflowFunctions.WorkflowStatusUnholdPk(.Pk) Then
                ' Refresh Workflow to update values
                .Refresh
              Else
                Process_BrokenPromise = False
              End If
            End If

            ' Black Flag
            If Process_BrokenPromise AndAlso .FlagColour &lt;&gt; "Black" Then
              .FlagColour = "Black"
              .FlagNotes = "Broken promise from payment arrangement dated " &amp; finBL.FormatDate(AccountPayArrangement.ArrangementDate, True)
              Process_BrokenPromise = .Save
            End If
          End If
        End If
      End With
    End If
  End If

  ' Add Log
  If Process_BrokenPromise Then
    If Len(BrokenPromiseLogSubject) &lt;&gt; 0 Then
      AccountLog = finBL.CreateAccountLog()
      With AccountLog
        .AccountId = account.AccountId
        .LogType = isefinLogType.NormalUser
        .Subject = BrokenPromiseLogSubject
        .LogDbDate = promiseDate
        .AccountDataSet(promiseDate, account)
        .Notes = "Broken promise from Payment Arrangement dated " &amp; finBL.FormatDate(AccountPayArrangement.ArrangementDate, True)
        .OwnerUserPk = account.AccountManagerUserPk

        ' Link the log to the workflow or set an action date so it will appear in the Task Manager
        If AccountPayArrangement.WorkflowPk &lt;&gt; 0 AndAlso Workflow.Status &lt;&gt; isefinWorkflowStatus.Closed Then
          .WorkflowId = Workflow.WorkflowId
        Else
          .ActionDate = promiseDate
        End If

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

End Function

'###########################################
' Extra Actions on Final Promise with a Pass
'###########################################
Private Function Process_FinalPass(ByVal account As finAccount, _
                                   ByVal accountPayArrangement As finAccountPayArrangement, _
                                   ByVal promiseDate As Date) As Boolean

  Dim AccountLog As finAccountLog
  Dim Workflow As finWorkflow

  ' Assume Success
  Process_FinalPass = True

  ' Update Workflow if Payment Arrangement linked to a Workflow
  If Process_FinalPass Then
    If accountPayArrangement.WorkflowPk &lt;&gt; 0 Then
      Workflow = finBL.CreateWorkflow()
      With Workflow
        ' Load Workflow
        Process_FinalPass = .LoadPk(accountPayArrangement.WorkflowPk)

        If Process_FinalPass Then
          If .Status = isefinWorkflowStatus.Closed Then
            ' Workflow is closed, no action possible
          Else
            ' Set for immediate Recall
            If Process_FinalPass AndAlso (Not .RecallImmediate) Then
              If finBL.WorkflowFunctions.WorkflowRecallImmediateSet(.Pk) Then
                ' Refresh Workflow to update values
                .Refresh
              Else
                Process_FinalPass = False
              End If
            End If

            ' If On Hold remove Hold
            If Process_FinalPass And .Status = isefinWorkflowStatus.OnHold Then
              If finBL.WorkflowFunctions.WorkflowStatusUnholdPk(.Pk) Then
                ' Refresh Workflow to update values
                .Refresh
              Else
                Process_FinalPass = False
              End If
            End If

            ' Green Flag
            If Process_FinalPass AndAlso .FlagColour &lt;&gt; "Green" Then
              .FlagColour = "Green"
              .FlagNotes = "Completed promise from payment arrangement dated " &amp; finBL.FormatDate(AccountPayArrangement.ArrangementDate, True)
              Process_FinalPass = .Save
            End If
          End If
        End If
      End With
    End If
  End If

  ' Add Log
  If Process_FinalPass Then
    If Len(FinalPassPromiseLogSubject) &lt;&gt; 0 Then
      AccountLog = finBL.CreateAccountLog()
      With AccountLog
        .AccountId = account.AccountId
        .LogType = isefinLogType.NormalUser
        .Subject = FinalPassPromiseLogSubject
        .LogDbDate = promiseDate
        .AccountDataSet(promiseDate, account)
        .Notes = "Completed promise from Payment Arrangement dated " &amp; finBL.FormatDate(AccountPayArrangement.ArrangementDate, True)

        ' Link the log to the workflow or set an action date so it will appear in the Task Manager
        If AccountPayArrangement.WorkflowPk &lt;&gt; 0 AndAlso Workflow.Status &lt;&gt; isefinWorkflowStatus.Closed Then
          .WorkflowId = Workflow.WorkflowId
        End If

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

End Function

'#####################################################
' Extra Actions on Final Promise with a Fail or Broken
'#####################################################
Private Function Process_FinalFail(ByVal account As finAccount, _
                                   ByVal accountPayArrangement As finAccountPayArrangement, _
                                   ByVal promiseDate As Date, _
                                   ByVal failType As String) As Boolean

  ' Assume Success
  Process_FinalFail = True

  If failType = "Fail" Then
    ' Treat a fail on the last promise the same as a Broken promise
    Process_FinalFail = Process_BrokenPromise(account, accountPayArrangement, promiseDate)
  End If

End Function</Code>
    <Language>VisualBasic</Language>
    <Notes>Normally run as part of Account Processes, but can be run from Processes menu. To do this change the show in menu Option setting to "Process" - Parameters are already defined for use.</Notes>
    <PermissionKeyExecute />
    <ReferenceLinq>false</ReferenceLinq>
    <RunWithoutPrompts>false</RunWithoutPrompts>
    <TemplateText />
    <TemplateTextBookmarks />
    <TimeoutSeconds>600</TimeoutSeconds>
    <UniqueId>Uk5QVXgKpUq6JS-bMGnKKg</UniqueId>
    <AllowSaveLoadParametersOnExecute>true</AllowSaveLoadParametersOnExecute>
    <ShowInAccountProcesses>true</ShowInAccountProcesses>
    <AccountProcessesRunByDefault>true</AccountProcessesRunByDefault>
    <RunAsAdministrator>false</RunAsAdministrator>
    <ShowInMenu>Process</ShowInMenu>
    <ShowInTaskManager>false</ShowInTaskManager>
    <WebServiceName />
    <ParametersType>Custom</ParametersType>
    <Parameters>
      <ISParameterDefs version="1.00">
        <Parameters>
          <Parameter name="DateAsAt" type="Date">
            <BlankTip />
            <Caption>Date As At</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression>Now()</DefaultValueExpression>
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</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="Accounts" type="Range">
            <BlankTip />
            <Caption>Accounts</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <Rows>1</Rows>
            <RangeSingle>false</RangeSingle>
            <RangeType>Standard</RangeType>
            <RangeLookupSource>Accounts</RangeLookupSource>
            <RangeLookupSqlWhere />
          </Parameter>
        </Parameters>
      </ISParameterDefs>
    </Parameters>
    <Constants>
      <ISScriptConstants version="1.00">
        <ScriptConstant name="GraceDays" constantType="Integer">
          <Notes>Promise will be checked once this many days have elapsed</Notes>
          <Value>2</Value>
        </ScriptConstant>
        <ScriptConstant name="BrokenCount" constantType="Integer">
          <Notes>Promise will be deemed Broken after this number of consecutive fails</Notes>
          <Value>2</Value>
        </ScriptConstant>
        <ScriptConstant name="BrokenPromiseLogSubject" constantType="String">
          <Notes>Log subject used when creating a new Account Log when Promise broken, blank=do not add Log</Notes>
          <Value>Broken Promise</Value>
          <Encrypt>false</Encrypt>
        </ScriptConstant>
        <ScriptConstant name="FinalPassPromiseLogSubject" constantType="String">
          <Notes>Log subject used when creating a new Account Log when Promise is completed and passed, blank=do not add Log</Notes>
          <Value>Promised Completed (Pass)</Value>
          <Encrypt>false</Encrypt>
        </ScriptConstant>
        <ScriptConstant name="IncludeDefaultInterestFeesInOverdueAdjustment" constantType="Boolean">
          <Notes>Include Default Interest/Fees in expected Overdue?</Notes>
          <Value>false</Value>
        </ScriptConstant>
        <ScriptConstant name="IncludeManualTransactionsInOverdueAdjustment" constantType="Boolean">
          <Notes>Include manual Transactions in expected Overdue?</Notes>
          <Value>false</Value>
        </ScriptConstant>
      </ISScriptConstants>
    </Constants>
  </finScript>