' SummaryPage2_AccountAutomaticClose_CloseSummary
Option Explicit On
Option Strict On

' #################################################################
' Automatic Close Summary

' Version: 2.00 (31/10/2017)

' Usage: Accounts Close wizard, Write-Offs and Refunds page.
' #################################################################

' Objects
Private mAccount As finAccount
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

  Dim AccountAutomaticClose As finAccountAutomaticClose

  ' Assume Success
  Main = True

  ' Initialise
  AccountAutomaticClose = DirectCast(source, finAccountAutomaticClose)
  mAccount = finbl.CreateAccount

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

  ' Load Objects
  If mIndex <> -1 Then
    mAccountAutomaticCloseItem = AccountAutomaticClose(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(mAccount, mAccountAutomaticCloseItem))
  sb.BlockEnd()

  ' End Column 1
  sb.ColumnEnd()

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

  ' Transactions
  sb.BlockBegin("Financial Summary")
  sb.SummaryTablesAppend(AccountsClose_FinancialSummary(mAccount, mAccountAutomaticCloseItem))
  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(account As finAccount,
                                       accountAutomaticCloseItem As finAccountAutomaticCloseItem) 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

    ' Term
    .AddRowCaptionText("Name:",account.Name,,iseSummaryTableCellClass.Highlight1)
    .AddRowCaptionText("Term:", account.Calculation.TermCycleDescription)
    .AddRowCaptionDate("Opening:", account.Calculation.OpeningDate)
    If account.Calculation.DateMaturity = Nothing Then
      Warnings &= "{{info|No Maturity date set.}}"
    Else
      .AddRowCaptionDate("Maturity:", account.Calculation.DateMaturity)
    End If

    ' Close Basis
    .Rows.AddSectionHeading2("Close Details")
    .AddRowCaptionText("Close Basis:", accountAutomaticCloseItem.CloseBasisText)
    Select Case accountAutomaticCloseItem.CloseBasis
      Case isefinAccountAutoCloseBasis.PendingClose
        .AddRowCaptionDate("Review on:", account.DateClosedPendingReview)
        .AddRowCaptionDate("Close on:", account.DateClosed)

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

      Case isefinAccountAutoCloseBasis.PostMaturityZeroBalance
        .AddRowCaptionDate("Close on:", accountAutomaticCloseItem.CloseDate)

        ' Warning
        Warnings &= "{{info|" & String.Format("Account will be closed on {0}, having a Zero Balance as at that date.", finBL.FormatDate(accountAutomaticCloseItem.CloseDate, True)) & "}}"

      Case Else
        .AddRowCaptionDate("Close on:", accountAutomaticCloseItem.CloseDate)

    End Select

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

  Return SummaryTables

End Function

Private Function AccountsClose_FinancialSummary(account As finAccount,
                                                accountAutomaticCloseItem As finAccountAutomaticCloseItem) 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 account.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 Account.Calculation.OptionInterestChargeUpfront Then
                If AccountSummaryItem.ElementPk = Account.AccountType.InterestCreditElementPk OrElse AccountSummaryItem.ElementPk = Account.AccountType.InterestDebitElementPk Then
                  .AddText(String.Format("{0} precomputed to {1}", AccountSummaryItem.Description, finBL.FormatDateLong(Account.DateMaturity.AddDays(-1))))
                ElseIf AccountSummaryItem.ElementPk = Account.AccountType.DefaultInterestElementPk Then
                  .AddText(String.Format("{0} charged to {1}", AccountSummaryItem.Description, finBL.FormatDateLong(Account.Calculation.InterestChargedTo)))
                Else
                  .AddText(AccountSummaryItem.Description)
                End If
              Else
                If AccountSummaryItem.ElementPk = Account.AccountType.InterestCreditElementPk OrElse AccountSummaryItem.ElementPk = Account.AccountType.InterestDebitElementPk Then
                  .AddText(String.Format("{0} charged to {1}", AccountSummaryItem.Description, finBL.FormatDateLong(Account.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 accountAutomaticCloseItem.CloseBasis <> isefinAccountAutoCloseBasis.PendingClose
        ' Balance plus Accruals to Net Balance
        AccruedToDate = finBL.FormatDateLong(accountAutomaticCloseItem.closeDate.AddDays(-1))

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

        If accountAutomaticCloseItem.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(accountAutomaticCloseItem.AccruedDefaultInterest)
          End With
        End If
        If accountAutomaticCloseItem.AccruedOtherInterest <> 0 Then
          With.Add.Cells
            .AddText("Accrued Other Interest")
            .AddCurrency(accountAutomaticCloseItem.AccruedOtherInterest)
          End With
        End If
        If accountAutomaticCloseItem.UnpostedDefaultFees <> 0 Then
          With.Add.Cells
            .AddText("Default Fees not yet posted")
            .AddCurrency(accountAutomaticCloseItem.UnpostedDefaultFees)
          End With
        End If
        If accountAutomaticCloseItem.UnpostedOverLimitFees <> 0 Then
          With.Add.Cells
            .AddText("Over Limit Fees not yet posted")
            .AddCurrency(accountAutomaticCloseItem.UnpostedOverLimitFees)
          End With
        End If
        If accountAutomaticCloseItem.UnpostedFacilityFees <> 0 Then
          With.Add.Cells
            .AddText("Facility Fees not yet posted")
            .AddCurrency(accountAutomaticCloseItem.UnpostedFacilityFees)
          End With
        End If
        If accountAutomaticCloseItem.UnpostedStandardTransactions <> 0 Then
          With.Add.Cells
            .AddText("Transactions not yet posted")
            .AddCurrency(accountAutomaticCloseItem.UnpostedStandardTransactions)
          End With
        End If

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

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

  Return SummaryTables

End Function