' SummaryPage2_Workflow_Summary
Option Explicit On
Option Strict On

' #################################################################
' Workflow Summary
'
' Version: 2.08 (11/09/2024)
'
' Usage: Workflows and Task Manager forms
'
' NOTES
' -----
' Any of the constants defined in this Script can be overridden
' in the Summary Page Script that calls this Script, e.g.,
' a Workflow Key Details Script.
'
' Usage: Built-in Summary Page
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    2.08  11/09/2024  ISS      J033081   Not jumping to current item in finPOWER Connect Cloud
' #################################################################

'#const "ShowAccountMonitoring",Boolean,False,"Show full Monitoring block for Account Workflows"
'#const "ShowUserDefined",Boolean,False,"Show User Defined fields"
'#const "ShowUserDefinedItem",Boolean,True,"Show Item User Defined fields"
'#const "ShowNaItems",Boolean,True,"Show items flagged as 'Not Applicable'"
'#const "ShowSkippedItems",Boolean,False,"Show items flaged as 'Skipped'"

'#const "EventNumberOfDays",Integer,30,"Number of Days of Events to display."
'#const "EventAuditInclude",Boolean,False,"Include Audit Events?"
'#const "ShowEventBlock",Boolean,False,"Show Event block?"

' Constants
Private ShowAccountMonitoring As Boolean = False
Private ShowUserDefined As Boolean = False
Private ShowUserDefinedItem As Boolean = True

Private EventAuditInclude As Boolean = False
Private EventNumberOfDays As Integer = 30
Private ShowEventBlock As Boolean = False

' Internal Constants
Private Const CURRENT_COLOUR As String = "#90ff90"
Private Const LAST_ACTIONED_COLOUR As String = "#ccfffc"

' Objects
Private mWorkflow As finWorkflow
Private mWorkflowItem As finWorkflowItem

' Other
Private mIncludeActions As Boolean

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

  ' Assume Success
  Main = True

  ' Initialise
  If TypeOf source Is String Then
    mWorkflow = finBL.CreateWorkflow()
    mWorkflow.Load(CStr(source))
  Else
    mWorkflow = DirectCast(source, finWorkflow)
  End If
  If eventArgs.Exists("WorkflowItem") Then
    mWorkflowItem = DirectCast(eventArgs.GetObject("WorkflowItem"), finWorkflowItem)
  End If

  ' Get Constants
  With ScriptInfo.Constants
    ShowAccountMonitoring = .GetBoolean("ShowAccountMonitoring", ShowAccountMonitoring)
    ShowUserDefined = .GetBoolean("ShowUserDefined", ShowUserDefined)
    ShowUserDefinedItem = .GetBoolean("ShowUserDefinedItem", ShowUserDefinedItem)
    
    ShowEventBlock = .GetBoolean("ShowEventBlock", ShowEventBlock)
    EventAuditInclude = .GetBoolean("EventAuditInclude", EventAuditInclude)
    EventNumberOfDays = .GetInteger("EventNumberOfDays", EventNumberOfDays)    
  End With

  ' Include Actions?
  If ScriptInfo.Target = iseSummaryPageTarget.WebInternal Then
    ' When displayed in finPOWER Connect Cloud, Workflows can be actioned from anywhere except the Workflow Item preview popup which sets a special flag
    mIncludeActions = Not eventArgs.GetBoolean("_NoActions")
  Else
    mIncludeActions = (ScriptInfo.FormKey = "TaskManager" OrElse (ScriptInfo.FormKey = "Workflows" AndAlso ScriptInfo.FormRecordMode = iseFormRecordMode.Loaded))    
  End If

  ' Handle Events
  Select Case eventId
    Case ""
      ' Main event, i.e., return main page content
      If mWorkflowItem Is Nothing Then
        Main = CreatePage(text)
      Else
        Main = CreatePageItem(text)
      End If
  End Select

End Function

