' SummaryPage2_BankingInterfaceSummary_Ezidebit
Option Explicit On
Option Strict On

' #################################################################
' Ezidebit Banking Interface Summary Page Script
'
' Version: 1.00 (22/05/2024)
'
' Usage: Various forms
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.00  22/05/2024  ISS      J025068   Created
' #################################################################

' Constants

' Special Constants
Const TestMode As Boolean = False

' Properties
Private ServiceLogs As ISServiceLogs

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 Response As ISBankInterfaceResponse

  ' Assume Success
  Main = True

  ' Get Constants
  With ScriptInfo.Constants
  End With

  ' Get Service Logs
  Try
    Main = finBL.BankingInterface.GetServiceLogs(CInt(source), ServiceLogs)
  Catch ex As Exception
    Main = False
    finBL.Error.ErrorBeginFromException(ex)
  End Try
  If Main Then
    If ServiceLogs.Count = 0 Then
      Main = False
      finBL.Error.ErrorBegin("Invalid Service Log for the Banking Interface.")
    ElseIf ServiceLogs(0).RequestStatus <> iseAuditLogStatus.Success Then
      Main = False
      finBL.Error.ErrorBegin("Invalid Service Log. Initial Request was not successful.")
    Else
      Response = DirectCast(ServiceLogs(0).ExResponse, ISBankInterfaceResponse)
    End If
  End If

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

End Function

Private Function CreatePage(response As ISBankInterfaceResponse,
                            ByRef html As String) As Boolean

  Dim HtmlSummaryPage2StringBuilder As finHtmlSummaryPage2StringBuilder
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise ByRef
  html = ""

  ' Initialise
  HtmlSummaryPage2StringBuilder = finBL.CreateHtmlSummaryPage2StringBuilder()

  ' Initialise HTML
  With HtmlSummaryPage2StringBuilder
    ' Display test watermark
    If serviceLogs(0).TestMode Then .Watermark = "Test Mode"

    ' Note: Embed images (will also embed CSS) since we want to be able to easily produce a PDF document
    .Initialise(ScriptInfo, False, True)

    ' Begin HTML Header
    .HtmlHeaderBegin(String.Format("{0} {1}", response.ServiceName, response.ProductId), isefinSummaryPageStyle.ServiceReport)

    ' Theme
    .HtmlHeaderInsertServiceReportTheme("#6BB245", "#F0F0F0", "", "#F2F2F2")

    ' Intersoft PDF Options (including style tweaks)
    .HtmlHeaderInsertPdfGenerationHints("A4", "Portrait", 880, "1.5cm", "1.5cm", "1cm", "1cm", "font-size:0.9em")

    ' Finalise HTML Header
    .HtmlHeaderEnd()
  End With

  ' Body
  Select Case response.GetType()
    Case GetType(ISBankInterfaceResponse_Ezidebit_AddCustomer)
      Me.CreatePage_AddCustomer(DirectCast(response, ISBankInterfaceResponse_Ezidebit_AddCustomer), HtmlSummaryPage2StringBuilder)
    Case GetType(ISBankInterfaceResponse_Ezidebit_AddPayment)
      Me.CreatePage_AddPayment(DirectCast(response, ISBankInterfaceResponse_Ezidebit_AddPayment), HtmlSummaryPage2StringBuilder)
    Case GetType(ISBankInterfaceResponse_Ezidebit_GetCustomers)
      Me.CreatePage_GetCustomers(DirectCast(response, ISBankInterfaceResponse_Ezidebit_GetCustomers), HtmlSummaryPage2StringBuilder)
    Case GetType(ISBankInterfaceResponse_Ezidebit_UpdateCustomerBankAccount)
      Me.CreatePage_UpdateCustomerBankAccount(DirectCast(response, ISBankInterfaceResponse_Ezidebit_UpdateCustomerBankAccount), HtmlSummaryPage2StringBuilder)
    Case GetType(ISBankInterfaceResponse_Ezidebit_UpdateCustomerCreditCard)
      Me.CreatePage_UpdateCustomerCreditCard(DirectCast(response, ISBankInterfaceResponse_Ezidebit_UpdateCustomerCreditCard), HtmlSummaryPage2StringBuilder)
    Case Else
      Success = False
      finBL.Error.ErrorBeginFormat("Unexpected Response Type '{0}'.", TypeName(response))
  End Select

  ' Disclaimer
  HtmlSummaryPage2StringBuilder.AppendLine("<hr>")
  HtmlSummaryPage2StringBuilder.AppendLine("{{disclaimer|finPOWER Connect version " & finBL.VersionMajorMinorBuild & " using " & response.ServiceName & " service.}}")

  ' Finalise HTML
  HtmlSummaryPage2StringBuilder.HtmlFinalise()

  ' Resolve Templates
  html = HtmlSummaryPage2StringBuilder.ToString(True)

  Return Success

End Function

