<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2022-09-20T23:35:37.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2011-07-14T20:26:29.2870000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2022-09-20T23:35:23.5490000</UpdatedUtcDate>
    <ScriptId>WFA</ScriptId>
    <Description>Sample Script for Workflow Allocation</Description>
    <ScriptType>ObjectEvents</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Category />
    <Code>' Script_WorkflowUserAllocation.xml
Option Explicit On
'Option Strict On

' #################################################################
' Workflow User Allocation
' 
' Version: 1.02 (21/09/2022)
' 
' Remarks
' -------
' - Sample script code for User Allocations
' - Custom
'   + Pass 1 = User from OpenedFromWorkflow
'   + Pass 2 = User from latest opened workflow of this category (or last opened workflow for this account)
'   + Pass 3 = Use Random allocation
' - Proportion
'   + Proportions based on current user allocation of this workflow
' - Random
'   + Random allocation regardless of weighting
' - Workload
'   + Proportional based on User weighting of weighted workflows
'
' finPOWER Connect Configuration
' ------------------------------
' Script Type: Object Events
' Object : Workflow
'
' WARNING: Sample Script, please ensure this script fits your purposes before using.
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.00  08/08/2011  ISS.LR             Created
'    1.01  16/07/2021  ISS.AM             Fixed compilation warnings   
'    1.02  21/09/2022  ISS      J029586   Fixed compilation warnings
' #################################################################

Public Function Main(ByVal eventId As String, ByRef eventHandled As Boolean, ByVal source As Object, ByVal sourceIndex As Integer, ByVal contextData1 As Object, ByVal contextData2 As Object, ByVal parameters As Object) As Boolean

  Dim Workflow As finWorkflow
  Dim WorkflowItem As finWorkflowItem
  Dim WorkflowParameters As ISKeyValueList

  ' Assume Success
  Main = True

  ' Initialise
  Workflow = DirectCast(source, finWorkflow)
  WorkflowItem = DirectCast(contextData1, finWorkflowItem)
  WorkflowParameters = DirectCast(contextData2, ISKeyValueList)

  ' Handle Events
  ' NOTE: Set the 'eventHandled' parameter to True to NOT call an event in the Workflow Type Script

  Select Case eventId
    Case "AfterInitialise"
      ' Get our own Allocated User and set eventHandled = True so that the Workflow Type Script does not override this
      Workflow.AllocatedUserPk = SuggestedWorkflowUserPk(Workflow)
      eventHandled = True

    Case "BeforeProcess"

    Case "BeforeItemAction"

    Case "AfterItemAction"

    Case "BeforeItemReset"

    Case "AfterItemReset"

    Case "BeforeClose"

    Case "Reallocate"
      ' This is a custom event that can be called from another Script to reallocate the Workflow, e.g.:
      '   finBL.Scripts.Item("WFA").ExecuteObjectEvents(ReturnValue, "Reallocate", False, Workflow, -1, Nothing, Nothing, Nothing)
      Workflow.AllocatedUserPk = SuggestedWorkflowUserPk(Workflow)
  End Select

End Function

