Option Explicit

' Constants
Const IncludeCurrentBalance = True
Const IncludeCurrentOverdue = True

Function Main(ByVal finBL, ByVal ManagerId, ByVal CollectionLoans, ByVal CollectionLoansView, ByVal FolderKey, ByVal CollectionFolders) 'VBScript
'VBA Function Main(ByVal finBL As ISfinSupport, ByVal ManagerId As String, ByVal CollectionLoans As finCollectionLoans, ByVal CollectionLoansView As finCollectionLoansView, ByVal FolderKey As String, ByVal CollectionFolders As finCollectionFolders)

' Function should return (html) text for the Report
Main = ""

Dim i 'As Long
Dim j 'As Long
Dim b 'As String
Dim s 'As String
Dim strTemp 'As String
Dim Ok 'As Boolean
Dim SQLQuery 'As String
Dim EndDate 'As Variant
Dim OldManagerId 'As String
Dim Cols 'As Integer
Dim Stat
Dim Stats()
Dim StatsCount 'As Long
Dim AltRow 'As Boolean
Dim AltRowAttr 'As String
Dim MinutesRemaining 'As Long
Dim WorkloadMinutes 'As Long
Dim SumCountLoans 'As Long
Dim SumCountLoansActive 'As Long
Dim SumTotalOverdue 'As Currency
Dim SumTotalCurrentBalance 'As Currency
Dim SumTotalCurrentOverdue 'As Currency
Dim SumWorkloadMinutes 'As Long
Dim rst 'As Recordset
Dim rst2 'As Recordset
Dim CollectionGroup 'As finCollectionGroup
Dim LoanFunctions 'As finLoanFunctions

  ' Assume Success
  Ok = True

  ' Create Objects
  Set LoanFunctions = finBL.CreateLoanFunctions

  ' Initialise HTML
  s = s & "<html><head><style>"
  s = s & "BODY {font-family:verdana; font-size:8pt; background-color:appworkspace;}"
  s = s & "TH {font-weight:normal; font-size:8pt; color:buttontext; background-color:buttonface; border-top:1px solid buttonshadow; border-right:1px solid buttonshadow; border-bottom:1px solid buttonshadow;}"
  s = s & "TD {font-size:8pt; background-color:window; border-right:1px solid inactiveborder; border-bottom:1px solid inactiveborder}"
  s = s & ".error {font-weight:bold; color:red;}"
  s = s & ".header {font-size:9pt; font-weight:bold; color:#000090;}"
  s = s & ".headersub {font-size:7pt; font-weight:normal; color:#000090;}"
  s = s & ".footer {background-color:threedlightshadow;}"
  s = s & ".expander {font:7pt courier new; cursor:hand; width:14px; height:14px; text-align:center; overflow:hidden; border:1px solid buttonshadow;}"
  s = s & ".altRow {background-color:infobackground;}"
  s = s & "</style>"
  s = s & "<script>"
  s = s & "function expand(e, id)"
  s = s & "{"
  s = s & "var collapsed, i, nodes;"
  s = s & "collapsed=(e.innerHTML=='+');"
  s = s & "if(collapsed){e.innerHTML='-';}else{e.innerHTML='+';}"
  s = s & "nodes=document.getElementsByTagName('TR');"
  s = s & "for(i=0;i<nodes.length;i++){"
  s = s & "if(nodes[i].getAttribute('managerid')==id)"
  s = s & "{"
  s = s & "if(nodes[i].style.display=='none'){nodes[i].style.display='';}else{nodes[i].style.display='none';}"
  s = s & "}"
  s = s & "}"
  s = s & "}"
  s = s & "</script>"
  s = s & "</head><body leftmargin=0 rightmargin=0 topmargin=0 bottommargin=0>"
  
  ' Create SQLQuery
  SQLQuery = "SELECT Count(*) AS CountLoans,ContractCollectionHistory.CollectorManagerId,ContractCollectionHistory.CollectionGroupId,Sum(ContractCollectionHistory.Overdue) AS TotalOverdue"
  SQLQuery = SQLQuery & " FROM ContractCollectionHistory INNER JOIN Contract ON Contract.ContractId=ContractCollectionHistory.ContractId"
  SQLQuery = SQLQuery & " WHERE ContractCollectionHistory.MovedToDate Is Null AND ContractCollectionHistory.CollectorManagerId Is Not Null"
  SQLQuery = SQLQuery & " GROUP BY ContractCollectionHistory.CollectorManagerId,ContractCollectionHistory.CollectionGroupId"
  SQLQuery = SQLQuery & " ORDER BY ContractCollectionHistory.CollectorManagerId,ContractCollectionHistory.CollectionGroupId"
  
  ' Open Recordset and Generate Statistics
  If finBL.Database.RecordsetOpen(SQLQuery, rst) Then
    ' Dimension Array to Hold Statistics + Collection Group Totals
    ReDim Stats(rst.RecordCount + finBL.CollectionGroups.Count)
    StatsCount = 0
    
    ' Read Statistics
    Do Until rst.EOF
      ' Create Object
      Set Stat = New CollectionStat
      With Stat
        .CollectionGroupId = rst("CollectionGroupId").Value
        .CollectionGroupDescription = finBL.CollectionGroups(.CollectionGroupId).Description
        .ManagerId = rst("CollectorManagerId").Value
        .ManagerName = finBL.Managers(.ManagerId).Name
        .CountLoans = rst("CountLoans").Value
        .CountLoansActive = finBL.Database.GetRecordCount("ContractCollectionHistory", "MovedToDate Is Null AND CollectorManagerId=" & finBL.Database.SQLStringToField(.ManagerId, False) & " AND CollectionGroupId=" & finBL.Database.SQLStringToField(.CollectionGroupId, False) & " AND (ReviewDate Is Null OR ReviewDate<=" & finBL.Database.SQLDateToField(Now) & ")")
        .TotalOverdue = rst("TotalOverdue").Value
        If IncludeCurrentBalance And .CountLoans <> 0 Then
          ' Total Current Balance
          .TotalCurrentBalance = 0
          SQLQuery = "SELECT {BalanceLoan} FROM Contract WHERE ContractId IN (Select ContractId FROM ContractCollectionHistory WHERE MovedToDate Is Null AND CollectorManagerId=" & finBL.Database.SQLStringToField(.ManagerId, False) & " AND CollectionGroupId=" & finBL.Database.SQLStringToField(.CollectionGroupId, False) & ")"
          SQLQuery = finBL.ConvertSQLFields(SQLQuery, Int(Now))
          If finBL.Database.RecordsetOpen(SQLQuery, rst2) Then
            Do Until rst2.EOF
              If Not IsNull(rst2(0).Value) Then .TotalCurrentBalance = .TotalCurrentBalance + rst2(0).Value
              rst2.MoveNext
            Loop
            finBL.Database.RecordsetClose rst2
          End If
        End If
        If IncludeCurrentOverdue And .CountLoans <> 0 Then
          ' Total Current Overdue
          .TotalCurrentOverdue = 0
          SQLQuery = "SELECT {Overdue} FROM Contract WHERE ContractId IN (Select ContractId FROM ContractCollectionHistory WHERE MovedToDate Is Null AND CollectorManagerId=" & finBL.Database.SQLStringToField(.ManagerId, False) & " AND CollectionGroupId=" & finBL.Database.SQLStringToField(.CollectionGroupId, False) & ")"
          SQLQuery = finBL.ConvertSQLFields(SQLQuery, Int(Now))
          
          If finBL.Database.RecordsetOpen(SQLQuery, rst2) Then
            Do Until rst2.EOF
              If Not IsNull(rst2(0).Value) Then .TotalCurrentOverdue = .TotalCurrentOverdue + rst2(0).Value
              rst2.MoveNext
            Loop
            finBL.Database.RecordsetClose rst2
          End If
        End If
        .WorkloadMinutes = finBL.CollectionGroups(rst("CollectionGroupId").Value).CollectionMinutes * rst("CountLoans").Value
        .WorkloadText = LoanFunctions.CollectionsGetDurationText(.WorkloadMinutes, True, False)
      End With
      
      ' Add to Array
      Set Stats(StatsCount) = Stat
      StatsCount = StatsCount + 1
    
      rst.MoveNext
    Loop
    finBL.Database.RecordsetClose (rst)
    
    ' Add Special 'Totals' Section for Collection Groups
    For Each CollectionGroup In finBL.CollectionGroups
      If CollectionGroup.Active Then
        ' Create Object
        Set Stat = New CollectionStat
        With Stat
          .CollectionGroupId = CollectionGroup.CollectionGroupId
          .CollectionGroupDescription = finBL.CollectionGroups(.CollectionGroupId).Description
          .ManagerId = "*"
          .CountLoans = 0
          .CountLoansActive = 0
          .TotalCurrentBalance = 0
          .TotalCurrentOverdue = 0
          .TotalOverdue = 0
          .WorkloadMinutes = 0
          
          For i = 0 To StatsCount - 1
            If Stats(i).CollectionGroupId = CollectionGroup.CollectionGroupId And Stats(i).ManagerId <> "*" Then
              .CountLoans = .CountLoans + Stats(i).CountLoans
              .CountLoansActive = .CountLoansActive + Stats(i).CountLoansActive
              .TotalCurrentBalance = .TotalCurrentBalance + Stats(i).TotalCurrentBalance
              .TotalCurrentOverdue = .TotalCurrentOverdue + Stats(i).TotalCurrentOverdue
              .TotalOverdue = .TotalOverdue + Stats(i).TotalOverdue
              .WorkloadMinutes = .WorkloadMinutes + Stats(i).WorkloadMinutes
            End If
          Next
          
          .WorkloadText = LoanFunctions.CollectionsGetDurationText(.WorkloadMinutes, True, False)
        End With
        
        ' Add to Array
        Set Stats(StatsCount) = Stat
        StatsCount = StatsCount + 1
      End If
    Next
  Else
    Ok = False
  End If
  
  ' Generate HTML
  If Ok Then
    ' Add Table
    b = b & "<table cellspacing='0' border='0' width='100%' style='border:1px solid silver;'>"
    
    ' Column Headers
    Cols = 8
    b = b & "<colgroup>"
    b = b & "<col width='50' align='left' />"
    b = b & "<col width='*' align='left' />"
    b = b & "<col width='60' align='right' />"
    b = b & "<col width='60' align='right' />"
    b = b & "<col width='60' align='right' />"
    b = b & "<col width='80' align='right' />"
    If IncludeCurrentOverdue Then
      b = b & "<col width='80' align='right' />"
    Else
      Cols = Cols - 1
    End If
    If IncludeCurrentBalance Then
      b = b & "<col width='80' align='right' />"
    Else
      Cols = Cols - 1
    End If
    b = b & "<colgroup>"
    b = b & "<thead>"
    b = b & "<th>Group</th>"
    b = b & "<th>Description</th>"
    b = b & "<th>Workload</th>"
    b = b & "<th>Loans</th>"
    b = b & "<th>Active</th>"
    b = b & "<th>Overdue</th>"
    If IncludeCurrentOverdue Then
      b = b & "<th>Current Overdue</th>"
    End If
    If IncludeCurrentBalance Then
      b = b & "<th>Current Balance</th>"
    End If
    b = b & "</thead>"
    
    ' Stats
    For i = 0 To StatsCount - 1
      If Stats(i).ManagerId <> OldManagerId Then
        OldManagerId = Stats(i).ManagerId
        
        ' Group Header Row
        If Stats(i).ManagerId = "*" Then
          strTemp = "<span class='header'>Totals</span>"
        Else
          strTemp = "<span class='header'>" & Stats(i).ManagerId + ", " + Stats(i).ManagerName & "</span>"
          
          ' Summary of Workload
          WorkloadMinutes = 0
          For j = 0 To StatsCount - 1
            If Stats(j).ManagerId = Stats(i).ManagerId Then
              WorkloadMinutes = WorkloadMinutes + Stats(j).WorkloadMinutes
            End If
          Next
          If WorkloadMinutes <> 0 Then
            EndDate = finBL.Managers(Stats(i).ManagerId).CollectionsCalculateEndDate(Int(Now), WorkloadMinutes, MinutesRemaining)
            If MinutesRemaining <> -1 Then
              strTemp = strTemp & "<div class='headersub'>Estimated Completion Date: " + finBL.ISFormat(EndDate, "datelong")
              If MinutesRemaining <> 0 Then
                strTemp = strTemp & " + " + LoanFunctions.CollectionsGetDurationText(MinutesRemaining, True, False) & " hours"
              End If
              strTemp = strTemp & "</div>"
            End If
          End If
        End If
        
        ' Add Button to Expand/Collapse Section
        strTemp = "<span class='expander' onclick=""expand(this,'" & Stats(i).ManagerId & "')"">-</span>&nbsp;" & strTemp
        
        b = b & "<tr class='header'>"
        b = b & "<td colspan='" & Cols & "'>" & strTemp & "</td>"
        b = b & "</tr>"
        
        ' Reset Summary Totals
        SumCountLoans = 0
        SumCountLoansActive = 0
        SumTotalOverdue = 0
        SumTotalCurrentBalance = 0
        SumTotalCurrentOverdue = 0
        SumWorkloadMinutes = 0
        
        ' Data Rows (managerid attribute added to allow expand/collapse)
        AltRow = False
        For j = i To StatsCount - 1
          If AltRow Then AltRowAttr = " class='altRow'" Else AltRowAttr = ""
          
          If Stats(j).ManagerId = Stats(i).ManagerId Then
            b = b & "<tr managerid='" & Stats(i).ManagerId & "'>"
            b = b & "<td" & AltRowAttr & ">" & Stats(j).CollectionGroupId & "</td>"
            b = b & "<td" & AltRowAttr & ">" & Stats(j).CollectionGroupDescription & "</td>"
            b = b & "<td" & AltRowAttr & ">" & Stats(j).WorkloadText & "</td>"
            b = b & "<td" & AltRowAttr & ">" & Stats(j).CountLoans & "</td>"
            b = b & "<td" & AltRowAttr & ">" & Stats(j).CountLoansActive & "</td>"
            b = b & "<td" & AltRowAttr & ">" & finBL.ISFormat(Stats(j).TotalOverdue, "currency") & "</td>"
            If IncludeCurrentOverdue Then
              b = b & "<td" & AltRowAttr & ">" & finBL.ISFormat(Stats(j).TotalCurrentOverdue, "currency") & "</td>"
            End If
            If IncludeCurrentBalance Then
              b = b & "<td" & AltRowAttr & ">" & finBL.ISFormat(Stats(j).TotalCurrentBalance, "currency") & "</td>"
            End If
            b = b & "</tr>"
            
            SumCountLoans = SumCountLoans + Stats(j).CountLoans
            SumCountLoansActive = SumCountLoansActive + Stats(j).CountLoansActive
            SumTotalOverdue = SumTotalOverdue + Stats(j).TotalOverdue
            SumTotalCurrentBalance = SumTotalCurrentBalance + Stats(j).TotalCurrentBalance
            SumTotalCurrentOverdue = SumTotalCurrentOverdue + Stats(j).TotalCurrentOverdue
            SumWorkloadMinutes = SumWorkloadMinutes + Stats(j).WorkloadMinutes
            
            AltRow = Not AltRow
          Else
            Exit For
          End If
        Next
        
        ' Group Footer Row (managerid attribute added to allow expand/collapse)
        b = b & "<tr managerid='" & Stats(i).ManagerId & "'>"
        b = b & "<td class='footer'>&nbsp;</td>"
        b = b & "<td class='footer'>&nbsp;</td>"
        b = b & "<td class='footer'>" & LoanFunctions.CollectionsGetDurationText(SumWorkloadMinutes, True, False) & "</td>"
        b = b & "<td class='footer'>" & SumCountLoans & "</td>"
        b = b & "<td class='footer'>" & SumCountLoansActive & "</td>"
        b = b & "<td class='footer'>" & finBL.ISFormat(SumTotalOverdue, "currency") & "</td>"
        If IncludeCurrentOverdue Then
          b = b & "<td class='footer'>" & finBL.ISFormat(SumTotalCurrentOverdue, "currency") & "</td>"
        End If
        If IncludeCurrentBalance Then
          b = b & "<td class='footer'>" & finBL.ISFormat(SumTotalCurrentBalance, "currency") & "</td>"
        End If
        b = b & "</tr>"
      End If
    Next

    ' Finalise Table
    b = b & "</table>"
  End If
  
  ' Tidy Up
  Set LoanFunctions = Nothing
  
  ' Finalise HTML
  If Ok Then
    s = s & b & "</body></html>"
  Else
    s = s & "<div class='error'>" & finBL.ErrorMessage & "</div></body></html>"
  End If

  ' Return
  Main = s

  ' Destroy Objects
  Set LoanFunctions = Nothing

End Function

Function HTMLEncode(ByVal Text)

  HTMLEncode = Replace(Text, "&", "&amp;")
  HTMLEncode = Replace(HTMLEncode, "<", "&lt;")
  HTMLEncode = Replace(HTMLEncode, ">", "&lt;")
  HTMLEncode = Replace(HTMLEncode, vbNewLine, "<br/>")

End Function

Class CollectionStat

  Public CollectionGroupId
  Public CollectionGroupDescription
  Public ManagerId
  Public ManagerName
  Public CountLoans
  Public CountLoansActive
  Public TotalOverdue
  Public TotalCurrentBalance
  Public TotalCurrentOverdue
  Public WorkloadMinutes
  Public WorkloadText

End Class