Private Sub CreatePage_AddCustomer(response As ISBankInterfaceResponse_Ezidebit_AddCustomer,
                                   htmlSummaryPage2StringBuilder As finHtmlSummaryPage2StringBuilder)

  Dim ServiceLogSourceObjects As finServiceLogSourceObjects

  ' Get Requested Account or Client from Service Log
  ServiceLogSourceObjects = finBL.CreateServiceLogSourceObjects()
  ServiceLogSourceObjects.Load(ServiceLogs(0))

  With HtmlSummaryPage2StringBuilder
    .AppendH1(String.Format("Add Customer '{0}'", response.Request_AddCustomer.Name))
    .AppendH2(String.Format("{0} - {1}", response.ProductId, response.ServiceName))

    .SummaryTablesAppend(Me.Ezidebit_AddCustomer_Details(response, ServiceLogSourceObjects))
 End With

End Sub

Private Sub CreatePage_AddPayment(response As ISBankInterfaceResponse_Ezidebit_AddPayment,
                                  htmlSummaryPage2StringBuilder As finHtmlSummaryPage2StringBuilder)

  Dim BankTransactionView As finBankTransactionView

  ' Load Bank Transaction
  If serviceLogs(0).SourceType = "BankTransaction" Then
    BankTransactionView = finBL.CreateBankTransactionView
    If Not BankTransactionView.LoadFromBankTransactionPk(serviceLogs(0).SourcePk) Then
      BankTransactionView = Nothing
    End If
  End If

  With HtmlSummaryPage2StringBuilder
    If BankTransactionView Is Nothing Then
      .AppendH1(String.Format("Payment '{0}'", response.Request_AddPayment.PaymentReference))
    Else
      .AppendH1(String.Format("Payment for Account {0}, {1}", BankTransactionView.AccountTransactions(0).AccountId, BankTransactionView.AccountTransactions(0).AccountName))
    End If
    .AppendH2(String.Format("{0} - {1}", response.ProductId, response.ServiceName))

    .SummaryTablesAppend(Me.Ezidebit_AddPayment_Details(response, BankTransactionView))
    .SummaryTablesAppend(Me.Ezidebit_History())
 End With

End Sub

Private Sub CreatePage_GetCustomers(response As ISBankInterfaceResponse_Ezidebit_GetCustomers,
                                    htmlSummaryPage2StringBuilder As finHtmlSummaryPage2StringBuilder)

  Dim ServiceLogSourceObjects As finServiceLogSourceObjects

  ' Get Requested Account or Client from Service Log
  ServiceLogSourceObjects = finBL.CreateServiceLogSourceObjects()
  ServiceLogSourceObjects.Load(ServiceLogs(0))

  With HtmlSummaryPage2StringBuilder
    Select Case response.Customers.Count
      Case 0
       .AppendH1("Customer not found")
      Case 1
       .AppendH1(response.Customers(0).Name)
      Case 2
       .AppendH1(String.Format("{0} plus 1 other", response.Customers(0).Name))
      Case Else
       .AppendH1(String.Format("{0} plus {1} others", response.Customers(0).Name, response.Customers.Count - 1))
    End Select
    .AppendH2(String.Format("{0} - {1}", response.ProductId, response.ServiceName))

    .SummaryTablesAppend(Me.Ezidebit_GetCustomers_Request(response, ServiceLogSourceObjects))
    .SummaryTablesAppend(Me.Ezidebit_GetCustomers_List(response, ServiceLogSourceObjects))
 End With

End Sub

Private Sub CreatePage_UpdateCustomerBankAccount(response As ISBankInterfaceResponse_Ezidebit_UpdateCustomerBankAccount,
                                                 htmlSummaryPage2StringBuilder As finHtmlSummaryPage2StringBuilder)

  Dim ServiceLogSourceObjects As finServiceLogSourceObjects

  ' Get Requested Account or Client from Service Log
  ServiceLogSourceObjects = finBL.CreateServiceLogSourceObjects()
  ServiceLogSourceObjects.Load(ServiceLogs(0))

  With HtmlSummaryPage2StringBuilder
    .AppendH1(String.Format("Update Customer '{0}' Bank Account", response.Request_UpdateCustomerBankAccount.EzidebitCustomerId))
    .AppendH2(String.Format("{0} - {1}", response.ProductId, response.ServiceName))

    .SummaryTablesAppend(Me.Ezidebit_UpdateCustomerBankAccount_Request(response, ServiceLogSourceObjects))
    .SummaryTablesAppend(Me.Ezidebit_UpdateCustomerBankAccount_BankAccount(Response))
  End With

End Sub

Private Sub CreatePage_UpdateCustomerCreditCard(response As ISBankInterfaceResponse_Ezidebit_UpdateCustomerCreditCard,
                                                htmlSummaryPage2StringBuilder As finHtmlSummaryPage2StringBuilder)

  Dim ServiceLogSourceObjects As finServiceLogSourceObjects

  ' Get Requested Account or Client from Service Log
  ServiceLogSourceObjects = finBL.CreateServiceLogSourceObjects()
  ServiceLogSourceObjects.Load(ServiceLogs(0))

  With HtmlSummaryPage2StringBuilder
    .AppendH1(String.Format("Update Customer '{0}' Credit Card", response.Request_UpdateCustomerCreditCard.EzidebitCustomerId))
    .AppendH2(String.Format("{0} - {1}", response.ProductId, response.ServiceName))

    .SummaryTablesAppend(Me.Ezidebit_UpdateCustomerCreditCard_Request(response, ServiceLogSourceObjects))
    .SummaryTablesAppend(Me.Ezidebit_UpdateCustomerCreditCard_CreditCard(response))
 End With

