' SummaryPage2_BankAccountEnquiryReport_Akahu
Option Explicit On
Option Strict On

' #################################################################
' Akahu Bank Account Report Summary Page Script
'
' Version: 1.01 (12/06/2026)
'
' Usage: Bank Account Enquiry and Log forms
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.00  18/03/2026  ISS      J035834   Created
'    1.01  12/06/2026  ISS      J036728   Add Apply Referrals support (Create Referral Redemption root)
' #################################################################

'#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

' 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." & "Nothing")
    Else
      Select Case ServiceLogs(0).ExResponse.GetType()
        Case GetType(ISBankAccountEnquiryResponse_Akahu_ApplyCreateApplication), GetType(ISBankAccountEnquiryResponse_Akahu_ApplyCreateReferralRedemption)
          Response = DirectCast(ServiceLogs(0).ExResponse, ISBankAccountEnquiryResponse)
        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 = CreatePage(ServiceLogs, Response, text)
    End Select
  End If

End Function

Public Function Akahu_Alerts(serviceLogs As ISServiceLogs) As ISSummaryTables

  Dim AllowMultipleSubmissions As Boolean
  Dim ApplicationStatusText As String
  Dim ClosingBalance As Decimal
  Dim DateEnd As Date
  Dim DateStart As Date
  Dim Days As Integer
  Dim HasReports As Boolean
  Dim HasSharingRequests As Boolean
  Dim OpeningBalance As Decimal
  Dim PageCount As Integer
  Dim RedemptionStatusText As String
  Dim ReferrerName As String
  Dim SharingRequestPayLoad As ProxyObjects.Akahu.Apply.SharingRequest
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim WarningLevel As isefinWarningLevel
  Dim Warnings As finWarnings
  
  ' Create Objects
  SummaryTables = finBL.CreateSummaryTables ()
  Warnings = finBL.CreateWarnings()
  
  ' Application
  WarningLevel =  isefinWarningLevel.None
  For Each ServiceLog As ISServiceLog In serviceLogs
    If ServiceLog.ExResponse IsNot Nothing Then  
      Select Case ServiceLog.ExResponse.GetType()
        Case GetType(ISBankAccountEnquiryResponse_Akahu_ApplyGetApplicationStatus)
          With DirectCast(ServiceLog.ExResponse, ISBankAccountEnquiryResponse_Akahu_ApplyGetApplicationStatus)
            If .Payload IsNot Nothing Then
              Select Case .Payload.IS_Status
                Case iseCreditBureau_Akahu_ApplyApplicationStatus.Active
                  WarningLevel = isefinWarningLevel.Medium
                Case iseCreditBureau_Akahu_ApplyApplicationStatus.Archived
                  WarningLevel = isefinWarningLevel.Low
              End Select
              ApplicationStatusText = String.Format("Application status is {0}.", .Payload.IS_StatusText)
            End If
          End With
      End Select  
    End If
  Next
  If Len(ApplicationStatusText) <> 0 Then Warnings.AddWarning(ApplicationStatusText,,, WarningLevel)

  ' Referral Redemption (Apply Referrals flow) - the latest status and the referring organisation
  RedemptionStatusText = ""
  ReferrerName = ""
  For Each ServiceLog As ISServiceLog In serviceLogs
    If ServiceLog.ExResponse IsNot Nothing Then
      Select Case ServiceLog.ExResponse.GetType()
        Case GetType(ISBankAccountEnquiryResponse_Akahu_ApplyCreateReferralRedemption)
          With DirectCast(ServiceLog.ExResponse, ISBankAccountEnquiryResponse_Akahu_ApplyCreateReferralRedemption)
            If .Payload IsNot Nothing Then
              RedemptionStatusText = .Payload.IS_StatusText
              If .Payload.referrer IsNot Nothing Then ReferrerName = .Payload.referrer.name
            End If
          End With
        Case GetType(ISBankAccountEnquiryResponse_Akahu_ApplyGetReferralRedemptionStatus)
          With DirectCast(ServiceLog.ExResponse, ISBankAccountEnquiryResponse_Akahu_ApplyGetReferralRedemptionStatus)
            If .Payload IsNot Nothing Then
              RedemptionStatusText = .Payload.IS_StatusText
              If .Payload.referrer IsNot Nothing Then ReferrerName = .Payload.referrer.name
            End If
          End With
      End Select
    End If
  Next
  If Len(RedemptionStatusText) <> 0 Then Warnings.AddWarning(String.Format("Referral Redemption status is {0}.", RedemptionStatusText),,, isefinWarningLevel.Low)
  If Len(ReferrerName) <> 0 Then Warnings.AddWarning(String.Format("Referred by {0}.", ReferrerName),,, isefinWarningLevel.Low)

  ' Sharing Requests
  HasSharingRequests = False
  For Each ServiceLog As ISServiceLog In serviceLogs
    If ServiceLog.ExResponse IsNot Nothing Then  
      Select Case ServiceLog.ExResponse.GetType()
        Case GetType(ISBankAccountEnquiryResponse_Akahu_ApplyCreateSharingRequest)
          With DirectCast(ServiceLog.ExResponse, ISBankAccountEnquiryResponse_Akahu_ApplyCreateSharingRequest)
            If .Payload IsNot Nothing Then
              Me.Akahu_GetLatestSharingRequest(servicelogs, .Payload._id, AllowMultipleSubmissions, SharingRequestPayLoad)
            End If
            If SharingRequestPayLoad IsNot Nothing
              If AllowMultipleSubmissions Then
                Warnings.AddWarning("This Sharing Request allows multiple submissions.",,, isefinWarningLevel.High)                
              End If
              If SharingRequestPayLoad.IS_LastSubmittedAtUtcDate <> Nothing Then
                Warnings.AddWarning(String.Format("This Sharing Request was completed on {0}.", finBL.FormatDateTimeLong(SharingRequestPayLoad.IS_LastSubmittedAtDate, , , True)),,, isefinWarningLevel.Low)                
              Else
                Warnings.AddWarning("This Sharing Request is in progress.",,, isefinWarningLevel.High)                
              End If
              If AllowMultipleSubmissions Then
                If SharingRequestPayLoad.IS_ExpiresAtDate <> Nothing Then
                  If finBL.Runtime.TimeZoneUtilities.GetCurrentLocalDate() > SharingRequestPayLoad.IS_ExpiresAtDate Then
                    Warnings.AddWarning(String.Format("This Sharing Request expired on {0}.", finBL.FormatDateTimeLong(SharingRequestPayLoad.IS_ExpiresAtDate, , , True)),,, isefinWarningLevel.Critical)
                  Else
                    Warnings.AddWarning(String.Format("This Sharing Request expires on {0}.", finBL.FormatDateTimeLong(SharingRequestPayLoad.IS_ExpiresAtDate, , , True)),,, isefinWarningLevel.High)
                  End If
                End If
              End If
            End If
            HasSharingRequests = True
            Exit For
          End With
      End Select  
    End If
  Next
  ' An Apply Referrals enquiry legitimately has no Sharing Request (the broker already collected the data)
  If Not HasSharingRequests AndAlso Not (TypeOf serviceLogs(0).ExResponse Is ISBankAccountEnquiryResponse_Akahu_ApplyCreateReferralRedemption) Then Warnings.AddWarning("No Sharing Requests found.",, , isefinWarningLevel.High, "#SharingRequests")
    
  ' Reports
  HasReports = False
  For Each ServiceLog As ISServiceLog In serviceLogs
    If ServiceLog.ExResponse IsNot Nothing Then  
      Select Case ServiceLog.ExResponse.GetType()
        Case GetType(ISBankAccountEnquiryResponse_Akahu_ApplyCreateReport)
          With DirectCast(ServiceLog.ExResponse, ISBankAccountEnquiryResponse_Akahu_ApplyCreateReport)
            If .Payload IsNot Nothing Then
              Select Case .Payload.IS_Status
                Case iseCreditBureau_Akahu_ApplyReportStatus.Completed
                  Warnings.AddWarning(String.Format("Report '{0}': Completed.", .Payload._id), , , isefinWarningLevel.Low, "#Report_" & .Payload._id)
                Case iseCreditBureau_Akahu_ApplyReportStatus.Failed
                  Warnings.AddWarning(String.Format("Report '{0}': Failed.", .Payload._id), , , isefinWarningLevel.High, "#Report_" & .Payload._id)
                Case iseCreditBureau_Akahu_ApplyReportStatus.Processing  
                  Warnings.AddWarning(String.Format("Report '{0}': Processing.", .Payload._id), , , isefinWarningLevel.Medium, "#Report_" & .Payload._id)
              End Select
              
              Akahu_AlertsByReportId(.Payload._id, servicelogs, DateStart, DateEnd, OpeningBalance, ClosingBalance, PageCount)
              
              ' Dates
              If DateStart = Nothing AndAlso DateEnd = Nothing Then
                Warnings.AddWarning(String.Format("Report '{0}': Could not determine date range.", .Payload._id),,, isefinWarningLevel.Critical, "#Report_" & .Payload._id)
              End If
              If DateStart = Nothing AndAlso DateEnd <> Nothing Then
                Warnings.AddWarning(String.Format("Report '{0}': Could not determine earliest date.", .Payload._id),,, isefinWarningLevel.Critical, "#Report_" & .Payload._id)
              End If
              If DateEnd = Nothing AndAlso DateStart <> Nothing Then
                Warnings.AddWarning(String.Format("Report '{0}': Could not determine latest date.", .Payload._id),,, isefinWarningLevel.Critical, "#Report_" & .Payload._id)
              End If
              If DateEnd <> Nothing Then
                Days = CInt(DateDiff(DateInterval.Day, DateEnd, finBL.TimeZoneFunctions.GetCurrentLocalDateTime()))
                If Days > OutOfDateWarningDays Then
                  Warnings.AddWarning(String.Format("Report '{0}': This is an OLD report, data is from {1} days ago.", .Payload._id, Days),,, isefinWarningLevel.Critical, "#Report_" & .Payload._id)
                End If
              End If
              If DateStart <> Nothing AndAlso DateEnd <> Nothing Then
                Warnings.AddWarning(String.Format("Report '{0}': Period {1:d} - {2:d}.", .Payload._id, DateStart, DateEnd),,, isefinWarningLevel.Low, "#Report_" & .Payload._id)
              End If
              
              ' Balances
              Warnings.AddWarning(String.Format("Report '{0}': Opening Balance {1:C2}.", .Payload._id, OpeningBalance),,, isefinWarningLevel.Low, "#Report_" & .Payload._id)
              Warnings.AddWarning(String.Format("Report '{0}': Closing Balance {1:C2}.", .Payload._id, ClosingBalance),,, isefinWarningLevel.Low, "#Report_" & .Payload._id)
              
              ' Pages
              If PageCount <> 0 Then
                Warnings.AddWarning(String.Format("Report '{0}': Processed pages {1}.", .Payload._id, PageCount),,, isefinWarningLevel.Low, "#Report_" & .Payload._id)
              End If
            End If
          End With
          HasReports = True
      End Select  
    End If
  Next
  If Not HasReports Then Warnings.AddWarning("No Reports found.", , , isefinWarningLevel.High, "#Reports")
    
  ' Add Alerts
  If Warnings.Count <> 0 Then
    SummaryTable = SummaryTables.CreateSummaryTableInformation("Alerts", "Alerts", 2)
    SummaryTable.TextAfter = Warnings.GetHtmlTemplateText()
    
    Akahu_TabularTableHeaderRowUpdate(SummaryTable)
    SummaryTables.Add("Alerts", SummaryTable)
  End If

  Return SummaryTables

