' SummaryPage2_AccountAutomaticClose_CloseSummary
Option Explicit On
Option Strict On

' #################################################################
' Automatic Close Summary
' 
' Version: 2.01 (01/05/2024)
' 
' Usage: Accounts Close wizard, Write-Offs and Refunds page.
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    2.00  31/10/2017  ISS
'    2.01  01/05/2024  ISS      J029975   Add Zero Balance Deposits
' #################################################################

' Objects
Private mAccount As finAccount
Private mAccountAutomaticClose As finAccountAutomaticClose
Private mAccountAutomaticCloseItem As finAccountAutomaticCloseItem

' Other
Private mIndex As Integer

' Main
Public Function Main(source As Object,
                     eventId As String,
                     eventArgs As ISKeyValueList,
                     ByRef handled As Boolean,
                     ByRef returnValues As ISKeyValueList,
                     ByRef text As String) As Boolean

  ' Assume Success
  Main = True

  ' Initialise
  mAccountAutomaticClose = DirectCast(source, finAccountAutomaticClose)
  mAccount = finBL.CreateAccount

  ' Get Event Args
  mIndex = eventArgs.GetInteger("Index")

  ' Load Objects
  If mIndex <> -1 Then
    mAccountAutomaticCloseItem = mAccountAutomaticClose(mIndex)
    mAccount.LoadPk(mAccountAutomaticCloseItem.AccountPk)
  End If

  ' Handle Events
  Select Case eventId
    Case ""
      ' Main event, i.e., return main page content
      Main = CreatePage(text)
  End Select

End Function

Private Function CreatePage(ByRef html As String) As Boolean

  Dim Success As Boolean
  Dim sb As finHtmlSummaryPage2StringBuilder

  ' Assume Success
  Success = True

  ' Initialise
  sb = finBL.CreateHtmlSummaryPage2StringBuilder()

  ' Initialise HTML
  With sb
    .Initialise(ScriptInfo)
    .HtmlHeaderBegin("", isefinSummaryPageStyle.Blocks)
    .HtmlHeaderEnd()
  End With

  ' Begin Section
  sb.SectionColumnsBegin()

  ' Begin Column 1
  sb.ColumnBegin("50%")

  ' Summary
  sb.BlockBegin("Summary", "", isefinSummaryPageBlockHeadingStyle.Main, False)
  sb.SummaryTablesAppend(AccountsClose_Summary())
  sb.BlockEnd()

  ' End Column 1
  sb.ColumnEnd()

  ' Begin Column 2
  sb.ColumnBegin("50%", "25em", "70em")

  ' Transactions
  sb.BlockBegin("Financial Summary")
  sb.SummaryTablesAppend(AccountsClose_FinancialSummary())
  sb.BlockEnd()

  ' End Column 2
  sb.ColumnEnd()

  ' Finalise HTML
  sb.HtmlFinalise()

  ' Resolve Templates
  html = sb.ToString(True)

  Return Success

End Function

Private Function AccountsClose_Summary() As ISSummaryTables

  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim Warnings As String

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  ' Main
  SummaryTable = SummaryTables.CreateSummaryTableInformation("","Summary")
  With SummaryTable
    ' Account
    With .Rows
      With .AddCaptionText("Code:", mAccount.AccountId)
        .Cells(1).HyperlinkSetFormShow("Accounts", mAccount.AccountId)
      End With
      .AddCaptionText("Name:", mAccount.Name, iseSummaryTableCellClass.Highlight1)
      .AddCaptionCodeDescription("Type:", mAccount.AccountTypePk, finBL.AccountTypes)
      .AddCaptionDate("Opening:", mAccount.Calculation.OpeningDate)
      .AddCaptionText("Term:", mAccount.Calculation.TermCycleDescription)
      If mAccount.IsFixedTerm Then
        If mAccount.DateMaturity = Nothing Then
          Warnings &= "{{info|No Maturity date set.}}"
        Else
          .AddCaptionDate("Maturity:", mAccount.DateMaturity)
        End If
      End If  
    End With  

    ' Close Basis
    .Rows.AddSectionHeading2("Close Details")
    .AddRowCaptionText("Close Basis:", mAccountAutomaticCloseItem.CloseBasisText)
    Select Case mAccountAutomaticCloseItem.CloseBasis
      Case isefinAccountAutoCloseBasis.ChargeandWriteOff  
        .AddRowCaptionDate("Close On:", mAccountAutomaticCloseItem.CloseDate)
        
      Case isefinAccountAutoCloseBasis.DepositZeroBalance
        .AddRowCaptionDate("Close On:", mAccountAutomaticCloseItem.CloseDate)
        .AddRowCaptionText("Close Note:", mAccountAutomaticClose.DebitAccountCloseNote)

      Case isefinAccountAutoCloseBasis.PendingClose
        .AddRowCaptionDate("Review On:", mAccount.DateClosedPendingReview)
        .AddRowCaptionDate("Close On:", mAccount.DateClosed)

        ' Warning
        Warnings &= "{{info|Account is Closed pending finalisation.}}"

      Case isefinAccountAutoCloseBasis.PostMaturityZeroBalance
        .AddRowCaptionDate("Close On:", mAccountAutomaticCloseItem.CloseDate)

        ' Warning
        Warnings &= "{{info|" & String.Format("Account will be closed on {0}, having a Zero Balance as at that date.", finBL.FormatDate(mAccountAutomaticCloseItem.CloseDate, True)) & "}}"
        
      Case Else
        .AddRowCaptionDate("Close On:", mAccountAutomaticCloseItem.CloseDate)
    End Select

    ' Warnings
    If mAccountAutomaticCloseItem.Processed Then
      Warnings &= "{{info|Already processed.}}"
    ElseIf Len(mAccountAutomaticCloseItem.InvalidMessageResolved) <> 0 Then
      Warnings &= "{{warning|" & finBL.HtmlEncode(mAccountAutomaticCloseItem.InvalidMessageResolved) & "}}"
    End If
    .TextAfter = Warnings
  End With
  SummaryTables.Add("Summary", SummaryTable)

  Return SummaryTables

