<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2022-09-20T23:34:26.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2017-02-01T20:20:26.8440000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2022-09-20T23:34:12.7620000</UpdatedUtcDate>
    <ScriptId>NZBNCUP</ScriptId>
    <Description>Update NZBN for existing Clients</Description>
    <ScriptType>General</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Category />
    <Code>' Script_ClientUpdateNZBN.xml
Option Explicit On
Option Strict On

' #################################################################
' Sample Script to update NZBN for existing Clients.
' 
' Version: 1.02 (21/09/2022)
' 
' WARNING: Sample Script, please ensure this script fits your purposes before using.
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.01  16/07/2021  ISS      J026950   Cleaned up unused variables
'          20/08/2021  ISS      J027260   Removed reference to old configuration
'    1.02  21/09/2022  ISS      J029586   Fixed compilation warnings
' #################################################################

'#Const "MatchClientCompanyNumberOnly",Boolean,True,"Boolean flag to indicate whether to match on the Client Company Number only."
'#Const "MatchClientCompanyNumberAndLegalName",Boolean,False,"Boolean flag to indicate whether to match on the Client Company Number and Legal Name."
'#Const "MaximumClients",Integer,100,"Maximum number of Clients to check."
'#Const "UpdateClientBusinessNumber",Boolean,False,"Boolean flag to indicate whether to update the Business Number (NZBN) on the Client."
'#Const "UpdateClientLegalName",Boolean,False,"Boolean flag to indicate whether to update the Legal Name on the Client."

' Constants
Private MatchClientCompanyNumberAndLegalName As Boolean = False
Private MatchClientCompanyNumberOnly As Boolean = True
Private MaximumClients As Integer = 100
Private UpdateClientBusinessNumber As Boolean = False
Private UpdateClientLegalName As Boolean = False