End Function

Private Sub Akahu_AlertsByReportId(reportId As String,
                                   serviceLogs As ISServiceLogs,
                                   ByRef dateStart As Date, 
                                   ByRef dateEnd As Date, 
                                   ByRef openingBalance As Decimal, 
                                   ByRef closingBalance As Decimal, 
                                   ByRef pageCount As Integer)
  
  Dim Response_Akahu_ApplyGetReportData As ISBankAccountEnquiryResponse_Akahu_ApplyGetReportData
  
  ' Initialise ByRef
  dateStart = Nothing
  dateEnd = Nothing
  openingBalance = 0
  closingBalance = 0
  pageCount = 0
  
  ' Get the report
  Response_Akahu_ApplyGetReportData = Me.Akahu_GetLastReportDataById(serviceLogs, reportId)
  
  If Response_Akahu_ApplyGetReportData IsNot Nothing Then
    If Response_Akahu_ApplyGetReportData.HasDataSourceData Then
      For Each Item As ProxyObjects.Akahu.Apply.SourceItem In Response_Akahu_ApplyGetReportData.Payload.data_sources
        If Item.origin IsNot Nothing Then 
          pageCount += Item.origin.page_count.GetValueOrDefault()
        End If
      Next
    End If
    
    If Response_Akahu_ApplyGetReportData.HasAccountData Then
      For Each Item As ProxyObjects.Akahu.Apply.ReportAccountItem In Response_Akahu_ApplyGetReportData.Payload.accounts
        If Item.periods IsNot Nothing AndAlso item.periods.Length <> 0 Then
          For Each Period In Item.periods
            If datestart = Nothing OrElse Period.IS_StartDate < dateStart Then dateStart = Period.IS_StartDate
            If dateEnd = Nothing OrElse Period.IS_EndDate < dateEnd Then dateEnd = Period.IS_EndDate
            openingBalance += Period.opening_balance.GetValueOrDefault()
            closingBalance += Period.closing_balance.GetValueOrDefault()
          Next
        End If
      Next
    End If
  End If
  
End Sub