End Sub

Private Function Ezidebit_AddCustomer_Details(response As ISBankInterfaceResponse_Ezidebit_AddCustomer,
                                              serviceLogSourceObjects As finServiceLogSourceObjects) As ISSummaryTables

  Dim BankAccount As finBankAccountRO
  Dim ResponseUpdateCustomerBankAccount As ISBankInterfaceResponse_Ezidebit_UpdateCustomerBankAccount
  Dim ResponseUpdateCustomerCreditCard As ISBankInterfaceResponse_Ezidebit_UpdateCustomerCreditCard
  Dim ServiceLog As ISServiceLog
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  ' Get Bank Account
  If finBL.BankAccounts.ExistsPk(response.Request_AddCustomer.BankAccountPk) Then
    BankAccount = finBL.BankAccounts.ItemByPk(response.Request_AddCustomer.BankAccountPk)
  Else
    BankAccount = Nothing
  End If

  ' Fins Update Bank Account/ Credit Card details
  For Each ServiceLog In ServiceLogs
    Select Case ServiceLog.ExResponse.GetType()
      Case GetType(ISBankInterfaceResponse_Ezidebit_UpdateCustomerBankAccount)
        ResponseUpdateCustomerBankAccount = DirectCast(ServiceLog.ExResponse, ISBankInterfaceResponse_Ezidebit_UpdateCustomerBankAccount)
      Case GetType(ISBankInterfaceResponse_Ezidebit_UpdateCustomerCreditCard)
        ResponseUpdateCustomerCreditCard = DirectCast(ServiceLog.ExResponse, ISBankInterfaceResponse_Ezidebit_UpdateCustomerCreditCard)
    End Select
  Next

  SummaryTable = SummaryTables.CreateSummaryTableInformation("", "Request", 2, , , TestMode)
  With SummaryTable
    .AddRowCaptionUtcDateTimeWithTimeZone("Date:", response.RequestUtcDate, finBL.Settings.TimeZoneId)
    If BankAccount IsNot Nothing Then .AddRowCaptionCodeDescription("Bank Account:", BankAccount.Pk, finBL.BankAccounts, False)
    If serviceLogSourceObjects.Account IsNot Nothing Then
      With .Rows.AddCaptionCodeDescription("Account:", serviceLogSourceObjects.Account.AccountId, serviceLogSourceObjects.Account.Name)
        .Cells(1).HyperlinkSetFormShow("Accounts", serviceLogSourceObjects.Account.AccountId, "Payments")
      End With
    ElseIf serviceLogSourceObjects.Client IsNot Nothing Then
      With .Rows.AddCaptionCodeDescription("Client:", serviceLogSourceObjects.Client.ClientId, serviceLogSourceObjects.Client.Name)
        .Cells(1).HyperlinkSetFormShow("Clients", serviceLogSourceObjects.Client.ClientId, "Tax & Banking")
      End With
    End If
    If Len(response.Request_AddCustomer.BusinessName) = 0 Then
      .AddRowCaptionText("First Name:", response.Request_AddCustomer.FirstName)
      .AddRowCaptionText("Last Name:", response.Request_AddCustomer.LastName)
    Else
      .AddRowCaptionText("Business Name:", response.Request_AddCustomer.BusinessName)
    End If
    .AddRowCaptionText("Email:", response.Request_AddCustomer.EmailAddress, False)
    .AddRowCaptionText("Mobile:", response.Request_AddCustomer.MobilePhoneNumber, False)
    .AddRowCaptionDate("Started:", response.Request_AddCustomer.ContractStartDate)
  End With
  SummaryTables.Add("Request", SummaryTable)

  ' Bank Account/ Credit Card details
  If ResponseUpdateCustomerBankAccount IsNot Nothing Then
    SummaryTables.AppendSummaryTables(Me.Ezidebit_UpdateCustomerBankAccount_BankAccount(ResponseUpdateCustomerBankAccount))
  End If
  If ResponseUpdateCustomerCreditCard IsNot Nothing Then
    SummaryTables.AppendSummaryTables(Me.Ezidebit_UpdateCustomerCreditCard_CreditCard(ResponseUpdateCustomerCreditCard))
  End If

  ' Ezidebit Customer
  SummaryTable = SummaryTables.CreateSummaryTableInformation("Ezidebit Customer", "Customer", 2, , , TestMode)
  With SummaryTable
    .AddRowCaptionText("Customer ID:", response.EzidebitCustomerId)
  End With
  SummaryTables.Add("Customer", SummaryTable)

  Return SummaryTables

End Function