End Function

Private Function AccountsClose_FinancialSummary() As ISSummaryTables

  Dim AccountSummaryItem As finAccountSummaryItem
  Dim AccruedToDate As String
  Dim RowClass As iseSummaryTableRowClass
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Initialise
  RowClass = iseSummaryTableRowClass.Normal
  SummaryTables = finBL.CreateSummaryTables()

  ' Main
  SummaryTable = SummaryTables.CreateSummaryTableTabular("","FinancialSummary")
  With SummaryTable
    .WidthHtml = "100%"
    .AutoStripe = False

    ' Columns
    With .Columns
      .AddText()
      .AddCurrency(20)
    End With

    ' Rows
    With .Rows
      For Each AccountSummaryItem In mAccount.Summary
        ' Row Class
        If AccountSummaryItem.IsTotalItem Then
          RowClass = iseSummaryTableRowClass.FooterBold
        ElseIf AccountSummaryItem.GroupValue Then
          RowClass = iseSummaryTableRowClass.Alt2
        Else
          RowClass = iseSummaryTableRowClass.Normal
        End If

        With .Add(RowClass).Cells
          If AccountSummaryItem.IsTotalItem Then
            .AddText(AccountSummaryItem.Description)
            .AddCurrency(AccountSummaryItem.Balance, True)
          Else
            If AccountSummaryItem.ElementType = isefinElementType.Interest Then
              If mAccount.Calculation.OptionInterestChargeUpfront Then
                If AccountSummaryItem.ElementPk = mAccount.AccountType.InterestCreditElementPk OrElse AccountSummaryItem.ElementPk = mAccount.AccountType.InterestDebitElementPk Then
                  .AddText(String.Format("{0} precomputed to {1}", AccountSummaryItem.Description, finBL.FormatDateLong(mAccount.DateMaturity.AddDays(-1))))
                ElseIf AccountSummaryItem.ElementPk = mAccount.AccountType.DefaultInterestElementPk Then
                  .AddText(String.Format("{0} charged to {1}", AccountSummaryItem.Description, finBL.FormatDateLong(mAccount.Calculation.InterestChargedTo)))
                Else
                  .AddText(AccountSummaryItem.Description)
                End If
              Else
                If AccountSummaryItem.ElementPk = mAccount.AccountType.InterestCreditElementPk OrElse AccountSummaryItem.ElementPk = mAccount.AccountType.InterestDebitElementPk Then
                  .AddText(String.Format("{0} charged to {1}", AccountSummaryItem.Description, finBL.FormatDateLong(mAccount.Calculation.InterestChargedTo)))
                Else
                  .AddText(AccountSummaryItem.Description)
                End If
              End If
            Else
              .AddText(String.Format("{0}", AccountSummaryItem.Description))
            End If
            .AddCurrency(AccountSummaryItem.Value)
          End If
        End With
      Next

      If mAccountAutomaticCloseItem.CloseBasis <> isefinAccountAutoCloseBasis.PendingClose
        ' Balance plus Accruals to Net Balance
        AccruedToDate = finBL.FormatDateLong(mAccountAutomaticCloseItem.closeDate.AddDays(-1))

        With.Add.Cells
          If mAccount.Calculation.OptionInterestChargeUpfront AndAlso mAccountAutomaticCloseItem.closeDate.Date <= mAccount.DateMaturity Then
            ' Ignore
          Else
            If mAccount.SuspendInterest Then
              .AddText("Interest Suspended")
            Else
              .AddText(String.Format("Accrued Interest to {0}", AccruedToDate))
            End If
            .AddCurrency(mAccountAutomaticCloseItem.AccruedInterest)
            AccruedToDate = ""
          End If
        End With

        If mAccountAutomaticCloseItem.AccruedDefaultInterest <> 0 Then
          With.Add.Cells
            If Len(AccruedToDate) = 0 Then
              .AddText("Accrued Default Interest")
            Else
              .AddText(String.Format("Accrued Default Interest to {0}", AccruedToDate))
              AccruedToDate = ""
            End If
            .AddCurrency(mAccountAutomaticCloseItem.AccruedDefaultInterest)
          End With
        End If
        If mAccountAutomaticCloseItem.AccruedOtherInterest <> 0 Then
          With.Add.Cells
            .AddText("Accrued Other Interest")
            .AddCurrency(mAccountAutomaticCloseItem.AccruedOtherInterest)
          End With
        End If
        If mAccountAutomaticCloseItem.UnpostedDefaultFees <> 0 Then
          With.Add.Cells
            .AddText("Default Fees not yet posted")
            .AddCurrency(mAccountAutomaticCloseItem.UnpostedDefaultFees)
          End With
        End If
        If mAccountAutomaticCloseItem.UnpostedOverLimitFees <> 0 Then
          With.Add.Cells
            .AddText("Over Limit Fees not yet posted")
            .AddCurrency(mAccountAutomaticCloseItem.UnpostedOverLimitFees)
          End With
        End If
        If mAccountAutomaticCloseItem.UnpostedFacilityFees <> 0 Then
          With.Add.Cells
            .AddText("Facility Fees not yet posted")
            .AddCurrency(mAccountAutomaticCloseItem.UnpostedFacilityFees)
          End With
        End If
        If mAccountAutomaticCloseItem.UnpostedStandardTransactions <> 0 Then
          With.Add.Cells
            .AddText("Transactions not yet posted")
            .AddCurrency(mAccountAutomaticCloseItem.UnpostedStandardTransactions)
          End With
        End If

        ' Net Balance
        With.Add(iseSummaryTableRowClass.FooterBold).Cells
          .AddText("Net Balance")
          .AddCurrency(mAccountAutomaticCloseItem.BalanceNet, True)
        End With

        ' Net Balance plus Loss, Credits and Fees to Balance Due
        If mAccountAutomaticCloseItem.FeeValue <> 0 Then
          With.Add.Cells
            .AddText("Close Fee")
            .AddCurrency(mAccountAutomaticCloseItem.FeeValue)
          End With
        End If
        If mAccountAutomaticCloseItem.TotalCredits <> 0 Then
          With.Add.Cells
            .AddText("Total Credits")
            .AddCurrency(mAccountAutomaticCloseItem.TotalCredits)
          End With
        End If
        If mAccountAutomaticCloseItem.LossValue <> 0 Then
          With.Add.Cells
            .AddText("Loss")
            .AddCurrency(mAccountAutomaticCloseItem.LossValue)
          End With
        End If
        If mAccountAutomaticCloseItem.Other1Value <> 0 Then
          With.Add.Cells
            .AddText("Other")
            .AddCurrency(mAccountAutomaticCloseItem.Other1Value)
          End With
        End If
        If mAccountAutomaticCloseItem.Other2Value <> 0 Then
          With.Add.Cells
            .AddText("Other")
            .AddCurrency(mAccountAutomaticCloseItem.Other2Value)
          End With
        End If
        If mAccountAutomaticCloseItem.ResidualValue <> 0 Then
          With.Add.Cells
            .AddText("Less Residual Value")
            .AddCurrency(mAccountAutomaticCloseItem.ResidualValue)
          End With
        End If
        If mAccountAutomaticCloseItem.BalanceNet <> mAccountAutomaticCloseItem.BalanceDue Then
          With.Add(iseSummaryTableRowClass.FooterBold).Cells
            .AddText("Balance Due")
            .AddCurrency(mAccountAutomaticCloseItem.BalanceDue, True)
          End With
        End If
      End If
    End With
  End With
  SummaryTables.Add("FinancialSummary", SummaryTable)

  Return SummaryTables

End Function