Private Function Akahu_EnquiryDetails(serviceLogs As ISServiceLogs,
                                      responseCreateApplication As ISBankAccountEnquiryResponse_Akahu_ApplyCreateApplication,
                                      accountApp As finAccountApp,
                                      accountAppApplicant As finAccountAppApplicant,
                                      client As finClient,
                                      accountAppLog As finAccountAppLog,
                                      clientLog As finClientLog) As ISSummaryTables

  Dim Application As ProxyObjects.Akahu.Apply.Application
  Dim ApplicationShortCut As ISApplicationShortcut
  Dim BranchPk As Integer
  Dim ButtonText As String
  Dim CostCentreResolved As finCostCentreResolved
  Dim Days As Integer
  Dim DocumentId As String
  Dim IsLinkActive As Boolean
  Dim ReferralRedemption As ProxyObjects.Akahu.Apply.ReferralRedemption
  Dim ResponseCreateSharingRequest As ISBankAccountEnquiryResponse_Akahu_ApplyCreateSharingRequest
  Dim RootResponse As ISBankAccountEnquiryResponse_Akahu
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim Warnings As String

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

  ' The root Service Log is a Create Application (consumer consent flow) or a Create Referral Redemption (Apply Referrals flow)
  RootResponse = DirectCast(serviceLogs(0).ExResponse, ISBankAccountEnquiryResponse_Akahu)

  ' Determine the Branch from the root Service Log
  If RootResponse IsNot Nothing AndAlso RootResponse.Request IsNot Nothing Then
    BranchPk = RootResponse.Request.BranchPk
  End If

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

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

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

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

  ' Referrer (Apply Referrals flow only) - the referring organisation and the latest Redemption timestamps
  If TypeOf serviceLogs(0).ExResponse Is ISBankAccountEnquiryResponse_Akahu_ApplyCreateReferralRedemption Then
    ReferralRedemption = Me.Akahu_GetLatestReferralRedemption(serviceLogs)
    If ReferralRedemption IsNot Nothing Then
      SummaryTable = SummaryTables.CreateSummaryTableInformation("Referrer", "Referrer",2,,, TestMode)
      With SummaryTable
        If ReferralRedemption.referrer IsNot Nothing Then
          .AddRowCaptionText("Referrer:", ReferralRedemption.referrer.name)
          If Len(ReferralRedemption.referrer.logo) <> 0 Then
            .Rows.AddCaptionHtml("Logo:", "<img style='max-height:48px;' src='" & finBL.HtmlEncode(ReferralRedemption.referrer.logo) & "' />")
          End If
        End If
        .AddRowCaptionDateTime("Created At:", ReferralRedemption.IS_CreatedAtDate)
        .AddRowCaptionDateTime("Updated At:", ReferralRedemption.IS_UpdatedAtDate)
      End With
      Akahu_TabularTableHeaderRowUpdate(SummaryTable)
      SummaryTables.Add("Referrer", SummaryTable)
    End If
  End If

  ' Application
  SummaryTable = SummaryTables.CreateSummaryTableInformation("Application", "Application",2,,, TestMode)
  Application = Me.Akahu_GetLastApplicationStatus(serviceLogs)
  If Application IsNot Nothing Then
    With SummaryTable
      If responseCreateApplication IsNot Nothing AndAlso responseCreateApplication.Request_ApplyCreateApplication IsNot Nothing Then
        .AddRowCaptionText("Reference:", responseCreateApplication.Request_ApplyCreateApplication.Reference)
      End If
      .AddRowCaptionText("Application Id:", Application._id)
      .AddRowCaptionText("Status:", Application.IS_StatusText)
      .AddRowCaptionDateTime("Created At:", Application.IS_CreatedAtDate)
      .AddRowCaptionDateTime("Updated At:", Application.IS_UpdatedAtDate)
      .AddRowCaptionDateTime("Last Applicant Submission At:", Application.IS_LastApplicantSubmissionAtDate)
      .AddRowCaptionDateTime("Archived At:", Application.IS_ArchivedAtDate)
    End With
    Akahu_TabularTableHeaderRowUpdate(SummaryTable)
    SummaryTables.Add("Application", SummaryTable)
  End If

  ' Is a Sharing Request 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_Akahu_ApplyCreateSharingRequest)
            ResponseCreateSharingRequest = DirectCast(ServiceLog.ExResponse, ISBankAccountEnquiryResponse_Akahu_ApplyCreateSharingRequest)
            If ResponseCreateSharingRequest.Payload IsNot Nothing Then
              If responseCreateSharingRequest.Payload.IS_ExpiresAtUtcDate >= finBL.TimeZoneFunctions.GetCurrentUtcDateTime() 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 (client IsNot Nothing AndAlso clientLog IsNot Nothing) OrElse (accountAppApplicant IsNot Nothing AndAlso accountAppLog IsNot Nothing) Then
        ' Create Application Shortcut
        ApplicationShortcut = finBL.CreateApplicationShortcut()
        With ApplicationShortCut
          .Action = "FormShow"
          With .Parameters
            If client IsNot Nothing Then
              ' Client
              .SetString("form", "DocumentCreateClient")
              .SetString("id", client.ClientId)
              .SetInteger("replyLogPk", clientLog.Pk)
              .SetInteger("serviceLogPk", serviceLogs(0).Pk)
              .SetInteger("serviceLogBranchPk", BranchPk)
            ElseIf accountAppApplicant IsNot Nothing AndAlso accountAppApplicant.ClientPk <> 0 Then
              .SetString("form", "DocumentCreateClient_AccountApp")
              .SetString("id", accountAppApplicant.AccountApp.AccountAppId)
              .SetInteger("accountAppApplicantPk", accountAppApplicant.Pk)
              .SetInteger("replyLogPk", accountAppLog.Pk)
              .SetInteger("serviceLogPk", serviceLogs(0).pk)
              .SetInteger("serviceLogBranchPk", BranchPk)
            Else
              ' Application (not linked to an existing Client)
              .SetString("form", "DocumentCreateClient_AccountApp")
              .SetString("id", accountAppApplicant.AccountApp.AccountAppId)
              .SetInteger("accountAppApplicantPk", accountAppApplicant.Pk)
              .SetInteger("replyLogPk", accountAppLog.Pk)
              .SetInteger("serviceLogPk", serviceLogs(0).Pk)
              .SetInteger("serviceLogBranchPk", BranchPk)
            End If
          End With
        End With

        ' Email
        If IsLinkActive Then
          DocumentID =  CostCentreResolved.Akahu.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.akahu.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
      
      Select Case serviceLogs(0).ResponseStatus
        Case iseServiceLogResponseStatus.InProgress
          ButtonText = Akahu_GetReportButtonText(serviceLogs)
          .AddApplicationShortcutUrl("GetReport", ButtonText, String.Format("App://Global?Type=BankAccountEnquiry.GetReport&ServiceLogPk={0}", ServiceLogs(0).Pk), True).ShowInWebInterfaces = True
        Case iseServiceLogResponseStatus.Complete
          If Application IsNot Nothing Then
            Select Case Application.IS_Status
              Case iseCreditBureau_Akahu_ApplyApplicationStatus.Active
                .AddApplicationShortcutUrl("Archive", "Archive Application", String.Format("App://Global?Type=BankAccountEnquiry.Archive&ServiceLogPk={0}", ServiceLogs(0).Pk), True).ShowInWebInterfaces = True
              Case iseCreditBureau_Akahu_ApplyApplicationStatus.Archived
                .AddApplicationShortcutUrl("Restore", "Restore Application", String.Format("App://Global?Type=BankAccountEnquiry.Restore&ServiceLogPk={0}", ServiceLogs(0).Pk), True).ShowInWebInterfaces = True
            End Select
          End If
        Case Else
          ' Ignore
      End Select
    End With
  End With
  Akahu_TabularTableHeaderRowUpdate(SummaryTable)
  SummaryTables.Add("Actions", SummaryTable)

  Return SummaryTables

End Function