Private Function SuggestedWorkflowUserPk(ByVal workflow As finWorkflow) As Integer

  Dim WFTUser As finWorkflowTypeUserRO
  Dim User As finUserRO
  Dim UserPk As Integer

  Dim dt As DataTable
  Dim Row As DataRow

  Dim UserWeighting As Decimal

  ' Initialise
  UserPk = 0
  
  ' Create DataTable with list of applicable users and their weighting
  dt = New DataTable()
  With dt.Columns
    .Add("UserPk", GetType(Integer))
    .Add("UserWeighting", GetType(Decimal))
    .Add("AllocationCurrent", GetType(Decimal))
  End With

  With finBL.WorkflowTypes(workflow.WorkflowTypeId)
    If .Users.Count = 0 Then
      ' If there are no Users specifically listed on the Workflow Type
      '   the workflow can be allocated to any active user to is allowed for that Workflow Type Category
      For Each User In finBL.Users
        If User.Active Then
          If finBL.Runtime.TextUtilities.IsValueInRange(.Category, User.WorkflowCategoriesRange) Then
            UserWeighting = User.WorkflowWeighting
          Else
            UserWeighting = 0
          End If

          If UserWeighting &gt; 0 Then
            Row = dt.NewRow()
            Row!UserPk = User.Pk
            Row!UserWeighting = UserWeighting
            Row!AllocationCurrent = 0
            dt.Rows.Add(Row)
          End If
        End If
      Next
    Else
      For Each WFTUser In .Users
        Select Case .AllocationMethod
          Case isefinWorkflowAllocationMethod.Proportional: UserWeighting = WFTUser.Proportion
          Case isefinWorkflowAllocationMethod.Workload
            If WFTUser.WorkflowWeighting = 0 Then
              UserWeighting = 1
            Else
              UserWeighting = WFTUser.WorkflowWeighting
            End If
          Case Else: UserWeighting = 1
        End Select

        If WFTUser.ActiveResolved And UserWeighting &gt; 0 Then
          Row = dt.NewRow()
          Row!UserPk = WFTUser.UserPk
          Row!UserWeighting = UserWeighting
          Row!AllocationCurrent = 0
          dt.Rows.Add(Row)
        End If
      Next
    End If

    If dt.Rows.Count = 1 Then
      ' Only one active so easy allocation to that user
      UserPk = Row!UserPk
    ElseIf dt.Rows.Count &gt; 1 Then
      Select Case .AllocationMethod
        Case isefinWorkflowAllocationMethod.Custom
          UserPk = SuggestedWorkflowUserPk_Custom(workflow, dt)
        Case isefinWorkflowAllocationMethod.Proportional
          UserPk = SuggestedWorkflowUserPk_Proportional(workflow, dt)
        Case isefinWorkflowAllocationMethod.Random
          UserPk = SuggestedWorkflowUserPk_Random(workflow, dt)
        Case isefinWorkflowAllocationMethod.Workload
          UserPk = SuggestedWorkflowUserPk_Workload(workflow, dt)
        Case Else
          ' not included
      End Select
    End If
  End With

  ' Fall back to current allocated user
  If UserPk &lt;= 0 Then UserPk = workflow.AllocatedUserPk

  Return UserPk
    
End Function

Private Function SuggestedWorkflowUserPk_Custom(ByVal workflow As finWorkflow, ByVal dt As DataTable) As Integer

  Dim sqb As ISSelectQueryBuilder
  Dim dr As IDataReader

  Dim i As Integer
  Dim r As Integer
  Dim Pass As Integer
  Dim Row As DataRow

  Dim UserPk As Integer
  
  For Pass = 1 To 3
    UserPk = 0

    Select Case Pass
      Case 1
        ' Sample 1 - Retain user if workflow was opened from another workflow
        If workflow.OpenedFromWorkflowPk &gt; 0 Then
          sqb = finBL.Database.CreateSelectQueryBuilder()

          ' Build Query
          With sqb
            .Clear()
            .Table = "Workflow"
            .Fields.Add("AllocatedUserPk")
            .SqlWhere.AppendComparisonInteger("Pk", "=", workflow.OpenedFromWorkflowPk)
          End With

          If Not sqb.GetScalarInteger(UserPk) Then Exit For
        End If
      Case 2
        ' Sample 2 - Find user from last occurance of this workflow for this Object
          sqb = finBL.Database.CreateSelectQueryBuilder()

          ' Build Query
          With sqb
            .Clear()
            .Table = "Workflow"
            .Fields.Add("AllocatedUserPk")
            .Fields.Add("Status")
            .Fields.Add("WorkflowTypePk")
            .SqlWhere.AppendComparisonInteger("Workflow.Pk","&lt;&gt;", workflow.Pk)

            ' Currently workflows only for Accounts
            .SqlWhere.AppendComparisonInteger("AccountPk", "=", workflow.AccountPk)

            .OrderByFields.Add("Status")
            .OrderByFields.Add("OpenedDate", True)
          End With

          If sqb.ExecuteDisconnectedDataReader(dr) Then
            i = 0
            Do While dr.Read()
              r = finBL.Database.GetFieldInteger(dr!Status)

              ' hold fall back of latest open
              If r &lt;&gt; isefinWorkflowStatus.Closed And i = 0 Then i = finBL.Database.GetFieldInteger(dr!AllocatedUserPk)

              r = finBL.Database.GetFieldInteger(dr!WorkflowTypePk)
              If workflow.WorkflowType.Category = finBL.WorkflowTypes.ItemByPk(r).Category Then
                UserPk = finBL.Database.GetFieldInteger(dr!AllocatedUserPk)
                Exit Do
              End If
            Loop
            finBL.Database.DataReaderClose(dr)

            If UserPk = 0 Then UserPk = i
          End If

      Case Else
        ' Use Random as fallback
        UserPk = SuggestedWorkflowUserPk_Random(workflow, dt)
    End Select

    ' check suggested user is valid from this type, if ok do not continue
    UserPk = -UserPk
    For Each Row In dt.Rows
      If -UserPk = Row!UserPk Then
        UserPk = Row!UserPk
        Exit For
      End If
    Next
    If UserPk &gt; 0 Then Exit For
  Next

  Return UserPk
  
