Imports SDL.RKSVServer
Imports System.Drawing.Printing
Imports GrapeCity.ActiveReports
Imports VERAG_PROG_ALLGEMEIN.DSFinVKService
Imports VERAG_PROG_ALLGEMEIN.TESTJSON

Public Class cRKSV
    Shared SQL As New SQL

    Shared Function insertRKSV(ByVal kasse As cRKSV_Kasse, CompanyGUID As String, ByVal umsatzZaehler As Double, ByVal belegDat As DateTime, ByVal steuerSchluessel As Integer, ByVal RKSV_Beleg_Id As Integer, ByVal summeBRUTTO As Double, ByRef QR_CodeString As String, ByRef LastJWS As String, TEST As Boolean, ByRef answer As String) As Boolean
        '
        Try



            Dim client As RKSVWcfClient = New RKSVWcfClient()
            client.Endpoint.Address = New System.ServiceModel.EndpointAddress(getRKSVLink(kasse))
            client.Open()
            '   svcRKSV.DBUserCredentials m_credentials = new svcRKSV.DBUserCredentials();
            Dim credentials As New SDL.RKSVServer.DBUserCredentials

            credentials.Database = "RKSVWcfDB"
            credentials.Server = "AVISO\SQLEXPRESS"

            credentials.Username = "Admin"
            credentials.Password = "verag#2"
            credentials.CashboxID = kasse.rksv_bez
            '"VERAG-SUB-KASSE-ZOLL"
            credentials.CompanyGUID = CompanyGUID ' "9119d9ae-f549-4a0f-a50f-0500ec7ca059"

            Dim jws As String = String.Empty
            Dim qr As String = String.Empty
            Dim ocra As String = String.Empty
            'Dim answer As String = String.Empty

            Dim Belegnummer = RKSV_Beleg_Id
            Dim BelegDatumUhrzeit = belegDat ' BELEG.BelegDat

            Dim steuersatz As Double = SQL.getValueTxtBySql("SELECT isnull(tblSteuersätze.Steuersatz,0) FROM tblSteuersätze WHERE tblSteuersätze.Nr='" & steuerSchluessel & "' ", "FMZOLL")



            Dim BetragSatzNormal = IIf(steuersatz = 0.2, summeBRUTTO, 0.0) 'summe
            Dim BetragSatzErm1 = IIf(steuersatz = 0.1, summeBRUTTO, 0.0)
            Dim BetragSatzErm2 = IIf(steuersatz = 0.13, summeBRUTTO, 0.0)
            Dim BetragSatzNull = IIf(steuersatz = 0.0, summeBRUTTO, 0.0)
            Dim BetragSatzBesonders = IIf(steuersatz = 0.19, summeBRUTTO, 0.0)
            Dim StandUmsatzzaehler = umsatzZaehler 'KASSE.rksv_Umsatzzaehler



            If TEST Then
                If (client.SignTrainReceipt(credentials, Belegnummer, BelegDatumUhrzeit, BetragSatzNormal, BetragSatzErm1, BetragSatzErm2, BetragSatzBesonders, BetragSatzNull, jws, qr, ocra, answer)) Then
                    QR_CodeString = qr
                    LastJWS = jws
                Else
                    If (jws.Length > 50) Then
                        QR_CodeString = qr
                        LastJWS = jws
                    Else
                        'Unmittelbares return, damit Änderungen Rückgängig gemacht werden, bevor die nächste Belegerstellung anfängt
                        'MessageBox.Show(answer, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
                        Return False
                    End If
                End If
            Else
                If (client.SignReceipt(credentials, Belegnummer, BelegDatumUhrzeit, BetragSatzNormal, BetragSatzErm1, BetragSatzErm2, BetragSatzBesonders, BetragSatzNull, StandUmsatzzaehler, jws, qr, ocra, answer)) Then
                    QR_CodeString = qr
                    LastJWS = jws
                Else
                    If (jws.Length > 50) Then
                        QR_CodeString = qr
                        LastJWS = jws
                    Else
                        'Unmittelbares return, damit Änderungen Rückgängig gemacht werden, bevor die nächste Belegerstellung anfängt
                        ' MessageBox.Show(answer, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
                        Return False
                    End If
                End If
            End If

            If QR_CodeString.Length > 50 And LastJWS.Length > 50 Then
                Return True
            End If

        Catch ex As Exception
            MsgBox("Es ist ein Fehler bei der Signatur aufgetreten (insertRKSV): " & vbNewLine & ex.Message & ex.StackTrace)
        End Try
        Return False
    End Function

    Shared Function getKB(BELEG As EABeleg, PERSONAL As cPersonal, ByRef KBEntry As cKassenbuch, ByRef KBEntryGB As cKassenbuch, Firma As String) As Boolean
        Dim j1 = SQL.getValueTxtBySql("SELECT [JournalNr]  FROM [tblKassenbuch] " &
                                                                  " WHERE  [Mandant]='" & PERSONAL.Mandant & "'  AND [Niederlassung]='" & PERSONAL.Niederlassung & "'  AND [Benutzer]='" & PERSONAL.ID & "'  AND [Geschäftsjahr]='" & cRKSV.getGJ_FIRMA(BELEG.BelegDat, Firma) & "'  AND [BelegNr] ='" & BELEG.BelegNr & "'   and Steuer <=0   AND Soll <> 0", "FMZOLL")
        Dim j2 = SQL.getValueTxtBySql("SELECT [JournalNr]  FROM [tblKassenbuch] " &
                                                    " WHERE  [Mandant]='" & PERSONAL.Mandant & "'  AND [Niederlassung]='" & PERSONAL.Niederlassung & "'  AND [Benutzer]='" & PERSONAL.ID & "'  AND [Geschäftsjahr]='" & cRKSV.getGJ_FIRMA(BELEG.BelegDat, Firma) & "'  AND [BelegNr] ='" & BELEG.BelegNr & "'   and Steuer <=0   AND Haben <> 0", "FMZOLL")
        Dim journalNr = ""
        Dim journalNrGB = ""

        If BELEG.Belegart = 1 Then
            journalNr = j1
            journalNrGB = j2
        Else
            journalNr = j2
            journalNrGB = j1
        End If

        If Not IsNumeric(journalNr) Or Not IsNumeric(journalNrGB) Then
            MsgBox("Zugehörige Kassenbucheinträge wurden nicht gefunden!")
            Return False
        End If
        'J1 /j2 nicht ganz sicher...
        KBEntry = New cKassenbuch("LOAD", BELEG.Mandant, BELEG.Niederlassung, BELEG.Benutzer, cRKSV.getGJ_FIRMA(BELEG.BelegDat, Firma), j2)
        KBEntryGB = New cKassenbuch("LOAD", BELEG.Mandant, BELEG.Niederlassung, BELEG.Benutzer, cRKSV.getGJ_FIRMA(BELEG.BelegDat, Firma), j1)
        Return True
    End Function

    Shared Function getZahlungsmittel(BELEG As EABeleg, PERSONAL As cPersonal, Firma As String) As String
        Dim zm = SQL.getValueTxtBySql("SELECT [Finanzwege]  FROM [tblKassenbuch] " &
                                                                  " WHERE  [Mandant]='" & PERSONAL.Mandant & "'  AND [Niederlassung]='" & PERSONAL.Niederlassung & "'  AND [Benutzer]='" & PERSONAL.ID & "'  AND [Geschäftsjahr]='" & cRKSV.getGJ_FIRMA(BELEG.BelegDat, Firma) & "'  AND [BelegNr] ='" & BELEG.BelegNr & "'   and Steuer <=0   AND Soll <> 0", "FMZOLL")


        If zm Is DBNull.Value Or zm Is Nothing Then
            Return "-"
        End If

        Return zm
    End Function


    Shared Function getDEP(ByVal kasse_id As Integer, ByRef exportResult As String) As Boolean

        Dim KASSE As New cRKSV_Kasse(kasse_id)
        Dim client As RKSVWcfClient = New RKSVWcfClient()
        client.Endpoint.Address = New System.ServiceModel.EndpointAddress(getRKSVLink(KASSE))
        client.Open()
        '   svcRKSV.DBUserCredentials m_credentials = new svcRKSV.DBUserCredentials();
        Dim credentials As New SDL.RKSVServer.DBUserCredentials

        credentials.Database = "RKSVWcfDB"
        credentials.Server = "AVISO\SQLEXPRESS"
        'KASSENPWD: !VERAG-SUB-KASSE-ZOLL#2016
        '   Select Case kasse ' KASSE.rksv_bez
        '      Case "VERAG-SUB-KASSE-ZOLL"
        credentials.Username = "Admin"
        credentials.Password = "verag#2"



        If KASSE.rksv_ITG_id Is Nothing Then
            MsgBox("Keine RKSV-ITG-ID vorhanden!")
            Return False
        End If


        credentials.CashboxID = KASSE.rksv_bez '"VERAG-SUB-KASSE-ZOLL"
        credentials.CompanyGUID = KASSE.rksv_CompanyGUID ' "9119d9ae-f549-4a0f-a50f-0500ec7ca059"

        '     Dim inValue As RKSVServer.ExportJWSRequest = New RKSVServer.ExportJWSRequest()
        '   inValue.certificate = certificate
        ' #   inValue.certificateChain = certificateChain
        '    inValue.jwsCompactReceipts = jwsCompactReceipts
        '    inValue.exportResult = exportResult
        '    Dim retVal As RKSVServer.ExportJWSResponse = CType(Me, RKSVServer.IRKSVWcf).ExportJWS(inValue)
        '    exportResult = retVal.exportResult

        '      Dim exportResult = ""

        If False Then '(client.ExportJWS( certificate ,  certificateChain ,  jwsCompactReceipts,  exportResult )  Then
            '   If (client.SignTrainReceipt(credentials, Belegnummer, BelegDatumUhrzeit, BetragSatzNormal,
            '           BetragSatzErm1, BetragSatzErm2, BetragSatzNull, BetragSatzBesonders,
            '            jws, qr, ocra, answer)) Then

        Else

            MessageBox.Show("FEHLER", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Return False

        End If
        Return True
    End Function

    'Shared Function getRKSVLink(ByVal kasse As String) As String
    '    If kasse = "FRONT-OFFICE-SUB-KASSE" Then
    '        Return "http://192.168.0.25:8733/Design_Time_Addresses/RKSVCompleteServer/Service1/?singleWsdl"
    '    End If
    '    Return "http://192.168.0.106:8733/Design_Time_Addresses/RKSVCompleteServer/Service1/?singleWsdl"
    'End Function

    Shared Function getRKSVLink(ByVal kasse As cRKSV_Kasse) As String
        Return kasse.rksv_ipAdresse
        'Return getRKSVLink(kasse.rksv_bez)
    End Function
    'Shared Function stornoRKSV_DE(ByVal kasse As cRKSV_Kasse, ByVal belegDat As DateTime, ByVal steuerSchluessel As Integer, ByVal RKSV_Beleg_Id As Integer, ByVal summeBRUTTO As Double, ByRef QR_CodeString As String, ByRef LastJWS As String, ByRef answer As String) As Boolean
    Shared Function stornoRKSV_DE_TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT(PERSONAL As cPersonal, BELEG As EABeleg, ByVal kasse As cRKSV_Kasse, ByVal RKSV_Beleg_Id As Integer, ByVal OLD_RKSV_Beleg_Id As Object, ByVal summeBRUTTO As Double, ByRef QR_CodeString As String, ByRef LastJWS As String, TEST As Boolean, ByRef answer As String) As Boolean
        Try

            ' MsgBox("0: ")
            Dim cashbox As String = kasse.rksv_KassaGuid '"VERAG_GMBH_KASSE_01" "KASSA 001"

            Dim m_com As VERAG_PROG_ALLGEMEIN.RKSV_DE_DSFinVKService_2022.DSFinVKServerClient = New VERAG_PROG_ALLGEMEIN.RKSV_DE_DSFinVKService_2022.DSFinVKServerClient() 'PROBLEM??
            m_com.Endpoint.Address = New System.ServiceModel.EndpointAddress("http://ymgk028055.verag.ost.dmn:8733/DSFinVKService?wsdl")
            m_com.Open()
            '   svcRKSV.DBUserCredentials m_credentials = new svcRKSV.DBUserCredentials();
            'Dim credentials As New SDL.RKSVServer.DBUserCredentials

            'credentials.Database = "RKSVWcfDB"
            'credentials.Server = "AVISO\SQLEXPRESS"

            'credentials.Username = "Admin"
            'credentials.Password = "verag#2"
            'credentials.CashboxID = kasse.rksv_bez
            ''"VERAG-SUB-KASSE-ZOLL"
            'credentials.CompanyGUID = CompanyGUID ' "9119d9ae-f549-4a0f-a50f-0500ec7ca059"



            'Dim m_com As VERAG_PROG_ALLGEMEIN.RKSV_DE_DSFinVKService.DSFinVKServer = New VERAG_PROG_ALLGEMEIN.RKSV_DE_DSFinVKService.DSFinVKServer() 'PROBLEM??
            ' m_com.Url = "http://ymgk028055.verag.ost.dmn:8733/DSFinVKService"
            Dim [error] As VERAG_PROG_ALLGEMEIN.RKSV_DE_DSFinVKService.ErrorCode
            Dim InitializeLibraryResultSpecified As Boolean
            '     Dim [error] = "" 'm_com.InitializeLibrary(tbLicense.Text, "D:\Database\DSFinVK\dsfinvkdb.db3", "Administrator", "test", cashbox)
            [error] = m_com.InitializeLibrary("SQLGUIDE01.verag.ost.dmn", "itg_RKSV_DE", "dsfinvk", "dsfinvk#1337", cashbox) '[error], InitializeLibraryResultSpecified)

            ' MsgBox("1: " & [error])

            If [error] <> VERAG_PROG_ALLGEMEIN.DSFinVKService.ErrorCode.OK Then
                If [error].ToString() <> "CASHBOX_ALREADY_MANAGED" Then '--> CASHBOX_ALREADY_MANAGED --> der Fehler darf auftreten, die Cashbox wird Serverseitig initialisert, hier nur der Versuch, falls das nciht geschehen ist... lt. Jan Mika / AITG
                    MessageBox.Show([error].ToString(), "Error1", MessageBoxButtons.OK, MessageBoxIcon.[Error])
                    Return False
                End If
            End If

            'BelegNr wird von RKSV übernommen
            Dim BON_ID As Integer = 0
            If False Then

                Dim BON_IDSpecified = False
                Dim GetNextBON_IDResultSpecified = False
                [error] = m_com.GetNextBON_ID(cashbox, BON_ID)
                '  MsgBox("3: " & [error])

                If [error] <> VERAG_PROG_ALLGEMEIN.DSFinVKService.ErrorCode.OK Then
                    MessageBox.Show([error].ToString(), "Error2", MessageBoxButtons.OK, MessageBoxIcon.[Error])
                    Return False
                End If
            Else
                '  MsgBox(RKSV_Beleg_Id)
                BON_ID = RKSV_Beleg_Id
            End If


            'Dim BON_NR As Integer = 0
            '[error] = m_com.GetNextBON_NR(cashbox, BON_NR)

            'If [error] <> VERAG_PROG_ALLGEMEIN.DSFinVKService.ErrorCode.OK Then
            '    MessageBox.Show([error].ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.[Error])
            '    Return False
            'End If


            '  MsgBox("4")

            'Rechnung beginnen


            Dim stornoVz = -1


            Dim bonkopfBegin As VERAG_PROG_ALLGEMEIN.RKSV_DE_DSFinVKService_2022.BonKopfBegin = New VERAG_PROG_ALLGEMEIN.RKSV_DE_DSFinVKService_2022.BonKopfBegin
            ' Dim bonkopfBegin As VERAG_PROG_ALLGEMEIN.RKSV_DE_DSFinVKService.BonKopfBegin = New VERAG_PROG_ALLGEMEIN.RKSV_DE_DSFinVKService.BonKopfBegin()

            bonkopfBegin.Z_KASSE_ID = cashbox

            bonkopfBegin.BEDIENER_ID = VERAG_PROG_ALLGEMEIN.cAllgemein.USRID 'tbBEDIENER_ID.Text

            bonkopfBegin.BEDIENER_NAME = VERAG_PROG_ALLGEMEIN.cAllgemein.USRNAME 'tbBEDIENER_NAME.Text

            bonkopfBegin.BON_ID = BON_ID.ToString()
            bonkopfBegin.REF_BON_ID = If(OLD_RKSV_Beleg_Id, "").ToString

            bonkopfBegin.BON_NAME = "" 'tbBON_NAME.Text

            bonkopfBegin.BON_NOTIZ = "" 'tbBON_NOTIZ.Text

            bonkopfBegin.BON_NR = BON_ID

            bonkopfBegin.BON_STORNO = 1  'If(cbBON_STORNO.Checked, "1", "0")

            bonkopfBegin.BON_TYP = "Beleg" 'cmbBON_TYP.SelectedItem.ToString()

            bonkopfBegin.KUNDE_ID = If(BELEG.KundenNr > 0, BELEG.KundenNr, "") 'tbKUNDE_ID.Text

            bonkopfBegin.KUNDE_LAND = If(BELEG.LandKz, "") 'tbKUNDE_LAND.Text

            bonkopfBegin.KUNDE_NAME = If(BELEG.Frachtführer, "") 'tbKUNDE_NAME.Text

            bonkopfBegin.KUNDE_ORT = If(BELEG.Ort, "") 'tbKUNDE_ORT.Text

            bonkopfBegin.KUNDE_PLZ = If(BELEG.PLZ, "") 'tbKUNDE_PLZ.Text

            bonkopfBegin.KUNDE_STRASSE = If(BELEG.Straße, "") ' tbKUNDE_STRASSE.Text

            bonkopfBegin.KUNDE_TYP = "" ' tbKUNDE_TYP.Text

            bonkopfBegin.KUNDE_USTID = If(BELEG.UstIdKz, "") & If(BELEG.UstIdNr, "") ' tbKUNDE_USTID.Text

            bonkopfBegin.TERMINAL_ID = "" 'tbTERMINAL_ID.Text

            Dim transactionNumber As Integer = 0
            Dim transactionNumberSpecified As Boolean

            Dim BeginReceiptResultSpecified As Boolean
            [error] = m_com.BeginReceipt(cashbox, bonkopfBegin, transactionNumber)

            If [error] <> VERAG_PROG_ALLGEMEIN.DSFinVKService.ErrorCode.OK Then
                MessageBox.Show([error].ToString(), "Error3", MessageBoxButtons.OK, MessageBoxIcon.[Error])
                Return False
            End If

            '    MsgBox("5 ANZ: " & BELEG.POS.Count)
            Dim cntZeile = 1
            Dim GES_BRUTTO As Double = 0
            For Each POS In BELEG.POS

                'Bonposition hinzufügen
                Dim position As VERAG_PROG_ALLGEMEIN.RKSV_DE_DSFinVKService_2022.BonPosition = New VERAG_PROG_ALLGEMEIN.RKSV_DE_DSFinVKService_2022.BonPosition()

                position.AGENTUR_ID = -1 'Convert.ToInt32(dgvBonPos.Rows[m_dgvCurrentRow].Cells["AGENTUR_ID"].Value)

                position.ARTIKELTEXT = POS.LeistungsBez 'Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["ARTIKELTEXT"].Value)

                position.ART_NR = POS.LeistungsNr ' Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["ART_NR"].Value)

                position.BON_ID = Convert.ToString(BON_ID)

                position.EINHEIT = "Stk." ' Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["EINHEIT"].Value)

                position.FAKTOR = 1 ' Convert.ToDecimal(dgvBonPos.Rows[m_dgvCurrentRow].Cells["FAKTOR"].Value)

                position.GTIN = "" 'Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["GTIN"].Value)

                position.GUTSCHEIN_NR = "" 'Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["GUTSCHEIN_NR"].Value)

                position.GV_NAME = "" ' Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["GV_NAME"].Value)

                position.GV_TYP = "Umsatz" ' Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["GV_TYP"].Value)

                position.INHAUS = "" 'Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["INHAUS"].Value)

                position.MENGE = POS.Anzahl 'Convert.ToDecimal(dgvBonPos.Rows[m_dgvCurrentRow].Cells["MENGE"].Value)

                position.POS_TERMINAL_ID = "" 'Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["POS_TERMINAL_ID"].Value)

                position.POS_ZEILE = cntZeile 'Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["POS_ZEILE"].Value)

                position.P_STORNO = 0 'Hier kein Storno, das wäre nur wenn eine Pos storniert wird...

                position.STK_BR = POS.Preis 'Convert.ToDecimal(dgvBonPos.Rows[m_dgvCurrentRow].Cells["STK_BR"].Value)

                position.WARENGR = "" 'Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["WARENGR"].Value)

                position.WARENGR_ID = "" 'Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["WARENGR_ID"].Value)

                position.Z_KASSE_ID = cashbox 'Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["Z_KASSE_ID"].Value)

                ' Beträge der Position

                Dim position_vat = New VERAG_PROG_ALLGEMEIN.RKSV_DE_DSFinVKService_2022.BonPosition_Ust()

                position_vat.BON_ID = position.BON_ID

                position_vat.POS_ZEILE = position.POS_ZEILE

                Dim steuersatzID = 1
                Dim steuersatz As Double = SQL.getValueTxtBySql("SELECT [Steuersatz] FROM [tblSteuersätze] where nr='" & BELEG.Steuerschlüssel & "'", "FMZOLL")
                Select Case steuersatz
                    Case 0.19 : steuersatzID = 1
                    Case 0.07 : steuersatzID = 2
                    Case 0.00 : steuersatzID = 6
                End Select
                '  MsgBox(POS.Anzahl)
                '  MsgBox(POS.Betrag)

                position_vat.UST_SCHLUESSEL = steuersatzID 'm_com.GetTaxIds(cashbox,)   'Convert.ToInt32(dgvBonPos.Rows[m_dgvCurrentRow].Cells["UST_SCHLUESSEL"].Value)
                Dim steuerBetrag = POS.Betrag * position_vat.UST_SCHLUESSEL
                position_vat.POS_BRUTTO = POS.Betrag + steuerBetrag 'Convert.ToDecimal(dgvBonPos.Rows[m_dgvCurrentRow].Cells["POS_BRUTTO"].Value)

                position_vat.POS_NETTO = POS.Betrag 'Convert.ToDecimal(dgvBonPos.Rows[m_dgvCurrentRow].Cells["POS_NETTO"].Value)

                position_vat.POS_UST = steuerBetrag 'Convert.ToDecimal(dgvBonPos.Rows[m_dgvCurrentRow].Cells["POS_UST"].Value)

                position_vat.POS_BRUTTO *= stornoVz
                position_vat.POS_NETTO *= stornoVz
                position_vat.POS_UST *= stornoVz

                Dim AddPositionToReceiptResultSpecified As Boolean
                [error] = m_com.AddPositionToReceipt(cashbox, position, position_vat, transactionNumber)
                cntZeile += 1
                GES_BRUTTO += position_vat.POS_BRUTTO

            Next
            ' MsgBox("6: " & GES_BRUTTO)

            If [error] <> VERAG_PROG_ALLGEMEIN.DSFinVKService.ErrorCode.OK Then
                MessageBox.Show([error].ToString(), "Error4", MessageBoxButtons.OK, MessageBoxIcon.[Error])
                Return False
            End If

            'Rechnung abschließen

            Dim bonkopfFinish As VERAG_PROG_ALLGEMEIN.RKSV_DE_DSFinVKService_2022.BonKopfFinish = New VERAG_PROG_ALLGEMEIN.RKSV_DE_DSFinVKService_2022.BonKopfFinish()

            bonkopfFinish.Z_KASSE_ID = cashbox

            bonkopfFinish.BON_ID = BON_ID



            If Not Decimal.TryParse(GES_BRUTTO, bonkopfFinish.UMS_BRUTTO) Then
                bonkopfFinish.UMS_BRUTTO = 0.00
            End If


            bonkopfFinish.PROCESS_TYPE = "Kassenbeleg-V1"

            bonkopfFinish.payment_currencies = {"EUR"}

            bonkopfFinish.payment_types = {"Bar"}

            bonkopfFinish.payment_per_currency = {GES_BRUTTO} '{0.0} 'BETRAG"!!!!!!!!!!!!

            ' MsgBox("6,1: ")

            Dim FinishReceiptResult As Boolean = True
            Dim FinishReceiptResultSpecified As Boolean
            [error] = m_com.FinishReceipt(cashbox, bonkopfFinish, transactionNumber)
            '   MsgBox("6,2: ")

            If [error] <> VERAG_PROG_ALLGEMEIN.DSFinVKService.ErrorCode.OK Then
                MessageBox.Show([error].ToString(), "Error5", MessageBoxButtons.OK, MessageBoxIcon.[Error])
                Return False
            End If
            ' Kassenabschluss anlegen über alle noch nicht abgeschlossenen Rechnungen zu dieser Kasse

            ' Error = m_com.CreateCashpointClosing(cashbox)

            '            ' DSFinV-K-Export

            '            Int from = 0

            'Int to = 10

            'Dim ret = m_com.ExportCSVFiles(from, to, tbSelectedFolder.Text, tbZipName.Text, True, True,

            'true, true, true, true, true, true,

            'true, true, true, true,

            'true, true, true, true, true,

            'true, true, true);

            'If (ret == ErrorCode.OK) Then

            '{

            'MessageBox.Show("Die CSV Dateien wurden im Ordner " + tbSelectedFolder.Text + " angelegt und in die Zip-Datei " + tbZipName.Text + " gepackt.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);

            '}

            'Else

            '{

            'MessageBox.Show("Beim exportieren der CSV-Dateien ging etwas schief:\r\n" + ret.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

            '}
            ' MsgBox("7")

            Dim transactionNumberRet As String
            Dim serialNumber As String
            Dim signature As String
            Dim transactionStart As Date
            Dim transactionFinish As Date
            Dim sigCounter As String
            Dim transactionStartSpecified As Boolean
            Dim transactionFinishSpecified As Boolean
            Dim GetLastReceiptValuesResultSpecified As Boolean
            '
            [error] = m_com.GetLastReceiptValues(cashbox, transactionNumberRet, serialNumber, signature, transactionStart, transactionFinish, sigCounter)

            '   MsgBox("8")

            Dim qrCode As String = String.Empty
            Dim mimeType As String = String.Empty
            Dim GetLastReceiptQrCodeResult As Boolean
            Dim GetLastReceiptQrCodeResultSpecified As Boolean
            [error] = m_com.GetLastReceiptQrCode(cashbox, qrCode, mimeType)

            QR_CodeString = qrCode
            LastJWS = signature


            '  MsgBox("9")
            If QR_CodeString.Length > 50 And LastJWS.Length > 50 Then
                Return True
            End If
        Catch ex As Exception
            MsgBox("Es ist ein Fehler bei der Signatur aufgetreten (insertRKSV): " & vbNewLine & ex.Message & ex.StackTrace)
        End Try
        Return False
    End Function

    Shared Function stornoRKSV_DE(PERSONAL As cPersonal, BELEG As EABeleg, ByVal kasse As cRKSV_Kasse, ByVal RKSV_Beleg_Id As Integer, ByVal OLD_RKSV_Beleg_Id As Object, ByVal summeBRUTTO As Double, ByRef QR_CodeString As String, ByRef LastJWS As String, TEST As Boolean, ByRef answer As String) As Boolean
        Try

            ' MsgBox("0: ")
            Dim cashbox As String = kasse.rksv_KassaGuid '"VERAG_GMBH_KASSE_01" "KASSA 001"
            'Dim endpoint = New System.ServiceModel.EndpointAddress(getRKSVLink(kasse))
            '  Dim m_com As VERAG_PROG_ALLGEMEIN.DSFinVKService.DSFinVKServerClient = New VERAG_PROG_ALLGEMEIN.DSFinVKService.DSFinVKServerClient("DSFinVKService", endpoint) '"http://ymgk028055.verag.ost.dmn:8733/DSFinVKService")

            Dim m_com As VERAG_PROG_ALLGEMEIN.RKSV_DE_DSFinVKService.DSFinVKServer = New VERAG_PROG_ALLGEMEIN.RKSV_DE_DSFinVKService.DSFinVKServer() 'PROBLEM??
            m_com.Url = "http://ymgk028055.verag.ost.dmn:8733/DSFinVKService"
            Dim [error] As VERAG_PROG_ALLGEMEIN.RKSV_DE_DSFinVKService.ErrorCode
            Dim InitializeLibraryResultSpecified As Boolean
            '     Dim [error] = "" 'm_com.InitializeLibrary(tbLicense.Text, "D:\Database\DSFinVK\dsfinvkdb.db3", "Administrator", "test", cashbox)
            m_com.InitializeLibrary("SQLGUIDE01.verag.ost.dmn", "itg_RKSV_DE", "dsfinvk", "dsfinvk#1337", cashbox, [error], InitializeLibraryResultSpecified)

            '            Dim m_com As VERAG_PROG_ALLGEMEIN.RKSV_DE_DSFinVKService.DSFinVKServer = New VERAG_PROG_ALLGEMEIN.RKSV_DE_DSFinVKService.DSFinVKServer() 'PROBLEM??
            '  Dim m_com As VERAG_PROG_ALLGEMEIN.RKSV_DE_DSFinVKService_2022.DSFinVKServerClient = New VERAG_PROG_ALLGEMEIN.RKSV_DE_DSFinVKService_2022.DSFinVKServerClient() 'PROBLEM??

            ' m_com.Url = "http://ymgk028055.verag.ost.dmn:8733/DSFinVKService"
            'Dim [error] As VERAG_PROG_ALLGEMEIN.RKSV_DE_DSFinVKService.ErrorCode
            'Dim InitializeLibraryResultSpecified As Boolean
            '     Dim [error] = "" 'm_com.InitializeLibrary(tbLicense.Text, "D:\Database\DSFinVK\dsfinvkdb.db3", "Administrator", "test", cashbox)
            '  m_com.InitializeLibrary("SQLGUIDE01.verag.ost.dmn", "itg_RKSV_DE", "dsfinvk", "dsfinvk#1337", cashbox, [error], InitializeLibraryResultSpecified)

            ' MsgBox("1: " & [error])

            If [error] <> VERAG_PROG_ALLGEMEIN.DSFinVKService.ErrorCode.OK Then
                If [error].ToString() <> "CASHBOX_ALREADY_MANAGED" Then '--> CASHBOX_ALREADY_MANAGED --> der Fehler darf auftreten, die Cashbox wird Serverseitig initialisert, hier nur der Versuch, falls das nciht geschehen ist... lt. Jan Mika / AITG
                    MessageBox.Show([error].ToString(), "Error1", MessageBoxButtons.OK, MessageBoxIcon.[Error])
                    Return False
                End If
            End If

            ' MsgBox("2")
            Dim BON_ID As Integer = 0
            If False Then

                Dim BON_IDSpecified = False
                Dim GetNextBON_IDResultSpecified = False
                m_com.GetNextBON_ID(cashbox, BON_ID, BON_IDSpecified, [error], GetNextBON_IDResultSpecified)
                '  MsgBox("3: " & [error])

                If [error] <> VERAG_PROG_ALLGEMEIN.DSFinVKService.ErrorCode.OK Then
                    If [error].ToString() <> "CASHBOX_ALREADY_MANAGED" Then '--> CASHBOX_ALREADY_MANAGED --> der Fehler darf auftreten, die Cashbox wird Serverseitig initialisert, hier nur der Versuch, falls das nciht geschehen ist... lt. Jan Mika / AITG
                        MessageBox.Show([error].ToString(), "Error2", MessageBoxButtons.OK, MessageBoxIcon.[Error])
                        Return False
                    End If
                End If
            Else
                '  MsgBox(RKSV_Beleg_Id)
                BON_ID = RKSV_Beleg_Id
            End If

            'Dim BON_ID As Integer = 0
            'Dim BON_IDSpecified = False
            'Dim GetNextBON_IDResultSpecified = False
            'm_com.GetNextBON_ID(cashbox, BON_ID, BON_IDSpecified, [error], GetNextBON_IDResultSpecified)
            ''MsgBox("3: " & [error])

            'If [error] <> VERAG_PROG_ALLGEMEIN.DSFinVKService.ErrorCode.OK Then
            '    MessageBox.Show([error].ToString(), "Error2", MessageBoxButtons.OK, MessageBoxIcon.[Error])
            '    Return False
            'End If

            'Dim BON_NR As Integer = 0
            '[error] = m_com.GetNextBON_NR(cashbox, BON_NR)

            'If [error] <> VERAG_PROG_ALLGEMEIN.DSFinVKService.ErrorCode.OK Then
            '    MessageBox.Show([error].ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.[Error])
            '    Return False
            'End If


            '  MsgBox("4")

            'Rechnung beginnen


            Dim stornoVz = -1


            Dim bonkopfBegin As VERAG_PROG_ALLGEMEIN.RKSV_DE_DSFinVKService.BonKopfBegin = New VERAG_PROG_ALLGEMEIN.RKSV_DE_DSFinVKService.BonKopfBegin()

            bonkopfBegin.Z_KASSE_ID = cashbox

            bonkopfBegin.BEDIENER_ID = VERAG_PROG_ALLGEMEIN.cAllgemein.USRID 'tbBEDIENER_ID.Text

            bonkopfBegin.BEDIENER_NAME = VERAG_PROG_ALLGEMEIN.cAllgemein.USRNAME 'tbBEDIENER_NAME.Text

            bonkopfBegin.BON_ID = BON_ID.ToString()
            bonkopfBegin.REF_BON_ID = If(OLD_RKSV_Beleg_Id, "").ToString()

            bonkopfBegin.BON_NAME = "" 'tbBON_NAME.Text

            bonkopfBegin.BON_NOTIZ = "" 'tbBON_NOTIZ.Text

            bonkopfBegin.BON_NR = BON_ID

            bonkopfBegin.BON_STORNO = 1  'If(cbBON_STORNO.Checked, "1", "0")

            bonkopfBegin.BON_TYP = "Beleg" 'cmbBON_TYP.SelectedItem.ToString()

            bonkopfBegin.KUNDE_ID = If(BELEG.KundenNr > 0, BELEG.KundenNr, "") 'tbKUNDE_ID.Text

            bonkopfBegin.KUNDE_LAND = If(BELEG.LandKz, "") 'tbKUNDE_LAND.Text

            bonkopfBegin.KUNDE_NAME = If(BELEG.Frachtführer, "") 'tbKUNDE_NAME.Text

            bonkopfBegin.KUNDE_ORT = If(BELEG.Ort, "") 'tbKUNDE_ORT.Text

            bonkopfBegin.KUNDE_PLZ = If(BELEG.PLZ, "") 'tbKUNDE_PLZ.Text

            bonkopfBegin.KUNDE_STRASSE = If(BELEG.Straße, "") ' tbKUNDE_STRASSE.Text

            bonkopfBegin.KUNDE_TYP = "" ' tbKUNDE_TYP.Text

            bonkopfBegin.KUNDE_USTID = If(BELEG.UstIdKz, "") & If(BELEG.UstIdNr, "") ' tbKUNDE_USTID.Text

            bonkopfBegin.TERMINAL_ID = "" 'tbTERMINAL_ID.Text

            Dim transactionNumber As Integer = 0
            Dim transactionNumberSpecified As Boolean

            Dim BeginReceiptResultSpecified As Boolean
            m_com.BeginReceipt(cashbox, bonkopfBegin, transactionNumber, transactionNumberSpecified, [error], BeginReceiptResultSpecified)

            If [error] <> VERAG_PROG_ALLGEMEIN.DSFinVKService.ErrorCode.OK Then
                MessageBox.Show([error].ToString(), "Error3", MessageBoxButtons.OK, MessageBoxIcon.[Error])
                Return False
            End If

            '    MsgBox("5 ANZ: " & BELEG.POS.Count)
            Dim cntZeile = 1
            Dim GES_BRUTTO As Double = 0
            For Each POS In BELEG.POS

                'Bonposition hinzufügen
                Dim position As VERAG_PROG_ALLGEMEIN.RKSV_DE_DSFinVKService.BonPosition = New VERAG_PROG_ALLGEMEIN.RKSV_DE_DSFinVKService.BonPosition()

                position.AGENTUR_ID = -1 'Convert.ToInt32(dgvBonPos.Rows[m_dgvCurrentRow].Cells["AGENTUR_ID"].Value)

                position.ARTIKELTEXT = POS.LeistungsBez 'Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["ARTIKELTEXT"].Value)

                position.ART_NR = POS.LeistungsNr ' Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["ART_NR"].Value)

                position.BON_ID = Convert.ToString(BON_ID)

                position.EINHEIT = "Stk." ' Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["EINHEIT"].Value)

                position.FAKTOR = 1 ' Convert.ToDecimal(dgvBonPos.Rows[m_dgvCurrentRow].Cells["FAKTOR"].Value)

                position.GTIN = "" 'Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["GTIN"].Value)

                position.GUTSCHEIN_NR = "" 'Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["GUTSCHEIN_NR"].Value)

                position.GV_NAME = "" ' Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["GV_NAME"].Value)

                position.GV_TYP = "Umsatz" ' Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["GV_TYP"].Value)

                position.INHAUS = "" 'Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["INHAUS"].Value)

                position.MENGE = POS.Anzahl 'Convert.ToDecimal(dgvBonPos.Rows[m_dgvCurrentRow].Cells["MENGE"].Value)

                position.POS_TERMINAL_ID = "" 'Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["POS_TERMINAL_ID"].Value)

                position.POS_ZEILE = cntZeile 'Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["POS_ZEILE"].Value)

                position.P_STORNO = 0 'Hier kein Storno, das wäre nur wenn eine Pos storniert wird...

                position.STK_BR = POS.Preis 'Convert.ToDecimal(dgvBonPos.Rows[m_dgvCurrentRow].Cells["STK_BR"].Value)

                position.WARENGR = "" 'Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["WARENGR"].Value)

                position.WARENGR_ID = "" 'Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["WARENGR_ID"].Value)

                position.Z_KASSE_ID = cashbox 'Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["Z_KASSE_ID"].Value)

                ' Beträge der Position

                Dim position_vat = New VERAG_PROG_ALLGEMEIN.RKSV_DE_DSFinVKService.BonPosition_Ust()

                position_vat.BON_ID = position.BON_ID

                position_vat.POS_ZEILE = position.POS_ZEILE

                Dim steuersatzID = 1
                Dim steuersatz As Double = SQL.getValueTxtBySql("SELECT [Steuersatz] FROM [tblSteuersätze] where nr='" & BELEG.Steuerschlüssel & "'", "FMZOLL")
                Select Case steuersatz
                    Case 0.19 : steuersatzID = 1
                    Case 0.07 : steuersatzID = 2
                    Case 0.00 : steuersatzID = 6
                End Select
                '  MsgBox(POS.Anzahl)
                '  MsgBox(POS.Betrag)

                position_vat.UST_SCHLUESSEL = steuersatzID 'm_com.GetTaxIds(cashbox,)   'Convert.ToInt32(dgvBonPos.Rows[m_dgvCurrentRow].Cells["UST_SCHLUESSEL"].Value)
                Dim steuerBetrag = POS.Betrag * position_vat.UST_SCHLUESSEL
                position_vat.POS_BRUTTO = POS.Betrag + steuerBetrag 'Convert.ToDecimal(dgvBonPos.Rows[m_dgvCurrentRow].Cells["POS_BRUTTO"].Value)

                position_vat.POS_NETTO = POS.Betrag 'Convert.ToDecimal(dgvBonPos.Rows[m_dgvCurrentRow].Cells["POS_NETTO"].Value)

                position_vat.POS_UST = steuerBetrag 'Convert.ToDecimal(dgvBonPos.Rows[m_dgvCurrentRow].Cells["POS_UST"].Value)

                position_vat.POS_BRUTTO *= stornoVz
                position_vat.POS_NETTO *= stornoVz
                position_vat.POS_UST *= stornoVz

                Dim AddPositionToReceiptResultSpecified As Boolean
                m_com.AddPositionToReceipt(cashbox, position, position_vat, transactionNumber, transactionNumberSpecified, [error], AddPositionToReceiptResultSpecified)
                cntZeile += 1
                GES_BRUTTO += position_vat.POS_BRUTTO

            Next
            ' MsgBox("6: " & GES_BRUTTO)

            If [error] <> VERAG_PROG_ALLGEMEIN.DSFinVKService.ErrorCode.OK Then
                MessageBox.Show([error].ToString(), "Error4", MessageBoxButtons.OK, MessageBoxIcon.[Error])
                Return False
            End If

            'Rechnung abschließen

            Dim bonkopfFinish As VERAG_PROG_ALLGEMEIN.RKSV_DE_DSFinVKService.BonKopfFinish = New VERAG_PROG_ALLGEMEIN.RKSV_DE_DSFinVKService.BonKopfFinish()

            bonkopfFinish.Z_KASSE_ID = cashbox

            bonkopfFinish.BON_ID = BON_ID



            If Not Decimal.TryParse(GES_BRUTTO, bonkopfFinish.UMS_BRUTTO) Then
                bonkopfFinish.UMS_BRUTTO = 0.00
            End If


            bonkopfFinish.PROCESS_TYPE = "Kassenbeleg-V1"

            bonkopfFinish.payment_currencies = {"EUR"}

            bonkopfFinish.payment_types = {"Bar"}

            bonkopfFinish.payment_per_currency = {GES_BRUTTO} '{0.0} 'BETRAG"!!!!!!!!!!!!

            ' MsgBox("6,1: ")

            Dim FinishReceiptResult As Boolean = True
            Dim FinishReceiptResultSpecified As Boolean
            m_com.FinishReceipt(cashbox, bonkopfFinish, transactionNumber, FinishReceiptResult, [error], FinishReceiptResultSpecified)
            '   MsgBox("6,2: ")

            If [error] <> VERAG_PROG_ALLGEMEIN.DSFinVKService.ErrorCode.OK Then
                MessageBox.Show([error].ToString(), "Error5", MessageBoxButtons.OK, MessageBoxIcon.[Error])
                Return False
            End If
            ' Kassenabschluss anlegen über alle noch nicht abgeschlossenen Rechnungen zu dieser Kasse

            ' Error = m_com.CreateCashpointClosing(cashbox)

            '            ' DSFinV-K-Export

            '            Int from = 0

            'Int to = 10

            'Dim ret = m_com.ExportCSVFiles(from, to, tbSelectedFolder.Text, tbZipName.Text, True, True,

            'true, true, true, true, true, true,

            'true, true, true, true,

            'true, true, true, true, true,

            'true, true, true);

            'If (ret == ErrorCode.OK) Then

            '{

            'MessageBox.Show("Die CSV Dateien wurden im Ordner " + tbSelectedFolder.Text + " angelegt und in die Zip-Datei " + tbZipName.Text + " gepackt.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);

            '}

            'Else

            '{

            'MessageBox.Show("Beim exportieren der CSV-Dateien ging etwas schief:\r\n" + ret.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

            '}
            ' MsgBox("7")

            Dim transactionNumberRet As String
            Dim serialNumber As String
            Dim signature As String
            Dim transactionStart As Date
            Dim transactionFinish As Date
            Dim sigCounter As String
            Dim transactionStartSpecified As Boolean
            Dim transactionFinishSpecified As Boolean
            Dim GetLastReceiptValuesResultSpecified As Boolean
            '
            m_com.GetLastReceiptValues(cashbox, transactionNumberRet, serialNumber, signature, transactionStart, transactionStartSpecified, transactionFinish, transactionFinishSpecified, sigCounter, [error], GetLastReceiptValuesResultSpecified)

            '   MsgBox("8")

            Dim qrCode As String = String.Empty
            Dim mimeType As String = String.Empty
            Dim GetLastReceiptQrCodeResult As Boolean
            Dim GetLastReceiptQrCodeResultSpecified As Boolean
            m_com.GetLastReceiptQrCode(cashbox, qrCode, mimeType, GetLastReceiptQrCodeResult, GetLastReceiptQrCodeResultSpecified)

            QR_CodeString = qrCode
            LastJWS = signature


            '  MsgBox("9")
            If QR_CodeString.Length > 50 And LastJWS.Length > 50 Then
                Return True
            End If
        Catch ex As Exception
            MsgBox("Es ist ein Fehler bei der Signatur aufgetreten (insertRKSV): " & vbNewLine & ex.Message & ex.StackTrace)
        End Try
        Return False
    End Function

    Shared Function stornoRKSV(ByVal kasse As cRKSV_Kasse, ByVal belegDat As DateTime, ByVal steuerSchluessel As Integer, ByVal RKSV_Beleg_Id As Integer, ByVal summeBRUTTO As Double, ByRef QR_CodeString As String, ByRef LastJWS As String, ByRef answer As String) As Boolean
        Try

            If RKSV_Beleg_Id <= 0 Then
                MsgBox("Keine RKSV-Beleg-ID")
                Return False
            End If
            Dim client As RKSVWcfClient = New RKSVWcfClient()
            client.Endpoint.Address = New System.ServiceModel.EndpointAddress(getRKSVLink(kasse))
            client.Open()
            '   svcRKSV.DBUserCredentials m_credentials = new svcRKSV.DBUserCredentials();
            Dim credentials As New SDL.RKSVServer.DBUserCredentials

            credentials.Database = "RKSVWcfDB"
            credentials.Server = "AVISO\SQLEXPRESS"


            credentials.Username = "Admin"
            credentials.Password = "verag#2"
            'credentials.CashboxID = kasse '"VERAG-SUB-KASSE-ZOLL"
            'credentials.CompanyGUID = CompanyGUID ' "9119d9ae-f549-4a0f-a50f-0500ec7ca059"

            credentials.CashboxID = kasse.rksv_bez '"VERAG-SUB-KASSE-ZOLL"
            credentials.CompanyGUID = kasse.rksv_CompanyGUID ' "9119d9ae-f549-4a0f-a50f-0500ec7ca059"




            Dim jws As String = String.Empty
            Dim qr As String = String.Empty
            Dim ocra As String = String.Empty
            'Dim answer As String = String.Empty

            Dim Belegnummer = RKSV_Beleg_Id
            Dim BelegDatumUhrzeit = belegDat

            Dim steuersatz As Double = SQL.getValueTxtBySql("SELECT isnull(tblSteuersätze.Steuersatz,0) FROM tblSteuersätze WHERE tblSteuersätze.Nr='" & steuerSchluessel & "' ", "FMZOLL")



            Dim BetragSatzNormal = IIf(steuersatz = 0.2, summeBRUTTO, 0.0) 'summe
            Dim BetragSatzErm1 = IIf(steuersatz = 0.1, summeBRUTTO, 0.0)
            Dim BetragSatzErm2 = IIf(steuersatz = 0.13, summeBRUTTO, 0.0)
            Dim BetragSatzNull = IIf(steuersatz = 0.0, summeBRUTTO, 0.0)
            Dim BetragSatzBesonders = IIf(steuersatz = 0.19, summeBRUTTO, 0.0)
            Dim StandUmsatzzaehler = kasse.rksv_Umsatzzaehler 'KASSE.rksv_Umsatzzaehler


            ' Dim BetragSatzNormal = summe * -1
            '  Dim BetragSatzErm1 = IIf(steuersatz = 0.1, summe, 0.0) * -1
            ' Dim BetragSatzErm2 = IIf(steuersatz = 0.13, summe, 0.0) * -1
            ' Dim BetragSatzNull = IIf(steuersatz = 0.0, summe, 0.0) * -1
            ' Dim BetragSatzBesonders = IIf(steuersatz = 0.19, summe, 0.0) * -1
            ' Dim StandUmsatzzaehler = kasse.rksv_Umsatzzaehler

            ' Dim BetragSatzBesonders = 0
            ' Dim BetragSatzBesonders = 0
            ' Dim BetragSatzBesonders = 0
            'client.ExportJWS

            '  MsgBox(credentials.CashboxID & " credentials.CashboxID")
            '  MsgBox(credentials.CompanyGUID & " credentials.CompanyGUID")


            If (client.SignStornoReceipt(credentials, Belegnummer, BelegDatumUhrzeit, BetragSatzNormal, BetragSatzErm1, BetragSatzErm2, BetragSatzBesonders, BetragSatzNull, jws, qr, ocra, answer)) Then

                QR_CodeString = qr
                LastJWS = jws
            Else

                If (jws.Length > 50) Then

                    QR_CodeString = qr
                    '   Dim bmpBytes As Byte() = Convert.FromBase64String(qr)
                    '  Dim ms As New System.IO.MemoryStream(bmpBytes)
                    '  Dim bmp As Image = Image.FromStream(ms)
                    '  QR_Image = Image.FromStream(ms)
                    ' pbQrCode.Image = bmp
                    LastJWS = jws
                Else

                    Return False
                End If
            End If
            Return True

        Catch ex As Exception
            MsgBox("Es ist ein Fehler bei der Signatur aufgetreten (insertRKSV): " & vbNewLine & ex.Message & ex.StackTrace)
        End Try
        Return False
    End Function

    'Beleg storno und Kassenbuch Gegenbuchung
    Shared Function STORNO(BELEG As EABeleg, ByVal grund As String, Firma As String, Optional stornoGegenbuchen As Boolean = False) As EABeleg
        If (Not BELEG.gebuchtStorno) Or stornoGegenbuchen Then
            '   MsgBox("SELECT * FROM tblKassenbuch WHERE  [Mandant]='" & BELEG.Mandant & "' AND Niederlassung='" & BELEG.Niederlassung & "' AND Benutzer='" & BELEG.Benutzer & "' AND Geschäftsjahr='" & getGJ(BELEG.BelegDat) & "' AND BelegNr='" & BELEG.BelegNr & "'")
            'Dim dt As DataTable = SQL.loadDgvBySql("SELECT * FROM tblKassenbuch WHERE  [Mandant]='" & BELEG.Mandant & "' AND Niederlassung='" & BELEG.Niederlassung & "' AND Benutzer='" & BELEG.Benutzer & "' AND Geschäftsjahr='" & getGJ_FIRMA(BELEG.BelegDat, Firma) & "' AND BelegNr='" & BELEG.BelegNr & "'", "FMZOLL")
            Dim dt As DataTable = SQL.loadDgvBySql("SELECT * FROM tblKassenbuch WHERE  [Mandant]='" & BELEG.Mandant & "' AND Niederlassung='" & BELEG.Niederlassung & "' AND Benutzer='" & BELEG.Benutzer & "' AND Geschäftsjahr='" & getGJ_FIRMA(BELEG.BelegDat, Firma) & "' AND rksv_BelegId='" & BELEG.rksv_BelegId & "'", "FMZOLL")
            ' Dim GJ = New cGeschaeftsjahr(BELEG.Mandant, BELEG.Niederlassung, BELEG.Benutzer, getGJ(BELEG.BelegDat))
            If dt IsNot Nothing Then
                For Each r In dt.Rows
                    Dim KBEntry As New cKassenbuch("LOAD", BELEG.Mandant, BELEG.Niederlassung, BELEG.Benutzer, getGJ_FIRMA(BELEG.BelegDat, Firma), r("JournalNr"))
                    KBEntry.JournalNr = cRKSV.getNewJournalNr(BELEG, Firma) ' GJ.INCREASE_JOURNAL() 'Vergabe der Journalnummer'
                    KBEntry.BelegDat = BELEG.BelegDat
                    KBEntry.Buchungsdatum = Now.ToShortDateString
                    KBEntry.Soll = KBEntry.Soll * -1
                    KBEntry.Haben = KBEntry.Haben * -1
                    KBEntry.Steuerbetrag = KBEntry.Steuerbetrag * -1
                    KBEntry.INSERT()
                Next
            End If
            If Not stornoGegenbuchen Then
                BELEG.gebuchtStorno = True
                BELEG.storniert = True
                BELEG.Stornogrund = grund
                BELEG.SAVE()
            End If
        End If
        Return BELEG
    End Function

    'Beleg storno und Kassenbuch Gegenbuchung
    Shared Function STORNO_BELEG_ONLY(BELEG As EABeleg, ByVal grund As String) As EABeleg
        BELEG.gebuchtStorno = True
        BELEG.storniert = True
        BELEG.Stornogrund = grund
        BELEG.SAVE()
        Return BELEG
    End Function
    'Beleg storno und Kassenbuch Gegenbuchung
    Shared Function DELETE(BELEG As EABeleg, Firma As String) As Boolean
        Try
            Dim dt As DataTable = SQL.loadDgvBySql("DELETE FROM tblKassenbuch WHERE  [Mandant]='" & BELEG.Mandant & "' AND Niederlassung='" & BELEG.Niederlassung & "' AND Benutzer='" & BELEG.Benutzer & "' AND Geschäftsjahr='" & getGJ_FIRMA(BELEG.BelegDat, Firma) & "' AND BelegNr='" & BELEG.BelegNr & "'", "FMZOLL")
            Return BELEG.DELETE()
        Catch ex As Exception
            MsgBox(ex.Message)
            Return False
        End Try
        Return True
    End Function


    Shared Function STORNO_RUECKGAENGIG(BELEG As EABeleg, ByVal grund As String, Firma As String) As EABeleg
        If BELEG.gebuchtStorno Then
            Dim dt As DataTable = SQL.loadDgvBySql("SELECT * FROM tblKassenbuch WHERE  [Mandant]='" & BELEG.Mandant & "' AND Niederlassung='" & BELEG.Niederlassung & "' AND Benutzer='" & BELEG.Benutzer & "' AND Geschäftsjahr='" & getGJ_FIRMA(BELEG.BelegDat, Firma) & "' AND BelegNr='" & BELEG.BelegNr & "'", "FMZOLL")
            '  Dim GJ = New cGeschaeftsjahr(BELEG.Mandant, BELEG.Niederlassung, BELEG.Benutzer, getGJ(BELEG.BelegDat))
            If dt IsNot Nothing Then
                For Each r In dt.Rows
                    Dim KBEntry As New cKassenbuch("LOAD", BELEG.Mandant, BELEG.Niederlassung, BELEG.Benutzer, getGJ_FIRMA(BELEG.BelegDat, Firma), r("JournalNr"))
                    KBEntry.JournalNr = cRKSV.getNewJournalNr(BELEG, Firma) ' GJ.INCREASE_JOURNAL() 'Vergabe der Journalnummer'
                    KBEntry.BelegDat = BELEG.BelegDat
                    KBEntry.Buchungsdatum = Now.ToShortDateString
                    KBEntry.Soll = KBEntry.Soll * -1
                    KBEntry.Haben = KBEntry.Haben * -1
                    KBEntry.Steuerbetrag = KBEntry.Steuerbetrag * -1
                    KBEntry.INSERT()
                Next
            End If
            BELEG.gebuchtStorno = False
            BELEG.storniert = False
            BELEG.Stornogrund = ""
            BELEG.SAVE()
        End If
        Return BELEG
    End Function

    Shared Function getGJ_FIRMA(BelegDat As Date, FIRMA As String) As Integer
        If FIRMA = "" Then FIRMA = VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA
        Select Case FIRMA
            Case "VERAG", "ATILLA"
                Return IIf(BelegDat.Month = 1, BelegDat.Year - 1, BelegDat.Year)
            Case Else
                Return BelegDat.Year
        End Select

    End Function

    Shared Function getGJ(BelegDat As Date, FIRMA_ID As Integer) As Integer
        'If FIRMA = "" Then FIRMA = VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA
        Select Case FIRMA_ID
            Case -1, 1, 3, 11, 7, 15 'Abweichendes WJ
                Return IIf(BelegDat.Month = 1, BelegDat.Year - 1, BelegDat.Year)
            Case Else
                Return BelegDat.Year
        End Select
    End Function
    'Shared Function getGJ(BelegDat As Date, FIRMAId As String) As Integer

    '    If FIRMA = "" Then FIRMA = New VERAG_PROG_ALLGEMEIN.cFirmen()
    '    Select Case FIRMA
    '        Case "IMEX", "FRONTOFFICE", "UNISPED", "AMBAR"
    '            Return BelegDat.Year
    '        Case Else
    '            Return IIf(BelegDat.Month = 1, BelegDat.Year - 1, BelegDat.Year)
    '    End Select

    'End Function

    'Shared Function getGJ_ByRksvId(BelegDat As Date, RksvId As Integer) As Integer
    '    Select Case RksvId
    '        Case 1
    '            Return getGJ(BelegDat, "VERAG")
    '        Case Else
    '            Return IIf(BelegDat.Month = 1, BelegDat.Year - 1, BelegDat.Year)
    '    End Select

    'End Function


    Shared Function getGJ_EndOfYear(GeschaerftsJahr As Integer, Optional FIRMA As String = "") As Date
        If FIRMA = "" Then FIRMA = VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA
        Select Case FIRMA
            Case "VERAG", "ATILLA"
                Return CDate("31.01." & (GeschaerftsJahr + 1))
            Case Else
                Return CDate("31.12." & GeschaerftsJahr)
        End Select
    End Function

    Shared Function getGJ_BeginOfYear(GeschaerftsJahr As Integer, Optional FIRMA As String = "") As Date
        If FIRMA = "" Then FIRMA = VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA
        Select Case FIRMA
            Case "VERAG", "ATILLA"
                Return CDate("01.02." & GeschaerftsJahr)
            Case Else
                Return CDate("01.01." & GeschaerftsJahr)
        End Select
    End Function

    Public Shared Function isforbiddenDate() As Boolean
        Dim lastDayofMonth = CDate("01." & Now.AddMonths(1).Month & "." & Now.AddMonths(1).Year).AddDays(-1)
        Dim nowdate As Date = CDate("31.01.2018") 'Now
        'wenn letzter Tag im Monat...
        If nowdate.ToShortDateString = lastDayofMonth.ToShortDateString Then
            Dim zp As Date = CDate(Now.ToShortDateString & " 23:54:50")
            '... und kurz vor Mitternacht:
            If Now > zp Then
                Return True
            End If
        End If
        Return False
    End Function

    'cboPrinter.SelectedItem.ToString
    Public Shared Function printKundenBeleg(BELEG As EABeleg, KASSE As cRKSV_Kasse, PERSONAL As cPersonal, printername As String, showDok As Boolean) As Boolean

        'Dim print As New frmPrintLayout

        Dim rpt As New rptKundenBeleg
        rpt.lblRgNr.Text = BELEG.rksv_BelegId '"12345 / TR"
        rpt.lblRgDatum.Text = BELEG.BelegDat.ToString("dd.MM.yyyy") ' HH:mm")
        ' rpt.lblKdNr.Text = IIf(BELEG.KundenNr > 0, BELEG.KundenNr, "")
        rpt.lblFirma.Text = BELEG.Ordnungsbegriff

        Dim adr1 = BELEG.Straße
        Dim adr2 = (BELEG.LandKz & " " & BELEG.PLZ & " " & BELEG.Ort).Trim
        If adr1.Trim <> "" Then rpt.lblFirma.Text &= vbNewLine & adr1
        If adr2.Trim <> "" Then rpt.lblFirma.Text &= vbNewLine & adr2

        Dim uidkdnr = (BELEG.UstIdKz & " " & BELEG.UstIdNr).Trim
        If uidkdnr <> "" Then uidkdnr &= vbNewLine
        uidkdnr &= IIf(BELEG.KundenNr > 0, BELEG.KundenNr, "")
        rpt.lblUID.Text = uidkdnr

        rpt.lblFahrer.Text = BELEG.Fahrer
        rpt.lblLKWKz.Text = BELEG.LKW_Kennzeichen
        If BELEG.LKW_Kennzeichen = "" Then rpt.lblKennzeichenUeberschrift.Text = "" ' = False
        rpt.txtPassnummer.Text = BELEG.Passnummer
        If BELEG.Passnummer = "" Then rpt.TextBox1.Text = "" ' = False

        If BELEG.Fahrer = "" Then rpt.lblFahrerUeberschrift.Text = "" '= False
        rpt.lblTextSteuern.Text = SQL.getValueTxtBySql("SELECT TOP 1 isnull(Beschreibung,'< keine Steuerberechnung >')  FROM [tblSteuersätze] WHERE Nr='" & BELEG.Steuerschlüssel & "'", "FMZOLL")
        Dim steuersatz = SQL.getValueTxtBySql("SELECT isnull(tblSteuersätze.Steuersatz,0) FROM tblSteuersätze WHERE tblSteuersätze.Nr='" & BELEG.Steuerschlüssel & "' ", "FMZOLL")

        rpt.lblSachbearbeiter.Text = PERSONAL.Name
        rpt.lblKbNr.Text = "( " & PERSONAL.KassenbuchNr & " )"
        rpt.Label25.Visible = (BELEG.DruckDatumUhrzeit IsNot Nothing) 'KOPIE

        rpt.lblBetragSum.Text = ""
        rpt.lblGesamtbetrag.Text = ""
        rpt.lblBetragSteuern.Text = ""

        rpt.lblPosNr.Text = ""
        If If(BELEG.LKW_Beleg, True) Then
            If BELEG.FilialenNr > 0 And BELEG.AbfertigungsNr > 0 Then
                rpt.lblPosNr.Text = BELEG.FilialenNr & " / " & BELEG.AbfertigungsNr
            End If
        Else
            'alle betroffenen AbfNr:
            For Each b In BELEG.POS
                If b.FilialenNr > 0 And b.AbfertigungsNr > 0 Then
                    If Not rpt.lblPosNr.Text.Contains(b.FilialenNr & "/" & b.AbfertigungsNr) Then
                        rpt.lblPosNr.Text &= b.FilialenNr & "/" & b.AbfertigungsNr & vbNewLine
                    End If
                End If
            Next
        End If
        rpt.lblPosNr.Text = rpt.lblPosNr.Text.Trim
        If rpt.lblPosNr.Text = "" Then rpt.lblPosNr.Visible = False : rpt.Label26.Visible = False


        If If(BELEG.LKW_Id, 0) > 0 Then
            rpt.txtLKWId.Text = BELEG.LKW_Id
        Else
            rpt.txtLKWId.Visible = False : rpt.Label1.Visible = False
        End If


        If BELEG.storniert Then
            rpt.Label25.Text = "**** STORNO ****"
            rpt.Label25.Visible = True
            rpt.lblStorno.Visible = True
            rpt.lblStorno.Text = "STORNORECHNUNG" & vbNewLine & BELEG.Stornogrund
        End If


        Select Case KASSE.rksv_bez
            Case "VERAG-SUB-KASSE-ZOLL"
                'Default Werte:
                'rpt.picVERAG.Image = My.Resources.Verag_AG_Logo2 'Standart
                rpt.lblFirma_Name.Text = "VERAG Spedition AG"
                rpt.lblFirma_Details.Text = "A 4975 Suben  |  Suben 100" & vbNewLine & "UID: ATU53187000 "
            Case "VERAG-CUSTOMSSERVICE-KASSE-ZOLL"
                'Default Werte:
                rpt.picVERAG.Image = My.Resources.Verag_Customs_Service_GMBH_Logo_med
                rpt.lblFirma_Name.Text = "VERAG Customs Service GmbH"
                rpt.lblFirma_Details.Text = "A 4975 Suben  |  Suben 14" & vbNewLine & "UID: ATU68374109 "
            Case "ATILLA-SUB-KASSE-ZOLL"
                'Default Werte:
                rpt.picVERAG.Image = My.Resources.Atilla_big_med
                rpt.lblFirma_Name.Text = "ATILLA Spedition GmbH"
                rpt.lblFirma_Details.Text = "A 4975 Suben  |  Suben 15" & vbNewLine & "UID: ATU63158647 "
            Case "VERAG-GMBH-KASSE-ZOLL"
                'Default Werte:
                rpt.picVERAG.Image = My.Resources.Verag_Spedition_GMBH_Logo_med
                rpt.lblFirma_Name.Text = "VERAG Spedition GmbH"
                rpt.lblFirma_Details.Text = "D 94152 Neuhaus am Inn  |  Hartham 6" & vbNewLine & "UID: DE813570890 "
                Select Case PERSONAL.Niederlassung
                    Case "SBG"
                        rpt.lblFirma_Details.Text &= vbNewLine & "Niederlassung: Bad Reichenhall"
                    Case "WAI"
                        rpt.lblFirma_Details.Text &= vbNewLine & "Niederlassung: Waidhaus"
                End Select
            Case "KASSE-VERWALTUNG"
                'Default Werte:
                '    rpt.picVERAG.Image = My.Resources.Verag_AG_Logo2
                rpt.lblFirma_Name.Text = "KASSE VERWALTUNG"
                rpt.lblFirma_Details.Text = " *** nur intern ***"
            Case "IMEX-KASSE-VERWALTUNG"
                rpt.lblFirma_Name.Text = "KASSE VERWALTUNG"
                rpt.lblFirma_Details.Text = " *** nur intern ***"
                rpt.picVERAG.Image = My.Resources.IMEX_LOGO_simple
                rpt.lblFirma_Name.Text = "IMEX Customs Service GmbH"
                rpt.lblFirma_Details.Text = "A 4975 Suben  |  Suben 15" & vbNewLine & "UID: ATU68490714 "
            Case "TEST-KASSE"
                'Default Werte:
                '    rpt.picVERAG.Image = My.Resources.Verag_AG_Logo2
                If VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "IMEX" Then rpt.picVERAG.Image = My.Resources.IMEX_LOGO_simple
                If VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "ATILLA" Then rpt.picVERAG.Image = My.Resources.Atilla_big_med

                rpt.lblFirma_Name.Text = "TEST-KASSE"
                rpt.lblFirma_Details.Text = " *** nur intern ***"
            Case "IMEX-KASSE-SUB"
                'Default Werte:
                rpt.picVERAG.Image = My.Resources.IMEX_LOGO_simple
                rpt.lblFirma_Name.Text = "IMEX Customs Service GmbH"
                rpt.lblFirma_Details.Text = "A 4975 Suben  |  Suben 15" & vbNewLine & "UID: ATU68490714 "
            Case "FRONT-OFFICE-SUB-KASSE"
                'Default Werte:
                rpt.picVERAG.Image = My.Resources.FrontOfficeSUB
                rpt.lblFirma_Name.Text = "Front-Office Suben eG"
                rpt.lblFirma_Details.Text = "A 4975 Suben  |  Suben 14" & vbNewLine & "UID: ATU74813856 "
        End Select

        If KASSE.rksv_aktiv Or KASSE.rksvDE_aktiv Then
            If BELEG.rksv_qr Is Nothing OrElse BELEG.rksv_qr = "" Then
                If KASSE.rksv_KassaGuid <> "KASSE_01" Then
                    MsgBox("Fehler: QR-Code wurde nicht richtig erstellt!")
                End If
            Else
                Dim bmpBytes As Byte() = Convert.FromBase64String(BELEG.rksv_qr)
                Dim MS As New System.IO.MemoryStream(bmpBytes)
                Dim QR_Image = Image.FromStream(MS)
                rpt.QR.Image = QR_Image
            End If

        End If
        '     rpt.DataSource = cProgramFunctions.dgridViewTods(dgvBelegPos)

        Dim dt As New DataTable
        dt.Columns.Add("clmnAnzahl", GetType(String))
        dt.Columns.Add("clmnBeschreibung", GetType(String))
        dt.Columns.Add("clmnBetrag", GetType(String))
        dt.Columns.Add("clmnPreis", GetType(String))

        For Each p In BELEG.POS
            ' dt.Rows.Add(p.Anzahl, p.Leistungsbeschreibung, p.Betrag, p.Preis)
            If BELEG.Belegart = 1 Then
                dt.Rows.Add(p.Anzahl, p.LeistungsBez, p.Betrag, p.Preis)
            Else
                dt.Rows.Add(p.Anzahl, p.LeistungsBez, p.Betrag * -1, p.Preis * -1)
            End If
        Next

        rpt.DataSource = dt 'cProgramFunctions.dgridViewTods(dgvBelegPos)
        Dim sum As Double = 0
        'Dim cnt As Integer = 0
        AddHandler rpt.Detail.Format, Sub()
                                          rpt.lblLeistungsNr.Text = rpt.Fields.Item("clmnAnzahl").Value()
                                          rpt.lblLeistun.Text = rpt.Fields.Item("clmnBeschreibung").Value()
                                          rpt.lblBetrag.Text = CDbl(rpt.Fields.Item("clmnBetrag").Value()).ToString("C")
                                          rpt.lblEinzelpreis.Text = CDbl(rpt.Fields.Item("clmnPreis").Value()).ToString("C")
                                          sum += rpt.Fields.Item("clmnBetrag").Value()
                                      End Sub
        AddHandler rpt.ReportFooter1.Format, Sub()
                                                 rpt.lblBetragSum.Text = CDbl(sum).ToString("C")
                                                 Dim s As Double = IIf(IsNumeric(steuersatz), steuersatz, 0)
                                                 rpt.lblBetragSteuern.Text = CDbl(sum * s).ToString("C")
                                                 rpt.lblGesamtbetrag.Text = CDbl(sum + (sum * s)).ToString("C")
                                                 If sum < 0 Then rpt.Label2.Text = "Rechnungskorrektur Nr."
                                             End Sub

        'PaperKind = System.Drawing.Printing.PaperKind.Custom
        ' Me.PageSettings.PaperKind = System.Drawing.Printing.PaperKind.Custom
        If showDok Then ' Wird angezeigt, nicht gedruckt
            Dim print As New GrapeCity.ActiveReports.Viewer.Win.Viewer
            print.Text = "Beleg"
            Dim printForm As New frmPrintLayout
            AddHandler print.LoadCompleted, Sub()
                                                If BELEG.DruckDatumUhrzeit Is Nothing Then
                                                    BELEG.DruckDatumUhrzeit = Now
                                                    BELEG.SAVE()
                                                End If
                                            End Sub
            printForm.Viewer.LoadDocument(rpt)

            printForm.Viewer.ViewType = GrapeCity.Viewer.Common.Model.ViewType.Continuous
            printForm.Show()
            printForm.BringToFront()
        Else
            ' print.ViewType = GrapeCity.Viewer.Common.Model.ViewType.Continuous
            '   print.LoadDocument(rpt)


            If printername <> "" Then
                rpt.Document.Printer.PrinterName = printername
            Else
                Dim p As New PrintDialog
                If p.ShowDialog() = DialogResult.OK Then
                    printername = p.PrinterSettings.PrinterName
                Else
                    rpt.Dispose()
                End If
            End If

            rpt.Run(False)
            rpt.Document.Printer.PrinterSettings.Copies = 1

            If Not rpt.Document.Print(False, False) Then
                MsgBox("Problem beim Drucken.")
            End If
            If BELEG.DruckDatumUhrzeit Is Nothing Then
                BELEG.DruckDatumUhrzeit = Now
                BELEG.SAVE()
            End If
            rpt.Dispose()

        End If

        Return True
        '   Me.Cursor = Cursors.Default
    End Function


    Public Shared Function printKundenBelegLG(BELEG As EABeleg, KASSE As cRKSV_Kasse, PERSONAL As cPersonal, printername As String, Art As String) As Boolean

        'Dim print As New frmPrintLayout
        Dim print As New GrapeCity.ActiveReports.Viewer.Win.Viewer
        print.Text = "Beleg"
        Dim rpt As New rptLeihgeldBeleg
        rpt.lblRgNr.Text = BELEG.rksv_BelegId '"12345 / TR"
        rpt.lblRgDatum.Text = BELEG.BelegDat.ToString("dd.MM.yyyy") ' HH:mm")
        ' rpt.lblKdNr.Text = IIf(BELEG.KundenNr > 0, BELEG.KundenNr, "")
        rpt.lblFrachtf.Text = BELEG.Ordnungsbegriff


        Dim firenname = (If(BELEG.Name1, "") & If(BELEG.Name2, "")).Trim

        Dim adr1 = BELEG.Straße
        Dim adr2 = (BELEG.LandKz & " " & BELEG.PLZ & " " & BELEG.Ort).Trim
        If adr1.Trim <> "" Then rpt.lblFrachtf.Text &= vbNewLine & adr1
        If adr2.Trim <> "" Then rpt.lblFrachtf.Text &= vbNewLine & adr2

        rpt.lblFirma.Text = If(BELEG.KundenNr > 0, BELEG.KundenNr & " - ", "") & If(firenname <> "", firenname, BELEG.Ordnungsbegriff) & If(adr1 <> "", vbNewLine & adr1, "") & If(adr2 <> "", vbNewLine & adr2, "")
        rpt.txtFrachtfuhrer.Text = If(BELEG.FrachtführerKundenNr > 0, BELEG.FrachtführerKundenNr & " - ", "") & BELEG.Frachtführer

        rpt.lblUID.Text = (BELEG.UstIdKz & " " & BELEG.UstIdNr).Trim
        ' rpt.lblKdNr.Text = IIf(BELEG.KundenNr > 0, BELEG.KundenNr, "")
        rpt.Label24.Text = "Auszahlungsbetrag"

        rpt.lblFahrer.Text = BELEG.Fahrer
        rpt.lblFahrer2.Text = BELEG.Fahrer
        rpt.lblLKWKz.Text = BELEG.LKW_Kennzeichen
        rpt.lblPassnummer.Text = BELEG.Passnummer
        '  If BELEG.LKW_Kennzeichen = "" Then rpt.lblKennzeichenUeberschrift.Text = "" ' = False
        '  If BELEG.Fahrer = "" Then rpt.lblFahrerUeberschrift.Text = "" '= False
        rpt.lblTextSteuern.Text = SQL.getValueTxtBySql("SELECT TOP 1 isnull(Beschreibung,'< keine Steuerberechnung >')  FROM [tblSteuersätze] WHERE Nr='" & BELEG.Steuerschlüssel & "'", "FMZOLL")
        Dim steuersatz = SQL.getValueTxtBySql("SELECT isnull(tblSteuersätze.Steuersatz,0) FROM tblSteuersätze WHERE tblSteuersätze.Nr='" & BELEG.Steuerschlüssel & "' ", "FMZOLL")

        rpt.lblSachbearbeiter.Text = PERSONAL.Name
        rpt.lblSachbearbeiter2.Text = PERSONAL.Name
        rpt.lblKbNr.Text = "( " & PERSONAL.KassenbuchNr & " )"
        rpt.Label25.Visible = (BELEG.DruckDatumUhrzeit IsNot Nothing) 'KOPIE

        rpt.lblBetragSum.Text = ""
        rpt.lblGesamtbetrag.Text = ""
        rpt.lblBetragSteuern.Text = ""
        rpt.lblPosNr.Text = IIf(BELEG.FilialenNr > 0, BELEG.FilialenNr & " / ", "") & BELEG.AbfertigungsNr

        If BELEG.storniert Then
            rpt.Label25.Text = "**** STORNO ****"
            rpt.Label25.Visible = True
            rpt.lblStorno.Visible = True
            rpt.lblStorno.Text = "STORNORECHNUNG" & vbNewLine & BELEG.Stornogrund

        End If

        If Art = "LG" Then
        ElseIf Art = "A" Then

        End If

        If KASSE IsNot Nothing Then
            Select Case KASSE.rksv_bez
                Case "VERAG-SUB-KASSE-ZOLL"
                    'Default Werte:
                    'rpt.picVERAG.Image = My.Resources.Verag_AG_Logo2 'Standart
                    rpt.lblFirma_Name.Text = "VERAG Spedition AG"
                    rpt.lblFirma_Details.Text = "A 4975 Suben  |  Suben 100" & vbNewLine & "UID: ATU53187000 "
                Case "VERAG-CUSTOMSSERVICE-KASSE-ZOLL"
                    'Default Werte:
                    rpt.picVERAG.Image = My.Resources.Verag_Customs_Service_GMBH_Logo_med
                    rpt.lblFirma_Name.Text = "VERAG Customs Service GmbH"
                    rpt.lblFirma_Details.Text = "A 4975 Suben  |  Suben 14" & vbNewLine & "UID: ATU68374109 "
                    rpt.Label1.Text = "Wir bestätigen, den o.g. Betrag von der Firma VERAG Customs Service GmbH erhalten zu haben."
                Case "ATILLA-SUB-KASSE-ZOLL"
                    'Default Werte:
                    rpt.picVERAG.Image = My.Resources.Atilla_big_med
                    rpt.lblFirma_Name.Text = "ATILLA Spedition GmbH"
                    rpt.lblFirma_Details.Text = "A 4975 Suben  |  Suben 15" & vbNewLine & "UID: ATU63158647 "
                    rpt.Label1.Text = "Wir bestätigen, den o.g. Betrag von der Firma ATILLA Spedition GmbH erhalten zu haben."
                Case "VERAG-GMBH-KASSE-ZOLL"
                    'Default Werte:
                    rpt.picVERAG.Image = My.Resources.Verag_Spedition_GMBH_Logo_med
                    rpt.lblFirma_Name.Text = "VERAG Spedition GmbH"
                    rpt.lblFirma_Details.Text = "D 94152 Neuhaus am Inn  |  Hartham 6" & vbNewLine & "UID: DE813570890 "
                Case "KASSE-VERWALTUNG"
                    'Default Werte:
                    '    rpt.picVERAG.Image = My.Resources.Verag_AG_Logo2
                    rpt.lblFirma_Name.Text = "KASSE VERWALTUNG"
                    rpt.lblFirma_Details.Text = " *** nur intern ***"
                Case "IMEX-KASSE-VERWALTUNG"
                    rpt.lblFirma_Name.Text = "KASSE VERWALTUNG"
                    rpt.lblFirma_Details.Text = " *** nur intern ***"
                    rpt.picVERAG.Image = My.Resources.IMEX_LOGO_simple
                    rpt.lblFirma_Name.Text = "IMEX Customs Service GmbH"
                    rpt.lblFirma_Details.Text = "A 4975 Suben  |  Suben 15" & vbNewLine & "UID: ATU68490714 "
                Case "TEST-KASSE"
                    'Default Werte:
                    rpt.lblFirma_Name.Text = "TEST-KASSE"
                    rpt.lblFirma_Details.Text = " *** nur intern ***"

                    Select Case VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA
                        Case "IMEX"
                            rpt.picVERAG.Image = My.Resources.IMEX_LOGO_simple
                            rpt.Label1.Text = "Wir bestätigen, den o.g. Betrag von der Firma IMEX Customs Service GmbH erhalten zu haben."
                        Case "ATILLA"
                            rpt.picVERAG.Image = My.Resources.Atilla_big_med
                            rpt.Label1.Text = "Wir bestätigen, den o.g. Betrag von der Firma ATILLA Spedition GmbH erhalten zu haben."
                    End Select

                Case "IMEX-KASSE-SUB"
                    'Default Werte:
                    rpt.picVERAG.Image = My.Resources.IMEX_LOGO_simple
                    rpt.lblFirma_Name.Text = "IMEX Customs Service GmbH"
                    rpt.lblFirma_Details.Text = "A 4975 Suben  |  Suben 15" & vbNewLine & "UID: ATU68490714 "
                    rpt.Label1.Text = "Wir bestätigen, den o.g. Betrag von der Firma IMEX Customs Service GmbH erhalten zu haben."
                Case "FRONT-OFFICE-SUB-KASSE"
                    'Default Werte:
                    rpt.picVERAG.Image = My.Resources.FrontOfficeSUB
                    rpt.lblFirma_Name.Text = "Front-Office Suben eG"
                    rpt.lblFirma_Details.Text = "A 4975 Suben  |  Suben 14" & vbNewLine & "UID: ATU74813856 "
                    rpt.Label1.Text = "Wir bestätigen, den o.g. Betrag von der Firma Front-Office Suben eG erhalten zu haben."
            End Select


            If KASSE.rksv_aktiv Or KASSE.rksvDE_aktiv Then

                If BELEG.rksv_qr Is Nothing OrElse BELEG.rksv_qr = "" Then
                    If KASSE.rksv_KassaGuid <> "KASSE_01" Then
                        MsgBox("Fehler: QR-Code wurde nicht richtig erstellt!")
                    End If
                Else
                    Dim bmpBytes As Byte() = Convert.FromBase64String(BELEG.rksv_qr)
                    Dim MS As New System.IO.MemoryStream(bmpBytes)
                    Dim QR_Image = Image.FromStream(MS)
                    rpt.QR.Image = QR_Image
                End If

            End If
        End If
        '     rpt.DataSource = cProgramFunctions.dgridViewTods(dgvBelegPos)

        Dim dt As New DataTable
        dt.Columns.Add("clmnAnzahl", GetType(String))
        dt.Columns.Add("clmnBeschreibung", GetType(String))
        dt.Columns.Add("clmnBetrag", GetType(String))
        dt.Columns.Add("clmnPreis", GetType(String))

        For Each p In BELEG.POS
            dt.Rows.Add(p.Anzahl, p.Leistungsbeschreibung, p.Betrag, p.Preis)
        Next

        rpt.DataSource = dt 'cProgramFunctions.dgridViewTods(dgvBelegPos)
        Dim sum As Double = 0
        'Dim cnt As Integer = 0
        AddHandler rpt.Detail.Format, Sub()
                                          rpt.lblLeistungsNr.Text = rpt.Fields.Item("clmnAnzahl").Value()
                                          rpt.lblLeistun.Text = rpt.Fields.Item("clmnBeschreibung").Value()
                                          rpt.lblBetrag.Text = CDbl(rpt.Fields.Item("clmnBetrag").Value()).ToString("C")
                                          rpt.lblEinzelpreis.Text = CDbl(rpt.Fields.Item("clmnPreis").Value()).ToString("C")
                                          sum += rpt.Fields.Item("clmnBetrag").Value()
                                      End Sub
        AddHandler rpt.ReportFooter1.Format, Sub()
                                                 rpt.lblBetragSum.Text = CDbl(sum).ToString("C")
                                                 Dim s As Double = IIf(IsNumeric(steuersatz), steuersatz, 0)
                                                 rpt.lblBetragSteuern.Text = CDbl(sum * s).ToString("C")
                                                 rpt.lblGesamtbetrag.Text = CDbl(sum + (sum * s)).ToString("C")

                                             End Sub

        rpt.Run(False)

        If printername <> "" Then
            rpt.Document.Printer.PrinterName = printername
        Else
            Dim p As New PrintDialog
            If p.ShowDialog() = DialogResult.OK Then
                printername = p.PrinterSettings.PrinterName
            Else
                rpt.Dispose()
            End If
        End If

        If Not rpt.Document.Print(False, False) Then
            MsgBox("Problem beim Drucken.")
        End If
        If BELEG.DruckDatumUhrzeit Is Nothing Then
            BELEG.DruckDatumUhrzeit = Now
            BELEG.SAVE()
        End If
        rpt.Dispose()

        If False Then

            AddHandler print.LoadCompleted, Sub()
                                                '  MsgBox("b" & printername)
                                                ' MsgBox(cboPrinter.SelectedItem.ToString)
                                                ' If cboPrinter.SelectedItem.ToString <> "" Then print.Document.Printer.PrinterName = cboPrinter.SelectedItem.ToString
                                                If printername <> "" Then
                                                    print.Document.Printer.PrinterName = printername
                                                Else
                                                    Dim p As New PrintDialog
                                                    If p.ShowDialog() = DialogResult.OK Then
                                                        printername = p.PrinterSettings.PrinterName
                                                    Else
                                                        print.Dispose()
                                                        Exit Sub
                                                    End If
                                                End If
                                                If printername = "" Then print.Dispose() : Exit Sub
                                                print.Document.Printer.PrinterName = printername
                                                If Not print.Print(False, False) Then
                                                    MsgBox("Problem beim Drucken.")
                                                End If
                                                If BELEG.DruckDatumUhrzeit Is Nothing Then
                                                    BELEG.DruckDatumUhrzeit = Now
                                                    BELEG.SAVE()
                                                End If
                                                print.Dispose()
                                                '   print.Close()
                                            End Sub

        End If
        Return True

        '   Me.Cursor = Cursors.Default
    End Function


    Public Shared Function printNULLBeleg(KASSE As cRKSV_Kasse, PERSONAL As cPersonal, AUTODRUCK As Boolean, Firma As String) As Boolean
        Try

            If PERSONAL Is Nothing Then
                Dim FMZOLL_SQL As New FMZOLL_SQL
                PERSONAL = FMZOLL_SQL.getPersonalById(274)
            End If

            Dim ib = ""
            '  If Not AUTODRUCK Then ib = InputBox("Passwort:")
            '  If AUTODRUCK Or (ib = "verag#2" Or ib = "supervisor") Then
            '  Dim PERSONAL As SDL.cPersonal = Nothing
            '  Dim frmSecureLoginKassenbuch As New SDL.frmSecureLoginKassenbuch
            ' If frmSecureLoginKassenbuch.ShowDialog(Me) = Windows.Forms.DialogResult.OK Then
            'PERSONAL = frmSecureLoginKassenbuch.PERSONAL
            '

            Dim TESTBUCHUNG = False
            Dim oldBelegZaehler = KASSE.rksv_BelegIdZaehler
            Dim summe As Double = 0
            Dim RKSV_Beleg_Id = KASSE.INCREASE_BELEG_UMSATZ(If(TESTBUCHUNG, 0, summe))
            If RKSV_Beleg_Id < 0 Then
                'Exit Function
                Return False
            End If

            Dim BELEG As New EABeleg(PERSONAL.Mandant, PERSONAL.Niederlassung, PERSONAL.ID)
            '  Dim GJ = New cGeschaeftsjahr(BELEG.Mandant, BELEG.Niederlassung, BELEG.Benutzer, cRKSV.getGJ(BELEG.BelegDat))

            BELEG.Ordnungsbegriff = "*** NULL-BELEG ***"
            BELEG.Beleg_TYP = "0"
            BELEG.Belegart = "0"
            BELEG.Name1 = "*** NULL-BELEG ***"
            BELEG.Steuerschlüssel = 3510
            BELEG.BelegNr = cRKSV.getNewBelegNr(BELEG, Firma) 'GJ.INCREASE_BELEG() 'Vergabe der Belegnummer '
            ' Beleg noch nicht gespeichert.... BELEG.DEL_POS_List()' Positionen löschen, da BelegNr Neu vergeben
            For Each p In BELEG.POS
                p.BelegNr = BELEG.BelegNr
            Next
            BELEG.gebucht = True
            BELEG.SAVE()


            '  QR_Image = Nothing
            Dim QR_CodeString As String = ""
            Dim LastJWS As String = ""

            If KASSE.rksv_aktiv Then ' WENN für die Kasse die RKSV gilt
                Dim answer = ""

                If Not cRKSV.insertRKSV(KASSE, KASSE.rksv_CompanyGUID, KASSE.rksv_Umsatzzaehler, BELEG.BelegDat, BELEG.Steuerschlüssel, RKSV_Beleg_Id, 0, QR_CodeString, LastJWS, TESTBUCHUNG, answer) Then 'Digitale Signierung und Erfassung in die RKSV-Datenbank mittels ITG-Service
                    If Not TESTBUCHUNG Then
                        KASSE.DECREASE_BELEG_UMSATZ(oldBelegZaehler, summe * -1)
                        cRKSV.DELETE(BELEG, KASSE.rksv_firma)
                    End If
                    MsgBox("Programmfehler bei der digitalen Signatur." & vbNewLine & vbNewLine & answer, MsgBoxStyle.Critical)
                    ' Me.Cursor = Cursors.Default
                    'BELEG = cRKSV.STORNO(BELEG, "Programmfehler")
                    ' MsgBox("Programmfehler bei der digitalen Signatur.")

                    Return False
                End If
                KASSE.SET_LAST_QR_JWS(LastJWS, QR_CodeString)
            End If

            If KASSE.rksvDE_aktiv Then ' WENN für die Kasse die DEUTSCHLAND gilt
                Dim answer = ""

                '*Nullbelg-POS*
                Dim POS As New EABelegPositionen
                POS.Abfertigungsart = 10 '"Sonstiges"
                POS.Mandant = BELEG.Mandant
                POS.Niederlassung = BELEG.Niederlassung
                POS.Benutzer = BELEG.Benutzer
                POS.BelegDat = BELEG.BelegDat
                POS.BelegNr = BELEG.BelegNr
                POS.PreislistenPos = -1
                POS.LeistungsNr = 499
                POS.LeistungsBez = "NULLBELEG"
                POS.Leistungsbeschreibung = "NULLBELEG"
                POS.PreislistenNr = -1
                POS.PreistabellenNr = -1
                POS.Preis = 0
                POS.Anzahl = 1
                POS.Anzahlmultiplikator = 1
                POS.Betrag = 0
                POS.Preisbindung = 0
                '  POS.AbfertigungsNr = 000
                BELEG.POS.Add(POS)

                If Not cRKSV_DE.insertRKSV_DE(PERSONAL, BELEG, KASSE, RKSV_Beleg_Id, 0, QR_CodeString, LastJWS, TESTBUCHUNG, answer) Then 'Digitale Signierung und Erfassung in die RKSV-Datenbank mittels ITG-Service
                    If Not TESTBUCHUNG Then
                        KASSE.DECREASE_BELEG_UMSATZ(oldBelegZaehler, summe * -1)
                        cRKSV.DELETE(BELEG, KASSE.rksv_firma)
                    End If
                    MsgBox("Programmfehler bei der digitalen Signatur." & vbNewLine & vbNewLine & answer, MsgBoxStyle.Critical)
                    ' Me.Cursor = Cursors.Default
                    'BELEG = cRKSV.STORNO(BELEG, "Programmfehler")
                    ' MsgBox("Programmfehler bei der digitalen Signatur.")

                    Return False
                End If
                KASSE.SET_LAST_QR_JWS(LastJWS, QR_CodeString)

                'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
                If KASSE.rksv_KassaGuid = "KASSE_01" Then
                    BELEG.rksv_jws = Nothing
                    BELEG.rksv_qr = Nothing
                End If
                'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 

            End If

            'RKSV-Daten beim Beleg ergänzen:
            BELEG.rksv_jws = LastJWS
            BELEG.rksv_qr = QR_CodeString
            BELEG.rksv_BelegId = RKSV_Beleg_Id
            BELEG.rksv_id = KASSE.rksv_id
            BELEG.rksv_umsatz = summe
            BELEG.rksv_aktiv = (KASSE.rksv_aktiv Or KASSE.rksvDE_aktiv)
            BELEG.SAVE()


            'printBeleg(BELEG, KASSE, PERSONAL, cboPrinter.SelectedItem.ToString) 'Beleg drucken


            If AUTODRUCK Then
                Dim pName = ""
                For Each sPrinter As String In System.Drawing.Printing.PrinterSettings.InstalledPrinters
                    If sPrinter = "AUTODRUCK_MAIL" Then pName = sPrinter : Exit For
                Next
                If pName = "" Then
                    Dim oPS As New System.Drawing.Printing.PrinterSettings
                    pName = oPS.PrinterName
                End If
                cRKSV.printKundenBeleg(BELEG, KASSE, PERSONAL, pName, False) 'Beleg drucken
            Else
                cRKSV.printKundenBeleg(BELEG, KASSE, PERSONAL, "", False) 'Beleg drucken
            End If

            Return True
            ' End If

        Catch ex As Exception
            MsgBox(ex.Message & ex.StackTrace)
        End Try
        Return False

    End Function


    Public Shared Function getCardSerialInReader(kasse_id As Integer, reader As String)
        Try
            Dim KASSE As New cRKSV_Kasse(kasse_id)
            Dim client As RKSVWcfClient = New RKSVWcfClient()
            client.Endpoint.Address = New System.ServiceModel.EndpointAddress(getRKSVLink(KASSE))
            client.Open()
            '   svcRKSV.DBUserCredentials m_credentials = new svcRKSV.DBUserCredentials();
            Dim credentials As New SDL.RKSVServer.DBUserCredentials

            credentials.Database = "RKSVWcfDB"
            credentials.Server = "AVISO\SQLEXPRESS"

            credentials.Username = "Admin"
            credentials.Password = "verag#2"
            ' credentials.CashboxID = kasse '"VERAG-SUB-KASSE-ZOLL"
            '    credentials.CompanyGUID = CompanyGUID ' "9119d9ae-f549-4a0f-a50f-0500ec7ca059"



            Return client.GetCardInReader(reader)
        Catch ex As Exception
            MsgBox("ERROR " & ex.Message & ex.StackTrace)
        End Try
        Return ""
    End Function


    Public Shared Function printFremdBeleg(BELEG As EABeleg, KASSE As cRKSV_Kasse, PERSONAL As cPersonal, KBEntry As cKassenbuch, KBEntryGB As cKassenbuch, printername As String) As Boolean
        Dim print As New GrapeCity.ActiveReports.Viewer.Win.Viewer
        print.Text = "Beleg"
        Dim rpt As New rptEABeleg
        'rpt.lblRgNr.Text = BELEG.rksv_BelegId '"12345 / TR"

        ' Dim QR As String = ""

        If (KASSE.rksv_aktiv Or KASSE.rksvDE_aktiv) And BELEG.rksv_BelegId > 0 Then
            If BELEG.rksv_qr Is Nothing OrElse BELEG.rksv_qr = "" Then
                If KASSE.rksv_KassaGuid <> "KASSE_01" Then
                    MsgBox("Fehler: QR-Code wurde nicht richtig erstellt!")
                End If
            Else
                Dim bmpBytes As Byte() = Convert.FromBase64String(BELEG.rksv_qr)
                Dim MS As New System.IO.MemoryStream(bmpBytes)
                Dim QR_Image = Image.FromStream(MS)
                rpt.QR.Image = QR_Image
            End If

        End If
        '  Dim bmpBytes As Byte() = Convert.FromBase64String(QR)
        '   Dim MS As New System.IO.MemoryStream(bmpBytes)
        '    Dim QR_Image = Image.FromStream(MS)
        '     rpt.QR.Image = QR_Image

        rpt.Label25.Visible = (BELEG.DruckDatumUhrzeit IsNot Nothing) 'KOPIE
        rpt.lblBuchungsdatum.Text = CDate(BELEG.BelegDat).ToShortDateString
        rpt.lblUhrzeit.Text = "" 'Now.ToShortTimeString
        rpt.lblBuchungstext.Text = KBEntry.Buchungstext 'cboKonto.Text
        rpt.lblBelegdatum.Text = CDate(KBEntry.BelegDat).ToShortDateString
        rpt.lblReferenz.Text = KBEntry.Referenz 'txtReferenz.Text
        rpt.lblKonto.Text = KBEntryGB.Konto 'cboKonto._value
        rpt.lblBetrag.Text = CDbl(BELEG.rksv_umsatz).ToString("C2")

        rpt.lblSachbearbeiter.Text = PERSONAL.Name
        rpt.lblKontoSB.Text = PERSONAL.KassenbuchNr
        rpt.lblRgNr.Text = BELEG.rksv_BelegId
        If BELEG.Belegart = 1 Then
            'Einnahme
            rpt.lblTitel.Text = "KASSE - EINGANG"
        Else
            rpt.lblTitel.Text = "KASSE - AUSGANG"
        End If

        If BELEG.storniert Then
            rpt.Label25.Text = "** STORNO **"
            rpt.Label25.Visible = True
            rpt.lblStorno.Visible = True
            rpt.lblStorno.Text = "STORNO" & vbNewLine & BELEG.Stornogrund

        End If
        If KASSE IsNot Nothing Then
            Select Case KASSE.rksv_bez
                Case "VERAG-SUB-KASSE-ZOLL"
                    'Default Werte:
                    'rpt.picVERAG.Image = My.Resources.Verag_AG_Logo2 'Standart
                    rpt.lblFirma_Name.Text = "VERAG Spedition AG"
                    rpt.lblFirma_Details.Text = "A 4975 Suben  |  Suben 100" & vbNewLine & "UID: ATU53187000 "
                Case "VERAG-CUSTOMSSERVICE-KASSE-ZOLL"
                    'Default Werte:
                    rpt.picVERAG.Image = My.Resources.Verag_Customs_Service_GMBH_Logo_med
                    rpt.lblFirma_Name.Text = "VERAG Customs Service GmbH"
                    rpt.lblFirma_Details.Text = "A 4975 Suben  |  Suben 14" & vbNewLine & "UID: ATU68374109 "
                Case "ATILLA-SUB-KASSE-ZOLL"
                    'Default Werte:
                    rpt.picVERAG.Image = My.Resources.Atilla_big_med
                    rpt.lblFirma_Name.Text = "ATILLA Spedition GmbH"
                    rpt.lblFirma_Details.Text = "A 4975 Suben  |  Suben 15" & vbNewLine & "UID: ATU63158647 "
                Case "VERAG-GMBH-KASSE-ZOLL"
                    'Default Werte:
                    rpt.picVERAG.Image = My.Resources.Verag_Spedition_GMBH_Logo_med
                    rpt.lblFirma_Name.Text = "VERAG Spedition GmbH"
                    rpt.lblFirma_Details.Text = "D 94152 Neuhaus am Inn  |  Hartham 6" & vbNewLine & "UID: DE813570890 "
                Case "KASSE-VERWALTUNG"
                    'Default Werte:
                    '    rpt.picVERAG.Image = My.Resources.Verag_AG_Logo2
                    rpt.lblFirma_Name.Text = "KASSE VERWALTUNG"
                    rpt.lblFirma_Details.Text = " *** nur intern ***"
                Case "IMEX-KASSE-VERWALTUNG"
                    rpt.lblFirma_Name.Text = "KASSE VERWALTUNG"
                    rpt.lblFirma_Details.Text = " *** nur intern ***"
                    rpt.picVERAG.Image = My.Resources.IMEX_LOGO_simple
                    rpt.lblFirma_Name.Text = "IMEX Customs Service GmbH"
                    rpt.lblFirma_Details.Text = "A 4975 Suben  |  Suben 15" & vbNewLine & "UID: ATU68490714 "
                Case "TEST-KASSE"
                    'Default Werte:
                    '    rpt.picVERAG.Image = My.Resources.Verag_AG_Logo2
                    If VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "IMEX" Then rpt.picVERAG.Image = My.Resources.IMEX_LOGO_simple
                    If VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "ATILLA" Then rpt.picVERAG.Image = My.Resources.Atilla_big_med

                    rpt.lblFirma_Name.Text = "TEST-KASSE"
                    rpt.lblFirma_Details.Text = " *** nur intern ***"
                Case "IMEX-KASSE-SUB"
                    'Default Werte:
                    rpt.picVERAG.Image = My.Resources.IMEX_LOGO_simple
                    rpt.lblFirma_Name.Text = "IMEX Customs Service GmbH"
                    rpt.lblFirma_Details.Text = "A 4975 Suben  |  Suben 15" & vbNewLine & "UID: ATU68490714 "
                Case "FRONT-OFFICE-SUB-KASSE"
                    'Default Werte:
                    rpt.picVERAG.Image = My.Resources.FrontOfficeSUB
                    rpt.lblFirma_Name.Text = "Front-Office Suben eG"
                    rpt.lblFirma_Details.Text = "A 4975 Suben  |  Suben 14" & vbNewLine & "UID: ATU74813856 "
            End Select
        End If

        rpt.Run(False)

        If printername <> "" Then
            rpt.Document.Printer.PrinterName = printername
        Else
            Dim p As New PrintDialog
            If p.ShowDialog() = DialogResult.OK Then
                printername = p.PrinterSettings.PrinterName
            Else
                rpt.Dispose()
            End If
        End If

        If Not rpt.Document.Print(False, False) Then
            MsgBox("Problem beim Drucken.")
        End If
        If BELEG.DruckDatumUhrzeit Is Nothing Then
            BELEG.DruckDatumUhrzeit = Now
            BELEG.SAVE()
        End If
        rpt.Dispose()

        If False Then


            print.ViewType = GrapeCity.Viewer.Common.Model.ViewType.Continuous
            print.LoadDocument(rpt)
            'print = FormWindowState.Minimized
            'print.Visible = False
            ' print.Show()


            AddHandler print.LoadCompleted, Sub()
                                                If printername <> "" Then
                                                    print.Document.Printer.PrinterName = printername
                                                Else
                                                    Dim p As New PrintDialog
                                                    If p.ShowDialog() = DialogResult.OK Then
                                                        printername = p.PrinterSettings.PrinterName
                                                    Else
                                                        print.Dispose()
                                                        Exit Sub
                                                    End If
                                                End If
                                                If printername = "" Then print.Dispose() : Exit Sub
                                                print.Document.Printer.PrinterName = printername

                                                If Not print.Print(False, False) Then
                                                    MsgBox("Problem beim Drucken.")
                                                End If
                                                If BELEG.DruckDatumUhrzeit Is Nothing Then
                                                    BELEG.DruckDatumUhrzeit = Now
                                                    BELEG.SAVE()
                                                End If
                                                print.Dispose()
                                                '   print.Close()
                                            End Sub
        End If

        Return True

        '   Me.Cursor = Cursors.Default
    End Function


    Public Shared Sub printAESKey(KASSE As cRKSV_Kasse, printername As String)
        Dim print As New GrapeCity.ActiveReports.Viewer.Win.Viewer
        print.Text = "AES-Key"
        Dim rpt As New rptAESKey
        rpt.lblKASSE.Text = KASSE.rksv_bez
        rpt.lblDatum.Text = Now.ToString("dd.MM.yyyy") ' HH:mm")
        rpt.txtAES.Text = KASSE.rksv_AesKey ' HH:mm")

        Select Case KASSE.rksv_bez
            Case "VERAG-SUB-KASSE-ZOLL"
                'Default Werte:
                'rpt.picVERAG.Image = My.Resources.Verag_AG_Logo2 'Standart
                rpt.lblFirma_Name.Text = "VERAG Spedition AG"
                rpt.lblFirma_Details.Text = "A 4975 Suben  |  Suben 100" & vbNewLine & "UID: ATU53187000 "
            Case "VERAG-CUSTOMSSERVICE-KASSE-ZOLL"
                'Default Werte:
                rpt.picVERAG.Image = My.Resources.Verag_Customs_Service_GMBH_Logo_med
                rpt.lblFirma_Name.Text = "VERAG Customs Service GmbH"
                rpt.lblFirma_Details.Text = "A 4975 Suben  |  Suben 14" & vbNewLine & "UID: ATU68374109 "
            Case "ATILLA-SUB-KASSE-ZOLL"
                'Default Werte:
                rpt.picVERAG.Image = My.Resources.Atilla_big_med
                rpt.lblFirma_Name.Text = "ATILLA Spedition GmbH"
                rpt.lblFirma_Details.Text = "A 4975 Suben  |  Suben 15" & vbNewLine & "UID: ATU63158647 "
            Case "VERAG-GMBH-KASSE-ZOLL"
                'Default Werte:
                rpt.picVERAG.Image = My.Resources.Verag_Spedition_GMBH_Logo_med
                rpt.lblFirma_Name.Text = "VERAG Spedition GmbH"
                rpt.lblFirma_Details.Text = "D 94152 Neuhaus am Inn  |  Hartham 6" & vbNewLine & "UID: DE813570890 "
            Case "KASSE-VERWALTUNG"
                'Default Werte:
                '    rpt.picVERAG.Image = My.Resources.Verag_AG_Logo2
                rpt.lblFirma_Name.Text = "KASSE VERWALTUNG / BUCHHALTUNG"
                rpt.lblFirma_Details.Text = " *** nur intern ***"
            Case "IMEX-KASSE-VERWALTUNG"
                rpt.lblFirma_Name.Text = "KASSE VERWALTUNG"
                rpt.lblFirma_Details.Text = " *** nur intern ***"
                rpt.picVERAG.Image = My.Resources.IMEX_LOGO_simple
                rpt.lblFirma_Name.Text = "IMEX Customs Service GmbH"
                rpt.lblFirma_Details.Text = "A 4975 Suben  |  Suben 15" & vbNewLine & "UID: ATU68490714 "
            Case "TEST-KASSE"
                'Default Werte:
                '    rpt.picVERAG.Image = My.Resources.Verag_AG_Logo2
                If VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "IMEX" Then rpt.picVERAG.Image = My.Resources.IMEX_LOGO_simple
                If VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "ATILLA" Then rpt.picVERAG.Image = My.Resources.Atilla_big_med

                rpt.lblFirma_Name.Text = "TEST-KASSE"
                rpt.lblFirma_Details.Text = " *** nur intern ***"
            Case "IMEX-KASSE-SUB"
                'Default Werte:
                rpt.picVERAG.Image = My.Resources.IMEX_LOGO_simple
                rpt.lblFirma_Name.Text = "IMEX Customs Service GmbH"
                rpt.lblFirma_Details.Text = "A 4975 Suben  |  Suben 15" & vbNewLine & "UID: ATU68490714 "
            Case "FRONT-OFFICE-SUB-KASSE"
                'Default Werte:
                rpt.picVERAG.Image = My.Resources.FrontOfficeSUB
                rpt.lblFirma_Name.Text = "Front-Office Suben eG"
                rpt.lblFirma_Details.Text = "A 4975 Suben  |  Suben 14" & vbNewLine & "UID: ATU74813856 "
        End Select

        print.ViewType = GrapeCity.Viewer.Common.Model.ViewType.Continuous
        print.LoadDocument(rpt)


        AddHandler print.LoadCompleted, Sub()
                                            '  MsgBox("b" & printername)
                                            ' MsgBox(cboPrinter.SelectedItem.ToString)
                                            ' If cboPrinter.SelectedItem.ToString <> "" Then print.Document.Printer.PrinterName = cboPrinter.SelectedItem.ToString
                                            If printername <> "" Then
                                                print.Document.Printer.PrinterName = printername
                                            Else
                                                Dim p As New PrintDialog
                                                If p.ShowDialog() = DialogResult.OK Then
                                                    printername = p.PrinterSettings.PrinterName
                                                Else
                                                    print.Dispose()
                                                    Exit Sub
                                                End If
                                            End If
                                            If printername = "" Then print.Dispose() : Exit Sub
                                            print.Document.Printer.PrinterName = printername
                                            If Not print.Print(False, False) Then
                                                MsgBox("Problem beim Drucken.")
                                            End If
                                            print.Dispose()

                                        End Sub



    End Sub


    Shared Function GetGrenzstelle(avisoid) As String
        Try
            If avisoid IsNot Nothing AndAlso CInt(avisoid) > 0 Then
                Dim AVISO = (New VERAG_PROG_ALLGEMEIN.cAvisoDAL).LesenAviso(avisoid, "")

                If VERAG_PROG_ALLGEMEIN.cAllgemein.PARAMS.GET_PARAMETER_VALUE_BOOL("RPT_SND_Grenzstelle") Then
                    If AVISO.Zollstelle IsNot Nothing AndAlso AVISO.Zollstelle <> "" Then
                        Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
                        'Return "Grenze: " & SQL.getValueTxtBySql("SELECT basncd_dstnr +' - ' + [basncd_name]  FROM basncd WHERE basncd_dstnr='" & AVISO.Zollstelle & "' ", "ATLAS")
                        Return "Grenze: " & SQL.getValueTxtBySql("SELECT Code +' - ' + [Description] FROM tbl_DY_ZollDE_C0141_Zollstellen WHERE Code='" & AVISO.Zollstelle & "' AND  ((StartDate is null OR StartDate< GETDATE()) AND (EndDate is null OR EndDate> GETDATE())) ", "FMZOLL")

                    Else
                        Return "Grenze: " & AVISO.Grenzstelle
                    End If
                End If
            End If
        Catch ex As Exception
            Return ""
        End Try
        Return ""
    End Function
    Public Shared Function insertToSpedBuch(PERSONAL As cPersonal, PERSONAL_LG As cPersonal, BELEG As EABeleg, Optional AvisoID As Object = Nothing, Optional SendungsID As Object = Nothing, Optional barBetrag As Double = 0.0, Optional barBelegId As Integer = 0) As Boolean


        'Zuerst schaun, ob Einträge in der Tabelle tblEABelegposition vorhanden
        Dim dt As DataTable = SQL.loadDgvBySql("SELECT isnull(Abfertigungsart,10) as Abfertigungsart, Sum(isnull([Anzahl],isnull([TW1],0))*Anzahlmultiplikator) AS Abfertigungsanzahl, Sum(Betrag) AS Barzahlungsbetrag" &
                " FROM tblEABelegposition" &
                " WHERE Mandant = '" & BELEG.Mandant & "'" &
                " And Niederlassung = '" & BELEG.Niederlassung & "'" &
                " And Benutzer = " & BELEG.Benutzer & "" &
                " And BelegDat = '" & BELEG.BelegDat.ToShortDateString & "' " &
                " And BelegNr = " & BELEG.BelegNr & "" &
                " GROUP BY Abfertigungsart ", "FMZOLL")
        If dt Is Nothing OrElse dt.Rows.Count = 0 Then
            MsgBox("Fehler beim Eintrag ins Speditionsbuch!")
            Return False
        End If

        'Dann alte Einträge aus Spedbuch löschen
        SQL.doSQL("DELETE FROM Speditionsbuch WHERE FilialenNr=" & BELEG.FilialenNr & " AND AbfertigungsNr=" & BELEG.AbfertigungsNr & " ", "FMZOLL")

        Dim UnterNr As Integer = 0
        For Each r In dt.Rows
            Dim SPED As New VERAG_PROG_ALLGEMEIN.cSpeditionsbuch
            SPED.FilialenNr = BELEG.FilialenNr
            SPED.AbfertigungsNr = BELEG.AbfertigungsNr
            SPED.UnterNr = UnterNr
            SPED.Abfertigungsdatum = BELEG.BelegDat.ToShortDateString

            If PERSONAL.BLC = "R" Then
                SPED.ErfassungsNr = BELEG.Mandant & "/" & BELEG.Niederlassung & "/" & PERSONAL.Name & "/" & BELEG.BelegDat.ToShortDateString & "/" & BELEG.rksv_BelegId 'Benutzer.Column(3)
            End If
            SPED.Bar = True
            SPED.AvisUhrzeit = Now.ToShortTimeString
            SPED.Sachbearbeiter = VERAG_PROG_ALLGEMEIN.cAllgemein.USRKURZNAME

            If PERSONAL_LG IsNot Nothing Then
                SPED.Personalnummer = PERSONAL_LG.ID
            Else
                SPED.Personalnummer = PERSONAL.ID
            End If
            SPED.Vermerk = BELEG.Fahrer

            Select Case VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA
                Case "IMEX" : SPED.Bemerkungen = GetGrenzstelle(AvisoID)
            End Select

            SPED.LKW_Kennzeichen = BELEG.LKW_Kennzeichen
            SPED.Abfertigungsart = r("Abfertigungsart")

            SPED.KdAuftragsNr = BELEG.Auftraggeber_KdAuftragsnummer

            ' SPED.Abfertigungsart = Nz(r("Abfertigungsart"), 10) ' wenn Abfertigungsart Null dann 10 (Sonstiges)
            SPED.Abfertigungsanzahl = r("Abfertigungsanzahl")
            '  MsgBox(SQL.getValueTxtBySql("SELECT isnull(EpSbSgutKompl,0) FROM [Abfertigungsarten] WHERE [Abfertigungsart]=" & SPED.Abfertigungsart, "FMZOLL"))
            Dim varEpSbSgutKompl As Boolean = SQL.getValueTxtBySql("SELECT isnull(EpSbSgutKompl,0) FROM [Abfertigungsarten] WHERE [Abfertigungsart]=" & SPED.Abfertigungsart, "FMZOLL")
            'DLookup("[EpSbSgutKompl]", "Abfertigungsarten", "[Abfertigungsart] = " & !Abfertigungsart)

            If CBool(varEpSbSgutKompl) Then
                If BELEG.SgutKompl Is Nothing OrElse BELEG.SgutKompl = "" Then
                    If (MsgBox("Handelt es sich um Sammelgut?", vbYesNo, "Eingabeprüfung Sgut/Kompl")) = vbYes Then
                        SPED.SgutKompl = "S"
                    Else
                        SPED.SgutKompl = "K"
                    End If
                Else
                    SPED.SgutKompl = BELEG.SgutKompl
                End If
            Else
                SPED.SgutKompl = Nothing
            End If

            SPED.Zollsystem = "A"
            SPED.VermittlerKundenNr = If(BELEG.KundenNr > 0, BELEG.KundenNr, Nothing)
            SPED.Vermittler = BELEG.Ordnungsbegriff
            SPED.FrachtführerKundenNr = If(BELEG.FrachtführerKundenNr > 0, BELEG.FrachtführerKundenNr, Nothing)
            SPED.Frachtführer = BELEG.Frachtführer
            Dim AD = New VERAG_PROG_ALLGEMEIN.cAvisoDAL
            If AvisoID IsNot Nothing Then
                Dim aviso_tmp As VERAG_PROG_ALLGEMEIN.cAviso = AD.LesenAviso(AvisoID, "")
                If aviso_tmp.Grenzstelle IsNot Nothing AndAlso aviso_tmp.Grenzstelle <> "" Then SPED.Grenzstelle = aviso_tmp.Grenzstelle
            End If

            SPED.AvisoID = AvisoID
            If SendungsID IsNot Nothing Then SPED.SendungID = SendungsID
            Dim anz = SPED.Abfertigungsanzahl
            If SPED.Abfertigungsart Then
                SPED.AnzahlZA = IIf(SPED.Abfertigungsart = 1, anz, "0")
                SPED.AnzahlZAFremd = IIf(SPED.Abfertigungsart = 2, anz, "0")
                SPED.AnzahlZnV = IIf(SPED.Abfertigungsart = 3, anz, "0")
                SPED.AnzahlZnVFremd = IIf(SPED.Abfertigungsart = 4, anz, "0")
                SPED.AnzahlT1 = IIf(SPED.Abfertigungsart = 5, anz, "0")
                SPED.AnzahlT2 = IIf(SPED.Abfertigungsart = 6, anz, "0")
                SPED.AnzahlAE = IIf(SPED.Abfertigungsart = 7, anz, "0")
                SPED.AnzahlCarnetTIR = IIf(SPED.Abfertigungsart = 8, anz, "0")
                SPED.AnzahlBarvorlagen = IIf(SPED.Abfertigungsart = 9, anz, "0")
                SPED.AnzahlSonstiges = IIf(SPED.Abfertigungsart = 10, anz, "0")
                SPED.AnzahlGrenzgebühren = IIf(SPED.Abfertigungsart = 11, anz, "0")
            End If

            Select Case BELEG.Belegart
                Case 1  ' Einnahme
                    If PERSONAL.BLC = "R" Then
                        SPED.Barzahlungsbetrag = r("Barzahlungsbetrag")
                    Else
                        SPED.Barzahlungsbetrag = 0.0
                    End If
                Case 2  ' Ausgabe
                    SPED.Barzahlungsbetrag = barBetrag
                    If PERSONAL.BLC = "R" Then
                        SPED.ErfassungsNr = SPED.ErfassungsNr & "/" & FormatCurrency(r("Barzahlungsbetrag"))
                    End If
            End Select
            ' .Update()
            '  rst2.MoveNext()
            ' intUnterNr = intUnterNr + 1

            SPED.SAVE()

            UnterNr += 1
        Next
        Return True
    End Function

    Public Shared Function SpedBuchExists(BELEG As EABeleg) As Boolean
        Return (CInt(SQL.getValueTxtBySql("SELECT count(*) FROM Speditionsbuch WHERE FilialenNr=" & BELEG.FilialenNr & " AND AbfertigungsNr=" & BELEG.AbfertigungsNr & " ", "FMZOLL")) > 0)
    End Function
    Public Shared Function SpedBuchExists(FilialenNr As Integer, AbfertigungsNr As Integer) As Boolean
        Return (CInt(SQL.getValueTxtBySql("SELECT count(*) FROM Speditionsbuch WHERE FilialenNr=" & FilialenNr & " AND AbfertigungsNr=" & AbfertigungsNr & " ", "FMZOLL")) > 0)
    End Function

    Public Shared Function getNewBelegNr(BELEG As EABeleg, Firma As String) As Integer
        Dim GJ = New cGeschaeftsjahr(BELEG.Mandant, BELEG.Niederlassung, BELEG.Benutzer, cRKSV.getGJ_FIRMA(BELEG.BelegDat, Firma))
        Return GJ.INCREASE_BELEG()
    End Function
    Public Shared Function getNewJournalNr(BELEG As EABeleg, Firma As String) As Integer
        Dim GJ = New cGeschaeftsjahr(BELEG.Mandant, BELEG.Niederlassung, BELEG.Benutzer, cRKSV.getGJ_FIRMA(BELEG.BelegDat, Firma))
        Return GJ.INCREASE_JOURNAL()
    End Function

    Public Shared Function insertKB(PERSONAL As cPersonal, BELEG As EABeleg, RKSV_id As Integer, RKSV_Beleg_Id As Integer, RKSV_aktiv As Integer, ByRef JournalNr As Integer, Firma As String, POSFIBU As Integer, Optional Finanzwege As String = "Bar")
        Try
            If BELEG.POS.Count = 0 Then
                MsgBox("Keine Positionen gefunden")
                cRKSV.STORNO(BELEG, "Programmfehler: Keine Beleg-Pos. gefunden.", Firma)
                Return False
            End If
            ' Belegnr!!!!!!!!!!!!!!!!!!!!!!!!!!!!

            '   Dim GJ = New cGeschaeftsjahr(BELEG.Mandant, BELEG.Niederlassung, BELEG.Benutzer, cRKSV.getGJ(BELEG.BelegDat))

            BELEG.BelegNr = getNewBelegNr(BELEG, Firma) ' GJ.INCREASE_BELEG() 'Vergabe der Belegnummer'
            ' Beleg noch nicht gespeichert.... BELEG.DEL_POS_List()' Positionen löschen, da BelegNr Neu vergeben

            For Each p In BELEG.POS
                p.BelegNr = BELEG.BelegNr
            Next
            BELEG.SAVE()
            'BELEG.SAVE_POS_List()

            If BELEG.POS.Count > 0 Then
                ' Dim tb As DataRow = tbKBEintrag.Rows(0)
                If Not BELEG.gebucht Then 'CBool(tbKBEintrag.Rows(0)("gebucht")) Then 'wenn nicht bereits gebucht
                    Dim dtBetraege = SQL.loadDgvBySql(" SELECT  isnull(Sum(tblEABelegposition.Betrag),0) AS Nettobetrag,  " &
                                                      "       isnull(Sum(CASE WHEN [Steuerpflichtig]=1 THEN [Betrag] ELSE 0 END),0) AS SteuerpflichtigerBetrag, " &
                                                      "       isnull(Sum(cast((CASE WHEN [Steuerpflichtig]=1 THEN [Betrag] ELSE 0 END)* [Steuersatz] as decimal(8,2))),0) AS SteuerBetrag, " &
                                                      "       isnull(Sum(tblEABelegposition.Betrag+cast((CASE WHEN [Steuerpflichtig]=1 THEN [Betrag] ELSE 0 END)* [Steuersatz] as decimal(8,2))),0) AS Bruttobetrag " &
                                                    " FROM tblEABelegnummer INNER JOIN tblSteuersätze ON tblEABelegnummer.Steuerschlüssel = tblSteuersätze.Nr INNER JOIN tblEABelegposition INNER JOIN Leistungen ON tblEABelegposition.LeistungsNr = Leistungen.LeistungsNr ON tblEABelegnummer.Mandant = tblEABelegposition.Mandant AND tblEABelegnummer.Niederlassung = tblEABelegposition.Niederlassung AND tblEABelegnummer.Benutzer = tblEABelegposition.Benutzer AND tblEABelegnummer.BelegDat = tblEABelegposition.BelegDat AND tblEABelegnummer.BelegNr = tblEABelegposition.BelegNr " &
                                                   "  WHERE tblEABelegposition.Mandant='" & BELEG.Mandant & "' AND tblEABelegposition.Niederlassung='" & BELEG.Niederlassung & "' AND tblEABelegposition.Benutzer='" & BELEG.Benutzer & "' AND tblEABelegposition.BelegDat='" & BELEG.BelegDat.ToShortDateString & "' AND tblEABelegposition.BelegNr='" & BELEG.BelegNr & "'", "FMZOLL")

                    If dtBetraege.Rows.Count = 0 Then
                        MsgBox("ERROR: Beleg - Eintrag nicht gefunden. Abbruch!")
                        cRKSV.STORNO(BELEG, "Programmfehler: Beleg - Eintrag nicht gefunden.", Firma)

                        Return False
                    End If
                    Dim Bruttobetrag As Double = dtBetraege.Rows(0)("Bruttobetrag")
                    Dim Nettobetrag As Double = dtBetraege.Rows(0)("Nettobetrag")
                    Dim SteuerBetrag As Double = dtBetraege.Rows(0)("SteuerBetrag")

                    '################
                    ' EINTRAG: Kassenbuch
                    '################
                    Dim KBEntry As New cKassenbuch(BELEG.Mandant, BELEG.Niederlassung, BELEG.Benutzer, cRKSV.getGJ_FIRMA(BELEG.BelegDat, Firma), JournalNr)
                    KBEntry.JournalNr = getNewJournalNr(BELEG, Firma) ' GJ.INCREASE_JOURNAL() 'Vergabe der Journalnummer'
                    '    KBEntry.JournalNr = fktJournalNr(rst1!Mandant, rst1!Niederlassung, rst1!Benutzer, rst1!BelegDat)
                    KBEntry.Konto = PERSONAL.KassenbuchNr
                    If BELEG.FilialenNr = -1 Or BELEG.AbfertigungsNr = -1 Then
                        If If(BELEG.LKW_Id, -1) > 0 Then
                            KBEntry.Buchungstext = Trim("LKW-Id: " & BELEG.LKW_Id)
                        Else
                            KBEntry.Buchungstext = "-"
                        End If
                    Else
                        KBEntry.Buchungstext = Trim("Pos. " & BELEG.FilialenNr & "/" & Format(BELEG.AbfertigungsNr, "00000000"))
                    End If

                    KBEntry.Buchungsdatum = Now.ToShortDateString
                    KBEntry.BelegDat = BELEG.BelegDat.ToShortDateString
                    KBEntry.BelegNr = BELEG.BelegNr
                    KBEntry.Belegart = BELEG.Belegart
                    If BELEG.Belegart = 1 Then
                        KBEntry.Soll = Bruttobetrag
                    ElseIf BELEG.Belegart = 2 Then
                        KBEntry.Haben = Bruttobetrag
                    End If
                    KBEntry.rksv_id = RKSV_id
                    KBEntry.rksv_aktiv = RKSV_aktiv
                    KBEntry.rksv_BelegId = RKSV_Beleg_Id

                    KBEntry.Belegverbuchung = True
                    KBEntry.gebucht = True
                    KBEntry.Finanzwege = Finanzwege

                    If Not KBEntry.INSERT() Then
                        Return False
                    End If

                    '################
                    ' EINTRAG: Gegenbuchung
                    '################

                    Dim curSteuerbetrag As Double = 0
                    For Each p In BELEG.POS
                        Dim dtBetraegeGB = SQL.loadDgvBySql(" SELECT " & getGl_account(KBEntry.rksv_id) & " AS Gegenkonto, isnull(tblEABelegposition.Betrag,0) AS Nettobetrag, " &
                                                                " isnull((cast((CASE WHEN [Steuerpflichtig]=1 THEN [Betrag] ELSE 0 END)* [Steuersatz] as decimal(8,2))),0)  AS Steuerbetrag " &
                                                            " FROM tblSteuersätze INNER JOIN tblEABelegnummer ON tblSteuersätze.Nr = tblEABelegnummer.Steuerschlüssel INNER JOIN tblEABelegposition INNER JOIN Leistungen ON tblEABelegposition.LeistungsNr = Leistungen.LeistungsNr ON tblEABelegnummer.Mandant = tblEABelegposition.Mandant AND tblEABelegnummer.Niederlassung = tblEABelegposition.Niederlassung AND tblEABelegnummer.Benutzer = tblEABelegposition.Benutzer AND tblEABelegnummer.BelegDat = tblEABelegposition.BelegDat AND tblEABelegnummer.BelegNr = tblEABelegposition.BelegNr " &
                                                            " WHERE tblEABelegposition.Mandant='" & BELEG.Mandant & "' AND tblEABelegposition.Niederlassung='" & BELEG.Niederlassung & "' AND tblEABelegposition.Benutzer='" & BELEG.Benutzer & "' AND tblEABelegposition.BelegDat='" & BELEG.BelegDat.ToShortDateString & "' AND tblEABelegposition.BelegNr='" & BELEG.BelegNr & "' AND tblEABelegposition.LeistungsNr=" & p.LeistungsNr & " AND tblEABelegposition.PreislistenPos='" & p.PreislistenPos & "' " &
                                                            " AND tblEABelegposition.FilialenNr='" & p.FilialenNr & "' AND tblEABelegposition.AbfertigungsNr='" & p.AbfertigungsNr & "'", "FMZOLL")
                        If dtBetraegeGB.Rows.Count = 0 Then
                            MsgBox("ERROR: Beleg-Position - Eintrag nicht gefunden. Abbruch!")
                            cRKSV.STORNO(BELEG, "Programmfehler: Beleg - Eintrag nicht gefunden.", Firma)

                            Return False
                        End If
                        If Not IsNumeric(dtBetraegeGB.Rows(0)("Gegenkonto")) OrElse dtBetraegeGB.Rows(0)("Gegenkonto") <= 0 Then
                            MsgBox("ERROR: Gegenkonto nicht vorhanden. Abbruch!")
                            cRKSV.STORNO(BELEG, "Programmfehler: Gegenkonto nicht vorhanden.", Firma)
                            Return False
                        End If

                        Dim KBEntryGB As New cKassenbuch(BELEG.Mandant, BELEG.Niederlassung, BELEG.Benutzer, cRKSV.getGJ_FIRMA(BELEG.BelegDat, Firma), JournalNr)
                        KBEntryGB.JournalNr = getNewJournalNr(BELEG, Firma) 'GJ.INCREASE_JOURNAL() 'Vergabe der Journalnummer'
                        KBEntryGB.Konto = dtBetraegeGB.Rows(0)("Gegenkonto")
                        KBEntryGB.Buchungstext = p.LeistungsBez
                        KBEntryGB.Buchungsdatum = Now.ToShortDateString
                        KBEntryGB.BelegDat = p.BelegDat.ToShortDateString
                        KBEntryGB.Steuer = IIf(IsNumeric(BELEG.Steuerschlüssel) AndAlso BELEG.Steuerschlüssel > 0, BELEG.Steuerschlüssel, 0)
                        KBEntryGB.BelegNr = BELEG.BelegNr
                        KBEntryGB.Belegart = BELEG.Belegart
                        If BELEG.Belegart = 1 Then
                            KBEntryGB.Haben = dtBetraegeGB.Rows(0)("Nettobetrag")
                        ElseIf BELEG.Belegart = 2 Then
                            KBEntryGB.Soll = dtBetraegeGB.Rows(0)("Nettobetrag")
                        End If

                        KBEntryGB.Steuerbetrag = dtBetraegeGB.Rows(0)("SteuerBetrag")
                        curSteuerbetrag = curSteuerbetrag + dtBetraegeGB.Rows(0)("SteuerBetrag")
                        KBEntryGB.rksv_id = RKSV_id
                        KBEntryGB.rksv_aktiv = RKSV_aktiv
                        KBEntryGB.rksv_BelegId = RKSV_Beleg_Id

                        KBEntryGB.Belegverbuchung = True
                        KBEntryGB.gebucht = True
                        KBEntryGB.Finanzwege = Finanzwege

                        If Not KBEntryGB.INSERT() Then
                            Return False
                        End If
                    Next

                    '################
                    ' EINTRAG: Steuerbuchung
                    '################

                    If IsNumeric(BELEG.Steuerschlüssel) AndAlso BELEG.Steuerschlüssel > 0 And SteuerBetrag - curSteuerbetrag <> 0 Then
                        Dim KBEntryST As New cKassenbuch(BELEG.Mandant, BELEG.Niederlassung, BELEG.Benutzer, cRKSV.getGJ_FIRMA(BELEG.BelegDat, Firma), JournalNr)

                        KBEntryST.JournalNr = getNewJournalNr(BELEG, Firma) 'GJ.INCREASE_JOURNAL() 'Vergabe der Journalnummer'
                        KBEntryST.Konto = 8490
                        KBEntryST.Buchungstext = "Rundungsdifferenz in Steuer"
                        KBEntryST.Buchungsdatum = Now.ToShortDateString
                        KBEntryST.BelegDat = BELEG.BelegDat.ToShortDateString
                        KBEntryST.Steuer = IIf(IsNumeric(BELEG.Steuerschlüssel) AndAlso BELEG.Steuerschlüssel > 0, BELEG.Steuerschlüssel, 0)
                        KBEntryST.BelegNr = BELEG.BelegNr
                        KBEntryST.Belegart = BELEG.Belegart
                        If KBEntryST.Belegart = 1 Then
                            KBEntryST.Haben = SteuerBetrag - curSteuerbetrag
                        ElseIf KBEntryST.Belegart = 2 Then
                            KBEntryST.Soll = SteuerBetrag - curSteuerbetrag
                        End If
                        KBEntryST.rksv_id = RKSV_id
                        KBEntryST.rksv_aktiv = RKSV_aktiv
                        KBEntryST.rksv_BelegId = RKSV_Beleg_Id

                        KBEntryST.Belegverbuchung = True
                        KBEntryST.gebucht = True

                        If Not KBEntryST.INSERT() Then
                            Return False
                        End If

                    End If


                    '################
                    ' EINTRAG: Umbuchung bei EC-Zahlung
                    '################
                    If Finanzwege = "EC" Then
                        Dim BelegNrEC = -1

                        For i = 0 To 1

                            Dim KBEntryEC As New cKassenbuch(BELEG.Mandant, BELEG.Niederlassung, BELEG.Benutzer, cRKSV.getGJ_FIRMA(BELEG.BelegDat, Firma), JournalNr)
                            KBEntryEC.JournalNr = getNewJournalNr(BELEG, Firma)
                            If i = 0 Then

                                KBEntryEC.Konto = POSFIBU
                                BelegNrEC = getNewBelegNr(BELEG, Firma) '& KBEntryEC.Belegart 'zur Generierung von eigenem Buchungssatz
                            Else
                                KBEntryEC.Konto = PERSONAL.KassenbuchNr
                            End If

                            KBEntryEC.Buchungstext = "Umb. BK/KASSA"

                            KBEntryEC.Buchungsdatum = Now.ToShortDateString
                            KBEntryEC.BelegDat = BELEG.BelegDat.ToShortDateString
                            KBEntryEC.Belegart = 3
                            KBEntryEC.BelegNr = BelegNrEC
                            If BELEG.Belegart = 1 Then
                                If i = 0 Then
                                    KBEntryEC.Soll = Bruttobetrag
                                Else
                                    KBEntryEC.Haben = Bruttobetrag
                                End If

                            ElseIf BELEG.Belegart = 2 Then
                                If i = 0 Then
                                    KBEntryEC.Haben = Bruttobetrag
                                Else
                                    KBEntryEC.Soll = Bruttobetrag
                                End If

                            End If
                            KBEntryEC.rksv_id = RKSV_id
                            KBEntryEC.rksv_aktiv = RKSV_aktiv
                            KBEntryEC.rksv_BelegId = RKSV_Beleg_Id

                            KBEntryEC.Belegverbuchung = True
                            KBEntryEC.gebucht = True
                            KBEntryEC.Finanzwege = Finanzwege

                            If Not KBEntryEC.INSERT() Then
                                Return False
                            End If

                        Next
                    End If

                    '################
                    ' Buchung im EABeleg eintragen.
                    '################
                    BELEG.gebucht = True
                    BELEG.SAVE()

                End If
            End If

            Return True

        Catch ex As Exception
            MsgBox("ERROR: " & ex.Message & vbNewLine & vbNewLine & ex.StackTrace)
            cRKSV.STORNO(BELEG, "Programmfehler!", Firma)

            Return False
        End Try
    End Function


    Public Shared Function getGl_account(rksv_id)
        If rksv_id = 1 Then Return "Leistungen.Gl_account" ' VERAG-Kasse bei IMEX
        Select Case VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA
            Case "IMEX" : Return "Leistungen.IMEX_Gl_account"
            Case Else : Return "Leistungen.Gl_account"
        End Select
    End Function