Private Function CreatePage(ByRef html As String) As Boolean

  Dim Ok As Boolean
  Dim sb As finHtmlSummaryPage2StringBuilder
  Dim strTemp As String
  Dim SummaryTables As ISSummaryTables
  Dim Warnings As finWarnings

  ' Assume Success
  Ok = True

  ' Initialise
  sb = finBL.CreateHtmlSummaryPage2StringBuilder()

  ' Initialise HTML
  With sb
    .Initialise(ScriptInfo)
    .HtmlHeaderBegin("", isefinSummaryPageStyle.Blocks)
    .HtmlHeaderEnd()
  End With

  If mWorkflow.IsNew Then
    ' No Workflow loaded
    sb.SectionColumnsAddQuickBlock("Summary", "{{info|Please enter a code to view a Workflow record.}}")
  Else
    ' Workflow
    ' Begin Section
    sb.SectionFixedColumnsBegin()

    ' Begin Column 1
    sb.FixedColumnBegin("0", "60%")

    ' Items
    If ScriptInfo.Target = iseSummaryPageTarget.Form AndAlso (mWorkflow.Status = isefinWorkflowStatus.Closed OrElse mWorkflow.GetCurrentItem() Is Nothing) Then
      ' Normal heading
      strTemp = "Items"
    Else
      ' Special heading containing hyperlinks to jump to current and last item (uses stopPropagation to prevent block from collapsing when clicked)
      strTemp = "<html>Items&nbsp;&nbsp;<small style='font-weight:normal; font-size:10px; display:inline-block; position:relative; vertical-align:middle; margin-top:-2px'>" &
                "<a onclick=""var e = arguments[0] || window.event; e.stopPropagation(); try{document.getElementById('CURRENT').scrollIntoView(false);} catch(e){}; "" title='Go to the current item' onmouseover='this.style.backgroundColor=""rgba(0,0,0,0.075)""' onmouseout='this.style.backgroundColor=""""' style='display:inline-block; position:relative; padding:2px; text-decoration:none; line-height:10px; height:14px; overflow:hidden; vertical-align:top'><div style='border-radius:5px; width:10px; height:10px; display:inline-block; position:relative; vertical-align:top; background-color:" & CURRENT_COLOUR & "'></div> Current</a> " &
                "<a onclick=""var e = arguments[0] || window.event; e.stopPropagation(); try{document.getElementById('LATEST').scrollIntoView(false);} catch(e){}; "" title='Go to the last actioned item' onmouseover='this.style.backgroundColor=""rgba(0,0,0,0.075)""' onmouseout='this.style.backgroundColor=""""' style='display:inline-block; position:relative; padding:2px; text-decoration:none; line-height:10px; height:14px; overflow:hidden; vertical-align:top'><div style='border-radius:5px; width:10px; height:10px; display:inline-block; position:relative; vertical-align:top; background-color:" & LAST_ACTIONED_COLOUR & "'></div> Last Actioned</a> " &
                "</small>"
    End If
    sb.BlockBegin(strTemp)
    ' Train Stops diagram
    If mWorkflow.WorkflowType IsNot Nothing AndAlso mWorkflow.WorkflowType.SummaryPageShowTrainStops Then
      sb.Append(finBL.SummaryPageStandardBlocks.Workflow_TrainStops(ScriptInfo, mWorkflow.GetTrainStops(), mIncludeActions))
    End If
    ' Items
    sb.SummaryTablesAppend(finBL.SummaryPageStandardBlocks.Workflow_Items(ScriptInfo, mWorkflow, 0, mIncludeActions))
    sb.BlockEnd()

    ' User Defined
    If ShowUserDefined Then
      SummaryTables = mWorkflow.GetUserDataAsSummaryTables()
      If SummaryTables IsNot Nothing AndAlso SummaryTables.Count <> 0 Then
        sb.BlockBegin("User Defined")
        sb.SummaryTablesAppend(SummaryTables)
        sb.BlockEnd()
      End If
    End If

    ' End Column 1
    sb.FixedColumnEnd()

    ' Begin Column 2
    sb.FixedColumnBegin("60%", "40%")

    ' Summary
    sb.BlockBegin("Workflow", "", isefinSummaryPageBlockHeadingStyle.Main)
    sb.SummaryTablesAppend(finBL.SummaryPageStandardBlocks.Workflow_Summary(ScriptInfo, mWorkflow, Me.ScriptInfo.FormKey <> "Workflows", mIncludeActions))
    sb.BlockEnd()

    ' Target Summary
    sb.BlockBegin(mWorkflow.WorkflowType.TargetObjectTypeText)
    sb.SummaryTablesAppend(finBL.SummaryPageStandardBlocks.Workflow_TargetSummary(ScriptInfo, mWorkflow, mIncludeActions))
    sb.BlockEnd()

    ' Warnings
    Warnings = mWorkflow.GetWarnings()
    If Warnings.Count <> 0 Then
      sb.BlockBegin("Warnings", "", If(Warnings.Count = 0, isefinSummaryPageBlockHeadingStyle.Normal, isefinSummaryPageBlockHeadingStyle.Warning))
      sb.SummaryTablesAppend(finBL.SummaryPageStandardBlocks.WarningsSummary(ScriptInfo, Warnings))
      sb.BlockEnd()
    End If

    ' Account Monitoring
    If ShowAccountMonitoring AndAlso mWorkflow.WorkflowType.TargetObjectType = isefinWorkflowTargetObjectType.Account Then
      If finBL.Settings.MonitorCategoriesUsed Then
        sb.BlockBegin("Monitoring", "", If(mWorkflow.Account.MonitorCategoryAPk = 0 AndAlso mWorkflow.Account.MonitorCategoryBPk = 0 AndAlso mWorkflow.Account.MonitorCategoryCPk = 0, isefinSummaryPageBlockHeadingStyle.Normal, isefinSummaryPageBlockHeadingStyle.Warning))
        sb.SummaryTablesAppend(finBL.SummaryPageStandardBlocks.Account_Monitoring(ScriptInfo, mWorkflow.Account, False, False))
        sb.BlockEnd()
      End If
    End If

    ' Logs
    sb.BlockBegin("Logs")
    sb.SummaryTablesAppend(finBL.SummaryPageStandardBlocks.Workflow_Logs(ScriptInfo, mWorkflow.Logs, 20, mIncludeActions))
    sb.BlockEnd()

    ' Events
    If ShowEventBlock Then
      sb.BlockBegin("Events")
      sb.SummaryTableAppend(finBL.SummaryPageStandardBlocks.Events_Summary(ScriptInfo, mWorkflow.GetEvents(EventNumberOfDays, EventAuditInclude), Nothing))
      sb.BlockEnd()
    End If
    
    ' End Column 2
    sb.FixedColumnEnd()

    ' End Section
    sb.SectionFixedColumnsEnd()
  End If

  ' Special Script to jump to the Current/ Last Actioned item in the Items block
  ' NOTE: Delay slightly so page is fully rendered
  If (ScriptInfo.Target = iseSummaryPageTarget.Form OrElse ScriptInfo.Target = iseSummaryPageTarget.WebInternal) AndAlso 
     mWorkflow.Status <> isefinWorkflowStatus.Closed AndAlso mWorkflow.GetCurrentItem() IsNot Nothing Then
    sb.AppendLine("<script>")
    sb.AppendLine("window.setTimeout(function() {")
    If mWorkflow.GetCurrentItem() Is Nothing Then
      sb.AppendLine("try{document.getElementById('LATEST').scrollIntoView(false);} catch(e){};")
    Else
      sb.AppendLine("try{document.getElementById('CURRENT').scrollIntoView(false);} catch(e){};")
    End If
    sb.AppendLine("}, 100);")
    sb.AppendLine("</script>")
  End If

  ' Finalise HTML
  sb.HtmlFinalise()

  ' Resolve Templates
  html = sb.ToString(True)

  Return Ok

