Imports System.Data.SqlClient
Imports System.EnterpriseServices
Imports System.IO
Imports System.Net
Imports System.Reflection
Imports DocumentFormat.OpenXml.InkML

Public Class cMSEAPI

    Public API_STRING
    Dim API As New DataTable
    Dim rest As New Chilkat.Rest
    Dim defaultDebugLogFilePath = ""
    Dim SQL As New SQL
    Dim apiSettingsloaded As Boolean = False
    Dim test As Boolean = False
    Dim PDFRECHNUNGENPFAD As String = ""


    Sub New(program As String)
        VERAG_PROG_ALLGEMEIN.cChilkat_Helper.UnlockCilkat()
        API = SQL.loadDgvBySql("SELECT top(1) * FROM tblAPIEinstellungen WHERE api_program='" & program & "' and api_productive ='" & IIf(VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM, "0", "1") & "'", "ADMIN")
        If API.Rows.Count = 0 Then
            MsgBox("keine gültigen API-Einstellungen für " & program & " gefunden!")
        Else
            apiSettingsloaded = True
            API_STRING = API.Rows(0).Item("api_url")
            If Not IsDBNull(API.Rows(0).Item("api_debugpath")) AndAlso API.Rows(0).Item("api_debugpath") <> "" Then
                rest.VerboseLogging = True
                rest.DebugLogFilePath = API.Rows(0).Item("api_debugpath") & program & IIf(VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM, "_Test", "") & ".txt"
            Else
                rest.VerboseLogging = False
            End If

            PDFRECHNUNGENPFAD = Me.GET_PARAM_ByName("PDFRECHNUNGEN-PFAD", VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM)

        End If

    End Sub


    Shared Function GET_PARAM_ByName(tcParam_name, TESTSYSTEM) As String
        Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
        Return SQL.getValueTxtBySql("SELECT TOP 1 [Param_value]  FROM [tblPartnersystem_Paramter] WHERE  Param_system='MSE' AND [Param_name]='" & tcParam_name & "'", , , SQL.GetNewOpenConnectionFMZOLL_SYSTEM(TESTSYSTEM))
    End Function


    Public Function createJWT(ByRef failureText As String) As String
        Try

            Dim jwt As New Chilkat.Jwt
            Dim jose As New Chilkat.JsonObject
            Dim success As Boolean = jose.AppendString("alg", "HS256")
            success = jose.AppendString("typ", "JWT")

            ' Now build the JWT claims (also known as the payload)
            Dim claims As New Chilkat.JsonObject
            If API.Rows.Count = 0 Then Return "keine gültigen Zugangsdaten gefunden!"
            success = claims.AppendString("iss", API.Rows(0).Item("api_user"))
            Dim curDateTime As Integer = jwt.GenNumericDate(0)

            ' Set the timestamp defining an expiration time (end time) for the token
            ' to be now + 1 hour (3600 seconds)
            success = claims.AddIntAt(-1, "exp", curDateTime + 3600)

            jwt.AutoCompact = True

            Dim strJwt As String = jwt.CreateJwt(jose.Emit(), claims.Emit(), API.Rows(0).Item("api_password"))

            Debug.WriteLine(strJwt)
            Return strJwt

        Catch ex As WebException
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try

    End Function

    Public Function getNewestTransactions(jwt As String, dt As DataTable, ByRef batchNr As Integer, ByRef totalPages As Integer, ByRef currentPage As Integer, onlyBilledTransactions As Boolean) As String
        Try
            Dim returnText As String = ""
            Dim failureText As String = ""

            Dim success As Boolean

            rest.DebugMode = test

            Dim bTls As Boolean = True
            Dim port As Integer = 443
            Dim bAutoReconnect As Boolean = True
            success = rest.Connect(API_STRING, port, bTls, bAutoReconnect)
            If (success <> True) Then
                Debug.WriteLine("ConnectFailReason: " & rest.ConnectFailReason)
                Debug.WriteLine(rest.LastErrorText)
                failureText = rest.LastErrorText
                Return False
            End If

            If (success <> True) Then
                Debug.WriteLine("BAFailReason: " & rest.ConnectFailReason)
                Debug.WriteLine(rest.LastErrorText)
                failureText = rest.LastErrorText
                Return False
            End If

            rest.ClearAllQueryParams()

            rest.AddHeader("X-API-Key", jwt)

            rest.IdleTimeoutMs = 1000000

            Dim responseJson As String = rest.FullRequestNoBody("GET", "/v1/transactions/new")
            If (rest.LastMethodSuccess <> True) Then
                Debug.WriteLine(rest.LastErrorText)
                rest.IdleTimeoutMs = 30000 'defualt
                Return rest.LastErrorText
            End If

            If (rest.ResponseStatusCode <> IIf(rest.DebugMode = True, 201, 200) And rest.ResponseStatusCode <> 404) Then
                Debug.WriteLine(rest.ResponseHeader)
                Return rest.LastErrorText
            End If

            Debug.WriteLine(responseJson)

            If test Then
                responseJson = "{""sender"":""MSTS"",""receiver"":""10738"",""datetime"":""2024-06-28 10:56:39"",""code"":""OK"",""message"":""OK"",""batch_seq_nr"":""2"",""customer_currency"":""EUR"",""total_pages"":100,""total_count"":99998,""total_amount"":291133.02,""page_nr"":1,""page_count"":999,""page_amount"":26238.88,""transactions"":[{""transaction_id"":1001723285,""partner_haulier_id"":""401052"",""supplier_name"":""TUNNEL ALPIN DU FREJUS"",""transaction_country"":""FR"",""transaction_domain"":""Frejus tunnel"",""purchase_datetime"":""2024-04-20 14:02:34"",""entry_point_name"":""FREJUS TUNNEL"",""entry_datetime"":""2024-04-20 14:02:34"",""exit_point_name"":null,""exit_datetime"":null,""device_product_type"":""Frejus"",""device_product_number"":""3081184009005108291"",""transaction_product_id"":140,""transaction_product_name"":""Toll "",""license_plate_number"":""BG1000FG"",""vehicle_country"":""RS"",""original_currency"":""EUR"",""original_net_amount"":258.38,""original_gross_amount"":310.05,""original_vat_percentage"":20,""transaction_net_amount"":258.38,""transaction_gross_amount"":310.05,""exempt_amount"":0,""msts_fee_amount"":4.65,""msts_vat_amount"":0,""msts_vat_percentage"":0,""total_gross_amount"":314.7,""transaction_status"":""Billed"",""original_transaction_id"":null,""credit_comment"":null,""loading_date"":""2024-05-14"",""batch_seq_nr"":""2""},{""transaction_id"":1001723286,""partner_haulier_id"":""401052"",""supplier_name"":""TUNNEL ALPIN DU FREJUS"",""transaction_country"":""FR"",""transaction_domain"":""Frejus tunnel"",""purchase_datetime"":""2024-04-26 05:34:49"",""entry_point_name"":""FREJUS TUNNEL"",""entry_datetime"":""2024-04-26 05:34:49"",""exit_point_name"":null,""exit_datetime"":null,""device_product_type"":""Frejus"",""device_product_number"":""3081184009005108291"",""transaction_product_id"":140,""transaction_product_name"":""Toll "",""license_plate_number"":""BG1000FG"",""vehicle_country"":""RS"",""original_currency"":""EUR"",""original_net_amount"":258.38,""original_gross_amount"":310.05,""original_vat_percentage"":20,""transaction_net_amount"":258.38,""transaction_gross_amount"":310.05,""exempt_amount"":0,""msts_fee_amount"":4.65,""msts_vat_amount"":0,""msts_vat_percentage"":0,""total_gross_amount"":314.7,""transaction_status"":""Billed"",""original_transaction_id"":null,""credit_comment"":null,""loading_date"":""2024-05-14"",""batch_seq_nr"":""2""},{""transaction_id"":1001723289,""partner_haulier_id"":""401370"",""supplier_name"":""TUNNEL ALPIN DU FREJUS"",""transaction_country"":""FR"",""transaction_domain"":""Frejus tunnel"",""purchase_datetime"":""2024-04-03 09:57:14"",""entry_point_name"":""FREJUS TUNNEL"",""entry_datetime"":""2024-04-03 09:57:14"",""exit_point_name"":null,""exit_datetime"":null,""device_product_type"":""Frejus"",""device_product_number"":""3081184009005114273"",""transaction_product_id"":140,""transaction_product_name"":""Toll "",""license_plate_number"":""RU042IS"",""vehicle_country"":""RS"",""original_currency"":""EUR"",""original_net_amount"":258.38,""original_gross_amount"":310.05,""original_vat_percentage"":20,""transaction_net_amount"":258.38,""transaction_gross_amount"":310.05,""exempt_amount"":0,""msts_fee_amount"":4.65,""msts_vat_amount"":0,""msts_vat_percentage"":0,""total_gross_amount"":314.7,""transaction_status"":""Billed"",""original_transaction_id"":null,""credit_comment"":null,""loading_date"":""2024-05-14"",""batch_seq_nr"":""2""},{""transaction_id"":1001723290,""partner_haulier_id"":""401370"",""supplier_name"":""TUNNEL ALPIN DU FREJUS"",""transaction_country"":""FR"",""transaction_domain"":""Frejus tunnel"",""purchase_datetime"":""2024-04-04 14:47:25"",""entry_point_name"":""FREJUS TUNNEL"",""entry_datetime"":""2024-04-04 14:47:25"",""exit_point_name"":null,""exit_datetime"":null,""device_product_type"":""Frejus"",""device_product_number"":""3081184009005114273"",""transaction_product_id"":140,""transaction_product_name"":""Toll "",""license_plate_number"":""RU042IS"",""vehicle_country"":""RS"",""original_currency"":""EUR"",""original_net_amount"":258.38,""original_gross_amount"":310.05,""original_vat_percentage"":20,""transaction_net_amount"":258.38,""transaction_gross_amount"":310.05,""exempt_amount"":0,""msts_fee_amount"":4.65,""msts_vat_amount"":0,""msts_vat_percentage"":0,""total_gross_amount"":314.7,""transaction_status"":""Billed"",""original_transaction_id"":null,""credit_comment"":null,""loading_date"":""2024-05-14"",""batch_seq_nr"":""2""}]}"
            End If

            Dim json As New Chilkat.JsonObject
            success = json.Load(responseJson)
            If (success <> True) Then
                Debug.WriteLine(json.LastErrorText)
            End If

            Debug.WriteLine(json)

            batchNr = json.StringOf("batch_seq_nr")
            totalPages = json.IntOf("total_pages")
            currentPage = json.IntOf("page_nr")

            If json.StringOf("message") <> "" AndAlso json.StringOf("message") <> "OK" Then Return json.StringOf("message")

            Dim transactions As New Chilkat.JsonArray
            transactions = json.ArrayOf("transactions")
            If (json.LastMethodSuccess = False) Then
                Debug.WriteLine("transactions member not found.")
            End If


            Dim num As Integer = transactions.Size
            If num = -1 Then
                Return "FEHLER im TransaktionArray"
            End If

            If json.StringOf("receiver") = "10738" Then saveTransactions(num, dt, transactions, json.StringOf("receiver"), onlyBilledTransactions)


        Catch ex As WebException
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try

    End Function

    Public Function getNewestSettlements(jwt As String, dt As DataTable, ByRef batchNr As Integer, ByRef totalPages As Integer, ByRef currentPage As Integer) As String
        Try
            Dim returnText As String = ""
            Dim failureText As String = ""

            Dim success As Boolean

            rest.DebugMode = test

            Dim bTls As Boolean = True
            Dim port As Integer = 443
            Dim bAutoReconnect As Boolean = True
            success = rest.Connect(API_STRING, port, bTls, bAutoReconnect)
            If (success <> True) Then
                Debug.WriteLine("ConnectFailReason: " & rest.ConnectFailReason)
                Debug.WriteLine(rest.LastErrorText)
                failureText = rest.LastErrorText
                Return False
            End If

            If (success <> True) Then
                Debug.WriteLine("BAFailReason: " & rest.ConnectFailReason)
                Debug.WriteLine(rest.LastErrorText)
                failureText = rest.LastErrorText
                Return False
            End If

            rest.ClearAllQueryParams()

            rest.AddHeader("X-API-Key", jwt)

            rest.IdleTimeoutMs = 1000000

            Dim responseJson As String = rest.FullRequestNoBody("GET", "/v1/settlements/new")
            If (rest.LastMethodSuccess <> True) Then
                Debug.WriteLine(rest.LastErrorText)
                rest.IdleTimeoutMs = 30000 'defualt
                Return rest.LastErrorText
            End If

            If (rest.ResponseStatusCode <> IIf(rest.DebugMode = True, 201, 200) And rest.ResponseStatusCode <> 404) Then
                Debug.WriteLine(rest.ResponseHeader)
                Return rest.LastErrorText
            End If

            Debug.WriteLine(responseJson)

            'Newest Settlements werden nicht benötigt, erst beim Abrufen der RECHNUNG sollen die dazugehörigen Settlements abgerufen werden, allerdings müssen diese initial 1x per API abgerufen werden (mittels getNewSettlements) ansonsten können Sie nicht gefunden werden!

            'sollten sie dennoch gespeichert werden, dann fogenden Return-Statement auskommentieren (damit nachfolgender Code ausgeführt werden kann):

            '-------------START---

            Return ""

            '-------------ENDE---


            If test Then
                responseJson = ""
            End If

            Dim json As New Chilkat.JsonObject
            success = json.Load(responseJson)
            If (success <> True) Then
                Debug.WriteLine(json.LastErrorText)
            End If

            Debug.WriteLine(json)

            batchNr = json.StringOf("batch_seq_nr")
            totalPages = json.IntOf("total_pages")
            currentPage = json.IntOf("page_nr")

            If json.StringOf("message") <> "" AndAlso json.StringOf("message") <> "OK" Then Return json.StringOf("message")

            Dim settlements As New Chilkat.JsonArray
            settlements = json.ArrayOf("settlements")
            If (json.LastMethodSuccess = False) Then
                Debug.WriteLine("settlements member not found.")
            End If


            Dim num As Integer = settlements.Size
            If num = -1 Then
                Return "FEHLER im settlementsArray"
            End If

            If json.StringOf("receiver") = "10738" Then saveSettlements(num, dt, settlements, json.StringOf("receiver"))


        Catch ex As WebException
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try

    End Function

    Public Function getCustomers(jwt As String, dt As DataTable) As String
        Try
            Dim returnText As String = ""
            Dim failureText As String = ""

            Dim success As Boolean

            rest.DebugMode = test

            Dim bTls As Boolean = True
            Dim port As Integer = 443
            Dim bAutoReconnect As Boolean = True
            success = rest.Connect(API_STRING, port, bTls, bAutoReconnect)
            If (success <> True) Then
                Debug.WriteLine("ConnectFailReason: " & rest.ConnectFailReason)
                Debug.WriteLine(rest.LastErrorText)
                failureText = rest.LastErrorText
                Return False
            End If

            If (success <> True) Then
                Debug.WriteLine("BAFailReason: " & rest.ConnectFailReason)
                Debug.WriteLine(rest.LastErrorText)
                failureText = rest.LastErrorText
                Return False
            End If

            rest.ClearAllQueryParams()

            rest.AddHeader("X-API-Key", jwt)

            rest.IdleTimeoutMs = 1000000

            Dim responseJson As String = rest.FullRequestNoBody("GET", "/v1/customers")
            If (rest.LastMethodSuccess <> True) Then
                Debug.WriteLine(rest.LastErrorText)
                rest.IdleTimeoutMs = 30000 'defualt
                Return rest.LastErrorText
            End If

            If (rest.ResponseStatusCode <> IIf(rest.DebugMode = True, 201, 200) And rest.ResponseStatusCode <> 404) Then
                Debug.WriteLine(rest.ResponseHeader)
                Return rest.LastErrorText
            End If

            Debug.WriteLine(responseJson)

            If test Then
                responseJson = "[{""customer_id"":13579,""partner_customer_number"":""203102"",""customer_name"":""NEGRO GROUP SRL"",""vat_number"":""RO17587350""},{""customer_id"":13566,""partner_customer_number"":""203104"",""customer_name"":""DANEMA SPECIAL TRANSPORT S.R.L."",""vat_number"":""RO27454467""},{""customer_id"":10746,""coc_number"":""11111"",""partner_customer_number"":""401386"",""customer_name"":""Teoma Transport"",""vat_number"":""SR100427963""},{""customer_id"":27765,""partner_customer_number"":""402810"",""customer_name"":""EMS TRANSPORTI DOO"",""vat_number"":""BA219169270003""}]"
            End If

            Dim customers As New Chilkat.JsonArray
            success = customers.Load(responseJson)
            If (success <> True) Then
                Return customers.LastErrorText

            End If

            Dim num As Integer = customers.Size
            If num = -1 Then
                Return "FEHLER im Customer Array"
            End If

            saveCustomers(num, dt, customers)


        Catch ex As WebException
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try

    End Function

    Public Function getTransactionsFromToDate(jwt As String, dt As DataTable, start_date As Date, end_date As Date, ByRef batchNr As Integer, ByRef totalPages As Integer, ByRef currentPage As Integer) As String
        Try
            Dim returnText As String = ""
            Dim failureText As String = ""

            Dim success As Boolean

            rest.DebugMode = test

            Dim bTls As Boolean = True
            Dim port As Integer = 443
            Dim bAutoReconnect As Boolean = True
            success = rest.Connect(API_STRING, port, bTls, bAutoReconnect)
            If (success <> True) Then
                Debug.WriteLine("ConnectFailReason: " & rest.ConnectFailReason)
                Debug.WriteLine(rest.LastErrorText)
                failureText = rest.LastErrorText
                Return False
            End If

            If (success <> True) Then
                Debug.WriteLine("BAFailReason: " & rest.ConnectFailReason)
                Debug.WriteLine(rest.LastErrorText)
                failureText = rest.LastErrorText
                Return False
            End If

            rest.ClearAllQueryParams()
            rest.AddHeader("X-API-Key", jwt)
            rest.AddQueryParam("start_date", start_date.ToString("yyyy-MM-dd"))
            rest.AddQueryParam("end_date", end_date.ToString("yyyy-MM-dd"))

            rest.IdleTimeoutMs = 1000000

            Dim responseJson As String = rest.FullRequestNoBody("GET", "/v1/transactions")
            If (rest.LastMethodSuccess <> True) Then
                Debug.WriteLine(rest.LastErrorText)
                rest.IdleTimeoutMs = 30000 'defualt
                Return rest.LastErrorText
            End If

            If (rest.ResponseStatusCode <> IIf(rest.DebugMode = True, 201, 200) And rest.ResponseStatusCode <> 404) Then
                Debug.WriteLine(rest.ResponseHeader)
                Return rest.LastErrorText
            End If

            Debug.WriteLine(responseJson)

            If test Then
                responseJson = "{""sender"":""MSTS"",""receiver"":""10738"",""datetime"":""2024-06-28 10:56:39"",""code"":""OK"",""message"":""OK"",""batch_seq_nr"":""2"",""customer_currency"":""EUR"",""total_pages"":100,""total_count"":99998,""total_amount"":291133.02,""page_nr"":1,""page_count"":999,""page_amount"":26238.88,""transactions"":[{""transaction_id"":1001723285,""partner_haulier_id"":""401052"",""supplier_name"":""TUNNEL ALPIN DU FREJUS"",""transaction_country"":""FR"",""transaction_domain"":""Frejus tunnel"",""purchase_datetime"":""2024-07-20 14:02:34"",""entry_point_name"":""FREJUS TUNNEL"",""entry_datetime"":""2024-04-10 14:02:34"",""exit_point_name"":null,""exit_datetime"":""2024-04-11 14:02:34"",""device_product_type"":""Frejus"",""device_product_number"":""3081184009005108291"",""transaction_product_id"":140,""transaction_product_name"":""Toll "",""license_plate_number"":""BG1000FG"",""vehicle_country"":""RS"",""original_currency"":""EUR"",""original_net_amount"":-2549.2400000000002,""original_gross_amount"":-2549.2400000000002,""original_vat_percentage"":20,""transaction_net_amount"":258.38,""transaction_gross_amount"":310.05,""exempt_amount"":0,""msts_fee_amount"":4.65,""msts_vat_amount"":0,""msts_vat_percentage"":0,""total_gross_amount"":314.7,""transaction_status"":""Billed"",""original_transaction_id"":null,""credit_comment"":null,""loading_date"":""2024-05-14"",""batch_seq_nr"":""2""},{""transaction_id"":1001723286,""partner_haulier_id"":""401052"",""supplier_name"":""TUNNEL ALPIN DU FREJUS"",""transaction_country"":""FR"",""transaction_domain"":""Frejus tunnel"",""purchase_datetime"":""2024-04-26 05:34:49"",""entry_point_name"":""FREJUS TUNNEL"",""entry_datetime"":""2024-04-26 05:34:49"",""exit_point_name"":null,""exit_datetime"":null,""device_product_type"":""Frejus"",""device_product_number"":""3081184009005108291"",""transaction_product_id"":140,""transaction_product_name"":""Toll "",""license_plate_number"":""BG1000FG"",""vehicle_country"":""RS"",""original_currency"":""EUR"",""original_net_amount"":258.38,""original_gross_amount"":310.05,""original_vat_percentage"":20,""transaction_net_amount"":258.38,""transaction_gross_amount"":310.05,""exempt_amount"":0,""msts_fee_amount"":4.65,""msts_vat_amount"":0,""msts_vat_percentage"":0,""total_gross_amount"":314.7,""transaction_status"":""Billed"",""original_transaction_id"":null,""credit_comment"":null,""loading_date"":""2024-05-14"",""batch_seq_nr"":""2""},{""transaction_id"":1001723289,""partner_haulier_id"":""401370"",""supplier_name"":""TUNNEL ALPIN DU FREJUS"",""transaction_country"":""FR"",""transaction_domain"":""Frejus tunnel"",""purchase_datetime"":""2024-04-03 09:57:14"",""entry_point_name"":""FREJUS TUNNEL"",""entry_datetime"":""2024-04-03 09:57:14"",""exit_point_name"":null,""exit_datetime"":null,""device_product_type"":""Frejus"",""device_product_number"":""3081184009005114273"",""transaction_product_id"":140,""transaction_product_name"":""Toll "",""license_plate_number"":""RU042IS"",""vehicle_country"":""RS"",""original_currency"":""EUR"",""original_net_amount"":258.38,""original_gross_amount"":310.05,""original_vat_percentage"":20,""transaction_net_amount"":258.38,""transaction_gross_amount"":310.05,""exempt_amount"":0,""msts_fee_amount"":4.65,""msts_vat_amount"":0,""msts_vat_percentage"":0,""total_gross_amount"":314.7,""transaction_status"":""Billed"",""original_transaction_id"":null,""credit_comment"":null,""loading_date"":""2024-05-14"",""batch_seq_nr"":""2""},{""transaction_id"":1001723290,""partner_haulier_id"":""401370"",""supplier_name"":""TUNNEL ALPIN DU FREJUS"",""transaction_country"":""FR"",""transaction_domain"":""Frejus tunnel"",""purchase_datetime"":""2024-04-04 14:47:25"",""entry_point_name"":""FREJUS TUNNEL"",""entry_datetime"":""2024-04-04 14:47:25"",""exit_point_name"":null,""exit_datetime"":null,""device_product_type"":""Frejus"",""device_product_number"":""3081184009005114273"",""transaction_product_id"":140,""transaction_product_name"":""Toll "",""license_plate_number"":""RU042IS"",""vehicle_country"":""RS"",""original_currency"":""EUR"",""original_net_amount"":258.38,""original_gross_amount"":310.05,""original_vat_percentage"":20,""transaction_net_amount"":258.38,""transaction_gross_amount"":310.05,""exempt_amount"":0,""msts_fee_amount"":4.65,""msts_vat_amount"":0,""msts_vat_percentage"":0,""total_gross_amount"":314.7,""transaction_status"":""Billed"",""original_transaction_id"":null,""credit_comment"":null,""loading_date"":""2024-05-14"",""batch_seq_nr"":""2""}]}"
            End If

            Dim json As New Chilkat.JsonObject
            success = json.Load(responseJson)
            If (success <> True) Then
                Debug.WriteLine(json.LastErrorText)
            End If

            Debug.WriteLine(json)

            If json.StringOf("message") <> "" AndAlso json.StringOf("message") <> "OK" Then Return json.StringOf("message")

            batchNr = json.StringOf("batch_seq_nr")
            totalPages = json.IntOf("total_pages")
            currentPage = json.IntOf("page_nr")


            Dim transactions As New Chilkat.JsonArray
            transactions = json.ArrayOf("transactions")
            If (json.LastMethodSuccess = False) Then
                Debug.WriteLine("transactions member not found.")
            End If


            Dim num As Integer = transactions.Size
            If num = -1 Then
                Return "FEHLER Array Transaktions ist leer"
            End If


            If json.StringOf("receiver") = "10738" Then saveTransactions(num, dt, transactions, json.StringOf("receiver"))


        Catch ex As WebException
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try

    End Function

    Public Function getTransactionsFromTransactionID(jwt As String, dt As DataTable, ByRef transactionID As DataTable) As String
        Try
            Dim returnText As String = ""
            Dim failureText As String = ""
            Dim missingcounter As Integer = 0
            Dim listOfMissingTransactions As New List(Of String)

            Dim success As Boolean

            rest.DebugMode = test

            Dim bTls As Boolean = True
            Dim port As Integer = 443
            Dim bAutoReconnect As Boolean = True
            success = rest.Connect(API_STRING, port, bTls, bAutoReconnect)
            If (success <> True) Then
                Debug.WriteLine("ConnectFailReason: " & rest.ConnectFailReason)
                Debug.WriteLine(rest.LastErrorText)
                failureText = rest.LastErrorText
                Return False
            End If

            If (success <> True) Then
                Debug.WriteLine("BAFailReason: " & rest.ConnectFailReason)
                Debug.WriteLine(rest.LastErrorText)
                failureText = rest.LastErrorText
                Return False
            End If

            rest.ClearAllQueryParams()
            rest.AddHeader("X-API-Key", jwt)


            rest.IdleTimeoutMs = 1000000



            'transactionID.Columns.Add("transaction_id", GetType(String))


            If transactionID IsNot Nothing And transactionID.Columns.Contains("transaction_id") And transactionID.Rows.Count > 0 Then
                For Each row As DataRow In transactionID.Rows


                    Dim responseJson As String = rest.FullRequestNoBody("GET", "/v1/transactions/" & row("transaction_id"))
                    If (rest.LastMethodSuccess <> True) Then
                        Debug.WriteLine(rest.LastErrorText)
                        rest.IdleTimeoutMs = 30000 'defualt
                        Return rest.LastErrorText
                    End If

                    If (rest.ResponseStatusCode <> IIf(rest.DebugMode = True, 201, 200) And rest.ResponseStatusCode <> 404) Then
                        Debug.WriteLine(rest.ResponseHeader)
                        Return rest.LastErrorText
                    End If

                    Debug.WriteLine(responseJson)

                    If test Then
                        responseJson = "{""sender"":""MSTS"",""receiver"":""10738"",""datetime"":""2024-06-28 10:56:39"",""code"":""OK"",""message"":""OK"",""batch_seq_nr"":""2"",""customer_currency"":""EUR"",""total_pages"":100,""total_count"":99998,""total_amount"":291133.02,""page_nr"":1,""page_count"":999,""page_amount"":26238.88,""transactions"":[{""transaction_id"":1001723285,""partner_haulier_id"":""401052"",""supplier_name"":""TUNNEL ALPIN DU FREJUS"",""transaction_country"":""FR"",""transaction_domain"":""Frejus tunnel"",""purchase_datetime"":""2024-07-20 14:02:34"",""entry_point_name"":""FREJUS TUNNEL"",""entry_datetime"":""2024-04-10 14:02:34"",""exit_point_name"":null,""exit_datetime"":""2024-04-11 14:02:34"",""device_product_type"":""Frejus"",""device_product_number"":""3081184009005108291"",""transaction_product_id"":140,""transaction_product_name"":""Toll "",""license_plate_number"":""BG1000FG"",""vehicle_country"":""RS"",""original_currency"":""EUR"",""original_net_amount"":-2549.2400000000002,""original_gross_amount"":-2549.2400000000002,""original_vat_percentage"":20,""transaction_net_amount"":258.38,""transaction_gross_amount"":310.05,""exempt_amount"":0,""msts_fee_amount"":4.65,""msts_vat_amount"":0,""msts_vat_percentage"":0,""total_gross_amount"":314.7,""transaction_status"":""Billed"",""original_transaction_id"":null,""credit_comment"":null,""loading_date"":""2024-05-14"",""batch_seq_nr"":""2""},{""transaction_id"":1001723286,""partner_haulier_id"":""401052"",""supplier_name"":""TUNNEL ALPIN DU FREJUS"",""transaction_country"":""FR"",""transaction_domain"":""Frejus tunnel"",""purchase_datetime"":""2024-04-26 05:34:49"",""entry_point_name"":""FREJUS TUNNEL"",""entry_datetime"":""2024-04-26 05:34:49"",""exit_point_name"":null,""exit_datetime"":null,""device_product_type"":""Frejus"",""device_product_number"":""3081184009005108291"",""transaction_product_id"":140,""transaction_product_name"":""Toll "",""license_plate_number"":""BG1000FG"",""vehicle_country"":""RS"",""original_currency"":""EUR"",""original_net_amount"":258.38,""original_gross_amount"":310.05,""original_vat_percentage"":20,""transaction_net_amount"":258.38,""transaction_gross_amount"":310.05,""exempt_amount"":0,""msts_fee_amount"":4.65,""msts_vat_amount"":0,""msts_vat_percentage"":0,""total_gross_amount"":314.7,""transaction_status"":""Billed"",""original_transaction_id"":null,""credit_comment"":null,""loading_date"":""2024-05-14"",""batch_seq_nr"":""2""},{""transaction_id"":1001723289,""partner_haulier_id"":""401370"",""supplier_name"":""TUNNEL ALPIN DU FREJUS"",""transaction_country"":""FR"",""transaction_domain"":""Frejus tunnel"",""purchase_datetime"":""2024-04-03 09:57:14"",""entry_point_name"":""FREJUS TUNNEL"",""entry_datetime"":""2024-04-03 09:57:14"",""exit_point_name"":null,""exit_datetime"":null,""device_product_type"":""Frejus"",""device_product_number"":""3081184009005114273"",""transaction_product_id"":140,""transaction_product_name"":""Toll "",""license_plate_number"":""RU042IS"",""vehicle_country"":""RS"",""original_currency"":""EUR"",""original_net_amount"":258.38,""original_gross_amount"":310.05,""original_vat_percentage"":20,""transaction_net_amount"":258.38,""transaction_gross_amount"":310.05,""exempt_amount"":0,""msts_fee_amount"":4.65,""msts_vat_amount"":0,""msts_vat_percentage"":0,""total_gross_amount"":314.7,""transaction_status"":""Billed"",""original_transaction_id"":null,""credit_comment"":null,""loading_date"":""2024-05-14"",""batch_seq_nr"":""2""},{""transaction_id"":1001723290,""partner_haulier_id"":""401370"",""supplier_name"":""TUNNEL ALPIN DU FREJUS"",""transaction_country"":""FR"",""transaction_domain"":""Frejus tunnel"",""purchase_datetime"":""2024-04-04 14:47:25"",""entry_point_name"":""FREJUS TUNNEL"",""entry_datetime"":""2024-04-04 14:47:25"",""exit_point_name"":null,""exit_datetime"":null,""device_product_type"":""Frejus"",""device_product_number"":""3081184009005114273"",""transaction_product_id"":140,""transaction_product_name"":""Toll "",""license_plate_number"":""RU042IS"",""vehicle_country"":""RS"",""original_currency"":""EUR"",""original_net_amount"":258.38,""original_gross_amount"":310.05,""original_vat_percentage"":20,""transaction_net_amount"":258.38,""transaction_gross_amount"":310.05,""exempt_amount"":0,""msts_fee_amount"":4.65,""msts_vat_amount"":0,""msts_vat_percentage"":0,""total_gross_amount"":314.7,""transaction_status"":""Billed"",""original_transaction_id"":null,""credit_comment"":null,""loading_date"":""2024-05-14"",""batch_seq_nr"":""2""}]}"
                    End If

                    Dim json As New Chilkat.JsonObject
                    success = json.Load(responseJson)
                    If (success <> True) Then
                        Debug.WriteLine(json.LastErrorText)
                    End If

                    Debug.WriteLine(json)
                    Dim saveTransaction As Boolean = True
                    If json.StringOf("message") <> "" AndAlso json.StringOf("message") <> "OK" Then
                        If Not json.StringOf("message").ToString.Contains("No transaction found for") Then
                            Return json.StringOf("message")
                        Else
                            saveTransaction = False
                            transactionID.Columns("found").ReadOnly = False
                            row.Item("found") = False
                            transactionID.Columns("found").ReadOnly = True


                        End If

                    End If

                    If saveTransaction Then
                        Dim transactions As New Chilkat.JsonArray
                        transactions = json.ArrayOf("transactions")
                        If (json.LastMethodSuccess = False) Then
                            Debug.WriteLine("transactions member not found.")
                        End If


                        Dim num As Integer = transactions.Size
                        If num = -1 Then
                            Return "FEHLER Array Transaktions ist leer"
                        End If


                        'If json.StringOf("receiver") = "10738" Then saveTransactions(num, dt, transactions, json.StringOf("receiver"))
                        saveTransactions(num, dt, transactions, json.StringOf("receiver"), True,) ' wenn ID explizit aufgerufen keine Prüfung auf receivcer und purchaseDate
                    End If


                Next row


            End If





        Catch ex As WebException
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try

    End Function


    Public Function getTransactionsFromBatchNrAndPage(jwt As String, dt As DataTable, ByRef batchNr As Integer, ByRef totalPages As Integer, ByRef currentPage As Integer) As String
        Try
            Dim returnText As String = ""
            Dim failureText As String = ""

            Dim success As Boolean

            rest.DebugMode = test

            Dim bTls As Boolean = True
            Dim port As Integer = 443
            Dim bAutoReconnect As Boolean = True
            success = rest.Connect(API_STRING, port, bTls, bAutoReconnect)
            If (success <> True) Then
                Debug.WriteLine("ConnectFailReason: " & rest.ConnectFailReason)
                Debug.WriteLine(rest.LastErrorText)
                Return rest.LastErrorText

            End If

            If (success <> True) Then
                Debug.WriteLine("BAFailReason: " & rest.ConnectFailReason)
                Debug.WriteLine(rest.LastErrorText)
                Return rest.LastErrorText

            End If

            rest.ClearAllQueryParams()
            rest.AddHeader("X-API-Key", jwt)
            rest.AddQueryParam("batch_seq_nr", batchNr)
            If currentPage > 0 Then rest.AddQueryParam("page_nr", currentPage)

            rest.IdleTimeoutMs = 1000000

            Dim responseJson As String = rest.FullRequestNoBody("GET", "/v1/transactions")
            If (rest.LastMethodSuccess <> True) Then
                Debug.WriteLine(rest.LastErrorText)
                rest.IdleTimeoutMs = 30000 'defualt
                Return rest.LastErrorText
            End If

            If (rest.ResponseStatusCode <> IIf(rest.DebugMode = True, 201, 200) And rest.ResponseStatusCode <> 404) Then
                Debug.WriteLine(rest.ResponseHeader)
                Return rest.LastErrorText
            End If

            Debug.WriteLine(responseJson)

            If test Then
                responseJson = "{""sender"":""MSTS"",""receiver"":""10738"",""datetime"":""2024-06-28 10:56:39"",""code"":""OK"",""message"":""OK"",""batch_seq_nr"":""2"",""customer_currency"":""EUR"",""total_pages"":100,""total_count"":99998,""total_amount"":291133.02,""page_nr"":1,""page_count"":999,""page_amount"":26238.88,""transactions"":[{""transaction_id"":1001723285,""partner_haulier_id"":""401052"",""supplier_name"":""TUNNEL ALPIN DU FREJUS"",""transaction_country"":""FR"",""transaction_domain"":""Frejus tunnel"",""purchase_datetime"":""2024-04-20 14:02:34"",""entry_point_name"":""FREJUS TUNNEL"",""entry_datetime"":""2024-04-20 14:02:34"",""exit_point_name"":null,""exit_datetime"":null,""device_product_type"":""Frejus"",""device_product_number"":""3081184009005108291"",""transaction_product_id"":140,""transaction_product_name"":""Toll "",""license_plate_number"":""BG1000FG"",""vehicle_country"":""RS"",""original_currency"":""EUR"",""original_net_amount"":258.38,""original_gross_amount"":310.05,""original_vat_percentage"":20,""transaction_net_amount"":258.38,""transaction_gross_amount"":310.05,""exempt_amount"":0,""msts_fee_amount"":4.65,""msts_vat_amount"":0,""msts_vat_percentage"":0,""total_gross_amount"":314.7,""transaction_status"":""Billed"",""original_transaction_id"":null,""credit_comment"":null,""loading_date"":""2024-05-14"",""batch_seq_nr"":""2""},{""transaction_id"":1001723286,""partner_haulier_id"":""401052"",""supplier_name"":""TUNNEL ALPIN DU FREJUS"",""transaction_country"":""FR"",""transaction_domain"":""Frejus tunnel"",""purchase_datetime"":""2024-04-26 05:34:49"",""entry_point_name"":""FREJUS TUNNEL"",""entry_datetime"":""2024-04-26 05:34:49"",""exit_point_name"":null,""exit_datetime"":null,""device_product_type"":""Frejus"",""device_product_number"":""3081184009005108291"",""transaction_product_id"":140,""transaction_product_name"":""Toll "",""license_plate_number"":""BG1000FG"",""vehicle_country"":""RS"",""original_currency"":""EUR"",""original_net_amount"":258.38,""original_gross_amount"":310.05,""original_vat_percentage"":20,""transaction_net_amount"":258.38,""transaction_gross_amount"":310.05,""exempt_amount"":0,""msts_fee_amount"":4.65,""msts_vat_amount"":0,""msts_vat_percentage"":0,""total_gross_amount"":314.7,""transaction_status"":""Billed"",""original_transaction_id"":null,""credit_comment"":null,""loading_date"":""2024-05-14"",""batch_seq_nr"":""2""},{""transaction_id"":1001723289,""partner_haulier_id"":""401370"",""supplier_name"":""TUNNEL ALPIN DU FREJUS"",""transaction_country"":""FR"",""transaction_domain"":""Frejus tunnel"",""purchase_datetime"":""2024-04-03 09:57:14"",""entry_point_name"":""FREJUS TUNNEL"",""entry_datetime"":""2024-04-03 09:57:14"",""exit_point_name"":null,""exit_datetime"":null,""device_product_type"":""Frejus"",""device_product_number"":""3081184009005114273"",""transaction_product_id"":140,""transaction_product_name"":""Toll "",""license_plate_number"":""RU042IS"",""vehicle_country"":""RS"",""original_currency"":""EUR"",""original_net_amount"":258.38,""original_gross_amount"":310.05,""original_vat_percentage"":20,""transaction_net_amount"":258.38,""transaction_gross_amount"":310.05,""exempt_amount"":0,""msts_fee_amount"":4.65,""msts_vat_amount"":0,""msts_vat_percentage"":0,""total_gross_amount"":314.7,""transaction_status"":""Billed"",""original_transaction_id"":null,""credit_comment"":null,""loading_date"":""2024-05-14"",""batch_seq_nr"":""2""},{""transaction_id"":1001723290,""partner_haulier_id"":""401370"",""supplier_name"":""TUNNEL ALPIN DU FREJUS"",""transaction_country"":""FR"",""transaction_domain"":""Frejus tunnel"",""purchase_datetime"":""2024-04-04 14:47:25"",""entry_point_name"":""FREJUS TUNNEL"",""entry_datetime"":""2024-04-04 14:47:25"",""exit_point_name"":null,""exit_datetime"":null,""device_product_type"":""Frejus"",""device_product_number"":""3081184009005114273"",""transaction_product_id"":140,""transaction_product_name"":""Toll "",""license_plate_number"":""RU042IS"",""vehicle_country"":""RS"",""original_currency"":""EUR"",""original_net_amount"":258.38,""original_gross_amount"":310.05,""original_vat_percentage"":20,""transaction_net_amount"":258.38,""transaction_gross_amount"":310.05,""exempt_amount"":0,""msts_fee_amount"":4.65,""msts_vat_amount"":0,""msts_vat_percentage"":0,""total_gross_amount"":314.7,""transaction_status"":""Billed"",""original_transaction_id"":null,""credit_comment"":null,""loading_date"":""2024-05-14"",""batch_seq_nr"":""2""}]}"
            End If

            Dim json As New Chilkat.JsonObject
            success = json.Load(responseJson)
            If (success <> True) Then
                Debug.WriteLine(json.LastErrorText)
                Return json.LastErrorText
            End If

            Debug.WriteLine(json)

            If json.StringOf("message") <> "" AndAlso json.StringOf("message") <> "OK" Then Return json.StringOf("message")

            batchNr = json.StringOf("batch_seq_nr")
            totalPages = json.IntOf("total_pages")
            currentPage = json.IntOf("page_nr")


            Dim transactions As New Chilkat.JsonArray
            transactions = json.ArrayOf("transactions")
            If (json.LastMethodSuccess = False) Then
                Return "transactions member not found."
            End If


            Dim num As Integer = transactions.Size
            If num < 1 Then
                Return "FEHLER Array Transaktions ist leer"
            End If

            If json.StringOf("receiver") = "10738" Then saveTransactions(num, dt, transactions, json.StringOf("receiver"))


        Catch ex As WebException
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try

    End Function


    Public Function getSettlementsFromInvoiceID(jwt As String, dt As DataTable, invoiceID As String, ByRef batchNr As Integer, ByRef totalPages As Integer, ByRef currentPage As Integer) As String
        Try
            Dim returnText As String = ""
            Dim failureText As String = ""

            Dim success As Boolean

            rest.DebugMode = test

            Dim bTls As Boolean = True
            Dim port As Integer = 443
            Dim bAutoReconnect As Boolean = True
            success = rest.Connect(API_STRING, port, bTls, bAutoReconnect)
            If (success <> True) Then
                Debug.WriteLine("ConnectFailReason: " & rest.ConnectFailReason)
                Debug.WriteLine(rest.LastErrorText)
                Return rest.LastErrorText

            End If

            If (success <> True) Then
                Debug.WriteLine("BAFailReason: " & rest.ConnectFailReason)
                Debug.WriteLine(rest.LastErrorText)
                Return rest.LastErrorText

            End If

            rest.ClearAllQueryParams()


            rest.AddQueryParam("invoice_id", invoiceID)

            rest.AddHeader("X-API-Key", jwt)

            rest.IdleTimeoutMs = 1000000


            Dim responseJson As String = rest.FullRequestNoBody("GET", "/v1/settlements")
            If (rest.LastMethodSuccess <> True) Then
                Debug.WriteLine(rest.LastErrorText)
                rest.IdleTimeoutMs = 30000 'defualt
                Return rest.LastErrorText
            End If

            If (rest.ResponseStatusCode <> IIf(rest.DebugMode = True, 201, 200) And rest.ResponseStatusCode <> 404) Then
                Debug.WriteLine(rest.ResponseHeader)
                Return rest.LastErrorText
            End If

            Debug.WriteLine(responseJson)

            If test Then
                responseJson = "{""sender"":""MSTS"",""receiver"":""10738"",""datetime"":""2024-07-25 14:17:45"",""code"":""OK"",""message"":""OK"",""customer_currency"":""EUR"",""total_pages"":1,""total_count"":56351,""total_amount"":164386.34,""page_nr"":1,""page_count"":56351,""page_amount"":164386.34,""settlements"":[{""transaction_id"":1001723285,""purchase_datetime"":""2024-06-25 21:29:16"",""partner_haulier_id"":""401058"",""transaction_net_amount"":9.08,""transaction_gross_amount"":10.9,""msts_fee_amount"":0.11,""msts_vat_amount"":0,""total_gross_amount"":11.01,""invoice_number"":""1753066"",""invoice_date"":""2024-07-15"",""specification_page_id"":197,""specification_page_name"":""French toll roads - TISPL"",""transaction_debit_or_credit"":""Debit"",""original_transaction_id"":null,""original_invoice_number"":null,""original_invoice_date"":null,""credit_comment"":null,""batch_seq_nr"":""1""},{""transaction_id"":1001723286,""purchase_datetime"":""2024-06-26 11:17:48"",""partner_haulier_id"":""401267"",""transaction_net_amount"":10.42,""transaction_gross_amount"":12.5,""msts_fee_amount"":0.13,""msts_vat_amount"":0,""total_gross_amount"":12.63,""invoice_number"":""1753066"",""invoice_date"":""2024-07-15"",""specification_page_id"":197,""specification_page_name"":""French toll roads - TISPL"",""transaction_debit_or_credit"":""Debit"",""original_transaction_id"":null,""original_invoice_number"":null,""original_invoice_date"":null,""credit_comment"":null,""batch_seq_nr"":""1""}]}"
            End If

            Dim json As New Chilkat.JsonObject
            success = json.Load(responseJson)
            If (success <> True) Then
                Return json.LastErrorText
            End If

            Debug.WriteLine(json)

            If json.StringOf("message") <> "" AndAlso json.StringOf("message") <> "OK" Then Return json.StringOf("message")

            batchNr = json.StringOf("batch_seq_nr")
            totalPages = json.IntOf("total_pages")
            currentPage = json.IntOf("page_nr")


            Dim transactions As New Chilkat.JsonArray
            transactions = json.ArrayOf("settlements")
            If (json.LastMethodSuccess = False) Then
                Return "transactions member not found."
            End If



            Dim num As Integer = transactions.Size
            If num = -1 Then
                Return "FEHLER Array Transaktions ist leer"
            End If


            If json.StringOf("receiver") = "10738" Then saveSettlements(num, dt, transactions, json.StringOf("receiver"))

        Catch ex As WebException
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try

    End Function


    Public Function getSettlementsFromBatchNrAndPage(jwt As String, dt As DataTable, ByRef batchNr As Integer, ByRef totalPages As Integer, ByRef currentPage As Integer) As String
        Try
            Dim returnText As String = ""
            Dim failureText As String = ""

            Dim success As Boolean


            rest.DebugMode = test

            Dim bTls As Boolean = True
            Dim port As Integer = 443
            Dim bAutoReconnect As Boolean = True
            success = rest.Connect(API_STRING, port, bTls, bAutoReconnect)
            If (success <> True) Then
                Debug.WriteLine("ConnectFailReason: " & rest.ConnectFailReason)
                Debug.WriteLine(rest.LastErrorText)
                failureText = rest.LastErrorText
                Return False
            End If

            If (success <> True) Then
                Debug.WriteLine("BAFailReason: " & rest.ConnectFailReason)
                Debug.WriteLine(rest.LastErrorText)
                failureText = rest.LastErrorText
                Return False
            End If

            rest.ClearAllQueryParams()
            rest.AddHeader("X-API-Key", jwt)
            rest.AddQueryParam("batch_seq_nr", batchNr)
            If currentPage > 0 Then rest.AddQueryParam("page_nr", currentPage)

            rest.IdleTimeoutMs = 1000000

            Dim responseJson As String = rest.FullRequestNoBody("GET", "/v1/settlements")
            If (rest.LastMethodSuccess <> True) Then
                Debug.WriteLine(rest.LastErrorText)
                rest.IdleTimeoutMs = 30000 'defualt
                Return rest.LastErrorText
            End If

            If (rest.ResponseStatusCode <> IIf(rest.DebugMode = True, 201, 200) And rest.ResponseStatusCode <> 404) Then
                Debug.WriteLine(rest.ResponseHeader)
                Return rest.LastErrorText
            End If

            Debug.WriteLine(responseJson)

            If test Then
                responseJson = "{""sender"":""MSTS"",""receiver"":""23771"",""datetime"":""2024-06-28 10:56:39"",""code"":""OK"",""message"":""OK"",""batch_seq_nr"":""2"",""customer_currency"":""EUR"",""total_pages"":100,""total_count"":99998,""total_amount"":291133.02,""page_nr"":1,""page_count"":999,""page_amount"":26238.88,""transactions"":[{""transaction_id"":1001723285,""partner_haulier_id"":""401052"",""supplier_name"":""TUNNEL ALPIN DU FREJUS"",""transaction_country"":""FR"",""transaction_domain"":""Frejus tunnel"",""purchase_datetime"":""2024-04-20 14:02:34"",""entry_point_name"":""FREJUS TUNNEL"",""entry_datetime"":""2024-04-20 14:02:34"",""exit_point_name"":null,""exit_datetime"":null,""device_product_type"":""Frejus"",""device_product_number"":""3081184009005108291"",""transaction_product_id"":140,""transaction_product_name"":""Toll "",""license_plate_number"":""BG1000FG"",""vehicle_country"":""RS"",""original_currency"":""EUR"",""original_net_amount"":258.38,""original_gross_amount"":310.05,""original_vat_percentage"":20,""transaction_net_amount"":258.38,""transaction_gross_amount"":310.05,""exempt_amount"":0,""msts_fee_amount"":4.65,""msts_vat_amount"":0,""msts_vat_percentage"":0,""total_gross_amount"":314.7,""transaction_status"":""Billed"",""original_transaction_id"":null,""credit_comment"":null,""loading_date"":""2024-05-14"",""batch_seq_nr"":""2""},{""transaction_id"":1001723286,""partner_haulier_id"":""401052"",""supplier_name"":""TUNNEL ALPIN DU FREJUS"",""transaction_country"":""FR"",""transaction_domain"":""Frejus tunnel"",""purchase_datetime"":""2024-04-26 05:34:49"",""entry_point_name"":""FREJUS TUNNEL"",""entry_datetime"":""2024-04-26 05:34:49"",""exit_point_name"":null,""exit_datetime"":null,""device_product_type"":""Frejus"",""device_product_number"":""3081184009005108291"",""transaction_product_id"":140,""transaction_product_name"":""Toll "",""license_plate_number"":""BG1000FG"",""vehicle_country"":""RS"",""original_currency"":""EUR"",""original_net_amount"":258.38,""original_gross_amount"":310.05,""original_vat_percentage"":20,""transaction_net_amount"":258.38,""transaction_gross_amount"":310.05,""exempt_amount"":0,""msts_fee_amount"":4.65,""msts_vat_amount"":0,""msts_vat_percentage"":0,""total_gross_amount"":314.7,""transaction_status"":""Billed"",""original_transaction_id"":null,""credit_comment"":null,""loading_date"":""2024-05-14"",""batch_seq_nr"":""2""},{""transaction_id"":1001723289,""partner_haulier_id"":""401370"",""supplier_name"":""TUNNEL ALPIN DU FREJUS"",""transaction_country"":""FR"",""transaction_domain"":""Frejus tunnel"",""purchase_datetime"":""2024-04-03 09:57:14"",""entry_point_name"":""FREJUS TUNNEL"",""entry_datetime"":""2024-04-03 09:57:14"",""exit_point_name"":null,""exit_datetime"":null,""device_product_type"":""Frejus"",""device_product_number"":""3081184009005114273"",""transaction_product_id"":140,""transaction_product_name"":""Toll "",""license_plate_number"":""RU042IS"",""vehicle_country"":""RS"",""original_currency"":""EUR"",""original_net_amount"":258.38,""original_gross_amount"":310.05,""original_vat_percentage"":20,""transaction_net_amount"":258.38,""transaction_gross_amount"":310.05,""exempt_amount"":0,""msts_fee_amount"":4.65,""msts_vat_amount"":0,""msts_vat_percentage"":0,""total_gross_amount"":314.7,""transaction_status"":""Billed"",""original_transaction_id"":null,""credit_comment"":null,""loading_date"":""2024-05-14"",""batch_seq_nr"":""2""},{""transaction_id"":1001723290,""partner_haulier_id"":""401370"",""supplier_name"":""TUNNEL ALPIN DU FREJUS"",""transaction_country"":""FR"",""transaction_domain"":""Frejus tunnel"",""purchase_datetime"":""2024-04-04 14:47:25"",""entry_point_name"":""FREJUS TUNNEL"",""entry_datetime"":""2024-04-04 14:47:25"",""exit_point_name"":null,""exit_datetime"":null,""device_product_type"":""Frejus"",""device_product_number"":""3081184009005114273"",""transaction_product_id"":140,""transaction_product_name"":""Toll "",""license_plate_number"":""RU042IS"",""vehicle_country"":""RS"",""original_currency"":""EUR"",""original_net_amount"":258.38,""original_gross_amount"":310.05,""original_vat_percentage"":20,""transaction_net_amount"":258.38,""transaction_gross_amount"":310.05,""exempt_amount"":0,""msts_fee_amount"":4.65,""msts_vat_amount"":0,""msts_vat_percentage"":0,""total_gross_amount"":314.7,""transaction_status"":""Billed"",""original_transaction_id"":null,""credit_comment"":null,""loading_date"":""2024-05-14"",""batch_seq_nr"":""2""}]}"
            End If

            Dim json As New Chilkat.JsonObject
            success = json.Load(responseJson)
            If (success <> True) Then
                Debug.WriteLine(json.LastErrorText)
            End If

            Debug.WriteLine(json)

            If json.StringOf("message") <> "" AndAlso json.StringOf("message") <> "OK" Then Return json.StringOf("message")

            batchNr = json.StringOf("batch_seq_nr")
            totalPages = json.IntOf("total_pages")
            currentPage = json.IntOf("page_nr")


            Dim transactions As New Chilkat.JsonArray
            transactions = json.ArrayOf("transactions")
            If (json.LastMethodSuccess = False) Then
                Debug.WriteLine("transactions member not found.")
            End If


            Dim num As Integer = transactions.Size
            If num = -1 Then
                Return "FEHLER Array Transaktions ist leer"
            End If

            If json.StringOf("receiver") = "10738" Then saveSettlements(num, dt, transactions, json.StringOf("receiver"))


        Catch ex As WebException
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try

    End Function


    Public Function checkNullStr(ByVal o As Object) As String
        If o IsNot Nothing AndAlso o IsNot DBNull.Value AndAlso Not o = "null" Then Return CStr(o)
        Return ""
    End Function
    Public Function checkNullInteger(ByVal o As Object) As Integer
        If o IsNot Nothing AndAlso o IsNot DBNull.Value Then
            If IsNumeric(o) Then
                Return CInt(o)
            Else
                Return -1
            End If
        Else
            Return -1
        End If

    End Function
    Public Function checkNullReturnValue(ByVal o As Object, ByVal returnValue As Object) As Object
        If o IsNot Nothing And o IsNot DBNull.Value And Not o = "null" Then Return (o)
        Return returnValue
    End Function

    Public Function checkNullIntegerZero(ByVal o As Object) As Integer
        If o IsNot Nothing And o IsNot DBNull.Value And Not o = "null" Then Return CInt(o)
        Return 0
    End Function
    Public Function checkNulDbl(ByVal o As Object) As Double
        If o IsNot Nothing And o IsNot DBNull.Value Then
            If IsNumeric(o) Then
                Return Math.Round(CDbl(o), 2)
            Else
                Return -1
            End If
        Else
            Return -1
        End If
    End Function

    Public Function checkNullBool(ByVal o As Object) As Boolean
        If o Is Nothing Or o Is DBNull.Value Or o = "null" Then Return 0
        Try
            Return CBool(o)
        Catch ex As Exception
        End Try
        Return 0
    End Function

    Public Function checkNullDateNothing(ByVal o As Object) As Object
        If o Is DBNull.Value Or Not IsDate(o) Then
            Return Nothing
        Else
            Return CDate(o)
        End If
    End Function
    Public Function getInvoices(jwt As String, dt As DataTable, startDate As Date, end_date As Date, uploadToDs As Boolean) As String
        Try
            Dim returnText As String = ""
            Dim failureText As String = ""

            Dim success As Boolean

            rest.DebugMode = test

            Dim bTls As Boolean = True
            Dim port As Integer = 443
            Dim bAutoReconnect As Boolean = True
            success = rest.Connect(API_STRING, port, bTls, bAutoReconnect)
            If (success <> True) Then
                Debug.WriteLine("ConnectFailReason: " & rest.ConnectFailReason)
                Debug.WriteLine(rest.LastErrorText)
                failureText = rest.LastErrorText
                Return False
            End If

            If (success <> True) Then
                Debug.WriteLine("BAFailReason: " & rest.ConnectFailReason)
                Debug.WriteLine(rest.LastErrorText)
                failureText = rest.LastErrorText
                Return False
            End If

            rest.ClearAllQueryParams()


            rest.AddQueryParam("start_date", startDate.ToString("yyyy-MM-dd"))
            rest.AddQueryParam("end_date", end_date.ToString("yyyy-MM-dd"))

            rest.AddHeader("X-API-Key", jwt)

            rest.IdleTimeoutMs = 1000000

            Dim responseJson As String = rest.FullRequestNoBody("GET", "/v1/invoices")
            If (rest.LastMethodSuccess <> True) Then
                Debug.WriteLine(rest.LastErrorText)
                rest.IdleTimeoutMs = 30000 'defualt
                Return rest.LastErrorText
            End If

            If (rest.ResponseStatusCode <> IIf(rest.DebugMode = True, 201, 200) And rest.ResponseStatusCode <> 404) Then
                Debug.WriteLine(rest.ResponseHeader)
                Return rest.LastErrorText
            End If

            Debug.WriteLine(responseJson)

            If test Then
                responseJson = "{""sender"":""MSTS"",""receiver"":""10738"",""datetime"":""2024-07-24 11:07:08"",""code"":""OK"",""message"":""OK"",""pdf_invoices"":[{""name"":""20240715_11024_ES_VAT.pdf"",""url"":"""",""total_amount_euro"":-2549.2400000000004,""total_vat_amount_euro"":-2549.2400000000002,""msts_vat_number"":""N0034998E"",""invoice_id"":1753066,""invoice_date"":""2024-07-15""},{""name"":""20240715_11024_FR_VAT.pdf"",""url"":"""",""total_amount_euro"":326.90000000000006,""total_vat_amount_euro"":54.49,""msts_vat_number"":""FR39491257770"",""invoice_id"":1753066,""invoice_date"":""2024-07-15""},{""name"":""20240715_11070_FR_VAT.pdf"",""url"":"""",""total_amount_euro"":0.00,""total_vat_amount_euro"":0.00,""msts_vat_number"":""FR39491257770"",""invoice_id"":1753066,""invoice_date"":""2024-07-15""}]}"
            End If


            Dim json As New Chilkat.JsonObject
            success = json.Load(responseJson)
            If (success <> True) Then
                Debug.WriteLine(json.LastErrorText)
            End If

            If json.StringOf("message") <> "" AndAlso json.StringOf("message") <> "OK" Then Return json.StringOf("message")

            Debug.WriteLine(json)


            Dim invoices As New Chilkat.JsonArray
            invoices = json.ArrayOf("pdf_invoices")
            If (json.LastMethodSuccess = False) Then
                Debug.WriteLine("pdf_invoices member not found.")
            End If


            Dim num As Integer = invoices.Size
            If num = -1 Then
                Return "FEHLER Array Invoices ist leer"
            End If


            Dim j As Integer = 0

            If dt IsNot Nothing And Not dt.Columns.Contains("name") Then

                dt.Columns.Add("name", GetType(String))
                dt.Columns.Add("url", GetType(String))
                dt.Columns.Add("total_amount_euro", GetType(Double))
                dt.Columns.Add("total_vat_amount_euro", GetType(Double))
                dt.Columns.Add("msts_vat_number", GetType(String))
                dt.Columns.Add("invoice_id", GetType(String))
                dt.Columns.Add("invoice_date", GetType(String))

                While j < num

                    Dim invoice As Chilkat.JsonObject = invoices.ObjectAt(j)

                    Dim R As DataRow = dt.NewRow
                    R("name") = checkNullStr(invoice.StringOf("name"))
                    R("url") = checkNullStr(invoice.StringOf("url"))
                    R("total_amount_euro") = CDbl(IIf(invoice.StringOf("total_amount_euro") = "null", "0", invoice.StringOf("total_amount_euro").Replace(".", ",")))
                    R("total_vat_amount_euro") = CDbl(IIf(invoice.StringOf("total_vat_amount_euro") = "null", "0", invoice.StringOf("total_vat_amount_euro").Replace(".", ",")))
                    R("msts_vat_number") = checkNullStr(invoice.StringOf("msts_vat_number"))
                    R("invoice_id") = checkNullInteger(invoice.StringOf("invoice_id"))
                    R("invoice_date") = checkNullStr(invoice.StringOf("invoice_date"))

                    Dim invoice_date_string As String = invoice.StringOf("invoice_date")

                    Try
                        If invoice_date_string <> "" AndAlso invoice_date_string <> "null" Then R("invoice_date") = CDate(invoice_date_string)

                    Catch ex As Exception
                        'VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
                    End Try
                    dt.Rows.Add(R)

                    If R("total_amount_euro") <> 0 And R("total_vat_amount_euro") <> 0 Then
                        Dim inv As New cMSEInvoices()
                        Dim nameString = checkNullStr(R("name"))
                        inv.name = nameString
                        inv.total_amount_euro = Math.Round(R("total_amount_euro"), 2)
                        inv.total_vat_amount_euro = Math.Round(R("total_vat_amount_euro"), 2)
                        inv.msts_vat_number = checkNullStr(R("msts_vat_number"))
                        inv.invoice_id = checkNullInteger(R("invoice_id"))
                        inv.invoice_date = checkNullDateNothing(R("invoice_date"))

                        If nameString.Length > 13 AndAlso nameString.Contains("_") Then
                            inv.customer_number = nameString.Substring(nameString.IndexOf("_") + 1, 5)
                        End If

                        If nameString.Length > 16 AndAlso nameString.Contains("_") Then
                            Dim indexOfFirst_ = nameString.IndexOf("_")
                            If nameString.Length > indexOfFirst_ + 2 Then
                                Dim countryString = nameString.Substring(nameString.IndexOf("_", indexOfFirst_ + 1) + 1, 2)
                                inv.country = countryString
                            End If

                        End If

                        inv.SAVE()
                    End If

                    j = j + 1
                End While


                For Each r As DataRow In dt.Rows

                    '\\fmzoll\f\FMZoll\MSE\TESTRECHNUNGEN
                    '\\datenarchiv\Datenarchiv\MDM_SCHNITTSTELLEN\ECHTSYSTEM\Nachrichtendaten_ZIEL\MSE

                    If r("url") <> "" AndAlso r("name") <> "" AndAlso r("name").contains("VAT") Then 'only VAT-Invoices
                        Dim inv As New cMSEInvoices(r("name"), r("inv.invoice_id"))
                        If Not inv.imported Then 'verhindert unnötige Downloads
                            Dim filepath = VERAG_PROG_ALLGEMEIN.cFormularManager.getPDFViaSpirePDF_FromURLStream(r("url"), r("name"), PDFRECHNUNGENPFAD, False)
                            If filepath <> "" AndAlso uploadToDs Then
                                Dim DS As New VERAG_PROG_ALLGEMEIN.cDATENSERVER("MDM", "MDM_DATEN", "MSE", Now.Year, Now.ToString("yyyyMMdd"), r("name"))
                                DS.uploadDataToDATENSERVER(filepath & "\" & r("name"),,,,,, True)
                                SQL.doSQL("Update [tblMSEInvoices] SET [daId]='" & DS.da_id & "', imported = 1 where [name] = '" & r("name") & "'", "FMZOLL")
                            End If

                        End If
                    End If


                Next

                dt = dt.DefaultView.ToTable()

            End If
        Catch ex As WebException
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try

    End Function



    Public Sub saveTransactions(num As Integer, dt As DataTable, transactions As Chilkat.JsonArray, receiver As Integer, Optional ignorePurchaseDate As Boolean = False, Optional onlyBilledTransactions As Boolean = True)

        Dim j As Integer = 0

        If dt IsNot Nothing And Not dt.Columns.Contains("transaction_id") Then

            dt.Columns.Add("transaction_id", GetType(String))
            dt.Columns.Add("partner_haulier_id", GetType(Integer))
            dt.Columns.Add("supplier_name", GetType(String))
            dt.Columns.Add("transaction_country", GetType(String))
            dt.Columns.Add("transaction_domain", GetType(String))
            dt.Columns.Add("purchase_datetime", GetType(DateTime))
            dt.Columns.Add("entry_point_name", GetType(String))
            dt.Columns.Add("entry_datetime", GetType(DateTime))
            dt.Columns.Add("exit_point_name", GetType(String))
            dt.Columns.Add("exit_datetime", GetType(DateTime))
            dt.Columns.Add("device_product_type", GetType(String))
            dt.Columns.Add("device_product_number", GetType(String))
            dt.Columns.Add("transaction_product_id", GetType(Integer))
            dt.Columns.Add("transaction_product_name", GetType(String))
            dt.Columns.Add("license_plate_number", GetType(String))
            dt.Columns.Add("vehicle_country", GetType(String))
            dt.Columns.Add("original_currency", GetType(String))
            dt.Columns.Add("original_net_amount", GetType(Double))
            dt.Columns.Add("original_gross_amount", GetType(Double))
            dt.Columns.Add("original_vat_amount", GetType(Double))
            dt.Columns.Add("original_vat_percentage", GetType(Double))
            dt.Columns.Add("customer_currency", GetType(String))
            dt.Columns.Add("transaction_net_amount", GetType(Double))
            dt.Columns.Add("transaction_gross_amount", GetType(Double))
            dt.Columns.Add("exempt_amount", GetType(Double))
            dt.Columns.Add("msts_fee_amount", GetType(Double))
            dt.Columns.Add("msts_vat_amount", GetType(Double))
            dt.Columns.Add("msts_vat_percentage", GetType(Double))
            dt.Columns.Add("total_gross_amount", GetType(Double))
            dt.Columns.Add("transaction_status", GetType(String))
            dt.Columns.Add("original_transaction_id", GetType(String))
            dt.Columns.Add("loading_date", GetType(Date))
            dt.Columns.Add("batch_seq_nr", GetType(Integer))
            dt.Columns.Add("distance_km", GetType(Double))
            dt.Columns.Add("USteuer_EUR", GetType(Double))
        End If
        While j < num

            Dim transaction As Chilkat.JsonObject = transactions.ObjectAt(j)

            Dim purchaseDate As New Chilkat.CkDateTime
            Dim entryDate As New Chilkat.CkDateTime
            Dim exitDate As New Chilkat.CkDateTime
            Dim loadingDate As New Chilkat.CkDateTime
            Dim getAsLocal As Boolean = False
            Dim USteuer_EUR As Double = 0

            Dim R As DataRow = dt.NewRow
            R("transaction_id") = transaction.StringOf("transaction_id")
            R("partner_haulier_id") = transaction.IntOf("partner_haulier_id")
            R("supplier_name") = transaction.StringOf("supplier_name")
            R("transaction_country") = transaction.StringOf("transaction_country")
            R("transaction_domain") = transaction.StringOf("transaction_domain")
            R("entry_point_name") = transaction.StringOf("entry_point_name")
            R("exit_point_name") = transaction.StringOf("exit_point_name")
            R("device_product_type") = transaction.StringOf("device_product_type")
            R("device_product_number") = transaction.StringOf("device_product_number")
            R("transaction_product_id") = transaction.IntOf("transaction_product_id")
            R("transaction_product_name") = transaction.StringOf("transaction_product_name")
            R("license_plate_number") = transaction.StringOf("license_plate_number")
            R("vehicle_country") = transaction.StringOf("vehicle_country")
            R("original_currency") = transaction.StringOf("original_currency")
            R("original_net_amount") = CDbl(transaction.StringOf("original_net_amount").Replace(".", ","))
            R("original_gross_amount") = CDbl(transaction.StringOf("original_gross_amount").Replace(".", ","))
            R("original_vat_percentage") = CDbl(IIf(transaction.StringOf("original_vat_percentage") = "null", 0, transaction.StringOf("original_vat_percentage").Replace(".", ",")))
            R("transaction_net_amount") = CDbl(transaction.StringOf("transaction_net_amount").Replace(".", ","))
            R("transaction_gross_amount") = CDbl(transaction.StringOf("transaction_gross_amount").Replace(".", ","))
            R("exempt_amount") = CDbl(transaction.StringOf("exempt_amount").Replace(".", ","))
            R("msts_fee_amount") = CDbl(transaction.StringOf("msts_fee_amount").Replace(".", ","))
            R("msts_vat_amount") = CDbl(transaction.StringOf("msts_vat_amount").Replace(".", ","))
            R("msts_vat_percentage") = CDbl(transaction.StringOf("msts_vat_percentage").Replace(".", ","))
            R("total_gross_amount") = CDbl(transaction.StringOf("total_gross_amount").Replace(".", ","))
            R("transaction_status") = transaction.StringOf("transaction_status")
            R("batch_seq_nr") = transaction.StringOf("batch_seq_nr")
            R("original_vat_amount") = CDbl(R("original_gross_amount") - R("original_net_amount"))

            If (transaction.StringOf("original_currency") = "EUR" Or R("original_vat_amount") = 0) Then
                USteuer_EUR = R("original_vat_amount")
            Else
                If transaction.StringOf("transaction_country") = "HU" Then
                    Dim curBruttobetragEUR = R("msts_fee_amount") + R("transaction_gross_amount")
                    Dim steuersatz = SQL.DLookup("1+[Steuersatz]", "[Länderverzeichnis für die Außenhandelsstatistik]", "[LandNr]=64", "FMZOLL")
                    Dim curNettobetragEUR = CInt(curBruttobetragEUR / steuersatz * 100 + 0.5) / 100
                    USteuer_EUR = Math.Round(curBruttobetragEUR - curNettobetragEUR, 2)
                End If
            End If

            R("USteuer_EUR") = USteuer_EUR
            'R("distance_km") = transaction.StringOf("distance_km")


            If (CDbl(transaction.StringOf("msts_fee_amount").Replace(".", ",")) <> 0) Then
                If (transaction.StringOf("device_product_type") = "" Or transaction.StringOf("device_product_type") = "null") Then
                    R("device_product_type") = transaction.StringOf("transaction_product_name")
                End If

            End If

            If ((transaction.StringOf("device_product_type") = "" Or transaction.StringOf("device_product_type") = "null") And transaction.StringOf("transaction_product_name") = "Charge - HU-GO SIM card fee") Then
                R("device_product_type") = transaction.StringOf("transaction_product_name")
            End If

            If (transaction.IntOf("transaction_product_id") = 453 And (transaction.StringOf("device_product_type") = "" Or transaction.StringOf("device_product_type") = "null")) Then
                R("device_product_type") = "HU-GO SIM renewal"
            End If

            Dim purchase_datetime_string As String = transaction.StringOf("purchase_datetime")
            Dim entry_datetime_string As String = transaction.StringOf("entry_datetime")
            Dim exit_datetime_string As String = transaction.StringOf("exit_datetime")
            Dim loading_date_string As String = transaction.StringOf("loading_date")

            Try
                If purchase_datetime_string <> "" AndAlso purchase_datetime_string <> "null" Then R("purchase_datetime") = CDate(purchase_datetime_string)
                If entry_datetime_string <> "" AndAlso entry_datetime_string <> "null" Then R("entry_datetime") = CDate(entry_datetime_string)
                If exit_datetime_string <> "" AndAlso exit_datetime_string <> "null" Then R("exit_datetime") = CDate(exit_datetime_string)
                If loading_date_string <> "" AndAlso loading_date_string <> "null" Then R("loading_date") = CDate(loading_date_string)
            Catch ex As Exception
                'VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
            End Try
            dt.Rows.Add(R)


            If IIf(ignorePurchaseDate, True, CDate(R("purchase_datetime")) >= "30.05.2024") Then

                Dim trans As New cMSETransactions()
                trans.transaction_id = checkNullStr(R("transaction_id"))
                trans.controller_id = receiver
                trans.partner_haulier_id = checkNullInteger(R("partner_haulier_id"))
                trans.supplier_name = checkNullStr(R("supplier_name"))
                trans.transaction_country = checkNullStr(R("transaction_country"))
                trans.transaction_domain = checkNullStr(R("transaction_domain"))
                trans.purchase_datetime = checkNullDateNothing(R("purchase_datetime"))
                trans.entry_point_name = checkNullStr(R("entry_point_name"))
                trans.entry_datetime = checkNullDateNothing(R("entry_datetime"))
                trans.exit_point_name = checkNullStr(R("exit_point_name"))
                trans.exit_datetime = checkNullDateNothing(R("exit_datetime"))
                trans.device_product_type = checkNullStr(R("device_product_type"))
                trans.device_product_number = checkNullStr(R("device_product_number"))
                trans.transaction_product_id = checkNullInteger(R("transaction_product_id"))
                trans.transaction_product_name = checkNullStr(R("transaction_product_name"))
                trans.license_plate_number = checkNullStr(R("license_plate_number"))
                trans.vehicle_country = checkNullStr(R("vehicle_country"))
                trans.original_currency = checkNullStr(R("original_currency"))
                trans.original_net_amount = checkNulDbl(R("original_net_amount"))
                trans.original_gross_amount = checkNulDbl(R("original_gross_amount"))
                trans.original_vat_amount = checkNulDbl(R("original_vat_amount"))
                trans.original_vat_percentage = checkNulDbl(R("original_vat_percentage"))
                trans.transaction_net_amount = checkNulDbl(R("transaction_net_amount"))
                trans.transaction_gross_amount = checkNulDbl(R("transaction_gross_amount"))
                trans.msts_fee_amount = checkNulDbl(R("msts_fee_amount"))
                trans.msts_vat_amount = checkNulDbl(R("msts_vat_amount"))
                trans.total_gross_amount = checkNulDbl(R("total_gross_amount"))
                trans.transaction_status = checkNullStr(R("transaction_status"))
                trans.loading_date = checkNullDateNothing(R("loading_date"))
                trans.batch_seq_nr = checkNullInteger(R("batch_seq_nr"))
                trans.tstmp = Now()
                trans.USteuer_EUR = checkNulDbl(R("USteuer_EUR"))
                'trans.distance_km = CDbl(R("distance_km"))

                If onlyBilledTransactions Then
                    If trans.transaction_status = "Billed" Then trans.SAVE()
                Else
                    trans.SAVE()
                End If


            End If



            j = j + 1
        End While


        dt = dt.DefaultView.ToTable()



    End Sub

    Public Sub saveSettlements(num As Integer, dt As DataTable, transactions As Chilkat.JsonArray, receiver As Integer)


        Dim j As Integer = 0

        If dt IsNot Nothing And Not dt.Columns.Contains("transaction_id") Then

            dt.Columns.Add("transaction_id", GetType(String))
            dt.Columns.Add("invoice_number", GetType(String))
            dt.Columns.Add("invoice_date", GetType(String))
            dt.Columns.Add("specification_page_id", GetType(String))
            dt.Columns.Add("specification_page_name", GetType(String))
            dt.Columns.Add("transaction_debit_or_credit", GetType(String))
            dt.Columns.Add("original_transaction_id", GetType(String))
            dt.Columns.Add("original_invoice_number", GetType(Integer))
            dt.Columns.Add("original_invoice_date", GetType(String))
            dt.Columns.Add("credit_comment", GetType(String))
        End If

        While j < num

            Dim transaction As Chilkat.JsonObject = transactions.ObjectAt(j)

            Dim R As DataRow = dt.NewRow
            R("transaction_id") = checkNullStr(transaction.StringOf("transaction_id"))
            R("invoice_number") = checkNullStr(transaction.StringOf("invoice_number"))
            R("specification_page_id") = checkNullStr(transaction.StringOf("specification_page_id"))
            R("specification_page_name") = checkNullStr(transaction.StringOf("specification_page_name"))
            R("transaction_debit_or_credit") = checkNullStr(transaction.StringOf("transaction_debit_or_credit"))
            R("original_transaction_id") = checkNullStr(transaction.StringOf("original_transaction_id"))
            R("original_invoice_number") = checkNullInteger(transaction.StringOf("original_invoice_number"))
            R("credit_comment") = checkNullStr(transaction.StringOf("credit_comment"))


            Dim invoice_date_string As String = transaction.StringOf("invoice_date")
            Dim original_invoice_date_string As String = transaction.StringOf("original_invoice_date")


            Try
                If invoice_date_string <> "" AndAlso invoice_date_string <> "null" Then R("invoice_date") = CDate(invoice_date_string)
                If original_invoice_date_string <> "" AndAlso original_invoice_date_string <> "null" Then R("original_invoice_date") = CDate(original_invoice_date_string)

            Catch ex As Exception
                'VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
            End Try
            dt.Rows.Add(R)

            Dim trans = New cMSESettlements(R("transaction_id"))
            trans.invoice_number = checkNullStr(R("invoice_number"))
            trans.invoice_date = checkNullDateNothing(R("invoice_date"))
            trans.specification_page_id = checkNullStr(R("specification_page_id"))
            trans.specification_page_name = checkNullStr(R("specification_page_name"))
            trans.transaction_debit_or_credit = checkNullStr(R("transaction_debit_or_credit"))
            trans.original_transaction_id = checkNullStr(R("original_transaction_id"))
            trans.original_invoice_number = checkNullInteger(R("original_invoice_number"))
            trans.original_invoice_date = checkNullDateNothing(R("original_invoice_date"))
            trans.credit_comment = checkNullStr(R("credit_comment"))
            trans.SAVE()


            j = j + 1

        End While


        dt = dt.DefaultView.ToTable()


    End Sub

    Public Sub saveCustomers(num As Integer, dt As DataTable, customers As Chilkat.JsonArray)

        Dim j As Integer = 0

        If dt IsNot Nothing And Not dt.Columns.Contains("customer_id") Then
            dt.Columns.Add("customer_id", GetType(Integer))
            dt.Columns.Add("partner_customer_number", GetType(String))
            dt.Columns.Add("customer_name", GetType(String))
            dt.Columns.Add("vat_number", GetType(String))
            dt.Columns.Add("alternative_vat_number", GetType(String))
            dt.Columns.Add("coc_number", GetType(String))
            dt.Columns.Add("partner_fleet_card_number", GetType(String))
        End If

        While j < num

            Dim custom As Chilkat.JsonObject = customers.ObjectAt(j)



            Dim R As DataRow = dt.NewRow
            R("customer_id") = custom.IntOf("customer_id")
            R("partner_customer_number") = custom.StringOf("partner_customer_number")
            R("customer_name") = custom.StringOf("customer_name")
            R("vat_number") = custom.StringOf("vat_number")
            R("alternative_vat_number") = custom.StringOf("alternative_vat_number")
            R("coc_number") = custom.StringOf("coc_number")
            R("partner_fleet_card_number") = custom.StringOf("partner_fleet_card_number")

            dt.Rows.Add(R)



            Dim cust As New cMSECustomers(R("customer_id"))
            cust.partner_customer_number = checkNullStr(R("partner_customer_number"))
            cust.customer_name = checkNullStr(R("customer_name"))
            cust.vat_number = checkNullStr(R("vat_number"))
            cust.alternative_vat_number = checkNullStr(R("alternative_vat_number"))
            cust.coc_number = checkNullStr(R("coc_number"))
            cust.partner_fleet_card_number = checkNullStr(R("partner_fleet_card_number"))
            cust.tstmp = Now()
            If cust.customer_id <> "12065 " Then cust.SAVE() 'diesed Kunde soll nicht gespeichert werden!!

            j = j + 1
        End While


        dt = dt.DefaultView.ToTable()



    End Sub


End Class

Public Class cMSEInvoices
    Property id As Integer
    Property name As Object = Nothing
    Property total_amount_euro As Object = Nothing
    Property total_vat_amount_euro As Object = Nothing
    Property msts_vat_number As Object = Nothing
    Property invoice_id As Object = Nothing
    Property invoice_date As Object = Nothing
    Property customer_number As Object = Nothing
    Property country As Object = Nothing
    Property imported As Boolean = False
    Property daId As Object = Nothing

    Public hasEntry = False

    Dim SQL As New SQL

    Sub New()

    End Sub

    Sub New(name, invoice_id)
        Me.name = name
        Me.invoice_id = invoice_id
        LOAD()
    End Sub
    Function getParameterList() As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable)
        Dim list As New List(Of VERAG_PROG_ALLGEMEIN.SQLVariable)
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("name", name))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("total_amount_euro", total_amount_euro))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("total_vat_amount_euro", total_vat_amount_euro))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("msts_vat_number", msts_vat_number))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("invoice_id", invoice_id))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("invoice_date", invoice_date))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("customer_number", customer_number))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("country", country))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("imported", imported))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("daId", daId))

        Return list
    End Function



    Public Function SAVE() As Boolean
        Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()

        Dim sqlstr = " BEGIN TRAN IF EXISTS(SELECT * FROM tblMSEInvoices  WHERE name=@name AND invoice_id = @invoice_id) " &
                       " BEGIN " & getUpdateCmd() & " END " &
                       " Else " &
                       " BEGIN " & getInsertCmd() & " END " &
                       " commit tran "

        Return SQL.doSQLVarList(sqlstr, "FMZOLL", , list)
    End Function

    Public Sub LOAD()
        Try
            hasEntry = False
            Using conn As SqlConnection = SQL.GetNewOpenConnectionFMZOLL()
                Using cmd As New SqlCommand("SELECT * FROM tblMSEInvoices WHERE name=@name AND invoice_id = @invoice_id", conn)
                    cmd.Parameters.AddWithValue("@name", name)
                    cmd.Parameters.AddWithValue("@invoice_id", invoice_id)
                    Dim dr = cmd.ExecuteReader()
                    If dr.Read Then
                        For Each li In getParameterList()
                            Dim propInfo As PropertyInfo = Me.GetType.GetProperty(li.Scalarvariable)

                            If dr.Item(li.Text) Is DBNull.Value Then
                                propInfo.SetValue(Me, Nothing)
                            Else
                                propInfo.SetValue(Me, dr.Item(li.Text))
                            End If

                        Next
                        hasEntry = True
                    End If
                    dr.Close()
                End Using
            End Using
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try
    End Sub



    Public Function getUpdateCmd() As String
        Try
            Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()

            Dim str As String = ""
            For Each i In list
                If Not i.isPrimaryParam Then
                    str &= "[" & i.Text & "] = @" & i.Scalarvariable & "," '.Replace("-", "").Replace(" ", "") & ","
                End If
            Next
            str = str.Substring(0, str.Length - 1) 'wg. ','
            Return (" UPDATE tblMSEInvoices SET " & str & " WHERE name=@name AND invoice_id = @invoice_id ")

        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try
        Return ""
    End Function


    Public Function getInsertCmd() As String
        Try
            Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()
            Dim str As String = ""
            Dim values As String = ""
            For Each i In list
                If Not i.isPrimaryParam Then
                    str &= "[" & i.Text & "],"
                    values &= "@" & i.Scalarvariable & "," '.Replace("-", "").Replace(" ", "") & ","
                End If
            Next
            str = str.Substring(0, str.Length - 1) 'wg. ','
            values = values.Substring(0, values.Length - 1) 'wg. ','
            Return (" INSERT INTO tblMSEInvoices  (" & str & ") VALUES(" & values & ")  ")
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try
        Return ""
    End Function
End Class

Public Class cMSETransactions

    Property transaction_id As Object = Nothing
    Property controller_id As Integer
    Property partner_haulier_id As Object = Nothing
    Property supplier_name As Object = Nothing
    Property transaction_country As Object = Nothing
    Property transaction_domain As Object = Nothing
    Property purchase_datetime As Object = Nothing
    Property entry_point_name As Object = Nothing
    Property entry_datetime As Object = Nothing
    Property exit_point_name As Object = Nothing
    Property exit_datetime As Object = Nothing
    Property device_product_type As Object = Nothing
    Property device_product_number As Object = Nothing
    Property transaction_product_id As Object = Nothing
    Property transaction_product_name As Object = Nothing
    Property license_plate_number As Object = Nothing
    Property vehicle_country As Object = Nothing
    Property original_currency As Object = Nothing
    Property original_net_amount As Object = Nothing
    Property original_gross_amount As Object = Nothing
    Property original_vat_amount As Object = Nothing
    Property original_vat_percentage As Object = Nothing
    Property customer_currency As Object = Nothing
    Property transaction_net_amount As Object = Nothing
    Property transaction_gross_amount As Object = Nothing
    Property exempt_amount As Object = Nothing
    Property msts_fee_amount As Object = Nothing
    Property msts_vat_amount As Object = Nothing
    Property msts_vat_percentage As Object = Nothing
    Property total_gross_amount As Object = Nothing
    Property transaction_status As Object = Nothing
    Property loading_date As Object = Nothing
    Property batch_seq_nr As Object = Nothing
    Property distance_km As Object = Nothing
    Property tstmp As Object = Nothing
    Property USteuer_EUR As Object = Nothing
    Property charged As Boolean = False
    Property chargedDatetime As Object = Nothing

    Public hasEntry = False

    Dim SQL As New SQL

    Sub New()
    End Sub

    Sub New(transaction_id)
        Me.transaction_id = transaction_id
        LOAD()
    End Sub
    Function getParameterList() As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable)
        Dim list As New List(Of VERAG_PROG_ALLGEMEIN.SQLVariable)

        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("transaction_id", transaction_id))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("controller_id", controller_id))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("partner_haulier_id", partner_haulier_id))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("supplier_name", supplier_name))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("transaction_country", transaction_country))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("transaction_domain", transaction_domain))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("purchase_datetime", purchase_datetime))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("entry_point_name", entry_point_name))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("entry_datetime", entry_datetime))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("exit_point_name", exit_point_name))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("exit_datetime", exit_datetime))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("device_product_type", device_product_type))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("device_product_number", device_product_number))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("transaction_product_id", transaction_product_id))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("transaction_product_name", transaction_product_name))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("license_plate_number", license_plate_number))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("vehicle_country", vehicle_country))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("original_currency", original_currency))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("original_net_amount", original_net_amount))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("original_gross_amount", original_gross_amount))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("original_vat_amount", original_vat_amount))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("original_vat_percentage", original_vat_percentage))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("customer_currency", customer_currency))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("transaction_net_amount", transaction_net_amount))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("transaction_gross_amount", transaction_gross_amount))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("exempt_amount", exempt_amount))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("msts_fee_amount", msts_fee_amount))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("msts_vat_amount", msts_vat_amount))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("msts_vat_percentage", msts_vat_percentage))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("total_gross_amount", total_gross_amount))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("transaction_status", transaction_status))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("loading_date", loading_date))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("batch_seq_nr", batch_seq_nr))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("distance_km", distance_km))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("tstmp", tstmp))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("USteuer_EUR", USteuer_EUR))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("charged", charged))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("chargedDatetime", chargedDatetime))


        Return list
    End Function



    Public Function SAVE() As Boolean
        Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()

        Dim sqlstr = " BEGIN TRAN IF EXISTS(SELECT * FROM tblMSETransactions  WHERE transaction_id=@transaction_id) " &
                       " BEGIN " & getUpdateCmd() & " END " &
                       " Else " &
                       " BEGIN " & getInsertCmd() & " END " &
                       " commit tran "

        Return SQL.doSQLVarList(sqlstr, "FMZOLL", , list)
    End Function

    Public Sub LOAD()
        Try
            hasEntry = False
            Using conn As SqlConnection = SQL.GetNewOpenConnectionFMZOLL()
                Using cmd As New SqlCommand("SELECT * FROM tblMSETransactions WHERE transaction_id=@transaction_id", conn)
                    cmd.Parameters.AddWithValue("@transaction_id", transaction_id)
                    Dim dr = cmd.ExecuteReader()
                    If dr.Read Then
                        For Each li In getParameterList()
                            Dim propInfo As PropertyInfo = Me.GetType.GetProperty(li.Scalarvariable)

                            If dr.Item(li.Text) Is DBNull.Value Then
                                propInfo.SetValue(Me, Nothing)
                            Else
                                propInfo.SetValue(Me, dr.Item(li.Text))
                            End If

                        Next
                        hasEntry = True
                    End If
                    dr.Close()
                End Using
            End Using
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try
    End Sub



    Public Function getUpdateCmd() As String
        Try
            Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()

            Dim str As String = ""
            For Each i In list
                If Not i.isPrimaryParam Then
                    str &= "[" & i.Text & "] = @" & i.Scalarvariable & "," '.Replace("-", "").Replace(" ", "") & ","
                End If
            Next
            str = str.Substring(0, str.Length - 1) 'wg. ','
            Return (" UPDATE tblMSETransactions SET " & str & " WHERE transaction_id=@transaction_id and charged <> 1")

        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try
        Return ""
    End Function


    Public Function getInsertCmd() As String
        Try
            Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()
            Dim str As String = ""
            Dim values As String = ""
            For Each i In list
                If Not i.isPrimaryParam Then
                    str &= "[" & i.Text & "],"
                    values &= "@" & i.Scalarvariable & "," '.Replace("-", "").Replace(" ", "") & ","
                End If
            Next
            str = str.Substring(0, str.Length - 1) 'wg. ','
            values = values.Substring(0, values.Length - 1) 'wg. ','
            Return (" INSERT INTO tblMSETransactions  (" & str & ") VALUES(" & values & ")  ")
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try
        Return ""
    End Function
End Class

Public Class cMSESettlements

    Property transaction_id As Object = Nothing
    Property invoice_number As Object = Nothing
    Property invoice_date As Object = Nothing
    Property specification_page_id As Object = Nothing
    Property specification_page_name As Object = Nothing
    Property transaction_debit_or_credit As Object = Nothing
    Property original_transaction_id As Object = Nothing
    Property original_invoice_number As Object = Nothing
    Property original_invoice_date As Object = Nothing
    Property credit_comment As Object = Nothing


    Public hasEntry = False

    Dim SQL As New SQL

    Sub New()
    End Sub

    Sub New(transaction_id)
        Me.transaction_id = transaction_id
        LOAD()
    End Sub
    Function getParameterList() As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable)
        Dim list As New List(Of VERAG_PROG_ALLGEMEIN.SQLVariable)

        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("transaction_id", transaction_id))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("invoice_number", invoice_number))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("invoice_date", invoice_date))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("specification_page_id", specification_page_id))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("specification_page_name", specification_page_name))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("transaction_debit_or_credit", transaction_debit_or_credit))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("original_transaction_id", original_transaction_id))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("original_invoice_number", original_invoice_number))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("original_invoice_date", original_invoice_date))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("credit_comment", credit_comment))

        Return list
    End Function



    Public Function SAVE() As Boolean
        Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()

        Dim sqlstr = " BEGIN TRAN IF EXISTS(SELECT * FROM tblMSESettlements  WHERE transaction_id=@transaction_id) " &
                       " BEGIN " & getUpdateCmd() & " END " &
                       " Else " &
                       " BEGIN " & getInsertCmd() & " END " &
                       " commit tran "

        Return SQL.doSQLVarList(sqlstr, "FMZOLL", , list)
    End Function

    Public Sub LOAD()
        Try
            hasEntry = False
            Using conn As SqlConnection = SQL.GetNewOpenConnectionFMZOLL()
                Using cmd As New SqlCommand("SELECT * FROM tblMSESettlements WHERE transaction_id=@transaction_id", conn)
                    cmd.Parameters.AddWithValue("@transaction_id", transaction_id)
                    Dim dr = cmd.ExecuteReader()
                    If dr.Read Then
                        For Each li In getParameterList()
                            Dim propInfo As PropertyInfo = Me.GetType.GetProperty(li.Scalarvariable)

                            If dr.Item(li.Text) Is DBNull.Value Then
                                propInfo.SetValue(Me, Nothing)
                            Else
                                propInfo.SetValue(Me, dr.Item(li.Text))
                            End If

                        Next
                        hasEntry = True
                    End If
                    dr.Close()
                End Using
            End Using
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try
    End Sub



    Public Function getUpdateCmd() As String
        Try
            Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()

            Dim str As String = ""
            For Each i In list
                If Not i.isPrimaryParam Then
                    str &= "[" & i.Text & "] = @" & i.Scalarvariable & "," '.Replace("-", "").Replace(" ", "") & ","
                End If
            Next
            str = str.Substring(0, str.Length - 1) 'wg. ','
            Return (" UPDATE tblMSESettlements SET " & str & " WHERE transaction_id=@transaction_id")

        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try
        Return ""
    End Function


    Public Function getInsertCmd() As String
        Try
            Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()
            Dim str As String = ""
            Dim values As String = ""
            For Each i In list
                If Not i.isPrimaryParam Then
                    str &= "[" & i.Text & "],"
                    values &= "@" & i.Scalarvariable & "," '.Replace("-", "").Replace(" ", "") & ","
                End If
            Next
            str = str.Substring(0, str.Length - 1) 'wg. ','
            values = values.Substring(0, values.Length - 1) 'wg. ','
            Return (" INSERT INTO tblMSESettlements  (" & str & ") VALUES(" & values & ")  ")
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try
        Return ""
    End Function
End Class

Public Class cMSECustomers

    Property customer_id As Object = Nothing
    Property partner_customer_number As Object = Nothing
    Property customer_name As Object = Nothing
    Property vat_number As Object = Nothing
    Property alternative_vat_number As Object = Nothing
    Property coc_number As Object = Nothing
    Property partner_fleet_card_number As Object = Nothing
    Property tstmp As Object = Nothing

    Public hasEntry = False

    Dim SQL As New SQL

    Sub New()
    End Sub

    Sub New(customer_id)
        Me.customer_id = customer_id
        LOAD()
    End Sub
    Function getParameterList() As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable)
        Dim list As New List(Of VERAG_PROG_ALLGEMEIN.SQLVariable)

        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("customer_id", customer_id))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("partner_customer_number", partner_customer_number))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("customer_name", customer_name))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("vat_number", vat_number))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("alternative_vat_number", alternative_vat_number))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("coc_number", coc_number))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("partner_fleet_card_number", partner_fleet_card_number))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("tstmp", tstmp))

        Return list
    End Function



    Public Function SAVE() As Boolean
        Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()

        Dim sqlstr = " BEGIN TRAN IF EXISTS(SELECT * FROM tblMSECustomers  WHERE customer_id=@customer_id) " &
                       " BEGIN " & getUpdateCmd() & " END " &
                       " Else " &
                       " BEGIN " & getInsertCmd() & " END " &
                       " commit tran "

        Return SQL.doSQLVarList(sqlstr, "FMZOLL", , list)
    End Function

    Public Sub LOAD()
        Try
            hasEntry = False
            Using conn As SqlConnection = SQL.GetNewOpenConnectionFMZOLL()
                Using cmd As New SqlCommand("SELECT * FROM tblMSECustomers WHERE customer_id=@customer_id", conn)
                    cmd.Parameters.AddWithValue("@customer_id", customer_id)
                    Dim dr = cmd.ExecuteReader()
                    If dr.Read Then
                        For Each li In getParameterList()
                            Dim propInfo As PropertyInfo = Me.GetType.GetProperty(li.Scalarvariable)

                            If dr.Item(li.Text) Is DBNull.Value Then
                                propInfo.SetValue(Me, Nothing)
                            Else
                                propInfo.SetValue(Me, dr.Item(li.Text))
                            End If

                        Next
                        hasEntry = True
                    End If
                    dr.Close()
                End Using
            End Using
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try
    End Sub



    Public Function getUpdateCmd() As String
        Try
            Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()

            Dim str As String = ""
            For Each i In list
                If Not i.isPrimaryParam Then
                    str &= "[" & i.Text & "] = @" & i.Scalarvariable & "," '.Replace("-", "").Replace(" ", "") & ","
                End If
            Next
            str = str.Substring(0, str.Length - 1) 'wg. ','
            Return (" UPDATE tblMSECustomers SET " & str & " WHERE customer_id=@customer_id")

        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try
        Return ""
    End Function


    Public Function getInsertCmd() As String
        Try
            Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()
            Dim str As String = ""
            Dim values As String = ""
            For Each i In list
                If Not i.isPrimaryParam Then
                    str &= "[" & i.Text & "],"
                    values &= "@" & i.Scalarvariable & "," '.Replace("-", "").Replace(" ", "") & ","
                End If
            Next
            str = str.Substring(0, str.Length - 1) 'wg. ','
            values = values.Substring(0, values.Length - 1) 'wg. ','
            Return (" INSERT INTO tblMSECustomers  (" & str & ") VALUES(" & values & ")  ")
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try
        Return ""
    End Function
End Class