Private Function Ezidebit_AddPayment_Details(response As ISBankInterfaceResponse_Ezidebit_AddPayment,
                                             bankTransactionView As finBankTransactionView) As ISSummaryTables

  Dim ResponsePaymentDetail As ISBankInterfaceResponse_Ezidebit_GetPaymentDetail
  Dim ServiceLog As ISServiceLog
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  ' Find Payment Detail
  For Each ServiceLog In serviceLogs
    If ServiceLog.RequestStatus = iseAuditLogStatus.Success Then
      Select Case TypeName(ServiceLog.ExResponse)
        Case "ISBankInterfaceResponse_Ezidebit_GetPaymentDetail"
          ResponsePaymentDetail = DirectCast(ServiceLog.ExResponse, ISBankInterfaceResponse_Ezidebit_GetPaymentDetail)
      End Select
    End If
  Next

  ' Request
  SummaryTable = SummaryTables.CreateSummaryTableInformation("Request", "Details", 3, , , TestMode)
  With SummaryTable
    .AddRowCaptionCodeDescription("Bank Account:", response.Request_AddPayment.BankAccountPk, finBL.BankAccounts, False)
    If BankTransactionView IsNot Nothing Then
      With .Rows.AddCaptionInteger("Bank Transaction:", bankTransactionView.BankTransactionPk)
        .Cells(1).HyperlinkSetFormShow("BankTransactionView", CStr(bankTransactionView.BankTransactionPk))
      End With
      .Rows.AddCaptionCodeDescriptionWithFormShow("Account:", bankTransactionView.AccountTransactions(0).AccountId, bankTransactionView.AccountTransactions(0).AccountName, "Accounts")
    End If
    .AddRowCaptionDate("Date:", response.Request_AddPayment.Date)
    .AddRowCaptionText("Ezidebit Customer:", response.Request_AddPayment.EzidebitCustomerId)
    .AddRowCaptionText("Payment Reference:", response.Request_AddPayment.PaymentReference)
    .AddRowCaptionCurrency("Amount:", response.Request_AddPayment.Amount, True)

    ' Actions
    With .actions
      If ServiceLogs(0).ResponseStatus = iseServiceLogResponseStatus.InProgress Then
        If finBL.CurrentUser.Permissions.Allow("Banking.BankInterface.Requests.Update") Then
          .AddApplicationShortcutUrl("UpdateStatus", "Update Status", String.Format("App://Global?Type=BankingInterface.UpdateStatus&ServiceLogPk={0}", ServiceLogs(0).Pk), True).ShowInWebInterfaces = True
        End If
        If finBL.CurrentUser.Permissions.Allow("Banking.BankInterface.Requests.Delete") Then
          .AddApplicationShortcutUrl("Delete", "Delete", String.Format("App://Global?Type=BankingInterface.Delete&ServiceLogPk={0}", ServiceLogs(0).Pk), True).ShowInWebInterfaces = True
        End If
      End If
    End With
  End With
  SummaryTables.Add("Request", SummaryTable)

  ' Ezidebit Details
  If ResponsePaymentDetail IsNot Nothing Then
    SummaryTable = SummaryTables.CreateSummaryTableInformation("Ezidebit Details", "EzidebitDetails", 3, , , TestMode)
    With SummaryTable
      .AddRowCaptionDateTime("Date Debited:", ResponsePaymentDetail.Payment.DebitDate)
      '.AddRowCaptionText("Reference:", ResponsePaymentDetail.Payment.YourSystemReference)
      .AddRowCaptionText("Payment Id:", ResponsePaymentDetail.Payment.PaymentId)
      .AddRowCaptionCurrency("Scheduled Amount:", ResponsePaymentDetail.Payment.ScheduledAmount, True)
      .AddRowCaptionCurrency("Payment Amount:", ResponsePaymentDetail.Payment.PaymentAmount, True)
      .AddRowCaptionText("Invoice Id:", ResponsePaymentDetail.Payment.InvoiceId)
      .AddRowCaptionCurrency("Your Fee:", ResponsePaymentDetail.Payment.TransactionFeeClient, True)
      .AddRowCaptionCurrency("Customer Fee:", ResponsePaymentDetail.Payment.TransactionFeeCustomer, True)
    End With
    SummaryTables.Add("EzidebitDetails", SummaryTable)
  End If

  ' Current Status
  Select Case ServiceLogs(0).ResponseStatus
    Case iseServiceLogResponseStatus.Aborted
      SummaryTable = SummaryTables.CreateSummaryTableInformation("Current Status", "CurrentStatus", 3, , , TestMode)
      With SummaryTable
        .Rows.AddCaptionText("Current Status:", "ABORTED").BackgroundColour = "gold"
      End With
      SummaryTables.Add("CurrentStatus", SummaryTable)

    Case iseServiceLogResponseStatus.Deleted
      SummaryTable = SummaryTables.CreateSummaryTableInformation("Current Status", "CurrentStatus", 3, , , TestMode)
      With SummaryTable
        .Rows.AddCaptionText("Current Status:", "DELETED").BackgroundColour = "#EECCFF"
      End With
      SummaryTables.Add("CurrentStatus", SummaryTable)

    Case Else
      If ResponsePaymentDetail IsNot Nothing Then
        SummaryTable = SummaryTables.CreateSummaryTableInformation("Current Status", "CurrentStatus", 3, , , TestMode)
        With SummaryTable
          With .Rows.AddCaptionText("Current Status:", ResponsePaymentDetail.Payment.PaymentStatusText)
            Select Case ResponsePaymentDetail.Payment.PaymentStatus
              Case iseBankInterface_Ezidebit_PaymentStatus.Dishonoured, iseBankInterface_Ezidebit_PaymentStatus.FatalDishonour
                .BackgroundColour = "pink"
              Case iseBankInterface_Ezidebit_PaymentStatus.Successful
                .BackgroundColour = "lightgreen"
              Case Else
                .BackgroundColour = "orange"
              End Select
          End With
          .AddRowCaptionDateTime("Settlement Date:", ResponsePaymentDetail.Payment.SettlementDate)
          .AddRowCaptionText("Failed Reason:", ResponsePaymentDetail.Payment.BankFailedReason)
        End With
        SummaryTables.Add("CurrentStatus", SummaryTable)
      End If
  End Select

  Return SummaryTables