End Class



Public Class cRKSV_DE__TEST
    Shared SQL As New SQL

    Shared Function getBelegSting_BAR(summeBRUTTO As Double, steuerSchluessel As Integer) As String


        Dim steuersatz As Double = SQL.getValueTxtBySql("SELECT isnull(tblSteuersätze.Steuersatz,0) FROM tblSteuersätze WHERE tblSteuersätze.Nr='" & steuerSchluessel & "' ", "FMZOLL")


        Dim BetragSatzNormal = IIf(steuersatz = 0.19, summeBRUTTO, 0.0)
        Dim BetragSatzErm1 = IIf(steuersatz = 0.1, summeBRUTTO, 0.0)
        Dim BetragSatzNull = IIf(steuersatz = 0, summeBRUTTO, 0.0)


        BetragSatzNormal += IIf(steuersatz = 0.16, summeBRUTTO, 0.0)
        BetragSatzErm1 += IIf(steuersatz = 0.05, summeBRUTTO, 0.0)
        BetragSatzNormal += IIf(steuersatz = 0.2, summeBRUTTO, 0.0) ' Eig Nur AT
        'Dim BetragSatzNormal = IIf(steuersatz = 0.2, summeBRUTTO, 0.0) 'summe
        'Dim BetragSatzErm2 = IIf(steuersatz = 0.13, summeBRUTTO, 0.0)
        'Dim BetragSatzNull = IIf(steuersatz = 0.0, summeBRUTTO, 0.0)

        Dim sum = BetragSatzNormal
        sum += BetragSatzErm1
        sum += BetragSatzNull
        MsgBox("Beleg^" & BetragSatzNormal.ToString("0.00") & "_" & BetragSatzErm1.ToString("0.00") & "_0.00_0.00_" & BetragSatzNull.ToString("0.00") & "^" & sum.ToString("0.00") & ":Bar")
        Return "Beleg^" & BetragSatzNormal.ToString("0.00") & "_" & BetragSatzErm1.ToString("0.00") & "_0.00_0.00_" & BetragSatzNull.ToString("0.00") & "^" & sum.ToString("0.00") & ":Bar"

    End Function


    'Shared Function insertRKSV_DE(ByVal kasse As cRKSV_Kasse, CompanyGUID As String, ByVal umsatzZaehler As Double, ByVal belegDat As DateTime, ByVal steuerSchluessel As Integer, ByVal RKSV_Beleg_Id As Integer, ByVal summeBRUTTO As Double, ByRef QR_CodeString As String, ByRef LastJWS As String, TEST As Boolean, ByRef answer As String) As Boolean
    '    MsgBox("123")

    '    Try



    '        ' COM-Objekt anlegen

    '        '   Dim licenseKey As String = kasse.rksv_DE_license '"07.11.2020;MEUCIQDfTvMPWQo4IVvTtuTbU9YHNwJ7EdMbogfGqmAp+rdw4gIgPJoEDE0OCfac/nCOKdksWvOZq+xvkFoYI0HFxJPkldU="
    '        '  Dim TSESerialNumber As String = "77A9D25F044A89E87578A8CD52D2A92564CC09214CC6448465414008D31C1CF1"
    '        Dim m_ksv = New ItgKsV.KsVCom()
    '        'Dim m_ksv As ItgKsV.KsVCom = New ItgKsV.KsVCom()
    '        '  Dim result As Integer = m_ksv.InitialiseLibrary("F:", "SwissbitDemo", "12345", licenseKey)

    '        MsgBox(kasse.rksv_ipAdresse & "  --- " & kasse.rksv_DE_TSE_Serial & "  --- " & kasse.rksv_DE_apiToken & "  --- " & kasse.rksv_DE_user & "  --- " & kasse.rksv_DE_pwd & "  --- " & kasse.rksv_DE_license)

    '        Dim result As Integer = m_ksv.InitialiseLibraryLan(kasse.rksv_ipAdresse, kasse.rksv_DE_TSE_Serial, kasse.rksv_DE_apiToken, kasse.rksv_DE_user, kasse.rksv_DE_pwd, kasse.rksv_DE_license) '--> ClientId/User "Admin" mit KsVCom Demo registriert

    '        If result <> &H0 Then
    '            MessageBox.Show(m_ksv.StringifyErrorCode(result), "Error", MessageBoxButtons.OK, MessageBoxIcon.[Error])
    '            Return False
    '        End If



    '        '' Setup bei erstmaliger Verwendung der Swissbit-TSE !!!

    '        'result = m_ksv.SetupTSEForFirstUse("123456", "12345", "98765", "SwissbitDemo")

    '        'If result <> &H0 Then
    '        '    MessageBox.Show(m_ksv.StringifyErrorCode(result), "Error", MessageBoxButtons.OK, MessageBoxIcon.[Error])
    '        'Else
    '        '    MessageBox.Show("TSE setup succeeded.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information)
    '        'End If



    '        ' BeginTransaction: für jede neue Rechnung wird eine Transaktion gestartet

    '        Dim transactionNumber As Long = 0
    '        result = m_ksv.StartTransaction(transactionNumber)

    '        If result <> &H0 Then
    '            MessageBox.Show(m_ksv.StringifyErrorCode(result), "Error", MessageBoxButtons.OK, MessageBoxIcon.[Error])
    '            Return False
    '        End If



    '        ' UpdateTransaction: processData bleibt leer

    '        result = m_ksv.UpdateTransaction(transactionNumber, "", "KassenBeleg-V1")

    '        If result <> &H0 Then
    '            MessageBox.Show(m_ksv.StringifyErrorCode(result), "Error", MessageBoxButtons.OK, MessageBoxIcon.[Error])
    '        End If



    '        ' FinishTransaction: Abschluss einer Rechnung, processData nach vorgegebenem Format

    '        result = m_ksv.FinishTransaction(transactionNumber, getBelegSting_BAR(summeBRUTTO, steuerSchluessel), "KassenBeleg-V1")

    '        If result <> &H0 Then
    '            MessageBox.Show(m_ksv.StringifyErrorCode(result), "Error", MessageBoxButtons.OK, MessageBoxIcon.[Error])
    '        End If



    '        ' QR-Code und weitere Werte, die auf der Rechnung angedruckt werden müssen

    '        ' QR-Code wird als base64 kodiertes bitmap geliefert

    '        Dim qrCode As String = String.Empty

    '        ' QR-Code Inhalt für die Ablage in der Datenbank, falls eine Rechnung nochmals gedruckt werden muss

    '        Dim qrCodeContent As String = String.Empty
    '        m_ksv.GetLastReceiptQrCode(qrCode)
    '        m_ksv.GetLastReceiptQrCodeContent(qrCodeContent)
    '        Dim sTransactionNumber As String = String.Empty
    '        Dim serialNumber As String = String.Empty
    '        Dim signature As String = String.Empty
    '        Dim sigCounter As String = String.Empty
    '        Dim dtStartTransaction As Date = Date.MinValue
    '        Dim dtFinishTransaction As Date = Date.MinValue
    '        m_ksv.GetLastReceiptValues(sTransactionNumber, serialNumber, signature, dtStartTransaction, dtFinishTransaction, sigCounter)

    '        QR_CodeString = qrCode
    '        LastJWS = signature
    '        '' Anzeige der gestarteten/noch möglichen Transaktionen

    '        'Dim maxTransactions As Integer = 0
    '        'Dim openTransactions As Integer = 0
    '        'm_ksv.GetMaxStartedTransactions(maxTransactions)
    '        'm_ksv.GetStartedTransactions(openTransactions)
    '        'Dim startedTransactions As Integer() = Nothing
    '        'result = m_ksv.GetStartedTransactionNumbers(startedTransactions)

    '        'If result <> &H0 Then
    '        '    MessageBox.Show(m_ksv.StringifyErrorCode(result), "Error", MessageBoxButtons.OK, MessageBoxIcon.[Error])
    '        'End If



    '        '' Export der TSE-Daten im TAR-Format

    '        'result = m_ksv.ExportAsTarFile("d:\export.tar")

    '        'If result <> 0 Then
    '        '    MessageBox.Show(m_ksv.StringifyErrorCode(result), "Error", MessageBoxButtons.OK, MessageBoxIcon.[Error])
    '        'End If



    '        '' Bibliothek aufräumen, andernfalls wird ein power-cycle der TSE erforderlich um sie wieder einsetzen zu können

    '        ''result = CSharpImpl.__Assign(,, m_ksv.CleanupLibrary())
    '        'result = m_ksv.CleanupLibrary()

    '        'If result <> 0 Then
    '        '    MessageBox.Show(m_ksv.StringifyErrorCode(result), "Error", MessageBoxButtons.OK, MessageBoxIcon.[Error])
    '        'End If



    '    Catch ex As Exception
    '        MsgBox("Es ist ein Fehler bei der Signatur aufgetreten (insertRKSV): " & vbNewLine & ex.Message & ex.StackTrace)
    '    End Try
    '    Return False
    'End Function

End Class


Public Class cRKSV_DE
    Shared SQL As New SQL



    'Shared Function getBelegSting_BAR(summeBRUTTO As Double, steuerSchluessel As Integer) As String


    '    Dim steuersatz As Double = SQL.getValueTxtBySql("SELECT isnull(tblSteuersätze.Steuersatz,0) FROM tblSteuersätze WHERE tblSteuersätze.Nr='" & steuerSchluessel & "' ", "FMZOLL")


    '    Dim BetragSatzNormal = IIf(steuersatz = 0.19, summeBRUTTO, 0.0)
    '    Dim BetragSatzErm1 = IIf(steuersatz = 0.1, summeBRUTTO, 0.0)
    '    Dim BetragSatzNull = IIf(steuersatz = 0, summeBRUTTO, 0.0)


    '    BetragSatzNormal += IIf(steuersatz = 0.16, summeBRUTTO, 0.0)
    '    BetragSatzErm1 += IIf(steuersatz = 0.05, summeBRUTTO, 0.0)
    '    BetragSatzNormal += IIf(steuersatz = 0.2, summeBRUTTO, 0.0) ' Eig Nur AT
    '    'Dim BetragSatzNormal = IIf(steuersatz = 0.2, summeBRUTTO, 0.0) 'summe
    '    'Dim BetragSatzErm2 = IIf(steuersatz = 0.13, summeBRUTTO, 0.0)
    '    'Dim BetragSatzNull = IIf(steuersatz = 0.0, summeBRUTTO, 0.0)

    '    Dim sum = BetragSatzNormal
    '    sum += BetragSatzErm1
    '    sum += BetragSatzNull
    '    MsgBox("Beleg^" & BetragSatzNormal.ToString("0.00") & "_" & BetragSatzErm1.ToString("0.00") & "_0.00_0.00_" & BetragSatzNull.ToString("0.00") & "^" & sum.ToString("0.00") & ":Bar")
    '    Return "Beleg^" & BetragSatzNormal.ToString("0.00") & "_" & BetragSatzErm1.ToString("0.00") & "_0.00_0.00_" & BetragSatzNull.ToString("0.00") & "^" & sum.ToString("0.00") & ":Bar"

    'End Function
    Shared Function stornoRKSV_DE(PERSONAL As cPersonal, BELEG As EABeleg, ByVal kasse As cRKSV_Kasse, ByVal RKSV_Beleg_Id As Integer, ByVal summeBRUTTO As Double, ByRef QR_CodeString As String, ByRef LastJWS As String, TEST As Boolean, ByRef answer As String, Optional storno As Integer = 0) As Boolean

        Return insertRKSV_DE(PERSONAL, BELEG, kasse, RKSV_Beleg_Id, summeBRUTTO, QR_CodeString, LastJWS, TEST, answer, 1)

    End Function

    Shared Function getRKSVLink(ByVal kasse As cRKSV_Kasse) As String
        Return kasse.rksv_ipAdresse
        'Return getRKSVLink(kasse.rksv_bez)
    End Function

    Shared Function insertRKSV_DE_ORIG(PERSONAL As cPersonal, BELEG As EABeleg, ByVal kasse As cRKSV_Kasse, ByVal RKSV_Beleg_Id As Integer, ByVal summeBRUTTO As Double, ByRef QR_CodeString As String, ByRef LastJWS As String, TEST As Boolean, ByRef answer As String, Optional storno As Integer = 0) As Boolean

        Try

            Dim cashbox As String = kasse.rksv_KassaGuid '"VERAG_GMBH_KASSE_01" "KASSA 001"
            'Dim endpoint = New System.ServiceModel.EndpointAddress(getRKSVLink(kasse))
            '  Dim m_com As VERAG_PROG_ALLGEMEIN.DSFinVKService.DSFinVKServerClient = New VERAG_PROG_ALLGEMEIN.DSFinVKService.DSFinVKServerClient("DSFinVKService", endpoint) '"http://ymgk028055.verag.ost.dmn:8733/DSFinVKService")

            Dim m_com As DSFinVKServerClient = New DSFinVKServerClient() 'PROBLEM??


            ' Dim [error] = "" 'm_com.InitializeLibrary(tbLicense.Text, "D:\Database\DSFinVK\dsfinvkdb.db3", "Administrator", "test", cashbox)
            Dim [error] = m_com.InitializeLibrary("SQLGUIDE01.verag.ost.dmn", "itg_RKSV_DE", "dsfinvk", "dsfinvk#1337", cashbox)

            If [error] <> VERAG_PROG_ALLGEMEIN.DSFinVKService.ErrorCode.OK Then
                MessageBox.Show([error].ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.[Error])
                Return False
            End If


            Dim BON_ID As Integer = 0
            [error] = m_com.GetNextBON_ID(cashbox, BON_ID)

            If [error] <> VERAG_PROG_ALLGEMEIN.DSFinVKService.ErrorCode.OK Then
                MessageBox.Show([error].ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.[Error])
                Return False
            End If




            'Rechnung beginnen

            Dim bonkopfBegin As VERAG_PROG_ALLGEMEIN.DSFinVKService.BonKopfBegin = New VERAG_PROG_ALLGEMEIN.DSFinVKService.BonKopfBegin()

            bonkopfBegin.Z_KASSE_ID = cashbox

            bonkopfBegin.BEDIENER_ID = VERAG_PROG_ALLGEMEIN.cAllgemein.USRID 'tbBEDIENER_ID.Text

            bonkopfBegin.BEDIENER_NAME = VERAG_PROG_ALLGEMEIN.cAllgemein.USRNAME 'tbBEDIENER_NAME.Text

            bonkopfBegin.BON_ID = BON_ID.ToString()

            bonkopfBegin.BON_NAME = "" 'tbBON_NAME.Text

            bonkopfBegin.BON_NOTIZ = "" 'tbBON_NOTIZ.Text

            bonkopfBegin.BON_NR = BON_ID

            bonkopfBegin.BON_STORNO = storno 'If(cbBON_STORNO.Checked, "1", "0")

            bonkopfBegin.BON_TYP = "Beleg" 'cmbBON_TYP.SelectedItem.ToString()

            bonkopfBegin.KUNDE_ID = "" 'tbKUNDE_ID.Text

            bonkopfBegin.KUNDE_LAND = "" 'tbKUNDE_LAND.Text

            bonkopfBegin.KUNDE_NAME = "" 'tbKUNDE_NAME.Text

            bonkopfBegin.KUNDE_ORT = "" 'tbKUNDE_ORT.Text

            bonkopfBegin.KUNDE_PLZ = "" 'tbKUNDE_PLZ.Text

            bonkopfBegin.KUNDE_STRASSE = "" ' tbKUNDE_STRASSE.Text

            bonkopfBegin.KUNDE_TYP = "" ' tbKUNDE_TYP.Text

            bonkopfBegin.KUNDE_USTID = "" ' tbKUNDE_USTID.Text

            bonkopfBegin.TERMINAL_ID = "" 'tbTERMINAL_ID.Text

            Dim transactionNumber As Integer = 0

            [error] = m_com.BeginReceipt(cashbox, bonkopfBegin, transactionNumber)

            Dim cntZeile = 1
            Dim GES_BRUTTO As Double = 0
            For Each POS In BELEG.POS

                'Bonposition hinzufügen
                Dim position As VERAG_PROG_ALLGEMEIN.DSFinVKService.BonPosition = New VERAG_PROG_ALLGEMEIN.DSFinVKService.BonPosition()

                position.AGENTUR_ID = "" 'Convert.ToInt32(dgvBonPos.Rows[m_dgvCurrentRow].Cells["AGENTUR_ID"].Value)

                position.ARTIKELTEXT = POS.LeistungsBez 'Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["ARTIKELTEXT"].Value)

                position.ART_NR = POS.LeistungsNr ' Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["ART_NR"].Value)

                position.BON_ID = Convert.ToString(BON_ID)

                position.EINHEIT = "Stk." ' Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["EINHEIT"].Value)

                position.FAKTOR = 1 ' Convert.ToDecimal(dgvBonPos.Rows[m_dgvCurrentRow].Cells["FAKTOR"].Value)

                position.GTIN = "" 'Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["GTIN"].Value)

                position.GUTSCHEIN_NR = "" 'Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["GUTSCHEIN_NR"].Value)

                position.GV_NAME = "" ' Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["GV_NAME"].Value)

                position.GV_TYP = "Umsatz" ' Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["GV_TYP"].Value)

                position.INHAUS = "" 'Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["INHAUS"].Value)

                position.MENGE = POS.Anzahl 'Convert.ToDecimal(dgvBonPos.Rows[m_dgvCurrentRow].Cells["MENGE"].Value)

                position.POS_TERMINAL_ID = "" 'Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["POS_TERMINAL_ID"].Value)

                position.POS_ZEILE = cntZeile 'Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["POS_ZEILE"].Value)

                position.P_STORNO = storno ' Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["P_STORNO"].Value)

                position.STK_BR = POS.Preis 'Convert.ToDecimal(dgvBonPos.Rows[m_dgvCurrentRow].Cells["STK_BR"].Value)

                position.WARENGR = "" 'Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["WARENGR"].Value)

                position.WARENGR_ID = "" 'Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["WARENGR_ID"].Value)

                position.Z_KASSE_ID = cashbox 'Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["Z_KASSE_ID"].Value)

                ' Beträge der Position

                Dim position_vat = New VERAG_PROG_ALLGEMEIN.DSFinVKService.BonPosition_Ust()

                position_vat.BON_ID = position.BON_ID

                position_vat.POS_ZEILE = position.POS_ZEILE

                Dim steuersatzID = 1
                Dim steuersatz As Double = SQL.getValueTxtBySql("SELECT [Steuersatz] FROM [tblSteuersätze] where nr='" & BELEG.Steuerschlüssel & "'", "FMZOLL")
                Select Case steuersatz
                    Case 0.19 : steuersatzID = 1
                    Case 0.07 : steuersatzID = 2
                    Case 0.00 : steuersatzID = 6
                End Select

                position_vat.UST_SCHLUESSEL = steuersatzID 'm_com.GetTaxIds(cashbox,)   'Convert.ToInt32(dgvBonPos.Rows[m_dgvCurrentRow].Cells["UST_SCHLUESSEL"].Value)
                Dim steuerBetrag = POS.Betrag * position_vat.UST_SCHLUESSEL
                position_vat.POS_BRUTTO = POS.Betrag + steuerBetrag 'Convert.ToDecimal(dgvBonPos.Rows[m_dgvCurrentRow].Cells["POS_BRUTTO"].Value)

                position_vat.POS_NETTO = POS.Betrag 'Convert.ToDecimal(dgvBonPos.Rows[m_dgvCurrentRow].Cells["POS_NETTO"].Value)

                position_vat.POS_UST = steuerBetrag 'Convert.ToDecimal(dgvBonPos.Rows[m_dgvCurrentRow].Cells["POS_UST"].Value)

                [error] = m_com.AddPositionToReceipt(cashbox, position, position_vat, transactionNumber)
                cntZeile += 1
                GES_BRUTTO += position_vat.POS_BRUTTO

            Next

            'Rechnung abschließen

            Dim bonkopfFinish As VERAG_PROG_ALLGEMEIN.DSFinVKService.BonKopfFinish = New VERAG_PROG_ALLGEMEIN.DSFinVKService.BonKopfFinish()

            bonkopfFinish.Z_KASSE_ID = cashbox

            bonkopfFinish.BON_ID = BON_ID



            If Not Decimal.TryParse(GES_BRUTTO, bonkopfFinish.UMS_BRUTTO) Then
                bonkopfFinish.UMS_BRUTTO = 0.00
            End If


            bonkopfFinish.PROCESS_TYPE = "Kassenbeleg-V1"

            bonkopfFinish.payment_currencies = {"EUR"}

            bonkopfFinish.payment_types = {"Bar"}

            bonkopfFinish.payment_per_currency = {119.0}

            [error] = m_com.FinishReceipt(cashbox, bonkopfFinish, transactionNumber)

            ' Kassenabschluss anlegen über alle noch nicht abgeschlossenen Rechnungen zu dieser Kasse

            ' Error = m_com.CreateCashpointClosing(cashbox)

            '            ' DSFinV-K-Export

            '            Int from = 0

            'Int to = 10

            'Dim ret = m_com.ExportCSVFiles(from, to, tbSelectedFolder.Text, tbZipName.Text, True, True,

            'true, true, true, true, true, true,

            'true, true, true, true,

            'true, true, true, true, true,

            'true, true, true);

            'If (ret == ErrorCode.OK) Then

            '{

            'MessageBox.Show("Die CSV Dateien wurden im Ordner " + tbSelectedFolder.Text + " angelegt und in die Zip-Datei " + tbZipName.Text + " gepackt.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);

            '}

            'Else

            '{

            'MessageBox.Show("Beim exportieren der CSV-Dateien ging etwas schief:\r\n" + ret.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

            '}

            Dim transactionNumberRet As String
            Dim serialNumber As String
            Dim signature As String
            Dim transactionStart As Date
            Dim transactionFinish As Date
            Dim sigCounter As String
            m_com.GetLastReceiptValues(cashbox, transactionNumberRet, serialNumber, signature, transactionStart, transactionFinish, sigCounter)


            Dim qrCode As String = String.Empty
            Dim mimeType As String = String.Empty
            m_com.GetLastReceiptQrCode(cashbox, qrCode, mimeType)


            QR_CodeString = qrCode
            LastJWS = signature



        Catch ex As Exception
            MsgBox("Es ist ein Fehler bei der Signatur aufgetreten (insertRKSV): " & vbNewLine & ex.Message & ex.StackTrace)
        End Try
        Return False
    End Function

    Shared Function insertRKSV_DE(PERSONAL As cPersonal, BELEG As EABeleg, ByVal kasse As cRKSV_Kasse, ByVal RKSV_Beleg_Id As Integer, ByVal summeBRUTTO As Double, ByRef QR_CodeString As String, ByRef LastJWS As String, TEST As Boolean, ByRef answer As String, Optional storno As Integer = 0) As Boolean

        Try

            ' MsgBox("0: ")
            Dim cashbox As String = kasse.rksv_KassaGuid '"VERAG_GMBH_KASSE_01" "KASSA 001"
            'Dim endpoint = New System.ServiceModel.EndpointAddress(getRKSVLink(kasse))
            '  Dim m_com As VERAG_PROG_ALLGEMEIN.DSFinVKService.DSFinVKServerClient = New VERAG_PROG_ALLGEMEIN.DSFinVKService.DSFinVKServerClient("DSFinVKService", endpoint) '"http://ymgk028055.verag.ost.dmn:8733/DSFinVKService")

            Dim m_com As VERAG_PROG_ALLGEMEIN.RKSV_DE_DSFinVKService.DSFinVKServer = New VERAG_PROG_ALLGEMEIN.RKSV_DE_DSFinVKService.DSFinVKServer() 'PROBLEM??
            m_com.Url = "http://ymgk028055.verag.ost.dmn:8733/DSFinVKService"
            Dim [error] As VERAG_PROG_ALLGEMEIN.RKSV_DE_DSFinVKService.ErrorCode
            Dim InitializeLibraryResultSpecified As Boolean
            '     Dim [error] = "" 'm_com.InitializeLibrary(tbLicense.Text, "D:\Database\DSFinVK\dsfinvkdb.db3", "Administrator", "test", cashbox)
            m_com.InitializeLibrary("SQLGUIDE01.verag.ost.dmn", "itg_RKSV_DE", "dsfinvk", "dsfinvk#1337", cashbox, [error], InitializeLibraryResultSpecified)

            '   MsgBox("1: " & [error])

            If [error] <> VERAG_PROG_ALLGEMEIN.DSFinVKService.ErrorCode.OK Then
                If [error].ToString() <> "CASHBOX_ALREADY_MANAGED" Then '--> CASHBOX_ALREADY_MANAGED --> der Fehler darf auftreten, die Cashbox wird Serverseitig initialisert, hier nur der Versuch, falls das nciht geschehen ist... lt. Jan Mika / AITG
                    MessageBox.Show([error].ToString(), "Error1", MessageBoxButtons.OK, MessageBoxIcon.[Error])
                    Return False
                End If
            End If

            ' MsgBox("2")



            'BelegNr wird von RKSV übernommen
            Dim BON_ID As Integer = 0
            If False Then

                Dim BON_IDSpecified = False
                Dim GetNextBON_IDResultSpecified = False
                m_com.GetNextBON_ID(cashbox, BON_ID, BON_IDSpecified, [error], GetNextBON_IDResultSpecified)
                '  MsgBox("3: " & [error])

                If [error] <> VERAG_PROG_ALLGEMEIN.DSFinVKService.ErrorCode.OK Then
                    MessageBox.Show([error].ToString(), "Error2", MessageBoxButtons.OK, MessageBoxIcon.[Error])
                    Return False
                End If
            Else
                '  MsgBox(RKSV_Beleg_Id)
                BON_ID = RKSV_Beleg_Id
            End If


            'Dim BON_NR As Integer = 0
            '[error] = m_com.GetNextBON_NR(cashbox, BON_NR)

            'If [error] <> VERAG_PROG_ALLGEMEIN.DSFinVKService.ErrorCode.OK Then
            '    MessageBox.Show([error].ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.[Error])
            '    Return False
            'End If
            '  MsgBox("4")


            '-------------------------------------------------------------------------------------
            '--------------------------------- Rechnung beginnen ---------------------------------
            '-------------------------------------------------------------------------------------

            Dim bonkopfBegin As VERAG_PROG_ALLGEMEIN.RKSV_DE_DSFinVKService.BonKopfBegin = New VERAG_PROG_ALLGEMEIN.RKSV_DE_DSFinVKService.BonKopfBegin()

            bonkopfBegin.Z_KASSE_ID = cashbox

            bonkopfBegin.BEDIENER_ID = VERAG_PROG_ALLGEMEIN.cAllgemein.USRID 'tbBEDIENER_ID.Text

            bonkopfBegin.BEDIENER_NAME = VERAG_PROG_ALLGEMEIN.cAllgemein.USRNAME 'tbBEDIENER_NAME.Text

            bonkopfBegin.BON_ID = BON_ID.ToString()

            bonkopfBegin.BON_NAME = "" 'tbBON_NAME.Text

            bonkopfBegin.BON_NOTIZ = "" 'tbBON_NOTIZ.Text

            bonkopfBegin.BON_NR = bonkopfBegin.BON_ID

            bonkopfBegin.BON_STORNO = storno 'If(cbBON_STORNO.Checked, "1", "0")

            bonkopfBegin.BON_TYP = "Beleg" 'cmbBON_TYP.SelectedItem.ToString()

            bonkopfBegin.KUNDE_ID = If(BELEG.KundenNr > 0, BELEG.KundenNr, "") 'tbKUNDE_ID.Text

            bonkopfBegin.KUNDE_LAND = If(BELEG.LandKz, "") 'tbKUNDE_LAND.Text

            bonkopfBegin.KUNDE_NAME = If(BELEG.Frachtführer, "") 'tbKUNDE_NAME.Text

            bonkopfBegin.KUNDE_ORT = If(BELEG.Ort, "") 'tbKUNDE_ORT.Text

            bonkopfBegin.KUNDE_PLZ = If(BELEG.PLZ, "") 'tbKUNDE_PLZ.Text

            bonkopfBegin.KUNDE_STRASSE = If(BELEG.Straße, "") ' tbKUNDE_STRASSE.Text

            bonkopfBegin.KUNDE_TYP = "" ' tbKUNDE_TYP.Text

            bonkopfBegin.KUNDE_USTID = If(BELEG.UstIdKz, "") & If(BELEG.UstIdNr, "") ' tbKUNDE_USTID.Text

            bonkopfBegin.TERMINAL_ID = "" 'tbTERMINAL_ID.Text

            Dim transactionNumber As Integer = 0
            Dim transactionNumberSpecified As Boolean

            Dim BeginReceiptResultSpecified As Boolean
            m_com.BeginReceipt(cashbox, bonkopfBegin, transactionNumber, transactionNumberSpecified, [error], BeginReceiptResultSpecified)

            If [error] <> VERAG_PROG_ALLGEMEIN.DSFinVKService.ErrorCode.OK Then
                MessageBox.Show([error].ToString(), "Error3", MessageBoxButtons.OK, MessageBoxIcon.[Error])
                Return False
            End If

            '    MsgBox("5 ANZ: " & BELEG.POS.Count)
            Dim cntZeile = 1
            Dim GES_BRUTTO As Double = 0
            For Each POS In BELEG.POS

                'Bonposition hinzufügen
                Dim position As VERAG_PROG_ALLGEMEIN.RKSV_DE_DSFinVKService.BonPosition = New VERAG_PROG_ALLGEMEIN.RKSV_DE_DSFinVKService.BonPosition()

                position.AGENTUR_ID = -1 'Convert.ToInt32(dgvBonPos.Rows[m_dgvCurrentRow].Cells["AGENTUR_ID"].Value)

                position.ARTIKELTEXT = POS.LeistungsBez 'Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["ARTIKELTEXT"].Value)

                position.ART_NR = POS.LeistungsNr ' Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["ART_NR"].Value)

                position.BON_ID = Convert.ToString(BON_ID)

                position.EINHEIT = "Stk." ' Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["EINHEIT"].Value)

                position.FAKTOR = 1 ' Convert.ToDecimal(dgvBonPos.Rows[m_dgvCurrentRow].Cells["FAKTOR"].Value)

                position.GTIN = "" 'Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["GTIN"].Value)

                position.GUTSCHEIN_NR = "" 'Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["GUTSCHEIN_NR"].Value)

                position.GV_NAME = "" ' Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["GV_NAME"].Value)

                position.GV_TYP = "Umsatz" ' Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["GV_TYP"].Value)

                position.INHAUS = "" 'Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["INHAUS"].Value)

                position.MENGE = POS.Anzahl 'Convert.ToDecimal(dgvBonPos.Rows[m_dgvCurrentRow].Cells["MENGE"].Value)

                position.POS_TERMINAL_ID = "" 'Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["POS_TERMINAL_ID"].Value)

                position.POS_ZEILE = cntZeile 'Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["POS_ZEILE"].Value)

                position.P_STORNO = storno ' Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["P_STORNO"].Value)

                position.STK_BR = POS.Preis 'Convert.ToDecimal(dgvBonPos.Rows[m_dgvCurrentRow].Cells["STK_BR"].Value)

                position.WARENGR = "" 'Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["WARENGR"].Value)

                position.WARENGR_ID = "" 'Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["WARENGR_ID"].Value)

                position.Z_KASSE_ID = cashbox 'Convert.ToString(dgvBonPos.Rows[m_dgvCurrentRow].Cells["Z_KASSE_ID"].Value)

                ' Beträge der Position

                Dim position_vat = New VERAG_PROG_ALLGEMEIN.RKSV_DE_DSFinVKService.BonPosition_Ust()

                position_vat.BON_ID = position.BON_ID

                position_vat.POS_ZEILE = position.POS_ZEILE

                Dim steuersatzID = 1
                Dim steuersatz As Double = SQL.getValueTxtBySql("SELECT [Steuersatz] FROM [tblSteuersätze] where nr='" & BELEG.Steuerschlüssel & "'", "FMZOLL")
                Select Case steuersatz
                    Case 0.19 : steuersatzID = 1
                    Case 0.07 : steuersatzID = 2
                    Case 0.00 : steuersatzID = 6
                End Select
                '  MsgBox(POS.Anzahl)
                '  MsgBox(POS.Betrag)

                position_vat.UST_SCHLUESSEL = steuersatzID 'm_com.GetTaxIds(cashbox,)   'Convert.ToInt32(dgvBonPos.Rows[m_dgvCurrentRow].Cells["UST_SCHLUESSEL"].Value)
                Dim steuerBetrag As Double = POS.Betrag * steuersatz
                position_vat.POS_BRUTTO = Convert.ToDecimal(POS.Betrag + steuerBetrag) 'Convert.ToDecimal(dgvBonPos.Rows[m_dgvCurrentRow].Cells["POS_BRUTTO"].Value)
                position_vat.POS_NETTO = Convert.ToDecimal(POS.Betrag) 'Convert.ToDecimal(dgvBonPos.Rows[m_dgvCurrentRow].Cells["POS_NETTO"].Value)

                position_vat.POS_UST = Convert.ToDecimal(steuerBetrag) 'Convert.ToDecimal(dgvBonPos.Rows[m_dgvCurrentRow].Cells["POS_UST"].Value)

                Dim AddPositionToReceiptResultSpecified As Boolean
                m_com.AddPositionToReceipt(cashbox, position, position_vat, transactionNumber, transactionNumberSpecified, [error], AddPositionToReceiptResultSpecified)
                cntZeile += 1
                GES_BRUTTO += position_vat.POS_BRUTTO

            Next
            ' MsgBox("6: " & GES_BRUTTO)

            If [error] <> VERAG_PROG_ALLGEMEIN.DSFinVKService.ErrorCode.OK Then
                MessageBox.Show([error].ToString(), "Error4", MessageBoxButtons.OK, MessageBoxIcon.[Error])
                Return False
            End If

            'Rechnung abschließen

            Dim bonkopfFinish As VERAG_PROG_ALLGEMEIN.RKSV_DE_DSFinVKService.BonKopfFinish = New VERAG_PROG_ALLGEMEIN.RKSV_DE_DSFinVKService.BonKopfFinish()

            bonkopfFinish.Z_KASSE_ID = cashbox

            bonkopfFinish.BON_ID = BON_ID

            Try
                bonkopfFinish.UMS_BRUTTO = Convert.ToDecimal(GES_BRUTTO)
            Catch ex As Exception
                bonkopfFinish.UMS_BRUTTO = 0.00
            End Try

            'If Not Decimal.TryParse(GES_BRUTTO, bonkopfFinish.UMS_BRUTTO) Then
            '    bonkopfFinish.UMS_BRUTTO = 0.00
            'End If


            bonkopfFinish.PROCESS_TYPE = "Kassenbeleg-V1"

            bonkopfFinish.payment_currencies = {"EUR"}

            bonkopfFinish.payment_types = {"Bar"}

            bonkopfFinish.payment_per_currency = {GES_BRUTTO} '{0.0} 'BETRAG"!!!!!!!!!!!!

            ' MsgBox("6,1: ")

            Dim FinishReceiptResult As Boolean = True
            Dim FinishReceiptResultSpecified As Boolean
            m_com.FinishReceipt(cashbox, bonkopfFinish, transactionNumber, FinishReceiptResult, [error], FinishReceiptResultSpecified)
            '   MsgBox("6,2: ")

            If [error] <> VERAG_PROG_ALLGEMEIN.DSFinVKService.ErrorCode.OK Then
                MessageBox.Show([error].ToString(), "Error5", MessageBoxButtons.OK, MessageBoxIcon.[Error])
                Return False
            End If
            ' Kassenabschluss anlegen über alle noch nicht abgeschlossenen Rechnungen zu dieser Kasse

            ' Error = m_com.CreateCashpointClosing(cashbox)

            '            ' DSFinV-K-Export

            '            Int from = 0

            'Int to = 10

            'Dim ret = m_com.ExportCSVFiles(from, to, tbSelectedFolder.Text, tbZipName.Text, True, True,

            'true, true, true, true, true, true,

            'true, true, true, true,

            'true, true, true, true, true,

            'true, true, true);

            'If (ret == ErrorCode.OK) Then

            '{

            'MessageBox.Show("Die CSV Dateien wurden im Ordner " + tbSelectedFolder.Text + " angelegt und in die Zip-Datei " + tbZipName.Text + " gepackt.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);

            '}

            'Else

            '{

            'MessageBox.Show("Beim exportieren der CSV-Dateien ging etwas schief:\r\n" + ret.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

            '}
            ' MsgBox("7")

            Dim transactionNumberRet As String
            Dim serialNumber As String
            Dim signature As String
            Dim transactionStart As Date
            Dim transactionFinish As Date
            Dim sigCounter As String
            Dim transactionStartSpecified As Boolean
            Dim transactionFinishSpecified As Boolean
            Dim GetLastReceiptValuesResultSpecified As Boolean
            '
            m_com.GetLastReceiptValues(cashbox, transactionNumberRet, serialNumber, signature, transactionStart, transactionStartSpecified, transactionFinish, transactionFinishSpecified, sigCounter, [error], GetLastReceiptValuesResultSpecified)

            '   MsgBox("8")

            Dim qrCode As String = String.Empty
            Dim mimeType As String = String.Empty
            Dim GetLastReceiptQrCodeResult As Boolean
            Dim GetLastReceiptQrCodeResultSpecified As Boolean
            m_com.GetLastReceiptQrCode(cashbox, qrCode, mimeType, GetLastReceiptQrCodeResult, GetLastReceiptQrCodeResultSpecified)

            QR_CodeString = qrCode
            LastJWS = signature


            '  MsgBox("9")
            If QR_CodeString.Length > 50 And LastJWS.Length > 50 Then
                Return True
            End If
        Catch ex As Exception
            MsgBox("Es ist ein Fehler bei der Signatur aufgetreten (insertRKSV): " & vbNewLine & ex.Message & ex.StackTrace)
        End Try
        Return False
    End Function

    'Shared Function insertRKSV_DE(ByVal kasse As cRKSV_Kasse, CompanyGUID As String, ByVal umsatzZaehler As Double, ByVal belegDat As DateTime, ByVal steuerSchluessel As Integer, ByVal RKSV_Beleg_Id As Integer, ByVal summeBRUTTO As Double, ByRef QR_CodeString As String, ByRef LastJWS As String, TEST As Boolean, ByRef answer As String) As Boolean

    '    Try
    '        Dim xCom As New VERAG_PROG_ALLGEMEIN.RKSV_DE.DSFinVKServerClient
    '        Dim ret As Long
    '        Dim bonkopfBegin As New VERAG_PROG_ALLGEMEIN.RKSV_DE.BonKopfBegin
    '        Dim bonkopfFinish As New VERAG_PROG_ALLGEMEIN.RKSV_DE.BonKopfFinish
    '        Dim bonpos As New VERAG_PROG_ALLGEMEIN.RKSV_DE.BonPosition
    '        Dim bonpos_ust As New VERAG_PROG_ALLGEMEIN.RKSV_DE.BonPosition_Ust

    '        Dim transactionNumber As Long
    '        Dim bonId As Long
    '        Dim bonNr As Long
    '        Dim poszeile As Integer

    '        ' zwingend erforderliche Felder:


    '        Dim tbCashbox = kasse.rksv_KassaGuid ' VERAG_GMBH_KASSE_01
    '        bonkopfBegin.Z_KASSE_ID = tbCashbox
    '        bonkopfBegin.BON_ID = bonId
    '        bonkopfBegin.BON_NR = bonId
    '        bonkopfBegin.BON_TYP = "Beleg" 'tbBonTyp
    '        bonkopfBegin.BON_NAME = "" 'tbBonName

    '        bonkopfBegin.BON_STORNO = "0"
    '        bonkopfBegin.BEDIENER_ID = VERAG_PROG_ALLGEMEIN.cAllgemein.USRID 'tbBedienerId
    '        bonkopfBegin.BEDIENER_NAME = VERAG_PROG_ALLGEMEIN.cAllgemein.USRNAME ' tbBedienerName



    '        Dim tbBonStart = Format(Now(), "yyyy-mm-ddThh:MM:ss")



    '        poszeile = 1



    '    bonkopfBegin.BON_START = tbBonStart

    '    ' optionale Felder:



    '    ' bonkopfBegin.KUNDE_NAME = tbKundeName

    '    ' bonkopfBegin.KUNDE_ID = tbKundeId

    '    ' bonkopfBegin.KUNDE_TYP = tbKundeTyp

    '    ' bonkopfBegin.KUNDE_USTID = tbKundeUstId

    '    ' bonkopfBegin.KUNDE_STRASSE = tbKundeStrasse

    '    ' bonkopfBegin.KUNDE_PLZ = tbKundePlz

    '    ' bonkopfBegin.KUNDE_ORT = tbKundeOrt

    '    ' bonkopfBegin.KUNDE_LAND = tbKundeLand



    '    ret = xCom.BeginReceipt(tbCashbox, bonkopfBegin, transactionNumber)

    '    If ret <> 0 Then

    '        MsgBox("Es ist ein Fehler aufgetreten! ErrorCode = " + Str$(ret))

    '    Else

    '        tbTransNr = transactionNumber

    '    End If






    '    Dim qrCode As String = String.Empty

    '        ' QR-Code Inhalt für die Ablage in der Datenbank, falls eine Rechnung nochmals gedruckt werden muss

    '        Dim qrCodeContent As String = String.Empty
    '        m_ksv.GetLastReceiptQrCode(qrCode)
    '        m_ksv.GetLastReceiptQrCodeContent(qrCodeContent)
    '        Dim sTransactionNumber As String = String.Empty
    '        Dim serialNumber As String = String.Empty
    '        Dim signature As String = String.Empty
    '        Dim sigCounter As String = String.Empty
    '        Dim dtStartTransaction As Date = Date.MinValue
    '        Dim dtFinishTransaction As Date = Date.MinValue
    '        m_ksv.GetLastReceiptValues(sTransactionNumber, serialNumber, signature, dtStartTransaction, dtFinishTransaction, sigCounter)

    '        QR_CodeString = qrCode
    '        LastJWS = signature
    '        '' Anzeige der gestarteten/noch möglichen Transaktionen

    '        'Dim maxTransactions As Integer = 0
    '        'Dim openTransactions As Integer = 0
    '        'm_ksv.GetMaxStartedTransactions(maxTransactions)
    '        'm_ksv.GetStartedTransactions(openTransactions)
    '        'Dim startedTransactions As Integer() = Nothing
    '        'result = m_ksv.GetStartedTransactionNumbers(startedTransactions)

    '        'If result <> &H0 Then
    '        '    MessageBox.Show(m_ksv.StringifyErrorCode(result), "Error", MessageBoxButtons.OK, MessageBoxIcon.[Error])
    '        'End If



    '        '' Export der TSE-Daten im TAR-Format

    '        'result = m_ksv.ExportAsTarFile("d:\export.tar")

    '        'If result <> 0 Then
    '        '    MessageBox.Show(m_ksv.StringifyErrorCode(result), "Error", MessageBoxButtons.OK, MessageBoxIcon.[Error])
    '        'End If



    '        '' Bibliothek aufräumen, andernfalls wird ein power-cycle der TSE erforderlich um sie wieder einsetzen zu können

    '        ''result = CSharpImpl.__Assign(,, m_ksv.CleanupLibrary())
    '        'result = m_ksv.CleanupLibrary()

    '        'If result <> 0 Then
    '        '    MessageBox.Show(m_ksv.StringifyErrorCode(result), "Error", MessageBoxButtons.OK, MessageBoxIcon.[Error])
    '        'End If



    '    Catch ex As Exception
    '        MsgBox("Es ist ein Fehler bei der Signatur aufgetreten (insertRKSV): " & vbNewLine & ex.Message & ex.StackTrace)
    '    End Try
    '    Return False
    'End Function

End Class