End Function

Private Function SuggestedWorkflowUserPk_Proportional(ByVal workflow As finWorkflow, ByVal dt As DataTable) As Integer

  Dim sqb As ISSelectQueryBuilder
  Dim dr As IDataReader

  Dim i As Integer
  Dim Row As DataRow

  Dim UserWeightingTotal As Decimal
  Dim AllocationTotal As Decimal
  Dim AllocationRate As Decimal
  Dim AllocationBestRate As Decimal

    ' Initialise
    SuggestedWorkflowUserPk_Proportional = 0

    ' Get UserAllocationTotal
    UserWeightingTotal = 0
    For Each Row In dt.Rows
      UserWeightingTotal += Row!UserWeighting
    Next

    ' Get current allocation counts
    sqb = finBL.Database.CreateSelectQueryBuilder()

    ' Build Query
    With sqb
      .Clear()
      .Table = "Workflow"
      .Fields.Add("AllocatedUserPk")
      .Fields.AddCount("Count")
      .SqlWhere.AppendComparisonInteger("Status", "=", CInt(isefinWorkflowStatus.Open))
      .SqlWhere.AppendComparisonInteger("WorkflowTypePk","=",CInt(workflow.WorkflowTypePk))
      .SqlWhere.AppendComparisonInteger("Workflow.Pk","&lt;&gt;",CInt(workflow.Pk))
      .GroupByFields.Add("AllocatedUserPk")
    End With

    ' Add in current allocations
    If sqb.ExecuteDisconnectedDataReader(dr) Then
      Do While dr.Read()
        For Each row In dt.Rows
          If Row!UserPk = finBL.Database.GetFieldInteger(dr!AllocatedUserPk)
            Row!AllocationCurrent = finBL.Database.GetFieldDecimal(dr!Count)
            AllocationTotal += row!AllocationCurrent
            Exit For
          End If
        Next
      Loop
      finBL.Database.DataReaderClose(dr)
    End If

    ' Calculations
    i = 0
    For Each Row In dt.Rows
      i += 1

      ' Find the total that should have been allocated
      AllocationRate = AllocationTotal * Row!UserWeighting / UserWeightingTotal

      ' Then Deduct that currently allocated
      AllocationRate = AllocationRate - Row!AllocationCurrent

      ' Check if best to allocate to
      If i = 1 OrElse AllocationRate &gt; AllocationBestRate Then
        AllocationBestRate = AllocationRate
        SuggestedWorkflowUserPk_Proportional = Row!UserPk
      End If
    Next