End Function

Private Function Ezidebit_GetCustomers_List(response As ISBankInterfaceResponse_Ezidebit_GetCustomers,
                                            serviceLogSourceObjects As finServiceLogSourceObjects) As ISSummaryTables

  Dim Client As finClient
  Dim Customer As ISBankInterfaceResponse_Ezidebit_Customer
  Dim Row As Integer
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim Warnings As String

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  If response.Customers.Count = 0 Then
    SummaryTables.AddSummaryTableBlank("Customers", "Customers", "No customers found.", "", 2)
  Else
    Row = 0
    For Each Customer In response.Customers
      If Row Mod 2 = 0 Then SummaryTables.AddSummaryTableBlank("CustomerStart_" & CStr(Row), "", "<div style='background-color:#F2F2F2'>", , 3)

      ' Get Related Account or Client
      finBL.BankingInterface.Service_Ezidebit.GetRelatedRecord(Customer, Client)

      SummaryTable = SummaryTables.CreateSummaryTableInformation(Customer.Name, "Customer_" & CStr(Row),3,,, TestMode)
      With SummaryTable
        ' Customer Information
        If Customer.IsIndividual Then
          .AddRowCaptionText("First Name:", Customer.FirstName)
          .AddRowCaptionText("Last Name:", Customer.LastName)
        Else
          .AddRowCaptionText("Business:", Customer.Name)
        End If
        .AddRowCaptionText("Mobile:", Customer.MobilePhone)
        .AddRowCaptionText("Email:", Customer.Email)
        .AddRowCaptionAddressDetailsPhysical("Address:", Customer.Address.ToAddressDetails())

        .AddRowCaptionText("Ezidebit Customer ID:", Customer.EzidebitCustomerId)
         If Client IsNot Nothing Then
           With .Rows.AddCaptionCodeDescription("Client:", Client.ClientId, Client.Name)
             .Cells(1).HyperlinkSetFormShow("Clients", Client.ClientId, "Tax & Banking")
           End With
         Else
          .AddRowCaptionText("Reference:", Customer.YourSystemReference)
         End If
        .AddRowCaptionText("General Reference:",  Customer.YourGeneralReference)

        .AddRowCaptionText("Status:", Customer.StatusText)
        .AddRowCaptionBooleanYesNo("Can Process Payments:", Customer.CanProcessPayments)

        .AddRowCaptionBooleanYesNo("SMS Reminder:", Customer.SmsPaymentReminder)
        .AddRowCaptionBooleanYesNo("SMS Failed Notification:", Customer.SmsFailedNotification)
        .AddRowCaptionBooleanYesNo("SMS Card Expirying:", Customer.SmsExpiredCard)

        .AddRowCaptionDate("Contract Started:", Customer.ContractStartDate)
        .AddRowCaptionText("Method:", Customer.PaymentMethodText)
        Select Case Customer.PaymentPeriod
          Case iseBankInterface_Ezidebit_PaymentPeriod.Undefined
          Case Else
           .AddRowCaptionText("Period:", Customer.PaymentPeriodText)
        End Select
        If Customer.TotalPaymentsSuccessful <> 0 Then
          .AddRowCaptionWiki("Total Successful:", String.format("**{0}** payments, totalling **{1}**", Format(Customer.TotalPaymentsSuccessful, "#,###,##0"), finBL.FormatCurrency(Customer.TotalPaymentsSuccessfulAmount, True)))
        End If
        If Customer.TotalPaymentsFailed <> 0 Then
          .AddRowCaptionWiki("Total Failed:", String.format("**{0}** payments, totalling **{1}**", Format(Customer.TotalPaymentsFailed, "#,###,##0"), finBL.FormatCurrency(Customer.TotalPaymentsFailedAmount, True)))
        End If

        ' Warnings
        Warnings = ""
        If Client Is Nothing Then
          Warnings &= "{{warning|Ezidebit Customer not found.|true}}"
        End If
        Select Case Customer.Status
          Case iseBankInterface_Ezidebit_CustomerStatus.Active
            If Customer.TotalPaymentsFailed <> 0 Then
            Warnings &= "{{warning|" & String.Format("{0} failed payments.", Customer.TotalPaymentsFailed) & "}}"
            End If
          Case iseBankInterface_Ezidebit_CustomerStatus.New
            Warnings &= "{{info|" & String.Format("Status is '{0}'.", Customer.StatusText) & "}}"
          Case Else
            Warnings &= "{{warning|" & String.Format("Status is '{0}'.", Customer.StatusText) & "}}"
        End Select
        If Not Customer.CanProcessPayments Then
          Warnings &= "{{warning|Payments cannot be processed.}}"
        End If

        ' Warnings from Requested Account/ Client
        If serviceLogSourceObjects.Client IsNot Nothing Then
          If Client Is Nothing Then
          ElseIf serviceLogSourceObjects.Client.Pk <> Client.Pk Then
            Warnings &= "{{warning|The Client linked to the Ezidebit Customer DOES NOT match the requested Client.|True}}"
          End If
        End If

        .TextAfter = Warnings
      End With
      SummaryTables.Add("Customer" & CStr(Row), SummaryTable)

      If Row Mod 2 = 0 Then SummaryTables.AddSummaryTableBlank("CustomerEnd_" & CStr(Row), "", "</div>", , 3)
      Row += 1
    Next
  End If

  Return SummaryTables

