<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2025-07-16T20:59:26.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2025-06-17T01:45:53.2370000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2025-07-16T20:59:03.9470000</UpdatedUtcDate>
    <ScriptId>AUBSBIMPORT</ScriptId>
    <Description>Download and Import the latest AUPayNet BSB list</Description>
    <ScriptType>GeneralUserInterface</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' Script_AustralianBsbImport.xml
Option Explicit On
Option Strict On

' #################################################################
' This script will download the latest BSB Json file from the Australian Payments Network using their API.
' It then converts and saves the BSB to APCAL format which finPOWER can read.
' It then prompts to import the BSB list into finPOWER using the file it just generated.
'
' If in test mode, it will also prompt to save the json downloaded from the API.
' 
' (c) Copyright Intersoft Systems Limited 2024
' 
' Version: 1.01 (17/07/2025)
' 
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.00  16/10/2024  ISS      J033902   Created
'    1.01  17/07/2025  ISS      J035435   Updated to handle API changes      
' #################################################################

' Constants
'#const "APIKey",String,"","The Australian Payments Network API Key."
'#const "ClearExisting",Boolean,True,"Should existing Bank Branches be cleared?"
'#const "JsonFilePath",String,"","The path to the JSON file from a previous BSB download. If specified, the download process will be skipped."
'#const "UpdateExisting",Boolean,False,"Should existing Bank Branches be updated?"

' Script Constants
Private mAPIKey As String = ""
Private mClearExisting As Boolean = True
Private mJsonFilePath As String = ""
Private mUpdateExisting As Boolean = False