Public Function Main(ByVal parameters As ISKeyValueList) As Boolean

  Dim Client As finClient
  Dim dr As IDataReader
  Dim ExcelWorkbook As ISExcelWorkbook
  Dim InformationMessage As String
  Dim NZBN As String
  Dim NZBNEntity As ISCreditEnquiryResponse_NZGovernment_NZBNEntitySearchByNameResult
  Dim NZBNName As String
  Dim Row As Integer
  Dim sqb As ISSelectQueryBuilder
  Dim Success As Boolean
  Dim UpdatedMessage As String

  ' Assume Success
  Success = True

  ' Get Constants
  With ScriptInfo.Constants
    MatchClientCompanyNumberAndLegalName = .GetBoolean("MatchClientCompanyNumberAndLegalName", MatchClientCompanyNumberAndLegalName)
    MatchClientCompanyNumberOnly = .GetBoolean("MatchClientCompanyNumberOnly", MatchClientCompanyNumberOnly)
    MaximumClients = .GetInteger("MaximumClients", MaximumClients)
    UpdateClientBusinessNumber = .GetBoolean("UpdateClientBusinessNumber", UpdateClientBusinessNumber)
    UpdateClientLegalName = .GetBoolean("UpdateClientLegalName", UpdateClientLegalName)
  End With

  ' Create the file and write the header
  ExcelWorkbook = finBL.CreateExcelWorkbook()
  With ExcelWorkbook
    .Worksheets.Add("NZBN")

    ' Header
    With .Worksheets(0)
      .Rows(1).Style.Bold = True
      .Cell(1,1).SetString("ClientId")
      .Cell(2,1).SetString("Name")
      .Cell(3,1).SetString("CompanyNumber")
      .Cell(4,1).SetString("NZBN")
      .Cell(5,1).SetString("NZBNName")
      .Cell(6,1).SetString("Updated")
      .Cell(7,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
    ExcelWorkbook = Nothing
    Success = False
  End If

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

    sqb = finBL.Database.CreateSelectQueryBuilder()
    With sqb
      .Table = "Client"
      .Fields.AddList("Pk")
      With .SqlWhere
        ' Limit to Clients that have an Organisation (Company) number but not a Business (NZBN) number.
        .AppendComparisonNotNull("OrganisationNumber")
        .AppendComparisonNull("BusinessNumber")
      End With
      If MaximumClients &gt; 0 Then .TopLimit = MaximumClients
      .OrderByFields.Add("Pk")
    End With

    ' Execute Query
    If sqb.ExecuteDisconnectedDataReader(dr, 0, ScriptInfo.TimeoutSeconds) Then
      With dr
        Row = 1
        Do While .Read
          ' Increment Row
          Row += 1

          ' Load Client
          If Client.LoadPk(finBL.Database.GetFieldInteger(!Pk)) Then
            If Me.UpdateClient(Client, NZBNEntity, UpdatedMessage, InformationMessage) Then
              ' Client updated
              NZBN = NZBNEntity.NewZealandBusinessNumber
              NZBNName = NZBNEntity.EntityName
            Else
              ' Client not updated
              NZBN = ""
              NZBNName = ""
            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(Client.OrganisationNumber)
              .Cell(4, Row).SetString(NZBN)
              .Cell(5, Row).SetString(NZBNName)
              .Cell(6, Row).SetString(UpdatedMessage)
              .Cell(7, Row).SetString(InformationMessage)
            End With
          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

  ' Return Success
  Return Success

End Function

Private Function UpdateClient(ByRef client As finClient,
                              ByRef NZBNEntity As ISCreditEnquiryResponse_NZGovernment_NZBNEntitySearchByNameResult,
                              ByRef updatedMessage As String,
                              ByRef informationMessage As String) As Boolean

  Dim NZBNMessage As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise ByRef
  informationMessage = ""

  ' Find NZBN
  Success = Me.FindNZBN(client, NZBNEntity, NZBNMessage, updatedMessage)

  If Success Then
    If UpdateClientBusinessNumber OrElse UpdateClientLegalName Then
      ' Update Properties
      If UpdateClientBusinessNumber Then
        Client.BusinessNumber = NZBNEntity.NewZealandBusinessNumber
      End If
      If UpdateClientLegalName Then
        ' Firstly, clear Legal Name if same as the Client Name
        If StrComp(Client.Name, Client.LegalName, CompareMethod.Text) = 0 Then
          Client.LegalName = ""
        End If

        If StrComp(Client.Name, NZBNEntity.EntityName, CompareMethod.Text) = 0 Then
          ' If Client Name is the NZBN Entity Name, then clear Legal Name
          Client.LegalName = ""
        Else
          Client.LegalName = NZBNEntity.EntityName
        End If
      End If

      ' Save Client
      If Client.Save() Then
        updatedMessage = "Yes"
      Else
        updatedMessage = "Error"
        informationMessage = finBL.Error.Message()
      End If
    End If
  Else
    informationMessage = NZBNMessage
  End If

  ' Return Success
  Return Success

End Function

Private Function FindNZBN(client As finClient,
                          ByRef NZBNEntity As ISCreditEnquiryResponse_NZGovernment_NZBNEntitySearchByNameResult,
                          ByRef informationMessage As String,
                          ByRef updatedMessage As String) As Boolean

  Dim NZBNEntitySearchByNameResult As ISCreditEnquiryResponse_NZGovernment_NZBNEntitySearchByNameResult
  Dim Request As ISCreditEnquiryRequest
  Dim Response As ISCreditEnquiryResponse
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise ByRef
  informationMessage = ""
  NZBNEntity = Nothing
  updatedMessage = ""

  ' Create Request
  Request = finBL.CreditBureau.CreateCreditEnquiryRequest("NZGovernment", iseProductClass.CompanySelection, "NZBN Entity Search v4", client.BranchPk)

  ' Update Request from Client
  Success = finBL.CreditBureau.UpdateCreditEnquiryRequestFromClient(Request, client)

  ' Search
  If Success Then
    Success = finBL.CreditBureau.ExecuteCompanySelection(Request, Response)
  End If

  If Success Then
    Select Case Response.GetType()
      Case GetType(ISCreditEnquiryResponse_NZGovernment_NZBNEntitySearchV4)
        ' ---------------------
        ' NZBN Entity Search v4
        ' ---------------------
        With DirectCast(Response, ISCreditEnquiryResponse_NZGovernment_NZBNEntitySearchV4)
          For Each NZBNEntitySearchByNameResult In .SearchResults
            With NZBNEntitySearchByNameResult
              If MatchClientCompanyNumberAndLegalName Then
                ' Match by Company Number AND Legal Name
                If .CompanyNumber = client.OrganisationNumber AndAlso StrComp(client.LegalNameResolved, .EntityName, CompareMethod.Text) = 0 Then
                  NZBNEntity = NZBNEntitySearchByNameResult
                  Exit For
                End If
              ElseIf MatchClientCompanyNumberOnly Then
                ' Match by Company Number only
                If .CompanyNumber = client.OrganisationNumber Then
                  NZBNEntity = NZBNEntitySearchByNameResult
                  Exit For
                End If
              End If
            End With
          Next

          ' Error
          If NZBNEntity Is Nothing Then
            Success = False
            informationMessage = String.Format("NZBN not found, {0} records retrieved.", .SearchResults.Count)
          End If
        End With

      Case Else
        Success = False
        finBL.Error.ErrorBegin("Invalid NZBN Response Type.")
    End Select
  End If

  ' Error
  If Not Success Then
    updatedMessage = "Error"
    If Len(informationMessage) = 0 Then informationMessage = finBL.Error.Message(True, False, True)
  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 NZBN on "Company" Clients that have a Company Number but no NZBN.

Note, you must have configured and verified the NZ Government Credit Bureau service under Cost Centres, NZ Government first.

The following constants can be used:

MatchClientCompanyNumberOnly (Boolean, default=True)
Indicates whether to match on the Client's Company Number only.

MatchClientCompanyNumberAndLegalName (Boolean, default=False)
Indicates whether to match on the Client Company Number and Legal Name.

Note, if True this takes precedence over the MatchClientCompanyNumberOnly constant.

MaximumClients (Integer, default=100)
Maximum number of Clients to check. This is used to limit the script to this number of Clients.

UpdateClientBusinessNumber (Boolean, default=False)
Indicates whether to update the Business Number (NZBN) on the Client.

UpdateClientLegalName (Boolean, default=False)
Indicates whether to update the Legal Name on the Client.</Notes>
    <PermissionKeyExecute />
    <RunWithoutPrompts>false</RunWithoutPrompts>
    <TemplateText />
    <TemplateTextBookmarks />
    <TimeoutSeconds>600</TimeoutSeconds>
    <UniqueId>fBIGEZkWjECwT18TiXAPzQ</UniqueId>
    <AllowSaveLoadParametersOnExecute>true</AllowSaveLoadParametersOnExecute>
    <ShowInAccountProcesses>false</ShowInAccountProcesses>
    <AccountProcessesRunByDefault>false</AccountProcessesRunByDefault>
    <RunAsAdministrator>false</RunAsAdministrator>
    <ShowInMenu>None</ShowInMenu>
    <ShowInTaskManager>false</ShowInTaskManager>
    <WebServiceName />
    <ParametersType>None</ParametersType>
    <Constants>
      <ISScriptConstants version="1.00">
        <ScriptConstant name="MatchClientCompanyNumberOnly" constantType="Boolean">
          <Notes>Boolean flag to indicate whether to match on the Client Company Number only.</Notes>
          <Value>true</Value>
        </ScriptConstant>
        <ScriptConstant name="MatchClientCompanyNumberAndLegalName" constantType="Boolean">
          <Notes>Boolean flag to indicate whether to match on the Client Company Number and Legal Name.</Notes>
          <Value>false</Value>
        </ScriptConstant>
        <ScriptConstant name="MaximumClients" constantType="Integer">
          <Notes>Maximum number of Clients to check.</Notes>
          <Value>100</Value>
        </ScriptConstant>
        <ScriptConstant name="UpdateClientBusinessNumber" constantType="Boolean">
          <Notes>Boolean flag to indicate whether to update the Business Number (NZBN) on the Client.</Notes>
          <Value>false</Value>
        </ScriptConstant>
        <ScriptConstant name="UpdateClientLegalName" constantType="Boolean">
          <Notes>Boolean flag to indicate whether to update the Legal Name on the Client.</Notes>
          <Value>false</Value>
        </ScriptConstant>
      </ISScriptConstants>
    </Constants>
  </finScript>