End Function

Private Function Ezidebit_GetCustomers_Request(response As ISBankInterfaceResponse_Ezidebit_GetCustomers,
                                               serviceLogSourceObjects As finServiceLogSourceObjects) As ISSummaryTables

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

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  ' Get Bank Account
  If finBL.BankAccounts.ExistsPk(response.Request_GetCustomerList.BankAccountPk) Then
    BankAccount = finBL.BankAccounts.ItemByPk(response.Request_GetCustomerList.BankAccountPk)
  Else
    BankAccount = Nothing
  End If

  SummaryTable = SummaryTables.CreateSummaryTableInformation("", "Request", 2, , , TestMode)
  With SummaryTable
    .AddRowCaptionUtcDateTimeWithTimeZone("Date:", response.RequestUtcDate, finBL.Settings.TimeZoneId)
    If BankAccount IsNot Nothing Then .AddRowCaptionCodeDescription("Bank Account:", BankAccount.Pk, finBL.BankAccounts, False)
    .AddRowCaptionText("Ezidebit Customer:", response.Request_GetCustomerList.EzidebitCustomerId, False)
    If serviceLogSourceObjects.Account IsNot Nothing Then
      With .Rows.AddCaptionCodeDescription("Account:", serviceLogSourceObjects.Account.AccountId, serviceLogSourceObjects.Account.Name)
        .Cells(1).HyperlinkSetFormShow("Accounts", serviceLogSourceObjects.Account.AccountId, "Payments")
      End With
    ElseIf serviceLogSourceObjects.Client IsNot Nothing Then
      With .Rows.AddCaptionCodeDescription("Client:", serviceLogSourceObjects.Client.ClientId, serviceLogSourceObjects.Client.Name)
        .Cells(1).HyperlinkSetFormShow("Clients", serviceLogSourceObjects.Client.ClientId, "Tax & Banking")
      End With
    Else
      .AddRowCaptionText("Reference:", response.Request_GetCustomerList.YourSystemReference)
    End If

    ' Warnings
    Warnings = ""
    If response.Customers.Count = 1 Then
      Warnings &= Me.GetWarnings(response.Customers(0), serviceLogSourceObjects)
    End If
    .TextAfter = Warnings
  End With
  SummaryTables.Add("Request", SummaryTable)

  Return SummaryTables

End Function

Private Function Ezidebit_History() As ISSummaryTables

  Dim ServiceLog As ISServiceLog
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  SummaryTable = SummaryTables.CreateSummaryTableTabular("History", "History", 2, TestMode)
  With SummaryTable
    ' Columns
    With .Columns
      .AddText("Service Log")
      .AddDate("Date")
      .AddText("User")
      .AddText("Type")
      .AddText("Status")
    End With

    ' Rows
    With .Rows
      For Each ServiceLog In ServiceLogs
        With .Add
          If Len(ServiceLog.ExStatusHtmlColour) <> 0 Then
            .BackgroundColour = ServiceLog.ExStatusHtmlColour
            If finBL.Runtime.ColourUtilities.HtmlColourIsDark(ServiceLog.ExStatusHtmlColour) Then .ForegroundColour = "white"
          End If
          With .Cells
            .AddText(CStr(ServiceLog.Pk)).HyperlinkSetFormShow("ServiceLog", CStr(ServiceLog.Pk))
            .AddDateTime(ServiceLog.CreatedDate,, True)
            .AddCodeDescription(ServiceLog.CreatedUserPk, finBL.Users)
            .AddText(ServiceLog.ProductId)
            .AddText(ServiceLog.ExStatus).Tooltip = ServiceLog.ExStatusTooltip
          End With
        End With
      Next
    End With
  End With
  SummaryTables.Add("History", SummaryTable)

  Return SummaryTables

End Function

