Imports System.Data.OleDb
Imports System.IO
Imports System.Net
Imports System.Net.Security
Imports System.Security.Cryptography.X509Certificates
Imports System.Text
Imports System.Threading
Imports System.Xml
Imports com.sun.org.apache.xpath.internal.operations
Imports iTextSharp.text
Imports javax
Imports MDM_Worker
Imports Renci.SshNet
Imports VERAG_PROG_ALLGEMEIN
Imports VERAG_PROG_ALLGEMEIN.cAllgemein
Imports VERAG_PROG_ALLGEMEIN.cTelotecAPI

Public Class frmStartOptions
    Dim WithEvents timer As New System.Windows.Forms.Timer

    Private Sub lklAufschubkontenATLASEZOLL_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles lklAufschubkontenATLASEZOLL.LinkClicked, LinkLabel3.LinkClicked
        Dim f As New frmRoutineManager("AUFSCHUB", True, cbxHistory.Checked)
        Me.Visible = False
        f.ShowDialog()
        Me.Visible = True
        Me.BringToFront()
        ' AddHandler f.FormClosed, AddressOf closeMe
    End Sub

    Private Sub btn_Click(sender As Object, e As EventArgs) Handles btn.Click
        Me.Close()
    End Sub

    Private Sub LinkLabel1_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked
        Dim f As New frmRoutineManager("BRG", True, cbxHistory.Checked)
        Me.Visible = False
        f.ShowDialog()
        Me.Visible = True
        Me.BringToFront()
        'AddHandler f.FormClosed, AddressOf closeMe
    End Sub


    Sub closeMe()
        Me.Close()
        Application.Exit()
    End Sub

    Private Sub frmStartOptions_Load(sender As Object, e As EventArgs) Handles Me.Load
        timer.Interval = 2500


        VERAG_PROG_ALLGEMEIN.cAllgemein.PROGNAME = "ROUTINE_MANAGER"
        VERAG_PROG_ALLGEMEIN.cAllgemein.PROGID = 17

        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False

        MyComboBox1.Items.Clear()
        MyComboBox1.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("DAKOSY", "DY"))
        MyComboBox1.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("TELEOTEC", "TC"))
        MyComboBox1.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("DHF", "DHF"))

        MyComboBox2.Items.Clear()
        MyComboBox2.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("DAKOSY", "DY"))
        MyComboBox2.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("TELEOTEC", "TC"))
        MyComboBox2.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("DHF", "DHF"))

        cboBMDUnispedFirma.Items.Clear()
        cboBMDUnispedFirma.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("", ""))
        cboBMDUnispedFirma.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("UNISPED Österreich", "21"))
        cboBMDUnispedFirma.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("UNISPED Deutschland", "22"))
        cboBMDUnispedFirma.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("UNISPED Zollservice (AT)", "23"))
        cboBMDUnispedFirma.changeItem("")

        cboSYSKAFirma.Items.Clear()
        cboSYSKAFirma.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("", ""))
        cboSYSKAFirma.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("VERAG Spedition AG", "1"))
        cboSYSKAFirma.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("VERAG Spedition AG (DE)", "4"))
        cboSYSKAFirma.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("VERAG Customs Service GmbH", "11"))
        cboSYSKAFirma.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("ATILLA Spedition GmbH", "7"))
        cboSYSKAFirma.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("Front-Office Suben eG", "17"))
        cboSYSKAFirma.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("VERAG 360 GmbH", "19"))
        cboSYSKAFirma.changeItem("")

        cbxRMC.Items.Clear()
        cbxRMC.fillWithSQL("SELECT api_program FROM tblAPIEinstellungen WHERE api_program like 'RMC%'", False, "ADMIN", True)
        cbxRMC.changeItem("")

        txtUTAYear.Text = Now.Year
        txtIDSYear.Text = Now.Year
        txtGJ_UNISPED.Text = Now.Year
        txtUTADate.Text = Today.ToShortDateString


        MyTextBox5._value = Today.AddDays(-7).ToShortDateString

        txtEZOLLAnhDat._value = Now.ToShortDateString

        Dim Paramslist As New cParameterList(VERAG_PROG_ALLGEMEIN.cAllgemein.PROGID)

        cbxIDSalt.Checked = Paramslist.GET_PARAMETER_VALUE_BOOL("Schnittstelle_IDS_alt")
        cbxIDSneu.Checked = Paramslist.GET_PARAMETER_VALUE_BOOL("Schnittstelle_IDS_neu")
        cbxMSEalt.Checked = Paramslist.GET_PARAMETER_VALUE_BOOL("Schnittstelle_MSE_alt")
        cbxMSEneu.Checked = Paramslist.GET_PARAMETER_VALUE_BOOL("Schnittstelle_MSE_neu")
        cbxPlose.Checked = Paramslist.GET_PARAMETER_VALUE_BOOL("Schnittstelle_PLOSE")
        cbxPloseNeu.Checked = Paramslist.GET_PARAMETER_VALUE_BOOL("Schnittstelle_PLOSE_NEU")
        cbxITalt.Checked = Paramslist.GET_PARAMETER_VALUE_BOOL("Schnittstelle_IT")
        cbxUTAalt.Checked = Paramslist.GET_PARAMETER_VALUE_BOOL("Schnittstelle_UTA_alt")
        cbxUTANeu.Checked = Paramslist.GET_PARAMETER_VALUE_BOOL("Schnittstelle_UTA_neu")
        cbxGestellungspeichern.Checked = Paramslist.GET_PARAMETER_VALUE_BOOL("Gestellung_erstellen")
        cbxVW_Infomail.Checked = Paramslist.GET_PARAMETER_VALUE_BOOL("Gestellung_erstellen_Infomail")
        cbxGESTELLUNG_TESTLAUF.Checked = Paramslist.GET_PARAMETER_VALUE_BOOL("Gestellung_TESTLAUF")
        cbxPlose_TRNewFormat.Checked = Paramslist.GET_PARAMETER_VALUE_BOOL("PLOSE_TR_newFormat")
        cbxPlose_INVNewFormat.Checked = Paramslist.GET_PARAMETER_VALUE_BOOL("PLOSE_INV_newFormat")


        Dim PARAM = "" 'INSERT_BENACHRICHTIGUNG_VERMERKE_TEAMS

        PARAM = ""

        Dim parameter() As String = Environment.GetCommandLineArgs().ToArray
        If (parameter.Count - 1) >= 1 Then 'Höher als 1 weil der index 0 der Pfad zum programm ist
            PARAM = parameter(1)
            'For i = 1 To parameter.Count - 1
            ' 'If parameter(i) = "HISTORY" Then PARAM = True
            ' Next
        End If

        'doIDSPlatts()
        'Exit Sub
        datTranscodeVon._value = Now.Date.AddDays(-1).ToShortDateString
        datTranscodeBis._value = Now.Date.ToShortDateString

        'Standart-Errorverhalten ist MAIL
        VERAG_PROG_ALLGEMEIN.cAllgemein.ERR_OP_GLOBAL = VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL

        If VERAG_PROG_ALLGEMEIN.cAllgemein.SQLGUIDE01_USED Then
            lblRoutineManager.Text &= " UNLEASHED"
        End If

        If PARAM <> "" Then
            'LOG
        End If
        Select Case PARAM
            Case "BRG_AUFSCHUB"
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                Dim f As New frmRoutineManager("ALL", True)
                '  Me.Visible = False
                f.Show()
                AddHandler f.FormClosed, AddressOf closeMe
            Case "BRG_AUFSCHUB_HISTORY"
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                Dim f As New frmRoutineManager("ALL", True, True)
                ' Me.Visible = False
                f.Show()
                AddHandler f.FormClosed, AddressOf closeMe

            Case "DY_EINARBEITUNG"
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = True
                Dim f As New frmDYNachrichtenVerarbeitung(True)
                f.saveVerwahrung = cbxGestellungspeichern.Checked
                f.sendMail = cbxVW_Infomail.Checked
                f.GESTELLUNG_TESTLAUF = cbxGESTELLUNG_TESTLAUF.Checked
                'Me.Visible = False ' irgend ein Grund
                f.Show()
                AddHandler f.FormClosed, AddressOf closeMe
            Case "DY_EINARBEITUNG_PROD"
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                Dim f As New frmDYNachrichtenVerarbeitung(True)
                f.saveVerwahrung = cbxGestellungspeichern.Checked
                f.sendMail = cbxVW_Infomail.Checked
                f.GESTELLUNG_TESTLAUF = cbxGESTELLUNG_TESTLAUF.Checked
                ' Me.Visible = False ' irgend ein Grund
                f.Show()
                AddHandler f.EV_FINISHED, AddressOf closeMe
                AddHandler f.FormClosed, AddressOf closeMe

            Case "NCTSTR_EINARBEITUNG_TEST"
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = True
                Dim f As New frmTRNCTS_NachrichtenVerarbeitung(True)
                '  Me.Visible = False
                f.Show()
                AddHandler f.FormClosed, AddressOf closeMe
            Case "NCTSTR_EINARBEITUNG_PROD"
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                Dim f As New frmTRNCTS_NachrichtenVerarbeitung(True)
                ' Me.Visible = False
                f.Show()
                AddHandler f.FormClosed, AddressOf closeMe

            Case "NCTSTR_EINARBEITUNG_OREGON_TEST"
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = True
                Dim f As New frmTRNCTS_NachrichtenVerarbeitung_OREGON(True)
                ' Me.Visible = False
                f.Show()
                AddHandler f.FormClosed, AddressOf closeMe
            Case "NCTSTR_EINARBEITUNG_OREGON_PROD"
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                Dim f As New frmTRNCTS_NachrichtenVerarbeitung_OREGON(True)
                ' Me.Visible = False
                f.Show()
                AddHandler f.FormClosed, AddressOf closeMe


            Case "NCTSTR_EINARBEITUNG_ATEZ_TEST"
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = True
                Dim f As New frmTRNCTS_NachrichtenVerarbeitung_ATEZ(True)
                ' Me.Visible = False
                f.Show()
                AddHandler f.FormClosed, AddressOf closeMe

            Case "NCTSTR_EINARBEITUNG_ATEZ_PROD"
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                Dim f As New frmTRNCTS_NachrichtenVerarbeitung_ATEZ(True)
                ' Me.Visible = False
                f.Show()
                AddHandler f.FormClosed, AddressOf closeMe


            Case "UPDATE_SMS"
                Dim f As New frmInfo(PARAM)
                f.Show()
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "VERAG"
                UPDATE_SMS()
                closeMe()
            Case "DY_EINARBEITUNG_UNISPED"
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "UNISPED"
                Dim f As New frmDYNachrichtenVerarbeitung(True)
                f.saveVerwahrung = cbxGestellungspeichern.Checked
                f.sendMail = cbxVW_Infomail.Checked
                ' Me.Visible = False
                f.Show()
                AddHandler f.EV_FINISHED, AddressOf closeMe
                AddHandler f.FormClosed, AddressOf closeMe

            Case "MDM_EINARBEITUNG"
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                Dim f As New frmMDMNachrichtenVerarbeitung(True)
                f.newFormatTR = cbxPlose_TRNewFormat.Checked
                f.newFormatINV = cbxPlose_INVNewFormat.Checked
                ' Me.Visible = False
                f.Show()
                AddHandler f.FormClosed, AddressOf closeMe
                setInvoiceBackToCustomer("PLOSE", False)
            Case "TC_EINARBEITUNG"
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = True
                Dim f As New frmTCNachrichtenVerarbeitung(True)
                '  Me.Visible = False
                f.Show()
                AddHandler f.FormClosed, AddressOf closeMe
            Case "TC_EINARBEITUNG_PROD"
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                Dim f As New frmTCNachrichtenVerarbeitung(True)
                '  Me.Visible = False
                f.Show()
                AddHandler f.FormClosed, AddressOf closeMe

            Case "TELOTEC_API"
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                doTelotecAPIMulit_ALL()
                closeMe()

            Case "DY_CODELISTEN" ' TEST & PROD
                Dim f As New frmInfo(PARAM)
                f.Show()
                AddHandler Me.Shown, Sub()
                                         Me.Refresh()
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0008", True)
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0008", False)
                                         Me.Refresh()
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0017", True)
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0017", False)
                                         Me.Refresh()
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0014", True)
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0014", False)
                                         Me.Refresh()
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0141", True)
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0141", False)
                                         Me.Refresh()
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("I0400", True)
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("I0400", False)
                                         Me.Refresh()
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("I0700", True)
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("I0700", False)
                                         Me.Refresh()
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0010", True)
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0010", False)
                                         Me.Refresh()
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0013", True)
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0013", False)
                                         Me.Refresh()
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("A0122", True)
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("A0122", False)
                                         Me.Refresh()
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("A0127", True)
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("A0127", False)
                                         Me.Refresh()
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("I0200", True)
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("I0200", False)
                                         Me.Refresh()
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("I6010", True)
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("I6010", False)
                                         importEZOLLWechselkurse(True)
                                         importEZOLLWechselkurse(False)
                                         Me.Refresh()
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0219", True)
                                         DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0219", False)
                                         Me.Refresh()
                                         closeMe()
                                     End Sub
            Case "KD_DATA_DAKOSY"
                Dim f As New frmInfo(PARAM)
                f.Show()
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                DAKOSY_Worker.cDakosyFunftions.sendData()
                closeMe()
            Case "EZT_Bundesanzeiger_Importcodenummern"
                Dim f As New frmInfo(PARAM)
                f.Show()
                getETZBundesanzeiger_ImportCodenummern()
                closeMe()
            Case "EZB_Waehrungskurse"
                Dim f As New frmInfo(PARAM)
                f.Show()
                getEZB_Waehrungskurse()
                closeMe()
            Case "EZB_Waehrungskurse90D"
                Dim f As New frmInfo(PARAM)
                f.Show()
                getEZB_Waehrungskurse90D()
                closeMe()

            Case "NCTS_FREMD_GETLIST" 'TRANSCODE NCTS HOLEN
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                VERAG_PROG_ALLGEMEIN.cATEZ_ncts_api.query_declarations(Now.AddDays(-3), Now, False)
                closeMe()
            Case "NCTS_FREMD_UPDATE_MRN" 'TRANSCODE NCTS UPDATEN solange status <>60,90
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                updateATEZStatusByMRNTop(500)
                closeMe()

            Case "EMAIL_CHECKER" 'PRÜFT KUNDENADRESSEN AUF KORREKTEN AUFBAU
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                checkEmailAdressen(2, True)
                closeMe()

            Case "UID_Pruefung"
                Dim f As New frmInfo(PARAM)
                f.Show()
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                Dim finanzonline = True
                getUID_Pruefung(15000, finanzonline) 'max 15.000 wegen Zeit (Routine wird alle 24h wiederholt, 15 Abfragen pro Minute -> 21.600 pro 24h)
                closeMe()
            Case "WOELFL_USTVAntraege"
                Dim f As New frmInfo(PARAM)
                f.Show()
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                sendWOELFL_USTVAntraege("FTP", True)
                closeMe()
            Case "SDL_GUELTISBIS"
                Dim f As New frmInfo(PARAM)
                f.Show()
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                VERAG_PROG_ALLGEMEIN.SDL_Functions.SDL_GueltigBis_UTA_IDS()
                closeMe()

            Case "zoll_mail_attach"
                Dim f As New frmInfo(PARAM)
                f.Show()
                Dim pfad = ""
                Dim betreff = ""
                Dim von = ""

                If (parameter.Count - 1) >= 3 Then 'Höher als 1 weil der index 0 der Pfad zum programm ist

                    pfad = parameter(2)
                    betreff = parameter(3)
                    If (parameter.Count - 1) >= 5 Then von = parameter(5)

                    VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False

                    If von.Contains("@q8.com") Or von.Contains("@ibd.Q8.com") Or betreff.Contains("IDSPRD: Platts Price Report") Then
                        '---------------------IDS----------------------
                        importFileFromIDSMailAnhang(pfad, betreff, PARAM)
                    ElseIf von.Contains("@miccustoms.com") Or betreff.Contains("FORWARDING EMAIL | BEZUGSNUMMER") Or betreff = "Report nctsTransDeclGuarantees generated successfully" Then
                        '---------------------MIC----------------------
                        importFileFromMICMailAnhang(pfad, betreff)
                    Else
                        '---------------------DAKOSY----------------------
                        importFileFromDyMailAnhang(pfad, betreff)
                    End If
                End If
                closeMe()


            Case "mdm_mail_attach"
                Dim f As New frmInfo(PARAM)
                f.Show()
                Dim pfad = ""
                Dim betreff = ""
                Dim von = ""


                If (parameter.Count - 1) >= 3 Then 'Höher als 1 weil der index 0 der Pfad zum programm ist

                    'mdm_mail_attach %file% %subject% %datetimereceived% %from%" aus EEA-Attach

                    pfad = parameter(2)
                    betreff = parameter(3)

                    If (parameter.Count - 1) >= 5 Then von = parameter(5)

                    VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False

                    If (von.Contains("ebilling@uta.com") Or von.Contains("d.breimaier@verag.ag") Or von.Contains("s.kriegner@verag.ag")) AndAlso betreff.ToString.ToLower.Contains("uta") Then
                        '---------------------UTA----------------------
                        importFileFromUTAMailAnhang(pfad, betreff)

                    ElseIf von.Contains("@q8.com") Or von.Contains("d.breimaier@verag.ag") Or von.Contains("s.kriegner@verag.ag") Or von.Contains("q8truck.nl@q8.com") Or von.Contains("df@verag.ag") Or von.Contains("df@verag.ag") Then
                        '---------------------IDS----------------------

                        importFileFromIDSMailAnhang(pfad, betreff, PARAM)

                    End If

                End If
                closeMe()

            Case "mdm_mail_html"
                Dim f As New frmInfo(PARAM)
                f.Show()
                Dim pfad = ""
                Dim betreff = ""
                Dim von = ""


                If (parameter.Count - 1) >= 3 Then 'Höher als 1 weil der index 0 der Pfad zum programm ist

                    'mdm_mail_html %bodyfile% %subject% %datetimereceived% %from%  aus EEA-Attach
                    '%bodyfile% = Pfad zur Body HTML/Text Datei

                    'Bsp:
                    'ExportJob E-Invoice:processing mail: F:\vb.net\RoutineManager3\RoutineManager.exe mdm_mail_attach &quot;
                    'von = "d.breimaier@verag.ag"
                    'pfad = "F:\eee_e-invoice\0CD522B58DB96E184EFBD2C622DD4C3B781A2D35.html"
                    'betreff = "IDS, customer: 0060003360 Invoice: DE00360936 from 15/06/15"

                    pfad = parameter(2)
                    betreff = parameter(3)

                    If (parameter.Count - 1) >= 5 Then von = parameter(5)

                    VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                    If von.Contains("ids.de@q8.com") Or von.Contains("isselh@q8.com") Or von.Contains("d.breimaier@verag.ag") Or von.Contains("s.kriegner@verag.ag") Then
                        '---------------------IDS----------------------
                        importFileFromIDSMailAnhang(pfad, betreff, PARAM)

                    End If

                End If
                closeMe()

            Case "MAIL_ATTACH_WORK_FILES"

                Dim f As New frmInfo(PARAM)
                f.Show()
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                doIDSPlatts()
                doExcelImportNCTS_FREMD()

                closeMe()

            Case "ezoll_anhaenge"
                Dim f As New frmInfo(PARAM)
                f.Show()

                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                importFileFromEZOLL(Now) 'VERAG


                VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "UNISPED"
                importFileFromEZOLL(Now)

                closeMe()


            Case "ezoll_anhaenge_verag"
                Dim f As New frmInfo(PARAM)
                f.Show()
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False

                importFileFromEZOLL(Now)

                closeMe()


            Case "ezoll_anhaenge_unisped"
                Dim f As New frmInfo(PARAM)
                f.Show()
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "UNISPED"

                importFileFromEZOLL(Now)

                closeMe()


            Case "INSERT_BENACHRICHTIGUNG_VERMERKE_TEAMS"
                Dim f As New frmInfo(PARAM)
                f.Show()
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False

                INSERT_BENACHRICHTIGUNG_VERMERKE_TEAMS()

                closeMe()


            '-----------IMEX---------------
            Case "IMEX_DVO_KUNDEN_BU"
                Dim f As New frmInfo(PARAM)
                f.Show()
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                VERAG_PROG_ALLGEMEIN.cDVO_Interface.genStammdatenANSI(False, True, True)
                closeMe()

            Case "SYSKA_DATEN_BU"
                Dim f As New frmInfo(PARAM)
                f.Show()

                'FIBI Daten bereitstellen:
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                VERAG_PROG_ALLGEMEIN.cSyska_Interface.genDatensatz_Stammdaten(1, False)
                VERAG_PROG_ALLGEMEIN.cSyska_Interface.genDatensatz_Buchungen(1, False)

                VERAG_PROG_ALLGEMEIN.cSyska_Interface.genDatensatz_Stammdaten(7, False)
                VERAG_PROG_ALLGEMEIN.cSyska_Interface.genDatensatz_Buchungen(7, False)

                VERAG_PROG_ALLGEMEIN.cSyska_Interface.genDatensatz_Stammdaten(11, False)
                VERAG_PROG_ALLGEMEIN.cSyska_Interface.genDatensatz_Buchungen(11, False)

                VERAG_PROG_ALLGEMEIN.cSyska_Interface.genDatensatz_Stammdaten(17, False)
                VERAG_PROG_ALLGEMEIN.cSyska_Interface.genDatensatz_Buchungen(17, False)

                VERAG_PROG_ALLGEMEIN.cSyska_Interface.genDatensatz_Stammdaten(19, False)
                VERAG_PROG_ALLGEMEIN.cSyska_Interface.genDatensatz_Buchungen(19, False)

                VERAG_PROG_ALLGEMEIN.cSyska_Interface.genDatensatz_Buchungen(4, False) ' VERAG AG (DE)

                'Offene Posten übernehmen:
                VERAG_PROG_ALLGEMEIN.cSyska_Interface.OP_Einlesen_ALL()

                'Risiko in FiBu eintragen:
                VERAG_PROG_ALLGEMEIN.cSyska_Interface.UPDATE_FIBU_RISIKO()

                closeMe()
            Case "SYSKA_RISIKO"
                Dim f As New frmInfo(PARAM)
                f.Show()
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                VERAG_PROG_ALLGEMEIN.cSyska_Interface.UPDATE_FIBU_RISIKO()

                closeMe()

            Case "SYSKA_OP_EINLESEN"
                Dim f As New frmInfo(PARAM)
                f.Show()
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                VERAG_PROG_ALLGEMEIN.cSyska_Interface.OP_Einlesen_ALL()

                closeMe()

            Case "UNISPED_BMD"
                Dim f As New frmInfo(PARAM)
                f.Show()
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                VERAG_PROG_ALLGEMEIN.cBMD_Interface.genDatensatzCSV_ALL(False, False) 'Kunden noch nicht
                closeMe()
                '------------------------------
            Case "AWOR_LDV_to_BMD"
                Dim f As New frmInfo(PARAM)
                f.Show()
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                VERAG_PROG_ALLGEMEIN.cLDV_Interface.copyLDV_BMD()
                closeMe()

                '-----------AMBAR-------------------
            Case "AMBAR_DATEV_DEBITOREN"

                Dim f As New frmInfo(PARAM)
                f.Show()
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                VERAG_PROG_ALLGEMEIN.cDatev_Interface.genDatensatzCSV_ALL("AMBAR", False, True, False,,,, "ftp")
                closeMe()

            Case "AMBAR_DATEV_BUCHUNGEN"

                Dim f As New frmInfo(PARAM)
                f.Show()
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                VERAG_PROG_ALLGEMEIN.cDatev_Interface.genDatensatzCSV_ALL("AMBAR", False, False, True,,,, "ftp")
                closeMe()


            Case "AMBAR_DATEV_ALL"

                Dim f As New frmInfo(PARAM)
                f.Show()
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                VERAG_PROG_ALLGEMEIN.cDatev_Interface.genDatensatzCSV_ALL("AMBAR", False, True, True,,,, "ftp")
                closeMe()

            Case "ASFINAG_EXPORT"
                Dim f As New frmInfo(PARAM)
                f.Show()
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                Dim blt = New cAsfinag.Exportist
                Dim autoclose As Boolean = True
                blt.initExportPfade()
                blt.exportiereWhiteList(autoclose)
                blt.exportiereBlackList(autoclose)
                closeMe()

            Case "ASFINAG_IMPORT_CLF"
                Dim f As New frmInfo(PARAM)
                f.Show()
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                Dim autoclose As Boolean = True
                Dim testFTP As Boolean = VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM
                Dim fmCLF As New frmAsfinag_NachrichtenVerabeitung("CLF", testFTP, autoclose)
                fmCLF.Show()
                AddHandler fmCLF.FormClosed, AddressOf closeMe

            Case "ASFINAG_IMPORT_TTR"
                Dim f As New frmInfo(PARAM)
                f.Show()
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                Dim autoclose As Boolean = True
                Dim testFTP As Boolean = VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM
                Dim fmTTR As New frmAsfinag_NachrichtenVerabeitung("TTR", testFTP, autoclose)
                fmTTR.Show()
                AddHandler fmTTR.FormClosed, AddressOf closeMe

            Case "ASFINAG_IMPORT_TO_SDL"
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                ASFINAG_LKW(False)
                closeMe()

            Case "ABGLEICH_KUNDENUEMSAETZE"
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                Dim lastyears As Integer = 2
                If DELETE_Kundenumsaetze(lastyears) Then
                    INSERT_Kundenumsaetze(lastyears)
                End If
                closeMe()

            Case "AMBAR_VERAG_BUCHUNGEN"
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                Dim f As New frmInfo(PARAM)
                f.Show()
                VERAG_PROG_ALLGEMEIN.cSyska_Interface.genDatensatz_Buchungen(24,, "", True, "AG")
                closeMe()

            Case "AMBAR_VERAG_BUCHUNGEN_CS"
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                Dim f As New frmInfo(PARAM)
                f.Show()
                VERAG_PROG_ALLGEMEIN.cSyska_Interface.genDatensatz_Buchungen(24,, "", True, "CS")
                closeMe()
                '------------------------------
            Case "AAS" 'Aviso Alert System
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                Dim f As New frmInfo(PARAM)
                f.Show()
                doAASVermerke_Schwelle(Nothing)

                closeMe()
                '------------------------------

            Case "MODALTRANS_GET" '
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False

                getNCTS_MODALTRANS(Now.AddDays(-3))
                closeMe()
                '------------------------------
            Case "MODALTRANS_UPDATE" '
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False

                UpdateOpenModaltransNCTSFremdStatuses()
                closeMe()
                '------------------------------ 

            Case "MSE_NEWTRANSACTIONS_IMPORT" 'jeweils am 15/letzen Tag des Monats vor allen anderen MSE-Aufrufen!

                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                Dim API = VERAG_PROG_ALLGEMEIN.cAPI.INSERT_API(VERAG_PROG_ALLGEMEIN.cAPI_INOUT.IN, VERAG_PROG_ALLGEMEIN.cAPI_Type.REST, VERAG_PROG_ALLGEMEIN.cAPI_ART.AVISO_IN_MSE, "MSE - Multiservice", "MSE")

                Dim mse As New cMSEAPI("MSE")
                Dim fehler As String = ""
                Dim token = mse.createJWT(fehler)
                Dim dt As New DataTable
                If fehler <> "" Then
                    API.UPDTAE_ERR(, fehler, "createJWT")
                    closeMe()
                    Exit Sub
                Else
                    Dim totalPages = 0
                    Dim batchrequestNr = 0
                    Dim counTrans As Integer = 0
                    Dim pages As String = ""
                    Dim savedTrans As Integer = 0
                    Dim MDMEinarb As New cMDMEinarbeitung("MSE", Now())
                    MDMEinarb.setInvoicingDate(Now(), MDMEinarb)

                    'getNewestTransactions - Only returns the first page of transactions, subsequent pages are to be requested via /transactions with batch_seq_nr and page_nr.
                    fehler = mse.getNewestTransactions(token, dt, batchrequestNr, totalPages, 0, True, savedTrans)
                    If fehler <> "" Then
                        API.UPDTAE_ERR("Batch-Nr:   " & batchrequestNr & "-" & totalPages, fehler, "getNewestTransactions")
                        closeMe()
                        Exit Sub
                    Else
                        pages = "1"
                        counTrans += dt.Rows.Count
                    End If
                    If totalPages > 1 Then
                        For i = 2 To totalPages
                            If dt.Rows.Count > 0 Then dt.Clear()
                            fehler = mse.getTransactionsFromBatchNrAndPage(token, dt, batchrequestNr, totalPages, i, savedTrans)
                            If fehler <> "" Then
                                API.UPDTAE_ERR("Batch-Nr: " & batchrequestNr & "-" & totalPages, fehler, "getTransactionsFromBatchNrAndPage")
                                closeMe()
                                Exit For
                            Else
                                counTrans += dt.Rows.Count
                            End If
                            pages &= " " & i
                        Next
                    End If
                    API.UPDTAE_OK(,, PARAM & " Batch-Nr: " & batchrequestNr & "-" & totalPages & " Transactions: " & counTrans & " Pages: " & pages)
                    MDMEinarb.ds_count += savedTrans
                    MDMEinarb.ds_total += counTrans

                    If MDMEinarb.ds_count = MDMEinarb.ds_total Then
                        MDMEinarb.completed = True
                        MDMEinarb.completed_date = Now()
                        Dim empfaneger = cMitarbeiter.GetEMailRecipientForEmailNotification("MSE-Import", 19)
                        If empfaneger <> "" Then
                            VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(empfaneger, "MSE-Import durchgeführt", "Der automatische Import der MSE-Transaktionen wurde durchgeführt und " & MDMEinarb.ds_total & " Datensätze importiert." & vbNewLine & vbNewLine & "Infos: " & batchrequestNr & "-" & totalPages & " Transactions: " & counTrans & " Pages: " & pages, getAbsenderEmail(),,,,)
                        End If
                    End If

                    MDMEinarb.import_date = Now()
                    MDMEinarb.importfilename = "API_BatchNr_" & batchrequestNr & "_totalPages_" & totalPages
                    MDMEinarb.SAVE()
                    closeMe()
                End If


            Case "MSE_NEWSETTLEMENTS_IMPORT" 'jeweils am 15/letzen Tag des Monats(allerdings vor den Rechnungen)
                Dim API = VERAG_PROG_ALLGEMEIN.cAPI.INSERT_API(VERAG_PROG_ALLGEMEIN.cAPI_INOUT.IN, VERAG_PROG_ALLGEMEIN.cAPI_Type.REST, VERAG_PROG_ALLGEMEIN.cAPI_ART.AVISO_IN_MSE, "MSE - Multiservice", "MSE")
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                Dim mse As New cMSEAPI("MSE")
                Dim fehler As String = ""
                Dim token = mse.createJWT(fehler)
                Dim dt As New DataTable

                If fehler <> "" Then
                    API.UPDTAE_ERR(, fehler, "createJWT")
                    closeMe()
                    Exit Sub
                Else
                    Dim totalPages = 0
                    Dim batchrequestNr = 0

                    fehler = mse.getNewestSettlements(token, dt, batchrequestNr, totalPages, 0)

                    If fehler <> "" Then
                        API.UPDTAE_ERR("Batch-Nr: " & batchrequestNr & "-" & totalPages, fehler, "getNewestSettlements")
                        closeMe()
                        Exit Sub
                    End If
                    API.UPDTAE_OK(,, PARAM)
                    closeMe()
                End If



            Case "MSE_NEWCUSTOMERS_IMPORT" 'jeweils am 15/letzen Tag des Monats(allerdings vor den Rechnungen)
                Dim API = VERAG_PROG_ALLGEMEIN.cAPI.INSERT_API(VERAG_PROG_ALLGEMEIN.cAPI_INOUT.IN, VERAG_PROG_ALLGEMEIN.cAPI_Type.REST, VERAG_PROG_ALLGEMEIN.cAPI_ART.AVISO_IN_MSE, "MSE - Multiservice", "MSE")
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                Dim mse As New cMSEAPI("MSE")
                Dim fehler As String = ""
                Dim token = mse.createJWT(fehler)
                Dim dt As New DataTable

                If fehler <> "" Then
                    API.UPDTAE_ERR(, fehler, "createJWT")
                    closeMe()
                    Exit Sub
                Else
                    Dim totalPages = 0
                    Dim batchrequestNr = 0
                    fehler = mse.getCustomers(token, dt)
                    If fehler <> "" Then
                        API.UPDTAE_ERR(, fehler, "getCustomers")
                        closeMe()
                        Exit Sub
                    End If
                    API.UPDTAE_OK(,, PARAM)
                    closeMe()
                End If


            Case "MSE_NEWINVOICES_IMPORT" 'jeweils am 15/letzen Tage des Monats
                Dim API = VERAG_PROG_ALLGEMEIN.cAPI.INSERT_API(VERAG_PROG_ALLGEMEIN.cAPI_INOUT.IN, VERAG_PROG_ALLGEMEIN.cAPI_Type.REST, VERAG_PROG_ALLGEMEIN.cAPI_ART.AVISO_IN_MSE, "MSE - Multiservice", "MSE")
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                Dim mse As New cMSEAPI("MSE")
                Dim fehler As String = ""
                Dim token = mse.createJWT(fehler)
                Dim transactions As New DataTable
                Dim invoice As New DataTable

                If fehler <> "" Then
                    API.UPDTAE_ERR(, fehler, "createJWT")
                    closeMe()
                    Exit Sub
                Else
                    fehler = mse.getInvoices(token, invoice, Today(), Today(), True)
                    If fehler <> "" Then
                        API.UPDTAE_ERR("Datum: " & Today(), fehler, "getInvoices")
                        closeMe()
                        Exit Sub
                    End If

                    If invoice IsNot Nothing And invoice.Columns.Contains("invoice_id") AndAlso invoice.Rows.Count > 0 Then

                        Dim dvInvoice As New DataView(invoice)
                        Dim distinctInv As DataTable = dvInvoice.ToTable(True, New String() {"invoice_id"})

                        For Each r As DataRow In distinctInv.Rows
                            Dim totalPages = 0
                            Dim batchrequestNr = 0
                            fehler = mse.getSettlementsFromInvoiceID(token, transactions, r("invoice_id"), batchrequestNr, totalPages, 1)
                            If fehler <> "" Then
                                API.UPDTAE_ERR("Batch-Nr: " & batchrequestNr & "-" & totalPages, fehler, "getSettlementsFromInvoiceID")
                                closeMe()
                                Exit Sub
                            End If
                            If totalPages > 1 Then

                                For i = 2 To totalPages
                                    If transactions.Rows.Count > 0 Then transactions.Clear()
                                    fehler = mse.getSettlementsFromBatchNrAndPage(token, transactions, batchrequestNr, totalPages, i)

                                    If fehler <> "" Then
                                        API.UPDTAE_ERR("Batch-Nr: " & batchrequestNr & "-" & totalPages, fehler, "getSettlementsFromBatchNrAndPage")
                                        closeMe()
                                        Exit Sub
                                    End If
                                Next

                            End If
                        Next

                    End If
                    API.UPDTAE_OK(,, PARAM)

                    setInvoiceBackToCustomer("MSE", False)

                    closeMe()
                    Exit Sub
                End If


            Case "USTVA_SUMMEN_BERECHNEN"
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                Dim ok As Boolean = False
                Dim sendMail As Boolean = True
                Dim dt As New DataTable

                Dim IDSalt = Paramslist.GET_PARAMETER_VALUE_BOOL("Schnittstelle_IDS_alt")
                Dim IDSneu = Paramslist.GET_PARAMETER_VALUE_BOOL("Schnittstelle_IDS_neu")
                Dim MSEalt = Paramslist.GET_PARAMETER_VALUE_BOOL("Schnittstelle_MSE_alt")
                Dim MSEneu = Paramslist.GET_PARAMETER_VALUE_BOOL("Schnittstelle_MSE_neu")
                Dim PLOSEalt = Paramslist.GET_PARAMETER_VALUE_BOOL("Schnittstelle_PLOSE")
                Dim IT = Paramslist.GET_PARAMETER_VALUE_BOOL("Schnittstelle_IT")
                Dim UTAalt = Paramslist.GET_PARAMETER_VALUE_BOOL("Schnittstelle_UTA_alt")
                Dim UTAneu = Paramslist.GET_PARAMETER_VALUE_BOOL("Schnittstelle_UTA_neu")
                Dim PLOSEneu = Paramslist.GET_PARAMETER_VALUE_BOOL("Schnittstelle_PLOSE_NEU")

                cMDMFunctionsAllgemein.setSchnittstellen(PLOSEalt, IT, MSEalt, MSEneu, IDSalt, IDSneu, UTAalt, UTAneu, PLOSEneu)

                If cMDMFunctionsAllgemein.Update_UStVASummenNeuBerechnen_USTVA() Then
                    ok = cMDMFunctionsAllgemein.UStVAKunden_SummenNeuBerechnen(,, dt, sendMail)
                End If

                If dt.Rows.Count > 0 AndAlso sendMail Then
                    Dim filepath = VERAG_PROG_ALLGEMEIN.cProgramFunctions.genExcelFromDT_NEW(dt,,,,, False,)
                    If filepath <> "" Then
                        Dim anhenge As New List(Of String)
                        anhenge.Add(filepath)
                        Dim empfaenger = cMitarbeiter.GetEMailRecipientForEmailNotification("Stichtagsliste Kundensummen", 19)
                        If empfaenger <> "" Then VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(empfaenger, "Stichtagsliste Kundensummen " & Now().ToShortDateString, "Im Anhang die Stichtagsliste der Kundensummen vom:  " & Now() & vbNewLine & "*Automatic generated e-mail*", getAbsenderEmail(),,,,, anhenge)
                    End If

                End If


            Case "CREDITSAFE_EVENTS_MONTHLY"
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False

                Dim upateKunden As Boolean = False
                Dim checkDate As Boolean = True
                Dim setzeInfoImKunden As Boolean = False
                Dim sendMail As Boolean = False 'nicht nochmals, oder?

                importCreditsafeEvents(CDate("01." & Now.Month & "." & Now.Year).ToShortDateString, checkDate, upateKunden, setzeInfoImKunden, sendMail, True)
                closeMe()

            Case "CREDITSAFE_EVENTS_DAILY"
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False

                Dim upateKunden As Boolean = False
                Dim checkDate As Boolean = True
                Dim setzeInfoImKunden As Boolean = False
                Dim sendMail As Boolean = True

                importCreditsafeEvents(CDate(Today().AddDays(-1)).ToShortDateString, checkDate, upateKunden, setzeInfoImKunden, sendMail, False)
                closeMe()

            Case "CREDITSAFE_UPLOADS"
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False

                Dim sync As Boolean = True
                UploadCompaniesToCreditsafe(sync)
                closeMe()

            Case "ZUGFERD_CHECK_DAILY"
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                Dim sendNotificationEmails As Boolean = True
                checkZugferd(sendNotificationEmails)
                closeMe()

            Case "SENDE_ESSENSBESTELLUNGEN"
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                Dim test As Boolean = False
                sendEssensbestellungenInfoMail(test, False)
                closeMe()


            Case Else
                'Nur bei manuellem Start wird der fehler ausgegeben
                VERAG_PROG_ALLGEMEIN.cAllgemein.ERR_OP_GLOBAL = VERAG_PROG_ALLGEMEIN.ERROR_OP.SHOW
                Me.WindowState = FormWindowState.Normal
        End Select
    End Sub

    Function INSERT_BENACHRICHTIGUNG_VERMERKE_TEAMS() As Boolean
        Try

            Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL

            Dim DT = SQL.loadDgvBySql("
                                    SELECT * FROM (
                                    SELECT Vermerke.*, CASE WHEN tblSnd_TeamId IS NULL THEN (SELECT TeamId from ADMIN.dbo.tblMitarbeiter WHERE mit_id=MitarbeiterId) ELSE tblSnd_TeamId END as tblSnd_TeamId,Firma
                                      FROM [Aviso] inner join tblSendungen on [Aviso].AvisoID=tblSnd_AvisoID inner join Vermerke on Vermerke.SendungID=tblSnd_SendungID
                                      where Status NOT IN (1,2) and Vermerke.VermerkeCode=13
                                      and VermerkIDAufgehoben is null 
                                      and DATEDIFF(HOUR,Vermerke.Datum,getdate())>24
                                        ) as T1 where tblSnd_TeamId is not null
	                                    and tblSnd_TeamId=1 
            ", "AVISO")
            If DT IsNot Nothing Then
                For Each r In DT.Rows
                    VERAG_PROG_ALLGEMEIN.cAvisoBenachrichtigungen.INSERT_BENACHRICHTIGUNG(r("AvisoId"), r("SendungId"), 5, "T", r("tblSnd_TeamId"), "Reminder: " & r("hinweis_vermerk"), 0,, , r("VermerkID"), r("VermerkeCode"), r("Firma"))
                Next
            End If
            Return True
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)

            Return False

        End Try
    End Function

    Private Sub addTODatatable(dtSPEDEintrageAusEinarbeitung_HISTORY As DataTable, Anhaenge As cDHF_Anhaenge, SPEDBUCH_TMP As cSpeditionsbuch, datumImport As Date)

        If SPEDBUCH_TMP IsNot Nothing Then
            Dim R As DataRow = dtSPEDEintrageAusEinarbeitung_HISTORY.NewRow
            R("FilialNr") = SPEDBUCH_TMP.FilialenNr
            R("AbfertigungsNr") = SPEDBUCH_TMP.AbfertigungsNr
            R("Abfertigungsdatum") = SPEDBUCH_TMP.Abfertigungsdatum
            R("LNR") = Anhaenge.LRN
            R("CRN") = Anhaenge.CRN
            R("Abfertigungsart") = R("AbfertigungsNr") = SPEDBUCH_TMP.Abfertigungsart
            R("Firma") = VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA
            R("AnhaengeAbDatum") = datumImport.ToShortDateString
            dtSPEDEintrageAusEinarbeitung_HISTORY.Rows.Add(R)
        End If

    End Sub
    Function importFileFromEZOLL(datum As Date, Optional sendMail As Boolean = True) As Boolean
        Try
            Dim db = "EZOLL"
            Select Case VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA
                Case "UNISPED" : db = "EZOLL_UNISPED"
            End Select
            Dim sql As New VERAG_PROG_ALLGEMEIN.SQL
            Dim dt As DataTable = sql.loadDgvBySql("SELECT [zzAktivitaet].LizenzNr,[zzAktivitaet].Operatorid,[zzAktivitaet].AnmID,MsgTyp,[zzAktivitaet].ErstelltAm,pfad,zsAnmRefs.LRN,zsAnmRefs.CRN ,[zzAktivitaet].VorgangID   FROM [zzAktivitaet]     INNER JOIN zsAnmRefs On zsAnmrefs.AnmID=zzAktivitaet.AnmID 
                                                where MsgTyp IN ('EZ922','EZ923','TR109', 'EX431', 'CC529C', 'CC599C', 'CC029C') and ErstelltAm>='" & datum.ToShortDateString & " 00:00:00'  and pfad is not null", db, 200)

            Dim dtSPEDEintrageAusEinarbeitung_HISTORY As New DataTable

            With dtSPEDEintrageAusEinarbeitung_HISTORY
                .Columns.Add("FilialNr", GetType(Integer))
                .Columns.Add("AbfertigungsNr", GetType(Integer))
                .Columns.Add("Abfertigungsdatum", GetType(String))
                .Columns.Add("LNR", GetType(String))
                .Columns.Add("CRN", GetType(String))
                .Columns.Add("Abfertigungsart", GetType(String))
                .Columns.Add("AnhaengeAbDatum", GetType(String))
                .Columns.Add("Firma", GetType(String))
            End With



            If dt IsNot Nothing Then
                For Each row In dt.Rows
                    Dim cDHF_Anhaenge As New VERAG_PROG_ALLGEMEIN.cDHF_Anhaenge(row("AnmID"), row("MsgTyp"), row("LizenzNr"))

                    If Not cDHF_Anhaenge.hasEntry Then 'WENN NEU::

                        cDHF_Anhaenge.AnmID = row("AnmID")
                        cDHF_Anhaenge.LizenzNr = row("LizenzNr")
                        cDHF_Anhaenge.Operatorid = row("Operatorid")
                        cDHF_Anhaenge.AnmID = row("AnmID")
                        cDHF_Anhaenge.MsgTyp = row("MsgTyp")
                        cDHF_Anhaenge.ErstelltAm = row("ErstelltAm")
                        cDHF_Anhaenge.pfad = row("pfad")
                        cDHF_Anhaenge.LRN = If(row("LRN") IsNot DBNull.Value, row("LRN"), "")
                        cDHF_Anhaenge.CRN = If(row("CRN") IsNot DBNull.Value, row("CRN"), "")

                        Dim destFull = ""
                        Dim Bezeichnung = ""
                        Select Case row("MsgTyp")
                            Case "EZ922" : Bezeichnung = "STEUERBESCHEID"
                            Case "EZ923", "CC529C"
                                Select Case row("VorgangID")
                                    Case "AF" ' -> CC529C ist immer AF!
                                        Bezeichnung = "ABD"
                                    Case Else '"EF" 
                                        Bezeichnung = "STEUERBESCHEID_MITT"
                                End Select

                            Case "TR109", "CC029C" : Bezeichnung = "VBD"
                            Case "EX431", "CC599C" : Bezeichnung = "AVM"
                        End Select

                        Try


                            If cDHF_Anhaenge.pfad <> "" Then
                                Dim DS As New VERAG_PROG_ALLGEMEIN.cDATENSERVER("ZOLLDATEN", Bezeichnung, cDHF_Anhaenge.AnmID, "", "", "DHF_" & cDHF_Anhaenge.LRN.ToString.Replace("/", "-").Replace(",", "-").Replace("\", "-").Replace(":", "."), 0, False)
                                DS.da_vorlage = False

                                Dim ZIEL_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "ZOLARIS\ECHTSYSTEM\ZOLLDATEN\" & Bezeichnung & "\" & Now.Year & "\" & Now.ToString("yyyyMMdd") & "\"
                                If Not System.IO.Directory.Exists(ZIEL_PFAD) Then System.IO.Directory.CreateDirectory(ZIEL_PFAD)

                                destFull = ""
                                Select Case VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA

                                    Case "UNISPED" : copyFile(cDHF_Anhaenge.pfad.Replace("C:\Program Files (x86)\DHF\", "\\SRV04.unisu.at\DHF\"), ZIEL_PFAD, destFull)
                                    Case Else : copyFile(cDHF_Anhaenge.pfad.Replace("C:\", "\\Ezoll\c$\"), ZIEL_PFAD, destFull)

                                End Select

                                If destFull <> "" Then
                                    If DS.insertDataToDATENSERVER(destFull) Then
                                        cDHF_Anhaenge.docID = DS.da_id
                                    End If
                                End If
                            End If
                        Catch ex As Exception
                            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
                        End Try

                        cDHF_Anhaenge.SAVE()
                        Dim SPEDBUCH_TMP As VERAG_PROG_ALLGEMEIN.cSpeditionsbuch = Nothing
                        If cDHF_Anhaenge.docID > 0 AndAlso cDHF_Anhaenge.LRN <> "" Then
                            Select Case row("MsgTyp")
                                Case "EZ922" 'STEUERBESCHEID
                                    If DAKOSY_Worker.cZOLL_IMPORT.EZOLLImport(cDHF_Anhaenge.LRN, "EZA", SPEDBUCH_TMP) And Not sendMail Then 'Versucht den SpedBucheintrag, falls noch nicht vorhanden
                                        'Eintrag aus Nacharbeitung -> Protokollieren
                                        addTODatatable(dtSPEDEintrageAusEinarbeitung_HISTORY, cDHF_Anhaenge, SPEDBUCH_TMP, datum)
                                    End If

                                    '=====IMPORT IN VERAG DATENMODELL==========
                                    Dim IMP As New DAKOSY_Worker.cImporter_DHFToVERAG
                                    Select Case VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA
                                        Case "UNISPED" : IMP.ImportEZOLLByLRN(cDHF_Anhaenge.CRN, "EZOLL_UNISPED", False, True)
                                        Case Else : IMP.ImportEZOLLByLRN(cDHF_Anhaenge.CRN, "EZOLL", False)
                                    End Select
                                    '==========================================

                                    sql.doSQL("Update Speditionsbuch SET [DokumentId_Steuerbeleg]='" & cDHF_Anhaenge.docID & "' WHERE AtlasBezNrEZA='" & cDHF_Anhaenge.LRN & "' AND [DokumentId_Steuerbeleg] is null", "FMZOLL")
                                    If sendMail AndAlso SPEDBUCH_TMP IsNot Nothing AndAlso SPEDBUCH_TMP.SendungID IsNot Nothing Then doMailZollbeleg(destFull, "STB", SPEDBUCH_TMP.SendungID, cDHF_Anhaenge.LRN)
                                Case "TR109", "CC029C"
                                    If DAKOSY_Worker.cZOLL_IMPORT.EZOLLImport(cDHF_Anhaenge.LRN, "NCTS", SPEDBUCH_TMP) And Not sendMail Then
                                        addTODatatable(dtSPEDEintrageAusEinarbeitung_HISTORY, cDHF_Anhaenge, SPEDBUCH_TMP, datum)
                                    End If 'Versucht den SpedBucheintrag, falls noch nicht vorhanden
                                    sql.doSQL("Update Speditionsbuch SET [DokumentId_VBD]='" & cDHF_Anhaenge.docID & "' WHERE AtlasBezNrNCTS='" & cDHF_Anhaenge.LRN & "' AND [DokumentId_VBD] is null", "FMZOLL")
                                    ' BEREITSTELLUNG DER DATEN AN FREMDSYSTEME
                                    If sendMail AndAlso SPEDBUCH_TMP IsNot Nothing AndAlso SPEDBUCH_TMP.SendungID IsNot Nothing Then
                                        cVERAG_out_ncts.copyFileFTP_VERAGncts_EZOLL(cDHF_Anhaenge.AnmID)
                                        doMailZollbeleg(destFull, "VBD", SPEDBUCH_TMP.SendungID, cDHF_Anhaenge.LRN)
                                    End If

                                Case "EZ923", "CC529C" ' STB/ABD
                                    Select Case row("VorgangID")
                                        Case "AF" ' --> AUSFUHR --> ABD
                                            'AES Stuff.... 
                                            If DAKOSY_Worker.cZOLL_IMPORT.EZOLLImport(cDHF_Anhaenge.LRN, "AES", SPEDBUCH_TMP) And Not sendMail Then 'Versucht den SpedBucheintrag, falls noch nicht vorhanden
                                                addTODatatable(dtSPEDEintrageAusEinarbeitung_HISTORY, cDHF_Anhaenge, SPEDBUCH_TMP, datum)
                                            End If
                                            sql.doSQL("Update Speditionsbuch SET [DokumentId_ABD]='" & cDHF_Anhaenge.docID & "' WHERE AtlasBezNrAES='" & cDHF_Anhaenge.LRN & "' AND DokumentId_ABD is null", "FMZOLL")

                                            'Zeitspanne ? 3 Tage , älter nicht senden..
                                            If destFull <> "" AndAlso SPEDBUCH_TMP IsNot Nothing AndAlso SPEDBUCH_TMP.SendungID IsNot Nothing Then
                                                If sendMail AndAlso SPEDBUCH_TMP IsNot Nothing AndAlso SPEDBUCH_TMP.SendungID IsNot Nothing Then doMailZollbeleg(destFull, "ABD", SPEDBUCH_TMP.SendungID, cDHF_Anhaenge.LRN)
                                            End If
                                        Case Else '' --> EINFUHR --> 'Ergänzung STB - Mitteilung

                                            If DAKOSY_Worker.cZOLL_IMPORT.EZOLLImport(cDHF_Anhaenge.LRN, "EZA", SPEDBUCH_TMP) And Not sendMail Then
                                                addTODatatable(dtSPEDEintrageAusEinarbeitung_HISTORY, cDHF_Anhaenge, SPEDBUCH_TMP, datum)
                                            End If 'Versucht den SpedBucheintrag, falls noch nicht vorhanden
                                            sql.doSQL("Update Speditionsbuch SET DokumentId_Mitteilung='" & cDHF_Anhaenge.docID & "' WHERE AtlasBezNrEZA='" & cDHF_Anhaenge.LRN & "' AND DokumentId_Mitteilung is null", "FMZOLL")
                                            If sendMail AndAlso SPEDBUCH_TMP IsNot Nothing AndAlso SPEDBUCH_TMP.SendungID IsNot Nothing Then doMailZollbeleg(destFull, "STB", SPEDBUCH_TMP.SendungID, cDHF_Anhaenge.LRN)

                                    End Select


                                    'Select Case art
                                    '    Case "NCTS" : SPEDBUCH.AtlasBezNrNCTS = LRN
                                    '    Case "AES" : SPEDBUCH.AtlasBezNrAES = LRN
                                    '    Case Else : SPEDBUCH.AtlasBezNrEZA = LRN
                                    'End Select

                                Case "EX431", "CC599C" '-> Ausgangsvermerk 'AVM  --> EZoll Anhänge & Mail senden
                                    'AES Stuff....
                                    If DAKOSY_Worker.cZOLL_IMPORT.EZOLLImport(cDHF_Anhaenge.LRN, "AES", SPEDBUCH_TMP) And Not sendMail Then
                                        addTODatatable(dtSPEDEintrageAusEinarbeitung_HISTORY, cDHF_Anhaenge, SPEDBUCH_TMP, datum)
                                    End If 'Versucht den SpedBucheintrag, falls noch nicht vorhanden
                                    sql.doSQL("Update Speditionsbuch SET [DokumentId_AVM]='" & cDHF_Anhaenge.docID & "' WHERE AtlasBezNrAES='" & cDHF_Anhaenge.LRN & "' AND DokumentId_AVM is null", "FMZOLL")

                                    If destFull <> "" AndAlso SPEDBUCH_TMP IsNot Nothing AndAlso SPEDBUCH_TMP.SendungID IsNot Nothing Then
                                        If sendMail AndAlso SPEDBUCH_TMP IsNot Nothing AndAlso SPEDBUCH_TMP.SendungID IsNot Nothing Then doMailZollbeleg(destFull, "AVM", SPEDBUCH_TMP.SendungID, cDHF_Anhaenge.LRN)
                                    End If

                            End Select

                        End If

                    End If
                Next
            End If

            If dtSPEDEintrageAusEinarbeitung_HISTORY.Rows.Count > 0 Then

                Dim filepath = VERAG_PROG_ALLGEMEIN.cProgramFunctions.genExcelFromDT_NEW(dtSPEDEintrageAusEinarbeitung_HISTORY,,,,, False)
                If filepath <> "" Then
                    Dim anhenge As New List(Of String)
                    anhenge.Add(filepath)
                    VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail("d.breimaier@verag.ag", "E-ZOLL nachträgliche Einarbeitung", "Im Anhang befinden sich die Speditionsbucheintrag, die bei der nachträglichen Einarbeitung angelegt wurden: " & vbNewLine & "*Automatic generated e-mail*", getAbsenderEmail(),,,,, anhenge)
                End If


            End If
            Return True

        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)

            Return False

        End Try
    End Function


    Sub doMailZollbeleg(pfad, art, dy_id)
        Try

            Dim DY As New DAKOSY_Worker.cDakosy_Zollanmeldungen(dy_id)
            If DY.dy_SendungsId IsNot Nothing AndAlso CInt(DY.dy_SendungsId) > 0 Then

                doMailZollbeleg(pfad, art, DY.dy_SendungsId, DY.dy_BezugsNr)

            End If

        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)
        End Try
    End Sub


    Sub doMailZollbelegTC(pfad As String, art As String, tc_id As Integer)
        Try

            Dim DY As New TELOTEC_Worker.cTelotec_Anmeldung(tc_id)
            If DY.telanm_SendungsId IsNot Nothing AndAlso CInt(DY.telanm_SendungsId) > 0 Then

                doMailZollbeleg(pfad, art, DY.telanm_SendungsId, DY.telanm_BezugsNr)

            End If

        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)
        End Try
    End Sub



    Sub doMailZollbelegTC(pfad As String, art As String, TC As TELOTEC_Worker.cTelotec_Anmeldung)
        Try
            If TC IsNot Nothing Then

                If TC.telanm_SendungsId IsNot Nothing AndAlso CInt(TC.telanm_SendungsId) > 0 Then

                    doMailZollbeleg(pfad, art, TC.telanm_SendungsId, TC.telanm_BezugsNr)

                End If
            End If

        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)
        End Try
    End Sub




    Sub doMailZollbeleg(pfad, art, dy_SendungsId, BezugsNr)
        Try

            If dy_SendungsId IsNot Nothing AndAlso CInt(dy_SendungsId) > 0 Then
                Dim SND As New VERAG_PROG_ALLGEMEIN.cSendungen(dy_SendungsId)
                Dim list As New List(Of Integer)

                sendMailZollbeleg(pfad, SND.tblSnd_EmpfaengerKdNr, art, list, BezugsNr, SND, SND.getKdAtrNr("EMPFAENGER"), "EMPFAENGER")
                sendMailZollbeleg(pfad, SND.tblSnd_FrachtfuehrerKdNr, art, list, BezugsNr, SND, SND.getKdAtrNr("FRAECHTER"), "FRAECHTER")
                sendMailZollbeleg(pfad, SND.tblSnd_AvisiererKdNr, art, list, BezugsNr, SND, SND.getKdAtrNr("AVISIERER"), "AVISIERER")
                sendMailZollbeleg(pfad, SND.tblSnd_AuftraggeberKdNr, art, list, BezugsNr, SND, SND.getKdAtrNr("AUFTRAGGEBER"), "AUFTRAGGEBER")
                sendMailZollbeleg(pfad, SND.tblSnd_AbsenderKdNr, art, list, BezugsNr, SND, "", "ABSENDER")
                sendMailZollbelegGESTELLUNGSADRESSE(pfad, SND.NCTS_ngaId, art, list, BezugsNr, SND)
            End If

        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)

        End Try
    End Sub




    'Sub doMailZollbelegTC(pfad, art, tc_id)
    '    Try

    '        Dim DY As New TELOTEC_Worker.cTelotec_Anmeldung(tc_id)
    '        If DY.telanm_SendungsId IsNot Nothing AndAlso CInt(DY.telanm_SendungsId) > 0 Then
    '            Dim SND As New VERAG_PROG_ALLGEMEIN.cSendungen(DY.telanm_SendungsId)
    '            Dim list As New List(Of Integer)

    '            sendMailZollbeleg(pfad, SND.tblSnd_EmpfaengerKdNr, art, list, DY, SND)
    '            sendMailZollbeleg(pfad, SND.tblSnd_AbsenderKdNr, art, list, DY, SND)
    '            sendMailZollbeleg(pfad, SND.tblSnd_FrachtfuehrerKdNr, art, list, DY, SND)
    '            sendMailZollbeleg(pfad, SND.tblSnd_AvisiererKdNr, art, list, DY, SND)
    '            sendMailZollbeleg(pfad, SND.tblSnd_AuftraggeberKdNr, art, list, DY, SND)
    '        End If

    '    Catch ex As Exception
    '        VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)

    '    End Try
    'End Sub

    Function getStandortTXT(AVISO) As String
        Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
        If AVISO IsNot Nothing Then

            If AVISO.Grenzstelle.Replace("???", "") = "" Then
                Return SQL.getValueTxtBySql("SELECT basncd_dstnr +' - ' + [basncd_name]  FROM basncd WHERE basncd_dstnr='" & If(AVISO.Zollstelle, "") & "' ", "ATLAS")
            Else
                Dim GRZ As New VERAG_PROG_ALLGEMEIN.cGrenzstelle(AVISO.Grenzstelle)
                If GRZ IsNot Nothing AndAlso GRZ.hasEntry Then
                    Return If(GRZ.grz_ZollamtDST, "") & " " & If(GRZ.grz_ZollamtBezeichnung, "")
                End If
            End If
        End If
        Return ""
    End Function
    Sub sendMailZollbeleg(pfad As String, KundenNr As Integer, art As String, ByRef list As List(Of Integer), BezugsNr As String, SND As VERAG_PROG_ALLGEMEIN.cSendungen, KdAtrNr As Object, artKunde As String)
        Try
            If KundenNr > 0 Then
                If Not list.Exists(Function(x) x = KundenNr) Then 'nicht bereits verarbeitet
                    list.Add(KundenNr)
                    Dim pfadList As New List(Of String)
                    pfadList.Add(pfad)
                    Dim KD As New VERAG_PROG_ALLGEMEIN.cKunde(KundenNr)
                    Dim KD_ERW As New VERAG_PROG_ALLGEMEIN.cKundenErweitert(KundenNr)

                    If KD_ERW IsNot Nothing AndAlso KD IsNot Nothing Then ' AndAlso KD.EmailFreigabe Then


                        Dim AVISO = VERAG_PROG_ALLGEMEIN.cAviso.getAvisoById(SND.tblSnd_AvisoID)
                        'Wenn Freigabe-Mail aktiv und Steuerbescheid oder VBD gewählt, soll bei Fremdgrenzen die BelegMail gesendet werden.
                        Dim sendMailFremdgrenze = False
                        If KD_ERW.EmailFreigabe_Art = "FG" Or KD_ERW.EmailFreigabe_Export_Art = "FG" Then
                            If KD_ERW.EmailFreigabe_SteuerbescheidPDF Or KD_ERW.EmailFreigabe_VBDPDF Then

                                If AVISO IsNot Nothing Then
                                    'Fremdgrenze    
                                    If AVISO.Grenzstelle = "???" Then
                                        sendMailFremdgrenze = True
                                    Else
                                        'Prüfen ob WO oder ZA
                                        Dim GRZ As New VERAG_PROG_ALLGEMEIN.cGrenzstelle(AVISO.Grenzstelle)
                                        If GRZ IsNot Nothing AndAlso GRZ.hasEntry Then
                                            If GRZ.grz_Zollamt Then sendMailFremdgrenze = True  '--> Mail bei Beleg
                                            If GRZ.grz_Warenort Then sendMailFremdgrenze = True   '--> Mail bei Beleg
                                        End If
                                    End If
                                End If
                            End If
                        End If


                        If sendMailFremdgrenze Or KD_ERW.EmailFreigabe_Art = "BLG" Or KD_ERW.EmailFreigabe_Export_Art = "BLG" Or (art = "AVM" And KD_ERW.Email_AVM) Or (art = "ABD" And (KD_ERW.EmailFreigabe_ABDPDF Or KD_ERW.EmailFreigabe_Export_Art = "BLG")) Or art = "ZNV" Then ' Bei AVM ist es immer nach Freigabe, auch ZNV 
                            Dim Standort = "SUB"
                            Select Case SND.FilialenNr
                                Case "5501" : Standort = "IMX"
                                Case "5601" : Standort = "UNI"
                                Case "5701" : Standort = "AMB"
                                Case "5801" : Standort = "FO"
                                Case "4801" : Standort = "ATL"
                                Case "4802" : Standort = "ATL"
                                Case "5003" : Standort = "SBG"
                                Case "5103" : Standort = "WAI"
                                Case "5303" : Standort = "NKD"
                                Case Else
                                    Standort = "SUB"
                            End Select

                            Dim cStandorteDAL As New VERAG_PROG_ALLGEMEIN.cStandorteDAL

                            'Dim gst = ""
                            'Dim AVISO = VERAG_PROG_ALLGEMEIN.cAviso.getAvisoById(DY.dy_AvisoId)
                            'If AVISO IsNot Nothing Then
                            '    gst = AVISO.Grenzstelle.Replace("???", "")
                            'End If

                            Dim cStandort = cStandorteDAL.LesenStandort(-1, "", "SELECT * FROM Standorte WHERE Standort = '" & Standort & "'")
                            Dim FirmaTmp = VERAG_PROG_ALLGEMEIN.cAllgemein.getFirmaFromFiliale2(SND.FilialenNr)



                            Dim betreff = cStandort.eMail_Zollbeleg_Betreff '"Zollbeleg"

                            If KundenNr = 770931 Then ' Sonderfall Kanadevia
                                If KdAtrNr.ToString.Contains("/") Then
                                    KdAtrNr = KdAtrNr.ToString.Split("/")(0) 'nur vorderer Teil nehmen
                                End If
                            End If

                            'Wenn ein fixer BEtreff verwendet werden sollte:
                            If KD_ERW.EmailFreigabeBeleg_Betreff Then
                                betreff = If(KD_ERW.EmailFreigabeBeleg_BetreffText, "")
                                betreff = betreff.Replace("%KdAuftrNr%", If(KdAtrNr, ""))

                            Else

                                betreff = betreff.Replace("%KdAuftrNr%", If(KdAtrNr IsNot Nothing AndAlso KdAtrNr.ToString.Trim <> "", "Ihre Auftragsnr: " & KdAtrNr, ""))

                            End If

                            betreff = betreff.Replace("%LKW%", AVISO.LKW_Nr)
                            betreff = betreff.Replace("%AbfertigungsNr%", SND.FilialenNr & "/" & SND.AbfertigungsNr)
                            betreff = betreff.Replace("%Standort%", "")
                            betreff = betreff.Replace("%Uhrzeit%", "")
                            betreff = betreff.Replace("%Absender%", "")
                            betreff = betreff.Replace("%Empfaenger%", "")
                            betreff = betreff.Replace("%KdAuftrNr%", If(KdAtrNr IsNot Nothing AndAlso KdAtrNr.ToString.Trim <> "", "Ihre Auftragsnr: " & KdAtrNr, ""))


                            Dim body = cStandort.eMail_Zollbeleg_Text


                            Dim EMails As String = ""
                            Dim EMails_CC As String = ""
                            Dim EMails_BCC As String = ""

                            Dim Emails_list_sent As New VERAG_PROG_ALLGEMEIN.cEmailBenachrichtigungList

                            Dim Mail_Art = -1
                            Select Case art
                                Case "AVM", "ABD" 'Export
                                    Mail_Art = 4 ' Freigabe Export

                                    'If EMails_BCC = "" Then
                                    '    EMails_BCC = "al@verag.ag"
                                    'Else
                                    '    EMails_BCC &= ";al@verag.ag"
                                    'End If
                                Case Else
                                    Mail_Art = 2
                            End Select
                            Select Case SND.tblSnd_Abfertigungsart_ID
                                Case 6, 7, 33, 34, 37, 40, 43
                                    Mail_Art = 4 ' Freigabe Export
                            End Select



                            '---------------------------------------------------------
                            ' Wenn Mail_Art = Freigabe Beleg und art = STB und EmailFreigabeBeleg_Sendungsunterlagen, dann werden die Sendungsunterlagen an die Kunden geschickt
                            '---------------------------------------------------------
                            If Mail_Art = 2 And art = "STB" And KD_ERW.EmailFreigabe_Art = "BLG" And KD_ERW.EmailFreigabeBeleg_Sendungsunterlagen Then
                                Dim ANH_LIST As New List(Of VERAG_PROG_ALLGEMEIN.cAvisoAnhaenge)
                                VERAG_PROG_ALLGEMEIN.cAvisoAnhaenge.LOAD_LIST_BySendung(ANH_LIST, SND.tblSnd_SendungID) 'LÄDT alle Aviso-Anhänge
                                For Each l In ANH_LIST
                                    Select Case l.anh_Art.ToString.ToUpper
                                        ' Case "EXPORT_DOCS"
                                        Case "RECHNUNG", "CMR", "ATR", "EUR1", "COO", "PACKLISTE"
                                            Dim PathTmpANH = (New VERAG_PROG_ALLGEMEIN.cDATENSERVER(l.anh_docId)).GET_TOP1_PATH(False)
                                            If PathTmpANH <> "" Then pfadList.Add(PathTmpANH)
                                    End Select
                                Next
                            End If
                            '---------------------------------------------------------



                            VERAG_PROG_ALLGEMEIN.cEmailBenachrichtigung.eMails_einlesen(KundenNr, Mail_Art, EMails, EMails_CC, EMails_BCC, Emails_list_sent)
                            '  body = body.Replace("%Platzhalter%", "E-Mails: " & EMails & " CC: " & EMails_CC & " BCC:" & EMails_BCC)
                            body = body.Replace("%Platzhalter%", "")

                            body = body.Replace("%LKW%", AVISO.LKW_Nr)
                            body = body.Replace("%AbfertigungsNr%", SND.FilialenNr & "/" & SND.AbfertigungsNr)
                            body = body.Replace("%Standort%", getStandortTXT(AVISO))
                            body = body.Replace("%Uhrzeit%", Now.ToShortDateString & " " & Now.ToShortTimeString & " Uhr")
                            body = body.Replace("%KdAuftrNr%", If(KdAtrNr IsNot Nothing AndAlso KdAtrNr.ToString.Trim <> "", "Ihre Auftragsnr: " & KdAtrNr, ""))

                            body = body.Replace("%Absender%", If(SND.tblSnd_Absender, ""))
                            body = body.Replace("%Empfaenger%", If(SND.tblSnd_Empfaenger, ""))



                            ''!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                            'VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR("!!!!!!!!!!!!!!!!!!!!!!!!!: " & vbNewLine & EMails & vbNewLine & EMails_CC, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)
                            ''!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

                            '!!!!!!!!!!!!!!!!!!!!!!!!!!
                            'EMails = "al@verag.ag"
                            'EMails_CC = ""
                            'EMails_BCC = ""
                            '!!!!!!!!!!!!!!!!!!!!!!!!!!

                            'If EMails_BCC = "" Then
                            '    EMails_BCC = "al@verag.ag"
                            'Else
                            '    EMails_BCC &= ";al@verag.ag"
                            ''End If
                            ''!!!!!!!!!!!!!!!!!!!!!!!!!!
                            'If KundenNr = 706113 Then
                            '    EMails = "al@verag.ag"
                            '    EMails_CC = ""
                            '    EMails_BCC = ""
                            'End If
                            ''!!!!!!!!!!!!!!!!!!!!!!!!!!


                            Dim API = VERAG_PROG_ALLGEMEIN.cAPI.INSERT_API(VERAG_PROG_ALLGEMEIN.cAPI_INOUT.OUT, VERAG_PROG_ALLGEMEIN.cAPI_Type.MAIL, VERAG_PROG_ALLGEMEIN.cAPI_ART.AVISO_OUT_BELEGMAIL, art,,, KundenNr, SND.tblSnd_AvisoID, SND.tblSnd_SendungID, SND.FilialenNr, SND.AbfertigungsNr)

                            API.api_EMail = EMails
                            API.api_EMailCC = EMails_CC
                            API.api_EMailBCC = EMails_BCC
                            API.api_EMailSubject = betreff
                            API.api_EMailText = body
                            API.api_EMailAttCnt = pfadList.Count

                            betreff = betreff.Replace(vbNewLine, "").Replace(vbCr, "").Replace(vbLf, "").Replace(vbCrLf, "").Replace(System.Environment.NewLine, " ")



                            Select Case art
                                Case "STB"
                                    Select Case artKunde
                                        Case "FRÄCHTER", "AVISIERER" 'Die bekommen keine Steuerbescheide..
                                        Case Else

                                            If KD_ERW.EmailFreigabe_SteuerbescheidPDF Then

                                                betreff = betreff.Replace("%Zollbeleg%", "Abgabenbescheid " & BezugsNr)
                                                If VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(EMails, betreff, body, getAbsenderEmail(FirmaTmp), False, False, EMails_CC, EMails_BCC, pfadList) Then
                                                    API.UPDTAE_OK()
                                                    insertSendungsVermerk(SND.tblSnd_SendungID, SND.tblSnd_AvisoID, "Zollbeleg '" & art & "' gesendet an: " & EMails, 46)
                                                Else
                                                    API.UPDTAE_ERR()
                                                End If
                                            End If

                                    End Select
                                Case "VBD"
                                    If (KD_ERW.EmailFreigabe_Export And KD_ERW.EmailFreigabe_Export_Art = "BLG") Or KD_ERW.EmailFreigabe_VBDPDF Then
                                        betreff = betreff.Replace("%Zollbeleg%", "Versandbegleitdokument " & BezugsNr)
                                        If VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(EMails, betreff, body, getAbsenderEmail(FirmaTmp), False, False, EMails_CC, EMails_BCC, pfadList) Then
                                            API.UPDTAE_OK()
                                            insertSendungsVermerk(SND.tblSnd_SendungID, SND.tblSnd_AvisoID, "Zollbeleg '" & art & "' gesendet an: " & EMails, 46)
                                        Else
                                            API.UPDTAE_ERR()
                                        End If
                                    End If
                                Case "ZNV"
                                    If KD_ERW.EmailFreigabe_SteuerbescheidPDF Then
                                        betreff = betreff.Replace("%Zollbeleg%", "Abgabenbescheid ZNV " & BezugsNr)
                                        If VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(EMails, betreff, body, getAbsenderEmail(FirmaTmp), False, False, EMails_CC, EMails_BCC, pfadList) Then
                                            API.UPDTAE_OK()
                                            insertSendungsVermerk(SND.tblSnd_SendungID, SND.tblSnd_AvisoID, "Zollbeleg '" & art & "' gesendet an: " & EMails, 46)
                                        Else
                                            API.UPDTAE_ERR()
                                        End If
                                    End If
                                Case "ABD"
                                    If KD_ERW.EmailFreigabe_Export Or KD_ERW.EmailFreigabe_ABDPDF Then
                                        betreff = betreff.Replace("%Zollbeleg%", "Ausfuhrbegleitdokument " & BezugsNr)
                                        If VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(EMails, betreff, body, getAbsenderEmail(FirmaTmp), False, False, EMails_CC, EMails_BCC, pfadList) Then
                                            API.UPDTAE_OK()
                                            insertSendungsVermerk(SND.tblSnd_SendungID, SND.tblSnd_AvisoID, "Zollbeleg '" & art & "' gesendet an: " & EMails, 46)
                                        Else
                                            API.UPDTAE_ERR()
                                        End If
                                    End If
                                Case "AVM"
                                    If KD_ERW.EmailFreigabe_Export Or KD_ERW.Email_AVM Then
                                        betreff = betreff.Replace("%Zollbeleg%", "Ausgangsvermerk " & BezugsNr)
                                        If VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(EMails, betreff, body, getAbsenderEmail(FirmaTmp), False, False, EMails_CC, EMails_BCC, pfadList) Then
                                            API.UPDTAE_OK()
                                            insertSendungsVermerk(SND.tblSnd_SendungID, SND.tblSnd_AvisoID, "Zollbeleg '" & art & "' gesendet an: " & EMails, 46)
                                        Else
                                            API.UPDTAE_ERR()
                                        End If
                                    End If
                            End Select

                        End If
                    End If
                End If
            End If
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)

        End Try
    End Sub


    Sub sendMailZollbelegGESTELLUNGSADRESSE(pfad As String, nga_id As Object, art As String, ByRef list As List(Of Integer), BezugsNr As String, SND As VERAG_PROG_ALLGEMEIN.cSendungen)
        Try
            If nga_id IsNot Nothing Then
                If nga_id > 0 Then 'Not list.Exists(Function(x) x = KundenNr) Then 'nicht bereits verarbeitet
                    '   list.Add(KundenNr)
                    Dim pfadList As New List(Of String)
                    pfadList.Add(pfad)
                    Dim GST As New VERAG_PROG_ALLGEMEIN.cNCTSGestellungsadressen(nga_id)

                    If GST IsNot Nothing Then ' AndAlso KD.EmailFreigabe Then


                        Dim AVISO = VERAG_PROG_ALLGEMEIN.cAviso.getAvisoById(SND.tblSnd_AvisoID)
                        'Wenn Freigabe-Mail aktiv und Steuerbescheid oder VBD gewählt, soll bei Fremdgrenzen die BelegMail gesendet werden.
                        Dim sendMailFremdgrenze = False
                        'If KD_ERW.EmailFreigabe_Art = "FG" Or KD_ERW.EmailFreigabe_Export_Art = "FG" Then
                        '    If KD_ERW.EmailFreigabe_SteuerbescheidPDF Or KD_ERW.EmailFreigabe_VBDPDF Then

                        '        If AVISO IsNot Nothing Then
                        '            'Fremdgrenze    
                        '            If AVISO.Grenzstelle = "???" Then
                        '                sendMailFremdgrenze = True
                        '            Else
                        '                'Prüfen ob WO oder ZA
                        '                Dim GRZ As New VERAG_PROG_ALLGEMEIN.cGrenzstelle(AVISO.Grenzstelle)
                        '                If GRZ IsNot Nothing AndAlso GRZ.hasEntry Then
                        '                    If GRZ.grz_Zollamt Then sendMailFremdgrenze = True  '--> Mail bei Beleg
                        '                    If GRZ.grz_Warenort Then sendMailFremdgrenze = True   '--> Mail bei Beleg
                        '                End If
                        '            End If
                        '        End If
                        '    End If
                        'End If


                        If True Then ' Bei AVM ist es immer nach Freigabe, auch ZNV 
                            Dim Standort = "SUB"
                            Select Case SND.FilialenNr
                                Case "5501" : Standort = "IMX"
                                Case "5601" : Standort = "UNI"
                                Case "5701" : Standort = "AMB"
                                Case "5801" : Standort = "FO"
                                Case "4801" : Standort = "ATL"
                                Case "4802" : Standort = "ATL"
                                Case "5003" : Standort = "SBG"
                                Case "5103" : Standort = "WAI"
                                Case "5303" : Standort = "NKD"
                                Case Else
                                    Standort = "SUB"
                            End Select

                            Dim cStandorteDAL As New VERAG_PROG_ALLGEMEIN.cStandorteDAL

                            Dim cStandort = cStandorteDAL.LesenStandort(-1, "", "SELECT * FROM Standorte WHERE Standort = '" & Standort & "'")
                            Dim FirmaTmp = VERAG_PROG_ALLGEMEIN.cAllgemein.getFirmaFromFiliale2(SND.FilialenNr)



                            Dim betreff = cStandort.eMail_Zollbeleg_Betreff '"Zollbeleg"
                            betreff = betreff.Replace("%LKW%", AVISO.LKW_Nr)
                            betreff = betreff.Replace("%AbfertigungsNr%", SND.FilialenNr & "/" & SND.AbfertigungsNr)
                            betreff = betreff.Replace("%Standort%", "")
                            betreff = betreff.Replace("%Uhrzeit%", "")
                            betreff = betreff.Replace("%KdAuftrNr%", "")


                            Dim body = cStandort.eMail_Zollbeleg_Text


                            Dim EMails As String = ""
                            Dim EMails_CC As String = ""
                            Dim EMails_BCC As String = ""

                            '   Dim Emails_list_sent As New VERAG_PROG_ALLGEMEIN.cEmailBenachrichtigungList

                            '   VERAG_PROG_ALLGEMEIN.cEmailBenachrichtigung.eMails_einlesen(KundenNr, Mail_Art, EMails, EMails_CC, EMails_BCC, Emails_list_sent)
                            EMails = If(GST.nga_gestellungsMail, "")

                            body = body.Replace("%Platzhalter%", "")

                            body = body.Replace("%LKW%", AVISO.LKW_Nr)
                            body = body.Replace("%AbfertigungsNr%", SND.FilialenNr & "/" & SND.AbfertigungsNr)
                            body = body.Replace("%Standort%", getStandortTXT(AVISO))
                            body = body.Replace("%Uhrzeit%", Now.ToShortDateString & " " & Now.ToShortTimeString & " Uhr")
                            body = body.Replace("%KdAuftrNr%", "")





                            ''!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                            'VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR("!!!!!!!!!!!!!!!!!!!!!!!!!: " & vbNewLine & EMails & vbNewLine & EMails_CC, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)
                            ''!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

                            '!!!!!!!!!!!!!!!!!!!!!!!!!!
                            'EMails = "luxbauer@gmail.com"
                            'EMails_CC = ""
                            'EMails_BCC = ""
                            '!!!!!!!!!!!!!!!!!!!!!!!!!!

                            'If EMails_BCC = "" Then
                            '    EMails_BCC = "al@verag.ag"
                            'Else
                            '    EMails_BCC &= ";al@verag.ag"
                            ''End If
                            ''!!!!!!!!!!!!!!!!!!!!!!!!!!
                            'If KundenNr = 706113 Then
                            '    EMails = "al@verag.ag"
                            '    EMails_CC = ""
                            '    EMails_BCC = ""
                            'End If
                            ''!!!!!!!!!!!!!!!!!!!!!!!!!!


                            betreff = betreff.Replace(vbNewLine, "").Replace(vbCr, "").Replace(vbLf, "").Replace(vbCrLf, "").Replace(System.Environment.NewLine, " ")

                            If EMails <> "" Then
                                Select Case art
                                    Case "VBD"
                                        Dim API = VERAG_PROG_ALLGEMEIN.cAPI.INSERT_API(VERAG_PROG_ALLGEMEIN.cAPI_INOUT.OUT, VERAG_PROG_ALLGEMEIN.cAPI_Type.MAIL, VERAG_PROG_ALLGEMEIN.cAPI_ART.AVISO_OUT_GESTELLUNGMAIL, art,,, nga_id, SND.tblSnd_AvisoID, SND.tblSnd_SendungID, SND.FilialenNr, SND.AbfertigungsNr)
                                        API.api_EMail = EMails
                                        API.api_EMailCC = EMails_CC
                                        API.api_EMailBCC = EMails_BCC
                                        API.api_EMailSubject = betreff
                                        API.api_EMailText = body
                                        API.api_EMailAttCnt = pfadList.Count

                                        betreff = betreff.Replace("%Zollbeleg%", "c " & BezugsNr)
                                        If VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(EMails, betreff, body, getAbsenderEmail(FirmaTmp), False, False, EMails_CC, EMails_BCC, pfadList) Then
                                            API.UPDTAE_OK()
                                            insertSendungsVermerk(SND.tblSnd_SendungID, SND.tblSnd_AvisoID, "Zollbeleg '" & art & "' gesendet an: " & EMails, 46)
                                        Else
                                            API.UPDTAE_ERR()
                                        End If

                                End Select

                            End If

                        End If
                    End If
                End If
            End If
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)

        End Try
    End Sub


    Shared Sub insertSendungsVermerk(SendungID As Integer, AvisoID As Integer, Text As String, VermerkCodeId As Integer, Optional Beschreibung As String = "", Optional VorauskasseId As Object = Nothing, Optional addAuto As Boolean = False)
        'Daten zuweisen und speichern
        Dim myVermerk As New VERAG_PROG_ALLGEMEIN.cVermerk
        myVermerk.VermerkID = 0
        myVermerk.AvisoID = AvisoID
        myVermerk.Datum = Now
        myVermerk.Mitarbeiter = "(AUTO)"
        myVermerk.MitarbeiterId = -1
        myVermerk.Hinweis_Vermerk = Text
        myVermerk.VermerkCodeId = VermerkCodeId
        myVermerk.SendungID = SendungID
        If VorauskasseId IsNot Nothing AndAlso VorauskasseId IsNot DBNull.Value Then myVermerk.VorauskasseId = VorauskasseId
        myVermerk.VermerkArt = "S"
        Dim VermerkeDAL As New VERAG_PROG_ALLGEMEIN.cVermerkeDAL

        VermerkeDAL.SpeichernVermerk(myVermerk)

        If myVermerk.VermerkCodeId = 18 Then
            VermerkeDAL.UpdateLKW(myVermerk.AvisoID, False)
        End If

    End Sub

    Public Shared Function getAbsenderEmail(Optional FirmaTmp = "") As String
        Select Case If(FirmaTmp = "", VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA, FirmaTmp)
            Case "IMEX" : Return "noreply@imex-group.at"
            Case "ATILLA" : Return "noreply@verag.ag"
            Case "UNISPED" : Return "No-Reply@unisped.at"
            Case "FRONTOFFICE" : Return "noreply@front-office.eu"
            Case Else : Return "noreply@verag.ag"
        End Select
    End Function
    Sub importFileFromMICMailAnhang(pfad, betreff)

        Try
            Dim sql As New VERAG_PROG_ALLGEMEIN.SQL
            Dim DS As VERAG_PROG_ALLGEMEIN.cDATENSERVER = Nothing

            'moveFile(d, VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\ECHTSYSTEM\nlc\")

            'IO.Directory.CreateDirectory(VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\ECHTSYSTEM\ZOLLDATEN\TEST3\" & betreff.ToString.Replace(",", ""))
            'Report nctsTransDeclGuarantees generated successfully
            'If betreff.ToString.Contains("VBD FORWARDING EMAIL | BEZUGSNUMMER = ") Then
            If betreff.ToString.Contains("TAD FORWARDING EMAIL | ") Then
                betreff = betreff.replace("WG: ", "")
                betreff = betreff.replace("FW: ", "")
                betreff = betreff.replace("TAD FORWARDING EMAIL | ", "")
                betreff = betreff.trim


                Dim split = betreff.ToString.Split("|")

                Dim MRN = ""
                Dim LRN = ""
                For Each s In split
                    If s.Trim.StartsWith("MRN") Then
                        MRN = s.Replace("MRN", "").Trim
                    End If
                    If s.Trim.StartsWith("LRN") Then
                        LRN = s.Replace("LRN", "").Trim
                    End If
                Next

                Dim tmp_filialenNr = ""
                Dim tmp_abfertigungsNr = ""

                Dim SPEDBUCH As VERAG_PROG_ALLGEMEIN.cSpeditionsbuch = Nothing
                If LRN.ToString.Length >= 13 And LRN.ToString.Replace("-", "/").Contains("/") Then
                    Dim sp = LRN.ToString.Replace("-", "/").Split("/")
                    If sp(0).Length = 4 And sp(1).Length >= 8 Then
                        tmp_filialenNr = sp(0)
                        tmp_abfertigungsNr = sp(1).Substring(0, 8)
                        If IsNumeric(tmp_filialenNr) And IsNumeric(tmp_abfertigungsNr) Then
                            SPEDBUCH = New VERAG_PROG_ALLGEMEIN.cSpeditionsbuch(tmp_filialenNr, tmp_abfertigungsNr)
                            insertIntoSpedBuch_MIC(tmp_filialenNr, tmp_abfertigungsNr, LRN, "", SPEDBUCH, MRN) 'SPEDBUCH GENEREITERENERENRNERNERNERN!!!!
                        End If
                    End If
                End If

                DS = New VERAG_PROG_ALLGEMEIN.cDATENSERVER("ZOLLDATEN", "VBD", tmp_filialenNr & tmp_abfertigungsNr, "", "", LRN.ToString.Replace("/", "-").Replace(",", "-").Replace("\", "-").Replace(":", "."), 0, False)
                DS.da_vorlage = False

                Dim ZIEL_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "MIC\ECHTSYSTEM\ZOLLDATEN\VBD\NOT_IDENTIFIED\"
                If SPEDBUCH IsNot Nothing AndAlso SPEDBUCH.hasEntry Then ZIEL_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "MIC\ECHTSYSTEM\ZOLLDATEN\VBD\" & Now.Year & "\" & Now.ToString("yyyyMMdd") & "\"
                If Not System.IO.Directory.Exists(ZIEL_PFAD) Then System.IO.Directory.CreateDirectory(ZIEL_PFAD)

                Dim destFull = ""
                moveFile(pfad, ZIEL_PFAD, destFull)



                If DS.insertDataToDATENSERVER(destFull) Then
                    If SPEDBUCH IsNot Nothing AndAlso SPEDBUCH.hasEntry Then
                        SPEDBUCH.DokumentId_VBD = DS.da_id
                        SPEDBUCH.SAVE()
                        'doMailZollbeleg(DS.GET_TOP1_PATH, "VBD", dy_id)
                    End If
                End If

                ''ABD
            ElseIf betreff.ToString.Contains("EAD FORWARDING EMAIL | ") Then
                betreff = betreff.replace("WG: ", "")
                betreff = betreff.replace("FW: ", "")
                betreff = betreff.replace("EAD FORWARDING EMAIL | ", "")
                betreff = betreff.trim

                Dim split = betreff.ToString.Split("|")

                Dim BEZUGSNUMMER = ""
                For Each s In split
                    If s.Trim.StartsWith("BEZUGSNUMMER ") Then
                        BEZUGSNUMMER = s.Replace("BEZUGSNUMMER ", "").Trim
                    End If

                Next

                Dim tmp_filialenNr = ""
                Dim tmp_abfertigungsNr = ""

                Dim SPEDBUCH As VERAG_PROG_ALLGEMEIN.cSpeditionsbuch = Nothing
                If BEZUGSNUMMER.ToString.Length >= 13 And BEZUGSNUMMER.ToString.Replace("-", "/").Contains("/") Then
                    Dim sp = BEZUGSNUMMER.ToString.Replace("-", "/").Split("/")
                    If sp(0).Length = 4 And sp(1).Length >= 8 Then
                        tmp_filialenNr = sp(0)
                        tmp_abfertigungsNr = sp(1).Substring(0, 8)
                        If IsNumeric(tmp_filialenNr) And IsNumeric(tmp_abfertigungsNr) Then
                            SPEDBUCH = New VERAG_PROG_ALLGEMEIN.cSpeditionsbuch(tmp_filialenNr, tmp_abfertigungsNr)
                            insertIntoSpedBuch_MIC(tmp_filialenNr, tmp_abfertigungsNr, "", BEZUGSNUMMER, SPEDBUCH, "")
                        End If
                    End If
                End If

                DS = New VERAG_PROG_ALLGEMEIN.cDATENSERVER("ZOLLDATEN", "ABD", tmp_filialenNr & tmp_abfertigungsNr, "", "", BEZUGSNUMMER.ToString.Replace("/", "-").Replace(",", "-").Replace("\", "-").Replace(":", "."), 0, False)
                DS.da_vorlage = False

                Dim ZIEL_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "MIC\ECHTSYSTEM\ZOLLDATEN\ABD\NOT_IDENTIFIED\"
                If SPEDBUCH IsNot Nothing AndAlso SPEDBUCH.hasEntry Then ZIEL_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "MIC\ECHTSYSTEM\ZOLLDATEN\ABD\" & Now.Year & "\" & Now.ToString("yyyyMMdd") & "\"
                If Not System.IO.Directory.Exists(ZIEL_PFAD) Then System.IO.Directory.CreateDirectory(ZIEL_PFAD)

                Dim destFull = ""
                moveFile(pfad, ZIEL_PFAD, destFull)

                If DS.insertDataToDATENSERVER(destFull) Then
                    If SPEDBUCH IsNot Nothing AndAlso SPEDBUCH.hasEntry Then
                        SPEDBUCH.DokumentId_ABD = DS.da_id
                        SPEDBUCH.SAVE()
                        'doMailZollbeleg(DS.GET_TOP1_PATH, "ABD", dy_id)
                    End If
                End If

                'AVM
            ElseIf betreff.ToString.Contains("AVM - Ausgangsvermerk (DE), ") Then
                betreff = betreff.replace("WG: ", "")
                betreff = betreff.replace("FW: ", "")
                betreff = betreff.replace("AVM - Ausgangsvermerk (DE), ", "")
                If betreff.ToString.Contains(",") Then
                    Dim sp = betreff.ToString.Split(",")
                    betreff = sp(0).Trim

                    Dim dy_id As String = ""
                    If betreff.ToString.Length > 15 Then
                        dy_id = sql.getValueTxtBySql("SELECT isnull(aes_dyaAnmID,-1)  FROM [tblDakosy_AES] inner join tblDakosy_Zollanmeldungen on dy_id=aes_dyaAnmID where '" & betreff.ToString.Trim & "' LIKE aes_ObjectName +'%'  and LEN(aes_ObjectName)>=13", "FMZOLL")
                    Else
                        dy_id = sql.getValueTxtBySql("SELECT isnull(aes_dyaAnmID,-1)  FROM [tblDakosy_AES] inner join tblDakosy_Zollanmeldungen on dy_id=aes_dyaAnmID where aes_ObjectName='" & betreff.ToString.Trim & "'", "FMZOLL")
                    End If
                    '  IO.Directory.CreateDirectory(VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\ECHTSYSTEM\ZOLLDATEN\TEST3\")

                    DS = New VERAG_PROG_ALLGEMEIN.cDATENSERVER("ZOLLDATEN", "AVM", dy_id, "", "", betreff.ToString.Replace("/", "-").Replace(",", "-").Replace("\", "-").Replace(":", "."), 0, False)
                    DS.da_vorlage = False

                    Dim ZIEL_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\ECHTSYSTEM\ZOLLDATEN\AVM\NOT_IDENTIFIED\"
                    If IsNumeric(dy_id) AndAlso dy_id > 0 Then ZIEL_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\ECHTSYSTEM\ZOLLDATEN\AVM\" & Now.Year & "\" & Now.ToString("yyyyMMdd") & "\"
                    If Not System.IO.Directory.Exists(ZIEL_PFAD) Then System.IO.Directory.CreateDirectory(ZIEL_PFAD)

                    Dim destFull = ""
                    moveFile(pfad, ZIEL_PFAD, destFull)

                    If DS.insertDataToDATENSERVER(destFull) Then
                        If IsNumeric(dy_id) AndAlso dy_id > 0 Then
                            sql.doSQL("UPDATE tblDakosy_Zollanmeldungen SET dy_AVM_dsId='" & DS.da_id & "' where dy_id='" & dy_id & "'", "FMZOLL")
                            sql.doSQL("UPDATE Speditionsbuch SET DokumentId_AVM='" & DS.da_id & "' where AtlasBezNrEZA='" & betreff.ToString.Trim & "' AND DokumentId_AVM is null", "FMZOLL") 'Falls Spedbuch schon zuvor generiert wurde!
                            doMailZollbeleg(DS.GET_TOP1_PATH, "AVM", dy_id)
                        End If
                    End If

                End If
            ElseIf betreff = "Report nctsTransDeclGuarantees generated successfully" Then

                ' Dim ZIEL_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\ECHTSYSTEM\ZOLLDATEN\NCTS_XLS\" & Now.Year & "\"
                Dim ZIEL_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\ECHTSYSTEM\ZOLLDATEN\NCTS_XLS\NEW\"
                If Not System.IO.Directory.Exists(ZIEL_PFAD) Then System.IO.Directory.CreateDirectory(ZIEL_PFAD)

                Dim destFull = ""
                moveFile(pfad, ZIEL_PFAD, destFull)




            End If

            ' GENERELLES NOT IDENTIFIED!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!




            '""""""""""""
            ' If Not alreadyMoved Then

            ' End If

        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)
        End Try

    End Sub
    Sub importFileFromIDSMailAnhang(pfad, betreff, type)

        Try
            Dim sql As New VERAG_PROG_ALLGEMEIN.SQL
            Dim DS As VERAG_PROG_ALLGEMEIN.cDATENSERVER = Nothing

            If betreff.contains("IDSPRD: Platts Price Report") AndAlso type = "zoll_mail_attach" Then

                Dim ZIEL_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "IDS\IDS_XLS\Platts_Price_Report\NEW\"
                If Not System.IO.Directory.Exists(ZIEL_PFAD) Then System.IO.Directory.CreateDirectory(ZIEL_PFAD)

                Dim destFull = ""
                moveFile(pfad, ZIEL_PFAD, destFull)

            ElseIf betreff.contains("Einlesedatei IDS Rechnungen vom letzten Rechnungslauf") AndAlso type = "mdm_mail_attach" Then 'CSV einarbeiten

                Dim ids As New cIDS
                ids.initImportPfade("IDS")
                Dim Zielpfad = ids.VERARBEITUNG_PFAD

                If betreff.ToString.ToLower.Contains("ids") Then 'zusätzlicher Check
                    Dim found = False
                    betreff = betreff.replace("WG: ", "")
                    betreff = betreff.replace("FW: ", "")
                    moveFile(pfad, Zielpfad)
                End If


            ElseIf betreff.contains("IDS, customer") AndAlso type = "mdm_mail_html" Then 'Email mit Rechnungslink -OLD------

                'Bsp:
                'ExportJob E-Invoice:processing mail: F:\vb.net\RoutineManager3\RoutineManager.exe mdm_mail_attach &quot;
                'pfad = F:\eee_e-invoice\0CD522B58DB96E184EFBD2C622DD4C3B781A2D35.html
                'betreff = IDS, customer: 0060003360 Invoice: DE00360936 from 15/06/15&quot; &quot;15.11.2024 08:13:37&quot; &quot;
                'von = d.breimaier@verag.ag&quot;   

                Dim ids As New cIDS
                ids.initImportPfade("IDS")
                Dim Zielpfad = ids.VERARBEITUNG_PFAD


                betreff = betreff.replace("WG: ", "")
                betreff = betreff.replace("FW: ", "")
                betreff = betreff.replace(": ", "")
                betreff = betreff.ToString.ToLower.Replace(" ", "")

                Dim customerNo = ""
                Dim invoiceNo = ""
                Dim dateNo = ""
                Dim outputDate = ""
                Dim customerString = "customer"
                Dim InvoiceString = "invoice"
                Dim dateString = "from"
                Dim filename = ""


                If betreff.Contains(customerString) Then
                    customerNo = betreff.Substring(betreff.IndexOf(customerString) + customerString.Length, 10)
                End If

                If betreff.Contains(InvoiceString) Then
                    invoiceNo = betreff.Substring(betreff.IndexOf(InvoiceString) + InvoiceString.Length, 10)
                End If

                If betreff.Contains(dateString) Then
                    dateNo = betreff.Substring(betreff.IndexOf(dateString) + dateString.Length, 8)
                    Dim parsedDate As DateTime = DateTime.ParseExact(dateNo, "dd/MM/yy", System.Globalization.CultureInfo.InvariantCulture)
                    outputDate = parsedDate.ToString("dd.MM.yyyy")

                End If

                If outputDate IsNot Nothing AndAlso customerNo <> "" AndAlso invoiceNo <> "" Then

                    Dim idsInvoice As New cIDSInvoice(outputDate, customerNo, invoiceNo)
                    If Not idsInvoice.hasEntry Then idsInvoice.SAVE()


                    Try

                        Dim htmlText = File.ReadAllText(pfad)

                        If htmlText IsNot Nothing Then
                            If idsInvoice.isMail_IDS(htmlText) Then
                                If idsInvoice.getPDF_IDS(htmlText, filename, Zielpfad & invoiceNo & "_" & customerNo & ".pdf") Then
                                    idsInvoice.DocumentName = filename
                                End If

                            End If

                        End If
                        idsInvoice.Zeitstempel = Now()
                        idsInvoice.SAVE()
                    Catch ex As Exception
                        VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.LOG)
                    End Try



                End If


            ElseIf betreff.contains("Q8Truck") AndAlso type = "mdm_mail_attach" Then

                'Bsp:
                'ExportJob E-Invoice:processing mail: F:\vb.net\RoutineManager2\RoutineManager.exe mdm_mail_attach &quot;
                'pfad =  F:\eee_e-invoice\IV_707156_522653_CO_OBO_0060011910_GEOB00080669-PL_EI.pdf&quot;
                'betreff =  &quot;WG: Q8Truck&#160;KSeF,&#160;0060011910 -&#160;GEOB00080669/PL&quot; &quot;24.04.2026 09:37:03&quot; &quot;
                'von = d.breimaier@verag.ag&quot;    

                Dim ids As New cIDS
                ids.initImportPfade("IDS")
                Dim Zielpfad = ids.VERARBEITUNG_PFAD

                Dim found = False

                betreff = betreff.replace("WG: ", "")
                betreff = betreff.replace("FW: ", "")
                moveFile(pfad, Zielpfad)



            End If


        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.LOG)

        End Try

    End Sub
    'Sub importFileFromIDSMailAnhang(pfad, betreff)

    '    Try
    '        Dim sql As New VERAG_PROG_ALLGEMEIN.SQL
    '        Dim DS As VERAG_PROG_ALLGEMEIN.cDATENSERVER = Nothing

    '        If betreff.contains("IDSPRD: Platts Price Report") Then

    '            Dim ZIEL_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "IDS\IDS_XLS\Platts_Price_Report\" & Now.Year & "\"
    '            If Not IO.Directory.Exists(ZIEL_PFAD) Then IO.Directory.CreateDirectory(ZIEL_PFAD)

    '            Dim destFull = ""
    '            moveFile(pfad, ZIEL_PFAD, destFull)

    '            Dim Excel1 As Object 'New Microsoft.Office.Interop.Excel.Application
    '            Dim Blatt As Object 'Microsoft.Office.Interop.Excel.Worksheet 'As Object 'as Worksheet
    '            Excel1 = CreateObject("Excel.Application")
    '            Dim txt As String
    '            Dim Datei As Object 'as WorkBook
    '            '  VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(destFull, "00", System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)

    '            Dim DT_PLATTS As New DataTable()

    '            DT_PLATTS.Columns.Add("IsoCode")
    '            DT_PLATTS.Columns.Add("Outlet")
    '            DT_PLATTS.Columns.Add("Group Description")
    '            DT_PLATTS.Columns.Add("Product")
    '            DT_PLATTS.Columns.Add("Price Period Start")
    '            DT_PLATTS.Columns.Add("Price Period End")
    '            DT_PLATTS.Columns.Add("Excise")
    '            DT_PLATTS.Columns.Add("Netprice")
    '            DT_PLATTS.Columns.Add("Currency")
    '            Try
    '                destFull = "\\datenarchiv.verag.ost.dmn\DATENARCHIV\IDS\IDS_XLS\Platts_Price_Report\2022\PLATTSPR_707156_0000167908_1_20032022063012.xls"

    '                VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail("al@verag.ag", "TEST 1OOO " & destFull, "*AUTO*",,,,,,  )

    '                With Excel1
    '                    VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail("al@verag.ag", "TEST 1.1", "*AUTO*",,,,,,  )
    '                    Try

    '                        Datei = .Workbooks.Open(destFull,, True) 'Anpassen
    '                        VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail("al@verag.ag", "TEST 1.2", "*AUTO*",,,,,,  )

    '                    Catch ex As Exception
    '                        VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)
    '                        MsgBox(ex.Message & ex.StackTrace)
    '                    End Try
    '                    'Try
    '                    '    Datei = .Workbooks.Open(destFull,, True) 'Anpassen
    '                    'Catch ex As Exception
    '                    '    System.Threading.Thread.Sleep(5000) ' 5 Sek. warten --> noch Zugriff vom Erstellen?
    '                    '    Datei = .Workbooks.Open(destFull,, True)
    '                    'End Try

    '                    Blatt = Datei.Worksheets(1) 'Anpassen

    '                    VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail("al@verag.ag", "TEST 1.3", "*AUTO*",,,,,,  )
    '                    'Excel1.Workbooks.Open(destFull)
    '                    'Excel1.Visible = True ....wers braucht ?

    '                    Dim zeile = 12
    '                    'txt =""

    '                    VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail("al@verag.ag", "TEST 2: " & Blatt.Range("A" & zeile).Value, "*AUTO*",,,,,,  )

    '                    While zeile <= 10000 AndAlso Blatt.Range("A" & zeile) IsNot Nothing AndAlso Blatt.Range("A" & zeile).Value <> ""

    '                        If Blatt.Range("A" & zeile).Value.ToString.Contains("Austria") Then

    '                            DT_PLATTS.Rows.Add({Blatt.Range("A" & zeile).Value, Blatt.Range("B" & zeile).Value, Blatt.Range("C" & zeile).Value, Blatt.Range("D" & zeile).Value, Blatt.Range("E" & zeile).Value, Blatt.Range("F" & zeile).Value, Blatt.Range("H" & zeile).Value, Blatt.Range("I" & zeile).Value, Blatt.Range("J" & zeile).Value})


    '                        End If



    '                        zeile += 1

    '                    End While
    '                    VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail("al@verag.ag", "zeile: " & zeile, "*AUTO*",,,,,,  )


    '                End With


    '                'NEUE EXCEL GENEREITER, PREISE ANPASSEN, MAIL SENDEN
    '                If DT_PLATTS.Rows.Count > 0 Then
    '                    Dim XLS_PAth = destFull.Replace(".xls", "_NEW.xls")
    '                    Dim XLS_Tmp = ""
    '                    VERAG_PROG_ALLGEMEIN.cProgramFunctions.genExcelFromDT_NEW(DT_PLATTS,,,,, False, XLS_Tmp)
    '                    If XLS_Tmp <> "" Then
    '                        IO.File.Move(XLS_Tmp, XLS_PAth) ' Verschiebt die Datei

    '                        VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail("al@verag.ag", "IDSPRD: Platts Price Report", "*AUTO*",,,,,, {XLS_PAth})

    '                    End If
    '                End If

    '                Excel1.Workbooks.Close
    '                System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Excel1)
    '                System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Blatt)
    '                Excel1 = Nothing
    '                Blatt = Nothing
    '                GC.Collect()


    '            Catch ex As Exception
    '                VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)

    '                Try
    '                    Excel1.Workbooks.Close
    '                    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Excel1)
    '                    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Blatt)
    '                    Excel1 = Nothing
    '                    Blatt = Nothing
    '                    GC.Collect()

    '                Catch ex2 As Exception
    '                    VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex2.Message, ex2.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)
    '                End Try
    '            End Try

    '        End If

    '    Catch ex As Exception
    '        VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)
    '    End Try

    'End Sub

    Function getPlattsAufschlag(outletGroug As String) As Double
        If outletGroug.Contains("4473") Then Return 0.032
        If outletGroug.Contains("4474") Then Return 0.032
        If outletGroug.Contains("4486") Then Return 0.042
        Return 0.048
    End Function

    Function getPlattsAufschlag_SONDER(outletGroug As String) As Double
        If outletGroug.Contains("4473") Then Return 0.032
        If outletGroug.Contains("4474") Then Return 0.032
        If outletGroug.Contains("4486") Then Return 0.042
        Return 0.048
    End Function

    Function getPlattsAufschlag_SONDER_Lukenda(outletGroug As String) As Double
        If outletGroug.Contains("4473") Then Return 0.032 - 0.015 - 0.0065 ' SUBEN
        If outletGroug.Contains("4474") Then Return 0.032 - 0.015 - 0.0065 ' SUBEN
        If outletGroug.Contains("4493") Then Return 0.032 - 0.015
        If outletGroug.Contains("4485") Then Return 0.032 - 0.015
        If outletGroug.Contains("4486") Then Return 0.032 - 0.015
        Return 0.048 '-0.015

    End Function
    Sub doIDSPlatts()

        Try
            Dim sql As New VERAG_PROG_ALLGEMEIN.SQL
            Dim DS As VERAG_PROG_ALLGEMEIN.cDATENSERVER = Nothing
            Dim ZIEL_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "IDS\IDS_XLS\Platts_Price_Report\NEW\"


            If System.IO.Directory.Exists(ZIEL_PFAD) Then



                For Each IDS_FILE In System.IO.Directory.GetFiles(ZIEL_PFAD)
                    Dim DT_PLATTS As New DataTable()
                    DT_PLATTS.Columns.Add("IsoCode")
                    DT_PLATTS.Columns.Add("Outlet")
                    DT_PLATTS.Columns.Add("Group Description")
                    DT_PLATTS.Columns.Add("Product")
                    DT_PLATTS.Columns.Add("Price Period Start")
                    DT_PLATTS.Columns.Add("Price Period End")
                    DT_PLATTS.Columns.Add("Excise")
                    DT_PLATTS.Columns.Add("Netprice")
                    DT_PLATTS.Columns.Add("Currency")
                    DT_PLATTS.Columns.Add("NetpriceNEW")

                    Dim DT_PLATTS_SONDER = DT_PLATTS.Clone
                    Dim DT_PLATTS_SONDER_Lukenda = DT_PLATTS.Clone

                    ':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
                    ' EXCEL AUSLESEN:::::::
                    ':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::



                    If Not System.IO.Directory.Exists(ZIEL_PFAD.Replace("\NEW\", "\" & Now.Year & "\")) Then System.IO.Directory.CreateDirectory(ZIEL_PFAD.Replace("\NEW\", "\" & Now.Year & "\"))

                    Dim FILE_NEW = IDS_FILE.Replace("\NEW\", "\" & Now.Year & "\").Replace(".xls", "_ORIG.xls")


                    While System.IO.File.Exists(FILE_NEW)
                        FILE_NEW = IDS_FILE.Replace("\NEW\", "\" & Now.Year & "\").Replace(".xls", Now.ToString("_ddMMyy.HHmmss") & "_ORIG.xls")
                    End While



                    System.IO.File.Move(IDS_FILE, FILE_NEW)


                    Dim FILE_NEW_Lukenda = FILE_NEW.Replace("_ORIG.xls", "_special_Lukenda_ORIG.xls")
                    System.IO.File.Copy(FILE_NEW, FILE_NEW_Lukenda)

                    'IDS_FILE = ZIEL_PFAD.Replace("\NEW\", "\" & Now.Year & "\").Replace(".xls", "_ORIG.xls")

                    Dim Excel1 As Object 'New Microsoft.Office.Interop.Excel.Application
                    Dim Blatt As Object 'Microsoft.Office.Interop.Excel.Worksheet 'As Object 'as Worksheet
                    Excel1 = CreateObject("Excel.Application")
                    Dim txt As String
                    Dim Datei As Object 'as WorkBook
                    '  VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(destFull, "00", System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)


                    Try

                        With Excel1
                            Try

                                Datei = .Workbooks.Open(FILE_NEW,, True) 'Anpassen

                            Catch ex As Exception
                                VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)
                                '  MsgBox(ex.Message & ex.StackTrace)
                            End Try

                            Blatt = Datei.Worksheets(1) 'Anpassen

                            'Excel1.Workbooks.Open(destFull)
                            'Excel1.Visible = True ....wers braucht ?
                            Dim zeile = 12

                            While zeile <= 10000 AndAlso Blatt.Range("A" & zeile) IsNot Nothing AndAlso Blatt.Range("A" & zeile).Value <> ""

                                If Blatt.Range("A" & zeile).Value.ToString.Contains("Austria") Then

                                    'ALLGEMEIN
                                    Dim NetpriceNEW As Double = getPlattsAufschlag(Blatt.Range("B" & zeile).Value)
                                    If NetpriceNEW > 0 Then
                                        NetpriceNEW += CDbl(Blatt.Range("I" & zeile).Value) ' Aufschalg + NETTO
                                        DT_PLATTS.Rows.Add({Blatt.Range("A" & zeile).Value, Blatt.Range("B" & zeile).Value, Blatt.Range("C" & zeile).Value, Blatt.Range("D" & zeile).Value, Blatt.Range("E" & zeile).Value, Blatt.Range("F" & zeile).Value, Blatt.Range("H" & zeile).Value, Blatt.Range("I" & zeile).Value, Blatt.Range("J" & zeile).Value, NetpriceNEW})
                                    End If

                                    'SONDERKONDITION
                                    Dim NetpriceNEW_SOND As Double = getPlattsAufschlag_SONDER(Blatt.Range("B" & zeile).Value)
                                    If NetpriceNEW_SOND > 0 Then
                                        NetpriceNEW_SOND += CDbl(Blatt.Range("I" & zeile).Value) ' Aufschalg + NETTO
                                        DT_PLATTS_SONDER.Rows.Add({Blatt.Range("A" & zeile).Value, Blatt.Range("B" & zeile).Value, Blatt.Range("C" & zeile).Value, Blatt.Range("D" & zeile).Value, Blatt.Range("E" & zeile).Value, Blatt.Range("F" & zeile).Value, Blatt.Range("H" & zeile).Value, Blatt.Range("I" & zeile).Value, Blatt.Range("J" & zeile).Value, NetpriceNEW_SOND})
                                    End If
                                    'SONDERKONDITION Lukenda
                                    NetpriceNEW_SOND = getPlattsAufschlag_SONDER_Lukenda(Blatt.Range("B" & zeile).Value)
                                    If NetpriceNEW_SOND > 0 Then
                                        NetpriceNEW_SOND += CDbl(Blatt.Range("I" & zeile).Value) ' Aufschalg + NETTO
                                        DT_PLATTS_SONDER_Lukenda.Rows.Add({Blatt.Range("A" & zeile).Value, Blatt.Range("B" & zeile).Value, Blatt.Range("C" & zeile).Value, Blatt.Range("D" & zeile).Value, Blatt.Range("E" & zeile).Value, Blatt.Range("F" & zeile).Value, Blatt.Range("H" & zeile).Value, Blatt.Range("I" & zeile).Value, Blatt.Range("J" & zeile).Value, NetpriceNEW_SOND})
                                    End If
                                End If

                                zeile += 1

                            End While


                        End With

                        ''NEUE EXCEL GENEREITER, PREISE ANPASSEN, MAIL SENDEN
                        'If DT_PLATTS.Rows.Count > 0 Then
                        '    'Dim XLS_PAth = IDS_FILE.Replace(".xls", "_NEW.xls")
                        '    Dim FIN_FILE = FILE_NEW.Replace("_ORIG.xls", ".xlsx")


                        '    Dim XLS_Tmp = VERAG_PROG_ALLGEMEIN.cProgramFunctions.genExcelFromDT_NEW(DT_PLATTS,,,,, False)
                        '    If XLS_Tmp <> "" Then
                        '        IO.File.Move(XLS_Tmp, FIN_FILE) ' Verschiebt die Datei

                        '        ' Dim FIN_FILE = IDS_FILE.Replace("_ORIG.xls", ".xls")
                        '        Dim MAIL_attach As New List(Of String)
                        '        MAIL_attach.Add(FIN_FILE)
                        '        VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail("al@verag.ag", "IDSPRD: Platts Price Report", "*AUTO*",,,,,, MAIL_attach)

                        '    End If
                        'End If

                        Excel1.Workbooks.Close
                        System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Excel1)
                        System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Blatt)
                        Excel1 = Nothing
                        Blatt = Nothing
                        GC.Collect()


                    Catch ex As Exception

                        VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)

                        Try
                            Excel1.Workbooks.Close
                            System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Excel1)
                            System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Blatt)
                            Excel1 = Nothing
                            Blatt = Nothing
                            GC.Collect()

                        Catch ex2 As Exception
                            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex2.Message, ex2.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)
                        End Try
                    End Try

                    Dim MailsAnIntern As Boolean = True

                    'ALLGEMEIN
                    genXLS_NewPrice(DT_PLATTS, FILE_NEW, "IDSPRD: Platts Price Report", "", "", "", MailsAnIntern) '--> Send XLS Mail
                    MailsAnIntern = False
                    'SONDERKONDITION
                    '  genXLS_NewPrice(DT_PLATTS_SONDER, FILE_NEW.Replace("_ORIG.xls", "_special_ORIG.xls")) '--> Send XLS Mail
                    genXLS_NewPrice(DT_PLATTS_SONDER_Lukenda, FILE_NEW_Lukenda, "IDSPRD: Platts Price Report - Lukenda", "Logistik@lukenda-transport.com;ivan.andric@lukenda-transport.hr", "", "sales@verag.ag;al@verag.ag", MailsAnIntern) '--> Send XLS Mail


                Next
            End If

        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)
        End Try

    End Sub

    Sub genXLS_NewPrice(DT_PLATTS As DataTable, FILE_NEW As String, MAIL_SUBJ As String, MAIL_TO As String, MAIL_CC As String, MAIL_BCC As String, MailsIntern As Boolean)
        ':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
        'NEUES EXCEL ERSTELLEN:::::::
        ':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
        If DT_PLATTS.Rows.Count > 0 Then
            Dim Excel2 As Object 'New Microsoft.Office.Interop.Excel.Application
            Dim Blatt2 As Object 'Microsoft.Office.Interop.Excel.Worksheet 'As Object 'as Worksheet
            Excel2 = CreateObject("Excel.Application")
            Dim Datei2 As Object 'as WorkBook
            '  VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(destFull, "00", System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)

            Try

                With Excel2
                    Try

                        Datei2 = .Workbooks.Open(System.AppDomain.CurrentDomain.BaseDirectory & "\Resources\Muster_IDS_PLATTSPR.xls",, True) 'Anpassen

                    Catch ex As Exception
                        VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)
                        MsgBox(ex.Message & ex.StackTrace)
                    End Try

                    Blatt2 = Datei2.Worksheets(1)

                    Dim zeile = 12

                    'Blatt2.Range("G:G").NumberFormat = "0.000"
                    For Each ROW In DT_PLATTS.Rows
                        Blatt2.Range("A" & zeile).Value = ROW("IsoCode")
                        Blatt2.Range("B" & zeile).Value = ROW("Outlet")
                        Blatt2.Range("C" & zeile).Value = ROW("Group Description")
                        Blatt2.Range("D" & zeile).Value = ROW("Product")
                        Blatt2.Range("E" & zeile).Value = ROW("Price Period Start").ToString
                        Blatt2.Range("F" & zeile).Value = ROW("Price Period End").ToString
                        Blatt2.Range("G" & zeile).Value = CDbl(ROW("NetpriceNEW")) '.ToString("N3")
                        Blatt2.Range("H" & zeile).Value = ROW("Currency")

                        zeile += 1
                    Next


                End With

                Dim FIN_FILE = FILE_NEW.Replace("_ORIG.xls", ".xls")
                While System.IO.File.Exists(FIN_FILE)
                    FIN_FILE = FILE_NEW.Replace("_ORIG.xls", Now.ToString("_ddMMyy.HHmmss") & ".xls")
                End While


                Datei2.SaveAs(FIN_FILE)


                Excel2.Workbooks.Close
                System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Excel2)
                System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Blatt2)
                Excel2 = Nothing
                Blatt2 = Nothing
                GC.Collect()



                ':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
                'NEUES EXCEL PER MAIL SCHICKEN:::::::
                ':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

                Dim MAIL_attach As New List(Of String)
                MAIL_attach.Add(FIN_FILE)

                If MailsIntern Then

                    Dim empfaneger = cMitarbeiter.GetEMailRecipientForEmailNotification("IDS-Preisliste", 19)

                    If empfaneger <> "" Then VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(empfaneger, MAIL_SUBJ, "*AUTO*", getAbsenderEmail(),,, MAIL_CC, MAIL_BCC, MAIL_attach)

                Else

                    VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(MAIL_TO, MAIL_SUBJ, "*AUTO*", getAbsenderEmail(),,, MAIL_CC, MAIL_BCC, MAIL_attach)

                End If

                ':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

            Catch ex As Exception
                VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)

                Try
                    Excel2.Workbooks.Close
                    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Excel2)
                    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Blatt2)
                    Excel2 = Nothing
                    Blatt2 = Nothing
                    GC.Collect()

                Catch ex2 As Exception
                    VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex2.Message, ex2.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)
                End Try
            End Try

        End If


    End Sub
    Public Function FileInUse(ByVal sFile As String) As Boolean
        If System.IO.File.Exists(sFile) Then
            Try
                Dim F As Short = FreeFile()
                FileOpen(F, sFile, OpenMode.Binary, OpenAccess.ReadWrite, OpenShare.LockReadWrite)
                FileClose(F)
            Catch
                Return True
            End Try
        End If
    End Function

    Function doExcelImportNCTS_FREMD() As Boolean
        Dim sql As New VERAG_PROG_ALLGEMEIN.SQL
        Dim DS As VERAG_PROG_ALLGEMEIN.cDATENSERVER = Nothing
        Dim ZIEL_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\ECHTSYSTEM\ZOLLDATEN\NCTS_XLS\NEW\"


        If System.IO.Directory.Exists(ZIEL_PFAD) Then

            For Each MIC_FILE In System.IO.Directory.GetFiles(ZIEL_PFAD)

                ':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
                ' EXCEL AUSLESEN:::::::
                ':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::


                'Excel2.Workbooks.Open(destFull,, True)
                Dim Excel1 As Object 'New Microsoft.Office.Interop.Excel.Application
                Dim Blatt As Object 'Microsoft.Office.Interop.Excel.Worksheet 'As Object 'as Worksheet
                Excel1 = CreateObject("Excel.Application")
                Dim txt As String
                Dim Datei As Object 'as WorkBook

                Try
                    With Excel1

                        Datei = .Workbooks.Open(MIC_FILE,, True) 'Anpassen
                        'Try
                        '    Datei = .Workbooks.Open(destFull,, True) 'Anpassen
                        'Catch ex As Exception
                        '    System.Threading.Thread.Sleep(5000) ' 5 Sek. warten --> noch Zugriff vom Erstellen?
                        '    Datei = .Workbooks.Open(destFull,, True)
                        'End Try

                        Blatt = Datei.Worksheets(1) 'Anpassen

                        'Excel1.Workbooks.Open(destFull)
                        'Excel1.Visible = True ....wers braucht ?

                        Dim zeile = 2
                        'txt =""
                        While zeile <= 20000 AndAlso Blatt.Range("A" & zeile) IsNot Nothing AndAlso Blatt.Range("A" & zeile).value IsNot Nothing AndAlso Blatt.Range("A" & zeile).value <> "" AndAlso Blatt.Range("F" & zeile) IsNot Nothing AndAlso Blatt.Range("A" & zeile).Value = "GB"
                            ' If zeile < 5 Then VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR("MIC", "AA", System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)
                            'asd
                            Dim MRN = Blatt.Range("F" & zeile).Value
                            If MRN <> "" Then
                                'If zeile < 5 Then VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR("MIC", "OO", System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)

                                Dim NCTS_FREMD = VERAG_PROG_ALLGEMEIN.cNCTS_TR.LOADByMRN(MRN, True)
                                If NCTS_FREMD Is Nothing Then NCTS_FREMD = New VERAG_PROG_ALLGEMEIN.cNCTS_TR()

                                Dim StatusTxt = Blatt.Range("G" & zeile).Value

                                NCTS_FREMD.ncts_ObjectName = Blatt.Range("H" & zeile).Value
                                NCTS_FREMD.ncts_MRN = MRN
                                NCTS_FREMD.ncts_Partnersystem = "MIC"
                                NCTS_FREMD.ncts_ArtAnmeldung = Blatt.Range("D" & zeile).Value

                                NCTS_FREMD.ncts_Trans_DatumZeit = Blatt.Range("E" & zeile).Value
                                NCTS_FREMD.ncts_Erstellung = Blatt.Range("E" & zeile).Value
                                NCTS_FREMD.ncts_Eroeffnung = Blatt.Range("E" & zeile).Value
                                NCTS_FREMD.ncts_Ankunft = Blatt.Range("U" & zeile).Value
                                If Blatt.Range("U" & zeile).Value IsNot Nothing AndAlso IsDate(Blatt.Range("U" & zeile).Value) Then
                                    NCTS_FREMD.ncts_Erledigung = Blatt.Range("U" & zeile).Value 'WriteOff ->nicht sicher
                                    NCTS_FREMD.ncts_GestelltAm = Blatt.Range("U" & zeile).Value 'WriteOff ->nicht sicher
                                End If
                                If NCTS_FREMD.ncts_Erledigung IsNot Nothing AndAlso IsDate(NCTS_FREMD.ncts_Erledigung) Then
                                    NCTS_FREMD.ncts_Gestellt = True
                                End If

                                NCTS_FREMD.ncts_AbgangsDienststellennummer = Blatt.Range("M" & zeile).Value
                                NCTS_FREMD.ncts_BestimmungsstelleDienststellennummer = Blatt.Range("N" & zeile).Value
                                NCTS_FREMD.ncts_VersendungsLandCode = Blatt.Range("K" & zeile).Value
                                NCTS_FREMD.ncts_BestimmungslandCode = Blatt.Range("L" & zeile).Value
                                NCTS_FREMD.ncts_Wiedergestellungsdatum = Blatt.Range("T" & zeile).Value 'Frist

                                Dim PLANT = Blatt.Range("B" & zeile).Value 'Plant

                                Select Case PLANT
                                    Case "01" : NCTS_FREMD.ncts_firma = "VERAG" : NCTS_FREMD.ncts_niederlassung = "SUB"
                                    Case "02" : NCTS_FREMD.ncts_firma = "UNISPED" : NCTS_FREMD.ncts_niederlassung = "SUB"
                                    Case "03" : NCTS_FREMD.ncts_firma = "AWOR" : NCTS_FREMD.ncts_niederlassung = "LNZ"
                                End Select

                                Select Case If(StatusTxt, "")
                                    Case "Write-off notification"
                                        NCTS_FREMD.ncts_Status = 60
                                    Case "Declaration sent", "Declaration Positive Acknowledge"
                                        NCTS_FREMD.ncts_Status = 41
                                    Case "Release for transit", "Cancellation request sent"
                                        NCTS_FREMD.ncts_Status = 50
                                    Case "Cancellation request accepted"
                                        NCTS_FREMD.ncts_Status = 90
                                    Case Else
                                        NCTS_FREMD.ncts_Status = 5
                                End Select
                                NCTS_FREMD.ncts_Status_KEWILL_Equivalent = NCTS_FREMD.ncts_Status



                                NCTS_FREMD.ncts_SICHERHEITSANGABEN.Clear()
                                Dim GRN As New VERAG_PROG_ALLGEMEIN.cNCTS_TR_Sicherheitsangaben
                                GRN.nctsSA_GRN = Blatt.Range("P" & zeile).Value
                                GRN.nctsSA_AbgabenBetrag = Blatt.Range("R" & zeile).Value 'GBP?????
                                NCTS_FREMD.ncts_SICHERHEITSANGABEN.Add(GRN)
                                NCTS_FREMD.SAVE_ALL()

                            End If
                            zeile += 1

                        End While
                        If VERAG_PROG_ALLGEMEIN.cAllgemein.ERR_OP_GLOBAL = VERAG_PROG_ALLGEMEIN.ERROR_OP.SHOW Then
                            MsgBox(zeile & " Zeilen eingearbeitet.")
                        End If
                    End With

                    Excel1.Workbooks.Close
                    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Excel1)
                    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Blatt)
                    Excel1 = Nothing
                    Blatt = Nothing
                    GC.Collect()

                    'Return True

                Catch ex As Exception
                    VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)

                    Try
                        Excel1.Workbooks.Close
                        System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Excel1)
                        System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Blatt)
                        Excel1 = Nothing
                        Blatt = Nothing
                        GC.Collect()

                    Catch ex2 As Exception
                        VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex2.Message, ex2.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)
                    End Try
                End Try

                Try
                    If Not System.IO.Directory.Exists(ZIEL_PFAD.Replace("\NEW\", "\" & Now.Year & "\")) Then System.IO.Directory.CreateDirectory(ZIEL_PFAD.Replace("\NEW\", "\" & Now.Year & "\"))

                    Dim newFile = MIC_FILE.Replace("\NEW\", "\" & Now.Year & "\")

                    While System.IO.File.Exists(newFile)
                        newFile = MIC_FILE.Replace("\NEW\", "\" & Now.Year & "\" & Now.ToString("ddMMyy_HHmmss") & "_")
                    End While

                    System.IO.File.Move(MIC_FILE, newFile)

                Catch ex2 As Exception
                    VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex2.Message, ex2.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)
                End Try

            Next
            Return True
        End If
        Return False
    End Function
    Function insertIntoSpedBuch_MIC(FilialenNr As Integer, AbfertigungsNr As Integer, AtlasBezNrNCTS As String, AtlasBezNrEZA As String, ByRef SPEDBUCH As VERAG_PROG_ALLGEMEIN.cSpeditionsbuch, MRN As String) As Boolean
        'Dim SPEDBUCH As New VERAG_PROG_ALLGEMEIN.cSpeditionsbuch

        Dim firmaTmp = VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA
        VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = VERAG_PROG_ALLGEMEIN.cAllgemein.getFirmaFromFiliale2(FilialenNr)
        If Not SPEDBUCH.hasEntry Then 'countSpedbuchEntrysFilialeAbf(FilialenNr, AbfertigungsNr) = 0 Then
            '  VERAG_PROG_ALLGEMEIN.cErrorHandler.sendERRORperMail("HEUREKA EZA ", "" & Me.eza_ObjectName, Now.ToString("yyyy.MM.dd HH:mm"), "al@verag.ag", "")
            SPEDBUCH.FilialenNr = FilialenNr
            SPEDBUCH.AbfertigungsNr = AbfertigungsNr
            SPEDBUCH.NewUNTER_NR()

            SPEDBUCH.Abfertigungsanzahl = 1
            SPEDBUCH.Fakturiert = 0
            SPEDBUCH.AtlasBezNrEZA = AtlasBezNrEZA
            SPEDBUCH.AtlasBezNrNCTS = AtlasBezNrNCTS
            SPEDBUCH.Zollsystem = "D"
            SPEDBUCH.Sachbearbeiter = "AUTO"
            SPEDBUCH.BelegNr = MRN

            Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
            SPEDBUCH.AvisoID = SQL.DLookup("tblSnd_AvisoID", "tblSendungen", " FilialenNr='" & FilialenNr & "' and AbfertigungsNr='" & AbfertigungsNr & "' ", "AVISO", 0)
            SPEDBUCH.SendungID = SQL.DLookup("tblSnd_SendungID", "tblSendungen", " FilialenNr='" & FilialenNr & "' and AbfertigungsNr='" & AbfertigungsNr & "' ", "AVISO", 0)

            Dim ZOLL_IMPORT As New DAKOSY_Worker.cZOLL_IMPORT

            Dim notfound = False
            Dim posAnzahl = 0
            Dim filialeBez = ""
            SPEDBUCH = ZOLL_IMPORT.IMPORT(SPEDBUCH, SPEDBUCH.AvisoID, SPEDBUCH.SendungID, "VERA", filialeBez, 2, AtlasBezNrEZA, "", notfound, True)

            If notfound Then Return False
            '   VERAG_PROG_ALLGEMEIN.cErrorHandler.sendERRORperMail("HEUREKA EZA !!", "" & Me.eza_ObjectName, Now.ToString("yyyy.MM.dd HH:mm"), "al@verag.ag", "")

            ' MsgBox(SPEDBUCH.FilialenNr & " - " & SPEDBUCH.AbfertigungsNr)
            VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = firmaTmp

            If SPEDBUCH.SAVE Then
                VERAG_PROG_ALLGEMEIN.cSendungen.SET_SpedbuchEntry(SPEDBUCH.SendungID, True)
                Return True
            Else
                Return False
            End If

        End If
        Return False

    End Function


    'Function countSpedbuchEntrysFilialeAbf(filiale, abfertigungsnummer) As Integer
    '    Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
    '    If If(abfertigungsnummer, "") = "" Then Return 0
    '    Return Sql.getValueTxtBySqlVarList("SELECT isnull(count(*),0) FROM Speditionsbuch WHERE [FilialenNr]='" & filiale & "' AND AbfertigungsNr='" & abfertigungsnummer & "'", "FMZOLL")
    'End Function


    Sub importFileFromDyMailAnhang(pfad, betreff)


        Try
            Dim sql As New VERAG_PROG_ALLGEMEIN.SQL
            Dim DS As VERAG_PROG_ALLGEMEIN.cDATENSERVER = Nothing

            'moveFile(d, VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\ECHTSYSTEM\nlc\")

            'IO.Directory.CreateDirectory(VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\ECHTSYSTEM\ZOLLDATEN\TEST3\" & betreff.ToString.Replace(",", ""))

            betreff = betreff.replace("*00*", "")

            If betreff.ToString.Contains("VBD - Versandbegleitdokument (DE), ") Then
                Dim found = False
                betreff = betreff.replace("WG: ", "")
                betreff = betreff.replace("FW: ", "")
                betreff = betreff.replace("VBD - Versandbegleitdokument (DE), ", "")

                If betreff.contains(",") Then
                    betreff = betreff.ToString.Split(",")(0).Trim
                End If
                'Dim dy_id As String = sql.getValueTxtBySql("SELECT isnull(ncts_dyaAnmID,-1)  FROM [tblDakosy_NCTSOut] inner join tblDakosy_Zollanmeldungen on dy_id=ncts_dyaAnmID where ncts_ObjectName='" & betreff.ToString.Trim & "' ", "FMZOLL")
                Dim dy_id As String = ""
                If betreff.ToString.Length > 15 Then
                    dy_id = sql.getValueTxtBySql("SELECT isnull(ncts_dyaAnmID,-1)  FROM [tblDakosy_NCTSOut004] inner join tblDakosy_Zollanmeldungen on dy_id=ncts_dyaAnmID where ncts_ObjectName='" & betreff.ToString.Trim & "' ", "FMZOLL")
                    If dy_id = "" Then
                        dy_id = sql.getValueTxtBySql("SELECT isnull(ncts_dyaAnmID,-1)  FROM [tblDakosy_NCTSOut004] inner join tblDakosy_Zollanmeldungen on dy_id=ncts_dyaAnmID where '" & betreff.ToString.Trim & "' LIKE ncts_ObjectName +'%'  and LEN(ncts_ObjectName)>=13 ", "FMZOLL")
                    End If
                Else
                    dy_id = sql.getValueTxtBySql("SELECT isnull(ncts_dyaAnmID,-1)  FROM [tblDakosy_NCTSOut004] inner join tblDakosy_Zollanmeldungen on dy_id=ncts_dyaAnmID where ncts_ObjectName='" & betreff.ToString.Trim & "' ", "FMZOLL")
                End If
                If IsNumeric(dy_id) AndAlso dy_id > 0 Then found = True

                '  IO.Directory.CreateDirectory(VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\ECHTSYSTEM\ZOLLDATEN\TEST3\")

                DS = New VERAG_PROG_ALLGEMEIN.cDATENSERVER("ZOLLDATEN", "VBD", dy_id, "", "", betreff.ToString.Replace("/", "-").Replace(",", "-").Replace("\", "-").Replace(":", "."), 0, False)
                DS.da_vorlage = False

                Dim ZIEL_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\ECHTSYSTEM\ZOLLDATEN\VBD\NOT_IDENTIFIED\"
                If IsNumeric(dy_id) AndAlso dy_id > 0 Then ZIEL_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\ECHTSYSTEM\ZOLLDATEN\VBD\" & Now.Year & "\" & Now.ToString("yyyyMMdd") & "\"
                If Not System.IO.Directory.Exists(ZIEL_PFAD) Then System.IO.Directory.CreateDirectory(ZIEL_PFAD)

                Dim destFull = ""
                moveFile(pfad, ZIEL_PFAD, destFull)


                If DS.insertDataToDATENSERVER(destFull) Then
                    If IsNumeric(dy_id) AndAlso dy_id > 0 Then
                        sql.doSQL("UPDATE tblDakosy_Zollanmeldungen SET dy_VBD_dsId='" & DS.da_id & "' where dy_id='" & dy_id & "'", "FMZOLL")
                        sql.doSQL("UPDATE Speditionsbuch SET DokumentId_VBD='" & DS.da_id & "' where AtlasBezNrNCTS='" & betreff.ToString.Trim & "' AND DokumentId_VBD is null", "FMZOLL") 'Falls Spedbuch schon zuvor generiert wurde!
                        doMailZollbeleg(DS.GET_TOP1_PATH, "VBD", dy_id)
                    End If
                End If


                If Not found Then 'OLD --- NCTS < 004!
                    'Dim dy_id As String = sql.getValueTxtBySql("SELECT isnull(ncts_dyaAnmID,-1)  FROM [tblDakosy_NCTSOut] inner join tblDakosy_Zollanmeldungen on dy_id=ncts_dyaAnmID where ncts_ObjectName='" & betreff.ToString.Trim & "' ", "FMZOLL")
                    dy_id = ""
                    If betreff.ToString.Length > 15 Then
                        dy_id = sql.getValueTxtBySql("SELECT isnull(ncts_dyaAnmID,-1)  FROM [tblDakosy_NCTSOut] inner join tblDakosy_Zollanmeldungen on dy_id=ncts_dyaAnmID where '" & betreff.ToString.Trim & "' LIKE ncts_ObjectName +'%'  and LEN(ncts_ObjectName)>=13 ", "FMZOLL")
                    Else
                        dy_id = sql.getValueTxtBySql("SELECT isnull(ncts_dyaAnmID,-1)  FROM [tblDakosy_NCTSOut] inner join tblDakosy_Zollanmeldungen on dy_id=ncts_dyaAnmID where ncts_ObjectName='" & betreff.ToString.Trim & "' ", "FMZOLL")
                    End If


                    '  IO.Directory.CreateDirectory(VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\ECHTSYSTEM\ZOLLDATEN\TEST3\")

                    DS = New VERAG_PROG_ALLGEMEIN.cDATENSERVER("ZOLLDATEN", "VBD", dy_id, "", "", betreff.ToString.Replace("/", "-").Replace(",", "-").Replace("\", "-").Replace(":", "."), 0, False)
                    DS.da_vorlage = False

                    ZIEL_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\ECHTSYSTEM\ZOLLDATEN\VBD\NOT_IDENTIFIED\"
                    If IsNumeric(dy_id) AndAlso dy_id > 0 Then ZIEL_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\ECHTSYSTEM\ZOLLDATEN\VBD\" & Now.Year & "\" & Now.ToString("yyyyMMdd") & "\"
                    If Not System.IO.Directory.Exists(ZIEL_PFAD) Then System.IO.Directory.CreateDirectory(ZIEL_PFAD)

                    destFull = ""
                    moveFile(pfad, ZIEL_PFAD, destFull)

                    Try

                        If DS.insertDataToDATENSERVER(destFull) Then
                            If IsNumeric(dy_id) AndAlso dy_id > 0 Then
                                sql.doSQL("UPDATE tblDakosy_Zollanmeldungen SET dy_VBD_dsId='" & DS.da_id & "' where dy_id='" & dy_id & "'", "FMZOLL")
                                sql.doSQL("UPDATE Speditionsbuch SET DokumentId_VBD='" & DS.da_id & "' where AtlasBezNrNCTS='" & betreff.ToString.Trim & "' AND DokumentId_VBD is null", "FMZOLL") 'Falls Spedbuch schon zuvor generiert wurde!
                                doMailZollbeleg(DS.GET_TOP1_PATH, "VBD", dy_id)
                            End If
                        End If
                    Catch ex As Exception
                        VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, "Pfad: " & destFull & vbNewLine & vbNewLine & ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)
                    End Try

                End If


                '=====ATEZ BEREITSTELLUNG==========
                cWorker_NCTS.checkATEZ_Bereitstellung_VBD(betreff.ToString.Trim, destFull)

                '==================================


            ElseIf betreff.ToString.Contains("DAKOSY GE - Abgabenbescheid/Befund , BezugsNr./LRN: ") Then '("DAKOSY GE - Abgabenbescheid/Befund , Bezugsnr.: ") Then
                betreff = betreff.replace("WG: ", "")
                betreff = betreff.replace("FW: ", "")
                betreff = betreff.replace("DAKOSY GE - Abgabenbescheid/Befund , BezugsNr./LRN: ", "") '("DAKOSY GE - Abgabenbescheid/Befund , Bezugsnr.: ", "")
                If betreff.ToString.Contains(",") Then
                    Dim sp = betreff.ToString.Split(",")


                    If betreff.contains("Registriernr.: ATD") Then ' ZNV!!!! ------> FUNKTIONIERT MIT NUEER ATLAS MRN Nummer nicht mehr  --> Keine ATD!
                        betreff = sp(0).Trim
                        Dim SND_ID = sql.getValueTxtBySql("SELECT TOP (1) [tblSnd_SendungID]  FROM [tblSendungen]  where '" & betreff.ToString.Trim & "' LIKE (cast(FilialenNr as varchar(4))+ '/' + cast(AbfertigungsNr as varchar(8))+'%')", "AVISO")
                        If IsNumeric(SND_ID) AndAlso SND_ID > 0 Then
                            DS = New VERAG_PROG_ALLGEMEIN.cDATENSERVER("ZOLLDATEN", "ZNV", "SND_ID_" & SND_ID, "", "", betreff.ToString.Replace("/", "-").Replace(",", "-").Replace("\", "-").Replace(":", "."), 0, False)
                            DS.da_vorlage = False
                            Dim destFull = ""
                            Dim ZIEL_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\ECHTSYSTEM\ZOLLDATEN\ZNV\" & Now.Year & "\" & Now.ToString("yyyyMMdd") & "\"
                            If Not System.IO.Directory.Exists(ZIEL_PFAD) Then System.IO.Directory.CreateDirectory(ZIEL_PFAD)
                            moveFile(pfad, ZIEL_PFAD, destFull)

                            If DS.insertDataToDATENSERVER(destFull) Then
                                ' sql.doSQL("UPDATE tblDakosy_Zollanmeldungen SET dy_STEUERBESCHEID_dsId='" & DS.da_id & "' where dy_id='" & dy_id & "'", "FMZOLL")
                                sql.doSQL("UPDATE Speditionsbuch SET DokumentId_Steuerbeleg='" & DS.da_id & "' where AtlasBezNrEZA='" & betreff.ToString.Trim & "' AND DokumentId_Steuerbeleg is null", "FMZOLL") 'Falls Spedbuch schon zuvor generiert wurde!
                                doMailZollbeleg(DS.GET_TOP1_PATH, "ZNV", SND_ID, betreff)
                            End If

                        End If


                    Else ' STB !!!!

                        betreff = sp(0).Trim
                        ' , RegistrierNr./MRN: 

                        Dim dy_id As String = ""
                        If betreff.ToString.Length > 15 Then
                            dy_id = sql.getValueTxtBySql("SELECT isnull(eza_dyaAnmID,-1)  FROM [tblDakosy_EZA] inner join tblDakosy_Zollanmeldungen on dy_id=eza_dyaAnmID where eza_ObjectName='" & betreff.ToString.Trim & "'", "FMZOLL")
                            If dy_id = "" Then
                                dy_id = sql.getValueTxtBySql("SELECT isnull(eza_dyaAnmID,-1)  FROM [tblDakosy_EZA] inner join tblDakosy_Zollanmeldungen on dy_id=eza_dyaAnmID where '" & betreff.ToString.Trim & "' LIKE eza_ObjectName +'%'  and LEN(eza_ObjectName)>=13", "FMZOLL")
                            End If
                        Else
                            dy_id = sql.getValueTxtBySql("SELECT isnull(eza_dyaAnmID,-1)  FROM [tblDakosy_EZA] inner join tblDakosy_Zollanmeldungen on dy_id=eza_dyaAnmID where eza_ObjectName='" & betreff.ToString.Trim & "'", "FMZOLL")
                        End If
                        '  IO.Directory.CreateDirectory(VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\ECHTSYSTEM\ZOLLDATEN\TEST3\")

                        DS = New VERAG_PROG_ALLGEMEIN.cDATENSERVER("ZOLLDATEN", "STEUERBESCHEID", dy_id, "", "", betreff.ToString.Replace("/", "-").Replace(",", "-").Replace("\", "-").Replace(":", "."), 0, False)
                        DS.da_vorlage = False

                        Dim ZIEL_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\ECHTSYSTEM\ZOLLDATEN\STEUERBESCHEID\NOT_IDENTIFIED\"
                        If IsNumeric(dy_id) AndAlso dy_id > 0 Then ZIEL_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\ECHTSYSTEM\ZOLLDATEN\STEUERBESCHEID\" & Now.Year & "\" & Now.ToString("yyyyMMdd") & "\"
                        If Not System.IO.Directory.Exists(ZIEL_PFAD) Then System.IO.Directory.CreateDirectory(ZIEL_PFAD)

                        Dim destFull = ""
                        moveFile(pfad, ZIEL_PFAD, destFull)

                        If DS.insertDataToDATENSERVER(destFull) Then
                            If IsNumeric(dy_id) AndAlso dy_id > 0 Then
                                sql.doSQL("UPDATE tblDakosy_Zollanmeldungen SET dy_STEUERBESCHEID_dsId='" & DS.da_id & "' where dy_id='" & dy_id & "'", "FMZOLL")
                                sql.doSQL("UPDATE Speditionsbuch SET DokumentId_Steuerbeleg='" & DS.da_id & "' where AtlasBezNrEZA='" & betreff.ToString.Trim & "' AND DokumentId_Steuerbeleg is null", "FMZOLL") 'Falls Spedbuch schon zuvor generiert wurde!
                                doMailZollbeleg(DS.GET_TOP1_PATH, "STB", dy_id)
                            End If
                        End If

                    End If
                End If

                'ABD
            ElseIf betreff.ToString.Contains("ABD - Ausfuhrbegleitdokument (DE), ") Then
                betreff = betreff.replace("WG: ", "")
                betreff = betreff.replace("FW: ", "")
                betreff = betreff.replace("*00*", "")
                betreff = betreff.replace("ABD - Ausfuhrbegleitdokument (DE), ", "")
                If betreff.ToString.Contains(",") Then
                    Dim sp = betreff.ToString.Split(",")
                    betreff = sp(0).Trim

                    Dim dy_id As String = ""
                    If betreff.ToString.Length > 15 Then
                        dy_id = sql.getValueTxtBySql("SELECT isnull(aes_dyaAnmID,-1)  FROM [tblDakosy_AES] inner join tblDakosy_Zollanmeldungen on dy_id=aes_dyaAnmID where aes_ObjectName='" & betreff.ToString.Trim & "'", "FMZOLL")
                        If dy_id = "" Then
                            dy_id = sql.getValueTxtBySql("SELECT isnull(aes_dyaAnmID,-1)  FROM [tblDakosy_AES] inner join tblDakosy_Zollanmeldungen on dy_id=aes_dyaAnmID where '" & betreff.ToString.Trim & "' LIKE aes_ObjectName +'%'  and LEN(aes_ObjectName)>=13", "FMZOLL")
                        End If
                    Else
                        dy_id = sql.getValueTxtBySql("SELECT isnull(aes_dyaAnmID,-1)  FROM [tblDakosy_AES] inner join tblDakosy_Zollanmeldungen on dy_id=aes_dyaAnmID where aes_ObjectName='" & betreff.ToString.Trim & "'", "FMZOLL")
                    End If
                    '  IO.Directory.CreateDirectory(VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\ECHTSYSTEM\ZOLLDATEN\TEST3\")

                    DS = New VERAG_PROG_ALLGEMEIN.cDATENSERVER("ZOLLDATEN", "ABD", dy_id, "", "", betreff.ToString.Replace("/", "-").Replace(",", "-").Replace("\", "-").Replace(":", "."), 0, False)
                    DS.da_vorlage = False

                    Dim ZIEL_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\ECHTSYSTEM\ZOLLDATEN\ABD\NOT_IDENTIFIED\"
                    If IsNumeric(dy_id) AndAlso dy_id > 0 Then ZIEL_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\ECHTSYSTEM\ZOLLDATEN\ABD\" & Now.Year & "\" & Now.ToString("yyyyMMdd") & "\"
                    If Not System.IO.Directory.Exists(ZIEL_PFAD) Then System.IO.Directory.CreateDirectory(ZIEL_PFAD)

                    Dim destFull = ""
                    moveFile(pfad, ZIEL_PFAD, destFull)

                    If DS.insertDataToDATENSERVER(destFull) Then
                        If IsNumeric(dy_id) AndAlso dy_id > 0 Then
                            sql.doSQL("UPDATE tblDakosy_Zollanmeldungen SET dy_ABD_dsId='" & DS.da_id & "' where dy_id='" & dy_id & "'", "FMZOLL")
                            sql.doSQL("UPDATE Speditionsbuch SET DokumentId_ABD='" & DS.da_id & "' where AtlasBezNrEZA='" & betreff.ToString.Trim & "' AND DokumentId_ABD is null", "FMZOLL") 'Falls Spedbuch schon zuvor generiert wurde!
                            doMailZollbeleg(DS.GET_TOP1_PATH, "ABD", dy_id)
                        End If
                    End If

                End If

                'AVM
            ElseIf betreff.ToString.Contains("AVM - Ausgangsvermerk (DE), ") Then
                betreff = betreff.replace("WG: ", "")
                betreff = betreff.replace("FW: ", "")
                betreff = betreff.replace("AVM - Ausgangsvermerk (DE), ", "")
                If betreff.ToString.Contains(",") Then
                    Dim sp = betreff.ToString.Split(",")
                    betreff = sp(0).Trim

                    Dim dy_id As String = ""
                    If betreff.ToString.Length > 15 Then
                        dy_id = sql.getValueTxtBySql("SELECT isnull(aes_dyaAnmID,-1)  FROM [tblDakosy_AES] inner join tblDakosy_Zollanmeldungen on dy_id=aes_dyaAnmID where aes_ObjectName='" & betreff.ToString.Trim & "'", "FMZOLL")
                        If dy_id = "" Then
                            dy_id = sql.getValueTxtBySql("SELECT isnull(aes_dyaAnmID,-1)  FROM [tblDakosy_AES] inner join tblDakosy_Zollanmeldungen on dy_id=aes_dyaAnmID where '" & betreff.ToString.Trim & "' LIKE aes_ObjectName +'%'  and LEN(aes_ObjectName)>=13", "FMZOLL")
                        End If
                    Else
                        dy_id = sql.getValueTxtBySql("SELECT isnull(aes_dyaAnmID,-1)  FROM [tblDakosy_AES] inner join tblDakosy_Zollanmeldungen on dy_id=aes_dyaAnmID where aes_ObjectName='" & betreff.ToString.Trim & "'", "FMZOLL")
                    End If
                    '  IO.Directory.CreateDirectory(VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\ECHTSYSTEM\ZOLLDATEN\TEST3\")

                    DS = New VERAG_PROG_ALLGEMEIN.cDATENSERVER("ZOLLDATEN", "AVM", dy_id, "", "", betreff.ToString.Replace("/", "-").Replace(",", "-").Replace("\", "-").Replace(":", "."), 0, False)
                    DS.da_vorlage = False

                    Dim ZIEL_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\ECHTSYSTEM\ZOLLDATEN\AVM\NOT_IDENTIFIED\"
                    If IsNumeric(dy_id) AndAlso dy_id > 0 Then ZIEL_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\ECHTSYSTEM\ZOLLDATEN\AVM\" & Now.Year & "\" & Now.ToString("yyyyMMdd") & "\"
                    If Not System.IO.Directory.Exists(ZIEL_PFAD) Then System.IO.Directory.CreateDirectory(ZIEL_PFAD)

                    Dim destFull = ""
                    moveFile(pfad, ZIEL_PFAD, destFull)

                    If DS.insertDataToDATENSERVER(destFull) Then
                        If IsNumeric(dy_id) AndAlso dy_id > 0 Then
                            sql.doSQL("UPDATE tblDakosy_Zollanmeldungen SET dy_AVM_dsId='" & DS.da_id & "' where dy_id='" & dy_id & "'", "FMZOLL")
                            sql.doSQL("UPDATE Speditionsbuch SET DokumentId_AVM='" & DS.da_id & "' where AtlasBezNrEZA='" & betreff.ToString.Trim & "' AND DokumentId_AVM is null", "FMZOLL") 'Falls Spedbuch schon zuvor generiert wurde!
                            doMailZollbeleg(DS.GET_TOP1_PATH, "AVM", dy_id)
                        End If
                    End If

                End If
            End If

            ' GENERELLES NOT IDENTIFIED!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!




            '""""""""""""
            ' If Not alreadyMoved Then

            ' End If

        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)
        End Try

    End Sub


    Sub importFileFromUTAMailAnhang(pfad, betreff)


        Try
            Dim sql As New VERAG_PROG_ALLGEMEIN.SQL
            Dim DS As VERAG_PROG_ALLGEMEIN.cDATENSERVER = Nothing
            Dim uta As New cUTA
            uta.initImportPfade("UTA")
            Dim Zielpfad = uta.VERARBEITUNG_PFAD


            If betreff.ToString.ToLower.Contains("uta") Then
                Dim found = False
                betreff = betreff.replace("WG: ", "")
                betreff = betreff.replace("FW: ", "")
                moveFile(pfad, Zielpfad)
            End If


        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)
        End Try

    End Sub

    Private Sub LinkLabel4_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel4.LinkClicked
        Me.Cursor = Cursors.WaitCursor
        Try
            DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0008", True) 'TESTSYSTEM
            Dim erg = DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0008", False) 'ECHTSYSTEM
            showPic(erg, picC0008)
        Catch ex As Exception : VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name) : End Try
        Me.Cursor = Cursors.Default
    End Sub


    Sub showPic(ok As Boolean, pic As PictureBox)
        pic.Visible = True
        If ok Then
            pic.BackgroundImage = My.Resources.ok
        Else
            pic.BackgroundImage = My.Resources.del
        End If
        timer.Enabled = True
    End Sub
    Private Sub timer_Tick(sender As Object, e As EventArgs) Handles timer.Tick
        timer.Enabled = False
        picC0008.Visible = False
        PictureBox1.Visible = False
        PictureBox2.Visible = False
        PictureBox3.Visible = False
        PictureBox4.Visible = False
        PictureBox5.Visible = False
        PictureBox6.Visible = False
        PictureBox7.Visible = False
        PictureBox8.Visible = False
        PictureBox9.Visible = False
        PictureBox10.Visible = False
        PictureBox11.Visible = False
        PictureBox12.Visible = False
        PictureBox13.Visible = False
        PictureBox14.Visible = False
        PictureBox18.Visible = False
        PictureBox19.Visible = False
        PictureBox20.Visible = False
        PictureBox21.Visible = False

    End Sub

    Private Sub LinkLabel5_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel5.LinkClicked
        Me.Visible = False
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = True
        Dim f As New frmDYNachrichtenVerarbeitung
        f.saveVerwahrung = cbxGestellungspeichern.Checked
        f.sendMail = cbxVW_Infomail.Checked
        f.GESTELLUNG_TESTLAUF = cbxGESTELLUNG_TESTLAUF.Checked
        f.ShowDialog()
        Me.Visible = True
    End Sub

    Private Sub LinkLabel6_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel6.LinkClicked
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = True
        If DAKOSY_Worker.cDakosyFunftions.sendData() Then ' Application.StartupPath & "\Dakosy_SEND\")

        End If

        Exit Sub

        Dim dt = DAKOSY_Worker.cDakosyFunftions.getKDData()

        If dt IsNot Nothing Then
            Dim saveFile = ""
            If DAKOSY_Worker.cDakosyFunftions.generateVERAGKdData(dt, Application.StartupPath & "\Dakosy_SEND\", saveFile) Then
                MsgBox(saveFile)
            End If
        End If
    End Sub



    Private Sub LinkLabel7_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel7.LinkClicked
        Me.Cursor = Cursors.WaitCursor
        Try
            DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0017", True) 'TESTSYSTEM
            Dim erg = DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0017", False) 'ECHTSYSTEM
            showPic(erg, PictureBox1)
        Catch ex As Exception : VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name) : End Try
        Me.Cursor = Cursors.Default
    End Sub

    Private Sub LinkLabel8_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel8.LinkClicked
        Me.Cursor = Cursors.WaitCursor
        Try
            DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0014", True) 'TESTSYSTEM
            Dim erg = DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0014", False) 'ECHTSYSTEM
            showPic(erg, PictureBox2)
        Catch ex As Exception : VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name) : End Try
        Me.Cursor = Cursors.Default
    End Sub

    Private Sub LinkLabel2_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel2.LinkClicked

    End Sub

    Private Sub pnl_Paint(sender As Object, e As PaintEventArgs) Handles pnl.Paint

    End Sub

    Private Sub LinkLabel9_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel9.LinkClicked
        Me.Visible = False
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
        Dim f As New frmDYNachrichtenVerarbeitung
        f.saveVerwahrung = cbxGestellungspeichern.Checked
        f.sendMail = cbxVW_Infomail.Checked
        f.GESTELLUNG_TESTLAUF = cbxGESTELLUNG_TESTLAUF.Checked
        f.ShowDialog()
        Me.Visible = True
    End Sub

    Private Sub LinkLabel10_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel10.LinkClicked
        Me.Cursor = Cursors.WaitCursor
        Try
            DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0010", True) 'TESTSYSTEM
            Dim erg = DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0010", False) 'ECHTSYSTEM
            showPic(erg, PictureBox3)
        Catch ex As Exception : VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name) : End Try
        Me.Cursor = Cursors.Default
    End Sub

    Private Sub LinkLabel11_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel11.LinkClicked
        Me.Cursor = Cursors.WaitCursor
        Try
            DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("A0122", True) 'TESTSYSTEM
            Dim erg = DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("A0122", False) 'ECHTSYSTEM
            showPic(erg, PictureBox4)
        Catch ex As Exception : VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name) : End Try
        Me.Cursor = Cursors.Default
    End Sub

    Private Sub LinkLabel12_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel12.LinkClicked
        Me.Cursor = Cursors.WaitCursor
        Try
            DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("A0127", True) 'TESTSYSTEM
            Dim erg = DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("A0127", False) 'ECHTSYSTEM
            showPic(erg, PictureBox5)
        Catch ex As Exception : VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name) : End Try
        Me.Cursor = Cursors.Default
    End Sub

    Private Sub LinkLabel13_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel13.LinkClicked
        Me.Cursor = Cursors.WaitCursor
        Try
            DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("I0400", True) 'TESTSYSTEM
            Dim erg = DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("I0400", False) 'ECHTSYSTEM
            showPic(erg, PictureBox6)
        Catch ex As Exception : VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name) : End Try
        Me.Cursor = Cursors.Default
    End Sub

    Private Sub LinkLabel14_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel14.LinkClicked
        Me.Cursor = Cursors.WaitCursor
        Try
            DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0013", True) 'TESTSYSTEM
            Dim erg = DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0013", False) 'ECHTSYSTEM
            showPic(erg, PictureBox7)
        Catch ex As Exception : VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name) : End Try
        Me.Cursor = Cursors.Default

    End Sub

    Private Sub LinkLabel15_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel15.LinkClicked
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
        If DAKOSY_Worker.cDakosyFunftions.sendData() Then ' Application.StartupPath & "\Dakosy_SEND\")

        End If

    End Sub

    Private Sub LinkLabel16_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel16.LinkClicked
        Me.Cursor = Cursors.WaitCursor
        Try
            DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("I0200", True) 'TESTSYSTEM
            Dim erg = DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("I0200", False) 'ECHTSYSTEM
            showPic(erg, PictureBox8)
        Catch ex As Exception : VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name) : End Try
        Me.Cursor = Cursors.Default
    End Sub


    Public Function moveFile(file, toDirectory, Optional ByRef dest = "") ', Optional unlockFile = True)
        Try
            If Not System.IO.File.Exists(file) Then Return False
            If Not System.IO.Directory.Exists(toDirectory) Then System.IO.Directory.CreateDirectory(toDirectory)
            dest = toDirectory & cut_file(file).Replace("lock_", "")
            If System.IO.File.Exists(dest) Then
                dest = toDirectory & Now.ToString("yyMMdd_HHmmss.fff_") & cut_file(file).Replace("lock_", "")
            End If
            System.IO.File.Move(file, dest) ' Verschiebt die Datei
            Return True
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace & vbNewLine & "Datei: " & file & vbNewLine & "DestPfad: " & toDirectory, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try
        Return False
    End Function
    Public Function lockFile(file) As String
        Try
            If Not System.IO.File.Exists(file) Then Return file
            If file.ToString.Contains("lock_") Then Return file
            Dim FIO As New FileInfo(file)
            Dim dest = FIO.Directory.FullName & "\lock_" & FIO.Name
            If System.IO.File.Exists(dest) Then Return file
            System.IO.File.Move(file, dest) ' Verschiebt die Datei
            Return dest
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace & vbNewLine & "Datei: " & file, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try
        Return file
    End Function

    Public Function unlockFile(file) As String
        Try
            Dim dest = file.ToString.Replace("\lock_", "")
            If Not System.IO.File.Exists(file) Then Return False
            If Not System.IO.File.Exists(dest) Then Return False

            System.IO.File.Move(file, dest) ' Verschiebt die Datei
            Return dest
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace & vbNewLine & "Datei: " & file, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try
        Return file
    End Function
    Public Function moveFile_DateBack(file, toDirectory, Optional ByRef dest = "")
        If Not System.IO.File.Exists(file) Then Return False
        If Not System.IO.Directory.Exists(toDirectory) Then System.IO.Directory.CreateDirectory(toDirectory)
        dest = toDirectory & cut_file(file)
        Dim fio As System.IO.FileInfo = New FileInfo(file)
        Dim ext = fio.Extension
        If System.IO.File.Exists(dest) Then
            dest = toDirectory & cut_file(file).Replace(ext, Now.ToString("_yyMMdd_HHmmss.fff")) & ext
        End If
        System.IO.File.Move(file, dest) ' Verschiebt die Datei
        Return True
    End Function

    Public Function copyFile_DateBack(file, toDirectory, Optional ByRef dest = "")
        If Not System.IO.File.Exists(file) Then Return False
        If Not System.IO.Directory.Exists(toDirectory) Then System.IO.Directory.CreateDirectory(toDirectory)
        dest = toDirectory & cut_file(file)
        Dim fio As System.IO.FileInfo = New FileInfo(file)
        Dim ext = fio.Extension
        If System.IO.File.Exists(dest) Then
            dest = toDirectory & cut_file(file).Replace(ext, Now.ToString("_yyMMdd_HHmmss.fff")) & ext
        End If
        System.IO.File.Copy(file, dest) ' Verschiebt die Datei
        Return True
    End Function

    'Public Function getFileName_DateBack(file) As String
    '    If Not IO.File.Exists(file) Then Return False

    '    Dim fio As IO.FileInfo = New FileInfo(file)
    '    Dim ext = fio.Extension

    '    Return cut_file(file).Replace(ext, Now.ToString("_yyMMdd_HHmmss.fff")) & ext
    'End Function
    Public Function getFileName(file) As String
        If Not System.IO.File.Exists(file) Then Return False

        Dim fio As System.IO.FileInfo = New FileInfo(file)

        Return fio.Name
    End Function


    Public Function copyFile(file, toDirectory, Optional ByRef dest = "")
        Dim fileINfo As New FileInfo(file)
        If Not HasDirectoryReadAccess(fileINfo.DirectoryName) Then Return False
        If Not fileINfo.Exists Then Return False
        If Not System.IO.Directory.Exists(toDirectory) Then System.IO.Directory.CreateDirectory(toDirectory)
        dest = toDirectory & ".tmp_" & cut_file(file)
        Dim tmpExt = ""
        While System.IO.File.Exists(dest) Or System.IO.File.Exists(dest).ToString.Replace(".tmp_", "") 'wenn mit oder ohen .tmp_ existiert...
            tmpExt = Now.ToString("yyMMdd_HHmmss.fff_")
            dest = toDirectory & ".tmp_" & tmpExt & cut_file(file)
        End While
        System.IO.File.Copy(file, dest) ' Verschiebt die Datei
        System.IO.File.Move(dest, dest.ToString.Replace(".tmp_" & tmpExt, "")) ' Umbenennen der Datei --> der "." am Anfang dient dazu, dass die Datei nicht abgegriffen wird, während sie kopiert wird!
        dest = dest.ToString.Replace(".tmp_" & tmpExt, "")
        Return True

    End Function


    Function HasDirectoryReadAccess(path As String) As Boolean
        Try
            If Not System.IO.Directory.Exists(path) Then Return False
            Dim entries = System.IO.Directory.EnumerateFileSystemEntries(path)
            Dim first = entries.FirstOrDefault()
            Return True
        Catch ex As UnauthorizedAccessException
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name, ERROR_OP.MAIL)
            Return False
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name, ERROR_OP.MAIL)
            Return False
        End Try
    End Function

    Public Function cut_file(ByVal file As String) As String ' Funktion zum Entfernen der Backslashs / Ordner While file.Contains("\") file = file.Remove(0, 1) End While Return file End Function 
        While file.Contains("\")
            file = file.Remove(0, 1)
        End While
        Return file
    End Function

    Private Sub LinkLabel17_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel17.LinkClicked
        getETZBundesanzeiger_ImportCodenummern()
    End Sub
    Sub getETZBundesanzeiger_ImportCodenummern()
        Dim bool = False
        Dim zip = getNachrichtenDatenFromBundesanzeiger()
        If zip <> "" Then
            bool = loadEZTZipToDB(zip)

        End If
        showPic(bool, PictureBox9)
    End Sub

    Function getEZB_Waehrungskurse() As Boolean
        Dim MyData As String = ""
        getEZB_Waehrungskurse = False
        Try
            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12

            Using WC As New System.Net.WebClient()
                ' C0008_URL()
                WC.Encoding = ASCIIEncoding.UTF8
                Dim URL = "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml" 'cDY_Paramter.GET_PARAM_ByName("C0008_URL", TESTSYSTEM)
                If URL = String.Empty Then Return False

                MyData = WC.DownloadString(URL)
                Dim doc As New XmlDocument()
                doc.LoadXml(MyData)
                If doc.HasChildNodes Then

                    If doc.GetElementsByTagName("gesmes:Envelope").Count > 0 Then
                        If doc.GetElementsByTagName("gesmes:Envelope")(0).HasChildNodes AndAlso doc.GetElementsByTagName("gesmes:Envelope")(0).ChildNodes.Count > 2 Then
                            Dim Cube = doc.GetElementsByTagName("gesmes:Envelope")(0).ChildNodes(2)
                            If Cube.HasChildNodes AndAlso Cube.ChildNodes(0).Name = "Cube" And Cube.ChildNodes(0).Attributes.Count > 0 Then
                                Dim Cube2 = Cube.ChildNodes(0)
                                Dim datum As Date = DateTime.ParseExact(Cube2.Attributes(0).Value, "yyyy-MM-dd", Nothing)
                                If Cube2.HasChildNodes Then
                                    For Each Entry As XmlNode In Cube2.ChildNodes

                                        Dim EZB As New VERAG_PROG_ALLGEMEIN.cEZB_Waehrungskurse

                                        '                  Dim Code = ""
                                        'Dim Description = ""
                                        ' Dim StartDate = Nothing
                                        ' Dim EndDate = Nothing
                                        If Entry.Attributes("currency") IsNot Nothing Then EZB.ezb_waehrungscode = Entry.Attributes("currency").Value
                                        If Entry.Attributes("rate") IsNot Nothing Then EZB.ezb_kurs = CDbl(Entry.Attributes("rate").Value.Replace(".", ","))
                                        'If Entry.SelectNodes("Description").Count > 0 Then EZB.ezb_waehrungsschluessel = Entry.SelectNodes("Description")(0).InnerText
                                        EZB.ezb_datum = datum 'CDate(Entry.SelectNodes("StartDate")(0).InnerText)
                                        EZB.SAVE()
                                        '  LC.Add(New VERAG_PROG_ALLGEMEIN.cEZB_Waehrungskurse(Code, Description, StartDate, EndDate))
                                        '   VERAG_PROG_ALLGEMEIN.
                                        getEZB_Waehrungskurse = True

                                        Try
                                            Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
                                            SQL.doSQL("IF NOT EXISTS (SELECT * FROM baskur WHERE baskur_code ='" & EZB.ezb_waehrungscode & "' AND  baskur_gbdat =cast(getdate() as date) ) 
                                                        BEGIN   
                                                            INSERT INTO [baskur] 
                                                               ([baskur_code],[baskur_typ],[baskur_bez],[baskur_faktor],[baskur_kurs],[baskur_gvdat],[baskur_gbdat],[baskur_edat],[baskur_adat],[baskur_sb],[baskur_cdealt],[baskur_wkz]) 
                                                               VALUES ('" & EZB.ezb_waehrungscode & "',1,'-',1," & Entry.Attributes("rate").Value & ",cast(getdate() as date),cast(getdate() as date),getdate(),getdate(),'VRG',000,'EUR')
                                                        END", "ATLAS")

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

                                        End Try

                                    Next
                                End If
                                VERAG_PROG_ALLGEMEIN.cEZB_Waehrungskurse.UPDATE_Waehrungstabelle(datum) ' Waehrungstabelle befüllen

                            End If

                        End If
                    End If
                End If
                'If LC.Count > 0 Then
                '    Return LC.INSERT_DB(TESTSYSTEM)
                'End If
            End Using

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


    End Function


    Function getUID_Pruefung(maxAnz As Integer, Optional finanzOnline As Boolean = True, Optional veroegerungMs As Integer = 1000) As Boolean


        Dim Empfaenger = cMitarbeiter.GetEMailRecipientForEmailNotification("UID-Prüfung", 19)
        getUID_Pruefung(maxAnz, "VERAG 360 GmbH", "UID Prüfung VERAG-360", Empfaenger, "",,, True, finanzOnline, veroegerungMs, True)
        Empfaenger = cMitarbeiter.GetEMailRecipientForEmailNotification("UID-Prüfung", 1)
        getUID_Pruefung(maxAnz, "VERAG", "UID Prüfung VERAG", Empfaenger, "al@verag.ag",,, True, finanzOnline, veroegerungMs, True)
        Empfaenger = cMitarbeiter.GetEMailRecipientForEmailNotification("UID-Prüfung", 20)
        getUID_Pruefung(maxAnz, "IMEX", "UID Prüfung IMEX", Empfaenger, "al@verag.ag",,, True, finanzOnline, veroegerungMs)
        Empfaenger = cMitarbeiter.GetEMailRecipientForEmailNotification("UID-Prüfung", 24)
        getUID_Pruefung(maxAnz, "AMBAR", "UID Prüfung AMBAR", Empfaenger, "al@verag.ag",,, True, finanzOnline, veroegerungMs)
        Empfaenger = cMitarbeiter.GetEMailRecipientForEmailNotification("UID-Prüfung", 21)
        getUID_Pruefung(maxAnz, "UNISPED", "UID Prüfung UNISPED", Empfaenger, "al@verag.ag",,, True, finanzOnline, veroegerungMs)

    End Function

    Function sendWOELFL_USTVAntraege(art As String, positionDaten As Boolean, Optional Mail_To As String = "", Optional Mail_CC As String = "", Optional Mail_BCC As String = "")
        Try
            Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
            Dim dt = Nothing
            If positionDaten Then
                dt = SQL.loadDgvBySql(" 
                            SELECT   [tblUStVAntrag].UStVAn_ID,[UStVAn_KuNr]VERAGKundenNr
                             ,Adressen.WölflKundenNr PartnerKundenNr
                                  --,[UStVAn_LandNr]
                                  ,cast([UStVAn_ReDatVon]as date)ReDatVon
                                  ,cast([UStVAn_ReDatBis]as date)ReDatBis
                                  ,LND.LandKz AntragsLand
	                              ,[UStVAn_Name]Firma
                                  ,isnull([UStVAn_Straße],'')Strasse
                                  ,isnull([UStVAn_LandKz],'')LandKz
                                  ,isnull([UStVAn_PLZ],'')Plz
                                  ,isnull([UStVAn_Ort],'') Ort 
                                  , isnull(cast( cast([UStVAn_AntragEingereichtAm] as date)as varchar),'') AntragEingereichtAm
                                  ,isnull([UStVAn_VZBetrag],'')VZBetrag
                                  , isnull(cast( cast([UStVAn_VZDatum] as date)as varchar),'') VZDatum 
                                  ,isnull([UStVAn_RZBetragVZ],'')RZBetragVZ 
                                  , isnull(cast( cast([UStVAn_RZDatumVZ] as date)as varchar),'') RZDatumVZ 
                                  ,isnull([UStVAn_Währungscode],'')Währungscode
                                  ,isnull([UStVAn_USteuerbetrag],'')USteuerbetrag
                                  ,isnull([UStVAn_Erstattungsbetrag],'')Erstattungsbetrag
                                  ,isnull([UStVAn_USteuerbetragEUR],'')USteuerbetragEUR
                                  ,isnull([UStVAn_ErstattungsbetragEUR],'') ErstattungsbetragEUR 
	  
	                              ,cast([UStVPo_ReDat] as date) PosRgDat
                                  ,[UStVPo_ReNr] PosRgNr
                                  ,[UStVPo_Leistender] PosLeistender
	                              ,[UStVPo_USteuerbetrag] PosUBetrag
                                  ,[UStVPo_USteuerbetragEUR]PosUBetragEUR
                                  ,[UStVPo_Umrechnungskurs] PosUmrechnungskurs
                                  ,[UStVPo_Leistungsbezeichnung] PosLeistungsbezeichnung
      
      
                              FROM [VERAG].[dbo].[tblUStVAntrag]
                              inner join tblUStVPositionen  on [tblUStVAntrag].UStVAn_ID=tblUStVPositionen.UStVAn_ID
                              inner join adressen on AdressenNr=UStVAn_KuNr
                              inner join [Länderverzeichnis für die Außenhandelsstatistik] as LND on LandNr=UStVAn_LandNr
                              where UStVAn_ReDatVon>= cast(('01.01.' + cast((DATEPART(YEAR,getdate())-1) as varchar)) as date)
                              and (UStVAn_KuNr between 150000 and 159999 OR UStVAn_KuNr between 180000 and 189999 )
                              order by UStVAn_KuNr,[UStVAn_LandNr],UStVAn_ReDatVon
                            ", "FMZOLL")
            Else
                dt = SQL.loadDgvBySql(" 
                            SELECT   [tblUStVAntrag].UStVAn_ID,[UStVAn_KuNr]VERAGKundenNr
                            ,isnull(WölflKundenNr,'')PartnerKundenNr
                                  --,[UStVAn_LandNr]
                                  ,cast([UStVAn_ReDatVon]as date)ReDatVon
                                  ,cast([UStVAn_ReDatBis]as date)ReDatBis
                                  ,LND.LandKz AntragsLand
	                              ,[UStVAn_Name]Firma
                                  ,isnull([UStVAn_Straße],'')Strasse
                                  ,isnull([UStVAn_LandKz],'')LandKz
                                  ,isnull([UStVAn_PLZ],'')Plz
                                  ,isnull([UStVAn_Ort],'') Ort 
                                  , isnull(cast( cast([UStVAn_AntragEingereichtAm] as date)as varchar),'') AntragEingereichtAm
                                  ,isnull([UStVAn_VZBetrag],'')VZBetrag
                                  , isnull(cast( cast([UStVAn_VZDatum] as date)as varchar),'') VZDatum 
                                  ,isnull([UStVAn_RZBetragVZ],'')RZBetragVZ 
                                  , isnull(cast( cast([UStVAn_RZDatumVZ] as date)as varchar),'') RZDatumVZ 
                                  ,isnull([UStVAn_Währungscode],'')Waehrungscode
                                  ,isnull([UStVAn_USteuerbetrag],'')USteuerbetrag
                                  ,isnull([UStVAn_Erstattungsbetrag],'')Erstattungsbetrag
                                  ,isnull([UStVAn_USteuerbetragEUR],'')USteuerbetragEUR
                                  ,isnull([UStVAn_ErstattungsbetragEUR],'') ErstattungsbetragEUR 
	                                FROM [VERAG].[dbo].[tblUStVAntrag]
                              inner join [Länderverzeichnis für die Außenhandelsstatistik] as LND on LandNr=UStVAn_LandNr
                              inner join Adressen on UStVAn_KuNr=AdressenNr
                                where UStVAn_ReDatVon>= cast(('01.01.' + cast((DATEPART(YEAR,getdate())-1) as varchar)) as date)
                              and (UStVAn_KuNr between 150000 and 159999 OR UStVAn_KuNr between 180000 and 189999 )
                              order by UStVAn_KuNr,[UStVAn_LandNr],UStVAn_ReDatVon
                            ", "FMZOLL")
            End If


            If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then
                Dim PDF = VERAG_PROG_ALLGEMEIN.cProgramFunctions.genCSVFromDT(dt, False,, "USTV_" & Now.ToString("ddMMyyyy"))
                If PDF <> "" Then
                    Select Case art
                        Case "MAIL"
                            Dim list As New List(Of String)
                            list.Add(PDF)
                            Dim Body = "Anbei befindet sich die Auflistung der USTV-Anträge.<br>"

                            Body &= "<br><br>Erstellt am: " & Now.ToShortDateString & ", um " & Now.ToShortTimeString
                            Body &= "<br><br>Automatisch generiertes E-Mail."
                            Dim Mail_betreff = "USTV-Anträge"

                            VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(Mail_To, Mail_betreff, Body, getAbsenderEmail(),, False, Mail_CC, Mail_BCC, list)


                        Case "FTP"


                            Dim sftpHost As String = "195.70.110.195" ' Deine SFTP-Server-IP
                            Dim sftpPort As Integer = 22 ' Standard-SFTP-Port (ändern, falls nötig)
                            Dim sftpUsername As String = "verag"
                            Dim sftpPassword As String = "Di1543V!r205"
                            Dim localFilePath As String = PDF
                            Dim remoteDirectory As String = "/verag2rmc/" ' Zielordner auf dem SFTP-Server

                            Try
                                ' Verbindung zum SFTP-Server herstellen
                                Using sftpClient As New SftpClient(sftpHost, sftpPort, sftpUsername, sftpPassword)
                                    sftpClient.Connect()
                                    Console.WriteLine("SFTP-Verbindung hergestellt.")

                                    ' Datei hochladen
                                    Using fileStream As New FileStream(localFilePath, FileMode.Open)
                                        sftpClient.UploadFile(fileStream, remoteDirectory & System.IO.Path.GetFileName(localFilePath))
                                    End Using

                                    Console.WriteLine("Datei erfolgreich hochgeladen!")
                                    sftpClient.Disconnect()
                                End Using
                            Catch ex As Exception
                                Console.WriteLine("Fehler: " & ex.Message)
                            End Try
                    End Select

                End If
            End If
            Return True
        Catch ex As Exception
            MsgBox(ex.Message & ex.StackTrace)
            Return False
        End Try
    End Function
    Private Function ValidateServerCertificate(sender As Object, certificate As X509Certificate, chain As X509Chain, sslPolicyErrors As SslPolicyErrors) As Boolean
        Return True
    End Function
    Function getUID_Pruefung(maxAnz As Integer, Mail_FIMRA As String, Mail_betreff As String, Mail_To As String, Optional Mail_CC As String = "", Optional Mail_BCC As String = "", Optional TageZurueck As String = "", Optional setKundenvermerk As Boolean = False, Optional finanzOnline As Boolean = True, Optional veroegerungMs As Integer = 1500, Optional updateFIBU As Boolean = False) As Boolean
        Dim firmatmp = VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA
        Try
            VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = Mail_FIMRA
            Dim dateBack = If(TageZurueck <> "", CDate(Now.AddDays(TageZurueck * -1)), Nothing)
            Dim dt = VERAG_PROG_ALLGEMEIN.cUIDPruefung.doUIDPruefungALL(dateBack, True, False, maxAnz, False, finanzOnline, veroegerungMs)
            If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then
                Dim PDF = VERAG_PROG_ALLGEMEIN.cProgramFunctions.genExcelFromDT_NEW(dt,,,,, False)
                If PDF <> "" Then
                    Dim list As New List(Of String)
                    list.Add(PDF)
                    Dim Body = "Anbei befinden sich die Auflistung der geprüften UID-Nummern.<br>Bei UID-Nummer mit dem Prüfungsergebnis 'OK' wurde das Prüfdatum in den Kundenstamm eingetragen. "

                    Body &= createUIDPruefungUebersicht(dt)

                    Body &= "<br><b>Ungültige UID-Nummern werden automatisch im Aviso" & IIf(updateFIBU, " und in der Buchhaltung (mit der Kennzeichnung UID)", "") & " vermerkt!</b>"
                    Body &= "<br><br>Erstellt am: " & Now.ToShortDateString & ", um " & Now.ToShortTimeString
                    Body &= "<br><br>Automatisch generiertes E-Mail."

                    VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = firmatmp
                    VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(Mail_To, Mail_betreff, Body, getAbsenderEmail(),, False, Mail_CC, Mail_BCC, list)
                    VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = Mail_FIMRA

                    'VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail("d.breimaier@verag.ag", "UID-Prüfung", Body,,, False, , , list)
                    '  VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail("al@verag.ag", "UID Prüfung", Body,,, False, ,, list)
                End If


                If setKundenvermerk Then

                    For Each r As DataRow In dt.Rows
                        If Not IsDBNull(r("Ergebnis")) AndAlso r("Ergebnis") = "UNGÜLTIG" AndAlso r("typ") <> "VAK" Then
                            Dim kunde As cKunde = New cKunde(r("kdNr"))
                            Dim KdFirma = VERAG_PROG_ALLGEMEIN.cAllgemein.getFirmaFromFiliale(kunde.FilialenNr)
                            If KdFirma = VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA Then
                                Dim kundeErw As cKundenErweitert = New cKundenErweitert(kunde.KundenNr)
                                Dim textUIDVermerk As String = "UID Nr." & r("UstIdKz") & r("UstIdnr") & " ungültig, zuletzt geprüft wo gültig am " & r("letzte Prüfung") & " lt. monatl. Prüfung!"

                                If kundeErw.kde_BesonderheitenNeu Then

                                    Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
                                    If SQL.doSQL("INSERT INTO tblKundenBesonderheiten (kdb_KundenNr,kdb_kategorie,kdb_text,kdb_mitId,kdb_mitName,kdb_EingetragenAm,kdb_visible,kdb_hervorheben,kdb_history) " &
                                    " VALUES(" & kunde.KundenNr & ",'ALLG' ,'" & textUIDVermerk & "'," & "4" & ",'" & "AUTO" & "','" & Now() & "',1,1,0)", "FMZOLL") Then
                                        setUIDToNull(kunde)
                                    End If

                                Else

                                    If kunde.Besonderheiten <> "" Then kunde.Besonderheiten &= vbNewLine
                                    kunde.Besonderheiten &= textUIDVermerk

                                    kunde.SAVE()
                                    setUIDToNull(kunde)

                                End If

                                If updateFIBU Then
                                    Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
                                    Dim firma_id As String = ""
                                    Dim vermerkNew As String = "UID Nr. " & r("UstIdKz") & r("UstIdnr") & " ungültig (" & Now().ToShortDateString & ")"
                                    Select Case VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA
                                        Case "VERAG" : firma_id = "'1', '11', '7'"
                                            'Case "ATILLA" : firma_id = "'7'" 'ATILLA UND VERAG haben selben Kundenstamm!!!
                                    End Select
                                    If firma_id <> "" Then SQL.doSQL("UPDATE [FIBU2].dbo.fibu_konto SET [c_homepage]='" & vermerkNew & "',[c_text2] = isnull([c_ustidnr],''), [c_ustidnr] = '', c_manipulator = 'AUTO', dt_manipulation = Getdate() where i_konto='" & kunde.KundenNr & "' AND i_firm_refid in (" & firma_id & ")", "FIBU")
                                End If

                                Select Case VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA
                                    Case "IMEX" : kunde.FiBuSchnittstelle = True : kunde.SAVE() 'IMEX-Kunden sollen neu in DVO exportiert werden!
                                End Select

                                changeSteuerschlüssel(kunde)
                            End If

                        End If

                    Next


                End If


            End If
            VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = firmatmp
            Return True
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = firmatmp
            MsgBox(ex.Message & ex.StackTrace)
            Return False
        End Try

    End Function

    Function createUIDPruefungUebersicht(dt As DataTable) As String


        Dim gruppiert = From row In dt.AsEnumerable()
                        Group row By kat = row.Field(Of String)("Ergebnis") Into grp = Group
                        Select New With {
                    .Ergebnis = kat,
                    .Anzahl = grp.Count()
                }

        ' Ergebnis in neue DataTable umwandeln
        Dim result As New DataTable()
        result.Columns.Add("Ergebnis", GetType(String))
        result.Columns.Add("Anzahl", GetType(Integer))

        For Each item In gruppiert
            result.Rows.Add(item.Ergebnis, item.Anzahl)
        Next



        Dim TextHTMLtable = ""

        TextHTMLtable &= "<br><br><table border=1>"
        TextHTMLtable &= "<tr><td>Anzahl</td><td>Ergebnis</td></tr>"

        For Each row As DataRow In result.Rows

            TextHTMLtable &= "<tr>"
            TextHTMLtable &= "<td><b>" & row.Item("Anzahl") & "</b></td>"
            TextHTMLtable &= "<td><b>" & row.Item("Ergebnis") & "</b></td>"
            TextHTMLtable &= "</tr>"

        Next

        Return TextHTMLtable & "</table><br><br>"


    End Function

    Sub setUIDToNull(kunde)

        Dim addressen As cAdressen = New cAdressen(kunde.KundenNr)
        addressen.UstIdKz = DBNull.Value
        addressen.UstIdNr = DBNull.Value
        addressen.UstIdGeprüft = DBNull.Value
        addressen.SAVE()

    End Sub

    Sub changeSteuerschlüssel(kunde As cKunde)

        If kunde.Steuerschlüssel IsNot Nothing Then

            Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
            Dim steuersatz = SQL.DLookup("[Steuersatz %]", "[Steuertabelle]", "[Steuerschlüssel]='" & kunde.Steuerschlüssel & "'", "FMZOLL", -1)


            Dim Filiale As New VERAG_PROG_ALLGEMEIN.cFilialen(kunde.FilialenNr)
            If steuersatz = 0 Then
                Select Case Filiale.LandKz
                    Case "A", "AT"
                        kunde.Steuerschlüssel = 2
                    Case "D", "DE"
                        kunde.Steuerschlüssel = 19
                    Case "GB"
                        kunde.Steuerschlüssel = 20
                End Select
                kunde.SAVE()
            Else
                Exit Sub 'Steuersatz ist hinterlegt, keiner Änderung!
            End If

        End If

    End Sub
    'Function getUID_PruefungVERAG(maxAnz As Integer) As Boolean
    '    Dim firmatmp = VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA
    '    Try
    '        VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "VERAG"
    '        Dim dt = VERAG_PROG_ALLGEMEIN.cUIDPruefung.doUIDPruefungALL(CDate(Now.ToString("01.MM.yyyy")).AddMonths(-1), True, False, maxAnz, False)
    '        If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then
    '            Dim PDF = VERAG_PROG_ALLGEMEIN.cProgramFunctions.genExcelFromDT_NEW(dt,,,,, False)
    '            If PDF <> "" Then
    '                Dim list As New List(Of String)
    '                list.Add(PDF)
    '                Dim Body = "Anbei befinden sich die Auflistung der geprüfen UID-Nummern.<br>Bei UID-Nummer mit dem Prüfungserbnis 'OK' wurde das Prüfdatum in den Kundenstamm eingetragen. "
    '                Body &= "<br><b>Ungültige UID-Nummern bitte manuell bearbeiten!</b>"
    '                Body &= "<br><br>Erstellt am: " & Now.ToShortDateString & ", um " & Now.ToShortTimeString
    '                Body &= "<br><br>Automatisch generiertes E-Mail."

    '                VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail("kb@verag.ag", "UID Prüfung VERAG", Body,,, False, "al@verag.ag",, list)
    '                '  VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail("al@verag.ag", "UID Prüfung", Body,,, False, ,, list)
    '            End If
    '        End If
    '        VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = firmatmp
    '        Return True
    '    Catch ex As Exception
    '        VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = firmatmp
    '        MsgBox(ex.Message & ex.StackTrace)
    '        Return False
    '    End Try
    'End Function
    'Function getUID_PruefungIMEX(maxAnz As Integer) As Boolean
    '    Dim firmatmp = VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA
    '    Try
    '        VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "IMEX"

    '        Dim dt = VERAG_PROG_ALLGEMEIN.cUIDPruefung.doUIDPruefungALL(CDate(Now.ToString("01.MM.yyyy")).AddMonths(-1), True, False, maxAnz, False)
    '        If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then
    '            Dim PDF = VERAG_PROG_ALLGEMEIN.cProgramFunctions.genExcelFromDT_NEW(dt,,,,, False)
    '            If PDF <> "" Then
    '                Dim list As New List(Of String)
    '                list.Add(PDF)
    '                Dim Body = "Anbei befinden sich die Auflistung der geprüfen UID-Nummern.<br>Bei UID-Nummer mit dem Prüfungserbnis 'OK' wurde das Prüfdatum in den Kundenstamm eingetragen. "
    '                Body &= "<br><b>Ungültige UID-Nummern bitte manuell bearbeiten!</b>"
    '                Body &= "<br><br>Erstellt am: " & Now.ToShortDateString & ", um " & Now.ToShortTimeString
    '                Body &= "<br><br>Automatisch generiertes E-Mail."

    '                VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail("Viktoria.Leirich@imex-group.at;kb@verag.ag", "UID Prüfung IMEX", Body,,, False, "al@verag.ag",, list)
    '                '  VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail("al@verag.ag", "UID Prüfung", Body,,, False, ,, list)
    '            End If
    '        End If
    '        VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = firmatmp
    '        Return True
    '    Catch ex As Exception
    '        VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = firmatmp
    '        MsgBox(ex.Message & ex.StackTrace)
    '        Return False
    '    End Try
    'End Function
    'Function getUID_PruefungAMBAR(maxAnz As Integer) As Boolean
    '    Dim firmatmp = VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA
    '    Try
    '        VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "AMBAR"

    '        Dim dt = VERAG_PROG_ALLGEMEIN.cUIDPruefung.doUIDPruefungALL(CDate(Now.ToString("01.MM.yyyy")).AddMonths(-1), True, False, maxAnz, False)
    '        If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then
    '            Dim PDF = VERAG_PROG_ALLGEMEIN.cProgramFunctions.genExcelFromDT_NEW(dt,,,,, False)
    '            If PDF <> "" Then
    '                Dim list As New List(Of String)
    '                list.Add(PDF)
    '                Dim Body = "Anbei befinden sich die Auflistung der geprüfen UID-Nummern.<br>Bei UID-Nummer mit dem Prüfungserbnis 'OK' wurde das Prüfdatum in den Kundenstamm eingetragen. "
    '                Body &= "<br><b>Ungültige UID-Nummern bitte manuell bearbeiten!</b>"
    '                Body &= "<br><br>Erstellt am: " & Now.ToShortDateString & ", um " & Now.ToShortTimeString
    '                Body &= "<br><br>Automatisch generiertes E-Mail."

    '                VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail("kb@verag.ag", "UID Prüfung AMBAR", Body,,, False, "al@verag.ag",, list)
    '                '  VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail("al@verag.ag", "UID Prüfung", Body,,, False, ,, list)
    '            End If
    '        End If
    '        VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = firmatmp
    '        Return True
    '    Catch ex As Exception
    '        VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = firmatmp
    '        MsgBox(ex.Message & ex.StackTrace)
    '        Return False
    '    End Try
    'End Function

    Function getEZB_Waehrungskurse90D() As Boolean
        Dim MyData As String = ""
        getEZB_Waehrungskurse90D = False
        Try
            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12

            Using WC As New System.Net.WebClient()
                ' C0008_URL()
                WC.Encoding = ASCIIEncoding.UTF8
                Dim URL = "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist-90d.xml" 'cDY_Paramter.GET_PARAM_ByName("C0008_URL", TESTSYSTEM)
                If URL = String.Empty Then Return False

                MyData = WC.DownloadString(URL)
                Dim doc As New XmlDocument()
                doc.LoadXml(MyData)
                If doc.HasChildNodes Then

                    If doc.GetElementsByTagName("gesmes:Envelope").Count > 0 Then
                        If doc.GetElementsByTagName("gesmes:Envelope")(0).HasChildNodes AndAlso doc.GetElementsByTagName("gesmes:Envelope")(0).ChildNodes.Count > 2 Then
                            If doc.GetElementsByTagName("gesmes:Envelope")(0).ChildNodes(2).HasChildNodes Then

                                For Each Entry2 As XmlNode In doc.GetElementsByTagName("gesmes:Envelope")(0).ChildNodes(2).ChildNodes

                                    Dim datum As Date = DateTime.ParseExact(Entry2.Attributes(0).Value, "yyyy-MM-dd", Nothing)

                                    If True Then

                                        If Entry2.Name = "Cube" Then
                                            Dim Cube = Entry2

                                            If Cube.HasChildNodes AndAlso Cube.ChildNodes(0).Name = "Cube" And Cube.ChildNodes(0).Attributes.Count > 0 Then

                                                For Each Entry As XmlNode In Cube.ChildNodes

                                                    Dim EZB As New VERAG_PROG_ALLGEMEIN.cEZB_Waehrungskurse

                                                    '                  Dim Code = ""
                                                    'Dim Description = ""
                                                    ' Dim StartDate = Nothing
                                                    ' Dim EndDate = Nothing
                                                    '      MsgBox("as!!!!!o")


                                                    If Entry.Attributes("currency") IsNot Nothing Then EZB.ezb_waehrungscode = Entry.Attributes("currency").Value
                                                    If Entry.Attributes("rate") IsNot Nothing Then EZB.ezb_kurs = CDbl(Entry.Attributes("rate").Value.Replace(".", ","))
                                                    'If Entry.SelectNodes("Description").Count > 0 Then EZB.ezb_waehrungsschluessel = Entry.SelectNodes("Description")(0).InnerText
                                                    EZB.ezb_datum = datum 'CDate(Entry.SelectNodes("StartDate")(0).InnerText)
                                                    EZB.SAVE()
                                                    '  LC.Add(New VERAG_PROG_ALLGEMEIN.cEZB_Waehrungskurse(Code, Description, StartDate, EndDate))
                                                    '   VERAG_PROG_ALLGEMEIN.
                                                    getEZB_Waehrungskurse90D = True


                                                    'MsgBox(datum.ToShortDateString & " - " & Now.ToShortDateString)

                                                    'If datum.ToShortDateString = Now.ToShortDateString Then 'aktuellen TAG sichern.
                                                    '    Try

                                                    '        Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
                                                    '        SQL.doSQL("INSERT INTO [baskur] 
                                                    '                   ([baskur_code],[baskur_typ],[baskur_bez],[baskur_faktor],[baskur_kurs],[baskur_gvdat],[baskur_gbdat],[baskur_edat],[baskur_adat],[baskur_sb],[baskur_cdealt],[baskur_wkz]) 
                                                    '                   VALUES ('" & EZB.ezb_waehrungscode & "',1,'-',1," & Entry.Attributes("rate").Value & ",cast(getdate() as date),cast(getdate() as date),getdate(),getdate(),'VRG',000,'EUR')", "ATLAS")

                                                    '    Catch ex As Exception
                                                    '        VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)

                                                    '    End Try
                                                    'End If


                                                Next



                                            End If
                                        End If
                                    End If
                                Next
                            End If




                        End If
                    End If
                End If
                'If LC.Count > 0 Then
                '    Return LC.INSERT_DB(TESTSYSTEM)
                'End If
            End Using

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

    End Function

    Function getNachrichtenDatenFromBundesanzeiger() As String
        Dim cnt = 0
        Try
            Dim DY_server = "ftp://www.awr-portal.de/" '"217.17.30.74"
            Dim DY_name = "SAPverag"
            Dim DY_pwd = "SAPi64c"
            Dim DY_port = "21"
            Dim DY_PFAD_out = "/ASCII(bis4.6B)/Importcodenummern/Deutschland/Initialload.zip"
            Dim VERARBEITUNGS_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\ECHTSYSTEM\EZT\Importcodenummern\" & Now.Year & "\"
            If Not System.IO.Directory.Exists(VERARBEITUNGS_PFAD) Then System.IO.Directory.CreateDirectory(VERARBEITUNGS_PFAD)

            '  DAKOSY_Worker.cDakosyFunftions.getSFTPLoginData(DY_server, DY_name, DY_pwd, DY_port, "", DY_PFAD_out)


            Dim ConnectionInfo As New ConnectionInfo(DY_server, DY_port, DY_name, New PasswordAuthenticationMethod(DY_name, DY_pwd))
            'Dim ConnectionInfo2 As New ConnectionInfo(DY_server, DY_port, DY_name, New PasswordAuthenticationMethod(DY_name, DY_pwd))

            Dim ftp As System.Net.FtpWebRequest = CType(System.Net.FtpWebRequest.Create(DY_server & DY_PFAD_out), System.Net.FtpWebRequest)


            ftp.Credentials = New System.Net.NetworkCredential(DY_name, DY_pwd)

            'Turn off KeepAlive (will close connection on completion)

            ftp.KeepAlive = False

            'we want a binary

            ftp.UseBinary = True

            'Define the action required (in this case, download a file)

            ftp.Method = System.Net.WebRequestMethods.Ftp.DownloadFile



            'If we were using a method that uploads data e.g. UploadFile

            'we would open the ftp.GetRequestStream here an send the data



            'Get the response to the Ftp request and the associated stream

            Dim dwlFileName = VERARBEITUNGS_PFAD & Now.ToString("yyyyMMdd_HHmmss_") & "Initialload.zip"
            Using response As System.Net.FtpWebResponse = CType(ftp.GetResponse, System.Net.FtpWebResponse)

                Using responseStream As System.IO.Stream = response.GetResponseStream

                    'loop to read & write to file
                    Using fs As New System.IO.FileStream(dwlFileName, System.IO.FileMode.Create)

                        Dim buffer(2047) As Byte

                        Dim read As Integer = 0

                        Do

                            read = responseStream.Read(buffer, 0, buffer.Length)

                            fs.Write(buffer, 0, read)

                        Loop Until read = 0 'see Note(1)

                        responseStream.Close()

                        fs.Flush()

                        fs.Close()

                    End Using

                    responseStream.Close()

                End Using

                response.Close()

            End Using

            Return dwlFileName


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

        Return ""
    End Function


    Function loadEZTZipToDB(pfadZIP As String) As Boolean
        Try
            loadEZTZipToDB = False
            Dim VERARBEITUNGS_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\ECHTSYSTEM\EZT\Importcodenummern\" & Now.Year & "\Extrakt\"
            If System.IO.Directory.Exists(VERARBEITUNGS_PFAD) Then System.IO.Directory.Delete(VERARBEITUNGS_PFAD, True) 'Zuerst löschen, damit leer ist
            System.IO.Directory.CreateDirectory(VERARBEITUNGS_PFAD)


            System.IO.Compression.ZipFile.ExtractToDirectory(pfadZIP, VERARBEITUNGS_PFAD)
            If System.IO.Directory.GetFiles(VERARBEITUNGS_PFAD).Count > 0 Then
                loadEZTZipToDB = (insertEZTIntoDB(System.IO.Directory.GetFiles(VERARBEITUNGS_PFAD)(0), True) And
                   insertEZTIntoDB(System.IO.Directory.GetFiles(VERARBEITUNGS_PFAD)(0), False))
            End If
            'System.IO.Directory.Delete(VERARBEITUNGS_PFAD,True)

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

    Function insertEZTIntoDB(pfad As String, TESTSYSTEM As Boolean) As Boolean
        Dim ts = VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = TESTSYSTEM
        Try
            If Not System.IO.File.Exists(pfad) Then Return False

            Dim reader As StreamReader = My.Computer.FileSystem.OpenTextFileReader(pfad, System.Text.Encoding.Default)
            Dim a As String

            'If Not VERAG_PROG_ALLGEMEIN.cEZT_ImportCodenummern.delWholeDB() Then Return False ' nicht mehr, da upgedatet wird
            Dim cnt = 0
            Do
                a = reader.ReadLine
                '
                ' Code here
                '
                If a IsNot Nothing AndAlso a.Length > 40 Then

                    Dim EZT As New VERAG_PROG_ALLGEMEIN.cEZT_ImportCodenummern
                    Dim pos As String = 0
                    EZT.ezt_Land = a.Substring(pos, 3) : pos += 3
                    EZT.ezt_Codenummer = a.Substring(pos, 11) : pos += 11
                    EZT.ezt_BesMasseinheit = a.Substring(pos, 3) : pos += 3
                    EZT.ezt_BesMasseinheit2 = a.Substring(pos, 3) : pos += 3
                    EZT.ezt_Start = Date.ParseExact(a.Substring(pos, 8), "yyyyMMdd", System.Globalization.DateTimeFormatInfo.CurrentInfo) : pos += 8
                    EZT.ezt_Ende = Date.ParseExact(a.Substring(pos, 8), "yyyyMMdd", System.Globalization.DateTimeFormatInfo.CurrentInfo) : pos += 8
                    EZT.ezt_Sprache = a.Substring(pos, 3) : pos += 3
                    EZT.ezt_Text = a.Substring(pos)
                    EZT.SAVE()
                    cnt += 1
                    ' Sub New(ezt_Land, ezt_Codenummer, ezt_BesMasseinheit, ezt_BesMasseinheit2, ezt_Start, ezt_Ende, ezt_Sprache, ezt_Text)
                    If cnt Mod 10 = 0 Then Application.DoEvents()
                End If
            Loop Until a Is Nothing
            reader.Close()
            VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = ts
            Return True
        Catch ex As Exception
            MsgBox(ex.Message & ex.StackTrace)
            VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = ts
            Return False
        End Try
    End Function

    Private Sub LinkLabel18_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel18.LinkClicked
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
        Dim bool = getEZB_Waehrungskurse()
        showPic(bool, PictureBox10)
    End Sub

    Private Sub LinkLabel19_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel19.LinkClicked
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
        Dim bool = getEZB_Waehrungskurse90D()
        showPic(bool, PictureBox11)
    End Sub

    Private Sub LinkLabel20_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel20.LinkClicked
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
        Dim Empfaenger = cMitarbeiter.GetEMailRecipientForEmailNotification("UID-Prüfung", 1)
        Dim bool = getUID_Pruefung(MyTextBox1.Text, "VERAG", "UID Prüfung VERAG", Empfaenger,,, MyTextBox2._value, cbxVermerk.Checked, cbxUseUIDFinanzOnline.Checked, , cbxUpdateFIBU.Checked)
        showPic(bool, PictureBox12)
    End Sub

    Private Sub Button9_Click(sender As Object, e As EventArgs) Handles Button9.Click
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
        VERAG_PROG_ALLGEMEIN.cDVO_Interface.genStammdatenANSI(False, cbxKd.Checked, cbxBu.Checked)
    End Sub

    Private Sub LinkLabel22_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel22.LinkClicked
        Me.Visible = False
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = True
        Dim f As New frmTCNachrichtenVerarbeitung
        f.ShowDialog()
        Me.Visible = True
    End Sub

    Private Sub LinkLabel21_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel21.LinkClicked
        Me.Visible = False
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
        Dim f As New frmTCNachrichtenVerarbeitung
        f.ShowDialog()
        Me.Visible = True
    End Sub

    Private Sub LinkLabel24_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel24.LinkClicked
        Me.Visible = False
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = True
        Dim f As New frmMDMNachrichtenVerarbeitung
        f.newFormatTR = cbxPlose_TRNewFormat.Checked
        f.newFormatINV = cbxPlose_INVNewFormat.Checked
        f.ShowDialog()
        Me.Visible = True
    End Sub

    Private Sub LinkLabel23_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel23.LinkClicked
        Me.Visible = False
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
        Dim f As New frmMDMNachrichtenVerarbeitung
        f.newFormatTR = cbxPlose_TRNewFormat.Checked
        f.newFormatINV = cbxPlose_INVNewFormat.Checked
        f.ShowDialog()
        Me.Visible = True
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs)
        For Each d In System.IO.Directory.GetDirectories(VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\ECHTSYSTEM\Nachrichtendaten_Ablage\2019")
            Dim fid As New FileInfo(d)
            If fid.Name >= 20190820 Then


                For Each f In System.IO.Directory.GetFiles(d)
                    Dim fi As New FileInfo(f)
                    If fi.Extension = ".xml" Then

                        Dim XML_Code = System.IO.File.ReadAllText(f, System.Text.UTF8Encoding.Default)

                        If XML_Code.Contains("<FCFCDC>") And XML_Code.Contains("<TaxOffice>9153</TaxOffice>") Then
                            If Not System.IO.File.Exists(VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\ECHTSYSTEM\TEST\FISKAL\" & fi.Name) Then
                                System.IO.File.Copy(f, VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\ECHTSYSTEM\TEST\FISKAL\" & fi.Name)
                            End If
                        End If


                        'Dim xmlWriterSettings As XmlWriterSettings = New XmlWriterSettings With {.Encoding = System.Text.Encoding.UTF8, .CheckCharacters = True}

                        'Dim doc As New XmlDocument()


                        'Dim XML_Code = System.IO.File.ReadAllText(f, System.Text.UTF8Encoding.Default)

                        'doc.LoadXml(frmDYNachrichtenVerarbeitung.SanitizeXmlString(XML_Code))

                        'If cGetMsgType.isEZA_FreierVerkehrAktVeredelUmwandlungXML(doc) Then
                        '    MsgBox(f)
                        'End If

                    End If
                Next
            End If

        Next

    End Sub

    Private Sub LinkLabel26_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel26.LinkClicked
        Me.Cursor = Cursors.WaitCursor
        Try
            DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("I0700", True) 'TESTSYSTEM
            Dim erg = DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("I0700", False) 'ECHTSYSTEM
            showPic(erg, PictureBox13)
        Catch ex As Exception : VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name) : End Try
        Me.Cursor = Cursors.Default
    End Sub

    Private Sub TabPage2_Click(sender As Object, e As EventArgs)

    End Sub
    Private Sub form1_KeyUp(ByVal sender As Object, ByVal e As EventArgs) Handles Button11.Click



        Dim rowSplitter As Char() = {vbCr, vbLf}
        Dim columnSplitter As Char() = {vbTab}
        Dim dataInClipboard As IDataObject = Clipboard.GetDataObject()
        Dim stringInClipboard As String = CStr(dataInClipboard.GetData(DataFormats.Text))
        Dim rowsInClipboard As String() = stringInClipboard.Split(rowSplitter, StringSplitOptions.RemoveEmptyEntries)
        Dim r As Integer = 0 'dgvMRN.SelectedRows(0).Index
        Dim c As Integer = 0 'dgvMRN.SelectedRows(0).Cells(0).ColumnIndex

        MsgBox(rowsInClipboard.Length)
        If dgvMRN.Rows.Count < (r + rowsInClipboard.Length) Then
            dgvMRN.Rows.Add(r + rowsInClipboard.Length - dgvMRN.Rows.Count)
        End If

        For iRow As Integer = 0 To rowsInClipboard.Length - 1
            Dim valuesInRow As String() = rowsInClipboard(iRow).Split(columnSplitter)

            For iCol As Integer = 0 To valuesInRow.Length - 1

                If dgvMRN.ColumnCount - 1 >= c + iCol Then
                    dgvMRN.Rows(r + iRow).Cells(c + iCol).Value = valuesInRow(iCol)
                End If
            Next
        Next
    End Sub
    Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
        Dim ftmp As Object = If(IsNumeric(txtVRGOut_FilialenNr.Text.Trim), txtVRGOut_FilialenNr.Text, Nothing)
        Dim atmp As Object = If(IsNumeric(txtVRGOut_AbfertigungsNr.Text.Trim), txtVRGOut_AbfertigungsNr.Text, Nothing)


        'DGV------------------------------------
        If dgvMRN.Rows.Count - 1 > 0 Then
            For Each r As DataGridViewRow In dgvMRN.Rows
                If r.Cells(0) IsNot Nothing Then
                    Dim BezugsNrDgv = ""
                    Dim okDGV = False
                    Dim mrn = r.Cells(0).Value
                    If If(mrn, "") <> String.Empty Then
                        Select Case MyComboBox1._value
                            Case "DY"
                                BezugsNrDgv = cVERAG_out_ncts.getBezugnNr_ByMRN(mrn)
                                okDGV = cVERAG_out_ncts.copyFileFTP_VERAGncts_DY_ByBezugsNr(BezugsNrDgv, getISett, ftmp, atmp)
                            Case "TC"
                                BezugsNrDgv = TELOTEC_Worker.cTelotec_Anmeldung.getBezugnNr_ByMRN(mrn)
                                okDGV = cVERAG_out_ncts.copyFileFTP_VERAGncts_TC_ByBezugsNr(BezugsNrDgv, getISett, ftmp, atmp)
                            Case "DHF"
                                BezugsNrDgv = cVERAG_out_ncts.getLRN_ByCRN(mrn)
                                okDGV = cVERAG_out_ncts.copyFileFTP_VERAGncts_EZOLL_ByBezugsNr(BezugsNrDgv, getISett, ftmp, atmp)
                        End Select
                    End If
                    If okDGV Then
                        r.DefaultCellStyle.BackColor = System.Drawing.Color.LightGreen
                    Else
                        r.DefaultCellStyle.BackColor = System.Drawing.Color.IndianRed
                    End If
                End If
                Me.Refresh()
            Next
            Exit Sub
        End If
        '------------------------------------

        Dim BezugsNr = txtVRGOut_BezugsNr.Text
        If txtVRGOut_BezugsNr.Text.Trim = "" And txtVRGOut_MRN.Text <> "" Then

            Select Case MyComboBox1._value
                Case "DY" : BezugsNr = cVERAG_out_ncts.getBezugnNr_ByMRN(txtVRGOut_MRN.Text)
                Case "TC" : BezugsNr = TELOTEC_Worker.cTelotec_Anmeldung.getBezugnNr_ByMRN(txtVRGOut_MRN.Text)
                Case "DHF" : BezugsNr = cVERAG_out_ncts.getLRN_ByCRN(txtVRGOut_MRN.Text)
            End Select

        End If
        If BezugsNr = "" Then
            MsgBox("Bezugsnummer leer!")
            Exit Sub
        End If

        Dim ok As Boolean = False
        Select Case MyComboBox1._value
            Case "DY" : ok = cVERAG_out_ncts.copyFileFTP_VERAGncts_DY_ByBezugsNr(BezugsNr, getISett, ftmp, atmp)
            Case "TC" : ok = cVERAG_out_ncts.copyFileFTP_VERAGncts_TC_ByBezugsNr(BezugsNr, getISett, ftmp, atmp)
            Case "DHF" : ok = cVERAG_out_ncts.copyFileFTP_VERAGncts_EZOLL_ByBezugsNr(BezugsNr, getISett, ftmp, atmp)
        End Select

        showPic(ok, PictureBox14)

    End Sub


    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim ok As Boolean = False
        Select Case MyComboBox2._value
            Case "DY" : ok = cVERAG_out_eza.copyFileFTP_VERAGEZA_DY_ByBezugsNr(txtVRGOutEZA_BezugsNr.Text, getISettEZA)
                'Case "TC" : ok = cVERAG_out_ncts.copyFileFTP_VERAGncts_TC_ByBezugsNr(txtVRGOut_BezugsNr.Text, getISett)
                'Case "DHF" : ok = cVERAG_out_ncts.copyFileFTP_VERAGncts_EZOLL_ByBezugsNr(txtVRGOut_BezugsNr.Text, getISett)
        End Select

        showPic(ok, PictureBox15)


    End Sub
    Function getISett() As cVERAG_Interface_Settings
        getISett = New cVERAG_Interface_Settings
        getISett.acticeInterface_OREGON = cbxISett_OREGON.Checked
        getISett.acticeInterface_TOBB = cbxISett_TOBB.Checked
        getISett.acticeInterface_EKOL = cbxISett_EKOL.Checked
        getISett.acticeInterface_TEST = cbxISett_TEST.Checked
        getISett.acticeInterface_VERAG = cbxISett_VERAG.Checked
        getISett.acticeInterface_IMEX = cbxISett_IMEX.Checked
    End Function

    Function getISettEZA() As cVERAG_Interface_Settings
        getISettEZA = New cVERAG_Interface_Settings
        getISettEZA.acticeInterface_VERAG = cbxISettEZA_VERAG.Checked
    End Function




    Private Sub LinkLabel28_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel28.LinkClicked
        Me.Visible = False
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
        VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "UNISPED"
        Dim f As New frmDYNachrichtenVerarbeitung
        f.ShowDialog()
        Me.Visible = True
    End Sub

    Private Sub LinkLabel30_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel30.LinkClicked
        Me.Visible = False
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = True
        Dim f As New frmTRNCTS_NachrichtenVerarbeitung
        f.ShowDialog()
        Me.Visible = True
    End Sub

    Private Sub LinkLabel31_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel31.LinkClicked
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
        ASFINAG_LKW()
    End Sub

    Function ASFINAG_LKW(Optional isFMZoll As Boolean = True) As Boolean
        Try
            Dim SQl As New VERAG_PROG_ALLGEMEIN.SQL

            ' CLF-Einträge aus den bestehenden SDL-Datensätzen entfernen,
            ' damit nach dem Aktualisierungslauf der Istzustand der CLF in der SDL hergestellt wird.
            If Not SQl.doSQL("UPDATE SDL Set  OBUID = NULL, Vertragsabschlussdatum = NULL, Kategorie = NULL, Status = NULL WHERE (SDLNr = 200) AND (NOT Vertragsabschlussdatum IS NULL)", "SDL") Then
                VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR("ERROR", "Fehler beim Reset SDL-Daten.", System.Reflection.MethodBase.GetCurrentMethod.Name)
                Return False
            End If

            ' Nummer der Speditionsdienstleistung für MautAT einlesen.
            Dim SDLNr = SQl.getValueTxtBySql("SELECT isnull(SDLNr,'') FROM vwSpeditionsdienstleistungen WHERE (Sicht = 'vwMautAT')", "SDL")
            If SDLNr = "" Then
                VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR("ERROR", "SDL-Nr nicht gefunden.", System.Reflection.MethodBase.GetCurrentMethod.Name)
                Return False
            End If


            If isFMZoll Then

                ' Verbindung zur ASFINAG Datenbank herstellen
                Dim connectionString = ""
                If VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM Then
                    connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\DEVELOPER\f\FMZoll\Mautmanager.adp"
                Else
                    connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\FMZOLL\f\FMZoll\Mautmanager.adp"
                End If
                Dim con As New OleDbConnection(connectionString)
                Dim cmd As New OleDbCommand
                Dim var1 As String
                Dim adapter As OleDbDataAdapter = New OleDbDataAdapter()
                Dim reader As OleDbDataReader = Nothing

                ' Kfz Kennzeichen einlesen.
                Dim SQLQuery = "SELECT CardNumber, ValidTo, OBUID, KfzKennzeichen, Nationalität, DatumVertragsabschluss, Kategorie, Schadstoffklasse, Status FROM vwCLFBody " ' vwCLFBody verwendet immer zuletzt importierte CLF!
                Using Command As New OleDbCommand(SQLQuery, con)
                    Using oRDR As OleDbDataReader = Command.ExecuteReader
                        While (oRDR.Read)
                            Dim KartenNr = oRDR.GetValue("CardNumber")

                            Dim KfzKennzeichen = fktConvert(oRDR.GetValue("KfzKennzeichen"))

                            ' Kundennummer einlesen
                            Dim KdNr As Integer = SQl.getValueTxtBySql("SELECT AdressenNr FROM Kreditkarten WHERE KartenNr='" & KartenNr & "'", "SDL",,, -1)

                            If KdNr > 0 Then

                                Call fktKundenSDLVerwalten(KdNr, SDLNr)
                                Call fktKundenLkwVerwalten(KdNr, oRDR.GetValue("KfzKennzeichen"), oRDR.GetValue("Nationalität"))

                                Dim SDL = New VERAG_PROG_ALLGEMEIN.cSDL(KdNr, oRDR.GetValue("KfzKennzeichen"), SDLNr)
                                If Not SDL.hasentry Then
                                    SDL.KundenNr = KdNr
                                    SDL.KfzKennzeichen = KfzKennzeichen
                                    SDL.SDLNr = SDLNr
                                    SDL.History = 0 'fktLiefereHistorywert(!KundenNr, !SDLNr)
                                    SDL.Erfassungsdatum = Now
                                Else
                                    SDL.Änderungsdatum = Now
                                End If
                                SDL.Sachbearbeiter = "ASFINAG"

                                Dim Validto = SQL.checkNullStr(oRDR.GetValue("DatumVertragsabschluss"))

                                SDL.KartenNr = SQL.checkNullStr(oRDR.GetValue("CardNumber"))
                                If Validto <> "" Then
                                    SDL.GültigBis = DateAdd("d", -1, DateAdd("m", 1, DateSerial("20" & Mid(oRDR.GetValue("CardNumber"), 1, 2), Mid(Validto, 3, 2), 1)))
                                End If
                                SDL.OBUID = SQL.checkNullStr(oRDR.GetValue("OBUID"))
                                SDL.Vertragsabschlussdatum = SQL.checkNullStr(oRDR.GetValue("DatumVertragsabschluss"))
                                SDL.Kategorie = SQL.checkNullStr(oRDR.GetValue("Kategorie"))
                                SDL.Schadstoffklasse = SQL.checkNullStr(oRDR.GetValue("Schadstoffklasse"))
                                SDL.Status = SQL.checkNullStr(oRDR.GetValue("Status"))
                                SDL.SAVE()
                            End If

                        End While
                    End Using
                End Using
                con.Close()
            Else

                ' Kfz Kennzeichen einlesen.

                Dim strSQLASFINAG = "SELECT cardNumber, ValidTo, OBUID, vehicleLicensePlate, nationality, contractDate, vehicleCategory, emissionCategory, status, CO2EmissionsClass FROM vwCLFBody"

                Dim dtAsfinag As DataTable = SQl.loadDgvBySql_Param(strSQLASFINAG, "ASFINAG")

                ' ????????
                'If dtAsfinag.Rows.Count < 1 Then
                '    Return False
                'End If

                For Each row As DataRow In dtAsfinag.Rows

                    Dim KdNr As Integer = SQl.getValueTxtBySql("SELECT Kreditkarten.AdressenNr FROM Kreditkarten WHERE Kreditkarten.KartenNr='" & row.Item("cardNumber") & "'", "FMZOLL",,, -1)


                    If KdNr > 0 Then

                        Call fktKundenSDLVerwalten(KdNr, SDLNr)
                        Call fktKundenLkwVerwalten(KdNr, row.Item("vehicleLicensePlate"), row.Item("nationality"))

                        ' Die MautAT Tabelle aktualisieren.

                        Dim SDL = New VERAG_PROG_ALLGEMEIN.cSDL(KdNr, row.Item("vehicleLicensePlate"), SDLNr)

                        If Not SDL.hasentry Then
                            SDL.KundenNr = KdNr
                            SDL.KfzKennzeichen = row.Item("vehicleLicensePlate")
                            SDL.SDLNr = SDLNr
                            SDL.History = 0 'fktLiefereHistorywert(!KundenNr, !SDLNr)
                            SDL.Erfassungsdatum = Now
                        Else
                            SDL.Änderungsdatum = Now
                        End If
                        SDL.Sachbearbeiter = "ASFINAG" & IIf(VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM, "_TEST", "")

                        Dim Validto = SQL.checkNullStr(row.Item("contractDate"))

                        SDL.KartenNr = SQL.checkNullStr(row.Item("cardNumber"))
                        If Validto <> "" Then
                            'MsgBox(Mid(row.Item("ValidTo"), 1, 2) & " " & Mid(row.Item("ValidTo"), 3, 2))
                            SDL.GültigBis = DateAdd("d", -1, DateAdd("m", 1, DateSerial("20" & Mid(row.Item("ValidTo"), 1, 2), Mid(row.Item("ValidTo"), 3, 2), 1))) 'noch im DETAIL checken!
                        End If

                        SDL.OBUID = SQL.checkNullStr(row.Item("OBUID"))
                        SDL.Vertragsabschlussdatum = SQL.checkNullStr(row.Item("contractDate"))
                        SDL.Kategorie = SQL.checkNullStr(row.Item("vehicleCategory"))
                        SDL.Schadstoffklasse = SQL.checkNullStr(row.Item("emissionCategory"))
                        SDL.Status = SQL.checkNullStr(row.Item("status"))
                        SDL.Nationalitaet = SQL.checkNullStr(row.Item("nationality"))
                        SDL.CO2Kategorie = SQL.checkNullStr(row.Item("CO2EmissionsClass"))
                        SDL.SAVE()
                    End If

                    Dim strOBU = "OBU " & row.Item("OBUID") & " jetzt in " & KdNr & "/" & row.Item("vehicleLicensePlate") & "/" & SDLNr & "/" & 0 & "."

                    ' Mehrfachvorkommen der OBU-ID prüfen.
                    Dim strSQL = "SELECT OBUID, Vermerk  FROM vwSDL WHERE (SDLNr = " & SDLNr & ") And (OBUID = '" & row.Item("OBUID") & "') And ((KundenNr <> " & KdNr & ") Or (KfzKennzeichen <> '" & row.Item("vehicleLicensePlate") & "'))"
                    Dim dtCheckOBUID As DataTable = SQl.loadDgvBySql_Param(strSQL, "SDL")

                    If dtCheckOBUID.Rows.Count > 0 Then

                        For Each rowCheckOBUID As DataRow In dtCheckOBUID.Rows
                            Dim SDL = New VERAG_PROG_ALLGEMEIN.cSDL(KdNr, row.Item("vehicleLicensePlate"), SDLNr)
                            Dim leftString = Trim(strOBU & " " & SDL.Vermerk.Substring(0, 100))
                            SDL.Vermerk = Trim(strOBU & " " & SDL.Vermerk.Substring(0, 100))
                            SDL.OBUID = DBNull.Value
                            SDL.SAVE()

                        Next
                    End If

                Next


            End If

            Return True

        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.SHOW)
            Return False
        End Try
    End Function

    Public Function fktConvert(KfzKennzeichen) As String
        fktConvert = ""
        Dim I As Integer

        If KfzKennzeichen Is Nothing OrElse KfzKennzeichen Is DBNull.Value Then
            Return Nothing
        End If

        For I = 1 To Len(KfzKennzeichen)
            Select Case Mid(KfzKennzeichen, I, 1)
                Case "A" To "Z"
                    fktConvert = fktConvert & UCase(Mid(KfzKennzeichen, I, 1))
                Case "0" To "9"
                    fktConvert = fktConvert & Mid(KfzKennzeichen, I, 1)
            End Select
        Next I
    End Function

    Public Function fktKundenLkwVerwalten(ByRef KdNr As Integer, ByRef KfzKennzeichen As String, Nationalitaet As String)
        Dim SDL_LKW As New VERAG_PROG_ALLGEMEIN.cSDL_LKW(KdNr, KfzKennzeichen)

        If Not SDL_LKW.hasEntry Then
            SDL_LKW.Erfassungsdatum = Now
        Else
            SDL_LKW.Änderungsdatum = Now
        End If
        SDL_LKW.Sachbearbeiter = "ASFINAG" & IIf(VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM, "_TEST", "")
        SDL_LKW.Nationalität = Nationalitaet

        Return SDL_LKW.SAVE
    End Function
    Public Function fktKundenSDLVerwalten(ByRef KdNr As Integer, ByRef SDLNr As Integer) As Boolean
        Dim KUNDEN_SDL As New VERAG_PROG_ALLGEMEIN.cKundenSDL(KdNr, SDLNr)

        If Not KUNDEN_SDL.hasEntry Then
            KUNDEN_SDL.Erfassungsdatum = Now
        Else
            KUNDEN_SDL.Änderungsdatum = Now
        End If
        KUNDEN_SDL.Sachbearbeiter = "ASFINAG" & IIf(VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM, "_TEST", "")

        Return KUNDEN_SDL.SAVE

    End Function

    Private Sub LinkLabel29_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel29.LinkClicked
        Me.Visible = False
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
        Dim f As New frmTRNCTS_NachrichtenVerarbeitung
        f.ShowDialog()
        Me.Visible = True
    End Sub

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = CheckBox5.Checked 'False
        If Not IsNumeric(txtGJ_UNISPED.Text) Then MsgBox("GJ: Falsches Fomat!")

        If cboBMDUnispedFirma._value = "" Then
            VERAG_PROG_ALLGEMEIN.cBMD_Interface.genDatensatzCSV_ALL(CheckBox4.Checked, False,, txtGJ_UNISPED.Text)
        Else
            VERAG_PROG_ALLGEMEIN.cBMD_Interface.genDatensatzCSV_Buchungen(cboBMDUnispedFirma._value, CheckBox4.Checked, txtGJ_UNISPED.Text)
        End If
    End Sub

    Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = CheckBox5.Checked 'False
        VERAG_PROG_ALLGEMEIN.cBMD_Interface.genDatensatzCSV_ALL(CheckBox4.Checked,, False)
    End Sub

    Private Sub LinkLabel32_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel32.LinkClicked
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
        Dim Empfaenger = cMitarbeiter.GetEMailRecipientForEmailNotification("UID-Prüfung", 20)
        Dim bool = getUID_Pruefung(MyTextBox1.Text, "IMEX", "UID Prüfung IMEX", Empfaenger,,, MyTextBox2._value, cbxVermerk.Checked, cbxUseUIDFinanzOnline.Checked)
        showPic(bool, PictureBox12)
    End Sub
    Private Sub LinkLabel33_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel33.LinkClicked
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
        Dim Empfaenger = cMitarbeiter.GetEMailRecipientForEmailNotification("UID-Prüfung", 24)
        Dim bool = getUID_Pruefung(MyTextBox1.Text, "AMBAR", "UID Prüfung AMBAR", Empfaenger, , "al@verag.ag;as@verag.ag", MyTextBox2._value, cbxVermerk.Checked, cbxUseUIDFinanzOnline.Checked)
        showPic(bool, PictureBox12)
    End Sub

    Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
        UPDATE_SMS()
    End Sub

    Function UPDATE_SMS() As Boolean
        Try
            Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
            Dim dt As DataTable = SQL.loadDgvBySql("SELECT * FROM tblSMS where sms_Status not IN(3,4) and (CASE sms_art WHEN 'WHATSAPP' THEN whatsApp_gatewayId ELSE sms_MessageIds END) is not null and isnull(sms_MessageIds,'') not like 'https://api.esendex.com/%' AND sms_Datum>DATEADD(DAY,-2, GETDATE())", "FMZOLL")
            If dt IsNot Nothing Then
                For Each r In dt.Rows
                    Dim cSMS As New VERAG_PROG_ALLGEMEIN.cSMS(r("sms_id"))

                    Select Case cSMS.sms_art
                        Case "WHATSAPP" : cSMS.checkWhatsAppStatus(True)
                        Case "SMS" : cSMS.checkSMSStatus(True)
                    End Select
                Next
            End If
            Return True
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name)
            Return False
        End Try
    End Function

    Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click, buchungenAMBAR.Click
        If cbxSyskaWdh.Checked And txtSyskaWdhDateiname.Text = "" Then
            MsgBox("Dateiname angeben!") : Exit Sub
        End If

        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = CheckBox6.Checked 'False

        Select Case sender.name
            Case "Button7" '
                If cboSYSKAFirma._value = "" Then
                    VERAG_PROG_ALLGEMEIN.cSyska_Interface.genDatensatz_ALL(CheckBox7.Checked, False, If(cbxSyskaWdh.Checked, txtSyskaWdhDateiname.Text, ""))
                Else
                    VERAG_PROG_ALLGEMEIN.cSyska_Interface.genDatensatz_Buchungen(cboSYSKAFirma._value, CheckBox7.Checked, If(cbxSyskaWdh.Checked, txtSyskaWdhDateiname.Text, ""))
                End If

            Case "buchungenAMBAR"
                VERAG_PROG_ALLGEMEIN.cSyska_Interface.genDatensatz_Buchungen(24, CheckBox7.Checked, If(cbxSyskaWdh.Checked, txtSyskaWdhDateiname.Text, "AG"), True)
                VERAG_PROG_ALLGEMEIN.cSyska_Interface.genDatensatz_Buchungen(24, CheckBox7.Checked, If(cbxSyskaWdh.Checked, txtSyskaWdhDateiname.Text, "CS"), True)
        End Select




    End Sub

    Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = CheckBox6.Checked 'False
        If cboSYSKAFirma._value = "" Then
            VERAG_PROG_ALLGEMEIN.cSyska_Interface.genDatensatz_ALL(CheckBox7.Checked,, False)
        Else
            VERAG_PROG_ALLGEMEIN.cSyska_Interface.genDatensatz_Stammdaten(cboSYSKAFirma._value, CheckBox7.Checked)
        End If
    End Sub

    Private Sub Button8_Click(sender As Object, e As EventArgs) Handles Button8.Click
        Dim FO As New VERAG_PROG_ALLGEMEIN.cFinanzOnlineWebService
        VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "VERAG"
        FO.initValues()

        If FO.Call_Web_Service_MethodUID_Login_NEU2020() = 0 Then
            Dim UID_ERG = FO.Call_Web_Service_MethodUID_Abfrage_NEU2020(759181)

            If UID_ERG IsNot Nothing Then

                Select Case UID_ERG.uid_valid
                    Case 1 : MsgBox("UID-Nr. GÜLTIG   -   OK")
                    Case 0 : MsgBox("UID-Nr. UNGÜLTIG")
                End Select
            End If
        End If

        FO.Call_Web_Service_MethodUID_Logout_NEU2020()


        ' VERAG_PROG_ALLGEMEIN.cFinanzOnlineWebService.Call_Web_Service_MethodUID_Abfrage_NEU2020("DE115311033")


        'doExcelImportNCTS_FREMD(InputBox("Eing:",, "F:\mic2.xlsx"))
        'Dim list As New List(Of Integer)
        'Dim DY As New DAKOSY_Worker.cDakosy_Zollanmeldungen(572237)
        'Dim SND As New VERAG_PROG_ALLGEMEIN.cSendungen(DY.dy_SendungsId)

        'sendMailZollbeleg("C:\VeragTMP\USER_4\VERG-SYS_IMP_ZOLL_TAX-IPDC-4803_21061055-ATC400039161120217701-$V8.pdf", 750735, "STB", list, DY.dy_BezugsNr, SND)
    End Sub

    Private Sub lblEZOLLDat_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles lblEZOLLDat.LinkClicked
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False

        If cbxEZOLLUNISPED.Checked Then

            Dim f = VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA
            VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "UNISPED"
            Dim bool = importFileFromEZOLL(txtEZOLLAnhDat._value, cbxSendEZOLL_INFO.Checked)
            showPic(bool, piceZollAnh)
            VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = f

        Else
            Dim bool = importFileFromEZOLL(txtEZOLLAnhDat._value, cbxSendEZOLL_INFO.Checked)
            showPic(bool, piceZollAnh)

        End If


    End Sub

    Private Sub CheckBox2_CheckedChanged(sender As Object, e As EventArgs)

    End Sub

    Private Sub LinkLabel35_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel35.LinkClicked
        Me.Visible = False
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = True
        Dim f As New frmTRNCTS_NachrichtenVerarbeitung_OREGON
        f.ShowDialog()
        Me.Visible = True
    End Sub

    Private Sub LinkLabel34_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel34.LinkClicked
        Me.Visible = False
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
        Dim f As New frmTRNCTS_NachrichtenVerarbeitung_OREGON
        f.ShowDialog()
        Me.Visible = True
    End Sub

    Private Sub Button10_Click(sender As Object, e As EventArgs) Handles Button10.Click
        'VERAG_PROG_ALLGEMEIN.cSyska_Interface.genDatensatz_StammdatenTEST(1, True)
    End Sub

    Private Sub Button12_Click(sender As Object, e As EventArgs) Handles Button12.Click
        'VERAG_PROG_ALLGEMEIN.cSyska_Interface.UPDATE_FIBU_RISIKO(401026)
        'VERAG_PROG_ALLGEMEIN.cSyska_Interface.UPDATE_FIBU_RISIKO(401516)
        'VERAG_PROG_ALLGEMEIN.cSyska_Interface.UPDATE_FIBU_RISIKO(203203)
        'VERAG_PROG_ALLGEMEIN.cSyska_Interface.UPDATE_FIBU_RISIKO(202888)
        'VERAG_PROG_ALLGEMEIN.cSyska_Interface.UPDATE_FIBU_RISIKO(101001)
        'VERAG_PROG_ALLGEMEIN.cSyska_Interface.UPDATE_FIBU_RISIKO(402155)
        'VERAG_PROG_ALLGEMEIN.cSyska_Interface.UPDATE_FIBU_RISIKO(402055)
        'VERAG_PROG_ALLGEMEIN.cSyska_Interface.UPDATE_FIBU_RISIKO(300405)
        'VERAG_PROG_ALLGEMEIN.cSyska_Interface.UPDATE_FIBU_RISIKO(202766)
        'VERAG_PROG_ALLGEMEIN.cSyska_Interface.UPDATE_FIBU_RISIKO(203252)
        'VERAG_PROG_ALLGEMEIN.cSyska_Interface.UPDATE_FIBU_RISIKO(401454)
        'VERAG_PROG_ALLGEMEIN.cSyska_Interface.UPDATE_FIBU_RISIKO(202479)
        'VERAG_PROG_ALLGEMEIN.cSyska_Interface.UPDATE_FIBU_RISIKO(402162)
        'VERAG_PROG_ALLGEMEIN.cSyska_Interface.UPDATE_FIBU_RISIKO(401729)
        'VERAG_PROG_ALLGEMEIN.cSyska_Interface.UPDATE_FIBU_RISIKO(202811)

        VERAG_PROG_ALLGEMEIN.cSyska_Interface.UPDATE_FIBU_RISIKO()

    End Sub

    Private Sub Button13_Click(sender As Object, e As EventArgs) Handles Button13.Click
        VERAG_PROG_ALLGEMEIN.cSyska_Interface.OP_Einlesen_ALL()
    End Sub

    Private Sub LinkLabel36_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel36.LinkClicked
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
        Dim Empfaenger = cMitarbeiter.GetEMailRecipientForEmailNotification("UID-Prüfung", 21)
        Dim bool = getUID_Pruefung(MyTextBox1.Text, "UNISPED", "UID Prüfung UNISPED", Empfaenger, "al@verag.ag",, MyTextBox2._value, cbxVermerk.Checked, cbxUseUIDFinanzOnline.Checked)
        showPic(bool, PictureBox12)
    End Sub

    Private Sub Button14_Click(sender As Object, e As EventArgs) Handles Button14.Click
        VERAG_PROG_ALLGEMEIN.cLDV_Interface.copyLDV_BMD()

    End Sub

    Private Sub TabPage1_Click(sender As Object, e As EventArgs) Handles TabPage1.Click

    End Sub

    Private Sub Button15_Click(sender As Object, e As EventArgs) Handles Button15.Click
        doExcelImportNCTS_FREMD()
    End Sub

    Private Sub Button16_Click(sender As Object, e As EventArgs) Handles Button16.Click
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
        doIDSPlatts()
        doExcelImportNCTS_FREMD()
    End Sub

    Private Sub LinkLabel37_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel37.LinkClicked
        Me.Cursor = Cursors.WaitCursor
        Try
            DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0141", True) 'TESTSYSTEM
            Dim erg = DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0141", False) 'ECHTSYSTEM
            showPic(erg, PictureBox16)
        Catch ex As Exception : VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name) : End Try
        Me.Cursor = Cursors.Default
    End Sub

    Private Sub LinkLabel38_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel38.LinkClicked
        Me.Cursor = Cursors.WaitCursor
        Try
            DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("I0610", True) 'TESTSYSTEM
            Dim erg = DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("I0610", False) 'ECHTSYSTEM
            showPic(erg, PictureBox17)
        Catch ex As Exception : VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name) : End Try
        Me.Cursor = Cursors.Default
    End Sub

    Private Sub LinkLabel40_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel40.LinkClicked
        Me.Visible = False
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = True
        Dim f As New frmTRNCTS_NachrichtenVerarbeitung_ATEZ
        f.ShowDialog()
        Me.Visible = True
    End Sub

    Private Sub LinkLabel39_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel39.LinkClicked
        Me.Visible = False
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
        Dim f As New frmTRNCTS_NachrichtenVerarbeitung_ATEZ
        f.ShowDialog()
        Me.Visible = True
    End Sub

    Private Sub btnDatev_Click(sender As Object, e As EventArgs) Handles btnDatev.Click
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = cbxDatevTest.Checked
        VERAG_PROG_ALLGEMEIN.cDatev_Interface.genDatensatzCSV_ALL("AMBAR", cbxDatevOpen.Checked, cbxDatevDebitoren.Checked, cbxDatevBuchungen.Checked)
    End Sub

    Private Sub LinkLabel44_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel44.LinkClicked
        Me.Visible = False
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = cbxTestsystem.Checked
        If Not checkTestsystemSettings() Then Exit Sub
        Dim f As New frmAsfinag_NachrichtenVerabeitung("TTR", cbxTestFTP.Checked)
        f.ShowDialog()
        Me.Visible = True
    End Sub

    Private Sub LinkLabel43_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel43.LinkClicked
        Me.Visible = False
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = cbxTestsystem.Checked
        If Not checkTestsystemSettings() Then Exit Sub
        Dim f As New frmAsfinag_NachrichtenVerabeitung("CLF", cbxTestFTP.Checked)
        f.ShowDialog()
        Me.Visible = True
        'ASFINAG_LKW(False)
    End Sub

    Private Sub LinkLabel42_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel42.LinkClicked
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = cbxTestsystem.Checked
        If Not checkTestsystemSettings() Then Exit Sub
        Me.Cursor = Cursors.WaitCursor
        Dim blt = New cAsfinag.Exportist
        blt.initExportPfade()
        showPic(blt.exportiereWhiteList, PictureBox18)
        Me.Cursor = Cursors.Default
    End Sub

    Private Sub LinkLabel41_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel41.LinkClicked
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = cbxTestsystem.Checked
        If Not checkTestsystemSettings() Then Exit Sub
        Me.Cursor = Cursors.WaitCursor
        Dim blt = New cAsfinag.Exportist
        blt.initExportPfade()
        showPic(blt.exportiereBlackList, PictureBox19)
        Me.Cursor = Cursors.Default
    End Sub

    Private Sub LinkLabel45_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel45.LinkClicked

        showPic(importEZOLLWechselkurse(VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM), PictureBox20)

    End Sub

    Private Sub LinkLabel63_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel63.LinkClicked

        showPic(importEZOLLWechselkurse(VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM, 2, 2), PictureBox24)
    End Sub
    Private Sub Button17_Click(sender As Object, e As EventArgs) Handles Button17.Click
        Dim f As New frmDatenarchivarchiv
        f.ShowDialog()
    End Sub

    Private Sub Button18_Click(sender As Object, e As EventArgs) Handles Button18.Click
        Dim abDatum = Nothing
        If MyTextBox4._value <> "" Then abDatum = CDate(MyTextBox4._value)
        doAASVermerke_Schwelle(abDatum)

    End Sub

    Function doAASVermerke_Schwelle(Optional abDatum = Nothing)
        Try
            Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
            Dim dt = SQL.loadDgvBySql("
               SELECT TOP 1000 aviso.AvisoID,Vermerke.[Hinweis_Vermerk],Vermerke.SendungID SendungsId
                ,CASE WHEN Vermerke.SendungID is not null THEN(SELECT FilialenNr from tblSendungen WHERE tblSnd_SendungID=Vermerke.SendungID) ELSE NULL END FilialenNr,VermerkID
                  FROM [Aviso]
                  inner join Vermerke on [Aviso].AvisoID=Vermerke.AvisoID
                  inner join VermerkeCodes on Vermerke.VermerkeCode=VermerkeCodes.VermerkCodeId
                  WHERE  [Aviso].Status NOT IN (1,2)  AND  AAS_Warnsystem=1 and AAS_Warnstufe=0 and DATEDIFF(HOUR,Vermerke.Datum,GETDATE())>AAS_SchwelleStunden and [VermerkIDAufgehoben] is null
                    /*and (Auftraggeber_KdNr IN (901043,100950,700945) or Frächter_KdNr IN (901043,100950,700945))*/
                    AND Aviso.Datum >  " & If(abDatum IsNot Nothing, "'" & CDate(abDatum).ToShortDateString & "'", " DATEADD( day,-1,GETDATE())") & "
                    AND Geloescht=0
                ", "AVISO")

            If dt IsNot Nothing Then
                For Each r In dt.Rows
                    '  MsgBox(r("AvisoId"))
                    insertBenachrichtigung_AAS(r("AvisoId"), r("SendungsId"), VERAG_PROG_ALLGEMEIN.cAllgemein.getFirmaFromFiliale2(r("FilialenNr")), VERAG_PROG_ALLGEMEIN.cAvisoBenachrichtigungenCodes.AAE_Benachrichtigung, "AAS: REMINDER", "REMINDER: " & r("Hinweis_Vermerk"), 1, r("VermerkID"))
                    ' insertVermerk(r("AvisoId"), r("SendungsId"), 115, "(AAS) " & r("Hinweis_Vermerk"))

                    ' MsgBox("done")
                Next
            End If
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
            Return False
        End Try
        Return True
    End Function
    Function doAASVermerke_24h()
        Try
            Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
            Dim dt = SQL.loadDgvBySql("
               SELECT TOP 1000 aviso.AvisoID, Datum
                  FROM [Aviso]
                  WHERE  [Aviso].Status NOT IN (1,2,5) 
                  and DATEDIFF(HOUR, (select top 1 Datum from Vermerke where Vermerke.AvisoID=aviso.AvisoID order by Vermerke.Datum desc),GETDATE())>24
                  and DATEDIFF(HOUR, (select top 1 Datum from Aenderungen where Aenderungen.AvisoID=aviso.AvisoID order by Aenderungen.Datum desc),GETDATE())>24
                  AND Datum > DATEADD( day,-2,GETDATE())    AND [Aviso].Firma not in ( 'ATILLA')
                ", "AVISO")

            If dt IsNot Nothing Then
                For Each r In dt.Rows
                    MsgBox("" & r("AvisoId"),)
                    insertBenachrichtigung_AAS(r("AvisoId"), r("SendungsId"), VERAG_PROG_ALLGEMEIN.cAllgemein.getFirmaFromFiliale2(r("FilialenNr")), VERAG_PROG_ALLGEMEIN.cAvisoBenachrichtigungenCodes.AAE_Benachrichtigung, "AAS: REMINDER 24h", "REMINDER: " & r("Hinweis_Vermerk"), 0, Nothing)
                    '  insertVermerk(r("AvisoId"), r("SendungsId"), 115, "(AAS) " & r("Hinweis_Vermerk"))
                    MsgBox("2")
                Next
            End If
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
            Return False
        End Try
        Return True
    End Function

    Function doAASVermerke_Ankunft() ' 4 Stunden
        Try
            Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
            Dim dt = SQL.loadDgvBySql("
                 SELECT TOP 1000 aviso.AvisoID, Datum
                  FROM [Aviso]
                  WHERE  [Aviso].Status IN (3) 
                  and DATEDIFF(HOUR, (select top 1 Datum from Vermerke where Vermerke.AvisoID=aviso.AvisoID order by Vermerke.Datum desc),GETDATE())>4
                  and DATEDIFF(HOUR, (select top 1 Datum from Aenderungen where Aenderungen.AvisoID=aviso.AvisoID order by Aenderungen.Datum desc),GETDATE())>4
                  AND Datum > DATEADD( day,-2,GETDATE())
  
                ", "AVISO")

            If dt IsNot Nothing Then
                For Each r In dt.Rows
                    insertBenachrichtigung_AAS(r("AvisoId"), r("SendungsId"), VERAG_PROG_ALLGEMEIN.cAllgemein.getFirmaFromFiliale2(r("FilialenNr")), VERAG_PROG_ALLGEMEIN.cAvisoBenachrichtigungenCodes.AAE_Benachrichtigung, "AAS: REMINDER", "REMINDER: " & r("Hinweis_Vermerk"), 0, Nothing)
                    insertVermerk(r("AvisoId"), r("SendungsId"), 115, "(AAS) " & r("Hinweis_Vermerk"))

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

    Function insertBenachrichtigung_AAS(AvisoId, SendungsId, firma, code, TXT_AAS_HEAD, TXT_AAS_BODY, prio, VermerkID)
        '
        'Benachrichtigung
        If SendungsId Is DBNull.Value Then SendungsId = Nothing
        Try
            'Benutzer vorschreiben der Sendung...
            Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
            Dim sendToID As String = SQL.DLookup("tblSnd_VG_MA", "tblSendungen", "tblSnd_SendungID='" & SendungsId & "'", "AVISO", -1)
            Dim art = "B"
            'MsgBox("Benutzer vorschreiben" & sendToID)

            'Wenn Benutzer vorschreiben nicht online, dann Benutzer der Sendung...
            If sendToID <= 0 OrElse (Not VERAG_PROG_ALLGEMEIN.cSession.IS_ONLINE(sendToID, True)) Then
                sendToID = SQL.DLookup("LetzterMitarbeiterId", "tblSendungen", "tblSnd_SendungID='" & SendungsId & "'", "AVISO", -1)
                art = "B"
            End If
            ' MsgBox("Benutzer der Sendung" & sendToID)

            'Wenn Benutzer der Sendung nicht online, dann Benutzer des LKW ..
            If sendToID <= 0 OrElse (Not VERAG_PROG_ALLGEMEIN.cSession.IS_ONLINE(sendToID, True)) Then
                sendToID = SQL.DLookup("LetzterMitarbeiterId", "Aviso", "AvisoId='" & AvisoId & "'", "AVISO", -1)
                art = "B"
            End If
            '  MsgBox("Benutzer der LKW" & sendToID)

            'Wenn Benutzer des LKWs nicht online, Team der Sendung...
            If sendToID <= 0 OrElse (Not VERAG_PROG_ALLGEMEIN.cSession.IS_ONLINE(sendToID, True)) Then
                sendToID = SQL.DLookup("tblSnd_TeamId", "tblSendungen", "tblSnd_SendungID='" & SendungsId & "'", "AVISO", -1)
                art = "T"
            End If
            '  MsgBox("Team der Sendung" & sendToID)

            'Wenn Team der Sendung nicht gefunden, Team des LKW...
            If sendToID <= 0 Then
                sendToID = SQL.DLookup("TeamId", "Aviso", "AvisoID='" & AvisoId & "'", "AVISO", -1)
                art = "T"
            End If
            ' MsgBox("Team LKW " & sendToID)

            'Wenn TEAM LKW nicht gefunden, Firma...
            If sendToID <= 0 Then
                If firma IsNot Nothing AndAlso firma <> "" Then
                    sendToID = firma
                    art = "F"
                End If
            End If
            ' MsgBox("XXXX" & sendToID)


            'Wenn gefunden
            If (art = "F" AndAlso If(sendToID, "") <> "") OrElse sendToID >= 0 Then
                Dim statusAVISO = SQL.DLookup("Status", "Aviso", "AvisoID='" & AvisoId & "'", "AVISO")
                Dim GrenzstelleAVISO = SQL.DLookup("Grenzstelle", "Aviso", "AvisoID='" & AvisoId & "'", "AVISO")
                '  If GrenzstelleAVISO = "???" Then
                Select Case statusAVISO
                    Case VERAG_PROG_ALLGEMEIN.cGlobal.Status_NichtEingetroffen, VERAG_PROG_ALLGEMEIN.cGlobal.Status_Freigegeben
                        'Nicht
                    Case Else
                        VERAG_PROG_ALLGEMEIN.cAvisoBenachrichtigungen.INSERT_BENACHRICHTIGUNG(AvisoId, SendungsId, code, art, sendToID, TXT_AAS_HEAD, prio, , TXT_AAS_BODY.Trim,,, firma, VermerkID)
                        insertVermerk(AvisoId, SendungsId, 115, "(AAS) " & TXT_AAS_BODY)
                        cVermerkeDAL.increaseWarnstufe(VermerkID)
                End Select
                ' End If
            End If

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


    Function insertBenachrichtigung_BearbeitendeEinheit(AvisoId, SendungsId, firma, code, TXT_HEAD, TXT_BODY, prio)
        '
        'Benachrichtigung
        If SendungsId Is DBNull.Value Then SendungsId = Nothing
        Try
            'Benutzer vorschreiben der Sendung...
            Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
            Dim sendToID As String = SQL.DLookup("tblSnd_VG_MA", "tblSendungen", "tblSnd_SendungID='" & SendungsId & "'", "AVISO", -1)
            Dim art = "B"
            'MsgBox("Benutzer vorschreiben" & sendToID)

            'Wenn Benutzer vorschreiben nicht online, dann Benutzer der Sendung...
            If sendToID <= 0 OrElse (Not VERAG_PROG_ALLGEMEIN.cSession.IS_ONLINE(sendToID, True)) Then
                sendToID = SQL.DLookup("LetzterMitarbeiterId", "tblSendungen", "tblSnd_SendungID='" & SendungsId & "'", "AVISO", -1)
                art = "B"
            End If
            ' MsgBox("Benutzer der Sendung" & sendToID)

            'Wenn Benutzer der Sendung nicht online, dann Benutzer des LKW ..
            If sendToID <= 0 OrElse (Not VERAG_PROG_ALLGEMEIN.cSession.IS_ONLINE(sendToID, True)) Then
                sendToID = SQL.DLookup("LetzterMitarbeiterId", "Aviso", "AvisoId='" & AvisoId & "'", "AVISO", -1)
                art = "B"
            End If
            '  MsgBox("Benutzer der LKW" & sendToID)

            'Wenn Benutzer des LKWs nicht online, Team der Sendung...
            If sendToID <= 0 OrElse (Not VERAG_PROG_ALLGEMEIN.cSession.IS_ONLINE(sendToID, True)) Then
                sendToID = SQL.DLookup("tblSnd_TeamId", "tblSendungen", "tblSnd_SendungID='" & SendungsId & "'", "AVISO", -1)
                art = "T"
            End If
            '  MsgBox("Team der Sendung" & sendToID)

            'Wenn Team der Sendung nicht gefunden, Team des LKW...
            If sendToID <= 0 Then
                sendToID = SQL.DLookup("TeamId", "Aviso", "AvisoID='" & AvisoId & "'", "AVISO", -1)
                art = "T"
            End If
            ' MsgBox("Team LKW " & sendToID)

            'Wenn TEAM LKW nicht gefunden, Firma...
            If sendToID <= 0 Then
                If firma IsNot Nothing AndAlso firma <> "" Then
                    sendToID = firma
                    art = "F"
                End If
            End If


            'Wenn gefunden
            If (art = "F" AndAlso If(sendToID, "") <> "") OrElse sendToID >= 0 Then
                Dim statusAVISO = SQL.DLookup("Status", "Aviso", "AvisoID='" & AvisoId & "'", "AVISO")
                Dim GrenzstelleAVISO = SQL.DLookup("Grenzstelle", "Aviso", "AvisoID='" & AvisoId & "'", "AVISO")
                '  If GrenzstelleAVISO = "???" Then
                Select Case statusAVISO
                    Case VERAG_PROG_ALLGEMEIN.cGlobal.Status_NichtEingetroffen, VERAG_PROG_ALLGEMEIN.cGlobal.Status_Freigegeben
                        'Nicht
                    Case Else
                        VERAG_PROG_ALLGEMEIN.cAvisoBenachrichtigungen.INSERT_BENACHRICHTIGUNG(AvisoId, SendungsId, code, art, sendToID, TXT_HEAD, prio, , TXT_BODY.Trim,,, firma)
                End Select
            End If

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


    Sub insertVermerk(AvisoID, SendungID, VermerkCodeId, VermerkText)
        If SendungID Is DBNull.Value Then SendungID = -1

        Dim myVermerk As New cVermerk
        myVermerk.VermerkID = 0
        myVermerk.AvisoID = AvisoID
        myVermerk.Datum = Now
        myVermerk.Mitarbeiter = "AAS (AUTO)"
        myVermerk.MitarbeiterId = -1
        myVermerk.Hinweis_Vermerk = VermerkText
        myVermerk.VermerkCodeId = VermerkCodeId
        myVermerk.SendungID = SendungID
        myVermerk.HintergrundVermerk = True
        If SendungID > 0 Then myVermerk.VermerkArt = "S" Else myVermerk.VermerkArt = "A"
        Dim VermerkeDAL As New cVermerkeDAL

        VermerkeDAL.SpeichernVermerk(myVermerk)

    End Sub

    Private Sub Button19_Click(sender As Object, e As EventArgs) Handles Button19.Click
        doAASVermerke_24h()
    End Sub

    Private Sub Button20_Click(sender As Object, e As EventArgs) Handles Button20.Click
        doAASVermerke_Ankunft()
    End Sub

    Private Sub LinkLabel99_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel46.LinkClicked

        Try
            VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = cbxTestsystem.Checked

            Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
            Dim frm As New Form
            Dim dgv As New DataGridView()
            Dim dt As DataTable = SQL.loadDgvBySql("SELECT dbo.CLFBody.PKHistory,
                                                    dbo.CLFBody.ImportDate,
                                                    dbo.CLFBody.PKFileName,
                                                    dbo.CLFBody.PKLine,
                                                    dbo.CLFBody.RecordType,
                                                    dbo.CLFBody.fileNumber,
                                                    dbo.CLFBody.cardNumber,
                                                    dbo.CLFBody.validTo,	
                                                    dbo.CLFBody.OBUID,
                                                    dbo.CLFBody.vehicleLicensePlate,
                                                    dbo.CLFBody.nationality,
                                                    dbo.CLFBody.vehicleCategory,
                                                    dbo.CLFBody.emissionCategory,
                                                    dbo.CLFBody.status,
                                                    dbo.CLFBody.contractDate,
                                                    dbo.CLFBody.fileVersion,
                                                    dbo.CLFBody.engineCharacteristics,
                                                    dbo.CLFBody.CO2EmissionsClass,
                                                    dbo.CLFBody.contractType FROM dbo.CLF INNER JOIN dbo.CLFBody ON dbo.CLF.PKHistory = dbo.CLFBody.PKHistory AND dbo.CLF.PKFileName = dbo.CLFBody.PKFileName
                                                    ", "ASFINAG")

            dgv.DataSource = dt
            If dgv IsNot Nothing Then
                frm.Size = New Size(1400, 1000)
                dgv.Size = New Size(frm.Size.Width - 50, frm.Size.Height - 50)
                dgv.Dock = DockStyle.Fill
                dgv.Anchor = AnchorStyles.Left
                dgv.Anchor = AnchorStyles.Top
                dgv.ReadOnly = True
                frm.Controls.Add(dgv)
                frm.StartPosition = FormStartPosition.CenterScreen
                frm.ShowDialog()
            End If


        Catch ex As Exception

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

    End Sub

    Private Function importEZOLLWechselkurse(isTestsystem As Boolean, Optional kursart As Integer = 1, Optional art As Integer = 1) As Boolean

        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = isTestsystem

        'KURSART 1 = notirete Währung, 2 ...
        'ART 1 = cFremdwaehrungskurse, 2 WährungkurseNeu


        Dim MyData As String = ""
        Dim SQL = New SQL
        Dim erg = True

        Dim firstDaycurrentMonth = DateTime.Now.AddMonths(0)
        firstDaycurrentMonth = New DateTime(firstDaycurrentMonth.Year, firstDaycurrentMonth.Month, 1)

        Dim lastDaycurrentMonth = DateTime.Now.AddMonths(1)
        lastDaycurrentMonth = New DateTime(lastDaycurrentMonth.Year, lastDaycurrentMonth.Month, 1).AddDays(-1)


        Dim startdatum_tag2 = firstDaycurrentMonth.Day
        Dim startdatum_monat2 = firstDaycurrentMonth.Month
        Dim startdatum_jahr2 = firstDaycurrentMonth.Year
        Dim enddatum_tag2 = lastDaycurrentMonth.Day
        Dim enddatum_monat2 = lastDaycurrentMonth.Month
        Dim enddatum_jahr2 = lastDaycurrentMonth.Year


        Try
            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12

            Using WC As New System.Net.WebClient()
                ' C0008_URL()
                WC.Encoding = ASCIIEncoding.UTF8

                'Mit dem 26.02.2025 hat sich die URL für den Abruf der Wechselkurse geändert!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                'Dim URL = "https://www.zoll.de/SiteGlobals/Functions/Kurse/KursExport.xml?view=xmlexportkursesearchresultZOLLWeb&kursart=" & kursart &
                Dim URL = "https://www.zoll.de/SiteGlobals/Functions/Kurse/KursExport.xml?view=xmlexportkursesearchresultzoll&kursart=" & kursart &
                    "&startdatum_tag2=" & startdatum_tag2 &
                    "&startdatum_monat2=" & startdatum_monat2 &
                    "&startdatum_jahr2=" & startdatum_jahr2 &
                    "&enddatum_tag2=" & enddatum_tag2 &
                    "&enddatum_monat2=" & enddatum_monat2 &
                    "&enddatum_jahr2=" & enddatum_jahr2 &
                    "&sort=asc&spalte=gueltigkeit"
                If URL = String.Empty Then Return False

                MyData = WC.DownloadString(URL)
                Dim doc As New XmlDocument()
                doc.LoadXml(MyData)
                If doc.HasChildNodes Then

                    If doc.GetElementsByTagName("kurs").Count > 0 Then
                        Dim endDatum, startDatum
                        Dim count As Integer = 1
                        For Each node As XmlElement In doc.GetElementsByTagName("kurs")
                            Dim wk
                            If art = 1 Then
                                wk = New cFremdwaehrungskurse() ' notierte Währungen
                            Else
                                wk = New cWaehrungskurseNEU() 'nicht notierte Währungen
                            End If
                            If node.Attributes("id") IsNot Nothing Then wk.fw_id = node.Attributes("id").Value
                            If node.HasChildNodes Then
                                For Each element As XmlElement In node.ChildNodes
                                    If element.Name = "land" AndAlso element.InnerText <> "" Then wk.fw_land = element.InnerText
                                    If element.Name = "iso2" AndAlso element.InnerText <> "" Then wk.fw_iso2 = element.InnerText
                                    If element.Name = "iso3" AndAlso element.InnerText <> "" Then wk.fw_iso3 = element.InnerText
                                    If element.Name = "kurswert" AndAlso element.InnerText <> "" Then
                                        wk.fw_kurswert = element.InnerText
                                    End If
                                    If art = 1 Then
                                        If element.Name = "startdatum" AndAlso element.InnerText <> "" Then
                                            wk.fw_startdatum = element.InnerText
                                            startDatum = wk.fw_startdatum
                                        End If
                                        If element.Name = "enddatum" AndAlso element.InnerText <> "" Then
                                            wk.fw_enddatum = element.InnerText
                                            endDatum = wk.fw_enddatum
                                        End If
                                    End If

                                Next
                                count = count + 1
                                wk.SAVE()
                            End If
                        Next
                        Dim wk_euro

                        If art = 1 Then
                            wk_euro = New cFremdwaehrungskurse()
                        Else
                            wk_euro = New cWaehrungskurseNEU()
                        End If

                        wk_euro.fw_id = 0
                        wk_euro.fw_land = "Europa"
                        wk_euro.fw_kurswert = 1
                        wk_euro.fw_iso3 = "EUR"
                        wk_euro.fw_iso2 = "EU"
                        If art = 1 Then
                            wk_euro.fw_startdatum = firstDaycurrentMonth.ToShortDateString()
                            wk_euro.fw_enddatum = lastDaycurrentMonth.ToShortDateString()
                        End If

                        wk_euro.SAVE()

                        'Dim sqlCount = SQL.getValueTxtBySqlVarList("SELECT isnull(count(*),0) FROM tblZOLL_Wechselkurse WHERE [fw_startdatum]='" & startDatum & "' AND fw_enddatum='" & endDatum & "'", "FMZOLL")
                        'If count <> sqlCount Then
                        '    'MsgBox("Anzahl der Importierten Datensätze:" & sqlCount & vbNewLine & "Anzahl Datensätze in Datei: " & count)
                        '    'erg = False
                        'End If

                    End If
                End If

            End Using
            Return erg
        Catch ex As Exception
            MsgBox(ex.Message & ex.StackTrace)
        End Try
    End Function

    Private Sub LinkLabel47_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel47.LinkClicked
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = cbxTestsystem.Checked
        showPic(ASFINAG_LKW(False), PictureBox21)
    End Sub

    Private Sub LinkLabel46_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel99.LinkClicked, LinkLabel46.LinkClicked
        Me.Cursor = Cursors.WaitCursor
        Try
            DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0219", True) 'TESTSYSTEM
            Dim erg = DAKOSY_Worker.cIMPORT_Codelisten.IMPORT("C0219", False) 'ECHTSYSTEM
            showPic(erg, PictureBox99)
        Catch ex As Exception : VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name) : End Try
        Me.Cursor = Cursors.Default
    End Sub

    Private Function checkTestsystemSettings() As Boolean
        Dim check As Boolean = False
        If cbxTestFTP.Checked And Not cbxTestsystem.Checked Then
            MsgBox("Testdaten von/auf TEST-FTP in/von Prod-Umgebung importieren/exportieren?" & vbNewLine & " Keine gute Idee!")
        Else
            check = True
        End If
        Return check

    End Function

    Private Sub tbcntr_SelectedIndexChanged(sender As Object, e As EventArgs) Handles tbcntr.SelectedIndexChanged
        If tbcntr.SelectedIndex = 3 Then

            checkTBLandTWLNr()
            getLatestBatchNrMSE()

        ElseIf tbcntr.SelectedIndex = 5 Then
            Dim count As Integer = 0
            countmissingCSinPortfolio(count)
            lbl_CS_online.Text = count

        ElseIf tbcntr.SelectedIndex = 6 Then

            VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = cbxDatevTest.Checked

            cbxOffertenNr.Items.Clear()
            cbxOffertenNr.fillWithSQL("SELECT [OffertenNr],[OffertenBez]  FROM [Offertenstamm] order by OffertenNr", True, "FMZOLL", True)
            cbxOffertenNr.changeItem("")
            cbxLeistungNr.Items.Clear()


        End If

    End Sub

    Private Sub checkTBLandTWLNr()

        Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = cbxTestsystem.Checked
        Dim dt = SQL.loadDgvBySql("SELECT filename, fileVersion from [dbo].[FileINfo]", "ASFINAG")

        If dt IsNot Nothing Then
            For Each r In dt.Rows
                If r("filename") = "TBL" Then txtTBLNr.Text = r("fileVersion")
                If r("filename") = "TWL" Then txtTWLNr.Text = r("fileVersion")

            Next


        End If

    End Sub

    Private Sub getLatestBatchNrMSE()

        Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = cbxTestsystem.Checked
        cbxMSEBatchNr.DataSource = SQL.loadCboBySql("SELECT distinct top 20 ([batch_seq_nr]) FROM [VERAG].[dbo].[tblMSETransactions] order by batch_seq_nr desc", "FMZOLL")

    End Sub


    Private Sub cbxTestsystem_CheckedChanged(sender As Object, e As EventArgs) Handles cbxTestsystem.CheckedChanged
        If tbcntr.SelectedIndex = 3 Then
            checkTBLandTWLNr()
            getLatestBatchNrMSE()
        End If
    End Sub

    Private Sub LinkLabel49_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel49.LinkClicked
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = cbxTestsystem.Checked
        If Not checkTestsystemSettings() Then Exit Sub
        Me.Cursor = Cursors.WaitCursor
        Dim blt = New cAsfinag.Exportist
        blt.initExportPfade()
        showPic(blt.exportiereWhiteList, PictureBox18)
        showPic(blt.exportiereBlackList, PictureBox19)
        Me.Cursor = Cursors.Default
    End Sub

    Private Sub LinkLabel50_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel50.LinkClicked, LinkLabel71.LinkClicked
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
        If sender Is LinkLabel50 Then
            sendWOELFL_USTVAntraege("MAIL", CheckBox9.Checked, "al@verag.ag")
        ElseIf sender Is LinkLabel71 Then
            sendWOELFL_USTVAntraege("FTP", CheckBox9.Checked)
        End If

    End Sub

    Function INSERT_Kundenumsaetze(insertLastYears As Integer) As Boolean
        Try

            Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL

            Dim sqltext = "INSERT INTO tblKundenumsatz ( KundenNr, Firma_ID, Jahr, steuerpflichtig, steuerfrei, Nettoumsatz, MwSt, Bruttoumsatz, Währung, Rechnungen, Gutschriften, Datum, Nummer )
                            SELECT RechnungsKundenNr AS KundenNr, 
                            Firma_ID, 
                            Year([Rechnungsdatum]) AS Jahr, 
                            Sum(SteuerpflichtigerBetragLokal) AS steuerpflichtig, 
                            Sum(SteuerfreierBetragLokal) AS steuerfrei,
                            Sum(SteuerfreierBetragLokal) AS Nettoumsatz, 
                            Sum(SteuerbetragLokal) AS MwSt, 
                            Sum(RechnungsbetragLokal) AS Bruttoumsatz, 
                            WährungLokal AS Währung, 
                            sum(Case when [BelegartenNr]=70 Then 1 else 0 End) as Rechnungen,
                            sum(Case when [BelegartenNr]=71 Then 1 else 0 End) as Gutschriften,
                            Max(Rechnungsdatum) AS Datum, 
                            Max(Rechnungsnummer) AS Nummer
                            FROM [VERAG].[dbo].[tblTrdinInvoice]
                            where Year([Rechnungsdatum]) > (year(getdate()) - " & insertLastYears & ")
                            GROUP BY RechnungsKundenNr, Firma_ID, Year([Rechnungsdatum]), WährungLokal
                            ORDER BY RechnungsKundenNr, Firma_ID, Year([Rechnungsdatum]) DESC , WährungLokal"

            Return SQL.doSQL(sqltext, "FMZOLL")
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)

            Return False

        End Try
    End Function




    Function DELETE_Kundenumsaetze(deleteLastYears As Integer) As Boolean
        Try

            Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
            Return SQL.doSQL("DELETE from tblKundenumsatz where Jahr > (year(getdate()) -" & deleteLastYears & ")", "FMZOLL")

        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)
            Return False
        End Try
    End Function

    Private Sub Button22_Click(sender As Object, e As EventArgs) Handles Button22.Click
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
        Dim lastyears = 2
        Dim ok = False
        If DELETE_Kundenumsaetze(lastyears) Then
            ok = INSERT_Kundenumsaetze(lastyears)
        End If
        showPic(ok, PictureBox22)
    End Sub

    Private Sub LinkLabel51_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel51.LinkClicked
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
        Dim CHAT As New cMessenger.cMessenger_Chat
        showPic(CHAT.setOldChatsInactiv(MyTextBox3.Text), PictureBox23)

    End Sub

    Private Sub LinkLabel52_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles RMC_import.LinkClicked

        Me.Visible = False
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = cbxTestsystem.Checked
        If cbxRMC._value = "" Then Exit Sub
        Dim f As New frmNachrichtenVerarbeitung_MDM_divers(cbxRMC._value, False, cbxDateienlöschenRMC.Checked, False)
        f.ShowDialog()
        Me.Visible = True
        setInvoiceBackToCustomer("RMC", False)
    End Sub

    Private Sub LinkLabel53_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles UTA_imports.LinkClicked
        Me.Visible = False
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = cbxTestsystem.Checked
        Dim f As New frmNachrichtenVerarbeitung_MDM_divers("UTA", False, cbxDateienlöschenUTA.Checked, False)
        f.year = txtUTAYear.Text
        f.UtaTestkunden = False
        f.ShowDialog()
        Me.Visible = True
        setInvoiceBackToCustomer("UTA", False)
    End Sub

    Private Sub LinkLabel54_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles MSE_Transaktions.LinkClicked
        Me.Visible = False
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = cbxTestsystem.Checked
        Dim mse As New cMSEAPI("MSE")
        Dim fehler As String = ""
        Dim token = mse.createJWT(fehler)
        Dim dt As New DataTable
        If fehler <> "" Then
            MsgBox(fehler)
        Else
            Dim totalPages = 0
            Dim batchrequestNr = 0
            Dim pages As String = ""
            Dim counTrans As Integer = 0
            Dim savedTrans As Integer = 0
            Dim MDMEinarb As New cMDMEinarbeitung("MSE", Now())
            MDMEinarb.setInvoicingDate(Now(), MDMEinarb)

            fehler = mse.getNewestTransactions(token, dt, batchrequestNr, totalPages, 0, cbxOnlyBilledTransactions.Checked, savedTrans)
            pages = "0"
            If fehler <> "" Then
                MsgBox(fehler)
                Me.Visible = True
                Exit Sub
            End If

            If totalPages > 1 Then

                For i = 2 To totalPages
                    If dt.Rows.Count > 0 Then dt.Clear()
                    fehler = mse.getTransactionsFromBatchNrAndPage(token, dt, batchrequestNr, totalPages, i, savedTrans)

                    If fehler <> "" Then
                        MsgBox(fehler)
                        Me.Visible = True
                        Exit Sub
                    End If

                    'i = i + 1 In a VB For loop, the loop automatically increases i by 1 each iteration.
                    pages &= " " & i
                Next



            End If

            MDMEinarb.ds_count += savedTrans
            MDMEinarb.ds_total += counTrans

            If MDMEinarb.ds_count = MDMEinarb.ds_total Then
                MDMEinarb.completed = True
                MDMEinarb.completed_date = Now()
            End If

            MDMEinarb.import_date = Now()
            MDMEinarb.SAVE()


        End If

        Me.Visible = True
    End Sub

    Private Sub MSE_RE_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles MSE_RE.LinkClicked

        Me.Visible = False
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = cbxTestsystem.Checked
        Dim mse As New cMSEAPI("MSE")
        Dim fehler As String = ""
        Dim token = mse.createJWT(fehler)
        Dim transactions As New DataTable
        Dim invoice As New DataTable

        If fehler <> "" Then
            MsgBox(fehler)
        Else
            fehler = mse.getInvoices(token, invoice, datVon.Value, datVon.Value, cbxUploadDA.Checked)
            If fehler <> "" Then
                MsgBox(fehler)
                Me.Visible = True
                Exit Sub
            End If

            If invoice IsNot Nothing And invoice.Columns.Contains("invoice_id") AndAlso invoice.Rows.Count > 0 Then

                Dim dvInvoice As New DataView(invoice)
                Dim distinctInv As DataTable = dvInvoice.ToTable(True, New String() {"invoice_id"})

                'Dim distinctInv As DataTable = (New SQL).loadDgvBySql("select distinct(invoice_id) FROM [VERAG].[dbo].[tblMSEInvoices] where  invoice_date = '2026-03-15' and invoice_id is not null ", "FMZOLL")


                For Each r As DataRow In distinctInv.Rows
                    Dim totalPages = 0
                    Dim batchrequestNr = 0
                    fehler = mse.getSettlementsFromInvoiceID(token, transactions, r("invoice_id"), batchrequestNr, totalPages, 0)
                    If fehler <> "" Then
                        MsgBox(fehler)
                        Exit Sub
                    End If
                    If totalPages > 1 Then

                        For i = 2 To totalPages
                            If transactions.Rows.Count > 0 Then transactions.Clear()
                            fehler = mse.getSettlementsFromBatchNrAndPage(token, transactions, batchrequestNr, totalPages, i)

                            If fehler <> "" Then
                                MsgBox(fehler)
                                Me.Visible = True
                                Exit Sub
                            End If
                        Next

                    End If
                Next

            End If


        End If

        Me.Visible = True

    End Sub

    Private Sub MSETransakt_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles MSETransakt.LinkClicked
        Me.Visible = False
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = cbxTestsystem.Checked
        Dim mse As New cMSEAPI("MSE")
        Dim fehler As String = ""
        Dim token = mse.createJWT(fehler)
        Dim transactions As New DataTable
        Dim invoice As New DataTable

        If fehler <> "" Then
            MsgBox(fehler)
        Else

            Dim totalPages = 0
            Dim batchrequestNr = 0

            fehler = mse.getTransactionsFromToDate(token, transactions, DateTimePicker1.Value, DateTimePicker2.Value, batchrequestNr, totalPages, 0)
            If fehler <> "" Then
                MsgBox(fehler)
                Me.Visible = True
                Exit Sub
            End If


            If totalPages > 1 Then

                For i = 2 To totalPages
                    If transactions.Rows.Count > 0 Then transactions.Clear()
                    fehler = mse.getTransactionsFromBatchNrAndPage(token, transactions, batchrequestNr, totalPages, i, 0)

                    If fehler <> "" Then
                        MsgBox(fehler)
                        Me.Visible = True
                        Exit Sub
                    End If
                Next



            End If

        End If

        Me.Visible = True
    End Sub

    Private Sub LinkLabel57_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel57.LinkClicked

        If txtBatchNr.Text <> "" Then
            If Not IsNumeric(txtBatchNr.Text) Then Exit Sub
            If CInt(txtBatchNr.Text) < 1 AndAlso CInt(txtBatchNr.Text) > 1000 Then Exit Sub
        End If

        If Not IsNumeric(cbxMSEBatchNr._value) Then Exit Sub
        If CInt(cbxMSEBatchNr._value) < 1 AndAlso CInt(cbxMSEBatchNr._value) > 1000 Then Exit Sub

        Me.Visible = False
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = cbxTestsystem.Checked
        Dim mse As New cMSEAPI("MSE")
        Dim fehler As String = ""
        Dim token = mse.createJWT(fehler)
        Dim transactions As New DataTable
        Dim invoice As New DataTable
        Dim pages As String = ""
        Dim counTrans As Integer = 0
        Dim savedTrans As Integer = 0
        Dim MDMEinarb As New cMDMEinarbeitung("MSE", Now())
        MDMEinarb.setInvoicingDate(Now(), MDMEinarb)

        If fehler <> "" Then
            MsgBox(fehler)
            Me.Visible = True
        Else

            Dim totalPages = 1
            Dim batchrequestNr As Integer

            If txtBatchNr.Text <> "" Then
                batchrequestNr = CInt(txtBatchNr.Text)
            Else
                batchrequestNr = CInt(cbxMSEBatchNr._value)
            End If


            fehler = mse.getTransactionsFromBatchNrAndPage(token, transactions, batchrequestNr, totalPages, 1, savedTrans)
            pages = "1"
            If fehler <> "" Then
                MsgBox(fehler)
                Me.Visible = True
                Exit Sub
            Else
                counTrans += transactions.Rows.Count


            End If


            If totalPages > 1 Then

                For i = 2 To totalPages
                    If transactions.Rows.Count > 0 Then transactions.Rows.Clear()
                    fehler = mse.getTransactionsFromBatchNrAndPage(token, transactions, batchrequestNr, totalPages, i, savedTrans)
                    If fehler <> "" Then
                        MsgBox(fehler)
                        Me.Visible = True
                        Exit Sub

                    Else
                        counTrans += transactions.Rows.Count
                        pages &= " " & i
                    End If
                Next

            End If

            MsgBox("DONE" & " Transactions: " & counTrans & " Pages: " & pages)

            MDMEinarb.ds_count += savedTrans
            MDMEinarb.ds_total += counTrans

            If MDMEinarb.ds_count = MDMEinarb.ds_total Then
                MDMEinarb.completed = True
                MDMEinarb.completed_date = Now()
            End If

            MDMEinarb.import_date = Now()
            If VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM Then
                MDMEinarb.SAVE()
            End If

        End If

        Me.Visible = True

    End Sub

    Private Sub MSE_Kunden_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles MSE_Kunden.LinkClicked
        Me.Visible = False
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = cbxTestsystem.Checked
        Dim mse As New cMSEAPI("MSE")
        Dim fehler As String = ""
        Dim token = mse.createJWT(fehler)
        Dim dt As New DataTable
        If fehler <> "" Then
            MsgBox(fehler)
        Else
            Dim totalPages = 0
            Dim batchrequestNr = 0

            fehler = mse.getCustomers(token, dt)

            If fehler <> "" Then
                MsgBox(fehler)
                Me.Visible = True
                Exit Sub
            End If


        End If


        Me.Visible = True
    End Sub

    Private Sub MSETransID_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles MSETransID.LinkClicked, MSE_missingTrans.LinkClicked, MSE_not_billed_Trans.LinkClicked


        If sender Is MSETransID Then
            If Not IsNumeric(txtTransactionID.Text) Then
                MsgBox("ID muss 10stellige Nr sein!")
                Me.Visible = True
                Exit Sub
            End If
            If CInt(txtTransactionID.Text) < 100000000 AndAlso CInt(txtTransactionID.Text) > 199999999 Then
                MsgBox("falsche ID")
                Me.Visible = True
                Exit Sub
            End If

        End If


        Me.Visible = False
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = cbxTestsystem.Checked
        Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
        Dim mse As New cMSEAPI("MSE")
        Dim fehler As String = ""
        Dim token = mse.createJWT(fehler)
        Dim transactions As New DataTable
        Dim invoice As New DataTable

        If fehler <> "" Then
            MsgBox(fehler)
            Me.Visible = True
        Else


            Dim dtTransactionID = New DataTable

            If sender Is MSETransID Then
                dtTransactionID.Columns.Add("transaction_id", GetType(String))
                dtTransactionID.Columns.Add("found", GetType(Boolean))
                dtTransactionID.Columns.Add("batch_seq_nr", GetType(Integer))
                Dim R As DataRow = dtTransactionID.NewRow
                R("transaction_id") = txtTransactionID.Text
                R("found") = True
                R("batch_seq_nr") = 0
                dtTransactionID.Rows.Add(R)

            ElseIf sender Is MSE_missingTrans Then

                dtTransactionID = SQL.loadDgvBySql("select [transaction_id], CAST(1 AS BIT) as found, 0 as batch_seq_nr  FROM [VERAG].[dbo].[tblMSESettlements] where [invoice_date] = '" & Date.Parse(datVon.Value).ToShortDateString & "' AND [transaction_id] not in (select [transaction_id] from [VERAG].[dbo].[tblMSETransactions])", "FMZOLL")
                If dtTransactionID.Rows.Count = 0 Then
                    MsgBox("Zu diesem Rechnungsdatum gibt es keine Rechnung!")
                    Me.Visible = True
                    Exit Sub
                End If

                If Not vbYes = MsgBox("Möchten Sie die " & dtTransactionID.Rows.Count & " fehlenden Transaktionen nachladen?" & vbNewLine & "Dieser Vorgang dauert je nach Anzahl der Transaktionen etwas.", vbYesNoCancel) Then
                    Me.Visible = True
                    Exit Sub
                End If

            ElseIf sender Is MSE_not_billed_Trans Then


                dtTransactionID = SQL.loadDgvBySql("select bills.[transaction_id], CAST(1 AS BIT) as found, trans.batch_seq_nr FROM [VERAG].[dbo].[tblMSESettlements] as bills 
                                                    inner  join [VERAG].[dbo].[tblMSETransactions] as trans on bills.[transaction_id] = trans.[transaction_id]  where trans.[transaction_status] <> 'Billed' and [invoice_date] = '" & datVon.Value & " '", "FMZOLL")
                If dtTransactionID.Rows.Count = 0 Then
                    MsgBox("Zu diesem Rechnungsdatum gibt es keine Rechnung!")
                    Me.Visible = True
                    Exit Sub
                End If

                If Not vbYes = MsgBox("Möchten Sie die " & dtTransactionID.Rows.Count & " Transaktionen aktualisieren?" & vbNewLine & "Dieser Vorgang dauert je nach Anzahl der Transaktionen etwas.", vbYesNoCancel) Then
                    Me.Visible = True
                    Exit Sub
                End If

            End If



            fehler = mse.getTransactionsFromTransactionID(token, transactions, dtTransactionID)
            If fehler <> "" Then
                MsgBox(fehler)
                Me.Visible = True
                Exit Sub
            Else

                If dtTransactionID.Rows.Count = 1 Then
                    txtBatchNrofTransaction.Text = dtTransactionID(0).Item("batch_seq_nr")
                End If

                Dim dv = New DataView(dtTransactionID)
                Dim dtMissingTransactions As New DataTable
                dv.RowFilter = "found = false"
                dtMissingTransactions = dv.ToTable

                If dtMissingTransactions.Rows.Count > 0 Then

                    Dim b = New System.Text.StringBuilder()
                    For Each resultRow In dtTransactionID.Rows
                        b.Append(resultRow(0) & vbNewLine)
                    Next

                    MsgBox(dtTransactionID.Rows.Count & " nicht gefundene Transaktionen:" & vbNewLine & b.ToString)
                    Me.Visible = True

                End If

            End If
        End If


        Me.Visible = True
    End Sub

    Private Sub LinkLabel60_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles MSE_Settlements.LinkClicked

        Me.Visible = False
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = cbxTestsystem.Checked
        Dim mse As New cMSEAPI("MSE")
        Dim fehler As String = ""
        Dim token = mse.createJWT(fehler)
        Dim dt As New DataTable
        If fehler <> "" Then
            MsgBox(fehler)
        Else
            Dim totalPages = 0
            Dim batchrequestNr = 0

            fehler = mse.getNewestSettlements(token, dt, batchrequestNr, totalPages, 1)

            If fehler <> "" Then
                MsgBox(fehler)
                Me.Visible = True
                Exit Sub
            End If


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

            'sollten sie dennoch gespeichert werden, dann fogenden Code aktivieren:

            '-------------START----------------------------------------------
            'If totalPages > 1 Then

            '    For i = 2 To totalPages
            '        If dt.Rows.Count > 0 Then dt.Clear()
            '        fehler = mse.getSettlementsFromBatchNrAndPage(token, dt, batchrequestNr, totalPages, i)

            '        If fehler <> "" Then
            '            MsgBox(fehler)
            '            Exit Sub
            '        End If

            '        'i = i + 1 In a VB For loop, the loop automatically increases i by 1 each iteration.
            '    Next



            'End If

            '-------------ENDE----------------------------------------------
        End If

        Me.Visible = True

    End Sub

    Private Sub Button23_Click(sender As Object, e As EventArgs) Handles Button23.Click, Button25.Click
        Dim ok = False
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = CheckBox8.Checked

        If txtKdNr.Text <> "" AndAlso IsNumeric(txtKdNr.Text) Then
            Dim ad As New cAdressen(txtKdNr.Text)
            If ad Is Nothing Then
                MsgBox("Diese KundenNr gibt es nicht!")
                showPic(ok, PictureBox25)
                Exit Sub
            End If

            If ad.Auswahl <> "A" Then
                MsgBox("Dieser Kunde ist inaktiv!")
                showPic(ok, PictureBox25)
                Exit Sub
            End If

            cMDMFunctionsAllgemein.setSchnittstellen(cbxPlose.Checked, cbxITalt.Checked, cbxMSEalt.Checked, cbxMSEneu.Checked, cbxIDSalt.Checked, cbxIDSneu.Checked, cbxUTAalt.Checked, cbxUTANeu.Checked, cbxPloseNeu.Checked)

            If sender Is Button23 Then

                If cMDMFunctionsAllgemein.Update_UStVASummenNeuBerechnen(ad.AdressenNr) Then
                    ok = cMDMFunctionsAllgemein.UStVAKunden_SummenNeuBerechnen(ad.AdressenNr)
                End If

            Else
                Dim dt As New DataTable
                cMDMFunctionsAllgemein.UStVAKunden_SummenNeuBerechnen(ad.AdressenNr, False, dt)
                If dt.Rows.Count = 1 Then
                    Dim rowData
                    'dt is the name of the data table
                    For Each row As DataRow In dt.Rows
                        For Each column As DataColumn In dt.Columns
                            rowData = rowData & column.ColumnName & “ ” & row(column) & vbNewLine
                        Next
                        rowData = rowData & vbNewLine & vbNewLine
                    Next
                    MessageBox.Show(rowData)

                End If
            End If
        Else
            'ansonsten alle Kunden
            If sender Is Button23 Then


                If cMDMFunctionsAllgemein.Update_UStVASummenNeuBerechnen_USTVA() Then
                    ok = cMDMFunctionsAllgemein.UStVAKunden_SummenNeuBerechnen()
                End If
            End If

        End If

        showPic(ok, PictureBox25)
    End Sub

    Private Sub LinkLabel64_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles UTA_Laender.LinkClicked, IDS_Laendercode.LinkClicked, Laender_Steuercode.LinkClicked

        Dim iso2Laneder = ""

        Select Case sender.Name
            Case "UTA_Laender" : iso2Laneder = "select distinct (Steuerliches_Lieferland) FROM [VERAG].[dbo].[tblUTAImportNew] where Lieferland_ISO2 is null" 'wichtig STEUERLAND!!!'
            Case "IDS_Laendercode" : iso2Laneder = "select distinct (LandNr) FROM [VERAG].[dbo].[tbl_IDS_Länder] where Lieferland_ISO2 is null"
            Case "Laender_Steuercode" : iso2Laneder = "select distinct (LandNr) FROM [VERAG].[dbo].[tblSteuernummern] where LandKZ is null"

        End Select

        Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
        Dim dtiso2Laneder As DataTable = SQL.loadDgvBySql(iso2Laneder, "FMZOLL")

        If dtiso2Laneder.Rows.Count > 0 Then
            For Each r As DataRow In dtiso2Laneder.Rows
                Select Case sender.Name
                    Case "UTA_Laender" : SQL.doSQL("Update [VERAG].[dbo].[tblUTAImportNew] set  Lieferland_ISO2 = '" & VERAG_PROG_ALLGEMEIN.cProgramFunctions.getISO2LandFromISO3Land(r.Item("Steuerliches_Lieferland")) & "' where Steuerliches_Lieferland = '" & r.Item("Steuerliches_Lieferland") & "'", "FMZOLL")
                    Case "IDS_Laendercode" : SQL.doSQL("Update [VERAG].[dbo].[tbl_IDS_Länder]  set  Lieferland_ISO2 = '" & VERAG_PROG_ALLGEMEIN.cProgramFunctions.getISO2LandFromLandNr(r.Item("LandNr")) & "' where LandNr = '" & r.Item("LandNr") & "'", "FMZOLL")
                    Case "Laender_Steuercode" : SQL.doSQL("Update [VERAG].[dbo].[tblSteuernummern] set  LandKZ = '" & VERAG_PROG_ALLGEMEIN.cProgramFunctions.getISO2LandFromLandNr(r.Item("LandNr")) & "' where LandNr = '" & r.Item("LandNr") & "'", "FMZOLL")
                End Select


            Next
            MsgBox("alle Länder gesetzt!")
        Else
            MsgBox("keine fehlenden Länder vorhanden!")
        End If

    End Sub



    Private Sub IDS_import_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles IDS_import.LinkClicked
        Me.Visible = False
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = cbxTestsystem.Checked
        Dim f As New frmNachrichtenVerarbeitung_MDM_divers("IDS", False, False, cbxIDSUmbenenen.Checked, True)
        f.year = txtIDSYear.Text
        f.ShowDialog()
        Me.Visible = True
    End Sub



    Private Sub ATCNRinRE_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles ATCNRinRE.LinkClicked

        Dim sql As New VERAG_PROG_ALLGEMEIN.SQL
        If txtMRNPrefix.Text = "" Then Exit Sub


        Dim dtRE = sql.loadDgvBySql_Param(" select RK_ID, Belegdaten, Weitere_Reg_Nr from RechnungsausgangPositionen where Belegdaten is not null and Left(Belegdaten ," & txtMRNPrefix.Text.Length & ") = '" & txtMRNPrefix.Text & "' and Weitere_Reg_Nr is null", "FMZOLL")


        If dtRE.Rows.Count > 0 Then
            Dim i As Integer = 0
            If vbYes = MsgBox("Möchten Sie bei " & dtRE.Rows.Count & " die alte MRN-Nr hinzufügen?" & vbNewLine & "(Daten werden nur erweitert, nicht überschrieben!!!)", vbYesNoCancel) Then


                For Each r In dtRE.Rows
                    Dim mrnAlt = sql.DLookup("Weitere_Reg_Nr", "[tbl_DY_Zollmeldungen_Import]", "[Weitere_Reg_Nr] is not null and [Registriernummer_MRN] = '" & r.Item("Belegdaten") & "'", "AVISO")
                    If mrnAlt IsNot Nothing AndAlso mrnAlt <> "" Then

                        If sql.doSQL("update RechnungsausgangPositionen set Weitere_Reg_Nr ='" & mrnAlt & "' where RK_ID= " & r.Item("RK_ID") & " AND  Belegdaten = '" & r.Item("Belegdaten") & "'", "FMZOLL") Then
                            i += 1
                        End If
                    End If

                Next
                MsgBox(i & " Rechnungspositionen wurden aktualisiert." & IIf((i < dtRE.Rows.Count), vbNewLine & " Zu den anderen " & dtRE.Rows.Count - i & " Rechnungspositionen konnte keine Verknüpfung gefunden werden!", ""))
            End If
        Else
            MsgBox("Keine Rechnungen mit MRN-Präfix" & txtMRNPrefix.Text)
        End If

    End Sub

    Private Sub LinkLabel68_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel68.LinkClicked
        Me.Cursor = Cursors.WaitCursor
        Try
            Dim erg = VERAG_PROG_ALLGEMEIN.cTariffKN8_Interface.UPDATE_KN8()
            showPic(erg, PictureBox26)
        Catch ex As Exception : VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name) : End Try
        Me.Cursor = Cursors.Default
    End Sub


    Private Sub Button26_Click(sender As Object, e As EventArgs) Handles Button26.Click
        VERAG_PROG_ALLGEMEIN.cATEZ_ncts_api.query_declarations(datTranscodeVon._value, datTranscodeBis._value, cbxOverrideNCTSFin.Checked)
    End Sub

    Private Sub Button27_Click(sender As Object, e As EventArgs) Handles btnTestATEZ.Click

        VERAG_PROG_ALLGEMEIN.cATEZ_ncts_api.updateStatusByMRN(txtCheckATEZMRN.Text)

    End Sub

    Private Sub IDS_RE_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles IDS_RE.LinkClicked

        Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL

nochmal:

        Select Case checkDatefromIDSInvioces("tblIDSInvoicesNew")
            Case 0 : Exit Sub
            Case 1 : GoTo nochmal
            Case 2 : GoTo weiter
        End Select



weiter:


        Dim fehlendeRechungsdaten As String = "select upper(Invoicenumber) as Invoicenumber, CustomerCode, cast(YearMonthDay as Date) as YearMonthDay FROM [VERAG].[dbo].[tblIDSInvoicesNew] where TransactionVolume is null and AmminclVAT is null and TotalNetAmount is null and VATAmount is null and Year(YearMonthDay) >= " & txtIDSYear.Text


        Dim dtRechnnungsdaten As DataTable = SQL.loadDgvBySql(fehlendeRechungsdaten, "FMZOLL")

        If dtRechnnungsdaten.Rows.Count > 0 Then
            For Each r As DataRow In dtRechnnungsdaten.Rows


                SQL.doSQL("
                  UPDATE 
                     inv
                SET 
                      inv.TransactionVolume = t.calcTrans,
                	  inv.AmminclVAT = t.calcInclvat,
                	  inv.TotalNetAmount = t.totalNet,
                	  inv.VATAmount = t.net
                FROM 
                     [VERAG].[dbo].[tblIDSInvoicesNew] AS inv
                INNER JOIN
                    (
                        SELECT 
                             Paymentsummarynumber,CustomerCode, YearMonthDay,
                             sum([TransactionVolume]) as calcTrans, sum([AmminclVAT]) as calcInclvat, sum([TotalNetAmount]) as totalNet, sum([VATAmount]) as net
                        
                		FROM [VERAG].[dbo].[tblIDSTransactionsNew] 
                        
                		WHERE 
                             Paymentsummarynumber = '" & r.Item("Invoicenumber") & "' and CustomerCode = '" & r.Item("CustomerCode") & "' and  YearMonthDay = '" & r.Item("YearMonthDay") & "' 
                        GROUP BY 
                             Paymentsummarynumber,CustomerCode, YearMonthDay
                    ) t
                ON 
                     t.Paymentsummarynumber = inv.Invoicenumber
                WHERE 
                     inv.Invoicenumber = '" & r.Item("Invoicenumber") & "' and inv.CustomerCode = '" & r.Item("CustomerCode") & "' and inv.YearMonthDay = '" & r.Item("YearMonthDay") & "' ", "FMZOLL")


            Next
            MsgBox("alle Daten in tblIDSInvoicesNew gesetzt!")
        Else
            MsgBox("keine fehlenden Daten in tblIDSInvoicesNew vorhanden!")
        End If



    End Sub

    Private Sub lblUTAPDFvollst_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles lblUTAPDFvollst.LinkClicked


        Dim fehlendeRechnungen As New DataTable
        Dim datumString = ""

        If txtUTADate.Text = "" AndAlso txtUTAYear.Text <> "" Then
            datumString = txtUTAYear.Text
            fehlendeRechnungen = (New SQL).loadDgvBySql(" SELECT A.AdressenNr, A.[Name 1], U.Abrechnungsnummer AS Abrechnungsnummer,U.Rechnungsnummer_pro_Lieferland,U.Lieferland,CAST(U.Rechnungsdatum AS date) AS Rechnungsdatum,A.LandKz FROM tblUTAImportNew U INNER JOIN Adressen A ON A.UTAKundenNr = U.Kundennummer WHERE U.daId IS NULL AND YEAR(U.Rechnungsdatum) = '" & datumString & "'  AND NOT (A.LandKz = 'RO' AND U.Lieferland = 'ROM') GROUP BY A.AdressenNr, A.[Name 1], U.Abrechnungsnummer,U.Rechnungsnummer_pro_Lieferland,U.Lieferland,U.Rechnungsdatum,A.LandKz", "FMZOLL")

        ElseIf txtUTADate.Text <> "" AndAlso IsDate(txtUTADate.Text) Then
            datumString = txtUTADate.Text
            fehlendeRechnungen = (New SQL).loadDgvBySql("SELECT A.AdressenNr, A.[Name 1], U.Abrechnungsnummer AS Abrechnungsnummer,U.Rechnungsnummer_pro_Lieferland,U.Lieferland,CAST(U.Rechnungsdatum AS date) AS Rechnungsdatum,A.LandKz FROM tblUTAImportNew U INNER JOIN Adressen A ON A.UTAKundenNr = U.Kundennummer WHERE U.daId IS NULL AND CAST(U.Rechnungsdatum AS date) = '" & datumString & "'  AND NOT (A.LandKz = 'RO' AND U.Lieferland = 'ROM') GROUP BY A.AdressenNr, A.[Name 1], U.Abrechnungsnummer,U.Rechnungsnummer_pro_Lieferland,U.Lieferland,U.Rechnungsdatum,A.LandKz", "FMZOLL")

        End If

        If fehlendeRechnungen.Rows.Count > 0 Then

            If vbYes = MsgBox("Details der " & fehlendeRechnungen.Rows.Count & " fehlenden Rechnungszuweisungen anzeigen?", vbYesNo) Then
                cProgramFunctions.genExcelFromDT_NEW(fehlendeRechnungen,,, "Fehlende PDFs zu Rechnungen: " & datumString)
            End If


            Dim hint As String = ""
            If fehlendeRechnungen.Rows.Count < 10 Then
                hint &= (New SQL).getValueTxtBySql("SELECT DISTINCT(U.Rechnungsnummer_pro_Lieferland) FROM tblUTAImportNew U INNER JOIN Adressen A ON A.UTAKundenNr = U.Kundennummer WHERE U.daId IS NULL AND CAST(U.Rechnungsdatum AS date) = '" & txtUTADate.Text & "'  AND NOT (A.LandKz = 'RO' AND U.Lieferland = 'ROM')", "FMZOLL")
            End If
            MsgBox("Es fehlen " & fehlendeRechnungen.Rows.Count & " PDF-Rechnungen in der Datenbank!" & vbNewLine & "Diese Dokumente (von Rechnung " & txtUTADate.Text & ") müssen nachgeladen werden (bitte an Administrator wenden)." & IIf(hint <> "", vbNewLine & "Bsp. Rechnungsnummer: " & hint, ""))

        Else
            MsgBox("Rechnungen vom " & txtUTADate.Text & " sind vollständig")
        End If

    End Sub

    Private Sub Button28_Click(sender As Object, e As EventArgs) Handles checkallopenATEZ.Click

        '        Dim dt = (New SQL).loadDgvBySql("SELECT TOP (1000) [ncts_Id]   FROM [tblNCTS_FREMD]  where ncts_Partnersystem='ATEZ' and ncts_status < 60", "FMZOLL")
        Dim top = 200
        If IsNumeric(MyTextBox06._value) AndAlso CInt(MyTextBox06._value) > 0 Then
            top = CInt(MyTextBox06._value)
        End If

        updateATEZStatusByMRNTop(top)
    End Sub

    Sub updateATEZStatusByMRNTop(top As Integer)
        Dim dt = (New SQL).loadDgvBySql("SELECT TOP (" & top & ") ncts_MRN  FROM  [tblNCTS_FREMD] where ncts_Status between 50 and 59 and ncts_Partnersystem='ATEZ'", "FMZOLL")
        If dt IsNot Nothing Then
            lblcheckopatez.Text = "-"
            Dim cnt = 1
            For Each r In dt.Rows
                lblcheckopatez.Text = cnt & "/" & dt.Rows.Count
                Me.Refresh()
                VERAG_PROG_ALLGEMEIN.cATEZ_ncts_api.updateStatusByMRN(r("ncts_MRN"))
            Next
            lblcheckopatez.Text = dt.Rows.Count & "fin"
        End If
    End Sub


    Private Sub PlosePdfRE_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles PlosePdfRE.LinkClicked
        If txtPloseJahr.Text.ToString.Length <> 4 Then MsgBox("Bitte Jahr eingeben!") : Exit Sub
        Dim kdNrPlose As Integer = -1
        If txtPLoseKdNr.Text <> "" AndAlso IsNumeric(txtPLoseKdNr.Text) Then kdNrPlose = txtPLoseKdNr.Text

        cPLOSE_Inv_Data.setDatenarchivID(txtPloseJahr.Text, True, kdNrPlose)

    End Sub

    Private Sub IDS_REDetails_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles IDS_REDetails.LinkClicked


nochmal:

        Select Case checkDatefromIDSInvioces("tblIDSInvoicesNewSplittedByCountry")
            Case 0 : Exit Sub
            Case 1 : GoTo nochmal
            Case 2 : GoTo weiter
        End Select
weiter:


        Dim fehlendeRechungsdatenOhneDVR As String = "select upper([Invoicenumber]) as Invoicenumber, CustomerCode, cast(YearMonthDay as Date) as YearMonthDay FROM [VERAG].[dbo].tblIDSInvoicesNewSplittedByCountry where TransactionVolume is null and AmminclVAT is null and TotalNetAmount is null and VATAmount is null and [Invoicenumber] not like 'DEVR%' and Year(YearMonthDay) >= " & txtIDSYear.Text
        Dim fehlendeRechungsdatenMitDVR As String = "select upper([Invoicenumber]) as Invoicenumber, CustomerCode, cast(YearMonthDay as Date) as YearMonthDay FROM [VERAG].[dbo].tblIDSInvoicesNewSplittedByCountry where TransactionVolume is null and AmminclVAT is null and TotalNetAmount is null and VATAmount is null and [Invoicenumber] like 'DEVR%' and Year(YearMonthDay) >= " & txtIDSYear.Text
        Dim fehlendeRechungsdatenTotalInvoiceID As String = "select CustomerCode, cast(YearMonthDay as Date) as YearMonthDay FROM [VERAG].[dbo].tblIDSInvoicesNewSplittedByCountry where TotalInvoiceId is null"

        Dim ok_OhneDVR As Boolean = False
        Dim ok_mitDVR As Boolean = False
        Dim ok_setInvoiceID As Boolean = False

        Dim rechnugdatum As String = ""

        Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
        Dim dtRechnnungsdatenOhneDVR As DataTable = SQL.loadDgvBySql(fehlendeRechungsdatenOhneDVR, "FMZOLL")

        Dim dtRechnnungsdatenMitDVR As DataTable = SQL.loadDgvBySql(fehlendeRechungsdatenMitDVR, "FMZOLL")

        Dim dtRechnnungsdatenTotalInvoiceID As DataTable = SQL.loadDgvBySql(fehlendeRechungsdatenTotalInvoiceID, "FMZOLL")

        If dtRechnnungsdatenOhneDVR.Rows.Count > 0 Then
            For Each r As DataRow In dtRechnnungsdatenOhneDVR.Rows


                SQL.doSQL("
                  UPDATE 
                     inv
                SET 
                      inv.TransactionVolume = t.calcTrans,
                	  inv.AmminclVAT = t.calcInclvat,
                	  inv.TotalNetAmount = t.totalNet,
                	  inv.VATAmount = t.net
                FROM 
                     [VERAG].[dbo].[tblIDSInvoicesNewSplittedByCountry] AS inv
                INNER JOIN
                    (
                        SELECT 
                             OBONumber,CustomerCode, YearMonthDay,
                             sum([TransactionVolume]) as calcTrans, sum([AmminclVAT]) as calcInclvat, sum([TotalNetAmount]) as totalNet, sum([VATAmount]) as net
                        
                		FROM [VERAG].[dbo].[tblIDSTransactionsNew] 
                        
                		WHERE 
                             Replace([OBONumber],'/','') = '" & r.Item("Invoicenumber") & "' and CustomerCode = '" & r.Item("CustomerCode") & "' and  YearMonthDay = '" & r.Item("YearMonthDay") & "' 
                        GROUP BY 
                             OBONumber,CustomerCode, YearMonthDay
                    ) t
                ON 
                     Replace(t.OBONumber,'/','') = inv.Invoicenumber
                WHERE 
                     inv.Invoicenumber = '" & r.Item("Invoicenumber") & "' and inv.CustomerCode = '" & r.Item("CustomerCode") & "' and inv.YearMonthDay = '" & r.Item("YearMonthDay") & "' ", "FMZOLL")


            Next
            MsgBox("alle Daten der tblIDSInvoicesNewSplittedByCountry Ohne DVR gesetzt!")
            ok_OhneDVR = True
        Else
            MsgBox("keine fehlenden Daten der tblIDSInvoicesNewSplittedByCountry Ohne DVR vorhanden!")
        End If


        If dtRechnnungsdatenMitDVR.Rows.Count > 0 Then
            For Each r As DataRow In dtRechnnungsdatenMitDVR.Rows


                SQL.doSQL("
                  UPDATE 
                     inv
                SET 
                      inv.TransactionVolume = t.calcTrans,
                	  inv.AmminclVAT = t.calcInclvat,
                	  inv.TotalNetAmount = t.totalNet,
                	  inv.VATAmount = t.net
                FROM 
                     [VERAG].[dbo].[tblIDSInvoicesNewSplittedByCountry] AS inv
                INNER JOIN
                    (
                        SELECT 
                             VRNumber,CustomerCode, YearMonthDay,
                             sum([TransactionVolume]) as calcTrans, sum([AmminclVAT]) as calcInclvat, sum([TotalNetAmount]) as totalNet, sum([VATAmount]) as net
                        
                		FROM [VERAG].[dbo].[tblIDSTransactionsNew] 
                        
                		WHERE 
                             VRNumber = '" & r.Item("Invoicenumber") & "' and CustomerCode = '" & r.Item("CustomerCode") & "' and  YearMonthDay = '" & r.Item("YearMonthDay") & "' 
                        GROUP BY 
                             VRNumber,CustomerCode, YearMonthDay
                    ) t
                ON 
                     VRNumber = inv.Invoicenumber
                WHERE 
                     inv.Invoicenumber = '" & r.Item("Invoicenumber") & "' and inv.CustomerCode = '" & r.Item("CustomerCode") & "' and inv.YearMonthDay = '" & r.Item("YearMonthDay") & "' ", "FMZOLL")


            Next
            ok_mitDVR = True
            MsgBox("alle Daten der tblIDSInvoicesNewSplittedByCountry mit DVR gesetzt!")
        Else
            MsgBox("keine fehlenden Daten der tblIDSInvoicesNewSplittedByCountry mit DVR vorhanden!")
        End If


        If dtRechnnungsdatenTotalInvoiceID.Rows.Count > 0 Then
            For Each r As DataRow In dtRechnnungsdatenTotalInvoiceID.Rows

                rechnugdatum = r.Item("YearMonthDay")

                SQL.doSQL("
                  UPDATE 
                     inv
                SET 
                      inv.TotalInvoiceId = t.invoice_id
                	  
                FROM 
                     [VERAG].[dbo].[tblIDSInvoicesNewSplittedByCountry] AS inv
                INNER JOIN
                    (
                     
                SELECT 

                             invoice_id
                        
                		FROM [VERAG].[dbo].[tblIDSInvoicesNew] 
                        
                		WHERE 
                             CustomerCode = '" & r.Item("CustomerCode") & "' and  YearMonthDay = '" & r.Item("YearMonthDay") & "' 
                        
                    ) t
                ON 
                     CustomerCode = inv.CustomerCode and YearMonthDay = inv.YearMonthDay
                WHERE 
                     inv.CustomerCode = '" & r.Item("CustomerCode") & "' and inv.YearMonthDay = '" & r.Item("YearMonthDay") & "' ", "FMZOLL")


            Next
            ok_setInvoiceID = True
            MsgBox("alle TotalInvoiceIDs gesetzt!")
        Else
            MsgBox("keine fehlenden TotalInvoiceIDs vorhanden!")
        End If

        If ok_mitDVR AndAlso ok_OhneDVR AndAlso ok_setInvoiceID AndAlso rechnugdatum <> "" Then
            SQL.doSQL("Update tblMDMEinarbeitung set nacharbeitung_completed = 1 where invoicedate = '" & rechnugdatum & "' and completed = 1", "FMZOLL")
            Dim empfaneger = cMitarbeiter.GetEMailRecipientForEmailNotification("IDS-Import", 19)
            VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(empfaneger, "IDS-Import", "IDS-Daten vom Rechnungslauf " & rechnugdatum & " wurden importiert! ", getAbsenderEmail())

        End If

    End Sub

    Private Sub UTAREPdf_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles UTAREPdf.LinkClicked


        Dim datumString = ""
        Dim SQLWhere As String = ""

        If txtUTADate.Text = "" AndAlso txtUTAYear.Text <> "" Then
            datumString = txtUTAYear.Text
            SQLWhere = "And YEAR(U.Rechnungsdatum) = '" & datumString & "'"
        ElseIf txtUTADate.Text <> "" AndAlso IsDate(txtUTADate.Text) Then
            datumString = txtUTADate.Text
            SQLWhere = "And CAST(U.Rechnungsdatum AS date) = '" & datumString & "'"
        End If



        Dim fehlendePDFzuRE As String = " SELECT U.Abrechnungsnummer AS Abrechnungsnummer,U.Kundennummer,U.Rechnungsnummer_pro_Lieferland,U.Lieferland,CAST(U.Rechnungsdatum AS date) AS Rechnungsdatum,A.LandKz FROM tblUTAImportNew U INNER JOIN Adressen A ON A.UTAKundenNr = U.Kundennummer WHERE U.daId IS NULL " & SQLWhere & "  AND NOT (A.LandKz = 'RO' AND U.Lieferland = 'ROM')  GROUP BY U.Abrechnungsnummer,U.Kundennummer,U.Rechnungsnummer_pro_Lieferland,U.Lieferland,U.Rechnungsdatum,A.LandKz  "

        Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
        Dim dtRechnnungsdaten As DataTable = SQL.loadDgvBySql(fehlendePDFzuRE, "FMZOLL")


        Dim counter As Integer = 0
        If dtRechnnungsdaten.Rows.Count > 0 Then

            For Each r As DataRow In dtRechnnungsdaten.Rows


                Dim utaYear As Integer = CDate(r.Item("Rechnungsdatum")).Year
                Dim utaDate As Date = CDate(r.Item("Rechnungsdatum"))
                If utaDate.Month = 12 And utaDate.Day = 31 Then
                    utaYear += 1 'bei 31.12 bekommen wir die Daten erst im nächsten Jahr!
                End If


                Dim daId As Integer = 0
                daId = CInt(SQL.getValueTxtBySql("Select top(1) isnull(da_id,0) FROM tblDatenarchiv WHERE da_KundenNr = 0  And da_kategorie = 'MDM' AND da_ordner='MDM_DATEN' AND da_uOrdner1= 'UTA' AND da_uOrdner2= '" & utaYear & "'  AND da_name like '%ZUGFERD.pdf' AND da_name like '%" & r.Item("Kundennummer") & "_" & r.Item("Abrechnungsnummer") & "_" & r.Item("Rechnungsnummer_pro_Lieferland") & "%'", "FMZOLL",,, 0))
                If daId > 0 Then
                    Dim DS As New VERAG_PROG_ALLGEMEIN.cDATENSERVER(daId)
                    Dim Path As String = DS.GET_TOP1_PATH()
                    If Path <> "" And System.IO.File.Exists(Path) Then
                        SQL.doSQL("Update [tblUTAImportNew] SET [daId]='" & DS.da_id & "', daIdgesetztDatum = getdate()  where [Rechnungsnummer_pro_Lieferland] = '" & r.Item("Rechnungsnummer_pro_Lieferland") & "' AND cast(Rechnungsdatum as Date) = '" & utaDate & "' AND Kundennummer =" & r.Item("Kundennummer") & " and Abrechnungsnummer =" & r.Item("Abrechnungsnummer") & "  and daId is null", "FMZOLL")
                        counter += 1
                    End If
                End If


            Next

            MsgBox(counter & " von " & dtRechnnungsdaten.Rows.Count & " Rechnungsdaten gesetzt!")

        End If


    End Sub
    Private Sub KN8_DESTAT_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles KN8_DESTAT.LinkClicked
        Me.Cursor = Cursors.WaitCursor
        Try
            Dim erg = VERAG_PROG_ALLGEMEIN.cTariffKN8_Interface.UPDATE_KN8_DESTAT()
            showPic(erg, PictureBox26)
        Catch ex As Exception : VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name) : End Try
        Me.Cursor = Cursors.Default

    End Sub

    'Private Sub Button27_Click_1(sender As Object, e As EventArgs) Handles Button27.Click
    '    cErrorHandler.sendERRORperMail(My.Application.Info.AssemblyName, "TEST", "", "error@verag.ag", "", "Error_Test")
    'End Sub

    Private Sub LinkLabel52_LinkClicked_1(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel52.LinkClicked

        If txtPloseJahr.Text.ToString.Length <> 4 Then MsgBox("Bitte Jahr eingeben!") : Exit Sub
        Dim kdNrPlose As Integer = -1
        If txtPLoseKdNr.Text <> "" AndAlso IsNumeric(txtPLoseKdNr.Text) Then kdNrPlose = txtPLoseKdNr.Text

        cPLOSE_Inv_Data.setWahrunginIvoiceFromTransactions(txtPloseJahr.Text, True, kdNrPlose)

    End Sub


    Private Function checkDatefromIDSInvioces(table As String) As Integer



        Dim sql As New SQL

        Dim fehlendeRechungsdatenDatum As String = "select distinct(cast(YearMonthDay as Date)) as YearMonthDay FROM [VERAG].[dbo].[" & table & "] where TransactionVolume is null and AmminclVAT is null and TotalNetAmount is null and VATAmount is null and Year(YearMonthDay) >= " & txtIDSYear.Text

        Dim dtRechnnungsdatenfalschesDatum As DataTable = sql.loadDgvBySql(fehlendeRechungsdatenDatum, "FMZOLL")

        For Each row As DataRow In dtRechnnungsdatenfalschesDatum.Rows

            If Not IsDBNull(row.Item("YearMonthDay")) AndAlso row.Item("YearMonthDay") IsNot Nothing AndAlso IsDate(row.Item("YearMonthDay")) Then

                Dim abrDate As Date = row.Item("YearMonthDay")

                If Not (abrDate.Day = 15 Or abrDate.Day = 30 Or abrDate.Day = 31 Or (abrDate.Month = 2 And abrDate.Day = 28)) Then

                    If Not vbYes = MsgBox("Die IDS-Rechnungen besitzen das Datum: " & abrDate.ToShortDateString & "!" & vbNewLine & "Soll das Datum geändert werden (im nächsten Schritt).", vbYesNoCancel) Then
                        Return 0
                    Else
                        Dim f As New frmDatumsabfrage("IDS-falsches Rechnungsdatum: " & abrDate.ToShortDateString, True)
                        f.ShowDialog()
                        If f.DialogResult = DialogResult.OK Then
                            If sql.doSQL("Update [" & table & "] set YearMonthDay = '" & f.Datum.ToShortDateString & "' where cast(YearMonthDay as Date) = '" & abrDate.ToShortDateString & "'", "FMZOLL") Then
                                Return 1
                            Else
                                Return 0
                            End If
                        Else
                            Return 0
                        End If
                    End If

                End If

            End If
        Next

        Return 2




    End Function

    Private Sub IDSUpdateDAID_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles IDSUpdateDAID.LinkClicked

        Dim sql As New SQL

        Dim IDSdaidaktualiseren As String = "select * from tblUStVPositionen where UStVPo_SchnittstellenNr = 8 and Year(UStVPo_ReDat) >= " & txtIDSYear.Text

        Dim dtUSTVA_daid_akt As DataTable = sql.loadDgvBySql(IDSdaidaktualiseren, "FMZOLL")

        Dim counter As Integer = 0

        If dtUSTVA_daid_akt.Rows.Count > 0 Then
            For Each row As DataRow In dtUSTVA_daid_akt.Rows

                Dim ustva As New cUSTVAntrag(row.Item("UStVAn_ID"))

                If ustva.UStVAn_LandNr IsNot Nothing AndAlso IsNumeric(ustva.UStVAn_LandNr) Then

                    Dim Antrag_LandKz = sql.DLookup("LandKz", "[Länderverzeichnis für die Außenhandelsstatistik]", "Landnr='" & ustva.UStVAn_LandNr & "'", "FMZOLL")

                    Dim daId As Integer = 0

                    Dim SQL_String = "SELECT isnull(tblIDSInvoicesNewSplittedByCountry.daId ,0)  FROM [tblIDSInvoicesNewSplittedByCountry]  where tblIDSInvoicesNewSplittedByCountry.[YearMonthDay] ='" & CDate(row.Item("UStVPo_ReDat")).ToShortDateString & "' AND tblIDSInvoicesNewSplittedByCountry.Invoicenumber ='" & row.Item("UStVPo_ReNr").ToString.Replace("/", "") & "' and tblIDSInvoicesNewSplittedByCountry.Country='" & Antrag_LandKz & "' AND tblIDSInvoicesNewSplittedByCountry.daId is not null"

                    daId = CInt(sql.getValueTxtBySql(SQL_String, "FMZOLL",,, 0))

                    If daId > 0 Then
                        sql.doSQL("update tblUStVPositionen set UStVPo_daId = " & daId & ", UStVPo_SchnittstellenNr = 12  where UStVAn_ID = " & row.Item("UStVAn_ID") & " and UStVPo_ID = " & row.Item("UStVPo_ID") & " AND UStVPo_SchnittstellenNr = 8", "FMZOLL")
                        counter += 1
                    End If

                End If

            Next

            MsgBox(counter & " von " & dtUSTVA_daid_akt.Rows.Count & " IDS-USTVA-Daten auf neue SchnistellenNr 12 gesetzt!")

        End If

    End Sub

    Private Sub LinkLabel53_LinkClicked_1(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles IDS_PDFmitREverkn.LinkClicked

        Dim fehlendePDFzuRE As String = "select *  FROM tblIDSInvoicesNewSplittedByCountry where daId is null "

        Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
        Dim dtRechnnungsdaten As DataTable = SQL.loadDgvBySql(fehlendePDFzuRE, "FMZOLL")

        If dtRechnnungsdaten.Rows.Count > 0 Then

            Dim counter As Integer = 0

            For Each r As DataRow In dtRechnnungsdaten.Rows

                Dim dateiname As String = r.Item("DocumentName")
                Dim invoicenumber As String = r.Item("Invoicenumber")
                Dim invoicenumber2 As String = ""

                If invoicenumber.Contains("DE") Then
                    invoicenumber2 = invoicenumber.Replace("DE", "-DE")
                ElseIf invoicenumber.Contains("PL") Then
                    invoicenumber2 = invoicenumber.Replace("PL", "-PL")
                ElseIf invoicenumber.Contains("SP") Then
                    invoicenumber2 = invoicenumber.Replace("SP", "-SP")
                ElseIf invoicenumber.Contains("RO") Then
                    invoicenumber2 = invoicenumber.Replace("RO", "-RO")
                ElseIf invoicenumber.Contains("DA") Then
                    invoicenumber2 = invoicenumber.Replace("DA", "-DA")
                ElseIf invoicenumber.Contains("FT") Then
                    invoicenumber2 = invoicenumber.Replace("FT", "FT-")
                    invoicenumber2 = invoicenumber2.Replace("I10", "I10-")
                ElseIf invoicenumber.Contains("GE") Then
                    invoicenumber2 = invoicenumber.Replace("GE", "-GE")
                End If

                Dim daId As Integer = 0
                daId = CInt(SQL.getValueTxtBySql("Select top(1) isnull(da_id,0) FROM tblDatenarchiv WHERE da_KundenNr = 0  And da_kategorie = 'MDM' AND da_ordner='MDM_DATEN' AND da_uOrdner1= 'IDS_COUNTRY' AND da_uOrdner2= '" & Now.Year & "' AND da_name like '%" & r.Item("CustomerCode") & "%'" & IIf(invoicenumber2 <> "", "AND da_name like '%" & invoicenumber2 & "%'", " AND da_name like '%" & r.Item("Invoicenumber") & "%'"), "FMZOLL",,, 0))
                If daId > 0 Then
                    Dim DS As New VERAG_PROG_ALLGEMEIN.cDATENSERVER(daId)
                    Dim Path As String = DS.GET_TOP1_PATH()
                    If Path <> "" And System.IO.File.Exists(Path) Then
                        SQL.doSQL("Update [tblIDSInvoicesNewSplittedByCountry] SET [daId]='" & DS.da_id & "' where [DocumentName] = '" & dateiname.ToString & "'  ", "FMZOLL")

                    End If
                End If


            Next

            MsgBox(counter & " von " & dtRechnnungsdaten.Rows.Count & " IDS- Rechnungsdaten gesetzt!")

        End If


    End Sub

    Private Sub Button29_Click(sender As Object, e As EventArgs) Handles cboTCAPI_Files.Click
        Dim TELO As New VERAG_PROG_ALLGEMEIN.cTelotecAPI
        Dim ZOLLIMPORT As New DAKOSY_Worker.cZOLL_IMPORT

        Dim messages As New List(Of TAMessage)()

        Using ofd As New OpenFileDialog()
            ofd.Title = "Wähle eine oder mehrere JSON-Dateien mit TA-Nachrichten"
            ofd.InitialDirectory = "\\datenarchiv\Datenarchiv\TELOTEC\ECHTSYSTEM\Nachrichtendaten_Ablage_JSON\"
            ofd.Filter = "JSON-Dateien (*.json)|*.json|Alle Dateien (*.*)|*.*"
            ofd.Multiselect = True

            If ofd.ShowDialog() = DialogResult.OK AndAlso ofd.FileNames IsNot Nothing AndAlso ofd.FileNames.Length > 0 Then
                For Each selectedPath In ofd.FileNames
                    ' Optional: kurze Info
                    Console.WriteLine($"📄 Verarbeite: {selectedPath}")

                    messages = TELO.ParseTAMessagesFromFile(selectedPath, cbxTCAnhEinlesen.Checked)

                    For Each msg In messages
                        Dim TELO_ANM = TELOTEC_Worker.cTelotec_Anmeldung.ConvertTAMessageToTelotec(msg)
                        If TELO_ANM.SAVE() Then
                            TELO_ANM.SAVE_ME_AKTUELLSTE_NACHRICHT()

                            ' SpedBuch
                            ZOLLIMPORT.TelotecImport(TELO_ANM)

                            ' Anhang
                            If cbxTCAnhEinlesen.Checked Then
                                SAVE_PDF(TELO_ANM, msg, cbxTCVB_Versand.Checked)
                            End If
                        End If
                    Next
                Next
            Else
                Console.WriteLine("🔕 Keine Datei ausgewählt.")
            End If
        End Using


        'Dim TELO As New VERAG_PROG_ALLGEMEIN.cTelotecAPI
        'Dim ZOLLIMPORT As New DAKOSY_Worker.cZOLL_IMPORT

        'Dim messages As New List(Of TAMessage)()

        'Using ofd As New OpenFileDialog()
        '    ofd.Title = "Wähle eine JSON-Datei mit TA-Nachrichten"
        '    ofd.InitialDirectory = "\\datenarchiv\Datenarchiv\TELOTEC\ECHTSYSTEM\Nachrichtendaten_Ablage_JSON\"
        '    ofd.Filter = "JSON-Dateien (*.json)|*.json|Alle Dateien (*.*)|*.*"

        '    If ofd.ShowDialog() = DialogResult.OK Then
        '        Dim selectedPath As String = ofd.FileName
        '        messages = TELO.ParseTAMessagesFromFile(selectedPath, cbxTCAnhEinlesen.Checked)



        '        For Each msg In messages
        '            Dim TELO_ANM = TELOTEC_Worker.cTelotec_Anmeldung.ConvertTAMessageToTelotec(msg)
        '            If TELO_ANM.SAVE() Then
        '                TELO_ANM.SAVE_ME_AKTUELLSTE_NACHRICHT()
        '                ' OK  
        '                'SpedBuch
        '                ZOLLIMPORT.TelotecImport(TELO_ANM)
        '                'ZOLLIMPORT.insertAbgabenTELOTEC(TC)

        '                'Anhang
        '                If cbxTCAnhEinlesen.Checked Then SAVE_PDF(TELO_ANM, msg, cbxTCVB_Versand.Checked)

        '            End If
        '        Next
        '    Else
        '        Console.WriteLine("🔕 Keine Datei ausgewählt.")
        '    End If
        'End Using

    End Sub

    Private Sub Button27_Click_1(sender As Object, e As EventArgs) Handles cboTCAPI_Call.Click

        Select Case cboTCAPI_Firma.Text
            Case "ALLE"
                doTelotecAPIMulit_ALL()

                'cTelotecAPI.GET_ALL_TELO_Messages() -> ohne Konvertierung zu cTelotec_Anmeldung, nur abholen

            Case Else
                doTelotecAPIMulit(cboTCAPI_Firma.Text)
        End Select


    End Sub
    Sub doTelotecAPIMulit_ALL()
        doTelotecAPIMulit("ATILLA")
        doTelotecAPIMulit("IMEX")
        doTelotecAPIMulit("DURMAZ")
    End Sub
    Sub doTelotecAPIMulit(Firma)
        Dim TELO As New VERAG_PROG_ALLGEMEIN.cTelotecAPI

        Dim ZOLLIMPORT As New DAKOSY_Worker.cZOLL_IMPORT

        For ii As Integer = 0 To 50
            Dim messages As List(Of VERAG_PROG_ALLGEMEIN.cTelotecAPI.TAMessage) = TELO.GetTAMessages(Firma, True)
            'Threading.Thread.Sleep(100) '
            'convert
            For Each msg In messages

                Dim TELO_ANM = TELOTEC_Worker.cTelotec_Anmeldung.ConvertTAMessageToTelotec(msg)
                If TELO_ANM.SAVE() Then
                    TELO_ANM.SAVE_ME_AKTUELLSTE_NACHRICHT()
                    ' OK  
                    'SpedBuch
                    ZOLLIMPORT.TelotecImport(TELO_ANM)
                    'ZOLLIMPORT.insertAbgabenTELOTEC(TC)
                    'Anhang
                    SAVE_PDF(TELO_ANM, msg, True)
                End If
            Next
        Next
    End Sub

    Public Function SAVE_PDF(TELO_ANM As TELOTEC_Worker.cTelotec_Anmeldung, msg As VERAG_PROG_ALLGEMEIN.cTelotecAPI.TAMessage, ZB_Versand As Boolean) As Boolean
        'Case "TR109" 'VBD
        If TELO_ANM.telanm_id >= 0 Then
            With msg
                If .declarationContent IsNot Nothing Then
                    Dim decl = .declarationContent

                    If decl.filePath <> "" Then

                        Dim frmStartOptions As New frmStartOptions
                        Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL

                        Dim DS = New VERAG_PROG_ALLGEMEIN.cDATENSERVER("ZOLLDATEN", "VBD", TELO_ANM.telanm_id, "", "", TELO_ANM.Refs_LRN.ToString.Replace("/", "-").Replace(",", "-").Replace("\", "-").Replace(":", "."), 0, False)
                        DS.da_vorlage = False

                        Dim ZIEL_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "TELOTEC\ECHTSYSTEM\ZOLLDATEN\VBD\NOT_IDENTIFIED\"
                        If IsNumeric(TELO_ANM.telanm_id) AndAlso TELO_ANM.telanm_id > 0 Then ZIEL_PFAD = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "TELOTEC\ECHTSYSTEM\ZOLLDATEN\VBD\" & Now.Year & "\" & Now.ToString("yyyyMMdd") & "\"
                        If Not System.IO.Directory.Exists(ZIEL_PFAD) Then System.IO.Directory.CreateDirectory(ZIEL_PFAD)

                        Dim destFull = ""
                        frmStartOptions.moveFile(msg.declarationContent.filePath, ZIEL_PFAD, destFull)

                        If DS.insertDataToDATENSERVER(destFull) Then
                            If IsNumeric(TELO_ANM.telanm_id) AndAlso TELO_ANM.telanm_id > 0 Then
                                SQL.doSQL("UPDATE [tblTelotec_Anmeldung] SET [telanm_VBD_dsId]='" & DS.da_id & "' where telanm_CRN='" & TELO_ANM.Refs_CRN & "'", "FMZOLL")
                                SQL.doSQL("UPDATE Speditionsbuch SET DokumentId_VBD='" & DS.da_id & "' where AtlasBezNrNCTS='" & TELO_ANM.Refs_LRN.ToString.Trim & "' AND DokumentId_VBD is null", "FMZOLL") 'Falls Spedbuch schon zuvor generiert wurde!
                                If ZB_Versand Then
                                    If DateDiff(DateInterval.Hour, TELO_ANM.dec_CreateDate, Now) < 24 Then frmStartOptions.doMailZollbelegTC(DS.GET_TOP1_PATH, "VBD", TELO_ANM)
                                End If
                            End If
                        End If
                    End If

                End If
            End With
        End If

    End Function

    Private Sub btnTesttc_Click(sender As Object, e As EventArgs) Handles btnTesttc.Click
        Dim TELO As New VERAG_PROG_ALLGEMEIN.cTelotecAPI
        Dim ZOLLIMPORT As New DAKOSY_Worker.cZOLL_IMPORT

        Dim messages As New List(Of TAMessage)()

        Using ofd As New OpenFileDialog()
            ofd.Title = "Wähle eine oder mehrere JSON-Dateien mit TA-Nachrichten"
            ofd.InitialDirectory = "\\datenarchiv\Datenarchiv\TELOTEC\ECHTSYSTEM\Nachrichtendaten_Ablage_JSON\"
            ofd.Filter = "JSON-Dateien (*.json)|*.json|Alle Dateien (*.*)|*.*"
            ofd.Multiselect = True

            If ofd.ShowDialog() = DialogResult.OK AndAlso ofd.FileNames IsNot Nothing AndAlso ofd.FileNames.Length > 0 Then
                For Each selectedPath In ofd.FileNames
                    ' Optional: kurze Info
                    Console.WriteLine($"📄 Verarbeite: {selectedPath}")

                    messages = TELO.ParseTAMessagesFromFile(selectedPath, False)

                    For Each msg In messages
                        Dim TELO_ANM = TELOTEC_Worker.cTelotec_Anmeldung.ConvertTAMessageToTelotec(msg)
                        'TELOTEC_Worker.cTelotec_Anmeldung.Update_Anmeldedatum(TELO_ANM.Refs_LRN, TELO_ANM.dec_CreateDate)
                        If TELO_ANM.telanm_Status = 60 Then
                            TELOTEC_Worker.cTelotec_Anmeldung.Update_Status_LRN(TELO_ANM.Refs_LRN, TELO_ANM.telanm_Status)
                        End If


                        'UPDATE_Status

                    Next
                Next
            Else
                Console.WriteLine("🔕 Keine Datei ausgewählt.")
            End If
        End Using
    End Sub

    Private Sub Button27_Click_2(sender As Object, e As EventArgs) Handles Button27.Click
        If txtWartungFaelligkeitAbDat._value <> "" Then
            cAuditFlow.ErzeugeFaelligePruefungen(txtWartungFaelligkeitAbDat._value)
        End If


    End Sub

    Private Sub btnCreditsaveLauf_Click(sender As Object, e As EventArgs) Handles btnCreditsaveLauf.Click

        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = cbxTestsystemCS.Checked

        'Existing companies in the portfolio will be skipped, and only new unique entries will be added.

        UploadCompaniesToCreditsafe(cbxCSsync.Checked)

    End Sub

    Private Sub countmissingCSinPortfolio(ByRef count As Integer)

        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = cbxTestsystemCS.Checked

        Dim countMissing As Integer = 0
        Dim countUploaeded As Integer = 0
        Dim sql As New SQL

        lblCSPortfolio.Text = "im Portfolio:"
        lblMissingCS.Text = "hochzuladende Unternehmen in CS: "

        Dim sqlCountNotUploaded As String = sql.getValueTxtBySql("select count(distinct(kde_CreditSaveNo)) from tblKundenErweitert where isnull(tblKundenErweitert.kde_CreditSaveId,'') <> '' and kde_CreditSaveId <> 'True' and kde_CreditSaveId <>'False' and isnull(kde_CreditSaveNo,'') <> '' and kde_CSPortfolioAdded = 0", "FMZOLL")

        Dim sqlCountUploaded As String = sql.getValueTxtBySql("select count(distinct(kde_CreditSaveNo)) from tblKundenErweitert where isnull(tblKundenErweitert.kde_CreditSaveId,'') <> '' and kde_CreditSaveId <> 'True' and kde_CreditSaveId <>'False' and isnull(kde_CreditSaveNo,'') <> '' and kde_CSPortfolioAdded = 1", "FMZOLL")

        If sqlCountNotUploaded <> "" AndAlso IsNumeric(sqlCountNotUploaded) Then countMissing = CInt(sqlCountNotUploaded)

        If sqlCountUploaded <> "" AndAlso IsNumeric(sqlCountUploaded) Then countUploaeded = CInt(sqlCountUploaded)

        lblCS_DB.Text = " VON " & sqlCountUploaded

        lblMissingCS.Text &= countMissing

        Dim cs = New cCreditSafeAPI("creditsafe")

        If cs.authenticate() = "200" Then

            Dim portOnline As Integer

            cs.GetCompaniesFromPortfolio(portOnline)

            count = portOnline

        End If


    End Sub

    Private Sub Button28_Click_1(sender As Object, e As EventArgs) Handles Button28.Click

        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = cbxTestsystemCS.Checked

        Dim datumString = ""

        If cbCheckDate.Checked Then

            If txtCSDate.Text <> "" AndAlso IsDate(txtCSDate.Text) Then
                datumString = txtCSDate.Text
            Else
                MsgBox("Datum hat falsches Format!" & vbNewLine & "Vorgang wird abgebrochen!")
                Exit Sub
            End If

        Else
            datumString = Today.ToShortDateString

        End If


        importCreditsafeEvents(datumString, cbCheckDate.Checked, bcxKundendatenaktCS.Checked, cbxKundenbesonderheitenCS.Checked, cbxMailsenden.Checked, Not cbxEventtriggered.Checked)


    End Sub

    Private Sub importCreditsafeEvents(datum As String, checkDate As Boolean, upateKunden As Boolean, setzeKundenbesonderheiten As Boolean, sendMail As Boolean, companyDetailEventsRequest As Boolean)


        '-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
        '-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

        'WICHTIG, bei companyDetailEventsRequest = true wird gleich Punkt 3 durchgeführt (dauert länger, aber mehr Datensätze und alle Kunden werden geprüft, bei companyDetailEventsRequest = false wird die u.a. Best Practice-Methode durchgeführt (Punkt 1 und 2) -> also triggerbasierend)!!!!
        'ANSATZ, bei der täglichen Prüfung die triggerbasierten Abruf, 1x im Monat bzw. wenn spezisches Unternehmen geprüft wird, dann Punkt 3.

        '-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
        'Best Practices for Viewing Notification Events

        '1. Use Portfolio-Specific Events for Targeted Monitoring: Start with the portfolio-specific endpoint to focus on changes relevant to a particular portfolio.
        '2. Leverage Global Events for a Broader View: Use the all-events endpoint to gain a comprehensive overview of all notifications across your portfolios.
        '3. Drill Down to Company-Level Events WHEN NEEDED: For detailed insights into a specific company, use the company-specific endpoint.

        '-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
        '-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
        '-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

        'Dim creditsaveOld As String = "
        '                        select ba_KundenNr FROM tblBonitaetsauskunft  WHERE ba_Pruefungstool = 'creditsafe API'

        '                        EXCEPT

        '                        SELECT * FROM ( SELECT  ba_KundenNr
        '                                        FROM tblBonitaetsauskunft  
        '                                        WHERE ba_Pruefungstool = 'creditsafe API' and cast(ba_Datum as Date) >= '" & datum & "'

        '                        UNION ALL 

        '                        SELECT e.KundenNr
        '                                        FROM (
        '                                               SELECT e.KundenNr,
        '                        								e.eventDate,
        '                                                     'creditsafe API' AS Source
        '                                                          FROM [VERAG].[dbo].[tblCreditsafeEvents] e
        '                                                                    INNER JOIN [VERAG].[dbo].[tblBonitaetsauskunft] b 
        '                                                                        ON e.bonId = b.ba_id
        '                                                                    WHERE  b.ba_Pruefungstool = 'creditsafe API'
        '                                                                      AND (e.localEventCode IN ('CL','CR') OR e.globalEventCode IN ('CL','CR'))
        '                                                                ) e
        '                        										WHERE cast(e.eventDate as Date) >= '" & datum & "'
        '                                                                GROUP BY Source, e.KundenNr, cast(e.eventDate as Date)
        '                                                            ) AS Temp"





        Dim creditsave As String = "select distinct(ba_KundenNr),f.Firma from Kunden 
									inner join tblKundenErweitert on Kunden.KundenNr = kde_KundenNr
                                    inner join Filialen as  f on f.FilialenNr = Kunden.FilialenNr
                                    inner join tblBonitaetsauskunft on ba_KundenNr = kde_KundenNr
									 where  isnull(tblKundenErweitert.kde_CreditSaveId,'') <> '' and kde_CreditSaveId <> 'True' and kde_CreditSaveId <>'False' and isnull(kde_CreditSaveNo,'') <> '' and kde_CSPortfolioAdded = 1 AND ba_Pruefungstool = 'creditsafe API'" & IIf(datum <> "", " AND Kunden.Bonitätsdatum <= '" & datum & "' ", "")

        If VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM Then
            creditsave &= " AND ba_Kundennr in (701809, 1096780)"
        End If

        Dim cs = New cCreditSafeAPI("creditsafe")

        Dim Mailinfolast1Year As Boolean = False

        If cs.authenticate() = "200" Then

            If Not companyDetailEventsRequest Then

                Dim API_Start_Daily = VERAG_PROG_ALLGEMEIN.cAPI.INSERT_API(VERAG_PROG_ALLGEMEIN.cAPI_INOUT.IN, VERAG_PROG_ALLGEMEIN.cAPI_Type.REST, VERAG_PROG_ALLGEMEIN.cAPI_ART.AVISO_IN_CS, "DAILY-CREDITSAFE-EVENTS-IMPORT", "CS")

                Dim dtMonitoredRequest As New DataTable

                Dim companyDummy As New cCreditSafeAPI.Company("", "", "", "", "", "", Nothing, "", "", "", "", "", "", "", "", "", 0)
                If datum <> "" AndAlso IsDate(datum) Then
                    companyDummy.lastChecked = CDate(datum)
                End If
repeatRequestDaily:
                Dim page As Integer = 0
                Dim totalPages As Integer = -1

                Dim APIText = cs.getCompanyEvents(companyDummy, dtMonitoredRequest, False, totalPages, checkDate, upateKunden, False,, setzeKundenbesonderheiten, True,, page)
                If (APIText.Contains("Error") Or APIText.Contains("Verbindungsfehler")) Then API_Start_Daily.UPDTAE_ERR("ERROR", APIText, "dailyImportCreditsafeEvents")

                If APIText.Contains("Invalid token") Then
                    If Not cs.authenticate() = 200 Then
                        API_Start_Daily.UPDTAE_ERR("ERROR", APIText, "dailyImportCreditsafeEvents")
                        Exit Sub
                    Else
                        Thread.Sleep(4000)
                        GoTo repeatRequestDaily
                    End If
                End If

                If totalPages > 1 Then
                    For i = 2 To totalPages
repeatRequestDailyPages:
                        APIText = cs.getCompanyEvents(companyDummy, dtMonitoredRequest, False, totalPages, checkDate, upateKunden, False,, setzeKundenbesonderheiten, True,, i)
                        If APIText.Contains("Invalid token") Then
                            If Not cs.authenticate() = 200 Then
                                API_Start_Daily.UPDTAE_ERR("ERROR", APIText, "dailyImportCreditsafeEvents")
                                Exit For
                            Else
                                Thread.Sleep(4000)
                                GoTo repeatRequestDailyPages
                            End If
                        End If
                    Next

                End If


                API_Start_Daily.UPDTAE_OK(,, "dailyImportCreditsafeEvents" & " Seiten:" & totalPages & "/" & page)

                Exit Sub

            End If


            Dim dtRechnungen As DataTable = (New SQL).loadDgvBySql("select distinct(RechnungsKundenNr) from Rechnungsausgang where cast(RechnungsDatum as Date) >= ' " & Today().AddYears(-1) & "' ", "FMZOLL")

            Dim dtCreditsafe As DataTable = (New SQL).loadDgvBySql(creditsave, "FMZOLL")

            If dtCreditsafe.Rows.Count = 0 Then Exit Sub

            Dim countMissingVerag As Integer = 0
            Dim countMissingIMEX As Integer = 0
            Dim countMissingUNISPED As Integer = 0
            Dim countMissingAMBAR As Integer = 0

            Dim dt_fehlendeCreditsafeIDS As New DataTable
            dt_fehlendeCreditsafeIDS.Columns.Add("KundenNr", GetType(String))
            dt_fehlendeCreditsafeIDS.Columns.Add("Creditsafe-ID", GetType(String))
            dt_fehlendeCreditsafeIDS.Columns.Add("Creditsafe-NO", GetType(String))
            dt_fehlendeCreditsafeIDS.Columns.Add("Firma", GetType(String))



            Dim counter As Integer = 0
            Dim API_Start = VERAG_PROG_ALLGEMEIN.cAPI.INSERT_API(VERAG_PROG_ALLGEMEIN.cAPI_INOUT.IN, VERAG_PROG_ALLGEMEIN.cAPI_Type.REST, VERAG_PROG_ALLGEMEIN.cAPI_ART.AVISO_IN_CS, "CREDITSAFE-EVENTS-IMPORT", "CS")
            If dtCreditsafe.Rows.Count = 0 Then
                API_Start.UPDTAE_ERR("ERROR - KEINE DATEN", "Anzahl abgefragte Datensätze:" & dtCreditsafe.Rows.Count & " Anzahl importierte Datensätze:" & counter & " Anzahl fehlende Creditsafe-IDs:" & dt_fehlendeCreditsafeIDS.Rows.Count, "importCreditsafeEvents")
            End If

            For Each row As DataRow In dtCreditsafe.Rows

                Dim KUNDE_ERW As New cKundenErweitert(row("ba_KundenNr"))

                Dim company As New cCreditSafeAPI.Company("", "", "", "", KUNDE_ERW.kde_CreditSaveNo, KUNDE_ERW.kde_CreditSaveId, Nothing, "", "", "", "", "", "", "", "", "", KUNDE_ERW.kde_KundenNr)
                If txtCSDate.Text <> "" AndAlso IsDate(txtCSDate.Text) Then
                    company.lastChecked = CDate(txtCSDate.Text)
                End If

                Dim currentBonID As Integer = (New SQL).getValueTxtBySql("Select Top(1) isnull(ba_id, -1) FROM [tblBonitaetsauskunft] where ba_KundenNr = " & KUNDE_ERW.kde_KundenNr & " AND [ba_Pruefungstool] = 'creditsafe API' ORDER BY ba_Datum DESC", "FMZOLL")

                If currentBonID > 0 Then company.csBonID = currentBonID
                Dim dt As New DataTable()

                Dim exists As Boolean = dtRechnungen.AsEnumerable().Any(Function(r) r.Field(Of Integer)("RechnungsKundenNr") = KUNDE_ERW.kde_KundenNr)
                If sendMail Then

                    If VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM Then
                        Mailinfolast1Year = True
                    Else
                        Mailinfolast1Year = exists
                    End If

                End If
repeatRequest:
                Dim APIText As String = ""
                If exists Then
                    APIText = cs.getCompanyEventsDetails(company, dt, checkDate, upateKunden, False, , setzeKundenbesonderheiten, Mailinfolast1Year, row("Firma"))
                End If

                If (APIText.Contains("Error") Or APIText.Contains("Verbindungsfehler")) Then
                    Dim API = VERAG_PROG_ALLGEMEIN.cAPI.INSERT_API(VERAG_PROG_ALLGEMEIN.cAPI_INOUT.IN, VERAG_PROG_ALLGEMEIN.cAPI_Type.REST, VERAG_PROG_ALLGEMEIN.cAPI_ART.AVISO_IN_CS, "CREDITSAFE-EVENTS", "CS",, KUNDE_ERW.kde_KundenNr)
                    API.UPDTAE_ERR("ERROR", APIText, "importCreditsafeEvents")
                    If APIText.Contains("Not Found") AndAlso APIText.Contains(KUNDE_ERW.kde_CreditSaveId) Then

                        Dim R As DataRow = dt_fehlendeCreditsafeIDS.NewRow
                        R("KundenNr") = KUNDE_ERW.kde_KundenNr
                        R("Creditsafe-ID") = KUNDE_ERW.kde_CreditSaveId
                        R("Creditsafe-NO") = KUNDE_ERW.kde_CreditSaveNo
                        R("Firma") = row("Firma")
                        dt_fehlendeCreditsafeIDS.Rows.Add(R)

                        If Not VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM Then
                            Select Case row(FIRMA)
                                Case "VERAG" : countMissingVerag += 1
                                Case "IMEX" : countMissingIMEX += 1
                                Case "AMBAR" : countMissingAMBAR += 1
                                Case "UNISPED" : countMissingUNISPED += 1
                            End Select
                        End If


                        KUNDE_ERW.kde_CreditSaveId = ""
                        KUNDE_ERW.SAVE()
                    End If

                    If APIText.Contains("Invalid token") Then
                        Dim ERR = Not cs.authenticate()
                        If ERR <> "200" Then
                            API.UPDTAE_ERR("ERROR", APIText & vbNewLine & "ERR-Code: " & ERR, "importCreditsafeEvents")
                            Exit For
                        Else
                            Thread.Sleep(4000)
                            GoTo repeatRequest
                        End If
                    End If

                Else
                    counter += 1

                End If


                Thread.Sleep(500) 'von 1000 auf 500 reduziert!
            Next

            If dtCreditsafe.Rows.Count = (counter - dt_fehlendeCreditsafeIDS.Rows.Count) Then
                API_Start.UPDTAE_OK()
            Else
                API_Start.UPDTAE_ERR("IMPORT UNVOLLSTÄNDIG", "Anzahl abgefragte Datensätze:" & dtCreditsafe.Rows.Count & " Anzahl importierte Datensätze:" & counter & " Anzahl fehlende Creditsafe-IDs:" & dt_fehlendeCreditsafeIDS.Rows.Count, "importCreditsafeEvents")
            End If



            If dt_fehlendeCreditsafeIDS.Rows.Count > 0 Then
                Dim filepath = VERAG_PROG_ALLGEMEIN.cProgramFunctions.genExcelFromDT_NEW(dt_fehlendeCreditsafeIDS,,,,, False)
                If filepath <> "" Then
                    Dim anhenge As New List(Of String)
                    anhenge.Add(filepath)
                    Dim empfaneger As String = ""
                    If countMissingVerag > 0 Then empfaneger &= cMitarbeiter.GetEMailRecipientForEmailNotification("Creditsafe", 1)
                    If countMissingIMEX > 0 Then empfaneger &= cMitarbeiter.GetEMailRecipientForEmailNotification("Creditsafe", 20)
                    If countMissingUNISPED > 0 Then empfaneger &= cMitarbeiter.GetEMailRecipientForEmailNotification("Creditsafe", 21)
                    If countMissingAMBAR > 0 Then empfaneger &= cMitarbeiter.GetEMailRecipientForEmailNotification("Creditsafe", 24)
                    If empfaneger <> "" Then VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(empfaneger, IIf(VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM, "TEST-", "") & "CREDITSAFE - fehlende CS-IDs", "Im Anhang befinden sich eine Liste der Kunden, deren Creditsafe-ID ungültig sind/nicht gefunden wurden!" & "<br><br>" & "*Automatic generated e-mail*", getAbsenderEmail(),,,,, anhenge)
                End If
            End If

        End If

    End Sub

    Private Sub UploadCompaniesToCreditsafe(sync As Boolean)

        Dim cs = New cCreditSafeAPI("creditsafe")
        Dim addCreditsave As Boolean = False
        If cs.authenticate() = "200" Then addCreditsave = True

        'The Sync  method allows you to replace all existing companies in a portfolio with the contents of an uploaded file.
        'Unlike the Import method, this endpoint overwrites the entire portfolio, deleting all previously allocated companies.

        Dim where As String = ""

        If Not sync Then
            where = " and kde_CSPortfolioAdded = 0"
        Else
            addCreditsave = (New SQL).doSQL("Update tblKundenErweitert set kde_CSPortfolioAdded = 0 where kde_CSPortfolioAdded = 1", "FMZOLL")
        End If

        While addCreditsave
            Dim creditsave As String = "select kde_CreditSaveNo 'Safe Number', '' as 'Local Org No.',left(kde_CreditSaveId,2) as 'Country Code', '' as Reference, '' as 'Free Text', '' as 'Personal Limit'   from tblKundenErweitert inner join Adressen on Adressen.AdressenNr = kde_KundenNr inner join Rechnungsausgang on  Rechnungsausgang.RechnungsKundenNr = Adressen.AdressenNr where isnull(tblKundenErweitert.kde_CreditSaveId,'') <> '' and kde_CreditSaveId <> 'True' and kde_CreditSaveId <>'False' and isnull(kde_CreditSaveNo,'') <> '' " & where & " and Adressen.Auswahl = 'A' and cast(RechnungsDatum as Date) >= ' " & Today().AddYears(-1) & "' group by kde_CreditSaveNo, kde_CreditSaveId"
            Dim dtCreditsafe_CSV As DataTable = (New SQL).loadDgvBySql(creditsave, "FMZOLL")

            If dtCreditsafe_CSV.Rows.Count = 0 Then
                addCreditsave = False
            Else

                Dim Path As String = VERAG_PROG_ALLGEMEIN.cProgramFunctions.genCSVFromDT(dtCreditsafe_CSV,,, "importcsv")
                If Path <> "" Then

                    Dim resp = cs.AddCompaniesCSVToPortfolio(Path, sync)
                    If resp IsNot Nothing AndAlso (resp.Contains("400") Or resp.Contains("Unauthorized")) Then 'bei Fehler abbrechen!
                        Dim API = VERAG_PROG_ALLGEMEIN.cAPI.INSERT_API(VERAG_PROG_ALLGEMEIN.cAPI_INOUT.IN, VERAG_PROG_ALLGEMEIN.cAPI_Type.REST, VERAG_PROG_ALLGEMEIN.cAPI_ART.AVISO_IN_CS, "CREDITSAFE-PORTFOLIO UPLOAD", "CS")
                        API.UPDTAE_ERR("ERROR", resp, "AddCompaniesCSVToPortfolio")
                        Exit While
                    End If
                End If

            End If

            Dim displayView = New DataView(dtCreditsafe_CSV, "", "Safe Number", DataViewRowState.CurrentRows)
            Dim distinctDT_CSV As DataTable = displayView.ToTable(True, "Safe Number")
            Dim CS_ID As String = ""
            Dim counter = 0
            For Each row As DataRow In distinctDT_CSV.Rows
                CS_ID &= "'" & row.Item("Safe Number") & "'"
                counter = counter + 1
                If (distinctDT_CSV.Rows.Count <> 1 And counter <> distinctDT_CSV.Rows.Count) Then CS_ID &= ","

            Next

            If CS_ID <> "" Then
                addCreditsave = (New SQL).doSQL("Update tblKundenErweitert set kde_CSPortfolioAdded = 1 where kde_CreditSaveNo in (" & CS_ID & ")", "FMZOLL")
            End If

            If sync Then
                addCreditsave = False
            End If

        End While

        Dim countMissing As Integer = 0
        Dim countUploaeded As Integer = 0
        Dim sql As New SQL

        lblCSPortfolio.Text = "im CS-Portfolio:"
        lblMissingCS.Text = "hochzuladende Unternehmen in CS: "

        Dim sqlCountNotUploaded As String = sql.getValueTxtBySql("select count(distinct(kde_CreditSaveNo)) from tblKundenErweitert where isnull(tblKundenErweitert.kde_CreditSaveId,'') <> '' and kde_CreditSaveId <> 'True' and kde_CreditSaveId <>'False' and isnull(kde_CreditSaveNo,'') <> '' and kde_CSPortfolioAdded = 0", "FMZOLL")

        Dim sqlCountUploaded As String = sql.getValueTxtBySql("select count(distinct(kde_CreditSaveNo)) from tblKundenErweitert where isnull(tblKundenErweitert.kde_CreditSaveId,'') <> '' and kde_CreditSaveId <> 'True' and kde_CreditSaveId <>'False' and isnull(kde_CreditSaveNo,'') <> '' and kde_CSPortfolioAdded = 1", "FMZOLL")

        If sqlCountNotUploaded <> "" AndAlso IsNumeric(sqlCountNotUploaded) Then countMissing = CInt(sqlCountNotUploaded)

        If sqlCountUploaded <> "" AndAlso IsNumeric(sqlCountUploaded) Then countUploaeded = CInt(sqlCountUploaded)

        lblMissingCS.Text &= countMissing

        lblCS_DB.Text = " VON " & sqlCountUploaded
    End Sub

    Private Sub cbCheckDate_CheckedChanged(sender As Object, e As EventArgs) Handles cbCheckDate.CheckedChanged
        txtCSDate.Enabled = cbCheckDate.Checked
        If cbCheckDate.Checked Then txtCSDate.Text = ""
    End Sub

    Private Sub LinkLabel53_LinkClicked_2(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel53.LinkClicked

        Dim fehlendePDFzuRE As String = "select rmc_daId,rmc_pdfFileName, Year(cast(rmc_importDatum as Date)) as rmc_importDatumYear  FROM [tblRMCImport] where rmc_daId is null and cast(rmc_importDatum as Date) >= '02.10.2025' " 'hardcoded, weil erst zu diesem Zeitpunkt bekommen wir alle RMC-Rechnungen vollständig

        Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
        Dim dtRechnnungsdaten As DataTable = SQL.loadDgvBySql(fehlendePDFzuRE, "FMZOLL")

        If dtRechnnungsdaten.Rows.Count > 0 Then

            Dim counter As Integer = 0

            For Each r As DataRow In dtRechnnungsdaten.Rows

                Dim dateinameSearch As String = r.Item("rmc_pdfFileName")

                If dateinameSearch.Contains("bto") Then

                    dateinameSearch = dateinameSearch.Replace("bto.pdf", "bto%.pdf")

                ElseIf dateinameSearch.Contains("nto") Then
                    dateinameSearch = dateinameSearch.Replace("nto.pdf", "nto%.pdf")
                End If
                If dateinameSearch <> "" Then

                    Dim daId As Integer = 0
                    daId = CInt(SQL.getValueTxtBySql("Select top(1) isnull(da_id,0) FROM tblDatenarchiv WHERE da_KundenNr = 0  And da_kategorie = 'MDM' AND da_ordner='MDM_DATEN' AND da_uOrdner1= 'RMC' AND da_uOrdner2= '" & r.Item("rmc_importDatumYear") & "' AND da_name like '%" & dateinameSearch & "'", "FMZOLL",,, 0))
                    If daId > 0 Then
                        Dim DS As New VERAG_PROG_ALLGEMEIN.cDATENSERVER(daId)
                        Dim Path As String = DS.GET_TOP1_PATH()
                        If Path <> "" And System.IO.File.Exists(Path) Then
                            SQL.doSQL("Update [tblRMCImport] SET [rmc_daId]='" & DS.da_id & "', rmc_daIdgesetztDatum = getdate()  where [rmc_pdfFileName] = '" & r.Item("rmc_pdfFileName") & "'  ", "FMZOLL")
                            counter += 1
                        End If
                    End If
                End If

            Next



            MsgBox(counter & " von " & dtRechnnungsdaten.Rows.Count & " RMC - Rechnungsdaten gesetzt!")

        Else

            MsgBox("Keine fehlenden RMC-Rechnungsdaten seit 02.10.2025")

        End If

    End Sub

    Private Sub LinkLabel54_LinkClicked_1(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles lblPlosefoppelteIMporte.LinkClicked
        cPLOSE_Inv_Data.checkImport()
    End Sub

    Private Sub lbl_setBackToCustomerIDS_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles lbl_setBackToCustomerIDS.LinkClicked, lblBackToCustomer_MSE.LinkClicked, lblBackToCustomer_PLOSE.LinkClicked, lblBackToCustomer_UTA.LinkClicked, lblBackToCustomer_RMC.LinkClicked

        Dim Lieferant As String = ""

        Select Case sender.Name
            Case "lbl_setBackToCustomerIDS" : Lieferant = "IDS"
            Case "lblBackToCustomer_MSE" : Lieferant = "MSE"
            Case "lblBackToCustomer_PLOSE" : Lieferant = "PLOSE"
            Case "lblBackToCustomer_UTA" : Lieferant = "UTA"
            Case "lblBackToCustomer_RMC" : Lieferant = "RMC"
        End Select

        setInvoiceBackToCustomer(Lieferant)

    End Sub


    Private Sub setInvoiceBackToCustomer(Lieferant As String, Optional showError As Boolean = True)

        Dim sql_query = ""
        Dim sql_query_keineMWST = ""

        Dim dtkeineMWST As DataTable = (New SQL).loadDgvBySql("select Land, Erstattungsland, Lieferant from tblKeineMWSTErstattung", "FMZOLL")
        Dim dtKundeMWST As DataTable = (New SQL).loadDgvBySql("select * from tblKundenMWST", "FMZOLL")

        'alle ab 2025!

        Select Case Lieferant
            Case "IDS"
                sql_query = "  select Adressen.AdressenNr as KundenNr,Adressen.AdressenNr as KundenNrVerag, invoice_id, LandKz as KundenLandKz, VATAmount as MWST, Country as RELandKz  FROM tblIDSInvoicesNewSplittedByCountry 
                            inner join [VERAG].[dbo].[tbl_IDS_Kunden] on tblIDSInvoicesNewSplittedByCountry.CustomerCode = tbl_IDS_Kunden.CustomerCode 
                            inner join Adressen on Adressen.AdressenNr = KdNrVERAG 
                             WHERE tblIDSInvoicesNewSplittedByCountry.[CustomerCode] in (SELECT distinct([CustomerCode]) FROM [VERAG].[dbo].[tbl_IDS_Kunden]  
                             WHERE 1 = 1 AND isnull([tbl_IDS_Kunden].KdNrAlt, 0) = 0) AND tblIDSInvoicesNewSplittedByCountry.InvToCustomer is null and Year(YearMonthDay) > 2024"

                sql_query_keineMWST = "select distinct(tblKundenErweitert.kde_KundenNr) as KundenNr  FROM tblIDSInvoicesNewSplittedByCountry 
                            inner join [VERAG].[dbo].[tbl_IDS_Kunden] on tblIDSInvoicesNewSplittedByCountry.CustomerCode = tbl_IDS_Kunden.CustomerCode 
                            inner join tblKundenErweitert on tblKundenErweitert.kde_KundenNr = KdNrVERAG 
                             WHERE tblIDSInvoicesNewSplittedByCountry.[CustomerCode] in (SELECT distinct([CustomerCode]) FROM [VERAG].[dbo].[tbl_IDS_Kunden]  
                             WHERE 1 = 1 AND isnull([tbl_IDS_Kunden].KdNrAlt, 0) = 0) AND tblIDSInvoicesNewSplittedByCountry.InvToCustomer is null and Year(YearMonthDay) > 2024 and kde_keineMWSt = 1"

            Case "MSE"
                sql_query = " select customer_number as KundenNr,Adressen.AdressenNr as KundenNrVerag,invoice_id,LandKz as KundenLandKz, total_vat_amount_euro as MWST,  country as RELandKz FROM tblMSEInvoices 
                              inner join tblMSECustomers on customer_id = [customer_number] 
                              inner join Adressen on Adressen.AdressenNr = partner_customer_number 
                              where tblMSEInvoices.InvToCustomer is null and Year(invoice_date) > 2024"

                sql_query_keineMWST = "select distinct(customer_number) as KundenNr FROM tblMSEInvoices 
                            inner join tblMSECustomers on customer_id = [customer_number] 
                            inner join tblKundenErweitert on tblKundenErweitert.kde_KundenNr = partner_customer_number 
                            where tblMSEInvoices.InvToCustomer is null and Year(invoice_date) > 2024 and kde_keineMWSt = 1"

            Case "PLOSE"

                Dim kdNrPlose As String = ""
                If txtPLoseKdNr.Text <> "" AndAlso IsNumeric(txtPLoseKdNr.Text) Then
                    kdNrPlose = " AND plInv_PLOSEKundennummer = " & txtPLoseKdNr.Text
                End If

                sql_query = "  select plInv_PLOSEKundennummer as KundenNr,Adressen.AdressenNr as KundenNrVerag, [plInv_Id] as invoice_id,LandKz as KundenLandKz ,[plInv_MWSTBetrag] as MWST, [plInv_SupplierCountry] as RELandKz FROM tblPLOSE_Inv_Data  
                                inner join Adressen on Adressen.PLOSEKundenNr = plInv_PLOSEKundennummer 
                                where plInv_InvToCustomer is null and YEAR(plInv_SupplierRechnungsDatum) > 2024" & kdNrPlose


                sql_query_keineMWST = "select distinct(plInv_PLOSEKundennummer) as KundenNr FROM tblPLOSE_Inv_Data  
                                        inner join Adressen on Adressen.PLOSEKundenNr = plInv_PLOSEKundennummer  
                                       inner join tblKundenErweitert on tblKundenErweitert.kde_KundenNr = Adressen.AdressenNr 
                                        where plInv_InvToCustomer is null and YEAR(plInv_SupplierRechnungsDatum) > 2024 and kde_keineMWSt = 1 "

            Case "UTA"
                sql_query = "  select Adressen.UTAKundenNr as KundenNr,Adressen.AdressenNr as KundenNrVerag,[Rechnungsnummer_pro_Lieferland] as invoice_id,LandKz as KundenLandKz, SUM(Gesamtbetrag_Umsatzsteuer_in_Darstellwährung) as MWSt,[Lieferland_ISO2] as RELandKz  FROM [VERAG].[dbo].[tblUTAImportNew] 
                                inner join Adressen on Adressen.UTAKundenNr= [tblUTAImportNew].Kundennummer  
                                inner join tblKundenErweitert on tblKundenErweitert.kde_KundenNr = Adressen.AdressenNr   
                                where InvToCustomer is null and Year(Rechnungsdatum) > 2024
                                group by Adressen.UTAKundenNr,Adressen.AdressenNr ,[Rechnungsnummer_pro_Lieferland],LandKz,[Lieferland_ISO2]"

                sql_query_keineMWST = "select distinct(Adressen.UTAKundenNr) as KundenNr  FROM [VERAG].[dbo].[tblUTAImportNew] 
                                        inner join Adressen on Adressen.UTAKundenNr= [tblUTAImportNew].Kundennummer  
                                        inner join tblKundenErweitert on tblKundenErweitert.kde_KundenNr = Adressen.AdressenNr   
                                        where InvToCustomer is null and Year(Rechnungsdatum) > 2024 and kde_keineMWSt = 1
                                        group by Adressen.UTAKundenNr  "

            Case "RMC"
                sql_query = " select Adressen.WölflKundenNr as KundenNr,Adressen.AdressenNr as KundenNrVerag,rmc_id as invoice_id,LandKz as KundenLandKz,[rmc_betragMWST] as MWST,rmc_landKZ as RELandKz
                            FROM [VERAG].[dbo].[tblRMCImport] 
                            inner join Adressen on Adressen.WölflKundenNr = rmc_kdNr
                            where InvToCustomer is null and Year(rmc_reDatum) > 2024"

                sql_query_keineMWST = "select distinct(Adressen.WölflKundenNr) as KundenNr FROM [VERAG].[dbo].[tblRMCImport] 
                                        inner join Adressen on Adressen.WölflKundenNr = rmc_kdNr
                                        inner join tblKundenErweitert on tblKundenErweitert.kde_KundenNr = Adressen.AdressenNr
                                        where InvToCustomer is null and Year(rmc_reDatum) > 2024 and kde_keineMWSt = 1"



        End Select


        Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL


        Dim dt_keineMWST As DataTable = SQL.loadDgvBySql(sql_query_keineMWST, "FMZOLL")

        'zuerst alle setzen, MWST nicht MDM uns machen!
        For Each r In dt_keineMWST.Rows

            If Not IsDBNull(r.Item("KundenNr")) AndAlso IsNumeric(r.Item("KundenNr")) Then
                Select Case Lieferant
                    Case "IDS" 'OK

                        Dim IDS As cIDS
                        IDS.setBackToCustomerCustomerID(SQL, True, r.Item("KundenNr"))

                    Case "MSE" 'OK
                        Dim MSE As cMSEAPI
                        MSE.setBackToCustomerCustomerID(SQL, True, r.Item("KundenNr"))

                    Case "PLOSE"
                        Dim ploseRE As cPLOSE_Inv_Data
                        ploseRE.setBackToCustomerCustomerID(SQL, True, r.Item("KundenNr"))

                    Case "UTA"

                        Dim uta As cUTA
                        uta.setBackToCustomerCustomerID(SQL, True, r.Item("KundenNr"))

                    Case "RMC"
                        Dim rmc As cRMC
                        rmc.setBackToCustomerCustomerID(SQL, True, r.Item("KundenNr"))

                End Select

            End If

        Next

        Dim dtnichtGesetzteInvToCustomer As DataTable = SQL.loadDgvBySql(sql_query, "FMZOLL")

        Dim rows_fehlendesErstattungsland() As DataRow = dtnichtGesetzteInvToCustomer.Select("RELandKz is null")
        If rows_fehlendesErstattungsland.Length > 0 Then
            If showError Then MsgBox("Rechnungsland fehlt noch bei " & rows_fehlendesErstattungsland.Length & " Einträgen von " & Lieferant & vbNewLine & "Bitte Ländercode ISO2 einfügen!")
            Exit Sub
        End If

        For Each r In dtnichtGesetzteInvToCustomer.Rows

            'checks!
            'ORIGINAL-RECHNUNG setzen:

            If Not IsDBNull(r.Item("MWST")) AndAlso IsNumeric(r.Item("MWST")) AndAlso CDbl(r.Item("MWST")) = 0 Then

                'wenn die Rechnung die MWST-SUMME 0 aufweist!!!
                UpdateLieferantInvToCustomer(Lieferant, r.Item("invoice_id"), r.Item("KundenNr"))
                Continue For
            Else

                If Not IsDBNull(r.Item("KundenNr")) AndAlso Not IsDBNull(r.Item("KundenLandKz")) AndAlso Not IsDBNull(r.Item("KundenNrVerag")) Then

                    Dim kdnr As Integer = r.Item("KundenNr")
                    Dim kdnrVerag As Integer = r.Item("KundenNrVerag")
                    Dim LandKz = r.Item("KundenLandKz")
                    Dim landKZiso2 = ""

                    If LandKz.Length = 2 Then
                        landKZiso2 = LandKz
                    ElseIf LandKz.Length = 3 Then
                        landKZiso2 = VERAG_PROG_ALLGEMEIN.cProgramFunctions.getISO2LandFromISO3Land(LandKz)
                    ElseIf LandKz.Length = 1 Then
                        landKZiso2 = VERAG_PROG_ALLGEMEIN.cProgramFunctions.getISO2LandFromISO1Land(LandKz)
                    End If

                    If IsDBNull(r.Item("RELandKz")) Then Continue For

                    Dim Erstattungsland As String = r.Item("RELandKz")

                    If landKZiso2 = Erstattungsland Then
                        'wenn die Rechnung in dem Land in dem er ansässig ist ausgestellt wurde (rumän. Kunde – Rechnung ausgestellt in Rumänien = z.B. IDS in RO getankt…)
                        UpdateLieferantInvToCustomer(Lieferant, r.Item("invoice_id"), r.Item("KundenNr"))
                        Continue For
                    End If


                    If landKZiso2 <> "" AndAlso dtkeineMWST.Rows.Count > 0 Then
                        'Rechnungen der Länder in denen der Kunde keine MWST erstattet bekommt
                        Dim rows_keineMWST() As DataRow = dtkeineMWST.Select("Land = '" & landKZiso2 & "' AND Erstattungsland= '" & Erstattungsland & "'" & IIf(Lieferant <> "IDS", " AND Lieferant <> 'IDS'", ""))
                        If rows_keineMWST.Length > 0 Then
                            UpdateLieferantInvToCustomer(Lieferant, r.Item("invoice_id"), r.Item("KundenNr"))
                            Continue For
                        End If

                    End If

                    'Rechnungen der Länder, in denen der Kunde selber MWST beantragt
                    If landKZiso2 <> "" AndAlso dtKundeMWST.Rows.Count > 0 Then
                        Dim rows_KundeMWST() As DataRow = dtKundeMWST.Select("LandKz = '" & Erstattungsland & "' AND KdNr =" & kdnrVerag)
                        If rows_KundeMWST.Length > 0 Then
                            UpdateLieferantInvToCustomer(Lieferant, r.Item("invoice_id"), r.Item("KundenNr"))
                            Continue For
                        End If
                    End If


                End If
            End If


        Next

        Select Case Lieferant
            Case "IDS"

                Dim IDS As cIDS
                IDS.setBackToCustomerInvoiceID(SQL, False)

            Case "MSE"
                Dim MSE As cMSEAPI
                MSE.setBackToCustomerInvoiceID(SQL, False)

            Case "PLOSE"
                Dim ploseRE As cPLOSE_Inv_Data
                ploseRE.setBackToCustomerInvoiceID(SQL, False)

            Case "UTA"

                Dim uta As cUTA
                uta.setBackToCustomerInvoiceID(SQL, False)

            Case "RMC"
                Dim rmc As cRMC
                rmc.setBackToCustomerInvoiceID(SQL, False)

        End Select


    End Sub

    Private Sub UpdateLieferantInvToCustomer(Lieferant As String, InvoiceID As String, Optional CustomerNr As String = "")

        Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL

        Select Case Lieferant
            Case "IDS"

                Dim IDS As cIDS
                IDS.setBackToCustomerInvoiceID(SQL, True, InvoiceID)


            Case "MSE"
                Dim MSE As cMSEAPI
                MSE.setBackToCustomerInvoiceID(SQL, True, InvoiceID, CustomerNr) 'bei MSE ist die InvoiceID nur in Verbindung mit dem CustomerCode eindeutig!


            Case "PLOSE"
                Dim ploseRE As cPLOSE_Inv_Data
                ploseRE.setBackToCustomerInvoiceID(SQL, True, InvoiceID)

            Case "UTA"

                Dim uta As cUTA
                uta.setBackToCustomerInvoiceID(SQL, True, InvoiceID)

            Case "RMC"
                Dim rmc As cRMC
                rmc.setBackToCustomerInvoiceID(SQL, True, InvoiceID)


        End Select

    End Sub

    Private Sub Button29_Click_1(sender As Object, e As EventArgs)

        ' doMailZollbeleg("", "STB", 725002)

        'Dim SND As New VERAG_PROG_ALLGEMEIN.cSendungen(1956266)
        'Dim list As New List(Of Integer)

        'sendMailZollbeleg("", SND.tblSnd_AuftraggeberKdNr, "STB", list, "4803/26002277A", SND, SND.getKdAtrNr("AUFTRAGGEBER"), "AUFTRAGGEBER")


        ''Dim ZA = VERAG_PROG_ALLGEMEIN.cVERAG_CustomsDeclarations.loadByMRN("26DE7458ACA000YYR2", True)
        'Dim ZA = VERAG_PROG_ALLGEMEIN.cVERAG_CustomsDeclarations.loadByMRN("26DE7701ACA0024DR0", True)
        'ZA.checkfreshCBAMWarning()

    End Sub

    Private Sub lblIDS_plauscheck_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles lblIDS_plauscheck.LinkClicked

        Dim IDS As cIDS
        Dim dt As New DataTable
        IDS.checkPDFInvoices(,, dt)

        If dt.Rows.Count > 0 Then

            If Not vbYes = MsgBox("Fehler bei " & dt.Rows.Count & " IDS-Rechnungen!" & vbNewLine & "Details anzeigen?", vbYesNoCancel) Then
                Exit Sub
            End If

            VERAG_PROG_ALLGEMEIN.cProgramFunctions.genExcelFromDT_NEW(dt)

        Else
            MsgBox("OK")
        End If


    End Sub

    Private Sub btnKKEmailscheck_Click(sender As Object, e As EventArgs) Handles btnKKEmailscheck.Click

        Dim sendNotificationEmails = False

        If vbYes = MsgBox("Soll eine Info-Mail an die zuständigen Mitarbeiter geschickt werden?", vbYesNoCancel) Then
            sendNotificationEmails = True
        End If

        checkEmailAdressen(2, sendNotificationEmails)

    End Sub

    Private Sub dtp_MDM_Einarbeitung_ValueChanged(sender As Object, e As EventArgs) Handles dtp_MDM_Einarbeitung.ValueChanged

        Dim ok As Boolean = checkMDMdatum(dtp_MDM_Einarbeitung.Value)

        showPic(ok, PictureBox27)



        With dgv_MDMEinarbeitung

            .ClearSelection()
            .SET_SQL("Select [supplier], [completed], sum(ds_total) As DS, sum(ds_count) As DS_importiert,  FROM [VERAG].[dbo].[tblMDMEinarbeitung]
                            where cast(invoicedate as Date) = '" & dtp_MDM_Einarbeitung.Value & "'
                            group by [supplier], completed", "FMZOLL")

            .LOAD()
            .RowTemplate.Height = 20
            .AllowUserToOrderColumns = False

        End With




    End Sub

    Private Function checkMDMdatum(abrDate As Date)


        Dim checkDate As Boolean = False

        If Not (abrDate.Day = 15 Or abrDate.Day = 30 Or abrDate.Day = 31 Or (abrDate.Month = 2 And abrDate.Day = 28)) Then

            checkDate = False

        Else
            checkDate = True
        End If

        Return checkDate
    End Function

    Private Sub Button30_Click(sender As Object, e As EventArgs) Handles Button30.Click


        Dim BezeichnungSetzen As String = "select Beschreibung_DE,Beschreibung_EN  FROM [tblVZPreisliste] where Beschreibung_DE = ''"

        Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
        Dim dtRechnnungsdaten As DataTable = SQL.loadDgvBySql(BezeichnungSetzen, "FMZOLL")

        If dtRechnnungsdaten.Rows.Count > 0 Then


            For Each r As DataRow In dtRechnnungsdaten.Rows

                Dim BezDE As String = SQL.getValueTxtBySql("Select Beschreibung_DE FROM [tblVZPreisliste] WHERE Beschreibung_EN= '" & r.Item("Beschreibung_EN") & "'", "FMZOLL",,, "")

                If BezDE <> "" Then
                    SQL.doSQL("Update [tblVZPreisliste]  SET Beschreibung_DE='" & BezDE & "'  where Beschreibung_EN = '" & r.Item("Beschreibung_EN") & "' AND Beschreibung_DE = ''  ", "FMZOLL")
                End If


            Next

        End If


    End Sub

    Private Sub btnCheckPDF_USTVA_Click(sender As Object, e As EventArgs) Handles btnCheckPDF_USTVA.Click

        Dim USTVA_PDFS_AUS_DA As String = "select Replace(da_uOrdner3,'USTVA_','') as USTVA, da_id, da_date from tblDatenarchiv where da_uordner2 = 'MDM_DATEN' and da_uOrdner3 like 'USTVA_%' order by da_KundenNr,da_uOrdner3"

        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = cbxTestsystem.Checked

        Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
        Dim dtRechnnungsdaten As DataTable = SQL.loadDgvBySql(USTVA_PDFS_AUS_DA, "FMZOLL")

        Dim dt_falscheEintraege As New DataTable

        If dtRechnnungsdaten.Rows.Count > 0 Then

            dt_falscheEintraege.Columns.Add("daid", GetType(Integer))
            dt_falscheEintraege.Columns.Add("id", GetType(Integer))
            dt_falscheEintraege.Columns.Add("pos", GetType(Integer))
            dt_falscheEintraege.Columns.Add("pos_new", GetType(Integer))
            dt_falscheEintraege.Columns.Add("posAfterDaId", GetType(Integer))
            dt_falscheEintraege.Columns.Add("Path", GetType(String))
            dt_falscheEintraege.Columns.Add("deleted", GetType(Boolean))

            For Each r As DataRow In dtRechnnungsdaten.Rows

                Dim Bez As String = r.Item("USTVA")

                Dim ID As String = Bez.Substring(0, Bez.IndexOf("_"))
                Dim POS As String = Bez.Substring(Bez.IndexOf("_") + 1, Bez.Length - (Bez.IndexOf("_") + 1))

                If IsNumeric(ID) AndAlso IsNumeric(POS) Then

                    Dim cUSTVA As New cUSTVAntrag(CInt(ID))

                    Dim cUSTVA_POS As New cUStVPositionen(CInt(ID), CInt(POS), CInt(POS))

                    If Not cUSTVA.hasEntry Then

                        Dim ROW As DataRow = dt_falscheEintraege.NewRow
                        ROW("id") = ID
                        ROW("pos") = -1
                        ROW("daid") = r.Item("da_id")

                        Dim DS As New cDATENSERVER(ROW("daid"))

                        If DS.hasITEMS Then
                            ROW("Path") = DS.GET_TOP1_PATH

                            Dim exists = SQL.getValueTxtBySql("SELECT UStVPo_ID FROM [tblUStVPositionen] WHERE UStVPo_daId =" & r.Item("da_id") & " AND UStVPo_SchnittstellenNr <> 1", "FMZOLL",,, -1)
                            If exists <= 0 Then 'OK-> löschen
                                If DS.DELETE_COMPLETE() Then
                                    ROW("deleted") = True
                                End If
                            Else
                                ROW("deleted") = False
                                ROW("pos_new") = exists
                            End If

                            dt_falscheEintraege.Rows.Add(ROW)
                        End If


                    ElseIf Not cUSTVA_POS.hasEntry Then

                        Dim ROW As DataRow = dt_falscheEintraege.NewRow
                        ROW("id") = ID
                        ROW("pos") = POS
                        ROW("daid") = r.Item("da_id")

                        Dim DS As New cDATENSERVER(ROW("daid"))

                        If DS.hasITEMS Then
                            ROW("Path") = DS.GET_TOP1_PATH
                            ROW("deleted") = False

                            'check if daid nicht bei anderen POS verknüpft (wenn nicht, dann löschen!)
                            Dim exists = SQL.getValueTxtBySql("SELECT UStVPo_ID FROM [tblUStVPositionen] WHERE UStVPo_daId =" & r.Item("da_id") & " AND UStVPo_SchnittstellenNr <> 1", "FMZOLL",,, -1)
                            If exists <= 0 Then 'OK-> löschen
                                If DS.DELETE_COMPLETE() Then
                                    ROW("deleted") = True
                                End If
                            Else
                                ROW("deleted") = False
                                ROW("pos_new") = exists
                            End If

                        End If

                        dt_falscheEintraege.Rows.Add(ROW)


                    ElseIf Not IsDBNull(r.Item("da_date")) Then

                        If cUSTVA_POS.UStVPo_Zeitstempel > CDate(r.Item("da_date")) Then

                            Dim ROW As DataRow = dt_falscheEintraege.NewRow
                            ROW("id") = ID
                            ROW("pos") = POS
                            ROW("daid") = r.Item("da_id")
                            ROW("posAfterDaId") = 1
                            ROW("deleted") = False

                            dt_falscheEintraege.Rows.Add(ROW)
                        End If


                    End If

                End If

            Next

            If dt_falscheEintraege.Rows.Count > 0 Then
                VERAG_PROG_ALLGEMEIN.cProgramFunctions.genExcelFromDT_NEW(dt_falscheEintraege)
            End If


        End If


    End Sub

    Private Sub Button31_Click(sender As Object, e As EventArgs) Handles btnEZOLL_7days.Click
        txtEZOLLAnhDat._value = Now().AddDays(-7).ToShortDateString
    End Sub

    Private Sub Button32_Click(sender As Object, e As EventArgs) Handles btnEZOLL_1month.Click
        txtEZOLLAnhDat._value = Now().AddMonths(-1).ToShortDateString
    End Sub

    Private Sub LinkLabel25_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel25.LinkClicked

        Me.Visible = False
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = cbxTestsystem.Checked
        Dim f As New frmNachrichtenVerarbeitung_MDM_divers("MSE", False, False, cbxIDSUmbenenen.Checked, True)
        f.year = txtIDSYear.Text
        f.ShowDialog()
        Me.Visible = True
    End Sub

    Private Sub TabControl1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles TabControl1.SelectedIndexChanged


        Select Case TabControl1.SelectedIndex
            Case 1 'IDS
                Dim invoice As New cIDS
                Dim missingITC As Integer = 0
                missingITC = invoice.countBackToCustomerNotSet(New SQL)
                If missingITC > 0 Then
                    lblOriginalRechnungIDS.Text &= " ITC nicht gesetzt: " & missingITC
                Else
                    lblOriginalRechnungIDS.Text = "Original-Rechnungen"
                End If

            Case 2 'MSE
                Dim invoice As New cMSEAPI
                Dim missingITC As Integer = 0
                missingITC = invoice.countBackToCustomerNotSet(New SQL)
                If missingITC > 0 Then
                    lblOriginalRechnungMSE.Text &= " ITC nicht gesetzt: " & missingITC
                Else
                    lblOriginalRechnungMSE.Text = "Original-Rechnungen"

                End If

            Case 3 'RMC
                Dim invoice As New cRMC
                Dim missingITC As Integer = 0
                missingITC = invoice.countBackToCustomerNotSet(New SQL)
                If missingITC > 0 Then
                    lblOriginalRechnungRMC.Text &= " ITC nicht gesetzt: " & missingITC
                Else
                    lblOriginalRechnungRMC.Text = "Original-Rechnungen"
                End If

            Case 4 'UTA
                Dim invoice As New cUTA
                Dim missingITC As Integer = 0
                missingITC = invoice.countBackToCustomerNotSet(New SQL)
                If missingITC > 0 Then
                    lblOriginalRechnungUTA.Text &= " ITC nicht gesetzt: " & missingITC
                Else
                    lblOriginalRechnungUTA.Text = "Original-Rechnungen"
                End If

            Case 5 'PLOSE
                Dim invoice As New cPLOSE_Inv_Data
                Dim missingITC As Integer = 0
                missingITC = invoice.countBackToCustomerNotSet(New SQL)
                If missingITC > 0 Then
                    lblOriginalRechnungPLOSE.Text &= " ITC nicht gesetzt: " & missingITC
                Else
                    lblOriginalRechnungPLOSE.Text = "Original-Rechnungen"
                End If

        End Select




    End Sub

    Private Sub Button29_Click_2(sender As Object, e As EventArgs) Handles Button29.Click
        getNCTS_MODALTRANS(CDate(MyTextBox5._value))
    End Sub

    Sub getNCTS_MODALTRANS(Optional from As Object = Nothing)
        'Dim MT As New VERAG_PROG_ALLGEMEIN.cModalTransNCTS.cMT_NCTS_ApiClient
        'Dim LIST = MT.GetNCTSDeclarations(CDate("01.03.2026"))
        'If LIST.Count = 0 Then Console.WriteLine("Keine Eintäge")


        'For Each MRN In LIST
        '    Console.WriteLine(MRN.lrn)

        'Next

        If from Is Nothing Then from = Now.AddDays(-1)

        Dim MT As New VERAG_PROG_ALLGEMEIN.cModalTransNCTS.cMT_NCTS_ApiClient
        Dim LIST = MT.GetAllNCTSDeclarations(CDate(from))
        If LIST.Count = 0 Then Console.WriteLine("Keine Eintäge")


        For Each MRN In LIST
            Try



                Dim nctsFremd = VERAG_PROG_ALLGEMEIN.cNCTS_FREMD.LOADByMRN(MRN.mrn, False)
                If nctsFremd IsNot Nothing Then
                    Console.WriteLine(MRN.mrn & " found")
                Else
                    Console.WriteLine(MRN.mrn & " not found")
                End If
                Console.WriteLine(MRN.mrn & " - " & MRN.lrn)

                Dim statusValue As Integer = -1
                If nctsFremd IsNot Nothing Then
                    Integer.TryParse(If(nctsFremd.ncts_Status, "").ToString(), statusValue)
                End If

                ' Fall 1: vorhanden + Status 60/90 -> nichts tun
                If nctsFremd IsNot Nothing AndAlso (statusValue = 60 OrElse statusValue = 90) Then
                    Console.WriteLine("Übersprungen, da ncts_Status = " & statusValue)
                    Continue For
                End If


                If nctsFremd Is Nothing Then
                    ' 
                    Console.WriteLine("*Neu anlegen")
                    Dim nctsMt = MT.GetNCTSDeclarationByMRN(MRN.mrn)
                    If nctsMt Is Nothing Then
                        Console.WriteLine("Keine Modaltrans-Daten gefunden.")
                        Continue For
                    End If
                    ' Debug-Ausgaben
                    Console.WriteLine("vehicle_code:" & If(nctsMt.vehicle_code, ""))
                    Console.WriteLine("lrn:" & If(nctsMt.lrn, ""))
                    Console.WriteLine("letter_grn:" & If(nctsMt.letter_grn, ""))
                    Console.WriteLine("guarantee_curr:" & If(nctsMt.guarantee_curr, ""))
                    Console.WriteLine("guarantee_price:" & If(nctsMt.guarantee_price, ""))
                    Console.WriteLine("status:" & If(nctsMt.status, ""))
                    MT.ConvertModaltransToNCTSFremd(nctsMt)

                Else
                    ' Vorhanden, aber anderer Status -> Update (auskommentiert)
                    'Status updaten:
                    Console.WriteLine("*Updaten")

                    If MT.UpdateNCTSFremdStatusFromTimelines(nctsFremd.ncts_MRN, nctsFremd, False) Then
                        nctsFremd.SAVE()
                    End If

                End If
            Catch ex As Exception
                VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name, VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL)

            End Try
        Next
    End Sub

    Private Sub Button31_Click_1(sender As Object, e As EventArgs) Handles Button31.Click
        UpdateOpenModaltransNCTSFremdStatuses()
    End Sub
    Public Function UpdateOpenModaltransNCTSFremdStatuses() As Integer
        Dim updatedCount As Integer = 0
        Dim totalCount As Integer = 0

        Try
            Dim sqlstr As String = "SELECT ncts_MRN FROM [tblNCTS_FREMD] " &
                               "WHERE ncts_Partnersystem = 'MODALTRANS' " &
                               "AND ISNULL(ncts_Status, 0) < 60 " &
                               "AND ISNULL(ncts_MRN, '') <> ''"

            Console.WriteLine("=== Starte Update Modaltrans NCTS_FREMD ===")


            Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL

            Dim dt As DataTable = SQL.loadDgvBySql(sqlstr, "FMZOLL")

            If dt Is Nothing OrElse dt.Rows.Count = 0 Then
                Console.WriteLine("Keine offenen Datensätze gefunden.")
                Return 0
            End If

            Console.WriteLine("Gefundene Datensätze: " & dt.Rows.Count)

            Dim MT As New VERAG_PROG_ALLGEMEIN.cModalTransNCTS.cMT_NCTS_ApiClient

            For Each row As DataRow In dt.Rows
                totalCount += 1

                Dim mrn As String = If(row("ncts_MRN"), "").ToString.Trim
                If String.IsNullOrWhiteSpace(mrn) Then
                    Console.WriteLine("[" & totalCount & "] MRN leer -> übersprungen")
                    Continue For
                End If

                Console.WriteLine("[" & totalCount & "] Prüfe MRN: " & mrn)

                Dim nctsFremd As VERAG_PROG_ALLGEMEIN.cNCTS_FREMD = VERAG_PROG_ALLGEMEIN.cNCTS_FREMD.LOADByMRN(mrn, False)

                If nctsFremd Is Nothing Then
                    Console.WriteLine("   -> Datensatz nicht gefunden")
                    Continue For
                End If

                Try
                    If MT.UpdateNCTSFremdStatusFromTimelines(nctsFremd.ncts_MRN, nctsFremd, False) Then
                        nctsFremd.SAVE()
                        updatedCount += 1
                        Console.WriteLine("   -> ✔ Aktualisiert (Status: " & nctsFremd.ncts_Status & ")")
                    End If
                Catch exInner As Exception
                    Console.WriteLine("   -> ❌ Fehler bei MRN " & mrn & ": " & exInner.Message)
                End Try
            Next

            Console.WriteLine("=== Fertig ===")
            Console.WriteLine("Gesamt geprüft: " & totalCount)
            Console.WriteLine("Aktualisiert: " & updatedCount)

        Catch ex As Exception
            Console.WriteLine("❌ Globaler Fehler: " & ex.Message)

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

        Return updatedCount
    End Function

    Private Sub checkEmailAdressen(CustomersWithInvoiceWithingYears As Integer, sendNotificationEmails As Boolean)


        Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL

        Dim dt As DataTable = SQL.loadDgvBySql("select *  from (

                        select ADR.AdressenNr, ADR.[Name 1],F.FilialenNr,KK.kkd_kkaBez, ISNULL(KK.kkd_Email,'') as kkd_email ,isnull(KK.kkd_EmailCC,'') as kkd_EmailCC , isnull(KK.kkd_EmailBCC,'') as kkd_EmailBCC, F.Firma from Adressen ADR
                       inner join Kunden K on K.KundenNr = ADR.AdressenNr
                       inner join Filialen F On  F.FilialenNr=K.FilialenNr 
                       INNER JOIN tblKundenKontakt KK on KK.kkd_KundenNr = K.KundenNr
                       where isnull(ADR.Auswahl,'A') = 'A' and (KK.kkd_Email is not null or KK.kkd_EmailCC is not null  or KK.kkd_EmailBCC is not null)
                       
                       UNION
                       
                        select ADR.AdressenNr, ADR.[Name 1] ,F.FilialenNr,'Standard',isnull(ADR.[E-Mail],''), isnull(ADR.[E-Mail2],''),'', F.Firma  from Adressen ADR
                       inner join Kunden K on K.KundenNr = ADR.AdressenNr
                       inner join Filialen F On  F.FilialenNr=K.FilialenNr 
                        where isnull(ADR.Auswahl,'A') = 'A' and (ADR.[E-Mail] is not null or ADR.[E-Mail2] is not null)
                       
                        UNION
                       
                       select ADR.AdressenNr, ADR.[Name 1] ,F.FilialenNr,'Statusmails',isnull(BEN.eb_EMail,''), '','', F.Firma  from Adressen ADR
                       inner join Kunden K on K.KundenNr = ADR.AdressenNr
                       inner join Filialen F On  F.FilialenNr=K.FilialenNr 
                       INNER JOIN  tblEmailBenachrichtigung BEN on BEN.eb_KundenNr = K.KundenNr
                        where isnull(ADR.Auswahl,'A') = 'A' and (BEN.eb_EMail is not null or BEN.eb_cc is not null or BEN.eb_bcc is not null)
                       
                        ) as temp
                        order by temp.AdressenNr", "FMZOLL", 100, False)

        Dim dt_wrongEmails As New DataTable
        dt_wrongEmails.Columns.Add("KdNr", GetType(String))
        dt_wrongEmails.Columns.Add("Art", GetType(String))
        dt_wrongEmails.Columns.Add("Name", GetType(String))
        dt_wrongEmails.Columns.Add("FilialenNr", GetType(Integer))
        dt_wrongEmails.Columns.Add("Firma", GetType(String))
        dt_wrongEmails.Columns.Add("fehlerhafteMail", GetType(String))
        dt_wrongEmails.Columns.Add("fehlerhafteMail-CC", GetType(String))
        dt_wrongEmails.Columns.Add("fehlerhafteMail-BCC", GetType(String))

        Dim dtVerag As DataTable = dt_wrongEmails.Clone()
        Dim dtIMEX As DataTable = dt_wrongEmails.Clone()
        Dim dtAMBAR As DataTable = dt_wrongEmails.Clone()
        Dim dtUNISPED As DataTable = dt_wrongEmails.Clone()
        Dim dtFRONTOFFICE As DataTable = dt_wrongEmails.Clone()
        Dim dtVERAG360 As DataTable = dt_wrongEmails.Clone()

        'nur Prüfung bei Kunden, die in den letzen 2 Jahren eine Rechnung bekommen haben! (laut A.Stockenhuber).
        Dim yearstocheck As Integer = CustomersWithInvoiceWithingYears
        Dim dtRechnungen As DataTable = (New SQL).loadDgvBySql("select distinct(RechnungsKundenNr) from Rechnungsausgang where cast(RechnungsDatum as Date) >= ' " & Today().AddYears(-yearstocheck) & "' ", "FMZOLL")



        If dt IsNot Nothing Then
            For Each r As DataRow In dt.Rows

                Dim fehlerhafteMail As String = VERAG_PROG_ALLGEMEIN.cProgramFunctions.checkifMailisOK_better(r("kkd_email"))
                Dim fehlerhafteMailCC As String = VERAG_PROG_ALLGEMEIN.cProgramFunctions.checkifMailisOK_better(r("kkd_emailcc"))
                Dim fehlerhafteMailBCC As String = VERAG_PROG_ALLGEMEIN.cProgramFunctions.checkifMailisOK_better(r("kkd_emailbcc"))

                If fehlerhafteMail <> "" Or fehlerhafteMailCC <> "" Or fehlerhafteMailBCC <> "" Then

                    Dim exists As Boolean = dtRechnungen.AsEnumerable().Any(Function(r_rechnung) r_rechnung.Field(Of Integer)("RechnungsKundenNr") = r.Item("AdressenNr"))
                    If exists Then
                        Dim ROW As DataRow = dt_wrongEmails.NewRow
                        ROW("KdNr") = r.Item("AdressenNr")
                        ROW("Art") = r.Item("kkd_kkaBez")
                        ROW("FilialenNr") = r.Item("FilialenNr")
                        ROW("Name") = r.Item("Name 1")
                        ROW("Firma") = r.Item("Firma")
                        ROW("fehlerhafteMail") = fehlerhafteMail
                        ROW("fehlerhafteMail-CC") = fehlerhafteMailCC
                        ROW("fehlerhafteMail-BCC") = fehlerhafteMailBCC
                        dt_wrongEmails.Rows.Add(ROW)

                        Select Case ROW("Firma").ToString()
                            Case "VERAG"
                                If ROW("FilialenNr") = 8001 Then
                                    dtVERAG360.ImportRow(ROW)
                                Else
                                    dtVerag.ImportRow(ROW)
                                End If
                            Case "IMEX"
                                dtIMEX.ImportRow(ROW)
                            Case "AMBAR"
                                dtAMBAR.ImportRow(ROW)
                            Case "UNISPED"
                                dtUNISPED.ImportRow(ROW)
                            Case "FRONTOFFICE"
                                dtFRONTOFFICE.ImportRow(ROW)
                        End Select

                    End If
                End If


            Next

            If dt_wrongEmails.Rows.Count > 0 Then

                If Not sendNotificationEmails Then
                    VERAG_PROG_ALLGEMEIN.cProgramFunctions.genExcelFromDT_NEW(dt_wrongEmails,,,,, True,,, True)
                Else


                    Dim Betreff = "EMAIL-CHECK"
                    Dim MailText = "Hallo, <br><br>anbei übermitteln wird eine Auflistung von Kunden mit fehlerhaften E-Mail-Adressen, die in den letzten " & yearstocheck & " Jahre(n) eine Rechnung von UNS bekommen haben."
                    MailText &= "<br><br>Aufgrund fehlerhafter Angaben können Emails nicht zugestellt werden, wir ersuchen Sie daher dringend, die angeführten E-Mail-Adressen zeitnah zu überprüfen und zu korrigieren!"
                    MailText &= "<br><br>Erstellt am: " & Now.ToShortDateString & " um " & Now.ToShortTimeString
                    MailText &= "<br><br>Automatisch generiertes E-Mail."


                    If dtVerag.Rows.Count > 0 Then
                        Dim empfaneger = cMitarbeiter.GetEMailRecipientForEmailNotification("EMail-Check", 1)
                        If empfaneger <> "" Then
                            Dim path = VERAG_PROG_ALLGEMEIN.cProgramFunctions.genExcelFromDT_NEW(dtVerag,,,,, False,,, True)
                            Dim anhenge As New List(Of String)
                            anhenge.Add(path)
                            VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(empfaneger, IIf(VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM, "TEST-", "") & Betreff & " VERAG", MailText, getAbsenderEmail(), True, False,,, anhenge)
                        End If
                    End If

                    If dtIMEX.Rows.Count > 0 Then
                        Dim empfaneger = cMitarbeiter.GetEMailRecipientForEmailNotification("EMail-Check", 20)
                        If empfaneger <> "" Then
                            Dim path = VERAG_PROG_ALLGEMEIN.cProgramFunctions.genExcelFromDT_NEW(dtIMEX,,,,, False,,, True)
                            Dim anhenge As New List(Of String)
                            anhenge.Add(path)
                            VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(empfaneger, IIf(VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM, "TEST-", "") & Betreff & " IMEX", MailText, getAbsenderEmail(), True, False,,, anhenge)
                        End If
                    End If

                    If dtAMBAR.Rows.Count > 0 Then
                        Dim empfaneger = cMitarbeiter.GetEMailRecipientForEmailNotification("EMail-Check", 24)
                        If empfaneger <> "" Then
                            Dim path = VERAG_PROG_ALLGEMEIN.cProgramFunctions.genExcelFromDT_NEW(dtAMBAR,,,,, False,,, True)
                            Dim anhenge As New List(Of String)
                            anhenge.Add(path)
                            VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(empfaneger, IIf(VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM, "TEST-", "") & Betreff & " AMBAR", MailText, getAbsenderEmail(), True, False,,, anhenge)
                        End If
                    End If

                    If dtUNISPED.Rows.Count > 0 Then
                        Dim empfaneger = cMitarbeiter.GetEMailRecipientForEmailNotification("EMail-Check", 21)
                        If empfaneger <> "" Then
                            Dim path = VERAG_PROG_ALLGEMEIN.cProgramFunctions.genExcelFromDT_NEW(dtUNISPED,,,,, False,,, True)
                            Dim anhenge As New List(Of String)
                            anhenge.Add(path)
                            VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(empfaneger, IIf(VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM, "TEST-", "") & Betreff & " UNISPED", MailText, getAbsenderEmail(), True, False,,, anhenge)
                        End If
                    End If

                    If dtFRONTOFFICE.Rows.Count > 0 Then
                        Dim empfaneger = cMitarbeiter.GetEMailRecipientForEmailNotification("EMail-Check", 17)
                        If empfaneger <> "" Then
                            Dim path = VERAG_PROG_ALLGEMEIN.cProgramFunctions.genExcelFromDT_NEW(dtFRONTOFFICE,,,,, False,,, True)
                            Dim anhenge As New List(Of String)
                            anhenge.Add(path)
                            VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(empfaneger, IIf(VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM, "TEST-", "") & Betreff & " FRONTOFFICE", MailText, getAbsenderEmail(), True, False,,, anhenge)
                        End If
                    End If

                    If dtVERAG360.Rows.Count > 0 Then
                        Dim empfaneger = cMitarbeiter.GetEMailRecipientForEmailNotification("EMail-Check", 19)
                        If empfaneger <> "" Then
                            Dim path = VERAG_PROG_ALLGEMEIN.cProgramFunctions.genExcelFromDT_NEW(dtVERAG360,,,,, False,,, True)
                            Dim anhenge As New List(Of String)
                            anhenge.Add(path)
                            VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(empfaneger, IIf(VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM, "TEST-", "") & Betreff & " VERAG360", MailText, getAbsenderEmail(), True, False,,, anhenge)
                        End If
                    End If

                End If

            End If

            showPic(dt_wrongEmails.Rows.Count > 0, pbEmailscheck)

        End If


    End Sub


    Private Function checkZugferd(sendNotificationEmails As Boolean) As Boolean

        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False

        Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL

        'aktuell verwendet Verag360 kein Zugferd und Sammelrechnung 6 geht aktuell noch nicht - 29.04.2026 Start der neuen Funktion!

        Dim dt As DataTable = SQL.loadDgvBySql("SELECT RK_ID, dsId, Firma_ID, RechnungsNr FROM [Rechnungsausgang] where [zugferdcheck_daid] is null and [zugferdcheck_datetime] is null  and  dsId is not null and cast(RechnungsDatum as Date) between '29.04.2026' and CONVERT(DATE, GETDATE()) and Sammelrechnung <> 6 and Firma_ID <> 19 ", "FMZOLL", 100, False)

        Dim sumTotal_IMEX As Integer = 0
        Dim sumTotal_VERAG As Integer = 0
        Dim sumTotal_CS As Integer = 0
        Dim sumTotal_US As Integer = 0
        Dim sumTotal_AMBAR As Integer = 0
        Dim sumTotal_ATILLA As Integer = 0
        Dim sumTotal_360 As Integer = 0

        Dim sumvalid_IMEX As Integer = 0
        Dim sumvalid_VERAG As Integer = 0
        Dim sumvalid_CS As Integer = 0
        Dim sumvalid_US As Integer = 0
        Dim sumvalid_AMBAR As Integer = 0
        Dim sumvalid_ATILLA As Integer = 0
        Dim sumvalid_360 As Integer = 0

        Dim sumInvalid_IMEX As Integer = 0
        Dim sumInvalid_VERAG As Integer = 0
        Dim sumInvalid_CS As Integer = 0
        Dim sumInvalid_US As Integer = 0
        Dim sumInvalid_AMBAR As Integer = 0
        Dim sumInvalid_ATILLA As Integer = 0
        Dim sumInvalid_360 As Integer = 0

        Dim sumInvalid_Total As Integer = 0
        Dim sumvalid_Total As Integer = 0
        Dim sumTotal_Total As Integer = 0

        Dim dtVerag As DataTable = dt.Clone()
        Dim dtIMEX As DataTable = dt.Clone()
        Dim dtAMBAR As DataTable = dt.Clone()
        Dim dtUNISPED As DataTable = dt.Clone()
        Dim dtCS As DataTable = dt.Clone()
        Dim dtATILLA As DataTable = dt.Clone()
        Dim dt360 As DataTable = dt.Clone()

        Dim Paramslist As New cParameterList(VERAG_PROG_ALLGEMEIN.cAllgemein.PROGID)
        Dim fileName = Paramslist.GET_PARAMETER_VALUE("ZUGFeRD_Check_Pfad_JAVA")
        Dim arguments = Paramslist.GET_PARAMETER_VALUE("ZUGFeRD_Check_Pfad_CMD")


        For Each row In dt.Rows

            Dim rkObj As Object = row("RK_ID")
            Dim dsObj As Object = row("dsId")

            If rkObj IsNot DBNull.Value AndAlso dsObj IsNot DBNull.Value Then

                Dim rkId As Integer
                Dim dsId As Integer

                If Integer.TryParse(rkObj.ToString(), rkId) AndAlso
                   Integer.TryParse(dsObj.ToString(), dsId) AndAlso
                   dsId > 0 Then

                    Dim DS As New VERAG_PROG_ALLGEMEIN.cDATENSERVER(dsId)
                    Dim Path As String = DS.GET_TOP1_PATH()
                    If Path <> "" And System.IO.File.Exists(Path) Then

                        Try


                            Dim psi As New ProcessStartInfo()
                            psi.FileName = fileName
                            psi.Arguments = arguments & Path

                            'Workstation Daniel
                            'psi.FileName = "C:\Program Files\Eclipse Adoptium\jre-11.0.28.6-hotspot\bin\java.exe"
                            'psi.Arguments = "-jar ""C:\Users\d.breimaier\Downloads\Mustang-CLI-2.21.0.jar""  --no-notices --action validate --source " & Path & ""

                            psi.RedirectStandardOutput = True
                            psi.RedirectStandardError = True
                            psi.UseShellExecute = False
                            psi.CreateNoWindow = True

                            Using p As Process = Process.Start(psi)
                                Dim output = p.StandardOutput.ReadToEnd()
                                Dim err = p.StandardError.ReadToEnd()
                                p.WaitForExit()

                                If output <> "" Then
                                    Dim tmpPath_Report = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getTMPPath("MUSTANG-REPORT_" & rkObj & ".pdf", ".pdf", , False)
                                    Dim PruefungOK = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.CreateValidationPdf(output, Path, rkId, tmpPath_Report)
                                    If tmpPath_Report <> "" Then
                                        'Process.Start(tmpPath_Report)

                                        Dim fileInfo_ZP As New FileInfo(tmpPath_Report)
                                        Dim ZUGF_DS As New VERAG_PROG_ALLGEMEIN.cDATENSERVER("DOKUMENTE", "ZUGFERD", Now().Year, "", "", fileInfo_ZP.Name, -1, False)
                                        ZUGF_DS.uploadDataToDATENSERVER(tmpPath_Report, fileInfo_ZP.Name & ".pdf", fileInfo_ZP.Extension,,,, True)
                                        SQL.doSQL("Update [Rechnungsausgang] SET zugferdcheck_datetime=getDate(),zugferdcheck = " & IIf(PruefungOK, "1", "0") & ", zugferdcheck_daid = " & ZUGF_DS.da_id & "  where RK_ID = " & rkId, "FMZOLL")


                                        Select Case row("Firma_ID")
                                            Case 11
                                                sumTotal_CS += 1
                                                If PruefungOK Then
                                                    sumvalid_CS += 1
                                                Else
                                                    sumInvalid_CS += 1

                                                    dtCS.ImportRow(row)
                                                End If
                                            Case 24
                                                sumTotal_AMBAR += 1

                                                If PruefungOK Then
                                                    sumvalid_AMBAR += 1
                                                Else
                                                    sumInvalid_AMBAR += 1
                                                    dtAMBAR.ImportRow(row)
                                                End If

                                            Case 21, 22, 23
                                                sumTotal_US += 1
                                                If PruefungOK Then
                                                    sumvalid_US += 1
                                                Else
                                                    sumInvalid_US += 1
                                                    dtUNISPED.ImportRow(row)
                                                End If

                                            Case 20
                                                sumTotal_IMEX += 1
                                                If PruefungOK Then
                                                    sumvalid_IMEX += 1
                                                Else
                                                    sumInvalid_IMEX += 1
                                                    dtIMEX.ImportRow(row)
                                                End If

                                            Case 19
                                                sumTotal_360 += 1
                                                If PruefungOK Then
                                                    sumvalid_360 += 1
                                                Else
                                                    sumInvalid_360 += 1
                                                    dt360.ImportRow(row)
                                                End If

                                            Case 7
                                                sumTotal_ATILLA += 1
                                                If PruefungOK Then
                                                    sumvalid_ATILLA += 1
                                                Else
                                                    sumInvalid_ATILLA += 1
                                                    dtATILLA.ImportRow(row)
                                                End If
                                            Case Else
                                                sumTotal_VERAG += 1
                                                If PruefungOK Then
                                                    sumvalid_VERAG += 1
                                                Else
                                                    sumInvalid_VERAG += 1
                                                    dtVerag.ImportRow(row)
                                                End If


                                        End Select

                                    End If
                                End If


                            End Using

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

                    End If

                End If

            End If

        Next


        If dt.Rows.Count > 0 Then

            If Not sendNotificationEmails Then
                'VERAG_PROG_ALLGEMEIN.cProgramFunctions.genExcelFromDT_NEW(dt,,,,, True,,, True)
            Else


                Dim Betreff = "ZUGFeRD-CHECK"

                'hier ungültigen Prüfungen pro Firma

                If dtVerag.Rows.Count > 0 Then
                    Dim empfaneger = cMitarbeiter.GetEMailRecipientForEmailNotification("ZUGFERD-Check", 1)
                    If empfaneger <> "" Then
                        Dim path = VERAG_PROG_ALLGEMEIN.cProgramFunctions.genExcelFromDT_NEW(dtVerag,,,,, False,,, True)
                        Dim anhenge As New List(Of String)
                        anhenge.Add(path)
                        VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(empfaneger, IIf(VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM, "TEST-", "") & Betreff & " VERAG", createMailTextZugferd(sumTotal_VERAG, sumvalid_VERAG, sumInvalid_VERAG, "VERAG"), getAbsenderEmail(), True, False,,, anhenge)
                    End If
                End If

                If dtIMEX.Rows.Count > 0 Then
                    Dim empfaneger = cMitarbeiter.GetEMailRecipientForEmailNotification("ZUGFERD-Check", 20)
                    If empfaneger <> "" Then
                        Dim path = VERAG_PROG_ALLGEMEIN.cProgramFunctions.genExcelFromDT_NEW(dtIMEX,,,,, False,,, True)
                        Dim anhenge As New List(Of String)
                        anhenge.Add(path)
                        VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(empfaneger, IIf(VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM, "TEST-", "") & Betreff & " IMEX", createMailTextZugferd(sumTotal_IMEX, sumvalid_IMEX, sumInvalid_IMEX, "IMEX"), getAbsenderEmail(), True, False,,, anhenge)
                    End If
                End If

                If dtAMBAR.Rows.Count > 0 Then
                    Dim empfaneger = cMitarbeiter.GetEMailRecipientForEmailNotification("ZUGFERD-Check", 24)
                    If empfaneger <> "" Then
                        Dim path = VERAG_PROG_ALLGEMEIN.cProgramFunctions.genExcelFromDT_NEW(dtAMBAR,,,,, False,,, True)
                        Dim anhenge As New List(Of String)
                        anhenge.Add(path)
                        VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(empfaneger, IIf(VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM, "TEST-", "") & Betreff & " AMBAR", createMailTextZugferd(sumTotal_AMBAR, sumvalid_AMBAR, sumInvalid_AMBAR, "AMBAR"), getAbsenderEmail(), True, False,,, anhenge)
                    End If
                End If

                If dtUNISPED.Rows.Count > 0 Then
                    Dim empfaneger = cMitarbeiter.GetEMailRecipientForEmailNotification("ZUGFERD-Check", 21)
                    If empfaneger <> "" Then
                        Dim path = VERAG_PROG_ALLGEMEIN.cProgramFunctions.genExcelFromDT_NEW(dtUNISPED,,,,, False,,, True)
                        Dim anhenge As New List(Of String)
                        anhenge.Add(path)
                        VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(empfaneger, IIf(VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM, "TEST-", "") & Betreff & " UNISPED", createMailTextZugferd(sumTotal_US, sumvalid_US, sumInvalid_US, "UNISPED"), getAbsenderEmail(), True, False,,, anhenge)
                    End If
                End If

                If dtATILLA.Rows.Count > 0 Then
                    Dim empfaneger = cMitarbeiter.GetEMailRecipientForEmailNotification("ZUGFERD-Check", 7)
                    If empfaneger <> "" Then
                        Dim path = VERAG_PROG_ALLGEMEIN.cProgramFunctions.genExcelFromDT_NEW(dtATILLA,,,,, False,,, True)
                        Dim anhenge As New List(Of String)
                        anhenge.Add(path)
                        VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(empfaneger, IIf(VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM, "TEST-", "") & Betreff & " ATILLA", createMailTextZugferd(sumTotal_ATILLA, sumvalid_ATILLA, sumInvalid_ATILLA, "ATILLA"), getAbsenderEmail(), True, False,,, anhenge)
                    End If
                End If

                If dt360.Rows.Count > 0 Then
                    Dim empfaneger = cMitarbeiter.GetEMailRecipientForEmailNotification("ZUGFERD-Check", 19)
                    If empfaneger <> "" Then
                        Dim path = VERAG_PROG_ALLGEMEIN.cProgramFunctions.genExcelFromDT_NEW(dt360,,,,, False,,, True)
                        Dim anhenge As New List(Of String)
                        anhenge.Add(path)
                        VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(empfaneger, IIf(VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM, "TEST-", "") & Betreff & " VERAG 360", createMailTextZugferd(sumTotal_360, sumvalid_360, sumInvalid_360, "VERAG 360"), getAbsenderEmail(), True, False,,, anhenge)
                    End If
                End If

                If dtCS.Rows.Count > 0 Then
                    Dim empfaneger = cMitarbeiter.GetEMailRecipientForEmailNotification("ZUGFERD-Check", 11)
                    If empfaneger <> "" Then
                        Dim path = VERAG_PROG_ALLGEMEIN.cProgramFunctions.genExcelFromDT_NEW(dtCS,,,,, False,,, True)
                        Dim anhenge As New List(Of String)
                        anhenge.Add(path)
                        VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(empfaneger, IIf(VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM, "TEST-", "") & Betreff & "VERAG CS", createMailTextZugferd(sumTotal_CS, sumvalid_CS, sumInvalid_CS, "VERAG CS"), getAbsenderEmail(), True, False,,, anhenge)
                    End If
                End If


                'hier alle Prüfungen

                Dim empfanegerALL = cMitarbeiter.GetEMailRecipientForEmailNotification("ZUGFERD-Check_ALL",)
                If empfanegerALL <> "" Then

                    sumTotal_Total = sumTotal_VERAG + sumTotal_ATILLA + sumTotal_AMBAR + sumTotal_360 + sumTotal_CS + sumTotal_IMEX + sumTotal_US
                    sumInvalid_Total = sumInvalid_VERAG + sumInvalid_ATILLA + sumInvalid_AMBAR + sumInvalid_360 + sumInvalid_CS + sumInvalid_IMEX + sumInvalid_US
                    sumvalid_Total = sumvalid_VERAG + sumvalid_ATILLA + sumvalid_AMBAR + sumvalid_360 + sumvalid_CS + sumvalid_IMEX + sumvalid_US

                    VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(empfanegerALL, IIf(VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM, "TEST-", "") & Betreff & " ALL", createMailTextZugferd(sumTotal_Total, sumvalid_Total, sumInvalid_Total, "ALL"), getAbsenderEmail(), True, False)
                End If

            End If

        End If




        Return True


    End Function

    Private Function createMailTextZugferd(total As Integer, valid As Integer, invalid As Integer, Firma As String) As String

        Dim MailText = "Auflistung der gültigen/ungültigen ZUGFeRD-Prüfungen vom " & Now.ToShortDateString & " für  " & Firma & " <br><br>"
        MailText &= "<table border=1>"
        MailText &= "<tr><td>Gültig</td><td>Ungültig</td><td>Gesamt</td></tr>"
        MailText &= "<tr>"
        MailText &= "<td><b>" & valid & "</b></td>"
        MailText &= "<td><b>" & invalid & "</b></td>"
        MailText &= "<td><b>" & total & "</b></td>"
        MailText &= "</tr>"
        MailText &= "</table>"
        MailText &= "<br><br>Erstellt am: " & Now.ToShortDateString & " um " & Now.ToShortTimeString
        MailText &= "<br><br>Automatisch generiertes E-Mail."

        Return MailText

    End Function

    Private Sub Button32_Click_1(sender As Object, e As EventArgs) Handles Button32.Click

        Dim sendNotificationEmails = False

        Select Case MsgBox("Soll eine Info-Mail an die zuständigen Mitarbeiter geschickt werden?", vbYesNoCancel)
            Case MsgBoxResult.Cancel : Exit Sub
            Case MsgBoxResult.Yes : sendNotificationEmails = True
            Case Else

        End Select

        checkZugferd(sendNotificationEmails)
    End Sub

    Private Sub LinkLabel54_LinkClicked_2(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel54.LinkClicked
        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
        Dim Empfaenger = cMitarbeiter.GetEMailRecipientForEmailNotification("UID-Prüfung", 19)
        Dim bool = getUID_Pruefung(MyTextBox1.Text, "VERAG 360 GmbH", "UID Prüfung VERAG 360", Empfaenger, "",, MyTextBox2._value, cbxVermerk.Checked, cbxUseUIDFinanzOnline.Checked)
        showPic(bool, PictureBox12)
    End Sub

    Private Sub Button33_Click(sender As Object, e As EventArgs) Handles Button33.Click
        sendEssensbestellungenInfoMail(True, True)
    End Sub

    Public Function sendEssensbestellungenInfoMail(test As Boolean, showInfo As Boolean)


        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
        Dim Empfaenger = cMitarbeiter.GetEMailRecipientForEmailNotification("Essenbestellungen")
        Dim Betreff As String = ""
        Dim EmailText = generateEssensbestellungen(Betreff, test)
        If Empfaenger <> "" AndAlso EmailText <> "" Then
            VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(IIf(Not test, "info@highway-118.de; service@highway-118.de", "d.breimaier@verag.ag"), IIf(VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM, "TEST-", "") & Betreff, EmailText, getAbsenderEmail(),, False, Empfaenger)
        Else
            If EmailText = "" AndAlso showInfo Then
                MsgBox("keine zu schickenden Daten!")
            End If
        End If

    End Function

    Private Function generateEssensbestellungen(ByRef Betreff As String, ByRef test As Boolean) As String

        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False

        Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL

        Dim SQLWHERE = " eb_kw = (SELECT TOP (1) eb_kw FROM tblEssensbestellungen WHERE eb_archiviert = 0 AND eb_datum >= CAST(GETDATE() AS DATE) ORDER BY eb_datum ASC)  and isnull(eb_storniert,0) <> 1 and isnull(eb_gesendet,0) <> 1"
        Dim SQLAnmerkung = ", MAX(CASE WHEN ISNULL(LTRIM(RTRIM(eb_anmerkung)), '') <> '' THEN 1 ELSE 0 END) AS HatAnmerkung "

        Dim dtBestellungenMail As DataTable = SQL.loadDgvBySql("SELECT  [eb_mitname] as Name ,[eb_mitid] as ID , [eb_kw] as KW , [eb_gebaeude] as Gebaeude ,[eb_abteilung] as Abteilung ,[eb_montag] As Montag ,[eb_dienstag] As Dienstag,[eb_mittwoch] As Mittwoch,  
        [eb_donnerstag] As Donnerstag , [eb_freitag] As Freitag, [eb_anmerkung] As Anmerkung , [eb_datum] As Datum , [eb_storniert] as Storniert,  [eb_firma] as Firma, eb_MenuID
                                    FROM [tblEssensbestellungen] left join tblEBMenu on tblEBMenu.MenuID = eb_MenuID
        WHERE  " & SQLWHERE & " order by Gebaeude, Firma", "AVISO", 100, False)


        If dtBestellungenMail.Rows.Count > 0 Then
            Dim bestellung As New cEssensbestellung(dtBestellungenMail.Rows(0)("KW"), dtBestellungenMail.Rows(0)("ID"))
            If bestellung IsNot Nothing AndAlso bestellung.eb_MenuID IsNot Nothing AndAlso bestellung.eb_MenuID.ToString <> "" AndAlso IsDate(bestellung.eb_datum) Then

                Dim BestellungsTrigger As Date = bestellung.eb_datum
                Dim tageBisBestellende = CInt((New SQL).getValueTxtBySql("SELECT TOP(1) MenuBestellungBisTageVorher FROM [tblEBMenu] WHERE MenuID='" & bestellung.eb_MenuID & "' ", "AVISO"))
                If tageBisBestellende > 0 Then
                    BestellungsTrigger = BestellungsTrigger.AddDays(tageBisBestellende * -1)
                    If BestellungsTrigger <= Today() Then 'dann OK
                    Else
                        Return ""
                    End If

                End If
            End If

        Else
            Return ""
        End If


        Dim dt_bestellungen_aggregiert As DataTable = SQL.loadDgvBySql("select * from (SELECT 1 as tagID, eb_gebaeude, 'Montag' AS Tag, eb_montag AS Menu, COUNT(*) AS Anzahl" & SQLAnmerkung & " FROM tblEssensbestellungen WHERE ISNULL(eb_montag,'') <> '' and " & SQLWHERE & "  GROUP BY eb_gebaeude, eb_montag UNION ALL
                                                                            SELECT 2 as tagID, eb_gebaeude, 'Dienstag' AS Tag, eb_dienstag AS Menu, COUNT(*) AS Anzahl" & SQLAnmerkung & " FROM tblEssensbestellungen WHERE ISNULL(eb_dienstag,'') <> '' and " & SQLWHERE & " GROUP BY eb_gebaeude, eb_dienstag UNION ALL
                                                                            SELECT 3 as tagID, eb_gebaeude, 'Mittwoch' AS Tag, eb_mittwoch AS Menu, COUNT(*) AS Anzahl" & SQLAnmerkung & " FROM tblEssensbestellungen WHERE ISNULL(eb_mittwoch,'') <> '' and " & SQLWHERE & " GROUP BY eb_gebaeude, eb_mittwoch UNION ALL
                                                                            SELECT 4 as tagID, eb_gebaeude, 'Donnerstag' AS Tag, eb_donnerstag AS Menu, COUNT(*) AS Anzahl" & SQLAnmerkung & " FROM tblEssensbestellungen WHERE ISNULL(eb_donnerstag,'') <> '' and " & SQLWHERE & " GROUP BY eb_gebaeude, eb_donnerstag UNION ALL
                                                                            SELECT 5 as tagID, eb_gebaeude, 'Freitag' AS Tag, eb_freitag AS Menu, COUNT(*) AS Anzahl" & SQLAnmerkung & " FROM tblEssensbestellungen WHERE ISNULL(eb_freitag,'') <> '' and " & SQLWHERE & " GROUP BY eb_gebaeude, eb_freitag) as temp order by eb_gebaeude, tagId", "AVISO")




        Dim TextHTMLtable As String = ""
        Dim TextHTMLtableAgg As String = ""
        Dim StartTextHTML As String = ""
        Dim EndTextHTML As String = ""

        TextHTMLtable &= "<table border=1>"
        TextHTMLtable &= "<tr><td>Mitarbeiter</td><td>Montag</td><td>Dienstag</td><td>Mittwoch</td><td>Donnerstag</td><td>Freitag</td><td>Gebäude</td><td>Anmerkung</td><td>Firma</td></tr>"

        TextHTMLtableAgg &= "<br>Aufteilung nach Gebäude/Abteilung:<br>"
        TextHTMLtableAgg &= "<table border=1>"
        TextHTMLtableAgg &= "<tr><td>Gebäude</td><td>Montag</td><td>Dienstag</td><td>Mittwoch</td><td>Donnerstag</td><td>Freitag</td><td>Anmerkung</td></tr>"

        Dim KW = ""

        If dtBestellungenMail.Rows.Count > 0 Then

            Dim lastGebaeude As String = ""
            Dim useBlue As Boolean = False


            For Each row As DataRow In dtBestellungenMail.Rows

                If KW = "" Then
                    KW = row("KW")
                End If

                If lastGebaeude <> "" AndAlso lastGebaeude <> row("Gebaeude").ToString() Then
                    useBlue = Not useBlue
                End If

                lastGebaeude = row("Gebaeude").ToString()

                Dim bgColor As String = If(useBlue, "#D9EAF7", "transparent")

                TextHTMLtable &= "<tr style='background-color:" & bgColor & ";'>"
                'TextHTMLtable &= "<tr>"
                TextHTMLtable &= "<td><b>" & row("Name") & "</b></td>"
                TextHTMLtable &= "<td><b>" & row("Montag") & "</b></td>"
                TextHTMLtable &= "<td><b>" & row("Dienstag") & "</b></td>"
                TextHTMLtable &= "<td><b>" & row("Mittwoch") & "</b></td>"
                TextHTMLtable &= "<td><b>" & row("Donnerstag") & "</b></td>"
                TextHTMLtable &= "<td><b>" & row("Freitag") & "</b></td>"
                TextHTMLtable &= "<td><b>" & row("Gebaeude") & "</b></td>"
                TextHTMLtable &= "<td><b>" & row("Anmerkung") & "</b></td>"
                TextHTMLtable &= "<td><b>" & row("Firma") & "</b></td>"
                TextHTMLtable &= "</tr>"

                If row("ID") <> 0 Then
                    If Not test Then
                        Dim bestellung As New cEssensbestellung(row("KW"), row("ID"))
                        bestellung.eb_gesendet = True
                        bestellung.eb_gesendet_am = Now
                        bestellung.SAVE()
                    End If

                End If
            Next


            Dim dict As New Dictionary(Of String, Dictionary(Of String, List(Of String)))
            Dim dictHatAnmerkung As New Dictionary(Of String, Boolean)

            For Each row As DataRow In dt_bestellungen_aggregiert.Rows


                Dim gebaeude As String = row("eb_gebaeude").ToString()
                Dim tag As String = row("Tag").ToString()
                Dim text As String = row("Anzahl").ToString() & "x " & row("Menu").ToString()

                If Not dict.ContainsKey(gebaeude) Then
                    dict.Add(gebaeude, New Dictionary(Of String, List(Of String)))
                End If

                If Not dict(gebaeude).ContainsKey(tag) Then
                    dict(gebaeude).Add(tag, New List(Of String))
                End If

                dict(gebaeude)(tag).Add(text)

                If Not dictHatAnmerkung.ContainsKey(gebaeude) Then
                    dictHatAnmerkung.Add(gebaeude, CBool(row("HatAnmerkung")))
                Else
                    dictHatAnmerkung(gebaeude) = dictHatAnmerkung(gebaeude) OrElse CBool(row("HatAnmerkung"))
                End If

            Next

            For Each gebaeude As String In dict.Keys

                TextHTMLtableAgg &= "<tr>"
                TextHTMLtableAgg &= "<td><b>" & gebaeude & "</b></td>"

                For Each tag As String In {"Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag"}

                    Dim value As String = ""

                    If dict(gebaeude).ContainsKey(tag) Then
                        value = String.Join("<br>", dict(gebaeude)(tag))
                    End If

                    TextHTMLtableAgg &= "<td>" & value & "</td>"

                Next

                TextHTMLtableAgg &= "<td>"
                If dictHatAnmerkung.ContainsKey(gebaeude) AndAlso dictHatAnmerkung(gebaeude) Then
                    TextHTMLtableAgg &= "⚠ Anmerkung vorhanden"
                End If
                TextHTMLtableAgg &= "</td>"

                TextHTMLtableAgg &= "</tr>"

            Next

            TextHTMLtableAgg &= "</table>"




            StartTextHTML &= "Hallo,<br>"
            StartTextHTML &= "<br>"

            Betreff = "Essensbestellung: " & IIf(KW <> "", "für " & KW, "")
            StartTextHTML &= "anbei ist die Essensbestellung " & IIf(KW <> "", "für " & KW, "") & ".<br><br>"


            If TextHTMLtable <> "" Then TextHTMLtable &= "</table><br><br>"
            If TextHTMLtableAgg <> "" Then TextHTMLtableAgg &= "</table><br><br>"


            EndTextHTML &= "Mit freundlichen Grüßen/Best regards<br>"
            EndTextHTML &= "<br>"

        End If

        Return StartTextHTML & TextHTMLtable & TextHTMLtableAgg & EndTextHTML




    End Function

    Private Sub Button34_Click(sender As Object, e As EventArgs) Handles Button34.Click

        VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = cbxDatevTest.Checked

        If cbxOffertenNr._value <> "" AndAlso IsNumeric(cbxOffertenNr._value) AndAlso cbxLeistungNr._value <> "" AndAlso IsNumeric(cbxLeistungNr._value) Then
            Dim dt As DataTable = checkLeitungsNrimOffert(cbxOffertenNr._value, cbxLeistungNr._value)

            If dt.Rows.Count > 0 Then
                Dim STDOF As New cStandardofferten(cbxOffertenNr._value, "EUR", cbxLeistungNr._value, cbxLeistungNr.SelectedItem.text)
                If STDOF.hasEntry Then


                    If Not checkStandardOffert(STDOF) Then
                        MsgBox("BerechnungsartNr ist nicht im Standardoffert hinterlegt!")
                    Else
                        showPic(insertOfferenPositionen(STDOF), pbOfferten)
                    End If
                End If

            Else
                showPic(True, pbOfferten)
            End If

        End If




    End Sub


    Private Function checkLeitungsNrimOffert(OffertenNr As Integer, LeistungsNr As Integer) As DataTable

        Dim sqlWhere = ""
        Dim selectString = "*"
        If cbxNurAktiveKunen.Checked Then
            sqlWhere = "  inner join Adressen on Adressen.AdressenNr = Temp.KundenNr
	  inner join Kunden on Kunden.KundenNr = Temp.KundenNr 
	  where isnull(Kunden.Abfertigungsverbot, 0) = 0 and Adressen.Auswahl = 'A'"

            selectString = "Kunden.KundenNr, OffertenNr"

        End If

        Dim sqlStringFehlendeOffertenNr = "select " & selectString & " from (select KundenNr, OffertenNr from Offertenpositionen where OffertenNr = " & OffertenNr & "
                                            GROUP by KundenNr, OffertenNr
                                            EXCEPT 
                                            select KundenNr, OffertenNr from Offertenpositionen where LeistungsNr = " & LeistungsNr & " and OffertenNr = " & OffertenNr & " 
                                            GROUP by KundenNr, OffertenNr) as Temp " & sqlWhere

        Dim dtfehlendeOfferten As DataTable = (New SQL).loadDgvBySql(sqlStringFehlendeOffertenNr, "FMZOLL")
        If dtfehlendeOfferten.Rows.Count > 0 Then

            Select Case MsgBox("Es fehlen bei " & dtfehlendeOfferten.Rows.Count & IIf(cbxNurAktiveKunen.Checked, " aktiven", "") & " Kunden im Offert " & OffertenNr & " die LeistungsNr " & LeistungsNr & "!" & vbNewLine & "Soll diese eingefügt werden??", vbYesNoCancel)
                Case vbYes
                Case vbNo : dtfehlendeOfferten.Clear()
                Case Else : dtfehlendeOfferten.Clear()
            End Select
        End If

        Return dtfehlendeOfferten


    End Function

    Private Function checkStandardOffert(StandardOffert As cStandardofferten) As Boolean
        If StandardOffert.BerechnungsartNr Is Nothing Then

            If txtBerechnungsart.Text <> "" AndAlso IsNumeric(txtBerechnungsart.Text) AndAlso txtBerechnungsart.Text.Length = 1 Then
                StandardOffert.BerechnungsartNr = txtBerechnungsart.Text
                Return True
            Else
                Return False
            End If

        Else
            Return True

        End If
    End Function

    Private Function insertOfferenPositionen(StandardOffert As cStandardofferten)

        Dim sqlWhere = ""
        If cbxNurAktiveKunen.Checked Then
            sqlWhere = "  inner join Adressen on Adressen.AdressenNr = Temp.KundenNr
	  inner join Kunden on Kunden.KundenNr = Temp.KundenNr 
	  where isnull(Kunden.Abfertigungsverbot, 0) = 0 and Adressen.Auswahl = 'A'"

        End If

        Dim sqlstr_select As String = "SELECT 
        Temp.KundenNr,
        Temp.OffertenNr,

        " & SQLSafe(StandardOffert.LeistungsNr) & " AS LeistungsNr,
        " & SQLSafe(StandardOffert.LeistungsBez) & " AS LeistungsBez,
        " & SQLSafe(StandardOffert.BerechnungsartNr) & " AS BerechnungsartNr,
        " & SQLSafe(StandardOffert.Preis) & " AS Preis,
        " & SQLSafe(StandardOffert.Anzahl) & " AS Anzahl,
        " & SQLSafe(StandardOffert.BGebLeistungsNr) & " AS BGebLeistungsNr,
        " & SQLSafe(StandardOffert.BGebProzent) & " AS BGebProzent,
        " & SQLSafe(StandardOffert.BGebMinBetrag) & " AS BGebMinBetrag,

        GETDATE() AS [Eingegeben am],
        GETDATE() AS [Geändert am],

        'AUTO-IMPORT' AS Sachbearbeiter,
        NULL AS Preisänderung,
        NULL AS PreisänderungProzent,
        NULL AS PreisAlt,

        " & SQLSafe(StandardOffert.BerechnungsartPosInkludiert) & " AS BerechnungsartPosInkludiert,

        NULL AS MDM_Land,
        NULL AS MDM_VZ,
        NULL AS MDM_RMC,
        NULL AS MDM_Fremd,
        NULL AS MDM_Preisstaffel

         FROM (
        SELECT KundenNr, OffertenNr
        FROM Offertenpositionen
        WHERE OffertenNr =  " & SQLSafe(StandardOffert.OffertenNr) & "
        GROUP BY KundenNr, OffertenNr

        EXCEPT

        SELECT KundenNr, OffertenNr
        FROM Offertenpositionen
        WHERE LeistungsNr = " & SQLSafe(StandardOffert.LeistungsNr) & "
          AND OffertenNr = " & SQLSafe(StandardOffert.OffertenNr) & "
        GROUP BY KundenNr, OffertenNr
 ) AS Temp " & sqlWhere


        Dim dt As DataTable = (New SQL).loadDgvBySql_Param(sqlstr_select, "FMZOLL")

        Dim updated As Boolean = False

        If dt.Rows.Count > 0 Then


            Dim InsertSatement As String = " INSERT INTO Offertenpositionen
                                                    (
                                                   [KundenNr]
                                                  ,[OffertenNr]
                                                  ,[LeistungsNr]
                                                  ,[LeistungsBez]
                                                  ,[BerechnungsartNr]
                                                  ,[Preis]
                                                  ,[Anzahl]
                                                  ,[BGebLeistungsNr]
                                                  ,[BGebProzent]
                                                  ,[BGebMinBetrag]
                                                  ,[Eingegeben am]
                                                  ,[Geändert am]
                                                  ,[Sachbearbeiter]
                                                  ,[Preisänderung]
                                                  ,[PreisänderungProzent]
                                                  ,[PreisAlt]
                                                  ,[BerechnungsartPosInkludiert]
                                                  ,[MDM_Land]
                                                  ,[MDM_VZ]
                                                  ,[MDM_RMC]
                                                  ,[MDM_Fremd]
                                                  ,[MDM_Preisstaffel]
	                                                )"

            If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then

                updated = (New SQL).doSQL(InsertSatement & sqlstr_select, "FMZOLL",,,, 500)


            End If
        End If

        Return updated


    End Function

    Private Function SQLSafe(value As Object, Optional defaultValue As Object = Nothing) As String
        If value Is Nothing OrElse IsDBNull(value) Then
            If defaultValue Is Nothing Then Return "NULL"
            Return defaultValue.ToString()
        End If

        If TypeOf value Is String Then
            Return "'" & value.ToString().Replace("'", "''") & "'"
        End If

        If TypeOf value Is Boolean Then
            Return If(CBool(value), "1", "0")
        End If

        Return value.ToString().Replace(",", ".")
    End Function



    Private Sub cbxOffertenNr_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbxOffertenNr.SelectedIndexChanged
        If cbxOffertenNr._value <> "" AndAlso IsNumeric(cbxOffertenNr._value) Then
            txtOfferenNr.Text = cbxOffertenNr.SelectedItem.text
            cbxLeistungNr.fillWithSQL("SELECT [LeistungsNr],[LeistungsBez]  FROM [Standardofferten] where OffertenNr = " & cbxOffertenNr._value, False, "FMZOLL", True)
        Else
            txtOfferenNr.Text = ""
        End If
    End Sub

    Private Sub cbxLeistungNr_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbxLeistungNr.SelectedIndexChanged
        If cbxLeistungNr._value <> "" AndAlso IsNumeric(cbxLeistungNr._value) Then
            txtLeistungsNr.Text = cbxLeistungNr.SelectedItem.text
        Else
            txtLeistungsNr.Text = ""
        End If
    End Sub
End Class
