
Imports System.Data.SqlClient
Imports System.Reflection
Imports System.Text.RegularExpressions
Imports VERAG_PROG_ALLGEMEIN
Public Class cPLOSE_Inv_Data

    Property plInv_Id As Integer
    Property plInv_SupplierRechnungsDatum As Object = Nothing
    Property plInv_SupplierRechnungsNr As String
    Property plInv_SupplierCountry As Object = Nothing
    Property plInv_Lieferant As Object = Nothing
    Property plInv_LieferantCode As Object = Nothing
    Property plInv_LieferantUID As Object = Nothing
    Property plInv_RechnungsJahr As Object = Nothing
    Property plInv_Dateiname As Object = Nothing
    Property plInv_Einlesedatum As Object = Nothing
    Property plInv_Datensatztyp As Object = Nothing
    Property plInv_PLOSEKundennummer As Object = Nothing
    Property plInv_Firmenname As Object = Nothing
    Property plInv_Nettobetrag As Object = Nothing
    Property plInv_MWSTBetrag As Object = Nothing
    Property plInv_Bruttobetrag As Object = Nothing
    Property plInv_Services As Object = Nothing
    Property plInv_PdfFileName As Object = Nothing
    Property plInv_Currency As Object = Nothing
    Property plInv_daId As Object = Nothing
    Property plInv_tstmp As DateTime = Now
    Property plInv_UStVAn_ID As Object = Nothing
    Property plInv_Archiv As Boolean = False
    Property plInv_ArchiviertDatum As Object = Nothing
    Property plInv_daIdgesetztDatum As Object = Nothing


    Public hasEntry = False

    Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL

    Sub New()

    End Sub

    Sub New(plInv_Id)
        Me.plInv_Id = plInv_Id
        LOAD()
    End Sub
    Function getParameterList(Optional withPrimaryKey As Boolean = True) As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable)
        Dim list As New List(Of VERAG_PROG_ALLGEMEIN.SQLVariable)

        If withPrimaryKey Then
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("plInv_Id", plInv_Id,, True))
        Else
            'list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("plInv_Id", plInv_Id))
        End If

        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("plInv_SupplierRechnungsDatum", plInv_SupplierRechnungsDatum))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("plInv_SupplierRechnungsNr", plInv_SupplierRechnungsNr))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("plInv_SupplierCountry", plInv_SupplierCountry))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("plInv_Lieferant", plInv_Lieferant))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("plInv_LieferantCode", plInv_LieferantCode))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("plInv_LieferantUID", plInv_LieferantUID))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("plInv_RechnungsJahr", plInv_RechnungsJahr))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("plInv_Dateiname", plInv_Dateiname))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("plInv_Einlesedatum", plInv_Einlesedatum))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("plInv_Datensatztyp", plInv_Datensatztyp))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("plInv_PLOSEKundennummer", plInv_PLOSEKundennummer))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("plInv_Firmenname", plInv_Firmenname))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("plInv_Nettobetrag", plInv_Nettobetrag))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("plInv_MWSTBetrag", plInv_MWSTBetrag))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("plInv_Bruttobetrag", plInv_Bruttobetrag))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("plInv_Services", plInv_Services))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("plInv_PdfFileName", plInv_PdfFileName))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("plInv_Currency", plInv_Currency))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("plInv_daId", plInv_daId))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("plInv_tstmp", plInv_tstmp))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("plInv_UStVAn_ID", plInv_UStVAn_ID))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("plInv_Archiv", plInv_Archiv))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("plInv_ArchiviertDatum", plInv_ArchiviertDatum))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("plInv_daIdgesetztDatum", plInv_daIdgesetztDatum))

        Return list
    End Function



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

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

        'Return SQL.doSQLVarList(sqlstr, "FMZOLL", , list)
        plInv_Id = SQL.doSQLVarListID(plInv_Id, sqlstr, "FMZOLL", , list)
        Return (plInv_Id > 0)
    End Function



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

        Dim sqlstr = " BEGIN TRAN IF EXISTS(SELECT plInv_Id FROM tblPLOSE_Inv_Data WHERE plInv_SupplierRechnungsDatum=@plInv_SupplierRechnungsDatum and plInv_SupplierRechnungsNr=@plInv_SupplierRechnungsNr and plInv_SupplierCountry=@plInv_SupplierCountry and plInv_LieferantCode=@plInv_LieferantCode and plInv_PLOSEKundennummer=@plInv_PLOSEKundennummer) " &
                       " BEGIN " & getUpdateCmdUnique() & " END " &
                       " Else " &
                       " BEGIN " & getInsertCmd() & " END " &
                       " commit tran "

        plInv_Id = SQL.doSQLVarListID(plInv_Id, sqlstr, "FMZOLL", , list)
        Return (plInv_Id > 0)

    End Function


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

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

                        Next
                        hasEntry = True
                    End If
                    dr.Close()
                End Using
            End Using
        Catch ex As Exception
            MsgBox("Fehler in der Funktion '" & System.Reflection.MethodInfo.GetCurrentMethod.Name & "'" & vbNewLine & vbNewLine & ex.Message & vbNewLine & vbNewLine & ex.StackTrace)
        End Try
    End Sub



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

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

        Catch ex As Exception
            MsgBox("Fehler in der Funktion '" & System.Reflection.MethodInfo.GetCurrentMethod.Name & "'" & vbNewLine & vbNewLine & ex.Message & vbNewLine & vbNewLine & ex.StackTrace)
        End Try
        Return ""
    End Function

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

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

        Catch ex As Exception
            MsgBox("Fehler in der Funktion '" & System.Reflection.MethodInfo.GetCurrentMethod.Name & "'" & vbNewLine & vbNewLine & ex.Message & vbNewLine & vbNewLine & ex.StackTrace)
        End Try
        Return ""
    End Function


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



    Public Shared Function setDatenarchivID(jahr As Integer, Optional message As Boolean = False, Optional kdNr As Integer = -1) As Boolean

        If jahr > Now.Year Then Return False
        If jahr < 2020 Then Return False


        Dim REohneDAID As String = "Select plInv_Id, plInv_Dateiname,plInv_PdfFileName, plInv_daId, plInv_PLOSEKundennummer  FROM [tblPLOSE_Inv_Data] where plInv_daId Is null And plInv_PdfFileName Is Not null And Year(plInv_SupplierRechnungsDatum) = " & jahr & IIf(kdNr > 0, " and plInv_PLOSEKundennummer = " & kdNr, "") & " order by plInv_Einlesedatum desc"

        Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
        Dim dtREohneDAID As DataTable = SQL.loadDgvBySql(REohneDAID, "FMZOLL")
        Dim jahrEnd = jahr.ToString.Substring(2, 2)

        If dtREohneDAID.Rows.Count > 0 Then

            If IIf(message, vbYes = MsgBox("Bei " & dtREohneDAID.Rows.Count & " PLOSE-Rechnungen fehlt die Zuweisung zur Datenarchiv-ID (PDF)." & vbNewLine & "Datenarchiv-ID setzen?", vbYesNoCancel), True) Then
                Dim counter = 0
                For Each r As DataRow In dtREohneDAID.Rows

                    Dim filename As String = IIf(Not IsDBNull(r.Item("plInv_PdfFileName")), r.Item("plInv_PdfFileName"), "")
                    Dim filename2 As String = ""
                    Dim filename3 As String = ""
                    Dim filename4 As String = ""


                    If filename <> "" Then

                        filename2 = filename.Replace("-", "_")


                        'If r.Item("plInv_Dateiname") = "830850-PSS-MAUT. PLOSE BOX-2025-09-15-000000-999999-00_RGDAT_16.09.2025.csv" Then

                        '    filename3 = filename.ToString().Substring(0, 9)
                        '    'filename3 &= "%"
                        '    filename3 &= filename.ToString().Substring(10, filename.Length - 10)
                        '    filename4 = filename3.Replace("-", "_")

                        '    filename3 = filename3.Replace(" ", "")
                        '    filename4 = filename4.Replace(" ", "")
                        'End If


                        If Regex.IsMatch(filename, "^[A-Za-z]") Then
                            Dim match As Match = Regex.Match(filename, "\d+")
                            If match.Success Then
                                filename3 = filename.Substring(match.Index).Trim
                                filename4 = filename.Replace("-", "_")
                            End If

                        ElseIf filename.Contains("_dk") Then 'Sonderlogik Dänemark

                            filename3 = filename.Replace(jahrEnd & "-", jahrEnd)
                            filename4 = filename.Replace(jahrEnd & "-", jahrEnd)

                            filename3 = filename3.Replace(" ", "")
                            filename4 = filename4.Replace(" ", "")

                        ElseIf filename.Contains("_fy") Then 'Sonderlogik Norwegen

                            Dim indexOfFirst_ = filename.IndexOf("_fy")
                            If filename.Length > indexOfFirst_ + 5 Then
                                Dim month = filename.Substring(indexOfFirst_ + 3, 2)
                                If IsNumeric(month) Then
                                    Dim test = month.IndexOf(0)
                                    Dim monthWithoutLeadingZero As String = month
                                    If monthWithoutLeadingZero.IndexOf(0) = 0 Then monthWithoutLeadingZero = monthWithoutLeadingZero.Replace("0", "")
                                    filename3 = filename.Replace(jahrEnd & month, jahrEnd & monthWithoutLeadingZero)
                                    filename4 = filename.Replace(jahrEnd & month, jahrEnd & monthWithoutLeadingZero)
                                    filename3 = filename3.Replace(" ", "")
                                    filename4 = filename4.Replace(" ", "")
                                End If

                            End If




                        End If

                        Dim daId As Integer = 0
                        If filename3 = "" Then
                            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= 'PLOSE' AND da_uOrdner2= '" & jahr & "'  AND (da_name like '%" & filename & "' or da_name like '%" & filename2 & "')", "FMZOLL",,, 0))
                        Else
                            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= 'PLOSE' AND da_uOrdner2= '" & jahr & "'  AND (da_name like '%" & filename & "'  or da_name like '%" & filename2 & "'  or da_name like '%" & filename3 & "'  or da_name like '%" & filename4 & "')", "FMZOLL",,, 0))
                        End If



                        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 [tblPLOSE_Inv_Data] SET plInv_daId = " & DS.da_id & ", plInv_daIdgesetztDatum = getdate()   WHERE plInv_Id = " & r.Item("plInv_Id") & " AND plInv_daId is null", "FMZOLL")
                                counter += 1
                            End If
                        End If
                    End If


                Next


                If message Then MsgBox(counter & " von " & dtREohneDAID.Rows.Count & " Rechnungsdaten gesetzt!")
                Return True
            End If

        Else
            If message Then MsgBox("keine fehlenden PLOSE-Rechnunngsdaten vorhanden!")
            Return False
        End If




    End Function

    Public Shared Function checkImport() As Boolean

        Dim mehrfachIMportiert_SQL As String = "  select plose_Dateiname,  count(distinct(plose_Einlesedatum)) as Einlesedatum from tblPLOSE_Details 
                                        where  plose_Fakturiert = 0
                                        group by  plose_Dateiname
                                        having count(distinct(plose_Einlesedatum))  > 1
                                        order by plose_Dateiname"

        Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
        Dim dtMehrfachImportiert_DT As DataTable = SQL.loadDgvBySql(mehrfachIMportiert_SQL, "FMZOLL", 40)


        If dtMehrfachImportiert_DT.Rows.Count > 0 Then

            If vbYes = MsgBox("ACHTUNG, es wurden  " & dtMehrfachImportiert_DT.Rows.Count & " Abrechnungsdaten mehrfach importiert!" & vbNewLine & "Info anzeigen?", vbYesNo) Then
                cProgramFunctions.genExcelFromDT_NEW(dtMehrfachImportiert_DT,,, "Mehrfach importierte Dateien")
            End If
            Return False
        Else
            Return True
        End If




    End Function

    Public Shared Function setBackToCustomer(SQL As SQL, backToCustomer As Boolean, ab As Date, customerNo As Integer) As Boolean


        Return SQL.doSQL("update tblPLOSE_Inv_Data set plInv_InvToCustomer = " & IIf(backToCustomer, "1", "NULL") & "  where cast(plInv_SupplierRechnungsDatum as Date) >= '" & ab.ToShortDateString & "' AND  plInv_PLOSEKundennummer =  '" & customerNo & "'", "FMZOLL")

    End Function

    Public Shared Function setBackToCustomerCustomerID(SQL As SQL, backToCustomer As Boolean, customerNo As String) As Boolean

        Return SQL.doSQL("update tblPLOSE_Inv_Data set plInv_InvToCustomer = " & IIf(backToCustomer, "1", "NULL") & "  where plInv_InvToCustomer Is null AND  plInv_PLOSEKundennummer =  '" & customerNo & "'", "FMZOLL")

    End Function

    Public Shared Function setBackToCustomerInvoiceID(SQL As SQL, backToCustomer As Boolean, Optional invoiceID As String = "") As Boolean

        Return SQL.doSQL("update tblPLOSE_Inv_Data set plInv_InvToCustomer = " & IIf(backToCustomer, "1", "0") & "  where plInv_InvToCustomer Is null " & IIf(invoiceID <> "", "AND  plInv_Id = '" & invoiceID & "'", " ") & "", "FMZOLL")

    End Function

    Public Shared Function countBackToCustomerNotSet(SQL As SQL) As Integer
        Return SQL.getValueTxtBySql("SELECT count(*) FROM [tblPLOSE_Inv_Data] where plInv_InvToCustomer Is null ", "FMZOLL",,, -1)
    End Function

    Public Shared Function countBackToCustomerNotSet(SQL As SQL, AdressenNrVon As Integer, AdressenNrBis As Integer) As Integer
        Return SQL.getValueTxtBySql("SELECT count(*) FROM [tblPLOSE_Inv_Data] inner join Adressen on Adressen.PLOSEKundenNr = plInv_PLOSEKundennummer  where plInv_InvToCustomer Is null and Adressen.AdressenNr between " & AdressenNrVon & " AND " & AdressenNrBis, "FMZOLL",,, -1)
    End Function


    Public Shared Function checkPDFInvoices(Optional reDatVon As Date = Nothing, Optional reDatBis As Date = Nothing, Optional dt As DataTable = Nothing, Optional AdressenNrVon As Integer = -1, Optional AdressenNrBis As Integer = -1) As Integer
        Try
            Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL

            Dim sqlTime As String = ""
            Dim sqlAdressenNr As String = ""

            If IsDate(reDatVon) AndAlso CDate(reDatVon) > "01.01.2020" AndAlso IsDate(reDatBis) AndAlso CDate(reDatBis) > "01.01.2020" Then
                sqlTime = " And cast([plInv_SupplierRechnungsDatum] As Date) between '" & reDatVon.ToShortDateString & "' and '" & reDatBis.ToShortDateString & "'"
            End If

            If AdressenNrVon > 0 AndAlso AdressenNrBis > 0 Then
                sqlAdressenNr = " AND Adressen.AdressenNr between " & AdressenNrVon & " AND " & AdressenNrBis
            End If

            If dt IsNot Nothing Then
                Dim SQLstr = "Select [plInv_SupplierRechnungsNr] As RechnungsNr,plInv_SupplierRechnungsDatum As Rechnungsdatum,Adressen.AdressenNr,Adressen.[Name 1] As Kunde, kde_keineMWSt As keineMWST  from [tblPLOSE_Inv_Data] INNER JOIN Adressen On [plInv_PLOSEKundennummer]=Adressen.PLOSEKundenNr INNER JOIN tblKundenErweitert On AdressenNr = kde_KundenNr where [plInv_daId] Is null " & sqlTime & sqlAdressenNr & " group by plInv_SupplierRechnungsNr, Adressen.AdressenNr, Adressen.[Name 1], plInv_SupplierRechnungsDatum, kde_keineMWSt"
                dt = (New VERAG_PROG_ALLGEMEIN.SQL).loadDgvBySql(SQLstr, "FMZOLL")
                Return dt.Rows.Count

            Else
                Dim SQLstr = "Select count(plInv_SupplierRechnungsNr) from [tblPLOSE_Inv_Data] INNER JOIN Adressen On [plInv_PLOSEKundennummer]=Adressen.PLOSEKundenNr INNER JOIN tblKundenErweitert On AdressenNr = kde_KundenNr where [plInv_daId] Is null " & sqlTime & sqlAdressenNr & " group by plInv_SupplierRechnungsNr, Adressen.AdressenNr, Adressen.[Name 1], plInv_SupplierRechnungsDatum, kde_keineMWSt"
                Return SQL.getValueTxtBySql(SQLstr, "FMZOLL",,, 0)

            End If

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

        Return Nothing

    End Function


    Public Shared Function setWahrunginIvoiceFromTransactions(jahr As Integer, Optional message As Boolean = False, Optional kdNr As Integer = -1) As Boolean

        If jahr > Now.Year Then Return False
        If jahr < 2020 Then Return False


        Dim REohneWaehrung As String = "Select [plInv_SupplierRechnungsDatum], [plInv_SupplierRechnungsNr], [plInv_SupplierCountry], [plInv_Lieferant]
                                        From [VERAG].[dbo].[tblPLOSE_Inv_Data] 
                                        where YEAR( [plInv_SupplierRechnungsDatum]) = " & jahr & " and plInv_Currency is null " & IIf(kdNr > 0, " and plInv_PLOSEKundennummer = " & kdNr, "") & "
                                        Group by  [plInv_SupplierCountry],[plInv_Lieferant],[plInv_SupplierRechnungsDatum],[plInv_SupplierRechnungsNr]"

        Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
        Dim dtREohneWahrung As DataTable = SQL.loadDgvBySql(REohneWaehrung, "FMZOLL")



        If dtREohneWahrung.Rows.Count > 0 Then

            If vbYes = MsgBox("Details der fehlenden Währungen anzeigen?", vbYesNo) Then
                cProgramFunctions.genExcelFromDT_NEW(dtREohneWahrung,,, "Fehlende Währung in Rechnungen: " & jahr)
            End If


            If IIf(message, vbYes = MsgBox("Bei " & dtREohneWahrung.Rows.Count & " PLOSE-Rechnungen fehlt die Währungsbezeichnung in den Rechnungen." & vbNewLine & "Währung setzen?", vbYesNoCancel), True) Then

                For Each r As DataRow In dtREohneWahrung.Rows

                    Dim Waehrungtabelle As DataTable = SQL.loadDgvBySql("Select plose_WaehrungAbbuchung, plose_WaehrungLandDiesntleistung, plp_Land from tblPLOSE_Details INNER JOIN tblPLOSE_Produktbeschreibung ON [plp_ProductCode]=[plose_ProduktCode]  WHERE plose_SupplierRechnungsNr = '" & r.Item("plInv_SupplierRechnungsNr") & "' And plose_SupplierRechnungsDatum = '" & r.Item("plInv_SupplierRechnungsDatum") & "' group by plose_WaehrungAbbuchung, plose_WaehrungLandDiesntleistung, plp_Land", "FMZOLL")

                    If Waehrungtabelle.Rows.Count = 1 Then
                        If Waehrungtabelle.Rows(0).Item("plose_WaehrungAbbuchung") = Waehrungtabelle.Rows(0).Item("plose_WaehrungLandDiesntleistung") And Waehrungtabelle.Rows(0).Item("plp_Land").ToString.Trim = r.Item("plInv_SupplierCountry").ToString.Trim Then
                            Dim Waehrung As String = IIf(IsDBNull(Waehrungtabelle.Rows(0).Item("plose_WaehrungAbbuchung")), "", Waehrungtabelle.Rows(0).Item("plose_WaehrungAbbuchung"))
                            If Waehrung <> "" Then
                                SQL.doSQL("UPDATE [tblPLOSE_Inv_Data] SET plInv_Currency = '" & Waehrung & "' WHERE plInv_Currency is null and [plInv_SupplierRechnungsDatum] = '" & r.Item("plInv_SupplierRechnungsDatum") & "' AND [plInv_SupplierRechnungsNr] = '" & r.Item("plInv_SupplierRechnungsNr") & "' and [plInv_SupplierCountry] ='" & r.Item("plInv_SupplierCountry") & "'", "FMZOLL")
                            End If
                        End If
                    End If

                Next


                If message Then MsgBox("alle Währungen gesetzt!")
                Return True
            End If

        Else
            If message Then MsgBox("keine fehlenden Währungen vorhanden!")
            Return False
        End If




    End Function

    Public Shared Function checkAndsetArchivFromUSTVAPos(jahr As Integer, Optional message As Boolean = False, Optional kdNr As Integer = -1) As Boolean

        If jahr > Now.Year Then Return False
        If jahr < 2020 Then Return False


        Dim nichtEingearbetieteEintrage As String = "select * from tblPLOSE_Details where Year(plose_RechnungsDatum) =  " & jahr & "  and UStVAn_ID is null and plose_ArchiviertDatum is null and plose_Archiv = 0 " & IIf(kdNr > 0, " And plose_POLSEKundennummer = " & kdNr, "")


        Dim REohneWaehrung As String = "SELECT [plInv_SupplierRechnungsDatum],[plInv_SupplierRechnungsNr],[plInv_SupplierCountry],[plInv_Lieferant]
                                        FROM [VERAG].[dbo].[tblPLOSE_Inv_Data] 
                                        where YEAR( [plInv_SupplierRechnungsDatum]) = " & jahr & " and plInv_Currency is null " & "
                                        Group by  [plInv_SupplierCountry],[plInv_Lieferant],[plInv_SupplierRechnungsDatum],[plInv_SupplierRechnungsNr]"

        Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
        Dim dtREohneWahrung As DataTable = SQL.loadDgvBySql(REohneWaehrung, "FMZOLL")

        'TODO: umbauen auf checkAndSet


        'If dtREohneWahrung.Rows.Count > 0 Then

        '    If vbYes = MsgBox("Details der fehlenden Währungen anzeigen?", vbYesNo) Then
        '        cProgramFunctions.genExcelFromDT_NEW(dtREohneWahrung,,, "Fehlende Währung in Rechnungen: " & jahr)
        '    End If


        '    If IIf(message, vbYes = MsgBox("Bei " & dtREohneWahrung.Rows.Count & " PLOSE-Rechnungen fehlt die Währungsbezeichnung in den Rechnungen." & vbNewLine & "Währung setzen?", vbYesNoCancel), True) Then

        '        For Each r As DataRow In dtREohneWahrung.Rows

        '            Dim Waehrungtabelle As DataTable = SQL.loadDgvBySql("Select plose_WaehrungAbbuchung, plose_WaehrungLandDiesntleistung, plp_Land from tblPLOSE_Details INNER JOIN tblPLOSE_Produktbeschreibung ON [plp_ProductCode]=[plose_ProduktCode]  WHERE plose_SupplierRechnungsNr = '" & r.Item("plInv_SupplierRechnungsNr") & "' And plose_SupplierRechnungsDatum = '" & r.Item("plInv_SupplierRechnungsDatum") & "' group by plose_WaehrungAbbuchung, plose_WaehrungLandDiesntleistung, plp_Land", "FMZOLL")

        '            If Waehrungtabelle.Rows.Count = 1 Then
        '                If Waehrungtabelle.Rows(0).Item("plose_WaehrungAbbuchung") = Waehrungtabelle.Rows(0).Item("plose_WaehrungLandDiesntleistung") And Waehrungtabelle.Rows(0).Item("plp_Land").ToString.Trim = r.Item("plInv_SupplierCountry").ToString.Trim Then
        '                    Dim Waehrung As String = IIf(IsDBNull(Waehrungtabelle.Rows(0).Item("plose_WaehrungAbbuchung")), "", Waehrungtabelle.Rows(0).Item("plose_WaehrungAbbuchung"))
        '                    If Waehrung <> "" Then
        '                        SQL.doSQL("UPDATE [tblPLOSE_Inv_Data] SET plInv_Currency = '" & Waehrung & "' WHERE plInv_Currency is null and [plInv_SupplierRechnungsDatum] = '" & r.Item("plInv_SupplierRechnungsDatum") & "' AND [plInv_SupplierRechnungsNr] = '" & r.Item("plInv_SupplierRechnungsNr") & "' and [plInv_SupplierCountry] ='" & r.Item("plInv_SupplierCountry") & "'", "FMZOLL")
        '                    End If
        '                End If
        '            End If

        '        Next


        '        If message Then MsgBox("alle Währungen gesetzt!")
        '        Return True
        '    End If

        'Else
        '    If message Then MsgBox("keine fehlenden Währungen vorhanden!")
        '    Return False
        'End If




    End Function



End Class

