<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2022-09-21T00:02:11.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2017-03-13T22:41:11.9490000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2022-09-20T23:39:17.9420000</UpdatedUtcDate>
    <ScriptId>AKACUP</ScriptId>
    <Description>Update AKAs for existing Clients</Description>
    <ScriptType>GeneralUserInterface</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Category />
    <Code>' Script_ClientUpdateAKAs.xml
Option Explicit On
Option Strict On

' #################################################################
' Sample Script to update all Client AKAs to include or exclude as a Debtor in PPSR Financing Statements
' 
' Version: 1.01 (21/09/2022)
' 
' WARNING: Sample Script, please ensure this script fits your purposes before using.
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.00  14/03/2017  ISS
'    1.01  21/09/2022  ISS      J029586   Fixed compilation warnings
' #################################################################

'#Const "SecurityParty",Boolean,True,"Boolean flag to indicate whether to include the Individual Client AKAs as a Debtor in PPSR Financing Statements?"

' Constants
Private SecurityParty As Boolean = True

Public Function Main(userInterface As ISUserInterfaceBL, reports As ISfinReports, parameters As ISKeyValueList) As Boolean

  Dim Client As finClient
  Dim dr As IDataReader
  Dim ExcelWorkbook As ISExcelWorkbook
  Dim InformationMessage As String
  Dim Row As Integer
  Dim Success As Boolean
  Dim sqb As ISSelectQueryBuilder
  Dim sqbSub As ISSelectQueryBuilder
  Dim strTemp As String
  Dim UpdatedMessage As String

  ' Assume Success
  Success = True

  ' Get Constants
  With ScriptInfo.Constants
    SecurityParty = .GetBoolean("SecurityParty", SecurityParty)
  End With

  ' Check Permissions
  If finBL.Settings.AddOns.SecurityRegisterPPSR Then
    Select Case finBL.CountryCode
      Case "NZ"
        ' OK
      Case Else
        Success = False
        finBL.Error.ErrorBeginFormat("Unsupported country code {0}.", finBL.CountryCode)
    End Select
  Else
    Success = False
    finBL.Error.ErrorBegin("You are not licenced for the Security Register PPSR Add-On.")
  End If

  ' Confirmation
  If Success Then
    If SecurityParty Then
      Select Case userInterface.MsgBoxEx("WARNING: This will set all Individual Client AKAs to be INCLUDED as Debtors in PPSR Financing Statements." &amp; vbNewLine &amp; vbNewLine &amp; "Continue?", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2)
        Case MsgBoxResult.Yes
        Case Else
          Success = False
          finBL.Error.ErrorBegin("User cancelled.")
      End Select
    Else
      Select Case userInterface.MsgBoxEx("WARNING: This will set all Individual Client AKAs to be EXCLUDED as Debtors in PPSR Financing Statements." &amp; vbNewLine &amp; vbNewLine &amp; "Continue?", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2)
        Case MsgBoxResult.Yes
        Case Else
          Success = False
          finBL.Error.ErrorBegin("User cancelled.")
      End Select
    End If
  End If

  ' Create the file and write the header
  If Success Then
    ExcelWorkbook = finBL.CreateExcelWorkbook()
    With ExcelWorkbook
      .Worksheets.Add("AKAs")

      ' Header
      With .Worksheets(0)
        .Rows(1).Style.Bold = True
        .Cell(1,1).SetString("ClientId")
        .Cell(2,1).SetString("Name")
        .Cell(3,1).SetString("Updated")
        .Cell(4,1).SetString("Information")
      End With
    End With

    If ExcelWorkbook.Save(String.Format("{0}{1}_{2}.xls", finBL.SettingsUser.ExportDataFolderResolved(True), finBL.Runtime.FileUtilities.GetFileNameCleaned(ScriptInfo.ScriptId), Format(finBL.Runtime.TimeZoneUtilities.GetCurrentLocalDateTime,"yyyyMMdd_HHmmss")))
      ' OK
    Else
      Success = False
      ExcelWorkbook = Nothing
    End If
  End If

  ' Process Clients
  If Success Then
    ' Initialise
    Client = finBL.CreateClient()

    ' Create AKA Sub Query
    sqbSub = finBL.Database.CreateSelectQueryBuilder()
    With sqbSub
      .Table = "ClientAKA"
      .DistinctType = iseSelectQueryDistinctType.Distinct
      .Fields.AddList("ClientPk")
      With .SqlWhere
        ' Limit to AKAs that are not set to the constant
        .AppendComparisonIntegerBoolean("SecurityParty", "&lt;&gt;", SecurityParty)
      End With
    End With

    ' Create Client Query
    sqb = finBL.Database.CreateSelectQueryBuilder()
    With sqb
      .Table = "Client"
      .Fields.AddList("Pk")
      With .SqlWhere
        ' Limit AKA list
        .AppendInSubQuery("Pk", sqbSub, False)

        ' Limit to Individuals
        strTemp = finBL.ClientTypes.GetIndividualPksList(False).ToCsvString()
        If Len(strTemp) &lt;&gt; 0 Then
          .AppendRange("ClientTypePk", strTemp, iseRangeDataType.Integer)
        End If
      End With
      .OrderByFields.Add("ClientId")
    End With

    ' Execute Query
    If sqb.ExecuteDisconnectedDataReader(dr, 0, ScriptInfo.TimeoutSeconds) Then
      With dr
        Row = 1
        Do While .Read
          ' Load Client
          If Client.LoadPk(finBL.Database.GetFieldInteger(!Pk)) Then
            If Client.IsIndividual Then
              ' Increment Row
              Row += 1

              ' Update Client AKAs
              If Me.UpdateAkas(Client, SecurityParty, UpdatedMessage, InformationMessage) Then
                ' OK
              End If

              ' Output to Excel
              With ExcelWorkbook.Worksheets(0)
                .Cell(1, Row).SetString(Client.ClientId)
                .Cell(2, Row).SetString(Client.Name)
                .Cell(3, Row).SetString(UpdatedMessage)
                .Cell(4, Row).SetString(InformationMessage)
              End With
            End If
          Else
            Success = False
            Exit Do
          End If
        Loop
      End With
      finBL.Database.DataReaderClose(dr)
    Else
      Success = False
    End If
  End If

  ' Save Workbook (ignore errors)
  If ExcelWorkbook IsNot Nothing Then
    ' Autofit Columns
    ExcelWorkbook.Worksheets(0).Columns.Autofit

    If ExcelWorkbook.Save() Then
      ' Open Workbook
      finBL.OpenAssociatedApplication(ExcelWorkbook.Filename)
    End If
  End If

  ' Error
  If Not Success Then
    finBL.Error.ErrorExtend("Failed to update AKAs for existing Clients.")
  End If

  ' Return Success
  Return Success

