' SummaryPage2_MessagingSummary_Kudosity
Option Explicit On
Option Strict On

' #################################################################
' Kudosity (Burst SMS) SMS Messaging Report Summary Page Script
' 
' Version: 1.00 (27/05/2024)
' 
' Usage: SMS Messaging and Log forms
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.00  27/05/2024  ISS      J033539   Created
' #################################################################

' Constants
'#const "IncludeCostInformation",Boolean,False,"Include Cost information?"

' Constants
Private IncludeCostInformation As Boolean = False

' Special Constants
Const TestMode As Boolean = False

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 ISSmsResponse_Kudosity_SendSms
  Dim ServiceLogs As ISServiceLogs

  ' Assume Success
  Main = True

  ' Get Constants
  With ScriptInfo.Constants
    IncludeCostInformation = .GetBoolean("IncludeCostInformation", IncludeCostInformation)
  End With

  ' Get Service Logs
  Try
    Main = finBL.Messaging.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 a SMS Message.")
    ElseIf ServiceLogs(0).RequestStatus <> iseAuditLogStatus.Success Then
      Main = False
      finBL.Error.ErrorBegin("Invalid Service Log. Initial Request was not successful.")
    Else
      Select Case ServiceLogs(0).ExResponse.GetType()
        Case GetType(ISSmsResponse_Kudosity_SendSms)
          Response = DirectCast(ServiceLogs(0).ExResponse, ISSmsResponse_Kudosity_SendSms)
        Case Else
          Main = False
          finBL.Error.ErrorBegin("Invalid Service Log." & typename(ServiceLogs(0).ExResponse) )
      End Select
    End If
  End If

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

End Function

