#Description: Example Custom Web Service Script to demonstrate applying 'Security Filters' on SQL querying Accounts.
#Author: Intersoft Systems Limited
#Version: 1.01
#Last Updated: 07/02/2024

Option Explicit On
Option Strict On

' #################################################################
' Custom Web Service to retrieve a list of Client's Accounts

' Version: 1.00 (12/05/2014)

' Usage: Code Snippet to demonstrate 'Security Filters' on SQL
'        querying Accounts.
'
'        Call this Web Service passing in a 'ClientId' parameter as
'        part of the URL.
' #################################################################

Public Function Main(request As finwsHttpRequest) As finwsHttpResponse

  Dim ClientAccount As ClientAccount
  Dim ClientAccounts As List(Of ClientAccount)
  Dim ClientId As String
  Dim dr As IDataReader
  Dim ErrorCode As String
  Dim ErrorStatusCode As HttpStatusCode
  Dim Ok As Boolean
  Dim sqb As ISSelectQueryBuilder

  ' Assume Success
  Ok = True

  ' Initialise
  ErrorStatusCode = HttpStatusCode.BadRequest

  ' Get Parameters
  ClientId = request.Parameters.GetString("ClientId")

  ' Validate
  If Len(ClientId) = 0 Then
    Ok = False
    finBL.Error.ErrorBegin("Client Id not specified.")
    ErrorCode = "ClientId.NotSpecified"
  End If

  If Ok Then
    ' Create Objects
    ClientAccounts = New List(Of ClientAccount)
    sqb = finBL.Database.CreateSelectQueryBuilder()

    ' Build Query
    With sqb
      .Clear()
      .Table = "Account"

      ' Add Fields
      .Fields.AddList("Account.AccountId,Account.Name")
      .Fields.AddList("AccountClient.RoleType,AccountClient.SendDocuments")

      ' Joins
      With .Joins
        .Add("AccountClient", "AccountClient.AccountPk", "Account.Pk")
        .Add("Client", "Client.Pk", "AccountClient.ClientPk")
      End With

      ' SQL Where
      With .SqlWhere
        ' Restrict to specified Client's Accounts
        .AppendComparisonString("Client.ClientId", "=", ClientId)

        ' Ensure Account is not hidden from this Client
        .AppendComparisonIntegerBoolean("AccountClient.AccountHidden", "=", False)

        ' Security Filters
        Select Case request.AuthenticatedUserType
          Case isefinwsAuthenticatedUserType.Client
            ' Restrict to Authenticated Client
            .AppendComparisonString("Client.ClientId", "=", request.AuthenticatedClientId)

          Case Else
            ' User Filters
            .Append(finBL.CurrentUserInformation.FilterAccountSqlWhere)
        End Select
      End With

      ' Order By
      .OrderByFields.Add("Account.AccountId")
    End With

    ' Execute Query
    If sqb.ExecuteDisconnectedDataReader(dr) Then
      Do While dr.Read()
        ' Create Client Account
        ClientAccount = New ClientAccount()
        With ClientAccount
          .AccountId = finBL.Database.GetFieldString(dr!AccountId)
          .AccountName = finBL.Database.GetFieldString(dr!Name)
          .RoleType = finBL.Enums.isefinAccountRoleType_ToString(DirectCast(finBL.Database.GetFieldEnum(dr!RoleType, GetType(isefinAccountRoleType)), isefinAccountRoleType))
          .SendDocuments = finBL.Database.GetFieldIntegerBoolean(dr!SendDocuments)
        End With

        ' Add
        ClientAccounts.Add(ClientAccount)
      Loop

      finBL.Database.DataReaderClose(dr)
    Else
      Ok = False
      ErrorCode = "Query.ExecuteFailed"
    End If
  End If

  ' Return Response
  If Ok Then
    ' Return list of Accounts
    Return request.CreateResponse(HttpStatusCode.OK, ClientAccounts)
  Else
    ' Error
    Return request.CreateErrorResponse(ErrorStatusCode, String.Format("Failed to execute custom Web Service Script '{0}'.", ScriptInfo.ScriptId), ErrorCode, finBL.Error.Message())
  End If

End Function


Public Class ClientAccount

  Public AccountId As String
  Public AccountName As String
  Public RoleType As String
  Public SendDocuments As Boolean

End Class