Private Function Ezidebit_UpdateCustomerBankAccount_Request(response As ISBankInterfaceResponse_Ezidebit_UpdateCustomerBankAccount,
                                                            serviceLogSourceObjects As finServiceLogSourceObjects) As ISSummaryTables

  Dim BankAccount As finBankAccountRO
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  ' Get Bank Account
  If finBL.BankAccounts.ExistsPk(response.Request_UpdateCustomerBankAccount.BankAccountPk) Then
    BankAccount = finBL.BankAccounts.ItemByPk(response.Request_UpdateCustomerBankAccount.BankAccountPk)
  Else
    BankAccount = Nothing
  End If

  SummaryTable = SummaryTables.CreateSummaryTableInformation("", "Request", 2, , , TestMode)
  With SummaryTable
    .AddRowCaptionUtcDateTimeWithTimeZone("Date:", response.RequestUtcDate, finBL.Settings.TimeZoneId)
    If BankAccount IsNot Nothing Then .AddRowCaptionCodeDescription("Bank Account:", BankAccount.Pk, finBL.BankAccounts, False)
    If serviceLogSourceObjects.Account IsNot Nothing Then
      With .Rows.AddCaptionCodeDescription("Account:", serviceLogSourceObjects.Account.AccountId, serviceLogSourceObjects.Account.Name)
        .Cells(1).HyperlinkSetFormShow("Accounts", serviceLogSourceObjects.Account.AccountId, "Payments")
      End With
    ElseIf serviceLogSourceObjects.Client IsNot Nothing Then
      With .Rows.AddCaptionCodeDescription("Client:", serviceLogSourceObjects.Client.ClientId, serviceLogSourceObjects.Client.Name)
        .Cells(1).HyperlinkSetFormShow("Clients", serviceLogSourceObjects.Client.ClientId, "Tax & Banking")
      End With
    End If
    .AddRowCaptionText("Ezidebit Customer ID:", response.Request_UpdateCustomerBankAccount.EzidebitCustomerId)
  End With
  SummaryTables.Add("Request", SummaryTable)

  Return SummaryTables

End Function

Private Function Ezidebit_UpdateCustomerBankAccount_BankAccount(response As ISBankInterfaceResponse_Ezidebit_UpdateCustomerBankAccount) As ISSummaryTables

  Dim BankingDetails As finBankingDetails
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  ' Get Banking Details
  BankingDetails = finBL.CreateBankingDetails()
  With BankingDetails
    .PaymentTypeId = isePaymentTypeClass.BankAccount.ToString()
    .AccountSortCode = response.Request_UpdateCustomerBankAccount.BankAccountBSB
    .AccountNumber = response.Request_UpdateCustomerBankAccount.BankAccountNumber
    .AccountName = response.Request_UpdateCustomerBankAccount.BankAccountName
  End With
  BankingDetails = BankingDetails.CloneForDisplay()

  SummaryTable = SummaryTables.CreateSummaryTableInformation("Bank Account Details", "BankAccount", 2, , , TestMode)
  With SummaryTable
    .AddRowCaptionText("Account Name:", BankingDetails.AccountName)
    If finBL.CurrentCountry.SupportsBankSortCode Then
      .AddRowCaptionText(finBL.CurrentCountry.Terminology(isefinCountryTerminology.BankSortCode) & ":", BankingDetails.AccountSortCode)
      .AddRowCaptionText("Account Number:", BankingDetails.AccountNumber)
    Else
    .AddRowCaptionText("Account Number:", BankingDetails.AccountNumber)
    End If
  End With
  SummaryTables.Add("BankAccount", SummaryTable)

  Return SummaryTables

End Function

Private Function Ezidebit_UpdateCustomerCreditCard_Request(response As ISBankInterfaceResponse_Ezidebit_UpdateCustomerCreditCard,
                                                           serviceLogSourceObjects As finServiceLogSourceObjects) As ISSummaryTables

  Dim BankAccount As finBankAccountRO
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  ' Get Bank Account
  If finBL.BankAccounts.ExistsPk(response.Request_UpdateCustomerCreditCard.BankAccountPk) Then
    BankAccount = finBL.BankAccounts.ItemByPk(response.Request_UpdateCustomerCreditCard.BankAccountPk)
  Else
    BankAccount = Nothing
  End If

  SummaryTable = SummaryTables.CreateSummaryTableInformation("", "Request", 2, , , TestMode)
  With SummaryTable
    .AddRowCaptionUtcDateTimeWithTimeZone("Date:", response.RequestUtcDate, finBL.Settings.TimeZoneId)
    If BankAccount IsNot Nothing Then .AddRowCaptionCodeDescription("Bank Account:", BankAccount.Pk, finBL.BankAccounts, False)
    If serviceLogSourceObjects.Account IsNot Nothing Then
      With .Rows.AddCaptionCodeDescription("Account:", serviceLogSourceObjects.Account.AccountId, serviceLogSourceObjects.Account.Name)
        .Cells(1).HyperlinkSetFormShow("Accounts", serviceLogSourceObjects.Account.AccountId, "Payments")
      End With
    ElseIf serviceLogSourceObjects.Client IsNot Nothing Then
      With .Rows.AddCaptionCodeDescription("Client:", serviceLogSourceObjects.Client.ClientId, serviceLogSourceObjects.Client.Name)
        .Cells(1).HyperlinkSetFormShow("Clients", serviceLogSourceObjects.Client.ClientId, "Tax & Banking")
      End With
    End If
    .AddRowCaptionText("Ezidebit Customer ID:", response.Request_UpdateCustomerCreditCard.EzidebitCustomerId)
  End With
  SummaryTables.Add("Request", SummaryTable)

  Return SummaryTables

End Function