End Function

Private Function CreatePageItem(ByRef html As String) As Boolean

  Dim Ok As Boolean
  Dim sb As finHtmlSummaryPage2StringBuilder
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Assume Success
  Ok = True

  ' Initialise
  sb = finBL.CreateHtmlSummaryPage2StringBuilder()

  ' Initialise HTML
  With sb
    .Initialise(ScriptInfo)
    .HtmlHeaderBegin("", isefinSummaryPageStyle.Blocks)
    .HtmlHeaderEnd()
  End With

  ' Begin Section
  sb.SectionColumnsBegin()

  ' Begin Column 1
  sb.ColumnBegin("60%")

  ' Summary
  sb.BlockBegin("Summary", "", isefinSummaryPageBlockHeadingStyle.Main, False)
  sb.SummaryTablesAppend(finBL.SummaryPageStandardBlocks.WorkflowItem_Summary(ScriptInfo, mWorkflowItem, mIncludeActions))
  sb.BlockEnd()

  ' User Defined
  If ShowUserDefinedItem AndAlso (mWorkflowItem.Status = isefinWorkflowItemStatus.Open OrElse mWorkflowItem.Status = isefinWorkflowItemStatus.Complete) Then
    SummaryTables = mWorkflowItem.GetUserDataAsSummaryTables()
    If SummaryTables IsNot Nothing AndAlso SummaryTables.Count <> 0 Then
      sb.BlockBegin("User Defined")
      sb.SummaryTablesAppend(SummaryTables)
      sb.BlockEnd()
    End If
  End If

  ' Supplemental (e.g., Credit Enquiry details) for Completed Items (1 block per table)
  If mWorkflowItem.Status = isefinWorkflowItemStatus.Complete Then
    SummaryTables = finBL.SummaryPageStandardBlocks.WorkflowItem_Supplemental(ScriptInfo, mWorkflowItem, mIncludeActions)

    For Each SummaryTable In SummaryTables
      sb.BlockBegin(SummaryTable.Caption)
      sb.SummaryTableAppend(SummaryTable)
      sb.BlockEnd()
    Next
  End If

  ' End Column 1
  sb.ColumnEnd()

  ' Begin Column 2
  sb.ColumnBegin("40%", "32em", "50em")

  ' Logs
  If mWorkflowItem.Logs.Count <> 0 Then
    sb.BlockBegin("Logs")
    sb.SummaryTablesAppend(finBL.SummaryPageStandardBlocks.Workflow_Logs(ScriptInfo, mWorkflowItem.Logs, 20, mIncludeActions))
    sb.BlockEnd()
  End If

  ' Audit
  SummaryTables = finBL.SummaryPageStandardBlocks.WorkflowItem_AuditItems(ScriptInfo, mWorkflowItem, mIncludeActions)
  If SummaryTables.Count <> 0 AndAlso (Len(SummaryTables.ItemByIndex(0).TextAfter) <> 0 OrElse SummaryTables.ItemByIndex(0).Rows.Count <> 0) Then
    sb.BlockBegin("Audit", , , True, True)
    sb.SummaryTablesAppend(SummaryTables)
    sb.BlockEnd()
  End If

  ' End Column 2
  sb.ColumnEnd()

  ' End Section
  sb.SectionColumnsEnd()

  ' Finalise HTML
  sb.HtmlFinalise()

  ' Resolve Templates
  html = sb.ToString(True)

  Return Ok

End Function