Private Function CreatePage(serviceLogs As ISServiceLogs,
                            response As ISSmsResponse_Kudosity_SendSms,
                            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("#1B3B6D", "#D0D0D0", "", "#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
  Me.CreatePage_Kudosity(serviceLogs, response, HtmlSummaryPage2StringBuilder)

  ' 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_Kudosity(serviceLogs As ISServiceLogs,
                                 response As ISSmsResponse_Kudosity_SendSms,
                                 htmlSummaryPage2StringBuilder As finHtmlSummaryPage2StringBuilder)

  Dim SmsStatusUpdates As ISSmsStatusUpdates

  ' Get SMS Statuses - ignore errors
  finBL.Messaging.GetSmsStatusUpdates(serviceLogs(0), SmsStatusUpdates)

  With HtmlSummaryPage2StringBuilder
    .AppendH1(response.Request_SendSms.Message)

    .SummaryTablesAppend(Me.Kudosity_SendSms_Details(serviceLogs, response, SmsStatusUpdates))
    If IncludeCostInformation Then .SummaryTablesAppend(Me.Kudosity_SendSms_Cost(serviceLogs, response))
    .SummaryTablesAppend(Me.Kudosity_SmsStatusUpdates(SmsStatusUpdates))
 End With

End Sub

Private Function Kudosity_SendSms_Details(serviceLogs As ISServiceLogs,
                                           response_SendSms As ISSmsResponse_Kudosity_SendSms,
                                           smsStatusUpdates As ISSmsStatusUpdates) As ISSummaryTables

  Dim Account As finAccount
  Dim AccountApp As finAccountApp
  Dim AccountAppLog As finAccountAppLog
  Dim AccountLog As finAccountLog
  Dim Client As finClient
  Dim ClientLog As finClientLog
  Dim ExternalParty As finExternalPartyRO
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim Warnings As String
  Dim User As finUserRO
  Dim UserLog As finUserLog

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  SummaryTable = SummaryTables.CreateSummaryTableInformation("", "SendDetails", 2, , , TestMode)
  With SummaryTable
    If response_SendSms.Request_SendSms.SendAtUtcDate = Nothing Then
      .AddRowCaptionUtcDateTimeWithTimeZone("Date Sent:", response_SendSms.RequestUtcDate, finBL.Settings.TimeZoneId)
    Else  
      .AddRowCaptionUtcDateTimeWithTimeZone("Date Created:", response_SendSms.RequestUtcDate, finBL.Settings.TimeZoneId)
      .AddRowCaptionUtcDateTimeWithTimeZone("Send At:", response_SendSms.Request_SendSms.SendAtDate, finBL.Settings.TimeZoneId)
    End If
    .AddRowCaptionText("Message Id:", response_SendSms.MessageId)
    .AddRowCaptionText("From:", response_SendSms.Request_SendSms.ReplyEmailResolved, False)
    .AddRowCaptionText("To:", Me.FormatPhoneNumber(response_SendSms.Request_SendSms.Recipient.PhoneNumberE164))
    .AddRowCaptionText("", response_SendSms.Request_SendSms.Recipient.Name, False)
    
    Select Case UCase(serviceLogs(0).SourceType)
      Case "ACCOUNTLOG"
        AccountLog = finBL.CreateAccountLog()
        If AccountLog.Load(ServiceLogs(0).SourcePk) Then
          Account = finBL.CreateAccount()

          If Account.LoadPk(AccountLog.AccountPk) Then
            With .Rows.AddCaptionCodeDescription("Account:", Account.AccountId, Account.Name)
              .Cells(1).HyperlinkSetFormShow("Accounts", Account.AccountId)
            End With
            With .Rows.AddCaptionText("", "Account Log", iseSummaryTableCellClass.Normal)
              .Cells(1).HyperlinkSetFormShow("AccountLog", CStr(AccountLog.Pk))
            End With
          End If

          ' Action
          If finBL.Messaging.IsMessagingAvailable AndAlso finBL.Settings.SmsUseNewInterface Then
            .Actions.AddFormShow("ReplyMessagingSMS", "Reply via SMS", "SmsMessage_New", True, String.Format("id={0}&type=Account&parentSourceLogPk={1}", Account.AccountId, AccountLog.Pk)).ShowInWebInterfaces = True
          End If
        End If

      Case "ACCOUNTAPPLOG"
        AccountAppLog = finBL.CreateAccountAppLog()
        If AccountAppLog.Load(ServiceLogs(0).SourcePk) Then
          AccountApp = finBL.CreateAccountApp()

          If AccountApp.LoadPk(AccountAppLog.AccountAppPk) Then
            With .Rows.AddCaptionCodeDescription("Account Application:", AccountApp.AccountAppId, AccountApp.Name)
              .Cells(1).HyperlinkSetFormShow("AccountApps", AccountApp.AccountAppId)
            End With
            With .Rows.AddCaptionText("", "Account Application Log", iseSummaryTableCellClass.Normal)
              .Cells(1).HyperlinkSetFormShow("AccountAppLog", CStr(AccountAppLog.Pk))
            End With
          End If

          ' Action
          If finBL.Messaging.IsMessagingAvailable AndAlso finBL.Settings.SmsUseNewInterface Then
            .Actions.AddFormShow("ReplyMessagingSMS", "Reply via SMS", "SmsMessage_New", True, String.Format("id={0}&type=Account Application&parentSourceLogPk={1}", AccountApp.AccountAppId, AccountAppLog.Pk)).ShowInWebInterfaces = True
          End If
        End If

      Case "CLIENTLOG"
        ClientLog = finBL.CreateClientLog()
        If ClientLog.Load(serviceLogs(0).SourcePk) Then
          ' Client
          Client = ClientLog.Client

          ' External Party?
          If Client.SpecialType = isefinClientSpecialType.ExternalParty Then
            ExternalParty = Client.ParentExternalPartyRO
          End If

          If ExternalParty Is Nothing Then
            ' Client
            With .Rows.AddCaptionCodeDescription("Client:", Client.ClientId, Client.Name)
              .Cells(1).HyperlinkSetFormShow("Clients", Client.ClientId)
            End With
            With .Rows.AddCaptionText("", "Client Log", iseSummaryTableCellClass.Normal)
              .Cells(1).HyperlinkSetFormShow("ClientLog", CStr(ClientLog.Pk))
            End With
          Else
            ' External Party
            With .Rows.AddCaptionCodeDescription(ExternalParty.ExternalPartyTypeText & ":", ExternalParty.ExternalPartyId, ExternalParty.Name)
              .Cells(1).HyperlinkSetFormShow("ExternalParties", ExternalParty.ExternalPartyId)
            End With
            With .Rows.AddCaptionText("", ExternalParty.ExternalPartyTypeText & " Log", iseSummaryTableCellClass.Normal)
              .Cells(1).HyperlinkSetFormShow("ClientLog", CStr(ClientLog.Pk))
            End With
          End If

          ' Action
          If finBL.Messaging.IsMessagingAvailable AndAlso finBL.Settings.SmsUseNewInterface Then
            .Actions.AddFormShow("ReplyMessagingSMS", "Reply via SMS", "SmsMessage_New", True, String.Format("id={0}&type=Client&parentSourceLogPk={1}", Client.ClientId, ClientLog.Pk)).ShowInWebInterfaces = True
          End If
        End If

      Case "USERLOG"
        UserLog = finBL.CreateUserLog()
        If UserLog.Load(serviceLogs(0).SourcePk) Then
          If finBL.Users.ExistsPk(UserLog.UserPk) Then
            User = finBL.Users.ItemByPk(UserLog.UserPk)

            With .Rows.AddCaptionCodeDescription("User:", User.UserId, User.Name)
              .Cells(1).HyperlinkSetFormShow("Users", User.UserId)
            End With
            With .Rows.AddCaptionText("", "User Log", iseSummaryTableCellClass.Normal)
              .Cells(1).HyperlinkSetFormShow("UserLog", CStr(UserLog.Pk))
            End With
          End If

          ' Action
          If finBL.Messaging.IsMessagingAvailable AndAlso finBL.Settings.SmsUseNewInterface Then
            .Actions.AddFormShow("ReplyMessagingSMS", "Reply via SMS", "SmsMessage_New", True, String.Format("id={0}&type=User&parentSourceLogPk={1}", User.UserId, UserLog.Pk)).ShowInWebInterfaces = True
          End If
        End If
    End Select

    ' Warnings
    Warnings = ""
    If SmsStatusUpdates IsNot Nothing Then
      Select Case finBL.Messaging.Enums.iseMessaging_Kudosity_MessageStatus_FromString(smsStatusUpdates.GetCurrentStatus)
        Case iseMessaging_Kudosity_MessageStatus.Delivered
          Warnings &= "{{info|SMS Delivered; Received by handset.|true}}"
        Case iseMessaging_Kudosity_MessageStatus.SoftBounce
          Warnings &= "{{warning|Message was undeliverable due to handset switched off, out of range or other temporary deliverability issue.|true}}"
        Case iseMessaging_Kudosity_MessageStatus.HardBounce
          Warnings &= "{{warning|Handset was disconnected.|true}}"
      End Select
      If smsStatusUpdates.HasReply Then
        If smsStatusUpdates.HasOptOut Then
          Warnings &= "{{warning|There is an 'Opt Out' Reply to the SMS recorded.|true}}"
        Else
          Warnings &= "{{warning|There is a Reply to the SMS recorded.|true}}"
        End If  
      End If
    End If
    .TextAfter = Warnings
  End With
  SummaryTables.Add("SendDetails", SummaryTable)

  Return SummaryTables

End Function

Private Function Kudosity_SendSms_Cost(serviceLogs As ISServiceLogs,
                                       response_SendSms As ISSmsResponse_Kudosity_SendSms) As ISSummaryTables

  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  SummaryTable = SummaryTables.CreateSummaryTableInformation("Message Cost", "MessageCost", 2, , , TestMode)
  With SummaryTable
    If response_SendSms.Recipients <> 1 Then .AddRowCaptionInteger("Message Recipients:", response_SendSms.Recipients)
    .AddRowCaptionInteger("Message Parts:", response_SendSms.Sms)
    .AddRowCaptionText("Cost:", finBL.Runtime.Locale.CurrencySymbol & Format(response_SendSms.Cost, "###0.000"), True)
  End With
  SummaryTables.Add("MessageCost", SummaryTable)

  Return SummaryTables

End Function

Private Function Kudosity_SmsStatusUpdates(smsStatusUpdates As ISSmsStatusUpdates) As ISSummaryTables

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

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  If SmsStatusUpdates Is Nothing OrElse SmsStatusUpdates.Count = 0 Then
    SummaryTables.AddSummaryTableBlank("StatusUpdates", "Status Updates", "No Status Updates found.", "StatusUpdates", 2)
  Else
    SummaryTable = SummaryTables.CreateSummaryTableTabular("Status Updates", "StatusUpdates", 2, TestMode)
    With SummaryTable
      ' Columns
      With .Columns
        .AddDateTime("Date")
        .AddText("Status")
        .AddText("Log")
        .AddText("Reply")
        If SmsStatusUpdates.HasOptOut Then .AddText("Opt Out")
      End With

      ' Rows
      With .Rows
        For Each SmsStatusUpdate In SmsStatusUpdates
          ' Get related Service Log to see if there is a Source Log recorded
          If SmsStatusUpdate.ServiceLogPk = 0 Then
            ServiceLog = Nothing
          Else
            finBL.Database.GetServiceLog(SmsStatusUpdate.ServiceLogPk, ServiceLog)
          End If

          With .Add.Cells
            .AddDateTime2(SmsStatusUpdate.Date, True)
            .AddText(SmsStatusUpdate.StatusText)
            If ServiceLog Is Nothing OrElse ServiceLog.SourcePk = 0 Then
              .AddText(String.Format("Service Log {0}", SmsStatusUpdate.ServiceLogPk)).HyperlinkSetFormShow("ServiceLog", CStr(SmsStatusUpdate.ServiceLogPk))
            Else
              .AddText(String.Format("{0} {1}", finBL.Runtime.TextUtilities.SplitWordsAtCapitals(ServiceLog.SourceType), ServiceLog.SourcePk)).HyperlinkSetFormShow(ServiceLog.SourceType, CStr(ServiceLog.SourcePk))
            End If
            .AddText(SmsStatusUpdate.ReplyText).CellClass = iseSummaryTableCellClass.NormalBold
            If SmsStatusUpdates.HasOptOut Then
              If SmsStatusUpdate.IsOptOut Then
                .AddText("OPT OUT").CellClass = iseSummaryTableCellClass.WarningBold
              Else
                .AddText("")
              End If  
            End If  
          End With
        Next
      End With
    End With
    SummaryTables.Add("StatusUpdates", SummaryTable)
  End If

  Return SummaryTables

End Function

Private Function FormatPhoneNumber(phoneNumber As String) As String

  With finBL.Runtime.CreatePhoneNumberDetails2()
    If .ParsePhoneNumber(phoneNumber) Then
      Return .GetPhoneNumberFull(False)
    Else
      Return phoneNumber
    End If
  End With

End Function