Private Function Ezidebit_UpdateCustomerCreditCard_CreditCard(response As ISBankInterfaceResponse_Ezidebit_UpdateCustomerCreditCard) As ISSummaryTables

  Dim BankingDetails As finBankingDetails
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  ' Get Banking Details
  BankingDetails = finBL.CreateBankingDetails()
  With BankingDetails
    .PaymentTypeId = response.Request_UpdateCustomerCreditCard.PaymentTypeClass.ToString()
    .AccountName = response.Request_UpdateCustomerCreditCard.CreditCardName
    .AccountNumber = response.Request_UpdateCustomerCreditCard.CreditCardNumber
    .CardExpiryDate = response.Request_UpdateCustomerCreditCard.CreditCardExpiryDate
  End With
  BankingDetails = BankingDetails.CloneForDisplay()

  SummaryTable = SummaryTables.CreateSummaryTableInformation("Credit Card Details", "CreditCard", 2, , , TestMode)
  With SummaryTable
    .AddRowCaptionText("Card Name:", BankingDetails.AccountName)
    .AddRowCaptionText("Card Number:", BankingDetails.AccountNumber)
    .AddRowCaptionText("Card Expiry:", format(BankingDetails.CardExpiryDate,"MM/yyyy"))
  End With
  SummaryTables.Add("CreditCard", SummaryTable)

  Return SummaryTables

End Function

Private Function GetWarnings(customer As ISBankInterfaceResponse_Ezidebit_Customer,
                             serviceLogSourceObjects As finServiceLogSourceObjects) As String

  Dim AccountBankingDetail As finAccountBankingDetail
  Dim AccountClient As finAccountClient
  Dim Found As Boolean

  ' Initialise
  GetWarnings = ""

'  ' Account
'  If account IsNot Nothing Then
'    ' Get Banking Detail
'    If account.BankingDetails.ExistsBankingDetailsType(isefinAccountBankingDetailsType.Incoming) Then
'      AccountBankingDetail = account.BankingDetails.Item(isefinAccountBankingDetailsType.Incoming)
'    Else
'      AccountBankingDetail = Nothing
'    End If
'
'    ' Account Status
'    Select Case account.Status
'      Case isefinAccountStatus.Open
'      Case Else
'        GetWarnings &= "{{warning|" & String.Format("Status is '{0}'.", account.StatusText) & "}}"
'    End Select
'
'    If AccountBankingDetail Is Nothing Then
'      GetWarnings &= "{{warning|Invalid Account. Ths Account does not support an 'Incoming' Bank Account.}}"
'    Else
'      ' Warning re Ezidebit Customer ID match
'      Select Case AccountBankingDetail.BankingDetails.PaymentTypeCategory
'        Case isefinPaymentTypeCategory.Ezidebit
'          If Len(AccountBankingDetail.BankingDetails.ExternalId) = 0 Then
'            GetWarnings &= "{{warning|Account's Ezidebit Customer ID not defined. Please review and update the Account.}}"
'          ElseIf AccountBankingDetail.BankingDetails.ExternalId = customer.EzidebitCustomerId Then
'            GetWarnings &= "{{info|Ezidebit Customer is currently being used for Payments.|true}}"
'          Else
'            GetWarnings &= "{{warning|Ezidebit Customer does not match Account. Please review and update the Account.|true}}"
'          End If
'        Case Else
'          GetWarnings &= "{{warning|Ezidebit is NOT currently being used for Payments.}}"
'      End Select
'
'      ' Name Match
'      For Each AccountClient In Account.Clients
'        If AccountClient.IsOwner Then
'          If StrComp(AccountClient.Client.FirstName, customer.FirstName, CompareMethod.Text) = 0 AndAlso StrComp(AccountClient.Client.LastName, customer.LastName, CompareMethod.Text) = 0 Then
'            Found = True
'
'            ' Other Checks
'            If AccountClient.Client.ContactMethods.GetCurrentEmail().Value <> customer.Email Then
'              GetWarnings &= "{{warning|Client Email address does not match Ezidebit Customer.}}"
'            End If
'          End If
'        End If
'      Next
'      If Not Found Then
'        GetWarnings &= "{{warning|Cannot match Name to an Owner of the Account.}}"
'      End If
'    End If
'  End If

  ' Client
  If serviceLogSourceObjects.Client IsNot Nothing Then
    ' Client Status
    If Not serviceLogSourceObjects.Client.Active Then
      GetWarnings &= "{{warning|Client is inactive.}}"
    End If

    ' Test name
    If serviceLogSourceObjects.Client.IsIndividualOrSoleTrader Then
      ' Individual
      If StrComp(AccountClient.Client.LastName, customer.LastName, CompareMethod.Text) <> 0 Then
        GetWarnings &= "{{warning|Client's Last Name does not match Ezidebit Customer.}}"
      ElseIf StrComp(AccountClient.Client.FirstName, customer.FirstName, CompareMethod.Text) <> 0 Then
        GetWarnings &= "{{warning|Client's First Name does not match Ezidebit Customer.}}"
      End If
    Else
      ' Organisation
      If StrComp(AccountClient.Client.Name, customer.LastName, CompareMethod.Text) <> 0 Then
        GetWarnings &= "{{warning|Client's Name does not match Ezidebit Customer.}}"
      End If
    End If

    ' Other Checks
    If serviceLogSourceObjects.Client.ContactMethods.GetCurrentEmail().Value <> customer.Email Then
      GetWarnings &= "{{warning|Client Email address does not match Ezidebit Customer.}}"
    End If
  End If

End Function