''' <summary>
'''  Returns the contextual label for the Get Report action button on the Akahu Bank Account Enquiry summary page.
'''  "Refresh Report" once at least one successful Create Report exists (we are polling / downloading the Report); "Check Status" otherwise (waiting on the consumer's consent in the standard Apply flow, or on the Referral Redemption in the Apply Referrals flow).
'''  Same shortcut URL in both cases - only the label changes so the user sees what the next click is actually advancing.
''' </summary>
Private Function Akahu_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_Akahu_ApplyCreateReport AndAlso ServiceLog.RequestStatus = iseAuditLogStatus.Success Then
        Result = "Refresh Report"
        Exit For
      End If
    Next
  End If

  Return Result

End Function

''' <summary>
'''  Returns the most recent Referral Redemption payload (Apply Referrals flow), scanning the Service Logs newest-first so the referrer details and timestamps reflect the latest known state.
'''  Both the Create Referral Redemption root and any subsequent Get Referral Redemption Status logs carry the payload; the newest wins.
''' </summary>
Private Function Akahu_GetLatestReferralRedemption(serviceLogs As ISServiceLogs) As ProxyObjects.Akahu.Apply.ReferralRedemption

  Dim ReferralRedemption As ProxyObjects.Akahu.Apply.ReferralRedemption

  ' Initialise
  ReferralRedemption = Nothing

  For i As Integer = serviceLogs.Count - 1 To 0 Step -1
    If serviceLogs(i).ExResponse IsNot Nothing Then
      Select Case serviceLogs(i).ExResponse.GetType()
        Case GetType(ISBankAccountEnquiryResponse_Akahu_ApplyGetReferralRedemptionStatus)
          With DirectCast(serviceLogs(i).ExResponse, ISBankAccountEnquiryResponse_Akahu_ApplyGetReferralRedemptionStatus)
            ReferralRedemption = .Payload
            Exit For
          End With

        Case GetType(ISBankAccountEnquiryResponse_Akahu_ApplyCreateReferralRedemption)
          With DirectCast(serviceLogs(i).ExResponse, ISBankAccountEnquiryResponse_Akahu_ApplyCreateReferralRedemption)
            ReferralRedemption = .Payload
            Exit For
          End With
      End Select
    End If
  Next

  ' Return
  Return ReferralRedemption

End Function

Private Function Akahu_GetLastApplicationStatus(serviceLogs As ISServiceLogs) As ProxyObjects.Akahu.Apply.Application

  Dim Application As ProxyObjects.Akahu.Apply.Application
  
  ' Initialise
  Application = Nothing
  
  For i As Integer = serviceLogs.Count - 1 To 0 Step -1
    If serviceLogs(i).ExResponse IsNot Nothing Then
      Select Case serviceLogs(i).ExResponse.GetType()
        Case GetType(ISBankAccountEnquiryResponse_Akahu_ApplyCreateApplication)
          With DirectCast(serviceLogs(i).ExResponse, ISBankAccountEnquiryResponse_Akahu_ApplyCreateApplication)
            Application = .Payload
            Exit For
          End With
         
        Case GetType(ISBankAccountEnquiryResponse_Akahu_ApplyGetApplicationStatus)
          With DirectCast(serviceLogs(i).ExResponse, ISBankAccountEnquiryResponse_Akahu_ApplyGetApplicationStatus)
            Application = .Payload
            Exit For
          End With
      End Select
    End If
  Next

  ' Return
  Return Application
  
End Function  

Private Function Akahu_GetLastReportDataById(serviceLogs As ISServiceLogs,
                                             reportId As String) As ISBankAccountEnquiryResponse_Akahu_ApplyGetReportData
                                             
  Dim Response_Akahu_ApplyGetReportData As ISBankAccountEnquiryResponse_Akahu_ApplyGetReportData
  
  ' Initialise
  Response_Akahu_ApplyGetReportData = Nothing
  
  For i As Integer = serviceLogs.Count - 1 To 0 Step -1
    If serviceLogs(i).ExResponse IsNot Nothing Then
      Select Case serviceLogs(i).ExResponse.GetType()
        Case GetType(ISBankAccountEnquiryResponse_Akahu_ApplyGetReportData)
          Response_Akahu_ApplyGetReportData = DirectCast(serviceLogs(i).ExResponse, ISBankAccountEnquiryResponse_Akahu_ApplyGetReportData)
          With Response_Akahu_ApplyGetReportData
            If StrComp(.Request_ApplyGetReportData.ReportId, reportId, CompareMethod.Text) = 0 AndAlso .Payload IsNot Nothing Then
              Exit For
            End If
          End With
      End Select
    End If
  Next
  
  ' Return
  Return Response_Akahu_ApplyGetReportData
                                             
End Function

Private Function Akahu_GetLastReportStatusById(serviceLogs As ISServiceLogs,
                                            reportId As String) As ProxyObjects.Akahu.Apply.Report

  Dim Report As ProxyObjects.Akahu.Apply.Report
  
  ' Initialise
  Report = Nothing
  
  For i As Integer = serviceLogs.Count - 1 To 0 Step -1
    If serviceLogs(i).ExResponse IsNot Nothing Then
      Select Case serviceLogs(i).ExResponse.GetType()
        Case GetType(ISBankAccountEnquiryResponse_Akahu_ApplyCreateReport)
          With DirectCast(serviceLogs(i).ExResponse, ISBankAccountEnquiryResponse_Akahu_ApplyCreateReport)
            If .Payload IsNot Nothing AndAlso .Payload._id = reportId Then
              Report = .Payload
              Exit For
            End If
          End With
          
        Case GetType(ISBankAccountEnquiryResponse_Akahu_ApplyGetReportStatus)
          With DirectCast(serviceLogs(i).ExResponse, ISBankAccountEnquiryResponse_Akahu_ApplyGetReportStatus)
            If .Payload IsNot Nothing AndAlso .Payload._id = reportId Then
              Report = .Payload
              Exit For
            End If
          End With
      End Select
    End If
  Next
  
  ' Return
  Return Report
  
End Function                                      

Private Sub Akahu_GetLatestSharingRequest(serviceLogs As ISServiceLogs,
                                               sharingRequestId As String,
                                               ByRef allowMultipleSubmissions As Boolean,
                                               ByRef payload As ProxyObjects.Akahu.Apply.SharingRequest)
  
  ' Initialise ByRef
  allowMultipleSubmissions = True
  payload = Nothing
  
  For Each ServiceLog As ISServiceLog In serviceLogs
    If ServiceLog.ExResponse IsNot Nothing Then
      Select ServiceLog.ExResponse.GetType()
        Case GetType(ISBankAccountEnquiryResponse_Akahu_ApplyCreateSharingRequest)
          With DirectCast(serviceLog.ExResponse, ISBankAccountEnquiryResponse_Akahu_ApplyCreateSharingRequest)
            If .Payload IsNot Nothing AndAlso StrComp(.Payload._id, sharingRequestId, CompareMethod.Text) = 0 Then
              Payload = .Payload  
              allowMultipleSubmissions = .Request_ApplyCreateSharingRequest.AllowMultipleSubmissions
            End If
          End With
          
        Case GetType(ISBankAccountEnquiryResponse_Akahu_ApplyGetSharingRequestStatus)
          With DirectCast(serviceLog.ExResponse, ISBankAccountEnquiryResponse_Akahu_ApplyGetSharingRequestStatus)
            If .Payload IsNot Nothing AndAlso StrComp(.Payload._id, sharingRequestId, CompareMethod.Text) = 0 Then
              Payload = .Payload  
            End If
          End With
        
      End Select
    End If
  Next
 
End Sub

Private Function Akahu_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
  Akahu_TabularTableHeaderRowUpdate(SummaryTable)
  SummaryTables.Add("History", SummaryTable)

  Return SummaryTables

End Function

Private Function Akahu_ReportData(serviceLogs As ISServiceLogs,
                                  reportId As String) As ISSummaryTables
  
  Dim Account As String
  Dim BackgroundColour As String
  Dim ClosingBalance As Decimal
  Dim FirstRow As Boolean
  Dim OpeningBalance As Decimal
  Dim PageCount As Integer
  Dim Response_Akahu_ApplyGetReportData As ISBankAccountEnquiryResponse_Akahu_ApplyGetReportData
  Dim Source As String
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  
  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()
  PageCount = 0
  OpeningBalance = 0
  ClosingBalance = 0
  
  ' Find the Report Data
  Response_Akahu_ApplyGetReportData = Akahu_GetLastReportDataById(serviceLogs, reportId)
  
  If Response_Akahu_ApplyGetReportData Is Nothing Then
    Summarytables.AddSummaryTableBlank("ReportData_" & reportId, "Report Data", "No Report Data.", "", 3)
  Else
    If Response_Akahu_ApplyGetReportData.HasInsightsData Then
      SummaryTable = SummaryTables.CreateSummaryTableTabular("Insights", "Insights_" & reportId, 3, TestMode)
      With SummaryTable
        With .Columns
          .AddText("Description")
          .AddInteger("Value")
          .AddText("Code")
          .AddText("Failure Reason")
        End With
      End With

      For Each InsightItem As ProxyObjects.Akahu.Apply.ReportInsightItem In  Response_Akahu_ApplyGetReportData.Payload.insights
        With SummaryTable
          With .Rows.Add.Cells
            Select Case InsightItem.IS_Status
              Case iseCreditBureau_Akahu_ApplyReportInsightStatus.Failed
                BackgroundColour = "pink"
              Case Else
                BackgroundColour = ""
            End Select
            .AddText(InsightItem.description).BackgroundColour = BackgroundColour
            With .AddText(InsightItem.formatted)
              .BackgroundColour = BackgroundColour
              .TextAlign = iseSummaryTableCellTextAlign.Right
            End With
            .AddText(InsightItem.code).BackgroundColour = BackgroundColour
            Select Case InsightItem.IS_Status
              Case iseCreditBureau_Akahu_ApplyReportInsightStatus.Failed
                If InsightItem.failure_reason IsNot Nothing Then
                  .AddText(String.Format("{0}: {1}", Insightitem.failure_reason.IS_CodeText, InsightItem.failure_reason.message)).BackgroundColour = BackgroundColour
                Else
                  .AddText("").BackgroundColour = BackgroundColour
                End If
              Case Else
                .AddText("")
            End Select
          End With
        End With
      Next
      
      Akahu_TabularTableHeaderRowUpdate(SummaryTable)
      SummaryTables.Add("Insights_" & reportId, SummaryTable)
    Else
      Summarytables.AddSummaryTableBlank("Insights_" & reportId, "Insights", "No Insights data.", "", 3)
    End If
    
    ' Find all Datasources for this report
    If Response_Akahu_ApplyGetReportData.HasDataSourceData Then
      SummaryTable = SummaryTables.CreateSummaryTableTabular("DataSources", "DataSources_" & reportId, 3, TestMode)
      With SummaryTable
        With .Columns
          .AddText("Id")
          .AddText("Account")
          .AddText(" ")
          .AddText("Provider")
          .AddText("Origin Type")
          .AddText("Origin Filename")
          .AddInteger("Origin Page Count")
          .AddInteger("Origin Page Start")
          .AddInteger("Origin Page End")
          .AddBoolean("Origin Unreadable")
          .AddText("Status")
        End With
      End With    
      
      For Each DataSourceItem As ProxyObjects.Akahu.Apply.SourceItem In Response_Akahu_ApplyGetReportData.Payload.data_sources
        If DataSourceItem.origin IsNot Nothing Then PageCount += DataSourceItem.origin.page_count.GetValueOrDefault()
        With SummaryTable
          With .Rows
            With .Add
              With .Cells
                .AddText(datasourceitem._id)
                .AddText(DataSourceItem._account).Hyperlink = "#Account_" & DataSourceItem._account
                If DataSourceItem.provider IsNot Nothing Then
                  If Len(DataSourceItem.provider.logo) <> 0 Then
                    .AddHtml("<img style='width:24px; height:24px;' src='" & DataSourceItem.provider.logo & "' />")
                  Else
                    .AddText("")
                  End If
                  .AddText(DataSourceItem.provider.name)
                Else
                  .AddText("")
                  .AddText("")
                End If
                If DataSourceItem.origin IsNot Nothing Then
                  .AddText(DataSourceItem.origin.IS_TypeText)
                  .AddText(DataSourceItem.origin.filename)
                  If DataSourceItem.origin.page_count.HasValue Then
                    .AddInteger(DataSourceItem.origin.page_count.GetValueOrDefault())
                  Else
                    .AddText("")
                  End If
                  If DataSourceItem.origin.page_start.HasValue Then
                    .AddInteger(DataSourceItem.origin.page_start.GetValueOrDefault())
                  Else
                    .AddText("")
                  End If
                  If DataSourceItem.origin.page_end.HasValue Then
                    .AddInteger(DataSourceItem.origin.page_end.GetValueOrDefault())
                  Else
                    .AddText("")
                  End If
                  Select Case DataSourceItem.origin.unreadable
                    Case True
                      .AddText("True").BackgroundColour = "#ffcccc"
                    Case Else
                      .AddText("")
                  End Select
                Else
                  .AddText("")
                  .AddText("")
                  .AddText("")
                  .AddText("")
                  .AddText("")
                  .AddText("")
                End If
                .AddText(DataSourceItem.IS_StatusText)
              End With
            End With
          End With
        End With
      Next
      
      With SummaryTable.Rows.Add.Cells
        .AddText("")
        .AddText("")
        .AddText("")
        .AddText("")
        .AddText("")
        .AddText("")
        .AddInteger(PageCount).CellClass = iseSummaryTableCellClass.NormalBold
        .AddText("")
        .AddText("")
        .AddText("")
        .AddText("")
      End With
      Akahu_TabularTableHeaderRowUpdate(SummaryTable)
      SummaryTables.Add("DataSources_" & reportId, SummaryTable)
    Else
      Summarytables.AddSummaryTableBlank("DataSources_" & reportId, "DataSources", "No DataSources data.", "", 3)
    End If

    ' Find all Accounts for this report
    If Response_Akahu_ApplyGetReportData.HasAccountData Then
      SummaryTable = SummaryTables.CreateSummaryTableTabular("Accounts", "Accounts_" & reportId, 3, TestMode)
      With SummaryTable
        With .Columns
          .AddText("Id")
          .AddText("Type")
          .AddText("Identifier")
          .AddText("Name")
          .AddText("Holder")
          .AddText(" ")
          .AddText("Provider")
          .AddDate("Period Start")
          .AddDate("Period End")
          .AddCurrency("Limit")
          .AddCurrency("Opening Balance")
          .AddCurrency("Closing Balance")      
        End With
      End With
      
      For Each AccountItem As ProxyObjects.Akahu.Apply.ReportAccountItem In Response_Akahu_ApplyGetReportData.Payload.accounts
        FirstRow = True
        If AccountItem.periods IsNot Nothing AndAlso AccountItem.periods.Length <> 0 Then
          For Each PeriodItem As ProxyObjects.Akahu.Apply.Period In AccountItem.periods
            OpeningBalance += PeriodItem.opening_balance.GetValueOrDefault()
            ClosingBalance += PeriodItem.closing_balance.GetValueOrDefault()
            With SummaryTable
              With .Rows
                With .Add                  
                  With .Cells
                    If FirstRow Then
                      .AddText(AccountItem._id).Hyperlink = "#Account_" & AccountItem._id
                      .AddText(AccountItem.IS_TypeText)
                      .AddText(AccountItem.identifier)
                      .AddText(AccountItem.name)
                      .AddText(AccountItem.holder)
                      If AccountItem.provider IsNot Nothing Then
                        If Len(AccountItem.provider.logo) <> 0 Then
                          .AddHtml("<img style='width:24px; height:24px;' src='" & AccountItem.provider.logo & "' />")
                        Else
                          .AddText("")
                        End If
                        .AddText(AccountItem.provider.name)
                      Else
                        .AddText("")
                        .AddText("")
                      End If
                    Else
                      .AddText("")
                      .AddText("")
                      .AddText("")
                      .AddText("")
                      .AddText("")
                      .AddText("")
                      .AddText("")
                    End If
                    .AddDate(PeriodItem.IS_StartDate)
                    .AddDate(PeriodItem.IS_EndDate)
                    If PeriodItem.limit.HasValue Then
                      .AddCurrency(PeriodItem.limit.GetValueOrDefault())
                    Else
                      .AddText("")
                    End If
                    If PeriodItem.opening_balance.HasValue Then
                      If PeriodItem.opening_balance.GetValueOrDefault() < 0 Then
                        .AddCurrency(PeriodItem.opening_balance.GetValueOrDefault()).CellClass = iseSummaryTableCellClass.Warning
                      Else
                        .AddCurrency(PeriodItem.opening_balance.GetValueOrDefault()).CellClass = iseSummaryTableCellClass.Positive
                      End If
                    Else
                      .AddText("")
                    End If
                    If PeriodItem.closing_balance.HasValue Then
                      If PeriodItem.closing_balance.GetValueOrDefault() < 0 Then
                        .AddCurrency(PeriodItem.closing_balance.GetValueOrDefault()).CellClass = iseSummaryTableCellClass.Warning
                      Else
                        .AddCurrency(PeriodItem.closing_balance.GetValueOrDefault()).CellClass = iseSummaryTableCellClass.Positive
                      End If
                    Else
                      .AddText("")
                    End If
                    Firstrow = False
                  End With
                End With
              End With
            End With
          Next
        End If
      Next      
      
      With SummaryTable.Rows.Add.Cells
        .AddText("")
        .AddText("")
        .AddText("")
        .AddText("")
        .AddText("")
        .AddText("")
        .AddText("")
        .AddText("")
        .AddText("")
        .AddText("")
        If OpeningBalance < 0 Then
          .AddCurrency(OpeningBalance).CellClass = iseSummaryTableCellClass.WarningBold
        Else
          .AddCurrency(OpeningBalance).CellClass = iseSummaryTableCellClass.PositiveBold
        End If
        If ClosingBalance < 0 Then
          .AddCurrency(ClosingBalance).CellClass = iseSummaryTableCellClass.WarningBold
        Else
          .AddCurrency(ClosingBalance).CellClass = iseSummaryTableCellClass.PositiveBold
        End If
      End With    
      Akahu_TabularTableHeaderRowUpdate(SummaryTable)
      SummaryTables.Add("Accounts_" & reportId, SummaryTable)
    Else
      Summarytables.AddSummaryTableBlank("Accounts_" & reportId, "Accounts", "No Account data.", "", 3)
    End If
    
    ' Find all Transactions for this report
    If Response_Akahu_ApplyGetReportData.HasTransactionData Then
      SummaryTable = SummaryTables.CreateSummaryTableTabular("Transactions", "Transactions_" & reportId, 3, TestMode)
      With SummaryTable
        With .Columns
          .AddText("Account")
          .AddText("Source")
          .AddText("Action")
          .AddText("Type")
          .AddDateTime("Date")
          .AddText(" ")
          .AddText("Description")
          .AddCurrency("Amount")
          .AddCurrency("Balance")
          .AddText("NZ FCC")
          .AddText("Income Category")
          .AddText("Spending Category")
          .AddText("Other Account")
          .AddText("Other Loan Account")
          .AddText("Other Card Suffix")
        End With
      End With

      For Each ReportTransactionItem As ProxyObjects.Akahu.Apply.ReportTransactionItem In Response_Akahu_ApplyGetReportData.Payload.transactions
        With SummaryTable
          .ShowHiddenRowsCaption = "More Transaction data..."
          .MaxDisplayRows = 50
          With .Rows
            With .Add
              With .Cells
                If StrComp(Account, ReportTransactionItem._account, CompareMethod.Text) = 0 Then
                  .AddText("")
                Else
                  .AddText(ReportTransactionItem._account).ElementId = "Account_" & ReportTransactionItem._account
                End If
                If StrComp(Source, ReportTransactionItem._source, comparemethod.Text) = 0 Then
                  .AddText("")
                Else
                  .AddText(ReportTransactionItem._source)
                End If
                .AddText(ReportTransactionItem.IS_ActionText)
                .AddText(ReportTransactionItem.IS_TypeText)
                .AddDateTime(ReportTransactionItem.IS_Date)
                
                If ReportTransactionItem.merchant IsNot Nothing Then
                  If len(ReportTransactionItem.merchant.logo ) <> 0 Then
                    .AddHtml("<img style='width:24px; height:24px;' src='" & ReportTransactionItem.merchant.logo & "' />")
                  Else
                    .AddText("")
                  End If
                  .AddWiki(String.Format("**{0}** //{1}//", ReportTransactionItem.merchant.name, ReportTransactionItem.description))
                Else
                  .AddText("")
                  .AddText(ReportTransactionItem.description)
                End If                     
                
                If ReportTransactionItem.amount.HasValue Then
                  If ReportTransactionItem.amount.GetValueOrDefault() < 0 Then
                    .AddCurrency(ReportTransactionItem.amount.GetValueOrDefault()).CellClass = iseSummaryTableCellClass.Warning
                  Else
                    .AddCurrency(ReportTransactionItem.amount.GetValueOrDefault()).CellClass = iseSummaryTableCellClass.Positive
                  End If
                Else
                  .AddText("")
                End If
                If ReportTransactionItem.balance.HasValue Then
                  If ReportTransactionItem.balance.GetValueOrDefault() < 0 Then
                    .AddCurrency(ReportTransactionItem.balance.GetValueOrDefault()).CellClass = iseSummaryTableCellClass.Warning
                  Else
                    .AddCurrency(ReportTransactionItem.balance.GetValueOrDefault()).CellClass = iseSummaryTableCellClass.Positive
                  End If
                Else
                  .AddText("")
                End If
                If ReportTransactionItem.nzfcc IsNot Nothing AndAlso Len(ReportTransactionItem.nzfcc.name) <> 0 Then
                  .AddText(ReportTransactionItem.nzfcc.name)
                Else
                  .AddText("")
                End If
                If ReportTransactionItem.income_category IsNot Nothing AndAlso Len(ReportTransactionItem.income_category.code) <> 0 AndAlso Len(ReportTransactionItem.income_category.name) <> 0 Then
                  .AddText(String.Format("{0} ({1})", ReportTransactionItem.income_category.name, ReportTransactionItem.income_category.code))
                ElseIf ReportTransactionItem.income_category IsNot Nothing AndAlso Len(ReportTransactionItem.income_category.code) <> 0 Then
                  .AddText(ReportTransactionItem.income_category.code)
                ElseIf ReportTransactionItem.income_category IsNot Nothing AndAlso Len(ReportTransactionItem.income_category.name) <> 0 Then
                  .AddText(ReportTransactionItem.income_category.name)
                Else
                  .AddText("")
                End If
                If ReportTransactionItem.spending_category IsNot Nothing AndAlso Len(ReportTransactionItem.spending_category.code) <> 0 AndAlso Len(ReportTransactionItem.spending_category.name) <> 0 Then
                  .AddText(String.Format("{0} ({1})", ReportTransactionItem.spending_category.name, ReportTransactionItem.spending_category.code))
                ElseIf ReportTransactionItem.spending_category IsNot Nothing AndAlso Len(ReportTransactionItem.spending_category.code) <> 0 Then
                  .AddText(ReportTransactionItem.spending_category.code)
                ElseIf ReportTransactionItem.spending_category IsNot Nothing AndAlso Len(ReportTransactionItem.spending_category.name) <> 0 Then
                  .AddText(ReportTransactionItem.spending_category.name)
                Else
                  .AddText("")
                End If
                .AddText(ReportTransactionItem.other_account)
                .AddText(ReportTransactionItem.other_loan_account)
                .AddText(ReportTransactionItem.other_card_suffix)
              End With
            End With
          End With
        End With
        Account = ReportTransactionItem._account
        Source = ReportTransactionItem._source
      Next      
      
      Akahu_TabularTableHeaderRowUpdate(SummaryTable)
      SummaryTables.Add("Transactions_" & reportId, SummaryTable)       
    Else
      Summarytables.AddSummaryTableBlank("Transactions_" & reportId, "Transactions", "No Transaction data.", "", 3)
    End If
  End If
  
  Return SummaryTables
  
End Function

Private Function Akahu_Reports(serviceLogs As ISServiceLogs) As ISSummaryTables
  
  Dim i As Integer
  Dim Report As ProxyObjects.Akahu.Apply.Report
  Dim Response_Akahu_ApplyCreateReport As ISBankAccountEnquiryResponse_Akahu_ApplyCreateReport
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  
  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()
  
  ' Sharing Requests
  SummaryTables.AddSummaryTableBlank("Reports", "Reports", "<div/>", "Reports", 2)
  i = 0
  For Each ServiceLog As ISServiceLog In serviceLogs
    If ServiceLog.ExResponse IsNot Nothing Then
      Select ServiceLog.ExResponse.GetType()
        Case GetType(ISBankAccountEnquiryResponse_Akahu_ApplyCreateReport)
          Response_Akahu_ApplyCreateReport = DirectCast(ServiceLog.ExResponse, ISBankAccountEnquiryResponse_Akahu_ApplyCreateReport)
          If Response_Akahu_ApplyCreateReport.Payload IsNot Nothing Then
            Report = Me.Akahu_GetLastReportStatusById(servicelogs, Response_Akahu_ApplyCreateReport.Payload._id)
            If Report IsNot Nothing Then
              SummaryTable = SummaryTables.CreateSummaryTableInformation(Report._id, "Report_" & Report._id,3,,, TestMode)
              With SummaryTable
                .AddRowCaptionText("Status:", Report.IS_StatusText)
                If Report.failure_reason IsNot Nothing Then
                  .AddRowCaptionText("Failure Reason:", Report.failure_reason.IS_CodeText, False)
                  .AddRowCaptionText("Failure Reason:", Report.failure_reason.message, False)
                End If
                .AddRowCaptionDateTime("Generated At:", Report.IS_GeneratedAtDate)
                .AddRowCaptionDateTime("Expires At:", Report.IS_ExpiresAtDate)
                
                With .Actions
                  .AddApplicationShortcutUrl("HTMLReport", "HTML Report", String.Format("App://Global?Type=BankAccountEnquiry.SupplementalReport&ServiceLogPk={0}&ReportKey=HTM.{1}", ServiceLogs(0).Pk, Report._id), True).ShowInWebInterfaces = True
                End With
              End With
              Akahu_TabularTableHeaderRowUpdate(SummaryTable)
              SummaryTables.Add("Report_" & Report._id, SummaryTable)
              
              ' Append the data
              SummaryTables.AppendSummaryTables(Akahu_ReportData(servicelogs, Report._id))
            End If
          End If
          i += 1
      End Select
    End If
  Next
  
    ' Reset if none found
  If i = 0 Then
    SummaryTables = finBL.CreateSummaryTables()
    SummaryTables.AddSummaryTableBlank("Reports", "Reports", "<div/>", "Reports", 2).TextAfter = "{{Warning|No Reports found.}}"
  End If
  
  Return SummaryTables
  
End Function

Private Function Akahu_Resources(serviceLogs As ISServiceLogs) As ISSummaryTables
  
  Dim Response_Akahu_ApplyGetApplicationResources As ISBankAccountEnquiryResponse_Akahu_ApplyGetApplicationResources
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  
    ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  ' Find Resource response
  For Each ServiceLog As ISServiceLog In serviceLogs
    If ServiceLog.ExResponse IsNot Nothing Then
      Select ServiceLog.ExResponse.GetType()
        Case GetType(ISBankAccountEnquiryResponse_Akahu_ApplyGetApplicationResources)
          Response_Akahu_ApplyGetApplicationResources = DirectCast(ServiceLog.ExResponse, ISBankAccountEnquiryResponse_Akahu_ApplyGetApplicationResources)
          If Response_Akahu_ApplyGetApplicationResources.Payload IsNot Nothing Then
            Exit For
          Else
             Response_Akahu_ApplyGetApplicationResources = Nothing
          End If
      End Select
    End If
  Next

  ' Resources
  If Response_Akahu_ApplyGetApplicationResources IsNot Nothing AndAlso Response_Akahu_ApplyGetApplicationResources.Payload IsNot Nothing AndAlso Response_Akahu_ApplyGetApplicationResources.Payload.items IsNot Nothing AndAlso Response_Akahu_ApplyGetApplicationResources.Payload.items.Length <> 0 Then
    SummaryTable = SummaryTables.CreateSummaryTableTabular("Resources", "Resources",2, TestMode)
    With SummaryTable
      ' Columns
      With .Columns
        .AddText("Name")
        .AddText("Status")
        .AddText("Type")
        .AddText("Failure Reason")
        .AddText("Channel")
        .AddText("Source")
        .AddDateTime("Created")
        .AddDateTime("Expires")
        .AddDateTime("Updated")
      End With
      
      ' Rows
      With .Rows
        For Each ResourceItem As ProxyObjects.Akahu.Apply.ResourceItem In Response_Akahu_ApplyGetApplicationResources.Payload.items
          With .Add.Cells
            If ResourceItem.IS_Type = iseCreditBureau_Akahu_ApplyReportResourceType.Document AndAlso ResourceItem.IS_Status = iseCreditBureau_Akahu_ApplyResourceStatus.Completed Then
              .AddText(ResourceItem.name).HyperlinkSetGlobalAction("BankAccountEnquiry.SupplementalReport", String.Format("ServiceLogPk={0}&ReportKey=PDF.{1}", ServiceLogs(0).Pk, ResourceItem._id))
            Else
            .AddText(ResourceItem.name)
            End If
            
            .AddText(ResourceItem.IS_StatusText)
            .AddText(ResourceItem.IS_TypeText)
            If ResourceItem.failure_reason IsNot Nothing AndAlso len(ResourceItem.failure_reason.message) <> 0 Then
              .AddText(String.Format("{0}: {1}", ResourceItem.failure_reason.IS_CodeText, ResourceItem.failure_reason.message))
            Else
              .AddText("")    
            End If
            If ResourceItem.channel IsNot Nothing Then
              .AddText(ResourceItem.channel.IS_TypeText)
            Else
              .AddText("")    
            End If
            If ResourceItem.source IsNot Nothing Then
              .AddText(ResourceItem.source.IS_TypeText)
            Else
              .AddText("")    
            End If            
            .AddDateTime(ResourceItem.IS_CreatedAtDate)
            .AddDateTime(ResourceItem.IS_ExpiresAtDate)
            .AddDateTime(ResourceItem.IS_UpdatedAtDate)
          End With
        Next
      End With
    End With
    Akahu_TabularTableHeaderRowUpdate(SummaryTable)
    SummaryTables.Add("Resources", SummaryTable)  
  Else
    SummaryTables.AddSummaryTableBlank("Resources", "Resources", "<div/>", "Resources", 2).TextAfter = "{{Warning|No Resources found.}}"
  End If
  
  Return SummaryTables
  
End Function

Private Function Akahu_SharingRequests(serviceLogs As ISServiceLogs) As ISSummaryTables
  
  Dim AllowMultipleSubmissions As Boolean
  Dim i As Integer
  Dim PayLoad As ProxyObjects.Akahu.Apply.SharingRequest
  Dim Response_Akahu_ApplyCreateSharingRequest As ISBankAccountEnquiryResponse_Akahu_ApplyCreateSharingRequest
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  
    ' Initialise
  SummaryTables = finBL.CreateSummaryTables()
  
  ' Sharing Requests
  SummaryTables.AddSummaryTableBlank("SharingRequests", "Sharing Requests", "<div/>", "SharingRequests", 2)
  i = 0
  For Each ServiceLog As ISServiceLog In serviceLogs
    If ServiceLog.ExResponse IsNot Nothing Then
      Select ServiceLog.ExResponse.GetType()
        Case GetType(ISBankAccountEnquiryResponse_Akahu_ApplyCreateSharingRequest)
          Response_Akahu_ApplyCreateSharingRequest = DirectCast(ServiceLog.ExResponse, ISBankAccountEnquiryResponse_Akahu_ApplyCreateSharingRequest)
          If Response_Akahu_ApplyCreateSharingRequest.Payload IsNot Nothing Then
            Me.Akahu_GetLatestSharingRequest(serviceLogs, Response_Akahu_ApplyCreateSharingRequest.Payload._id, AllowMultipleSubmissions, PayLoad)
            SummaryTable = SummaryTables.CreateSummaryTableInformation(Payload._id, "SharingRequest" & CStr(i),3,,, TestMode)
            With SummaryTable
              If Payload.IS_ExpiresAtUtcDate >= finBL.TimeZoneFunctions.GetCurrentUtcDateTime() Then
                If serviceLogs(0).ResponseStatus = iseServiceLogResponseStatus.InProgress Then
                  .Rows.AddCaptionText("Sharing Link:", Payload.link).Cells(1).HyperlinkSetExternal(Payload.link)
                Else
                  .Rows.AddCaptionText("Sharing Link:", Payload.link)
                End If
                .AddRowCaptionTick("Allow Multiple Submissions:", AllowMultipleSubmissions, True)
                .AddRowCaptionDateTime("Created At:", Payload.IS_CreatedAtDate)
                .AddRowCaptionDateTime("Expires At:", Payload.IS_ExpiresAtDate)
                .AddRowCaptionDateTime("Last Submitted At:", Payload.IS_LastSubmittedAtDate)
              Else
                .AddRowCaptionText("Sharing Link:", Payload.link)
                .AddRowCaptionTick("Allow Multiple Submissions:", AllowMultipleSubmissions, True)
                .AddRowCaptionDateTime("Created At:", Payload.IS_CreatedAtDate)
                .Rows.AddCaptionDateTime("Expires At:", Payload.IS_ExpiresAtDate, "Expired").BackgroundColour = "#FFB6C1"
                .AddRowCaptionDateTime("Last Submitted At:", Payload.IS_LastSubmittedAtDate)
              End If      
            End With
            Akahu_TabularTableHeaderRowUpdate(SummaryTable)
            SummaryTables.Add("SharingRequest" & 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("SharingRequests", "Sharing Requests", "<div/>", "SharingRequests", 2).TextAfter = "{{Warning|No Sharing Requests found.}}"
  End If
  
  Return SummaryTables
  
End Function

Private Sub Akahu_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 Sub CreatePage_Akahu_ApplyCreateApplication(serviceLogs As ISServiceLogs,
                                                    htmlSummaryPage2StringBuilder As finHtmlSummaryPage2StringBuilder)

  Dim AccountApp As finAccountApp
  Dim AccountAppApplicant As finAccountAppApplicant
  Dim AccountAppLog As finAccountAppLog
  Dim Client As finClient
  Dim ClientLog As finClientLog
  Dim ClientName As String
  Dim i As Integer
  Dim ResponseCreateApplication As ISBankAccountEnquiryResponse_Akahu_ApplyCreateApplication

  ' Get Responses
  ' The root Service Log is a Create Application (consumer consent flow) or a Create Referral Redemption (Apply Referrals flow); only the former is a Create Application response.
  If TypeOf serviceLogs(0).ExResponse Is ISBankAccountEnquiryResponse_Akahu_ApplyCreateApplication Then
    ResponseCreateApplication = DirectCast(serviceLogs(0).ExResponse, ISBankAccountEnquiryResponse_Akahu_ApplyCreateApplication)
  End If
  For i = serviceLogs.Count - 1 To 0 Step -1
    If serviceLogs(i).RequestStatus = iseAuditLogStatus.Success Then
      Select Case serviceLogs(i).ExResponse.GetType()
        Case GetType(ISBankAccountEnquiryResponse_Akahu_ApplyCreateApplication)
          ResponseCreateApplication = DirectCast(serviceLogs(i).ExResponse, ISBankAccountEnquiryResponse_Akahu_ApplyCreateApplication)
      End Select
    End If
  Next

  ' Get Client/ Applicant (ignore errors)
  Select Case ServiceLogs(0).SourceType
    Case "AccountAppLog"
      AccountAppLog = finBL.CreateAccountAppLog()
      If AccountAppLog.Load(ServiceLogs(0).SourcePk) Then
        AccountApp = finBL.CreateAccountApp()
        If AccountApp.LoadPk(AccountAppLog.AccountAppPk) Then
          AccountAppApplicant = AccountApp.Applicants.ItemByPk(AccountAppLog.AccountAppApplicantPk)
          ClientName = AccountAppApplicant.Name
        Else
          ClientName = "Account Application Client not found."
        End If
      Else
        ClientName = "Account Application Client not found."
      End If

    Case "Client"
      Client = finBL.CreateClient()
      If Client.LoadPk(ServiceLogs(0).SourcePk) Then
        ClientName = Client.Name
      Else
        ClientName = "Client not found."
      End If

    Case "ClientLog"
      ClientLog = finBL.CreateClientLog
      If ClientLog.Load(ServiceLogs(0).SourcePk) Then
        Client = finBL.CreateClient()
        If Client.LoadPk(ClientLog.ClientPk) Then
          ClientName = Client.Name
        Else
          ClientName = "Client not found."
        End If
      Else
        ClientName = "Client not found."
      End If

    Case Else
      ClientName = "No Associated Client - Imported log"
  End Select

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

    .SummaryTablesAppend(Me.Akahu_EnquiryDetails(serviceLogs, ResponseCreateApplication, accountApp, AccountAppApplicant, Client, AccountAppLog, ClientLog))
    .SummaryTablesAppend(Me.Akahu_Alerts(serviceLogs))

    ' An Apply Referrals enquiry has no Sharing Request (the broker already collected the data), so the Sharing Requests block is suppressed.
    If Not (TypeOf serviceLogs(0).ExResponse Is ISBankAccountEnquiryResponse_Akahu_ApplyCreateReferralRedemption) Then
      .SummaryTablesAppend(Me.Akahu_SharingRequests(serviceLogs))
    End If

    .SummaryTablesAppend(Me.Akahu_Resources(serviceLogs))
    .SummaryTablesAppend(Me.Akahu_Reports(serviceLogs))
    .SummaryTablesAppend(Me.Akahu_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("#000000", "#B383FF", "", "#F8F5FE")
    
    ' 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 - the root is a Create Application (consumer consent flow) or a Create Referral Redemption (Apply Referrals flow)
  Select Case Response.GetType()
    Case GetType(ISBankAccountEnquiryResponse_Akahu_ApplyCreateApplication), GetType(ISBankAccountEnquiryResponse_Akahu_ApplyCreateReferralRedemption)
      Me.CreatePage_Akahu_ApplyCreateApplication(ServiceLogs, HtmlSummaryPage2StringBuilder)

      Case Else
      ' Error
      finBL.Error.ErrorBegin("Invalid Service Log." & 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