End Function

Private Function SuggestedWorkflowUserPk_Random(ByVal workflow As finWorkflow, ByVal dt As DataTable) As Integer

  Dim i As Integer
  Dim r As Integer
  Dim Row As DataRow

    SuggestedWorkflowUserPk_Random = 0

    r = Int(Rnd() * dt.Rows.Count + 1)
    i = 0
    For Each Row In dt.Rows
      i += 1
      If r = i Then
        SuggestedWorkflowUserPk_Random = Row!UserPk
        Exit For
      End If
    Next

End Function

Private Function SuggestedWorkflowUserPk_Workload(ByVal workflow As finWorkflow, ByVal dt As DataTable) As Integer

  Dim sqb As ISSelectQueryBuilder
  Dim dr As IDataReader

  Dim i As Integer
  Dim r As Integer
  Dim Row As DataRow

  Dim UserWeightingTotal As Decimal
  Dim WorkflowWeighting As Decimal
  Dim AllocationTotal As Decimal
  Dim AllocationRate As Decimal
  Dim AllocationBestRate As Decimal

    ' Initialise
    SuggestedWorkflowUserPk_Workload = 0

    ' Get UserAllocationTotal
    UserWeightingTotal = 0
    For Each Row In dt.Rows
      UserWeightingTotal += Row!UserWeighting
    Next

    ' Get current allocation counts
    sqb = finBL.Database.CreateSelectQueryBuilder()

    ' Build Query
    With sqb
      .Clear()
      .Table = "Workflow"
      .Fields.Add("AllocatedUserPk")
      .Fields.Add("WorkflowTypePk")
      .Fields.AddCount("Count")
      .SqlWhere.AppendComparisonInteger("Status", "=", CInt(isefinWorkflowStatus.Open))
      .SqlWhere.AppendComparisonInteger("Workflow.Pk","&lt;&gt;", CInt(workflow.Pk))
      .GroupByFields.Add("AllocatedUserPk")
      .GroupByFields.Add("WorkFlowTypePk")
    End With

    ' Add in current allocations
    If sqb.ExecuteDisconnectedDataReader(dr) Then
      Do While dr.Read()
        For Each row In dt.Rows
          If Row!UserPk = finBL.Database.GetFieldInteger(dr!AllocatedUserPk)
            r = finBL.Database.GetFieldInteger(dr!WorkflowTypePk)
            WorkflowWeighting = finBL.WorkflowTypes.ItemByPk(r).Weighting
            If WorkflowWeighting = 0 Then WorkflowWeighting = 1
            AllocationRate = finBL.Database.GetFieldDecimal(dr!Count) * WorkflowWeighting
            Row!AllocationCurrent += AllocationRate
            AllocationTotal += AllocationRate

            Exit For
          End If
        Next
      Loop
      finBL.Database.DataReaderClose(dr)
    End If

    ' Calculations
    i = 0
    For Each Row In dt.Rows
      i += 1

      ' Find the total that should have been allocated
      AllocationRate = AllocationTotal * Row!UserWeighting / UserWeightingTotal

      ' Then Deduct that currently allocated
      AllocationRate = AllocationRate - Row!AllocationCurrent

      ' Check if best to allocate to
      If i = 1 OrElse AllocationRate &gt; AllocationBestRate Then
        AllocationBestRate = AllocationRate
        SuggestedWorkflowUserPk_Workload = Row!UserPk
      End If
    Next

End Function</Code>
    <Language>VisualBasic</Language>
    <Notes>WARNING: Please ensure this script fits your purposes before using.</Notes>
    <PermissionKeyExecute />
    <RunWithoutPrompts>false</RunWithoutPrompts>
    <TemplateText />
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>ECFs3KzQGEikJFr5N5a+hQ</UniqueId>
    <RunAsAdministrator>false</RunAsAdministrator>
    <TargetObjectType>Workflow</TargetObjectType>
    <ParametersType>None</ParametersType>
  </finScript>