End Function

Private Function UpdateAkas(ByRef client As finClient,
                            securityParty As Boolean,
                            ByRef updatedMessage As String,
                            ByRef informationMessage As String) As Boolean

  Dim ClientAka As finClientAka
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise ByRef
  informationMessage = ""

  ' Set the SecurityParty flag
  For Each ClientAka In client.Akas
    If ClientAka.SecurityParty &lt;&gt; securityParty Then
      If Len(informationMessage) &lt;&gt; 0 Then informationMessage &amp;= vbNewLine
      informationMessage &amp;= String.Format("{0} - {1}, SecurityParty set to {2}", ClientAka.Pk, ClientAka.NameFull, securityParty)
      ClientAka.SecurityParty = securityParty
    End If
  Next

  ' Save Client
  If Len(informationMessage) = 0 Then
    updatedMessage = "No"
    informationMessage = "Nothing to update"
  Else
    If Client.Save() Then
      updatedMessage = "Yes"
    Else
      Success = False
      updatedMessage = "Error"
      informationMessage = finBL.Error.Message()
    End If
  End If

  ' Return Success
  Return Success

End Function</Code>
    <Language>VisualBasic</Language>
    <Notes>This utility script can be used in New Zealand to update the SecurityParty flag on "Individual" Clients that have an AKA.

The following constants can be used:

SecurityParty(Boolean, default=True)
Indicates whether to include the AKA as a Debtor when registering a Security Statement.</Notes>
    <PermissionKeyExecute />
    <RunWithoutPrompts>false</RunWithoutPrompts>
    <TemplateText />
    <TemplateTextBookmarks />
    <TimeoutSeconds>600</TimeoutSeconds>
    <UniqueId>NGd01wgUMUeCsGfV4P4png</UniqueId>
    <AllowSaveLoadParametersOnExecute>true</AllowSaveLoadParametersOnExecute>
    <RunAsAdministrator>false</RunAsAdministrator>
    <ShowInMenu>None</ShowInMenu>
    <ParametersType>None</ParametersType>
    <Constants>
      <ISScriptConstants version="1.00">
        <ScriptConstant name="SecurityParty" constantType="Boolean">
          <Notes>Boolean flag to indicate whether to include the Individual Client AKAs as a Debtor in PPSR Financing Statements?</Notes>
          <Value>true</Value>
        </ScriptConstant>
      </ISScriptConstants>
    </Constants>
  </finScript>