' SummaryPage2_BankAccountEnquiryReport_Basiq
Option Explicit On
Option Strict On

' #################################################################
' Basiq Bank Account Report Summary Page Script
'
' Version: 1.00 (04/06/2026)
'
' Usage: Bank Account Enquiry and Log forms
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.00  04/06/2026  ISS      J036556   Created
' #################################################################

'#Const "OutOfDateWarningDays",Integer,30,"Number of days before warning the Enquiry is out-of-date."

' Constants
Private OutOfDateWarningDays As Integer = 30
Private TabularDataHeaderForegroundColour As String = "white"

' Special Constants
Const TestMode As Boolean = False
Const ClientExtensionDemo As Boolean = False  ' Toggle to True to render the "Client Extension Demo" block under each STATEMENT_01 report. Demonstrates how a customisation can supply its own local proxy class (see the BasiqDemo* Classes at the bottom of this script) and pull the report data via ResponseGetReport.GetDataAs(GetType(...)) - the pattern that lets new Basiq report types be consumed without touching the Business Layer.

' Properties
Private mVersion As String

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

  ' Assume Success
  Main = True

  ' Get Constants
  With ScriptInfo.Constants
    OutOfDateWarningDays = .GetInteger("OutOfDateWarningDays", OutOfDateWarningDays)
  End With

  ' Initialise
  mVersion = ""

  ' Get Bank Account Enquiry Service Logs
  If Main Then
    Main = finBL.CreditBureau.GetBankAccountEnquiryServiceLogs(CInt(source), ServiceLogs)
  End If

  ' Validate
  If Main Then
    If ServiceLogs.Count = 0 Then
      Main = False
      finBL.Error.ErrorBegin("Invalid Service Log. Not a Bank Account Enquiry.")
    ElseIf ServiceLogs(0).RequestStatus <> iseAuditLogStatus.Success Then
      Main = False
      finBL.Error.ErrorBegin("Invalid Service Log. Initial Request was not successful.")
    ElseIf ServiceLogs(0).ExResponse Is Nothing Then
      Main = False
      finBL.Error.ErrorBegin("Invalid Service Log. The response is missing.")
    Else
      Select Case ServiceLogs(0).ExResponse.GetType()
        Case GetType(ISBankAccountEnquiryResponse_Basiq_CreateUser)
          Response = DirectCast(ServiceLogs(0).ExResponse, ISBankAccountEnquiryResponse)
        Case Else
          Main = False
          finBL.Error.ErrorBeginFormat("Invalid Service Log. Unexpected response type '{0}'.", 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 = CreatePage(ServiceLogs, Response, text)
    End Select
  End If

End Function

Private Function Basiq_Accounts(serviceLogs As ISServiceLogs) As ISSummaryTables

  Dim Accounts As ProxyObjects.Basiq.AccountList
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  ' Collate every successful GetAccounts response (UpdateResponseIS already applied)
  Accounts = finBL.CreditBureau.Service_Basiq.GetAllAccounts(serviceLogs)

  If Accounts Is Nothing OrElse Accounts.data Is Nothing OrElse Accounts.data.Length = 0 Then
    SummaryTables.AddSummaryTableBlank("Accounts", "Accounts", "<div/>", "Accounts", 2).TextAfter = "{{Warning|No Accounts found.}}"
  Else
    SummaryTable = SummaryTables.CreateSummaryTableTabular("Accounts", "Accounts", 2, TestMode)
    With SummaryTable
      With .Columns
        .AddText("Name")
        .AddText("Account No")
        .AddText("Type")
        .AddText("Institution")
        .AddText("Status")
        .AddText("Currency")
        .AddCurrency("Balance")
        .AddCurrency("Available Funds")
        .AddDateTime("Last Updated")
      End With

      With .Rows
        For Each AccountItem As ProxyObjects.Basiq.Account In Accounts.data
          With .Add
            With .Cells
              .AddText(AccountItem.name)
              .AddText(AccountItem.accountNo)
              .AddText(If(AccountItem.[class] IsNot Nothing, AccountItem.[class].IS_TypeText, ""))
              .AddText(AccountItem.institution)
              .AddText(AccountItem.IS_StatusText)
              .AddText(AccountItem.currency)
              .AddCurrency(AccountItem.IS_Balance.GetValueOrDefault(), blankIfZero:=True).CellClass = If(AccountItem.IS_Balance.GetValueOrDefault() < 0, iseSummaryTableCellClass.Warning, iseSummaryTableCellClass.None)
              .AddCurrency(AccountItem.IS_AvailableFunds.GetValueOrDefault(), blankIfZero:=True).CellClass = If(AccountItem.IS_AvailableFunds.GetValueOrDefault() < 0, iseSummaryTableCellClass.Warning, iseSummaryTableCellClass.None)
              .AddDateTime(AccountItem.IS_LastUpdatedDate,, True)
            End With
          End With
        Next
      End With
    End With
    Basiq_TabularTableHeaderRowUpdate(SummaryTable)
    SummaryTables.Add("Accounts", SummaryTable)
  End If

  Return SummaryTables

End Function

Private Function Basiq_Alerts(serviceLogs As ISServiceLogs) As ISSummaryTables

  Dim Accounts As ProxyObjects.Basiq.AccountList
  Dim AlertMessage As String
  Dim CreateReportResponse As ISBankAccountEnquiryResponse_Basiq_CreateReport
  Dim Days As Integer
  Dim FailedCreateReport As ISBankAccountEnquiryResponse_Basiq_CreateReport
  Dim FailedReason As String
  Dim FailedReportType As String
  Dim FailedReportTypesSeen As ISList
  Dim FailedResponse As ISBankAccountEnquiryResponse
  Dim GetJobResponse As ISBankAccountEnquiryResponse_Basiq_GetJob
  Dim JobId As String
  Dim ReportTypeText As String
  Dim Status As String
  Dim SuccessfulReportTypes As ISList
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim Transactions As ProxyObjects.Basiq.TransactionList
  Dim WarningLevel As isefinWarningLevel
  Dim Warnings As finWarnings

  ' Create Objects
  FailedReportTypesSeen = finBL.Runtime.CreateList()
  SuccessfulReportTypes = finBL.Runtime.CreateList()
  SummaryTables = finBL.CreateSummaryTables()
  Warnings = finBL.CreateWarnings()

  ' Accounts (collated across all successful GetAccounts responses) - an informational alert linking to the Accounts block when present, or a High warning when none were retrieved.
  Accounts = finBL.CreditBureau.Service_Basiq.GetAllAccounts(serviceLogs)
  If Accounts Is Nothing OrElse Accounts.data Is Nothing OrElse Accounts.data.Length = 0 Then
    Warnings.AddWarning("No Accounts found.",,, isefinWarningLevel.High, "#Accounts")
  Else
    Warnings.AddWarning(String.Format("{0} Accounts retrieved.", Accounts.data.Length),,, isefinWarningLevel.Low, "#Accounts")
  End If

  ' Transactions (collated across all GetTransactions pages) - same treatment, linking to the Transactions block.
  Transactions = finBL.CreditBureau.Service_Basiq.GetAllTransactions(serviceLogs)
  If Transactions Is Nothing OrElse Transactions.data Is Nothing OrElse Transactions.data.Length = 0 Then
    Warnings.AddWarning("No Transactions found.",,, isefinWarningLevel.Medium, "#Transactions")
  Else
    Warnings.AddWarning(String.Format("{0} Transactions retrieved.", Transactions.data.Length),,, isefinWarningLevel.Low, "#Transactions")
  End If

  ' Reports — surface a status line per requested Report.
  ' Status is sourced newest-first: the latest GetJob log for the report's jobId takes priority; if none exists yet, fall back to the CreateReport response's own Job-stub payload (Basiq returns a Job envelope whose steps[] may already carry the initial status); finally default to "In Progress" because a CreateReport that succeeded by definition kicked off a Job that has not yet reached terminal state.
  ' Also collect every ReportType that has at least one successful CreateReport into SuccessfulReportTypes - the failed-CreateReport loop below uses this set to suppress a redundant alert when a 2-attempt retry recovered on its second try.
  For Each ServiceLog As ISServiceLog In serviceLogs
    If ServiceLog.ExResponse IsNot Nothing AndAlso TypeOf ServiceLog.ExResponse Is ISBankAccountEnquiryResponse_Basiq_CreateReport Then
      CreateReportResponse = DirectCast(ServiceLog.ExResponse, ISBankAccountEnquiryResponse_Basiq_CreateReport)
      ReportTypeText = ""
      Status = ""
      JobId = ""
      If CreateReportResponse.Request_CreateReport IsNot Nothing Then
        ReportTypeText = CreateReportResponse.Request_CreateReport.ReportType
      End If
      If CreateReportResponse.Payload IsNot Nothing Then
        JobId = CreateReportResponse.Payload.id
        Status = CreateReportResponse.Payload.IS_OverallStatusText
      End If

      ' Override with the latest GetJob status if this Job has been polled.
      If Len(JobId) <> 0 Then
        For j As Integer = serviceLogs.Count - 1 To 0 Step -1
          If serviceLogs(j).ExResponse IsNot Nothing AndAlso TypeOf serviceLogs(j).ExResponse Is ISBankAccountEnquiryResponse_Basiq_GetJob Then
            GetJobResponse = DirectCast(serviceLogs(j).ExResponse, ISBankAccountEnquiryResponse_Basiq_GetJob)
            If GetJobResponse.Request_GetJob IsNot Nothing AndAlso GetJobResponse.Request_GetJob.JobId = JobId AndAlso GetJobResponse.Payload IsNot Nothing Then
              Status = GetJobResponse.Payload.IS_OverallStatusText
              Exit For
            End If
          End If
        Next
      End If

      ' Default for a Job that has been kicked off but not yet polled.
      If Len(Status) = 0 Then Status = "In Progress"

      If Len(ReportTypeText) <> 0 Then
        SuccessfulReportTypes.Add(ReportTypeText, True, True)

        AlertMessage = String.Format("{0} status is {1}.", ReportTypeText, Status)
        Select Case Status
          Case "Success"
            WarningLevel = isefinWarningLevel.Low
          Case "Failed", "Timeout"
            WarningLevel = isefinWarningLevel.Critical
          Case Else
            WarningLevel = isefinWarningLevel.Medium
        End Select

        ' Link the alert to the report's detail block, which only exists once the report has succeeded (anchor "#Report_<reportId>", matching the Reports table's Report Id link).
        If StrComp(Status, "Success", CompareMethod.Text) = 0 AndAlso Len(JobId) <> 0 Then
          Warnings.AddWarning(AlertMessage,,, WarningLevel, "#Report_" & JobId)
        Else
          Warnings.AddWarning(AlertMessage,,, WarningLevel)
        End If
      End If
    End If
  Next

  ' Failed CreateReport logs - surface one Critical alert per ReportType that never succeeded at the /reports POST stage (e.g. an invalid Report Code that Basiq returns 400 for, or a 5xx that the 2-attempt retry could not recover from). The framework loader skips populating ExResponse on Failed logs but ProductId is set, so we identify the Failed CreateReport logs by ProductId and hydrate the typed Response on demand to recover the originating ReportType. Deduped by ReportType against SuccessfulReportTypes (built above) so a 5xx-then-success retry does NOT double-warn, and against FailedReportTypesSeen to avoid duplicating when a code has multiple failed attempts.
  For Each ServiceLog As ISServiceLog In serviceLogs
    If ServiceLog.RequestStatus = iseAuditLogStatus.Failed AndAlso ServiceLog.ProductId = "CreateReport" Then
      FailedReportType = ""
      FailedResponse = Nothing
      If finBL.CreditBureau.GetBankAccountEnquiryResponseFromServiceLog(ServiceLog, FailedResponse) Then
        FailedCreateReport = TryCast(FailedResponse, ISBankAccountEnquiryResponse_Basiq_CreateReport)
        If FailedCreateReport IsNot Nothing AndAlso FailedCreateReport.Request_CreateReport IsNot Nothing Then
          FailedReportType = FailedCreateReport.Request_CreateReport.ReportType
        End If
      End If

      If Len(FailedReportType) <> 0 AndAlso Not SuccessfulReportTypes.Exists(FailedReportType, True) AndAlso Not FailedReportTypesSeen.Exists(FailedReportType, True) Then
        FailedReportTypesSeen.Add(FailedReportType, True, True)

        ' Trim FailedReason to its first line - the underlying mApplication.Error.Message string typically appends stack-trace context that would otherwise overwhelm the alerts panel.
        FailedReason = ServiceLog.FailedReason
        If InStr(FailedReason, vbCrLf) > 0 Then FailedReason = Left(FailedReason, InStr(FailedReason, vbCrLf) - 1)
        If InStr(FailedReason, vbLf) > 0 Then FailedReason = Left(FailedReason, InStr(FailedReason, vbLf) - 1)

        Warnings.AddWarning(String.Format("{0} could not be requested: {1}", FailedReportType, FailedReason),,, isefinWarningLevel.Critical)
      End If
    End If
  Next

  ' Out of Date Warning - one row per stale Account across the collated list
  If Accounts IsNot Nothing AndAlso Accounts.data IsNot Nothing Then
    For Each AccountItem As ProxyObjects.Basiq.Account In Accounts.data
      If AccountItem.IS_LastUpdatedDate <> Nothing Then
        Days = CInt(DateDiff(DateInterval.Day, AccountItem.IS_LastUpdatedDate, finBL.TimeZoneFunctions.GetCurrentLocalDateTime()))
        If Days > OutOfDateWarningDays Then
          Warnings.AddWarning(String.Format("Account '{0}': Data is {1} days old.", AccountItem.name, Days),,, isefinWarningLevel.Critical)
        End If
      End If
    Next
  End If

  ' Add Alerts
  If Warnings.Count <> 0 Then
    SummaryTable = SummaryTables.CreateSummaryTableInformation("Alerts", "Alerts", 2)
    SummaryTable.TextAfter = Warnings.GetHtmlTemplateText()

    Basiq_TabularTableHeaderRowUpdate(SummaryTable)
    SummaryTables.Add("Alerts", SummaryTable)
  End If

  Return SummaryTables

End Function

Private Function Basiq_AuthLinks(serviceLogs As ISServiceLogs) As ISSummaryTables

  Dim AuthLinkUrl As String
  Dim i As Integer
  Dim IsExpired As Boolean
  Dim Payload As ProxyObjects.Basiq.AuthLink
  Dim ResponseCreateAuthLink As ISBankAccountEnquiryResponse_Basiq_CreateAuthLink
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  ' Auth Links - section header (one Information sub-table per CreateAuthLink Service Log).
  SummaryTables.AddSummaryTableBlank("AuthLinks", "Auth Links", "<div/>", "AuthLinks", 2)
  i = 0
  For Each ServiceLog As ISServiceLog In serviceLogs
    If ServiceLog.ExResponse IsNot Nothing Then
      Select Case ServiceLog.ExResponse.GetType()
        Case GetType(ISBankAccountEnquiryResponse_Basiq_CreateAuthLink)
          ResponseCreateAuthLink = DirectCast(ServiceLog.ExResponse, ISBankAccountEnquiryResponse_Basiq_CreateAuthLink)
          Payload = ResponseCreateAuthLink.Payload

          If Payload IsNot Nothing Then
            ' Treat the link as expired when expiresAt is past, OR when the parent enquiry is no longer in-progress.
            IsExpired = (Payload.IS_ExpiresAtUtcDate <> Nothing AndAlso Payload.IS_ExpiresAtUtcDate < finBL.TimeZoneFunctions.GetCurrentUtcDateTime()) OrElse (serviceLogs(0).ResponseStatus <> iseServiceLogResponseStatus.InProgress)

            AuthLinkUrl = ResponseCreateAuthLink.ConsentUrl

            SummaryTable = SummaryTables.CreateSummaryTableInformation(Payload.userId, "AuthLink" & CStr(i), 3,,, TestMode)
            With SummaryTable
              ' Auth Link URL - hyperlinked when the link is still active.
              If IsExpired Then
                .Rows.AddCaptionText("Auth Link:", AuthLinkUrl)
              Else
                .Rows.AddCaptionText("Auth Link:", AuthLinkUrl).Cells(1).HyperlinkSetExternal(AuthLinkUrl)
              End If
              .AddRowCaptionText("Mobile:", Payload.mobile)
              .AddRowCaptionText("User Id:", Payload.userId)
              .AddRowCaptionDateTime("Created At:", ServiceLog.CreatedDate)

              ' Expires At - flag in red when expired.
              If IsExpired AndAlso Payload.IS_ExpiresAtDate <> Nothing Then
                .Rows.AddCaptionDateTime("Expires At:", Payload.IS_ExpiresAtDate, "Expired").BackgroundColour = "#FFB6C1"
              Else
                .AddRowCaptionDateTime("Expires At:", Payload.IS_ExpiresAtDate)
              End If
            End With
            Basiq_TabularTableHeaderRowUpdate(SummaryTable)
            SummaryTables.Add("AuthLink" & CStr(i), SummaryTable)
          End If
          i += 1
      End Select
    End If
  Next

  ' Reset if none found
  If i = 0 Then
    SummaryTables = finBL.CreateSummaryTables()
    SummaryTables.AddSummaryTableBlank("AuthLinks", "Auth Links", "<div/>", "AuthLinks", 2).TextAfter = "{{Warning|No Auth Links found.}}"
  End If

  Return SummaryTables

End Function

Private Function Basiq_ConsentStarted(serviceLogs As ISServiceLogs) As Boolean

  Dim ResponseGetUserJobs As ISBankAccountEnquiryResponse_Basiq_GetUserJobs
  Dim Started As Boolean

  ' Assume Not Started
  Started = False

  ' Basiq creates the verify-credentials / retrieve-accounts / retrieve-transactions Job records when the Client completes the consent journey, so the presence of at least one Job in any successful GetUserJobs payload is the explicit signal that the Client has interacted with the Auth Link. The most recent payload is checked first - GetUserJobs is re-fired post-consent (per J036556) so a freshly-non-empty payload overwrites any earlier empty one.
  For i As Integer = serviceLogs.Count - 1 To 0 Step -1
    If serviceLogs(i).RequestStatus = iseAuditLogStatus.Success AndAlso serviceLogs(i).ExResponse IsNot Nothing AndAlso TypeOf serviceLogs(i).ExResponse Is ISBankAccountEnquiryResponse_Basiq_GetUserJobs Then
      ResponseGetUserJobs = DirectCast(serviceLogs(i).ExResponse, ISBankAccountEnquiryResponse_Basiq_GetUserJobs)
      If ResponseGetUserJobs.Payload IsNot Nothing AndAlso ResponseGetUserJobs.Payload.data IsNot Nothing AndAlso ResponseGetUserJobs.Payload.data.Length <> 0 Then
        Started = True
      End If
    End If
    If Started Then Exit For
  Next

  Return Started

End Function

Private Function Basiq_WaitingForAuthorisation() As ISSummaryTables

  Dim SummaryTables As ISSummaryTables

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  ' Rendered in place of the full Alerts / Reports / Accounts / Transactions blocks while the Client has not yet completed the Basiq consent journey - nothing to surface beyond the wait state itself.
  SummaryTables.AddSummaryTableBlank("Alerts", "Alerts", "<div/>", "Alerts", 2).TextAfter = "{{Warning|Waiting for Client Authorisation.}}"

  Return SummaryTables

End Function

Private Function Basiq_EnquiryDetails(serviceLogs As ISServiceLogs,
                                      responseCreateUser As ISBankAccountEnquiryResponse_Basiq_CreateUser,
                                      serviceLogSourceObjects As finServiceLogSourceObjects) As ISSummaryTables

  Dim ApplicationShortcut As ISApplicationShortcut
  Dim BranchPk As Integer
  Dim ButtonText As String
  Dim ConsentUrl As String
  Dim CostCentreResolved As finCostCentreResolved
  Dim Days As Integer
  Dim DocumentId As String
  Dim IsLinkActive As Boolean
  Dim ResponseCreateAuthLink As ISBankAccountEnquiryResponse_Basiq_CreateAuthLink
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim User As ProxyObjects.Basiq.User
  Dim Warnings As String

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()
  BranchPk = 0
  ConsentUrl = ""
  IsLinkActive = False

  ' Determine the Branch
  If responseCreateUser IsNot Nothing AndAlso responseCreateUser.Request IsNot Nothing Then
    BranchPk = responseCreateUser.Request.BranchPk
  End If

  ' Cost Centre
  CostCentreResolved = finBL.CostCentresResolved.ItemByBranchPk(BranchPk)

  ' Enquiry Details
  SummaryTable = SummaryTables.CreateSummaryTableInformation("", "EnquiryDetails",,,, TestMode)
  With SummaryTable
    .AddRowCaptionUtcDateTimeWithTimeZone("Date:", responseCreateUser.EnquiryUtcDate, finBL.Settings.TimeZoneId, , True)

    If serviceLogSourceObjects.Client IsNot Nothing AndAlso Not serviceLogSourceObjects.Client.IsNew Then
      With .Rows.AddCaptionCodeDescription("Client:", serviceLogSourceObjects.Client.ClientId, serviceLogSourceObjects.Client.Name)
        .Cells(1).HyperlinkSetFormShow("Clients", serviceLogSourceObjects.Client.ClientId)
      End With
      .AddRowCaptionText("Name:", serviceLogSourceObjects.Client.Name, True)
    ElseIf serviceLogSourceObjects.AccountAppApplicant IsNot Nothing Then
      With .Rows.AddCaptionCodeDescription("Applicant:", serviceLogSourceObjects.AccountApp.AccountAppId, String.Format("{0} ({1})", serviceLogSourceObjects.AccountApp.Name, serviceLogSourceObjects.AccountAppApplicant.Name))
        .Cells(1).HyperlinkSetFormShow("AccountApps", serviceLogSourceObjects.AccountApp.AccountAppId, "Applicants")
      End With
      .AddRowCaptionText("Name:", serviceLogSourceObjects.AccountAppApplicant.Name, True)
    Else
      .AddRowCaptionText("Client:", "", True)
    End If

    ' Warnings
    Warnings = ""
    Days = CInt(DateDiff(DateInterval.Day, responseCreateUser.EnquiryUtcDate, finBL.TimeZoneFunctions.GetCurrentUtcDateTime()))
    If Days > OutOfDateWarningDays Then
       Warnings &= "{{Warning|This Report is " & CStr(Days) & " days old.}}"
    End If
    .TextAfter = Warnings
  End With
  Basiq_TabularTableHeaderRowUpdate(SummaryTable)
  SummaryTables.Add("EnquiryDetails", SummaryTable)

  ' User
  User = responseCreateUser.Payload
  SummaryTable = SummaryTables.CreateSummaryTableInformation("User", "User", 2,,, TestMode)
  If User IsNot Nothing Then
    With SummaryTable
      .AddRowCaptionText("User Id:", User.id)
      .AddRowCaptionText("Email:", User.email)
      .AddRowCaptionText("Mobile:", User.mobile)
      .AddRowCaptionText("First Name:", User.firstName)
      .AddRowCaptionText("Last Name:", User.lastName)
    End With
  End If
  Basiq_TabularTableHeaderRowUpdate(SummaryTable)
  SummaryTables.Add("User", SummaryTable)

  ' Is an Auth Link Active
  If serviceLogs(0).ResponseStatus = iseServiceLogResponseStatus.InProgress Then
    For Each ServiceLog As ISServiceLog In serviceLogs
      If ServiceLog.ExResponse IsNot Nothing Then
        Select ServiceLog.ExResponse.GetType()
          Case GetType(ISBankAccountEnquiryResponse_Basiq_CreateAuthLink)
            ResponseCreateAuthLink = DirectCast(ServiceLog.ExResponse, ISBankAccountEnquiryResponse_Basiq_CreateAuthLink)
            If ResponseCreateAuthLink.Payload IsNot Nothing Then
              ConsentUrl = ResponseCreateAuthLink.ConsentUrl
              If Len(ConsentUrl) <> 0 Then
                IsLinkActive = True
              End If
            End If
        End Select
      End If
    Next
  End If

  ' Actions
  SummaryTable = SummaryTables.CreateSummaryTableInformation("Actions", "Actions", 2,,, TestMode)
  With SummaryTable
    With .Actions
      If (serviceLogSourceObjects.Client IsNot Nothing AndAlso serviceLogSourceObjects.ClientLog IsNot Nothing) OrElse (serviceLogSourceObjects.AccountAppApplicant IsNot Nothing AndAlso serviceLogSourceObjects.AccountAppLog IsNot Nothing) Then
        ' Create Application Shortcut
        ApplicationShortcut = finBL.CreateApplicationShortcut()
        With ApplicationShortcut
          .Action = "FormShow"
          With .Parameters
            If serviceLogSourceObjects.Client IsNot Nothing Then
              ' Client
              .SetString("form", "DocumentCreateClient")
              .SetString("id", serviceLogSourceObjects.Client.ClientId)
              .SetInteger("replyLogPk", serviceLogSourceObjects.ClientLog.Pk)
              .SetInteger("serviceLogPk", serviceLogs(0).Pk)
              .SetInteger("serviceLogBranchPk", BranchPk)
            ElseIf serviceLogSourceObjects.AccountAppApplicant IsNot Nothing AndAlso serviceLogSourceObjects.AccountAppApplicant.ClientPk <> 0 Then
              .SetString("form", "DocumentCreateClient_AccountApp")
              .SetString("id", serviceLogSourceObjects.AccountAppApplicant.AccountApp.AccountAppId)
              .SetInteger("accountAppApplicantPk", serviceLogSourceObjects.AccountAppApplicant.Pk)
              .SetInteger("replyLogPk", serviceLogSourceObjects.AccountAppLog.Pk)
              .SetInteger("serviceLogPk", serviceLogs(0).Pk)
              .SetInteger("serviceLogBranchPk", BranchPk)
            Else
              ' Application (not linked to an existing Client)
              .SetString("form", "DocumentCreateClient_AccountApp")
              .SetString("id", serviceLogSourceObjects.AccountAppApplicant.AccountApp.AccountAppId)
              .SetInteger("accountAppApplicantPk", serviceLogSourceObjects.AccountAppApplicant.Pk)
              .SetInteger("replyLogPk", serviceLogSourceObjects.AccountAppLog.Pk)
              .SetInteger("serviceLogPk", serviceLogs(0).Pk)
              .SetInteger("serviceLogBranchPk", BranchPk)
            End If
          End With
        End With

        ' Email
        If IsLinkActive Then
          DocumentID = CostCentreResolved.Basiq.BankAccountEnquiryEmailDocumentId
          If Len(DocumentId) <> 0 Then
            ApplicationShortcut.Parameters.SetString("documentId", DocumentId)
            .AddApplicationShortcut("FormShowEmail", "Send Email", ApplicationShortcut).ShowInWebInterfaces = True
          End If
        End If

        ' SMS
        If IsLinkActive Then
          If finBL.Settings.AddOns.Messaging Then
            DocumentID = CostCentreResolved.Basiq.BankAccountEnquirySmsDocumentId
            If Len(DocumentId) <> 0 Then
              ApplicationShortcut.Parameters.SetString("documentId", DocumentId)
              .AddApplicationShortcut("FormShowSms", "Send SMS", ApplicationShortcut).ShowInWebInterfaces = True
            End If
          End If
        End If
      End If

      ' The action button triggers UpdateEnquiry while the enquiry is still in-progress; it re-runs idempotently until every selected Report has both JSON + PDF.
      ' Its label tracks the workflow phase ("Check Status" pre-CreateReport, "Refresh Reports" once at least one Report has been requested) so the user knows what clicking actually advances.
      ' Archive / Restore are deliberately NOT exposed for Basiq - revoking consent is destructive (per Cuscal); leaving the connection inactive retains data.
      If serviceLogs(0).ResponseStatus = iseServiceLogResponseStatus.InProgress Then
        ButtonText = Basiq_GetReportButtonText(serviceLogs)
        .AddApplicationShortcutUrl("GetReport", ButtonText, String.Format("App://Global?Type=BankAccountEnquiry.GetReport&ServiceLogPk={0}", ServiceLogs(0).Pk), True).ShowInWebInterfaces = True
      End If
    End With
  End With
  Basiq_TabularTableHeaderRowUpdate(SummaryTable)
  SummaryTables.Add("Actions", SummaryTable)

  Return SummaryTables

End Function

''' <summary>
'''  Returns the contextual label for the action button on the Basiq Bank Account Enquiry summary page.
'''  "Refresh Reports" once at least one successful CreateReport exists (we are polling / downloading reports); "Check Status" otherwise (waiting for consent, or downloading Accounts / Transactions / GetUserJobs prior to the first CreateReport).
'''  Same shortcut URL in both cases - only the label changes so the user sees what the next click is actually doing.
''' </summary>
Private Function Basiq_GetReportButtonText(serviceLogs As ISServiceLogs) As String

  Dim Result As String

  ' Initialise
  Result = "Check Status"

  If serviceLogs IsNot Nothing Then
    For Each ServiceLog As ISServiceLog In serviceLogs
      If ServiceLog.ExResponse IsNot Nothing AndAlso TypeOf ServiceLog.ExResponse Is ISBankAccountEnquiryResponse_Basiq_CreateReport AndAlso ServiceLog.RequestStatus = iseAuditLogStatus.Success Then
        Result = "Refresh Reports"
        Exit For
      End If
    Next
  End If

  Return Result

End Function

Private Function Basiq_Reports(serviceLogs As ISServiceLogs) As ISSummaryTables

  Dim AnyReports As Boolean
  Dim ReportId As String
  Dim ReportTypeText As String
  Dim Status As String
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()
  AnyReports = False

  ' Probe for any successful CreateReport — those are the Reports the User requested
  For Each ServiceLog As ISServiceLog In serviceLogs
    If ServiceLog.ExResponse IsNot Nothing AndAlso TypeOf ServiceLog.ExResponse Is ISBankAccountEnquiryResponse_Basiq_CreateReport Then
      AnyReports = True
      Exit For
    End If
  Next

  If Not AnyReports Then
    SummaryTables.AddSummaryTableBlank("Reports", "Reports", "<div/>", "Reports", 2).TextAfter = "{{Warning|No Reports requested.}}"
  Else
    SummaryTable = SummaryTables.CreateSummaryTableTabular("Reports", "Reports", 2, TestMode)
    With SummaryTable
      With .Columns
        .AddText("Report Type")
        .AddText("Status")
        .AddText("Report Id")
        .AddText("PDF")
      End With

      With .Rows
        For Each ServiceLog As ISServiceLog In serviceLogs
          If ServiceLog.ExResponse IsNot Nothing AndAlso TypeOf ServiceLog.ExResponse Is ISBankAccountEnquiryResponse_Basiq_CreateReport Then
            ReportTypeText = ""
            Status = ""
            ReportId = ""

            With DirectCast(ServiceLog.ExResponse, ISBankAccountEnquiryResponse_Basiq_CreateReport)
              If .Request_CreateReport IsNot Nothing Then
                ReportTypeText = .Request_CreateReport.ReportType
              End If
              If .Payload IsNot Nothing Then
                ReportId = .Payload.id
                Status = .Payload.IS_OverallStatusText
              End If
            End With

            ' Override with the latest GetJob status if this Job has been polled; otherwise the CreateReport response's own Job-stub status (set above) remains, defaulting below to "In Progress" when blank.
            If Len(ReportId) <> 0 Then
              For Each Inner_ServiceLog As ISServiceLog In serviceLogs
                If Inner_ServiceLog.ExResponse IsNot Nothing AndAlso TypeOf Inner_ServiceLog.ExResponse Is ISBankAccountEnquiryResponse_Basiq_GetJob Then
                  With DirectCast(Inner_ServiceLog.ExResponse, ISBankAccountEnquiryResponse_Basiq_GetJob)
                    If .Request_GetJob IsNot Nothing AndAlso .Request_GetJob.JobId = ReportId AndAlso .Payload IsNot Nothing Then
                      Status = .Payload.IS_OverallStatusText
                    End If
                  End With
                End If
              Next
            End If

            ' Default for a Job that has been kicked off but not yet polled.
            If Len(Status) = 0 Then Status = "In Progress"

            With .Add.Cells
              .AddText(ReportTypeText)
              .AddText(Status)
              ' Report Id cell - jump anchor to the per-report detail block built by Basiq_ReportData below; only enabled when the report has succeeded (an in-progress report has no JSON data to land on).
              If StrComp(Status, "Success", CompareMethod.Text) = 0 AndAlso Len(ReportId) <> 0 Then
                .AddText(ReportId).Hyperlink = "#Report_" & ReportId
              Else
                .AddText(ReportId)
              End If
              ' Surface the PDF link only when the report Job has succeeded - clicking fires the BankAccountEnquiry.SupplementalReport global action which finds the existing GetReport(PDF) Service Log (or fetches it from Basiq on first click), extracts the bytes, saves the PDF against the originating Client / Account Application via DocumentFiles, and opens the file directly. Same pattern as Akahu.
              If StrComp(Status, "Success", CompareMethod.Text) = 0 AndAlso Len(ReportId) <> 0 Then
                .AddWiki("++{{icon|DocumentType_PDF}}++").HyperlinkSetGlobalAction("BankAccountEnquiry.SupplementalReport", String.Format("ServiceLogPk={0}&ReportKey=PDF.{1}", serviceLogs(0).Pk, ReportId))
              Else
                .AddText("")
              End If
            End With
          End If
        Next
      End With
    End With
    Basiq_TabularTableHeaderRowUpdate(SummaryTable)
    SummaryTables.Add("Reports", SummaryTable)

    ' Per-report detail blocks. One block per successful CreateReport; the block's first cell carries the ElementId anchor so the Reports table's Report Id hyperlink lands on it. Block content depends on the report's typed data slice (see Basiq_ReportData_Statement / Basiq_ReportData_Affordability).
    For Each ServiceLog As ISServiceLog In serviceLogs
      If ServiceLog.ExResponse IsNot Nothing AndAlso TypeOf ServiceLog.ExResponse Is ISBankAccountEnquiryResponse_Basiq_CreateReport Then
        With DirectCast(ServiceLog.ExResponse, ISBankAccountEnquiryResponse_Basiq_CreateReport)
          If .Payload IsNot Nothing AndAlso Len(.Payload.id) <> 0 Then
            SummaryTables.AppendSummaryTables(Me.Basiq_ReportData(serviceLogs, .Payload.id))
          End If
        End With
      End If
    Next
  End If

  Return SummaryTables

End Function

Private Function Basiq_ReportData(serviceLogs As ISServiceLogs,
                                  reportId As String) As ISSummaryTables

  Dim AffordabilityData As ProxyObjects.Basiq.ReportDataAffordability
  Dim ReportEnvelope As ProxyObjects.Basiq.Report
  Dim ResponseGetReport As ISBankAccountEnquiryResponse_Basiq_GetReport
  Dim StatementData As ProxyObjects.Basiq.ReportDataStatement
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Initialise
  AffordabilityData = Nothing
  ReportEnvelope = Nothing
  ResponseGetReport = Nothing
  StatementData = Nothing
  SummaryTables = finBL.CreateSummaryTables()

  ' Locate the latest successful GetReport(JSON) for this reportId - the PDF response carries only binary bytes; only the JSON response has the typed data slice we want to render.
  For i As Integer = serviceLogs.Count - 1 To 0 Step -1
    If serviceLogs(i).ExResponse IsNot Nothing AndAlso TypeOf serviceLogs(i).ExResponse Is ISBankAccountEnquiryResponse_Basiq_GetReport Then
      ResponseGetReport = DirectCast(serviceLogs(i).ExResponse, ISBankAccountEnquiryResponse_Basiq_GetReport)
      If ResponseGetReport.Request_GetReport IsNot Nothing AndAlso ResponseGetReport.Request_GetReport.ReportId = reportId AndAlso ResponseGetReport.Request_GetReport.Format = iseCreditBureau_Basiq_ReportFormat.Json AndAlso ResponseGetReport.Payload IsNot Nothing Then
        ReportEnvelope = ResponseGetReport.Payload
        Exit For
      End If
      ResponseGetReport = Nothing
    End If
  Next

  ' Without the JSON envelope there is nothing to render - the user has only fetched the PDF, or the GetReport(JSON) is still pending. The Reports table still surfaces the PDF download.
  If ReportEnvelope Is Nothing Then
    SummaryTable = SummaryTables.CreateSummaryTableInformation("Report " & reportId, "Report_" & reportId, 3,,, TestMode)
    With SummaryTable
      With .Rows.AddCaptionText("Report Id:", reportId)
        .Cells(0).ElementId = "Report_" & reportId
      End With
      .TextAfter = "{{Warning|Report data not yet retrieved as JSON. Click 'Refresh Reports' to fetch.}}"
    End With
    Basiq_TabularTableHeaderRowUpdate(SummaryTable)
    SummaryTables.Add("Report_" & reportId, SummaryTable)
  Else
    ' Envelope sub-table - first cell carries the ElementId anchor so the Reports table hyperlink can jump here. Title falls back to the report id when Basiq did not supply one (older payloads).
    SummaryTable = SummaryTables.CreateSummaryTableInformation(If(Len(ReportEnvelope.title) <> 0, ReportEnvelope.title, "Report " & reportId), "Report_" & reportId, 3,,, TestMode)
    With SummaryTable
      With .Rows.AddCaptionText("Report Id:", ReportEnvelope.id)
        .Cells(0).ElementId = "Report_" & reportId
      End With
      .AddRowCaptionText("Title:", ReportEnvelope.title)
      .AddRowCaptionText("Report Type:", ReportEnvelope.reportType)
      .AddRowCaptionDateTime("Created:", ReportEnvelope.IS_CreatedDateDate)
      .AddRowCaptionText("Created By:", ReportEnvelope.createdBy)

    End With
    Basiq_TabularTableHeaderRowUpdate(SummaryTable)
    SummaryTables.Add("Report_" & reportId, SummaryTable)

    ' Filter sub-table - rendered as its own "Filter" category so the per-filter rows read cleanly. Captions map Basiq's camelCase names to human Title Case; array values are unwrapped from JArray.ToString()'s prettified [...] form to a comma-joined list.
    If ReportEnvelope.filters IsNot Nothing AndAlso ReportEnvelope.filters.Length <> 0 Then
      SummaryTable = SummaryTables.CreateSummaryTableInformation("Filter", "Report_" & reportId & "_Filter", 3,,, TestMode)
      With SummaryTable
        For Each FilterItem As ProxyObjects.Basiq.ReportFilter In ReportEnvelope.filters
          .AddRowCaptionText(Basiq_ReportData_FilterCaption(FilterItem.name) & ":", Basiq_ReportData_FilterValue(FilterItem.value))
        Next
      End With
      Basiq_TabularTableHeaderRowUpdate(SummaryTable)
      SummaryTables.Add("Report_" & reportId & "_Filter", SummaryTable)
    End If

    ' Dispatch on reportType to the typed renderer. For known types, the GetReport response exposes typed shortcuts (GetDataAsStatement / GetDataAsConsumerAffordability / GetDataAsBusinessAffordability) so the script doesn't have to do the GetType + TryCast dance. For unknown types, the generic ResponseGetReport.GetDataAs(payloadType) still works - new report types only need a new Case here and a typed proxy class.
    Select Case UCase(ReportEnvelope.reportType)
      Case "STATEMENT_01"
        StatementData = ResponseGetReport.GetDataAsStatement()
        If StatementData IsNot Nothing Then
          SummaryTables.AppendSummaryTables(Me.Basiq_ReportData_Statement(reportId, StatementData))
        End If
      Case "CON_AFFOR_01"
        AffordabilityData = ResponseGetReport.GetDataAsConsumerAffordability()
        If AffordabilityData IsNot Nothing Then
          SummaryTables.AppendSummaryTables(Me.Basiq_ReportData_Affordability(reportId, AffordabilityData))
        End If
      Case "BUS_AFFOR_01"
        AffordabilityData = ResponseGetReport.GetDataAsBusinessAffordability()
        If AffordabilityData IsNot Nothing Then
          SummaryTables.AppendSummaryTables(Me.Basiq_ReportData_Affordability(reportId, AffordabilityData))
        End If
    End Select

    ' Client Extension Demo - off by default; flip the ClientExtensionDemo constant at the top of the script to render the example block. Demonstrates the pattern a customisation would follow to surface a new (or alternative) report shape without modifying the Business Layer.
    If ClientExtensionDemo AndAlso StrComp(ReportEnvelope.reportType, "STATEMENT_01", CompareMethod.Text) = 0 Then
      SummaryTables.AppendSummaryTables(Me.Basiq_ReportData_ClientExtensionDemo(reportId, ResponseGetReport))
    End If
  End If

  Return SummaryTables

End Function

Private Function Basiq_ReportData_FilterCaption(filterName As String) As String

  ' Map Basiq's camelCase filter names (per the /reports POST contract: fromDate / toDate / users / accounts / includeMetrics / includeGroups) to human Title Case for the Summary Page. Unknown names fall back to the raw value so a future Basiq addition still renders something.
  Select Case filterName
    Case "fromDate"       : Return "From Date"
    Case "toDate"         : Return "To Date"
    Case "users"          : Return "Users"
    Case "accounts"       : Return "Accounts"
    Case "includeMetrics" : Return "Include Metrics"
    Case "includeGroups"  : Return "Include Groups"
    Case Else             : Return filterName
  End Select

End Function

Private Function Basiq_ReportData_FilterValue(value As Object) As String

  Dim Result As String

  ' Initialise
  Result = ""

  If value IsNot Nothing Then
    Result = value.ToString()

    ' Scalar values (Basiq returns "fromDate" / "toDate" as a single ISO date string) come back as the bare string and render verbatim. Array values (accounts, users) come back as a Newtonsoft JArray whose default ToString() emits prettified JSON: a leading "[", per-item lines wrapped in double-quotes and separated by commas, then a trailing "]". The summary-page script runtime cannot resolve Newtonsoft types directly (they live outside its referenced assembly set), so we detect the JSON-array shape by the leading "[" and brute-force strip the artefacts. The underlying tokens are UUIDs / ISO dates and never contain quotes or square brackets so the replace pass is safe.
    If Result.TrimStart().StartsWith("[") Then
      Result = Replace(Result, vbCrLf, " ")
      Result = Replace(Result, vbCr, " ")
      Result = Replace(Result, vbLf, " ")
      Result = Replace(Result, """", "")
      Result = Result.Trim()
      If Result.StartsWith("[") Then Result = Result.Substring(1)
      If Result.EndsWith("]") Then Result = Result.Substring(0, Result.Length - 1)
      While Result.Contains("  ")
        Result = Replace(Result, "  ", " ")
      End While
      Result = Result.Trim()
    End If
  End If

  Return Result

End Function

Private Function Basiq_ReportData_Statement(reportId As String,
                                            data As ProxyObjects.Basiq.ReportDataStatement) As ISSummaryTables

  Dim AddressParts As List(Of String)
  Dim AddressText As String
  Dim EmailsText As String
  Dim PhonesText As String
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Initialise
  AddressParts = New List(Of String)()
  AddressText = ""
  EmailsText = ""
  PhonesText = ""
  SummaryTables = finBL.CreateSummaryTables()

  ' Institution - issuing bank metadata captured at statement-generation time. Logo is embedded inline as an img element to keep the page self-contained for PDF export.
  If data.institution IsNot Nothing Then
    SummaryTable = SummaryTables.CreateSummaryTableInformation("Institution", "ReportInstitution_" & reportId, 3,,, TestMode)
    With SummaryTable
      If Len(data.institution.logo) <> 0 Then
        .Rows.AddCaptionHtml("Logo:", "<img style='max-height:24px;' src='" & finBL.HtmlEncode(data.institution.logo) & "' />")
      End If
      .AddRowCaptionText("Name:", data.institution.name)
      .AddRowCaptionText("ABN:", data.institution.abn)
      .AddRowCaptionText("ACN:", data.institution.acn)
    End With
    Basiq_TabularTableHeaderRowUpdate(SummaryTable)
    SummaryTables.Add("ReportInstitution_" & reportId, SummaryTable)
  End If

  ' Identity - account holder details. Personal name fields plus optional business / agent fields. Phone numbers and email arrays are joined inline because most holders have one of each and the array is rarely large enough to justify a sub-table.
  If data.identity IsNot Nothing Then
    SummaryTable = SummaryTables.CreateSummaryTableInformation("Identity", "ReportIdentity_" & reportId, 3,,, TestMode)
    With SummaryTable
      .AddRowCaptionText("Customer Type:", data.identity.customerType)
      .AddRowCaptionText("Full Name:", data.identity.fullName)
      .AddRowCaptionText("Title:", data.identity.title)
      If data.identity.IS_DOBDate <> Nothing Then .AddRowCaptionDate("DOB:", data.identity.IS_DOBDate)
      .AddRowCaptionText("Occupation Code:", data.identity.occupationCode)

      ' Phones / Emails - flatten arrays into comma-joined cells
      If data.identity.phoneNumbers IsNot Nothing AndAlso data.identity.phoneNumbers.Length <> 0 Then
        PhonesText = String.Join(", ", data.identity.phoneNumbers)
      End If
      .AddRowCaptionText("Phones:", PhonesText)
      If data.identity.emails IsNot Nothing AndAlso data.identity.emails.Length <> 0 Then
        EmailsText = String.Join(", ", data.identity.emails)
      End If
      .AddRowCaptionText("Emails:", EmailsText)

      ' Agent block - only renders when the customer is acting via an agent (power of attorney etc.). Skip the rows entirely when blank to keep the panel uncluttered.
      If Len(data.identity.agentName) <> 0 OrElse Len(data.identity.agentRole) <> 0 Then
        .AddRowCaptionText("Agent Name:", data.identity.agentName)
        .AddRowCaptionText("Agent Role:", data.identity.agentRole)
      End If

      ' Business block - only renders for business / sole-trader customers (customerType drives population from Basiq side).
      If Len(data.identity.businessName) <> 0 OrElse Len(data.identity.legalName) <> 0 OrElse Len(data.identity.abn) <> 0 Then
        .AddRowCaptionText("Business Name:", data.identity.businessName)
        .AddRowCaptionText("Legal Name:", data.identity.legalName)
        .AddRowCaptionText("ABN:", data.identity.abn)
        .AddRowCaptionText("ACN:", data.identity.acn)
      End If

      ' Physical addresses - flattened to one row per address; most identities only carry one. Skip blank parts so the joined output collapses cleanly when address lines are sparse.
      If data.identity.physicalAddresses IsNot Nothing Then
        For Each AddressItem As ProxyObjects.Basiq.ReportDataStatementIdentityAddress In data.identity.physicalAddresses
          AddressParts.Clear()
          If Len(AddressItem.addressLine1) <> 0 Then AddressParts.Add(AddressItem.addressLine1)
          If Len(AddressItem.addressLine2) <> 0 Then AddressParts.Add(AddressItem.addressLine2)
          If Len(AddressItem.addressLine3) <> 0 Then AddressParts.Add(AddressItem.addressLine3)
          If Len(AddressItem.city) <> 0 Then AddressParts.Add(AddressItem.city)
          If Len(AddressItem.state) <> 0 Then AddressParts.Add(AddressItem.state)
          If Len(AddressItem.postCode) <> 0 Then AddressParts.Add(AddressItem.postCode)
          If Len(AddressItem.country) <> 0 Then AddressParts.Add(AddressItem.country)
          AddressText = String.Join(", ", AddressParts.ToArray())
          .AddRowCaptionText("Address:", AddressText)
        Next
      End If
    End With
    Basiq_TabularTableHeaderRowUpdate(SummaryTable)
    SummaryTables.Add("ReportIdentity_" & reportId, SummaryTable)
  End If

  ' CDR Accreditation footer - required disclosure on every Consumer Data Right statement extract; surfaces who supplied the data and under what licence.
  If data.accreditation IsNot Nothing Then
    SummaryTable = SummaryTables.CreateSummaryTableInformation("CDR Accreditation", "ReportAccreditation_" & reportId, 3,,, TestMode)
    With SummaryTable
      .AddRowCaptionText("Entity:", data.accreditation.entityName)
      .AddRowCaptionText("Title:", data.accreditation.title)
      .AddRowCaptionText("Licence No:", data.accreditation.licenceNo)
      .AddRowCaptionText("Access Model:", data.accreditation.cdrAccessModel)
      .AddRowCaptionText("Description:", data.accreditation.description)
    End With
    Basiq_TabularTableHeaderRowUpdate(SummaryTable)
    SummaryTables.Add("ReportAccreditation_" & reportId, SummaryTable)
  End If

  ' Statement Accounts - the accounts whose transactions populated this statement. Headline balance / availableFunds plus status. Balance and Available Funds render as currency (thousands separator) via the IS_* Decimal helpers; negatives flag in red.
  If data.account IsNot Nothing AndAlso data.account.Length <> 0 Then
    SummaryTable = SummaryTables.CreateSummaryTableTabular("Statement Accounts", "ReportStatementAccounts_" & reportId, 3, TestMode)
    With SummaryTable
      With .Columns
        .AddText("Name")
        .AddText("Account No")
        .AddText("Holder")
        .AddText("Type")
        .AddText("Currency")
        .AddCurrency("Balance")
        .AddCurrency("Available Funds")
        .AddText("Status")
        .AddDateTime("Last Updated")
      End With

      With .Rows
        For Each AccountItem As ProxyObjects.Basiq.ReportDataStatementAccount In data.account
          With .Add.Cells
            .AddText(AccountItem.name)
            .AddText(AccountItem.accountNo)
            .AddText(AccountItem.accountHolder)
            .AddText(If(AccountItem.[class] IsNot Nothing, AccountItem.[class].IS_TypeText, ""))
            .AddText(AccountItem.currency)
            .AddCurrency(AccountItem.IS_Balance.GetValueOrDefault(), blankIfZero:=True).CellClass = If(AccountItem.IS_Balance.GetValueOrDefault() < 0, iseSummaryTableCellClass.Warning, iseSummaryTableCellClass.None)
            .AddCurrency(AccountItem.IS_AvailableFunds.GetValueOrDefault(), blankIfZero:=True).CellClass = If(AccountItem.IS_AvailableFunds.GetValueOrDefault() < 0, iseSummaryTableCellClass.Warning, iseSummaryTableCellClass.None)
            .AddText(AccountItem.status)
            .AddDateTime(AccountItem.IS_LastUpdatedDate,, True)
          End With
        Next
      End With
    End With
    Basiq_TabularTableHeaderRowUpdate(SummaryTable)
    SummaryTables.Add("ReportStatementAccounts_" & reportId, SummaryTable)
  End If

  Return SummaryTables

End Function

Private Function Basiq_ReportData_Affordability(reportId As String,
                                                data As ProxyObjects.Basiq.ReportDataAffordability) As ISSummaryTables

  Dim FrequencyDisplay As String
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Initialise
  FrequencyDisplay = ""
  SummaryTables = finBL.CreateSummaryTables()

  ' Metrics - flat list of derived affordability indicators (e.g. monthly income, gambling expense, surplus). 'sections' carries which report section the metric belongs to; 'format' (currency / integer / percentage / etc.) drives how the value is rendered. The proxy's IS_ValueAs* helpers do the type conversion once; the renderer just dispatches on format.
  If data.metrics IsNot Nothing AndAlso data.metrics.Length <> 0 Then
    SummaryTable = SummaryTables.CreateSummaryTableTabular("Metrics", "ReportMetrics_" & reportId, 3, TestMode)
    With SummaryTable
      With .Columns
        .AddText("Id")
        .AddText("Title")
        .AddText("Description")
        .AddText("Value")
        .AddText("Sections")
      End With

      With .Rows
        For Each MetricItem As ProxyObjects.Basiq.ReportDataAffordabilityMetric In data.metrics
          With .Add.Cells
            .AddText(MetricItem.id)
            .AddText(MetricItem.title)
            .AddText(MetricItem.description)

            ' Value - rendered according to the metric's declared format. Any format we haven't explicitly catered for falls through to the raw string so no information is lost; add Cases here as new formats are confirmed against live Basiq data (the openapi spec leaves 'format' as free-form string with no enum).
            If MetricItem.result Is Nothing Then
              .AddText("")
            Else
              ' Verified Basiq format values from a CON_AFFOR_01 metrics payload: 'money', 'integer', 'percent', 'boolean'. Anything else falls through to raw text.
              Select Case LCase(MetricItem.result.format)
                Case "money"
                  .AddCurrency(MetricItem.result.IS_ValueAsDecimal.GetValueOrDefault(), blankIfZero:=True).CellClass = If(MetricItem.result.IS_ValueAsDecimal.GetValueOrDefault() < 0, iseSummaryTableCellClass.Warning, iseSummaryTableCellClass.None)
                Case "integer"
                  With .AddInteger(MetricItem.result.IS_ValueAsInteger.GetValueOrDefault())
                    .TextAlign = iseSummaryTableCellTextAlign.Right
                  End With
                Case "percent"
                  ' Basiq emits percent values as whole-number-scale strings (e.g. '23.4' for 23.4%), not 0-1 fractions; just append the '%' glyph.
                  With .AddText(MetricItem.result.IS_ValueAsDecimal.GetValueOrDefault().ToString() & "%")
                    .TextAlign = iseSummaryTableCellTextAlign.Right
                  End With
                Case "boolean"
                  .AddText(If(StrComp(MetricItem.result.IS_ValueAsString, "true", CompareMethod.Text) = 0, "Yes", "No"))
                Case Else
                  With .AddText(MetricItem.result.IS_ValueAsString)
                    .TextAlign = iseSummaryTableCellTextAlign.Right
                  End With
              End Select
            End If

            .AddText(If(MetricItem.sections IsNot Nothing, String.Join(", ", MetricItem.sections), ""))
          End With
        Next
      End With
    End With
    Basiq_TabularTableHeaderRowUpdate(SummaryTable)
    SummaryTables.Add("ReportMetrics_" & reportId, SummaryTable)
  End If

  ' Groups - top-level categorisation (Income, Living Expenses, Loan Repayments etc.) with each group's analysis aggregate flattened into a row. Subgroups nest below in their own tables per group. Numeric columns are typed via the proxy's IS_ helpers (IS_Total / transactionCount / IS_Amount) so each cell renders in the right format; 'Frequency' stays as the display label and the per-cycle dollar value is split out into a separate 'Amount' column.
  If data.groups IsNot Nothing AndAlso data.groups.Length <> 0 Then
    SummaryTable = SummaryTables.CreateSummaryTableTabular("Groups", "ReportGroups_" & reportId, 3, TestMode)
    With SummaryTable
      With .Columns
        .AddText("Id")
        .AddText("Title")
        .AddText("Sections")
        .AddInteger("Transactions")
        .AddCurrency("Total")
        .AddText("Frequency")
        .AddCurrency("Amount")
        .AddDate("Range Start")
        .AddDate("Range End")
      End With

      With .Rows
        For Each GroupItem As ProxyObjects.Basiq.ReportDataAffordabilityGroup In data.groups
          FrequencyDisplay = ""
          If GroupItem.analysis IsNot Nothing AndAlso GroupItem.analysis.frequency IsNot Nothing Then FrequencyDisplay = GroupItem.analysis.frequency.display
          With .Add.Cells
            .AddText(GroupItem.id)
            .AddText(GroupItem.title)
            .AddText(If(GroupItem.sections IsNot Nothing, String.Join(", ", GroupItem.sections), ""))
            If GroupItem.analysis IsNot Nothing AndAlso GroupItem.analysis.summary IsNot Nothing AndAlso GroupItem.analysis.summary.transactionCount.HasValue Then
              .AddInteger(GroupItem.analysis.summary.transactionCount.Value)
            Else
              .AddText("")
            End If
            If GroupItem.analysis Is Nothing OrElse GroupItem.analysis.amount Is Nothing Then
              .AddText("")
            Else
              .AddCurrency(GroupItem.analysis.amount.IS_Total.GetValueOrDefault(), blankIfZero:=True).CellClass = If(GroupItem.analysis.amount.IS_Total.GetValueOrDefault() < 0, iseSummaryTableCellClass.Warning, iseSummaryTableCellClass.None)
            End If
            .AddText(FrequencyDisplay)
            If GroupItem.analysis Is Nothing OrElse GroupItem.analysis.frequency Is Nothing Then
              .AddText("")
            Else
              .AddCurrency(GroupItem.analysis.frequency.IS_Amount.GetValueOrDefault(), blankIfZero:=True).CellClass = If(GroupItem.analysis.frequency.IS_Amount.GetValueOrDefault() < 0, iseSummaryTableCellClass.Warning, iseSummaryTableCellClass.None)
            End If
            .AddDate(If(GroupItem.analysis IsNot Nothing AndAlso GroupItem.analysis.range IsNot Nothing, GroupItem.analysis.range.IS_StartDate, Nothing))
            .AddDate(If(GroupItem.analysis IsNot Nothing AndAlso GroupItem.analysis.range IsNot Nothing, GroupItem.analysis.range.IS_EndDate, Nothing))
          End With
        Next
      End With
    End With
    Basiq_TabularTableHeaderRowUpdate(SummaryTable)
    SummaryTables.Add("ReportGroups_" & reportId, SummaryTable)

    ' Per-group subgroup tables - one per group when subgroups exist. Surfaces the recurring expense / income items that drove the parent group's metric (e.g. each individual employer paying into the Income group). Same typed-column convention as the Groups table above. Transactions are NOT expanded inline here - the affordability report can contain hundreds, and the per-transaction list lives behind the report's transactions endpoint URL if a developer wants the full pull.
    For Each GroupItem As ProxyObjects.Basiq.ReportDataAffordabilityGroup In data.groups
      If GroupItem.subgroup IsNot Nothing AndAlso GroupItem.subgroup.Length <> 0 Then
        SummaryTable = SummaryTables.CreateSummaryTableTabular(GroupItem.title & " - subgroups", "ReportGroupSub_" & reportId & "_" & GroupItem.id, 3, TestMode)
        With SummaryTable
          .ShowHiddenRowsCaption = "More subgroups..."
          .MaxDisplayRows = 50

          With .Columns
            .AddText("Id")
            .AddText("Name")
            .AddInteger("Transactions")
            .AddCurrency("Total")
            .AddText("Frequency")
            .AddCurrency("Amount")
          End With

          With .Rows
            For Each SubgroupItem As ProxyObjects.Basiq.ReportDataAffordabilitySubgroup In GroupItem.subgroup
              FrequencyDisplay = ""
              If SubgroupItem.analysis IsNot Nothing AndAlso SubgroupItem.analysis.frequency IsNot Nothing Then FrequencyDisplay = SubgroupItem.analysis.frequency.display
              With .Add.Cells
                .AddText(SubgroupItem.id)
                .AddText(SubgroupItem.name)
                If SubgroupItem.analysis IsNot Nothing AndAlso SubgroupItem.analysis.summary IsNot Nothing AndAlso SubgroupItem.analysis.summary.transactionCount.HasValue Then
                  .AddInteger(SubgroupItem.analysis.summary.transactionCount.Value)
                Else
                  .AddText("")
                End If
                If SubgroupItem.analysis Is Nothing OrElse SubgroupItem.analysis.amount Is Nothing Then
                  .AddText("")
                Else
                  .AddCurrency(SubgroupItem.analysis.amount.IS_Total.GetValueOrDefault(), blankIfZero:=True).CellClass = If(SubgroupItem.analysis.amount.IS_Total.GetValueOrDefault() < 0, iseSummaryTableCellClass.Warning, iseSummaryTableCellClass.None)
                End If
                .AddText(FrequencyDisplay)
                If SubgroupItem.analysis Is Nothing OrElse SubgroupItem.analysis.frequency Is Nothing Then
                  .AddText("")
                Else
                  .AddCurrency(SubgroupItem.analysis.frequency.IS_Amount.GetValueOrDefault(), blankIfZero:=True).CellClass = If(SubgroupItem.analysis.frequency.IS_Amount.GetValueOrDefault() < 0, iseSummaryTableCellClass.Warning, iseSummaryTableCellClass.None)
                End If
              End With
            Next
          End With
        End With
        Basiq_TabularTableHeaderRowUpdate(SummaryTable)
        SummaryTables.Add("ReportGroupSub_" & reportId & "_" & GroupItem.id, SummaryTable)
      End If
    Next
  End If

  ' Affordability Accounts - the accounts analysed for the report. Slightly different shape from the Bank Account Enquiry's own Accounts table (no isOwned / maskedNumber / meta) and adds credit limit. Balance / Available / Credit Limit render as currency via the IS_* Decimal helpers with negatives flagged in red.
  If data.accounts IsNot Nothing AndAlso data.accounts.Length <> 0 Then
    SummaryTable = SummaryTables.CreateSummaryTableTabular("Affordability Accounts", "ReportAffordabilityAccounts_" & reportId, 3, TestMode)
    With SummaryTable
      With .Columns
        .AddText("Name")
        .AddText("Account No")
        .AddText("Holder")
        .AddText("Type")
        .AddText("Currency")
        .AddCurrency("Balance")
        .AddCurrency("Available")
        .AddCurrency("Credit Limit")
        .AddText("Status")
        .AddDateTime("Last Updated")
      End With

      With .Rows
        For Each AccountItem As ProxyObjects.Basiq.ReportDataAffordabilityAccount In data.accounts
          With .Add.Cells
            .AddText(AccountItem.name)
            .AddText(AccountItem.accountNo)
            .AddText(AccountItem.accountHolder)
            .AddText(If(AccountItem.[class] IsNot Nothing, AccountItem.[class].IS_TypeText, ""))
            .AddText(AccountItem.currency)
            .AddCurrency(AccountItem.IS_Balance.GetValueOrDefault(), blankIfZero:=True).CellClass = If(AccountItem.IS_Balance.GetValueOrDefault() < 0, iseSummaryTableCellClass.Warning, iseSummaryTableCellClass.None)
            .AddCurrency(AccountItem.IS_AvailableFunds.GetValueOrDefault(), blankIfZero:=True).CellClass = If(AccountItem.IS_AvailableFunds.GetValueOrDefault() < 0, iseSummaryTableCellClass.Warning, iseSummaryTableCellClass.None)
            .AddCurrency(AccountItem.IS_CreditLimit.GetValueOrDefault(), blankIfZero:=True).CellClass = If(AccountItem.IS_CreditLimit.GetValueOrDefault() < 0, iseSummaryTableCellClass.Warning, iseSummaryTableCellClass.None)
            .AddText(AccountItem.status)
            .AddDateTime(AccountItem.IS_LastUpdatedDate,, True)
          End With
        Next
      End With
    End With
    Basiq_TabularTableHeaderRowUpdate(SummaryTable)
    SummaryTables.Add("ReportAffordabilityAccounts_" & reportId, SummaryTable)
  End If

  Return SummaryTables

End Function

Private Function Basiq_History(serviceLogs As ISServiceLogs) 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)
          End With
        End With
      Next
    End With
  End With
  Basiq_TabularTableHeaderRowUpdate(SummaryTable)
  SummaryTables.Add("History", SummaryTable)

  Return SummaryTables

End Function

Private Sub Basiq_TabularTableHeaderRowUpdate(ByRef summaryTable As ISSummaryTable)

  If summaryTable IsNot Nothing Then
    If summaryTable.TableClass = iseSummaryTableClass.TabularData Then
      If summaryTable.Rows.Count <> 0 Then
        For Each Cell As ISSummaryTableCell In summaryTable.Rows(0).Cells
          Cell.ForegroundColour = TabularDataHeaderForegroundColour
        Next
      End If
    End If
  End If

End Sub

Private Function Basiq_Transactions(serviceLogs As ISServiceLogs) As ISSummaryTables

  Dim PreviousAccount As String
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim Transactions As ProxyObjects.Basiq.TransactionList

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()
  PreviousAccount = ""

  ' Collate every GetTransactions page into one TransactionList (UpdateResponseIS already applied)
  Transactions = finBL.CreditBureau.Service_Basiq.GetAllTransactions(serviceLogs)

  If Transactions Is Nothing OrElse Transactions.data Is Nothing OrElse Transactions.data.Length = 0 Then
    SummaryTables.AddSummaryTableBlank("Transactions", "Transactions", "<div/>", "Transactions", 2).TextAfter = "{{Warning|No Transactions found.}}"
  Else
    SummaryTable = SummaryTables.CreateSummaryTableTabular("Transactions", "Transactions", 2, TestMode)
    With SummaryTable
      .ShowHiddenRowsCaption = "More Transaction data..."
      .MaxDisplayRows = 20

      With .Columns
        .AddText("Account")
        .AddDateTime("Date")
        .AddText("Description")
        .AddCurrency("Amount")
        .AddText("Direction")
        .AddCurrency("Balance")
        .AddText("Status")
        .AddText("Class")
        .AddText("Institution")
      End With

      With .Rows
        For Each TransactionItem As ProxyObjects.Basiq.Transaction In Transactions.data
          With .Add
            With .Cells
              If StrComp(PreviousAccount, TransactionItem.account, CompareMethod.Text) = 0 Then
                .AddText("")
              Else
                .AddText(TransactionItem.account)
              End If
              .AddDateTime(TransactionItem.IS_TransactionDateDate,, True)
              .AddText(TransactionItem.description)
              .AddCurrency(TransactionItem.IS_Amount.GetValueOrDefault(), blankIfZero:=True).CellClass = If(TransactionItem.IS_Amount.GetValueOrDefault() < 0, iseSummaryTableCellClass.Warning, iseSummaryTableCellClass.None)
              .AddText(TransactionItem.IS_DirectionText)
              .AddCurrency(TransactionItem.IS_Balance.GetValueOrDefault(), blankIfZero:=True).CellClass = If(TransactionItem.IS_Balance.GetValueOrDefault() < 0, iseSummaryTableCellClass.Warning, iseSummaryTableCellClass.None)
              .AddText(TransactionItem.IS_StatusText)
              .AddText(TransactionItem.[class])
              .AddText(TransactionItem.institution)
            End With
          End With
          PreviousAccount = TransactionItem.account
        Next
      End With
    End With
    Basiq_TabularTableHeaderRowUpdate(SummaryTable)
    SummaryTables.Add("Transactions", SummaryTable)
  End If

  Return SummaryTables

End Function

Private Sub CreatePage_Basiq_CreateUser(serviceLogs As ISServiceLogs,
                                        htmlSummaryPage2StringBuilder As finHtmlSummaryPage2StringBuilder)

  Dim ClientName As String
  Dim ResponseCreateUser As ISBankAccountEnquiryResponse_Basiq_CreateUser
  Dim ServiceLogSourceObjects As finServiceLogSourceObjects

  ' Get Responses
  ResponseCreateUser = DirectCast(serviceLogs(0).ExResponse, ISBankAccountEnquiryResponse_Basiq_CreateUser)
  For i As Integer = serviceLogs.Count - 1 To 0 Step -1
    If serviceLogs(i).RequestStatus = iseAuditLogStatus.Success Then
      Select Case serviceLogs(i).ExResponse.GetType()
        Case GetType(ISBankAccountEnquiryResponse_Basiq_CreateUser)
          ResponseCreateUser = DirectCast(serviceLogs(i).ExResponse, ISBankAccountEnquiryResponse_Basiq_CreateUser)
      End Select
    End If
  Next

  ' Get Source Objects
  ServiceLogSourceObjects = finBL.CreateServiceLogSourceObjects()
  ServiceLogSourceObjects.Load(serviceLogs(0))

  ' Determine Client Name
  If ServiceLogSourceObjects.Client IsNot Nothing AndAlso Not ServiceLogSourceObjects.Client.IsNew Then
    ClientName = ServiceLogSourceObjects.Client.Name
  ElseIf ServiceLogSourceObjects.AccountAppApplicant IsNot Nothing Then
    ClientName = ServiceLogSourceObjects.AccountAppApplicant.Name
  Else
    ClientName = "No Associated Client - Imported log"
  End If

  With HtmlSummaryPage2StringBuilder
    ' Heading
    .AppendH1(ClientName)
    .AppendH2(String.Format("Bank Account Enquiry Report - {0}", ResponseCreateUser.ServiceName))

    .SummaryTablesAppend(Me.Basiq_EnquiryDetails(serviceLogs, ResponseCreateUser, ServiceLogSourceObjects))

    ' Reports / Accounts / Transactions only render once the Client has completed the consent journey - until then there is nothing to surface in those sections (Basiq has no Job records, no Accounts and no Transactions for the User). Show a single waiting warning in place of the usual Alerts block to keep the page minimal and actionable - the Auth Links section remains visible so the Client can be re-prompted with the consent URL.
    If Me.Basiq_ConsentStarted(serviceLogs) Then
      .SummaryTablesAppend(Me.Basiq_Alerts(serviceLogs))
      .SummaryTablesAppend(Me.Basiq_AuthLinks(serviceLogs))
      .SummaryTablesAppend(Me.Basiq_Accounts(serviceLogs))
      .SummaryTablesAppend(Me.Basiq_Transactions(serviceLogs))
      .SummaryTablesAppend(Me.Basiq_Reports(serviceLogs))
    Else
      .SummaryTablesAppend(Me.Basiq_WaitingForAuthorisation())
      .SummaryTablesAppend(Me.Basiq_AuthLinks(serviceLogs))
    End If

    .SummaryTablesAppend(Me.Basiq_History(serviceLogs))
  End With

End Sub

Private Function CreatePage(serviceLogs As ISServiceLogs,
                            response As ISBankAccountEnquiryResponse,
                            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("#1A56DB", "#1A56DB", "", "#E8E8E8")

    ' 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

  ' Get original Create Response
  Select Case Response.GetType()
    Case GetType(ISBankAccountEnquiryResponse_Basiq_CreateUser)
      Me.CreatePage_Basiq_CreateUser(ServiceLogs, HtmlSummaryPage2StringBuilder)

      Case Else
      ' Error
      finBL.Error.ErrorBeginFormat("Invalid Service Log. Unexpected response type '{0}'.", TypeName(Response))
  End Select

  ' Disclaimer
  HtmlSummaryPage2StringBuilder.Append("<hr/>")
  HtmlSummaryPage2StringBuilder.AppendLine("{{disclaimer|This report was produced by finPOWER Connect version " & finBL.VersionMajorMinorBuild & " using information retrieved from the " & response.ServiceName & " service on " & finBL.FormatDateTime(response.EnquiryDate, True, True, True) &"}}")

  ' Finalise HTML
  HtmlSummaryPage2StringBuilder.HtmlFinalise()

  ' Resolve Templates
  html = HtmlSummaryPage2StringBuilder.ToString(True)

  Return Success

End Function

' #################################################################
' Client Extension Demo
'
' This section illustrates how a customisation can render Basiq report data using a proxy class defined inside the script itself - i.e. without modifying the Business Layer.
'
' Why it matters: the Basiq integration deliberately accepts any reportType string on the request side; if a new report type is added (by Basiq, or as a tenant-specific extension) the response wrapper's GetDataAs(payloadType) helper still works. A customisation only needs to:
'   1. Define a local proxy class matching the JSON fields it cares about.
'   2. Call responseGetReport.GetDataAs(GetType(MyLocalProxy)) to get a populated instance.
'   3. Render the fields it wants.
'
' The Business Layer is not touched. The local proxy can model a subset of the JSON - only the fields the renderer actually reads need to be declared.
'
' To enable, flip ClientExtensionDemo to True near the top of this script. The demo renders only for STATEMENT_01 reports.
' #################################################################

Private Function Basiq_ReportData_ClientExtensionDemo(reportId As String,
                                                      responseGetReport As ISBankAccountEnquiryResponse_Basiq_GetReport) As ISSummaryTables

  Dim AccountNames As List(Of String)
  Dim DemoData As BasiqDemo_Statement
  Dim FirstAccount As BasiqDemo_StatementAccount
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Initialise
  AccountNames = New List(Of String)()
  DemoData = Nothing
  FirstAccount = Nothing
  SummaryTables = finBL.CreateSummaryTables()

  ' Resolve the JSON 'data' field into the script-local proxy. The Business Layer has no knowledge of BasiqDemo_Statement; GetDataAs just deserialises the captured JObject into whatever Type the caller hands in. If the caller's proxy has more / fewer fields than the JSON, the extras are ignored (missing) or left at their default (extra on the proxy).
  DemoData = TryCast(responseGetReport.GetDataAs(GetType(BasiqDemo_Statement)), BasiqDemo_Statement)

  If DemoData Is Nothing Then
    SummaryTable = SummaryTables.CreateSummaryTableInformation("Client Extension Demo", "ReportClientDemo_" & reportId, 3,,, TestMode)
    SummaryTable.TextAfter = "{{Warning|GetDataAs returned Nothing - either no data was captured, or the JSON failed to deserialise into BasiqDemo_Statement.}}"
    Basiq_TabularTableHeaderRowUpdate(SummaryTable)
    SummaryTables.Add("ReportClientDemo_" & reportId, SummaryTable)
  Else
    SummaryTable = SummaryTables.CreateSummaryTableInformation("Client Extension Demo", "ReportClientDemo_" & reportId, 3,,, TestMode)
    With SummaryTable
      .TextBefore = "{{info|This block is rendered by ''Basiq_ReportData_ClientExtensionDemo'' using a proxy class defined inside this script (''BasiqDemo_Statement''), NOT the typed proxy in the Business Layer. It proves the GetDataAs pattern that lets customisations add support for new Basiq report types without modifying the Business Layer.}}"

      ' Institution
      If DemoData.institution IsNot Nothing Then
        .AddRowCaptionText("Institution (demo):", DemoData.institution.name)
        .AddRowCaptionText("ABN (demo):", DemoData.institution.abn)
      End If

      ' Identity
      If DemoData.identity IsNot Nothing Then
        .AddRowCaptionText("Full Name (demo):", DemoData.identity.fullName)
        .AddRowCaptionText("Customer Type (demo):", DemoData.identity.customerType)
      End If

      ' Accounts - collapse to a single row with a comma-joined list; mirrors the principle that the local proxy renderer only needs to surface what the customisation cares about, even if the JSON carries more.
      If DemoData.account IsNot Nothing AndAlso DemoData.account.Length <> 0 Then
        For Each AccountItem As BasiqDemo_StatementAccount In DemoData.account
          AccountNames.Add(AccountItem.name)
        Next
        .AddRowCaptionText("Accounts (demo):", String.Join(", ", AccountNames.ToArray()))

        ' Highlight the first account's balance to demonstrate that any field on the proxy is fair game once deserialisation succeeds.
        FirstAccount = DemoData.account(0)
        If FirstAccount IsNot Nothing Then
          .AddRowCaptionText("First Account Balance (demo):", FirstAccount.balance)
        End If
      Else
        .AddRowCaptionText("Accounts (demo):", "(none)")
      End If
    End With
    Basiq_TabularTableHeaderRowUpdate(SummaryTable)
    SummaryTables.Add("ReportClientDemo_" & reportId, SummaryTable)
  End If

  Return SummaryTables

End Function

' #################################################################
' Local Proxy Classes for the Client Extension Demo
'
' These mirror the STATEMENT_01 JSON 'data' shape, but only carry the subset of fields the demo above renders. A real customisation would define just the classes / fields it cares about - everything else in the JSON is silently ignored at deserialisation.
'
' Convention checklist (matches the Business Layer proxy convention - see /coding-standards §7.4.1):
'   - One Public Sub New per class with parameter names matching JSON field names (Newtonsoft matches by name).
'   - Public ReadOnly Property per field, defaulting to "" / Nothing / 0 as appropriate.
'   - The constructor assigns to the backing field (_field) the auto-property generates.
'   - No parameterless constructor.
'   - No UpdateResponseIS method is required when the proxy doesn't need IS_-prefixed Intersoft conversions; if needed, define a Public Sub UpdateResponseIS(service As ISServiceBasiq) and GetDataAs will invoke it via reflection.
' #################################################################

''' <summary>
'''  Script-local proxy for the STATEMENT_01 data envelope. Carries only the fields this demo renders.
''' </summary>
Public Class BasiqDemo_Statement

  Public Sub New(institution As BasiqDemo_StatementInstitution,
                 identity As BasiqDemo_StatementIdentity,
                 account As BasiqDemo_StatementAccount())
    _institution = institution
    _identity = identity
    _account = account
  End Sub

  Public ReadOnly Property institution As BasiqDemo_StatementInstitution = Nothing
  Public ReadOnly Property identity As BasiqDemo_StatementIdentity = Nothing
  Public ReadOnly Property account As BasiqDemo_StatementAccount() = Nothing

End Class

''' <summary>
'''  Script-local proxy for STATEMENT_01 data.institution. Subset of the BL proxy's fields.
''' </summary>
Public Class BasiqDemo_StatementInstitution

  Public Sub New(name As String,
                 abn As String)
    _name = name
    _abn = abn
  End Sub

  Public ReadOnly Property name As String = ""
  Public ReadOnly Property abn As String = ""

End Class

''' <summary>
'''  Script-local proxy for STATEMENT_01 data.identity. Subset of the BL proxy's fields.
''' </summary>
Public Class BasiqDemo_StatementIdentity

  Public Sub New(fullName As String,
                 customerType As String)
    _fullName = fullName
    _customerType = customerType
  End Sub

  Public ReadOnly Property fullName As String = ""
  Public ReadOnly Property customerType As String = ""

End Class

''' <summary>
'''  Script-local proxy for STATEMENT_01 data.account[]. Subset of the BL proxy's fields.
''' </summary>
Public Class BasiqDemo_StatementAccount

  Public Sub New(name As String,
                 accountNo As String,
                 balance As String)
    _name = name
    _accountNo = accountNo
    _balance = balance
  End Sub

  Public ReadOnly Property name As String = ""
  Public ReadOnly Property accountNo As String = ""
  Public ReadOnly Property balance As String = ""

End Class
