Imports System.IO
Imports System.Net
Imports System.Text
Imports System.Text.RegularExpressions
Imports System.Web
Imports System.Xml
Imports Renci.SshNet
Imports Renci.SshNet.Sftp
Imports VERAG_PROG_ALLGEMEIN

Public Class frmNachrichtenVerarbeitung_MDM_divers
    Dim cntDatenEingelesen As Integer = 0
    Dim dsNichtErkannt As Integer = 0
    Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
    Dim allowClose = False
    Dim deleteFilesAfterDownload = False
    Dim renameFilesAfterDownload = False
    Dim enableEinlesen = True
    Dim rmc As New cRMC
    Dim uta As New cUTA
    Dim ids As New cIDS
    Dim mse As New cMSEAPI("MSE")
    Dim programName As String
    Dim Dateiname = ""
    Public year As Integer
    Public UtaTestkunden As Boolean = False
    Public RMCNewFormat As Boolean = True


    Sub New(programName As String)

        ' Dieser Aufruf ist für den Designer erforderlich.
        InitializeComponent()
        Me.programName = programName

        ' Fügen Sie Initialisierungen nach dem InitializeComponent()-Aufruf hinzu.

    End Sub
    Sub New(programName As String, allowClose As Boolean, deleteFilesAfterDownload As Boolean, renameFilesAfterDownload As Boolean, Optional enableEinlesen As Boolean = True) 'autostart

        ' Dieser Aufruf ist für den Designer erforderlich.
        InitializeComponent()
        Me.programName = programName
        Me.allowClose = allowClose
        Me.deleteFilesAfterDownload = deleteFilesAfterDownload
        Me.renameFilesAfterDownload = renameFilesAfterDownload
        Me.enableEinlesen = enableEinlesen
        ' Fügen Sie Initialisierungen nach dem InitializeComponent()-Aufruf hinzu.

    End Sub

    Private Sub frmDYNachrichtenVerarbeitung_Load(sender As Object, e As EventArgs) Handles Me.Load

        ListBox3.Items.Clear()
        Me.Refresh()

        btnEinlesen.Enabled = enableEinlesen

        lblFTP.Text = programName

        If programName.Contains("RMC") Then
            rmc.initImportPfade(programName)
            setButtons(Not rmc.VERARBEITUNG_PFAD = "")
            setButtons(Not rmc.ZIEL_PFAD = "")
            If rmc.VERARBEITUNG_PFAD = "" Then Exit Sub
            If rmc.ZIEL_PFAD = "" Then Exit Sub
            For Each d In System.IO.Directory.GetFiles(rmc.VERARBEITUNG_PFAD)
                ListBox3.Items.Add(frmStartOptions.cut_file(d))
                Me.Refresh()
            Next
        ElseIf programName.Contains("UTA") Then
            uta.initImportPfade(programName)
            setButtons(Not uta.VERARBEITUNG_PFAD = "")
            setButtons(Not uta.ZIEL_PFAD = "")
            If uta.VERARBEITUNG_PFAD = "" Then Exit Sub
            If uta.ZIEL_PFAD = "" Then Exit Sub
            For Each d In System.IO.Directory.GetFiles(uta.VERARBEITUNG_PFAD)
                ListBox3.Items.Add(frmStartOptions.cut_file(d))
                Me.Refresh()
            Next
        ElseIf programName.Contains("IDS") Then
            ids.initImportPfade(programName)
            setButtons(Not ids.VERARBEITUNG_PFAD = "")
            setButtons(Not ids.ZIEL_PFAD = "")
            If ids.VERARBEITUNG_PFAD = "" Then Exit Sub
            If ids.ZIEL_PFAD = "" Then Exit Sub
            For Each d In System.IO.Directory.GetFiles(ids.VERARBEITUNG_PFAD)
                ListBox3.Items.Add(frmStartOptions.cut_file(d))
                Me.Refresh()
            Next

        ElseIf programName.Contains("MSE") Then
            If mse.PDFRECHNUNGENPFAD_VERARBEITUNG = "" Then Exit Sub
            For Each d In System.IO.Directory.GetFiles(mse.PDFRECHNUNGENPFAD_VERARBEITUNG)
                ListBox3.Items.Add(frmStartOptions.cut_file(d))
                Me.Refresh()
            Next

        End If

    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles btnEinlesen.Click
        Me.Enabled = False
        Try
            Label9.Visible = True
            Dim cnt = getNachrichtenDaten()
            Label9.Text = cnt & " Datensätze empfangen."

        Catch ex As System.Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace & vbNewLine & "Datei: " & Dateiname, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try
        Me.Enabled = True

    End Sub
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnEinarbeiten.Click

        If programName.Contains("IDS") Then
            If Not vbYes = MsgBox("Wurde der Batch-Jop für die Erstellung der COPY_INVOICE manuell ausgeführt?", vbYesNoCancel) Then
                Exit Sub
            End If

        End If

        Me.Enabled = False
        Try
            Label5.Visible = True
            DatenEinlesen()
            If dsNichtErkannt > 0 Then

                Label6.Text = dsNichtErkannt & " Datensätze nicht " & vbNewLine & "erkannt."
                Label6.Visible = True
            End If
        Catch ex As System.Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace & vbNewLine & "Datei: " & Dateiname, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try
        Me.Enabled = True
        Label5.Text = cntDatenEingelesen & " Datensätze verarbeitet."

    End Sub


    Function getNachrichtenDaten() As Integer
        Dim cnt = 0
        Try
            If programName.Contains("RMC") Then
                DownloadFtpDirectory(rmc.API_STRING & "/", New NetworkCredential(rmc.API.Rows(0).Item("api_user").ToString, rmc.API.Rows(0).Item("api_password").ToString), "", cnt, deleteFilesAfterDownload)
            ElseIf programName.Contains("UTA") Then
                DownloadSFtpDirectory(uta.API_STRING, New NetworkCredential(uta.API.Rows(0).Item("api_user").ToString, uta.API.Rows(0).Item("api_password").ToString), "", cnt, deleteFilesAfterDownload, "/TRX/" & year, renameFilesAfterDownload)
            ElseIf programName.Contains("IDS") Then
                DownloadSFtpDirectory(ids.API_STRING, New NetworkCredential(ids.API.Rows(0).Item("api_user").ToString, ids.API.Rows(0).Item("api_password").ToString), "", cnt, deleteFilesAfterDownload, "/IN/ALL", renameFilesAfterDownload)
            End If


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

        Return cnt
    End Function


    Sub DownloadFtpDirectory(url As String, credentials As NetworkCredential, localPath As String, ByRef cnt As Integer, deleteAfterDownload As Boolean)
        Dim listRequest As FtpWebRequest = WebRequest.Create(url)
        listRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails
        listRequest.Credentials = credentials

        Dim verarbeitungspfad = ""

        If programName.Contains("RMC") Then
            verarbeitungspfad = rmc.VERARBEITUNG_PFAD
        ElseIf programName.Contains("UTA") Then
            verarbeitungspfad = uta.VERARBEITUNG_PFAD
        End If

        Dim lines As List(Of String) = New List(Of String)

        Using listResponse As FtpWebResponse = listRequest.GetResponse(),
          listStream As Stream = listResponse.GetResponseStream(),
          listReader As StreamReader = New StreamReader(listStream)

            While Not listReader.EndOfStream
                lines.Add(listReader.ReadLine())
            End While
        End Using

        For Each line As String In lines
            Dim tokens As String() =
            line.Split(New Char() {" "}, 9, StringSplitOptions.RemoveEmptyEntries)
            Dim name As String = HttpUtility.UrlEncode(tokens(8)) 'tokens(8) 'handle special characters within filename!
            Dim permissions As String = tokens(0)

            Dim localFilePath As String = Path.Combine(localPath, name)
            Dim fileUrl As String = url + name


            If permissions(0) <> "d" Then 'in keine Unterorder suchen, nur die erste Ebene

                Dim downloadRequest As FtpWebRequest = WebRequest.Create(fileUrl)
                downloadRequest.Method = WebRequestMethods.Ftp.DownloadFile
                downloadRequest.Credentials = credentials

                ' Dim fileDateTmp As Date = ServerDateFile(credentials, fileUrl)
                'name = name.Replace(".csv", "_RGDAT_" & Now.ToShortDateString & ".csv")

                Dim destFilenameTMP = verarbeitungspfad
                If System.IO.File.Exists(verarbeitungspfad & name) Then
                    Dim fi As FileInfo = New FileInfo(verarbeitungspfad & name)
                    destFilenameTMP &= name.Replace(fi.Extension, "_") & Now.ToString("yyMMdd_HHmmss.fff") & fi.Extension
                Else
                    destFilenameTMP &= name

                End If

                Try


                    Using downloadResponse As FtpWebResponse = downloadRequest.GetResponse(),
                          sourceStream As Stream = downloadResponse.GetResponseStream(),
                          targetStream As Stream = File.OpenWrite(destFilenameTMP)
                        Dim buffer As Byte() = New Byte(10240 - 1) {}
                        Dim read As Integer
                        Do
                            read = sourceStream.Read(buffer, 0, buffer.Length)
                            If read > 0 Then
                                targetStream.Write(buffer, 0, read)
                            End If
                        Loop While read > 0

                        sourceStream.Dispose()
                        targetStream.Dispose()
                        downloadResponse.Dispose()

                        'Dim destFilename = verarbeitungspfad & If(IO.File.Exists(verarbeitungspfad & name), name.Replace(".csv", "_") & Now.ToString("yyMMdd_HHmmss.fff") & ".csv", name)

                        'IO.File.Move(destFilenameTMP, destFilename) 'Datei umbenennen


                        Dim fi As FileInfo = New FileInfo(destFilenameTMP)
                        ListBox3.Items.Add(frmStartOptions.cut_file(fi.Name)) 'zur Liste hinzufügen
                        cnt += 1


                        'Datei nach download löschen
                        If deleteAfterDownload Then
                            Dim ftpReq As FtpWebRequest = WebRequest.Create(fileUrl)
                            ftpReq.Method = WebRequestMethods.Ftp.DeleteFile
                            ftpReq.Credentials = credentials
                            Dim ftpResp As FtpWebResponse = ftpReq.GetResponse
                            ftpResp.Close()
                        End If

                    End Using
                Catch ex As System.Exception

                End Try
            End If
            'End If
        Next
    End Sub
    Function DownloadSFtpDirectory(url As String, credentials As NetworkCredential, localPath As String, ByRef cnt As Integer, deleteAfterDownload As Boolean, Path As String, renameAfterDownload As Boolean) As Integer


        Dim ConnectionInfo As New ConnectionInfo(url, "22", credentials.UserName, New PasswordAuthenticationMethod(credentials.UserName, credentials.Password))
        Using client = New SftpClient(ConnectionInfo)
            client.Connect()

            Dim files = client.ListDirectory(Path).OrderBy(Function(file) file.LastAccessTime).Reverse

            Dim targetFile As SftpFile

            For Each file As SftpFile In files

                'If file.IsRegularFile AndAlso file.Name.ToLower.EndsWith(".uta") AndAlso file.Length > 0 AndAlso IIf(renameAfterDownload, Not file.Name.ToLower.StartsWith("_"), True) Then

                If file.IsRegularFile AndAlso file.Name.ToLower.EndsWith(IIf(programName.Contains("UTA"), ".uta", ".pdf")) AndAlso file.Length > 0 AndAlso IIf(renameAfterDownload, Not file.Name.ToLower.StartsWith("_"), Not file.Name.ToLower.StartsWith("_")) Then

                    Dim remoteFileName = "/" & file.Name
                    Dim filePath = ""

                    If programName.Contains("UTA") Then
                        filePath = uta.VERARBEITUNG_PFAD & IIf(System.IO.File.Exists(uta.VERARBEITUNG_PFAD & file.Name), file.Name.Replace(".UTA", "_") & Now.ToString("yyMMdd_HHmmss.fff") & ".UTA", file.Name)
                    ElseIf programName.Contains("IDS") Then
                        filePath = ids.VERARBEITUNG_PFAD & IIf(System.IO.File.Exists(ids.VERARBEITUNG_PFAD & file.Name), file.Name.Replace(".pdf", "_") & Now.ToString("yyMMdd_HHmmss.fff") & ".pdf", file.Name)
                    End If

                    Dim downloadedFile As Stream = System.IO.File.Create(filePath)

                    client.DownloadFile(Path + remoteFileName, downloadedFile)

                    If System.IO.File.Exists(filePath) AndAlso deleteAfterDownload Then

                        client.DeleteFile(Path + remoteFileName) 'Datei nach erfolgreichem Herunterladen vom Server löschen

                    End If

                    If System.IO.File.Exists(filePath) AndAlso Not deleteAfterDownload And renameAfterDownload Then

                        Try

                            Dim remoteFileNameRenamed = "/_" & file.Name
                            client.RenameFile(Path + remoteFileName, Path + remoteFileNameRenamed) 'verarbeitete Datei kennzeichnen mit beginnenden "_"

                        Catch ex As Exception
                        End Try

                    End If

                    downloadedFile.Dispose()

                    Dim fi As FileInfo = New FileInfo(filePath)
                    If fi.Extension.ToLower = ".uta" AndAlso programName.Contains("UTA") Or fi.Extension.ToLower = ".pdf" AndAlso programName.Contains("IDS") Then
                        ListBox3.Items.Add(frmStartOptions.cut_file(fi.Name)) 'zur Liste hinzufügen
                        cnt += 1
                    End If
                End If
            Next

        End Using

    End Function

    Private Function createIDSInvoice(Dateiname As String, Type As String, Optional isMail As Boolean = False, Optional isNewFormat As Boolean = False)

        Dim Zielpfad = ids.VERARBEITUNG_PFAD
        Dim customerNo = ""
        Dim invoiceNo = ""
        Dim country = ""
        Dim dateNo = ""
        Dim outputDate = ""
        Dim customerString = "customer"
        Dim InvoiceString = "invoice"
        Dim dateString = "from"
        Dim filename = ""

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

        If Dateiname.Contains(InvoiceString) Then
            invoiceNo = Dateiname.Substring(Dateiname.IndexOf(InvoiceString) + InvoiceString.Length, 10)
        Else
            Select Case Type
                Case "INVOICE"
                    invoiceNo = Dateiname.Substring(Dateiname.LastIndexOf("_") + 1, 10)

                Case "INVOICEBYCOUNTRY"

                    Dim i1 = Dateiname.LastIndexOf(".pdf")
                    Dim i2 = Dateiname.LastIndexOf("_") + 1

                    'die RechnungNr steht nun nicht mehr am Ende, sondern an vorletzter Position!!!
                    '0060003421_31072025_GEOB00018288RO_DE00725749.pdf
                    Dim underscoreIndexes As New List(Of Integer)
                    For i As Integer = 0 To Dateiname.Length - 1
                        If Dateiname(i) = "_"c Then
                            underscoreIndexes.Add(i)
                        End If
                    Next

                    Dim invoiceNo_New As String = ""

                    If underscoreIndexes.Count >= 2 Then
                        ' Position des vorletzten Unterstrichs
                        Dim secondLastUnderscore As Integer = underscoreIndexes(underscoreIndexes.Count - 2)
                        ' Substring ab vorletztem Unterstrich bis Ende
                        invoiceNo_New = Dateiname.Substring(secondLastUnderscore + 1, ((i2 - 1) - (secondLastUnderscore + 1)))
                    End If

                    If invoiceNo_New <> "" Then
                        invoiceNo = invoiceNo_New
                        country = invoiceNo_New.Substring(0, 2)
                    Else
                        invoiceNo = Dateiname.Substring(Dateiname.LastIndexOf("_") + 1, (Dateiname.LastIndexOf(".pdf") - (Dateiname.LastIndexOf("_") + 1)))
                        country = Dateiname.Substring(Dateiname.LastIndexOf("_"), 2)

                    End If

                    If IsNumeric(country) Then
                        country = "SE" 'wenn kein Land angegeben, dann SCHWEDEN!

                    ElseIf country = "IG" Or country = "GE" Then 'wenn mit IG oder mit GE startet, dann steht das Land am Ende
                        If invoiceNo.Length > 2 Then
                            Dim invEndung As String = ""
                            invEndung = invoiceNo.ToString.Substring(invoiceNo.Length - 2, 2)

                            If invEndung <> "" Then

                                If IsNumeric(invEndung) Then 'wenn am ENde kein Land, dann IT
                                    country = "IT"
                                Else

                                    Select Case invEndung
                                        Case "SP" : country = "ES" 'SPANIEN
                                        Case "DA" : country = "DK" 'DÄNEMARK
                                        'Case "P1" : country = "PL" 'POLEN
                                        Case "FT" : country = "PT" 'PORTUGAL
                                        Case Else
                                            country = invEndung

                                    End Select
                                End If
                            End If
                        End If

                    End If


            End Select

        End If
        If Not isNewFormat Then
            If Dateiname.Contains(dateString) Then
                dateNo = Dateiname.Substring(Dateiname.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")
            Else
                dateNo = Dateiname.Substring(Dateiname.IndexOf("_") + 1, 8)
                Dim parsedDate As DateTime = DateTime.ParseExact(dateNo, "ddMMyyyy", System.Globalization.CultureInfo.InvariantCulture)
                outputDate = parsedDate.ToString("dd.MM.yyyy")
            End If
        Else
            'wenns in der Bezeichnung fehlt (bei New Format), heutiges Datum annehmen!
            outputDate = Today.ToString("dd.MM.yyyy")

        End If


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

            Select Case Type
                Case "INVOICE"


                    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

                        If Not isMail Then idsInvoice.DocumentName = Dateiname
                        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


                Case "INVOICEBYCOUNTRY"


                    Dim idsInvoice As New cIDSInvoiceSplittedByCountry(outputDate, customerNo, invoiceNo, country)
                    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

                        If Not isMail Then idsInvoice.DocumentName = Dateiname
                        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 Select


        End If



    End Function





    Private Function ServerDateFile(credentials As NetworkCredential, fileUrl As String) As Date
        Dim ServerDate As DateTime
        Try
            Dim request As FtpWebRequest = WebRequest.Create(fileUrl)
            request.Method = WebRequestMethods.Ftp.GetDateTimestamp
            request.Credentials = credentials

            Using response = CType(request.GetResponse(), Net.FtpWebResponse)
                ServerDate = response.LastModified.ToShortDateString
            End Using

            Return ServerDate
        Catch ex As WebException
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace & vbNewLine & programName & " GET DATE FILE: " & Dateiname, System.Reflection.MethodInfo.GetCurrentMethod.Name)
            Return Now
        End Try

        Return ServerDate
    End Function

    Sub DatenEinlesen()

        VERAG_PROG_ALLGEMEIN.cAllgemein.ERR_OP_GLOBAL = VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL

        If ListBox3.Items.Count = 0 Then
            Label6.Text = "Keine Daten zum Einlesen vorhanden."
            Label6.Visible = True
            Exit Sub
        End If

        Dim dt As New DataTable
        Dim loopInt As Int16 = 2
        Dim deleteTable As Boolean = False
        Dim verarbeitungspfad, zielpfad
        If programName.Contains("RMC") Then
            verarbeitungspfad = rmc.VERARBEITUNG_PFAD
            zielpfad = rmc.ZIEL_PFAD
            loopInt = 3

            dt.Columns.Add("KundenNr", GetType(String))
            dt.Columns.Add("UID", GetType(String))

        ElseIf programName.Contains("UTA") Then
            verarbeitungspfad = uta.VERARBEITUNG_PFAD
            zielpfad = uta.ZIEL_PFAD
        ElseIf programName.Contains("IDS") Then
            verarbeitungspfad = ids.VERARBEITUNG_PFAD
            zielpfad = ids.ZIEL_PFAD
        ElseIf programName.Contains("MSE") Then
            verarbeitungspfad = mse.PDFRECHNUNGENPFAD_VERARBEITUNG
            zielpfad = mse.PDFRECHNUNGENPFAD_VERARBEITUNG_ZIEL
        End If

        For i = 1 To loopInt

            For Each d In System.IO.Directory.GetFiles(verarbeitungspfad)
                Try
                    Dateiname = d
                    If System.IO.File.Exists(d) Then
                        Dim found = False
                        Dim fi As FileInfo = New FileInfo(d)

                        Dim alreadyMoved = False

                        If programName.Contains("RMC") Then

                            Select Case i

                                Case 1
                                    '------------------------------------------
                                    '------------------ CSV ------------------
                                    '------------------------------------------
                                    If fi.Extension.ToLower = ".csv" Then

                                        If Not found Then
                                            If readRMC(d, programName) <> "" Then found = True
                                        End If
                                        If found Then cntDatenEingelesen += 1
                                    End If
                                Case 2

                                    '------------------------------------------
                                    '------------------ PDF ------------------
                                    '------------------------------------------
                                    If fi.Extension.ToLower = ".pdf" Then

                                        found = False

                                        If Not System.IO.Directory.Exists(zielpfad & "Invoice_PDF\" & Now.Year & "\" & Now.ToString("yyyyMMdd") & "\") Then System.IO.Directory.CreateDirectory(zielpfad & Now.Year & "\" & Now.ToString("yyyyMMdd") & "\")

                                        'File in Datenarchiv sichern:
                                        'd.breimaier: 2024-06-05 aktuell nur die RMC-Dateien! (später, wenn CSV vollständig, dann alle PDFs importieren!
                                        'd.breimaier: 2024-06-17 laut Christian Schuster von Comcore (EDV-BEtr. von RMC) nicht möglich CSV mit easytrip und sofico Datensätzen zu ergängen!
                                        'd.breimaier: 2025-09-15 laut Christian Schuster erhalten wir nun die Rechnungen mit folgenden Aufbau:

                                        '•	    fixwert invoice
                                        '•	    Kundennummer 26807 (in der CSV enthalten)
                                        '•	    Abrechnungnummer 5549 (Stimmt mit der Abrechnungsnummer im Dateinamen der CSV überein)
                                        '•	    RechnungsNr "262014347" (in der CSV enthalten) - nicht verwechseln mit RechngsNrSL
                                        '•	    Das Land AT, DE, FR...
                                        '•	    zuletzt steht orig. Das ist für euch nicht wichtig, bedeutet nur das ist das Original und keine Kopie

                                        'easytrip-Rechnungen sind immer ITALIEN!

                                        Dim fileNamePath As String = d

                                        If RMCNewFormat Then

                                            Dim destFilename As String = fi.FullName

                                            If Not destFilename.Contains("_nto") AndAlso Not destFilename.Contains("_bto") Then 'verhindert eine mehrfache umbenennung.

                                                destFilename = destFilename.Replace(".pdf", IIf(programName.ToLower.Contains("nto"), "_nto", "_bto") & ".pdf")

                                                System.IO.File.Move(fi.FullName, destFilename) 'Datei umbenennen

                                                fileNamePath = destFilename
                                            End If


                                        End If

                                        If fi.Name.ToString.StartsWith("invoice_") OrElse (fi.Name.ToString.StartsWith("maut_") AndAlso fi.Name.ToString.Contains("EGR") AndAlso Not fi.Name.ToString.Contains("ALL")) Then 'RMC Eigenrechnungen

                                            If fi.Name.ToString.StartsWith("invoice_") Then

                                                Dim DS As New VERAG_PROG_ALLGEMEIN.cDATENSERVER("MDM", "MDM_DATEN", "RMC", Now.Year, Now.ToString("yyyyMMdd"), frmStartOptions.getFileName(fileNamePath))

                                                DS.uploadDataToDATENSERVER(fileNamePath,,,,,, True)

                                                SQL.doSQL("Update [tblRMCImport] SET [rmc_daId]='" & DS.da_id & "' where [rmc_pdfFileName] = '" & DS.da_name & "' and [rmc_importDatum] > DATEADD(DAY,-4,getdate())  ", "FMZOLL")

                                                frmStartOptions.moveFile_DateBack(fileNamePath, zielpfad & "Invoice_PDF\" & Now.Year & "\" & Now.ToString("yyyyMMdd") & "\")
                                                If fi.Name.ToLower.Contains("pdf") Then addDGVEinarbeitung("PDF", fi.Name)
                                                dgvEinarbeitung.Refresh()
                                                found = True
                                            ElseIf (fi.Name.ToString.StartsWith("maut_") AndAlso fi.Name.ToString.Contains("EGR") AndAlso Not fi.Name.ToString.Contains("ALL")) Then 'EasyTrip IT Rechnungen

                                                Dim DS As New VERAG_PROG_ALLGEMEIN.cDATENSERVER("MDM", "MDM_DATEN", "RMC", Now.Year, Now.ToString("yyyyMMdd"), frmStartOptions.getFileName(fileNamePath))

                                                DS.uploadDataToDATENSERVER(fileNamePath,,,,,, True)

                                                'EasyTrip sollen mit der Pos-Liste gemerged werden!!!

                                                Dim fileNameEasyTrip As String = fi.Name

                                                fileNameEasyTrip = fileNameEasyTrip.Replace("maut_", "")
                                                fileNameEasyTrip = fileNameEasyTrip.Replace("EGR_con", "")

                                                'maut_24952_EGR_con00079883FITFIT2002A25-07993920250908120506AT70DE_341929194_.pdf

                                                '24952_00079883FITFIT2002A25-07993920250908120506AT70DE_341929194_.pdf

                                                'RechnungNr: FIT2002A25-079939
                                                'Datum: 08/09/2025
                                                'Land: IT
                                                'VAT: DE_341929194

                                                Dim indexOfFIT = fileNameEasyTrip.LastIndexOf("FITFIT") + 3

                                                Dim kdNr As String = fileNameEasyTrip.Substring(0, 5)
                                                Dim invoiceNo As String = "" 'FIT2002A25-079939
                                                Dim invoiceDate As String = "" '20250908
                                                Dim UID As String = "" 'DE_341929194X

                                                Dim RMC As New cRMC() 'easytry über Filename anlegen!

                                                invoiceNo = fileNameEasyTrip.Substring(indexOfFIT, 17)
                                                invoiceDate = fileNameEasyTrip.Substring(indexOfFIT + 17, 8)
                                                Dim parsedDate As DateTime = DateTime.ParseExact(invoiceDate, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture)

                                                UID = fileNameEasyTrip.Substring(fileNameEasyTrip.IndexOf("AT70") + 4, 13)
                                                UID = UID.Replace("_", "")

                                                RMC.rmc_reDatum = parsedDate.ToString("dd.MM.yyyy")
                                                RMC.rmc_importDatum = Now()
                                                RMC.rmc_kdNr = kdNr
                                                RMC.rmc_UID = UID
                                                RMC.rmc_landKZ = "IT"
                                                RMC.rmc_landBezeichnung = "Italien"
                                                RMC.rmc_reDatum = parsedDate
                                                RMC.rmc_reNr = invoiceNo
                                                RMC.rmc_waehrung = "EUR"
                                                RMC.rmc_daId = DS.da_id
                                                RMC.rmc_pdfFileName = fi.Name

                                                'EasyTrip können die Beträge initial nicht ausgelesen werden, dürfen aber nicht 0 sein!

                                                RMC.rmc_betragBrutto = 0.01
                                                RMC.rmc_betragMWST = 0.01
                                                RMC.rmc_betragNetto = 0.01
                                                RMC.rmc_euroBrutto = 0.01


                                                If RMC.SAVE() Then


                                                    Dim adress As New VERAG_PROG_ALLGEMEIN.cAdressen(RMC.rmc_UID, RMC.rmc_kdNr, True)
                                                    If Not adress.hasEntry Then
                                                        Dim R As DataRow = dt.NewRow
                                                        R("KundenNr") = RMC.rmc_kdNr
                                                        R("UID") = RMC.rmc_UID
                                                        dt.Rows.Add(R)
                                                    End If

                                                End If

                                                frmStartOptions.moveFile_DateBack(fileNamePath, zielpfad & "Invoice_PDF\" & Now.Year & "\" & Now.ToString("yyyyMMdd") & "\")
                                                If fi.Name.ToLower.Contains("pdf") Then addDGVEinarbeitung("PDF", fi.Name)
                                                dgvEinarbeitung.Refresh()
                                                found = True

                                            End If

                                        End If

                                        'copy file to lydia - nicht mehr notwendig!!!
                                        'If Not VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM Then
                                        '    Dim filepathToLydia = IIf(rmc.PDFRECHNUNGEN <> "", rmc.PDFRECHNUNGEN, "\\share01\F\Juricevic Datensicherung\RMC_RECHNUNGEN\")
                                        '    If fileNamePath.ToString.ToLower.Contains("nto") Then
                                        '        frmStartOptions.copyFile(fileNamePath, filepathToLydia & "NETTO\")
                                        '    Else
                                        '        frmStartOptions.copyFile(fileNamePath, filepathToLydia & "BRUTTO\")
                                        '    End If
                                        'End If



                                    End If

                                Case 3

                                    If (fi.Name.ToString.StartsWith("maut_") AndAlso fi.Name.ToString.Contains("EGR") AndAlso fi.Name.ToString.Contains("ALL")) Then

                                        Dim fileNamePath As String = d



                                        Dim fileNameEasyTrip As String = fi.Name

                                        fileNameEasyTrip = fileNameEasyTrip.Replace("maut_", "")
                                        fileNameEasyTrip = fileNameEasyTrip.Replace("EGR_con", "")

                                        Dim indexOfFIT = fileNameEasyTrip.LastIndexOf("FITFIT") + 3

                                        Dim kdNr As String = fileNameEasyTrip.Substring(0, 5)
                                        Dim invoiceNo As String = "" 'FIT2002A25-079939
                                        Dim invoiceDate As String = "" '20250908

                                        invoiceNo = fileNameEasyTrip.Substring(indexOfFIT, 17)
                                        invoiceDate = fileNameEasyTrip.Substring(indexOfFIT + 17, 8)
                                        Dim parsedDate As DateTime = DateTime.ParseExact(invoiceDate, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture)

                                        Dim RMC As New cRMC(kdNr, invoiceNo, parsedDate.ToString("dd.MM.yyyy")) 'easytry über Filename anlegen!
                                        If RMC.hasEntry AndAlso RMC.rmc_daId_InvAtt Is Nothing Then

                                            Dim DS As New VERAG_PROG_ALLGEMEIN.cDATENSERVER("MDM", "MDM_DATEN", "RMC_ATT", Now.Year, Now.ToString("yyyyMMdd"), frmStartOptions.getFileName(fileNamePath))
                                            DS.uploadDataToDATENSERVER(fileNamePath,,,,,, True)
                                            RMC.rmc_daId_InvAtt = DS.da_id
                                            RMC.SAVE()
                                        End If

                                        frmStartOptions.moveFile_DateBack(fileNamePath, zielpfad & "Invoice_PDF\" & Now.Year & "\" & Now.ToString("yyyyMMdd") & "\")
                                        If fi.Name.ToLower.Contains("pdf") Then addDGVEinarbeitung("PDF", fi.Name)
                                        dgvEinarbeitung.Refresh()
                                        found = True
                                    End If



                            End Select


                        ElseIf programName.Contains("UTA") Then

                            Select Case i

                                Case 1
                                    '------------------------------------------
                                    '------------------ .UTA ------------------
                                    '------------------------------------------

                                    'If Not deleteTable Then
                                    '    deleteTable = uta.clearimporttable()
                                    'End If

                                    If fi.Extension.ToLower = ".uta" Then

                                        If Not found Then

                                            If readUTA(d) <> "" Then found = True

                                        End If

                                        If found Then cntDatenEingelesen += 1
                                    End If

                                Case 2
                                    '------------------------------------------
                                    '------------------ .PDF ------------------
                                    '------------------------------------------
                                    'PDFs über EEA und Zugpfrd
                                    If fi.Extension.ToLower = ".pdf" Then

                                        If True Then 'Not System.IO.Directory.Exists(zielpfad & "Invoice_PDF\" & Now.Year & "\" & Now.ToString("yyyyMMdd") & "\") Then System.IO.Directory.CreateDirectory(zielpfad & Now.Year & "\" & Now.ToString("yyyyMMdd") & "\")

                                            If (fi.Name.ToString.StartsWith("AP") AndAlso fi.Name.ToLower.Contains("zugferd")) OrElse (fi.Name.ToString.Contains("(") AndAlso fi.Name.ToString.Contains(")") AndAlso fi.Name.ToString.Contains("_RE_")) Then 'Rechnungen per Mail oder manuelle RE!

                                                Dim DS As New VERAG_PROG_ALLGEMEIN.cDATENSERVER("MDM", "MDM_DATEN", "UTA", Now.Year, Now.ToString("yyyyMMdd"), frmStartOptions.getFileName(d))

                                                DS.uploadDataToDATENSERVER(d,,,,,, True)


                                                'zugferd-Daten aus pdf auslesen!

                                                '1 Read your PDF
                                                '2 Get the catalog inside your PDF
                                                '3 Get the Array with name AF from Catalog
                                                '4 Get first element from AF array (should be file spec)
                                                '5 From file spec get the dictionary named EF
                                                '6 Get the stream content of EF

                                                Try

                                                    Dim invoiceNr As String = ""
                                                    Dim invoiceDate As String = ""
                                                    Dim Kundenummer As Integer
                                                    Dim Abrechnungsnummer As Integer
                                                    Dim Rechnungsland As String = ""
                                                    Dim doc = New Spire.Pdf.PdfDocument()
                                                    doc.LoadFromFile(fi.FullName)

                                                    If doc.Attachments.Count > 0 Then

                                                        Dim pdfAtt = doc.Attachments(0)
                                                        If pdfAtt.FileName = "ZUGFeRD-invoice.xml" OrElse pdfAtt.FileName = "factur-x.xml" Then

                                                            Dim xmlFile = doc.Attachments(0)
                                                            Dim pathTempXMLFile = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getTMPPath(xmlFile.FileName, ".xml", False, False)
                                                            File.WriteAllBytes(pathTempXMLFile, pdfAtt.Data)

                                                            Dim docxml As New XmlDocument()
                                                            docxml.Load(New XmlTextReader(pathTempXMLFile))
                                                            If docxml.HasChildNodes Then

                                                                If docxml.GetElementsByTagName("rsm:ExchangedDocument").Count > 0 Then
                                                                    Dim count As Integer = 1
                                                                    For Each node As XmlElement In docxml.GetElementsByTagName("rsm:ExchangedDocument")
                                                                        If node.HasChildNodes Then
                                                                            For Each element As XmlElement In node.ChildNodes
                                                                                If element.Name = "ram:ID" AndAlso element.InnerText <> "" Then invoiceNr = element.InnerText 'Rechnungsnummer
                                                                                If element.Name = "ram:IssueDateTime" AndAlso element.InnerText <> "" Then invoiceDate = element.InnerText 'Rechnungsdatum

                                                                            Next

                                                                            count = count + 1

                                                                        End If
                                                                    Next

                                                                End If

                                                                If docxml.GetElementsByTagName("ram:ApplicableHeaderTradeAgreement").Count > 0 Then
                                                                    Dim count As Integer = 1
                                                                    For Each node As XmlElement In docxml.GetElementsByTagName("ram:ApplicableHeaderTradeAgreement")
                                                                        If node.HasChildNodes Then
                                                                            For Each element As XmlElement In node.ChildNodes

                                                                                If element.Name = "ram:BuyerReference" Then
                                                                                    Kundenummer = CInt(element.InnerText) 'Kundennummer
                                                                                    Exit For
                                                                                End If

                                                                            Next

                                                                            count = count + 1

                                                                        End If
                                                                    Next

                                                                End If

                                                                If docxml.GetElementsByTagName("ram:SpecifiedTradeProduct").Count > 0 Then
                                                                    Dim count As Integer = 1
                                                                    For Each node As XmlElement In docxml.GetElementsByTagName("ram:OriginTradeCountry")
                                                                        If node.HasChildNodes Then
                                                                            For Each element As XmlElement In node.ChildNodes

                                                                                If element.Name = "ram:ID" AndAlso element.InnerText <> "" Then
                                                                                    Rechnungsland = element.InnerText 'Rechnungsnummer'Kundennummer

                                                                                    Exit For
                                                                                End If

                                                                            Next

                                                                            count = count + 1

                                                                        End If
                                                                    Next

                                                                End If

                                                            End If
                                                        End If

                                                    End If

                                                    found = True
                                                    If invoiceNr <> "" AndAlso invoiceDate <> "" AndAlso Kundenummer > 0 AndAlso Rechnungsland <> "" Then

                                                        Dim parsedDate As DateTime = DateTime.ParseExact(invoiceDate, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture)
                                                        invoiceDate = parsedDate.ToString("dd.MM.yyyy")

                                                        SQL.doSQL("Update [tblUTAImportNew] SET [daId]='" & DS.da_id & "', daIdgesetztDatum = getdate()  where [Rechnungsnummer_pro_Lieferland] = '" & invoiceNr & "' AND cast(Rechnungsdatum as Date) = '" & invoiceDate & "' AND Kundennummer =" & Kundenummer & " and Lieferland_ISO2 ='" & Rechnungsland & "'  and daId is null", "FMZOLL")


                                                        '    If SQL.doSQL("Update [tblUTAImportNew] SET [daId]='" & DS.da_id & "' where [Rechnungsnummer_pro_Lieferland] = '" & invoiceNr & "' AND cast(Rechnungsdatum as Date) = '" & invoiceDate & "' AND Kundennummer =" & Kundenummer & " and Abrechnungsnummer =" & r.Item("Abrechnungsnummer") & " and daId is null ", "FMZOLL") Then
                                                        '        frmStartOptions.moveFile_DateBack(d, zielpfad & "Invoice_PDF\" & Now.Year & "\" & Now.ToString("yyyyMMdd") & "\")
                                                        '        cntDatenEingelesen += 1
                                                        '    End If
                                                    End If


                                                Catch ex As System.Exception
                                                    MsgBox(ex.StackTrace)
                                                End Try

                                            ElseIf fi.Name.ToString.StartsWith("AP") AndAlso fi.Name.ToLower.Contains("epn") Then 'nur einzelpostennachweise

                                                Dim customerNo As Integer
                                                Dim invoiceNo As String = ""
                                                Dim dateNo = ""
                                                Dim outputDate = ""
                                                Dim documenttype As String = ""


                                                If fi.Name.Length >= 37 Then
                                                    customerNo = fi.Name.Substring(2, 6)
                                                    invoiceNo = fi.Name.Substring(9, 8)
                                                    dateNo = fi.Name.Substring(18, 10)
                                                    documenttype = fi.Name.Substring(33, 3)
                                                    Dim parsedDate As DateTime = DateTime.ParseExact(dateNo, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture)
                                                    outputDate = parsedDate.ToString("dd.MM.yyyy")

                                                End If

                                                Dim DS As New VERAG_PROG_ALLGEMEIN.cDATENSERVER("MDM", "MDM_DATEN", "UTA", Now.Year, Now.ToString("yyyyMMdd"), frmStartOptions.getFileName(d))

                                                DS.uploadDataToDATENSERVER(d,,,,,, True)

                                                Dim document As New cUTA.UTADocuments
                                                document.DocumentName = fi.Name
                                                document.daId = DS.da_id
                                                document.DocumentTyp = documenttype
                                                document.RechnungsNr = invoiceNo
                                                document.KundenNr = customerNo
                                                document.Datum = outputDate
                                                document.Zeitstempel = Now()

                                                If document.SAVE() Then cntDatenEingelesen += 1
                                                frmStartOptions.moveFile_DateBack(d, zielpfad & "EPN_PDF\" & Now.Year & "\" & Now.ToString("yyyyMMdd") & "\")
                                                cntDatenEingelesen += 1

                                            End If



                                        End If
                                    End If

                                    If fi.Name.ToLower.Contains("pdf") Then addDGVEinarbeitung("PDF", fi.Name)
                                    dgvEinarbeitung.Refresh()

                            End Select


                        ElseIf programName.Contains("IDS") Then

                            Select Case i

                                Case 1
                                    '------------------------------------------
                                    '------------------ .CSV ------------------
                                    '------------------------------------------


                                    If fi.Extension.ToLower = ".csv" Then

                                        If Not found Then

                                            If readIDS(d) <> "" Then found = True

                                        End If

                                        If found Then cntDatenEingelesen += 1
                                    End If

                                Case 2
                                    '------------------------------------------
                                    '------------------ .PDF ------------------
                                    '------------------------------------------

                                    If fi.Extension.ToLower = ".pdf" Then

                                        Dim dateiname As String = fi.Name.ToString
                                        Dim cutLenght As Integer = 20
                                        Dim newFormat As Boolean = False

                                        'im alten Format!
                                        'PS = Zusammenfassung
                                        'SP = Tankungen pro Karte
                                        'OBO = Rechnungen pro Land
                                        'VATR = Rechnungen pro Land
                                        'COPY_INVOICE = alles zusammen pro Kunde!

                                        If dateiname.Contains("IV_") AndAlso dateiname.Length > cutLenght Then 'dann ist es das neue Format von IDS!!!!

                                            newFormat = True

                                            'im neuen Format!
                                            'PS = Zusammenfassung
                                            'SPEC = Tankungen pro Karte
                                            'OBO = Rechnungen pro Land
                                            'VATR = Rechnungen pro Land

                                            'COPY_INVOICE = gibt es im neuen Format nicht mehr!!!!!!!!!!!! -> sehr schlecht, muss manuell zusammengebaut werden -> per BATCH-JOB
                                            'AUFBAU der COPY_INVOICE: PS + SPEC + OBO + VATR

                                            dateiname = dateiname.Substring(cutLenght, dateiname.Length - cutLenght)

                                            If dateiname.Contains("_WP") Then dateiname = dateiname.Replace("_WP", "")
                                            If dateiname.Contains("-") Then dateiname = dateiname.Replace("-", "")

                                        End If

                                        If dateiname.StartsWith("COPY_INVOICE_") Then

                                            createIDSInvoice(dateiname.Replace("COPY_INVOICE_", ""), "INVOICE",, newFormat)

                                            Dim DS As New VERAG_PROG_ALLGEMEIN.cDATENSERVER("MDM", "MDM_DATEN", "IDS", Now.Year, Now.ToString("yyyyMMdd"), frmStartOptions.getFileName(d))

                                            If DS.uploadDataToDATENSERVER(d,,,,,, True) Then
                                                If SQL.doSQL("Update [tblIDSInvoicesNew] SET [daId]='" & DS.da_id & "' where [DocumentName] = '" & dateiname.ToString.Replace("COPY_INVOICE_", "") & "'  ", "FMZOLL") Then
                                                    frmStartOptions.moveFile_DateBack(d, zielpfad & "Invoice_PDF\" & Now.Year & "\" & Now.ToString("yyyyMMdd") & "\")
                                                    cntDatenEingelesen += 1
                                                End If
                                            End If

                                            Try

                                            Catch ex As System.Exception
                                            End Try

                                        ElseIf dateiname.StartsWith("OBO_") Then

                                            createIDSInvoice(dateiname.Replace("OBO_", ""), "INVOICEBYCOUNTRY",, newFormat)

                                            Dim DS As New VERAG_PROG_ALLGEMEIN.cDATENSERVER("MDM", "MDM_DATEN", "IDS_COUNTRY", Now.Year, Now.ToString("yyyyMMdd"), frmStartOptions.getFileName(d))

                                            If DS.uploadDataToDATENSERVER(d,,,,,, True) Then
                                                If SQL.doSQL("Update [tblIDSInvoicesNewSplittedByCountry] SET [daId]='" & DS.da_id & "' where [DocumentName] = '" & dateiname.ToString.Replace("OBO_", "") & "'  ", "FMZOLL") Then
                                                    frmStartOptions.moveFile_DateBack(d, zielpfad & "Invoice_PDF_Country\" & Now.Year & "\" & Now.ToString("yyyyMMdd") & "\")
                                                    cntDatenEingelesen += 1
                                                End If
                                            End If


                                        ElseIf dateiname.StartsWith("VATR_") Then

                                            createIDSInvoice(dateiname.Replace("VATR_", ""), "INVOICEBYCOUNTRY",, newFormat)

                                            Dim DS As New VERAG_PROG_ALLGEMEIN.cDATENSERVER("MDM", "MDM_DATEN", "IDS_COUNTRY", Now.Year, Now.ToString("yyyyMMdd"), frmStartOptions.getFileName(d))

                                            If DS.uploadDataToDATENSERVER(d,,,,,, True) Then
                                                If SQL.doSQL("Update [tblIDSInvoicesNewSplittedByCountry] SET [daId]='" & DS.da_id & "' where [DocumentName] = '" & dateiname.ToString.Replace("VATR_", "") & "'  ", "FMZOLL") Then
                                                    frmStartOptions.moveFile_DateBack(d, zielpfad & "Invoice_PDF_Country\" & Now.Year & "\" & Now.ToString("yyyyMMdd") & "\")
                                                    cntDatenEingelesen += 1
                                                End If
                                            End If




                                        End If

                                    End If


                                    If fi.Name.ToLower.Contains("pdf") Then addDGVEinarbeitung("PDF", fi.Name)
                                    dgvEinarbeitung.Refresh()

                            End Select


                        ElseIf programName.Contains("MSE") Then


                            Select Case i

                                Case 1
                                    '------------------------------------------
                                    '------------------ .CSV ------------------
                                    '------------------------------------------


                                    If fi.Extension.ToLower = ".csv" Then

                                        If Not found Then

                                            If readMSE(d) <> "" Then found = True

                                        End If

                                        If found Then cntDatenEingelesen += 1
                                    End If


                                Case 2
                                    '------------------------------------------
                                    '------------------ .PDF ------------------
                                    '------------------------------------------

                                    If fi.Extension.ToLower = ".pdf" Then

                                        mse.importInvoicesPDF_alternative(Dateiname, True)

                                    End If

                                    If fi.Name.ToLower.Contains("pdf") Then addDGVEinarbeitung("PDF", fi.Name)
                                    dgvEinarbeitung.Refresh()

                            End Select




                        End If
                        If True Then
                            If Not alreadyMoved Then
                                If found Then
                                    If Not System.IO.Directory.Exists(zielpfad & Now.Year & "\" & Now.ToString("yyyyMMdd") & "\") Then System.IO.Directory.CreateDirectory(zielpfad & Now.Year & "\" & Now.ToString("yyyyMMdd") & "\")
                                    frmStartOptions.moveFile_DateBack(d, zielpfad & Now.Year & "\" & Now.ToString("yyyyMMdd") & "\")
                                End If
                            End If
                        End If
                    End If
                    Me.Refresh()



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

        If programName.Contains("UTA") Then
            uta.importUTALeistungen()
            If cntDatenEingelesen > 0 Then
                Dim empfaneger = cMitarbeiter.GetEMailRecipientForEmailNotification("UTA-Import", 19)
                VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(empfaneger, "UTA-Import", "UTA-Daten wurden importiert! ")
            End If

        End If

            If programName.Contains("RMC") Then


            If Not VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM Then
                If dt.Rows.Count > 0 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 empfaneger = cMitarbeiter.GetEMailRecipientForEmailNotification("RMC-Import", 19)
                        VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(empfaneger, "Wölfl-UIDNr (EASYTRIP)", "Im Anhang die zu prüfenden Kunden von WÖLFL EasyTrip: " & vbNewLine & "*Automatic generated e-mail*", "NoReply@verag.ag",,,, "d.breimaier@verag.ag", anhenge)
                    End If
                End If

            End If

        End If

    End Sub




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

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



    Sub addDGVEinarbeitung(art, BezugsNr)
        dgvEinarbeitung.Rows.Add(art, BezugsNr)
        Try
            dgvEinarbeitung.FirstDisplayedScrollingRowIndex = dgvEinarbeitung.RowCount - 1
        Catch ex As System.Exception
        End Try
    End Sub


    Function readRMC(d As String, typ As String) As String
        Try

            Dim fi As FileInfo = New FileInfo(d)
            Dim kdNr = ""

            Dim filetimestamp = Regex.Replace(fi.Name, "[^\d]", "") 'entferne alle nicht numerischen Werte!
            Dim fileNr = filetimestamp.Substring(0, IIf(filetimestamp.Length > 8, filetimestamp.Length - 8, filetimestamp.Length))
            Dim fileType = IIf(fi.Name.ToLower.Contains("nto"), "netto", "brutto")

            If RMCNewFormat Then
                fileType = IIf(typ.ToLower.Contains("nto"), "netto", "brutto")
            End If

            Dim dt As New DataTable
            dt.Columns.Add("KundenNr", GetType(String))
            dt.Columns.Add("Kunde", GetType(String))
            dt.Columns.Add("UID", GetType(String))


            Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser(d, Encoding.GetEncoding(1252))

                MyReader.TextFieldType = FileIO.FieldType.Delimited
                MyReader.SetDelimiters(";")
                Dim currentRow As String()



                Dim cnt = 0
                Dim firstLine = True

                While Not MyReader.EndOfData
                    Try

                        currentRow = MyReader.ReadFields()
                        If firstLine Then
                            If SQL.isleernothing(currentRow(0)) = "KundenNr" Then
                                firstLine = False
                            Else
                                createRMC(fi, fileNr, filetimestamp, currentRow, fileType, kdNr, cnt, dt)
                            End If
                        Else

                            createRMC(fi, fileNr, filetimestamp, currentRow, fileType, kdNr, cnt, dt)

                        End If

                    Catch ex As System.Exception
                        VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace & vbNewLine & "Datei: " & Dateiname, System.Reflection.MethodInfo.GetCurrentMethod.Name)
                    End Try
                End While
                readRMC = "Zeilen: " & cnt
            End Using

            addDGVEinarbeitung("RMC: Detail" & kdNr, readRMC)
            If Not VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM Then
                If dt.Rows.Count > 0 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 empfaneger = cMitarbeiter.GetEMailRecipientForEmailNotification("RMC-Import", 19)
                        VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(empfaneger, "Wölfl-UIDNr", "Im Anhang die zu prüfenden Kunden von RMC für Importdatei: " & fi.Name & vbNewLine & vbNewLine & "Pro Importdatei wird ein Email generiert/gesendet" & vbNewLine & vbNewLine & "*Automatic generated e-mail*", "NoReply@verag.ag",,,,, anhenge)
                    End If
                End If

            End If

        Catch ex As System.Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace & vbNewLine & "Datei: " & Dateiname, System.Reflection.MethodInfo.GetCurrentMethod.Name)
            MsgBox(ex.StackTrace & ex.Message)
            readRMC = ""
        End Try
    End Function


    Function readUTA(d As String) As String
        Try

            Dim fi As FileInfo = New FileInfo(d)
            Dim cnt = 0
            Dim objFileRead As StreamReader = New StreamReader(d)


            If uta.readAndSaveUTA(objFileRead, fi, cnt, UtaTestkunden) Then
                addDGVEinarbeitung(fi.Name, "OK")
            Else
                addDGVEinarbeitung(fi.Name, "Fehler")
            End If

            readUTA = "Zeilen: " & cnt

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


    End Function

    Function readIDS(d As String) As String
        Try

            Dim fi As FileInfo = New FileInfo(d)
            Dim cnt = 0
            Dim objFileRead As StreamReader = New StreamReader(d)


            If ids.readAndSaveIDS(objFileRead, fi, cnt) Then
                addDGVEinarbeitung(fi.Name, "OK")
            Else
                addDGVEinarbeitung(fi.Name, "Fehler")
            End If

            readIDS = "Zeilen: " & cnt

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


    End Function


    Function readMSE(d As String) As String
        Try

            Dim fi As FileInfo = New FileInfo(d)
            Dim cnt = 0
            Dim objFileRead As StreamReader = New StreamReader(d)


            If mse.readAndSaveMSE(objFileRead, fi, cnt) Then
                addDGVEinarbeitung(fi.Name, "OK")
            Else
                addDGVEinarbeitung(fi.Name, "Fehler")
            End If

            readMSE = "Zeilen: " & cnt

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


    End Function



    Private Sub dgvEinarbeitung_SelectionChanged(sender As Object, e As EventArgs) Handles dgvEinarbeitung.SelectionChanged
        dgvEinarbeitung.ClearSelection()

    End Sub


    Private Sub frmTCNachrichtenVerarbeitung_Shown(sender As Object, e As EventArgs) Handles Me.Shown
        If allowClose Then
            Me.Refresh()

            btnEinlesen.PerformClick()
            btnEinarbeiten.PerformClick()

            System.Threading.Thread.Sleep(2000)

            Me.Close()
        End If
    End Sub

    Private Sub createRMC(fi As FileInfo, filenr As Integer, filetimestamp As String, currentRow As String(), fileType As String, ByRef kdNr As String, cnt As Integer, dt As DataTable)

        Dim RMC As New VERAG_PROG_ALLGEMEIN.cRMC
        RMC.rmc_file = fi.Name
        RMC.rmc_version = filetimestamp
        RMC.rmc_fileNr = filenr
        RMC.rmc_kdNr = SQL.isleernothing(currentRow(0))
        RMC.rmc_kdName = SQL.isleernothing(currentRow(1))
        RMC.rmc_fibuNr = SQL.isleernothing(currentRow(2))
        RMC.rmc_UID = SQL.isleernothing(currentRow(3))
        RMC.rmc_landKZ = SQL.isleernothing(currentRow(4))
        RMC.rmc_landBezeichnung = SQL.isleernothing(currentRow(5))
        RMC.rmc_reDatum = SQL.isleernothing(currentRow(6))
        RMC.rmc_sammelReNr = SQL.isleernothing(currentRow(7))
        RMC.rmc_reNr = SQL.isleernothing(currentRow(8))
        RMC.rmc_betragNetto = SQL.isleernothing(currentRow(9))
        RMC.rmc_betragMWST = SQL.isleernothing(currentRow(10))
        RMC.rmc_betragBrutto = SQL.isleernothing(currentRow(11))

        Dim waherung = SQL.isleernothing(currentRow(12))
        If waherung IsNot Nothing Then
            RMC.rmc_waehrung = IIf(waherung.ToString.Length > 3, waherung.ToString.Substring(0, 3), waherung)
        End If

        RMC.rmc_euroBrutto = SQL.isleernothing(currentRow(13))

        If RMCNewFormat Then
            RMC.rmc_pdfFileName = "invoice_" & RMC.rmc_kdNr & "_" & filenr & "_" & RMC.rmc_sammelReNr & "_" & RMC.rmc_landKZ & "_orig" & IIf(fileType = "netto", "_nto", "_bto") & ".pdf"
        Else
            RMC.rmc_pdfFileName = "invoice_" & RMC.rmc_kdNr & "_" & filenr & "_" & RMC.rmc_sammelReNr & IIf(fileType = "netto", "_nto_e_verag.pdf", "_bto_e_verag.pdf")
        End If


        If RMC.SAVE() Then
            If kdNr <> RMC.rmc_kdNr Then
                Dim adress As New VERAG_PROG_ALLGEMEIN.cAdressen(RMC.rmc_UID, RMC.rmc_kdNr, True) 'bei Mehrfachanlage muss auf 15-KundenNr georüft werden!
                If Not adress.hasEntry Then
                    Dim R As DataRow = dt.NewRow
                    R("KundenNr") = RMC.rmc_kdNr
                    R("Kunde") = RMC.rmc_kdName
                    R("UID") = RMC.rmc_UID
                    dt.Rows.Add(R)
                End If
                'If adress IsNot Nothing Then adress.UpdateSpecialField("WölflKundenNr", RMC.rmc_kdNr) -> nicht updaten, sondern nur info ausgeben!
            End If

            kdNr = RMC.rmc_kdNr
            cnt += 1
        End If

    End Sub


    Private Sub setButtons(enable As Boolean, Optional alwaysDisableEinlesen As Boolean = False)


        btnEinarbeiten.Enabled = enable
        btnEinlesen.Enabled = enable
        If alwaysDisableEinlesen Then btnEinlesen.Enabled = False

    End Sub

End Class