' Objects
Private WithEvents mBankBranchImport As finBankBranchImportExport

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

  Dim APCALOutputFilePath As String
  Dim BSBItem As OutputItem
  Dim BSBList As OutputItems
  Dim BSBListCount As Integer
  Dim FileWriter As ISFileWriter
  Dim Index As Integer
  Dim Obj As Object
  Dim RequestData As String
  Dim ResponseData As Response
  Dim ResponseJson As String
  Dim StrTemp As String
  Dim Success As Boolean
  Dim WebClient As ISHttpClient
  
  ' Assume Success
  Success = True

  ' Constants
  With ScriptInfo.Constants
    mAPIKey = .GetString("APIKey", mAPIKey)
    mClearExisting = .GetBoolean("ClearExisting", mClearExisting)
    mJsonFilePath = .GetString("JsonFilePath", mJsonFilePath)
    mUpdateExisting = .GetBoolean("UpdateExisting", mUpdateExisting)
  End With
  
  ' Initialise
  BSBList = New OutputItems()
  mBankBranchImport = finBL.CreateBankBranchImportExport()
  
  ' Begin Process
  finBL.StatusProcessBegin("Importing BSB list", "Please wait...", False)
  
  If String.IsNullOrEmpty(mJsonFilePath) Then
    ' Download the latest BSB from Aus Pay Net
    finBL.StatusProcess(0, "Downloading from web")
    WebClient = finBL.Runtime.CreateHttpClient()
    With WebClient
      .TimeoutSeconds=0
  
      With .RequestHeaders
        .Add("Cache-Control", "no-cache")
        .Add("Content-Type", "application/json")
        .Add("Accept", "application/json")
        .Add("Ocp-Apim-Subscription-Key", mAPIKey)
      End With  
      
      ' Available request parameters (all optional): "{""FiMnemonic"": """",""Postcode"": """",""State"": """",""StreamCode "": """",""Suburb"": """",""bic"": """",""bicint"": """",""bsbcode"": """",""changedate "": """",""repair"": """",""outputparam"": """"}"
      RequestData = "{}"
      
      If .Execute(iseWebServiceMethod.Post, "https://auspaynet-bicbsb-api-prod.azure-api.net/bsbquery-v2/manual/paths/invoke", RequestData, ResponseJson) Then
        Success = True
        
        ' Prompt to save json response. Only do this if in test mode.
        If finBL.Runtime.ForceTestModeResolved Then
          If userInterface.MsgBox("Would you like to save the json response?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
            If userInterface.CommonDialog.GetFileSave(StrTemp, "AUBsbJsonResponse",, "Text Files (*.txt)|*.txt", ".txt", False, True, finBL.DocumentManager.LocalFolder) Then
              ' Save json response
              Success = finBL.Runtime.FileUtilities.WriteTextFile(StrTemp, ResponseJson)
            End If
          End If 
        End If
      Else
        Success = False
      End If
    End With
  Else
    ' Read existing
    finBL.StatusProcess(0, "Reading existing json file")
    Success = finBL.Runtime.FileUtilities.ReadTextFile(mJsonFilePath, ResponseJson)
  End If
  
  ' Validate Response
  If Success Then
    If String.IsNullOrEmpty(ResponseJson)
      ' Invalid
      Success = False 
      finBL.Error.ErrorBegin("Invalid BSB Json")
    End If
  End If  
  
  ' Deserialise the Response
  If Success Then
    If finBL.Runtime.WebUtilities.DeserialiseJsonStringToObject(ResponseJson, GetType(Response), Obj) Then
      ResponseData = DirectCast(Obj, Response)
    Else
      Success = False
    End If
  End If
  
  ' Deserialise the data (bsb json string) into a list
  If Success Then
    If finBL.Runtime.WebUtilities.DeserialiseJsonStringToObject(ResponseData.data, GetType(OutputItems), Obj) Then
      BSBList = DirectCast(Obj, OutputItems)
    Else
      ' Invalid
      Success = False
    End If
  End If
  
  If Success Then
    ' Get file path for APCAL file
    If Not userInterface.CommonDialog.GetFileSave(APCALOutputFilePath, "BSB_APCAL_Output.txt",, "Text Files (*.txt)|*.txt", ".txt", False, True, finBL.DocumentManager.LocalFolder) Then
      Success = False
      finBL.Error.ErrorBegin("Output File path not specified.")
    End If
  End If 
  
  ' Convert data to temporary APCAL (text) file
  If Success Then
    ' Update Process
    finBL.StatusProcess(0, String.Format("Saving to file '{0}'", APCALOutputFilePath))
    
    ' Open the file
    FileWriter = finBL.Runtime.CreateFileWriter()
    If FileWriter.Open(APCALOutputFilePath) Then
      ' Initialise loop vars
      BSBListCount = BSBList.Count
      Index = 0
      
      For Each BSBItem In BSBList
        ' Iterate
        Index += 1
        
        ' Notify Progress
        finBL.StatusProcess(Index / BSBListCount * 100)
        
        ' Build line
        StrTemp = AsFixedWidth(BSBItem.BSBCode, 7)
        StrTemp &amp;= AsFixedWidth(BSBItem.FiMnemonic, 3)
        StrTemp &amp;= AsFixedWidth(BSBItem.BSBName, 35)
        StrTemp &amp;= AsFixedWidth(BSBItem.Address, 35)
        StrTemp &amp;= AsFixedWidth(BSBItem.Suburb, 20)
        StrTemp &amp;= AsFixedWidth(BSBItem.State, 3)
        StrTemp &amp;= AsFixedWidth(BSBItem.Postcode, 4)
        StrTemp &amp;= BSBItem.StreamCode        
        
        ' Write line
        If Not FileWriter.WriteLine(StrTemp) Then
          ' Halt Process
          Success = False
          Exit For
        End If
      Next
      
      ' Close Writer
      FileWriter.Close()
    Else
      Success = False
    End If
  End If
  
  ' Import?
  If Success Then
    If userInterface.MsgBox("Do you want to import the BSB list now?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
      finBL.StatusProcess(0, "Importing BSB list")
      
      ' Initialise
      mBankBranchImport = finBL.CreateBankBranchImportExport()
      
      ' Import
      Success = mBankBranchImport.Import(APCALOutputFilePath, isefinBankBranchFileType.APCAL, mClearExisting, mUpdateExisting)  
    End If
  End If
  
  ' End Process
  finBL.StatusProcessEnd()  
  
  ' Reset Global Collection
  finBL.BankBranches.Refresh()
  
  ' Notify
  If Not Success Then
    finBL.Error.ErrorExtend("Failed to import Bank Branches. One or more errors occured.")
  End If
  
  Return Success

End Function

Public Sub BankBranchImport_ImportProgress(progress As Double, caption As String) Handles mBankBranchImport.ImportProgress
  Dim Cancelled As Boolean
  
  ' Initialise
  Cancelled = False
  
  finBL.StatusProcess(progress, caption, Cancelled)
  
  ' Cancelled?
  If Cancelled Then
    mBankBranchImport.Cancel()
  End If
End Sub

Public Function AsFixedWidth(text As String, length As Integer) As String
  Return text.PadRight(length).Substring(0, length)
End Function

Class OutputItems : Inherits List(Of OutputItem)
End Class 

Class Response
  Public status As String
  Public message As String
  Public timestamp As DateTime
  Public requestId As String
  Public data As String
End Class

Class OutputItem
  Public BSBCode As String
  Public BSBName As String
  Public FiMnemonic As String
  Public Address As String
  Public Suburb As String
  Public State As String
  Public Postcode As String
  Public StreamCode As String
  Public lastmodified As String
  Public BIC As String
  Public BICINT As String
  Public repair As String
End Class</Code>
    <Language>VisualBasic</Language>
    <Notes>This utility script can be used in Australia to update BSB Information.

The script downloads the latest Australia BSB file from the Australian Payments Network using there web API and then adds the information to Bank Branches within finPOWER Connect. 

The following constants must be used:

APIKey
AusPayNet API Key. To obtain an API Key, sign up at https://auspaynet-bicbsb-api-prod.developer.azure-api.net

ClearExisting (default=True)
Indicates whether to clear all existing Bank Branches. If False, existing items will be updated.

UpdateExisting (default=False)
Indicates whether to update existing records. If False, existing items will not be updated.


The following constants are optional:

JsonFilePath
If specified, this file will be used instead of re-downloading the BSB list from the AusPayNet API.
This file should be the raw Json response from AusPayNet.</Notes>
    <PermissionKeyExecute />
    <RunWithoutPrompts>false</RunWithoutPrompts>
    <TemplateText />
    <TemplateTextBookmarks />
    <UniqueId>GNqVpFnEakCyi0GHf-4HpA</UniqueId>
    <AllowSaveLoadParametersOnExecute>true</AllowSaveLoadParametersOnExecute>
    <RunAsAdministrator>false</RunAsAdministrator>
    <ShowInMenu>None</ShowInMenu>
    <ParametersType>None</ParametersType>
  </finScript>