Imports System.Data.OleDb
Imports System.IO
Imports com.sun.jdi
Imports DAKOSY_Worker.NichtAbschliessendeFestsetzung

Public Class frmMDMDatenverarbetiung

    Public LIEFERANT = ""

    Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL

    ' Dim ProduktCode_NOT_IN = "SELECT plp_ProductCode FROM [tblPLOSE_Produktbeschreibung] WHERE  [plp_einarbeiten]=0 "
    Dim ProduktCode_NOT_IN = "'9020'"
    Private Sub frmPloseDatenverarbetiung_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Me.Top = 0
        Me.Height = My.Computer.Screen.WorkingArea.Height
    End Sub

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

    End Sub

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

    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Select Case LIEFERANT
            Case "PLOSE" : genSummenbericht_PLOSE()
            Case "ASFINAG" : genSummenbericht_ASFINAG()
            Case Else : MsgBox("Nicht verfügbar!")
        End Select
    End Sub

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click

        MyDatagridview1.ClearSelection()

        Button3.BackColor = Color.White
        Button3.ForeColor = Color.Black

        Dim pruef As Boolean = False
        Select Case LIEFERANT
            Case "PLOSE" : pruef = pruefData_PLOSE()
            Case "ASFINAG" : pruef = pruefData_ASFINAG()
            Case Else : MsgBox("Nicht verfügbar!") : Exit Sub
        End Select

        cbx.Checked = pruef
        If pruef Then
            Button3.BackColor = Color.Green
            Button3.ForeColor = Color.White
        Else
            Button3.BackColor = Color.Red
            Button3.ForeColor = Color.White
        End If

    End Sub


    Private Sub btnDatenLaden_Click(sender As Object, e As EventArgs) Handles btnDatenLaden.Click
        init()
    End Sub

    Sub init()
        txtAnzahl.Text = ""
        txtPruefsummeNetto.Text = ""

        Select Case LIEFERANT
            Case "PLOSE" : initDgv_PLOSE()
                btnDatenLaden.Text = "Daten laden"
            Case "UTA" : initDgv_UTA()
                btnDatenLaden.Text = "Daten laden"
            Case "ASFINAG" : initDgv_ASFINAG(Not cbxNichtabgerechnet.Checked)
                btnDatenLaden.Text = "Mautdaten laden"
        End Select
    End Sub

    Private Sub Button4_Click_1(sender As Object, e As EventArgs) Handles Button4.Click
        Dim errorTmp = False
        Select Case LIEFERANT
            Case "PLOSE"
                If genRGAtt_PLOSE() Then
                    If MautD_Befuellen() Then
                        setFakturiertPLOSE()
                    End If
                End If
            Case "UTA"
                If genRGAtt_UTA() Then
                    'If MautD_Befuellen() Then
                    '    setFakturiertUTA()
                    'End If
                End If
            Case "ASFINAG"

        End Select
    End Sub



    Sub genSummenbericht_PLOSE()
        Dim displayFilter = False
        Dim sqlstr As String = ""

        sqlstr &= " SELECT 	  count(*) Anzahl	,plose_ProduktCode"
        sqlstr &= ",max(plose_Produktbeschreibung) as plose_Produktbeschreibung"
        sqlstr &= ",sum(plose_Menge) as plose_Menge"
        sqlstr &= ",sum(plose_Preis) as plose_Preis"
        sqlstr &= ",sum(plose_NettobetragWaehrungAbbuchung) as plose_NettobetragWaehrungAbbuchung"
        sqlstr &= ",sum(plose_MWSTBetragWaehrungAbbuchung) as plose_MWSTBetragWaehrungAbbuchung"
        sqlstr &= ",sum(plose_BruttobetragWaehrungAbbuchung) as plose_BruttobetragWaehrungAbbuchung "
        sqlstr &= " FROM tblPLOSE_Details"
        sqlstr &= " WHERE 1=1 "

        sqlstr &= " AND plose_DatumTransaktion between '" & dat_Sum_Von.Value & "' and '" & dat_Sum_Bis.Value & "' "
        sqlstr &= " AND plose_Fakturiert =0 "
        sqlstr &= " AND  plose_ProduktCode NOT IN (" & ProduktCode_NOT_IN & ") "

        sqlstr &= " group by plose_ProduktCode"
        sqlstr &= " order by plose_ProduktCode"


        Dim dt As DataTable = SQL.loadDgvBySql_Param(sqlstr, "FMZOLL")
        'DataGridView.DataSource = dt


        Dim print As New frmPrintLayout
        print.Text = "PLOSE"

        Dim rpt As New rptPLOSE_TransaktionenSumary

        rpt.DataSource = dt


        'If cbxProdukt.Checked Then
        '    rpt.GroupHeader2.DataField = "prod_descr"
        'Else
        '    rpt.GroupHeader2.Visible = False
        '    rpt.GroupFooter2.Visible = False
        'End If



        Dim sum = 0
        rpt.lblUeberschrift.Text = "PLOSE Summenbericht " & dat_Sum_Von.Text & " bis " & dat_Sum_Bis.Text
        rpt.lblSachbearbeiter.Text = VERAG_PROG_ALLGEMEIN.cAllgemein.USRNAME
        'rpt.lblMandantNiederlassung.Text = PERSONAL.Mandant & "  /  " & PERSONAL.Niederlassung

        'Dim cnt As Integer = 0
        rpt.lblDat.Text = Now.ToLongDateString


        Dim sumPreis As Double = 0
        Dim sumNetto As Double = 0
        Dim sumMWST As Double = 0
        Dim sumBrutto As Double = 0
        Dim sumMenge As Double = 0

        AddHandler rpt.Detail.Format, Sub()
                                          '   rpt.lblProduktBeschreibung.Text = isDbnullEmpty(rpt.Fields.Item("BC_DESCR").Value, "")
                                          rpt.lblAnzahl.Text = SQL.isDbnullEmpty(rpt.Fields.Item("Anzahl").Value, "")
                                          rpt.lblProdukt.Text = SQL.isDbnullEmpty(rpt.Fields.Item("plose_ProduktCode").Value, "") & " - " & SQL.isDbnullEmpty(rpt.Fields.Item("plose_Produktbeschreibung").Value, "")

                                          rpt.lblMenge.Text = SQL.isDbnullEmptyDbl(rpt.Fields.Item("plose_Menge").Value, 0, "")
                                          ' rpt.lblPreis.Text = SQL.isDbnullEmptyDbl(rpt.Fields.Item("plose_Preis").Value, 2, "")
                                          rpt.lblNetto.Text = SQL.isDbnullEmptyDbl(rpt.Fields.Item("plose_NettobetragWaehrungAbbuchung").Value, 2, "")
                                          rpt.lblMWST.Text = SQL.isDbnullEmptyDbl(rpt.Fields.Item("plose_MWSTBetragWaehrungAbbuchung").Value, 2, "")
                                          rpt.lblBrutto.Text = SQL.isDbnullEmptyDbl(rpt.Fields.Item("plose_BruttobetragWaehrungAbbuchung").Value, 2, "")



                                          sumMenge += SQL.isDbnullEmptyDbl(rpt.Fields.Item("plose_Menge").Value, 4, 0)
                                          '  sumPreis += SQL.isDbnullEmptyDbl(rpt.Fields.Item("plose_Preis").Value, 4, 0)
                                          sumNetto += SQL.isDbnullEmptyDbl(rpt.Fields.Item("plose_NettobetragWaehrungAbbuchung").Value, 4, 0)
                                          sumMWST += SQL.isDbnullEmptyDbl(rpt.Fields.Item("plose_MWSTBetragWaehrungAbbuchung").Value, 4, 0)
                                          sumBrutto += SQL.isDbnullEmptyDbl(rpt.Fields.Item("plose_BruttobetragWaehrungAbbuchung").Value, 4, 0)


                                      End Sub


        AddHandler rpt.ReportFooter1.Format, Sub()
                                                 rpt.lblSumMenge.Text = sumMenge.ToString("N0")
                                                 'rpt.lblSumPreis.Text = sumPreis.ToString("N2")
                                                 rpt.lblSumNetto.Text = sumNetto.ToString("N2")
                                                 rpt.lblSumMwst.Text = sumMWST.ToString("N2")
                                                 rpt.lblSumBrutto.Text = sumBrutto.ToString("N2")

                                             End Sub

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

    Sub genSummenbericht_ASFINAG()
        Dim displayFilter = False
        Dim sqlstr As String = ""


        sqlstr &= " SELECT     dbo.TTRBody.CardNumber,Adressen.AdressenNr AS KundenNr,Adressen.[Name 1], dbo.CLFArchiv.vehicleLicensePlate,dbo.TTRBody.DeliveryDate, 'ASFINAG ' + ISNULL(dbo.tblWarenarten.WarenartDE, dbo.tblWarenarten.ProductCode) as ProductCode,dbo.TTRBody.amountInclVAT - dbo.TTRBody.VATAmount as Netamount,dbo.TTRBody.VATAmount,dbo.TTRBody.amountInclVAT
                        FROM         dbo.CLFArchiv RIGHT OUTER JOIN
                      dbo.TTRBody ON dbo.CLFArchiv.OBUID = dbo.TTRBody.InfoField LEFT OUTER JOIN
                      dbo.tblWarenarten ON dbo.TTRBody.ProductCode = dbo.tblWarenarten.ProductCode
					  INNER JOIN [VERAG].[dbo].Kreditkarten ON dbo.TTRBody.CardNumber = Kreditkarten.KartenNr
					  INNER JOIN [VERAG].[dbo].Adressen ON Adressen.AdressenNr = Kreditkarten.AdressenNr
                    WHERE (dbo.TTRBody.PKHistory = 0) AND (dbo.TTRBody.PKFileName LIKE N'" & checkifTestfiles() & ".%') AND (TTRBody.abrechnungsdatum = '" & Datum_Abrechnungsdaten.Value.ToShortDateString & "')
                    ORDER BY dbo.TTRBody.CardNumber"


        Dim dt As DataTable = SQL.loadDgvBySql_Param(sqlstr, "ASFINAG")
        'DataGridView.DataSource = dt


        Dim print As New frmPrintLayout
        print.Text = "ASFINAG"

        Dim rpt As New rptASFINAG_TransaktionenSumary

        rpt.DataSource = dt


        'If cbxProdukt.Checked Then
        '    rpt.GroupHeader2.DataField = "prod_descr"
        'Else
        '    rpt.GroupHeader2.Visible = False
        '    rpt.GroupFooter2.Visible = False
        'End If



        Dim sum = 0
        rpt.lblUeberschrift.Text = "ASFINAG Summenbericht " & CDate(Datum_Abrechnungsdaten.Value.ToShortDateString)
        rpt.lblSachbearbeiter.Text = VERAG_PROG_ALLGEMEIN.cAllgemein.USRNAME
        'rpt.lblMandantNiederlassung.Text = PERSONAL.Mandant & "  /  " & PERSONAL.Niederlassung

        'Dim cnt As Integer = 0
        rpt.lblDat.Text = Now.ToLongDateString





        Dim sumNetto As Double = 0
        Dim sumMWST As Double = 0
        Dim sumBrutto As Double = 0

        Dim sumperKdNrNetto As Double = 0
        Dim sumperKdNrMWST As Double = 0
        Dim sumperKdNrBrutto As Double = 0


        AddHandler rpt.Detail.Format, Sub()


                                          rpt.lblKundennr.Text = SQL.isDbnullEmpty(rpt.Fields.Item("KundenNr").Value, "")
                                          rpt.lblName1.Text = SQL.isDbnullEmpty(rpt.Fields.Item("Name 1").Value, "")
                                          rpt.lblKartennr.Text = SQL.isDbnullEmpty(rpt.Fields.Item("CardNumber").Value, "") & " - " & SQL.isDbnullEmpty(rpt.Fields.Item("ProductCode").Value, "")

                                          rpt.lblNetto.Text = SQL.isDbnullEmptyDbl(rpt.Fields.Item("Netamount").Value, 2, "")
                                          rpt.lblMWST.Text = SQL.isDbnullEmptyDbl(rpt.Fields.Item("VATAmount").Value, 2, "")
                                          rpt.lblBrutto.Text = SQL.isDbnullEmptyDbl(rpt.Fields.Item("amountInclVAT").Value, 2, "")


                                          rpt.lblSumNet.Text = SQL.isDbnullEmptyDbl(rpt.Fields.Item("Netamount").Value, 2, "")
                                          rpt.lblSumVat.Text = SQL.isDbnullEmptyDbl(rpt.Fields.Item("VATAmount").Value, 2, "")
                                          rpt.lblSumBrt.Text = SQL.isDbnullEmptyDbl(rpt.Fields.Item("amountInclVAT").Value, 2, "")

                                          sumNetto += SQL.isDbnullEmptyDbl(rpt.Fields.Item("Netamount").Value, 4, 0)
                                          sumMWST += SQL.isDbnullEmptyDbl(rpt.Fields.Item("VATAmount").Value, 4, 0)
                                          sumBrutto += SQL.isDbnullEmptyDbl(rpt.Fields.Item("amountInclVAT").Value, 4, 0)


                                      End Sub


        AddHandler rpt.ReportFooter1.Format, Sub()

                                                 rpt.lblSumNetto.Text = sumNetto.ToString("N2")
                                                 rpt.lblSumMwst.Text = sumMWST.ToString("N2")
                                                 rpt.lblSumBrutto.Text = sumBrutto.ToString("N2")

                                             End Sub

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



    Sub initDgv_PLOSE()
        With MyDatagridview1
            .Columns.Clear()
            .SET_SQL("  SELECT plose_POLSEKundennummer,  count(*) Anzahl,plose_ProduktCode,max(plose_Produktbeschreibung) as plose_Produktbeschreibung, sum(plose_Menge) as plose_Menge,sum(plose_Preis) as plose_Preis,sum(plose_NettobetragWaehrungAbbuchung) as plose_NettobetragWaehrungAbbuchung,sum(plose_MWSTBetragWaehrungAbbuchung) as plose_MWSTBetragWaehrungAbbuchung,sum(plose_BruttobetragWaehrungAbbuchung) as plose_BruttobetragWaehrungAbbuchung 
                        FROM tblPLOSE_Details
                        WHERE 1 = 1 
                            And plose_DatumTransaktion between '" & dat_Sum_Von.Value & "' and '" & dat_Sum_Bis.Value & "' 
                            AND plose_Fakturiert=0 
                            AND  plose_ProduktCode NOT IN (" & ProduktCode_NOT_IN & ")
                        group by plose_POLSEKundennummer,plose_ProduktCode
                        order by plose_POLSEKundennummer,plose_ProduktCode", "FMZOLL")
            .LOAD()
            'TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT
            If .Columns.Count > 0 Then

                .Columns("plose_POLSEKundennummer").HeaderText = "PLOSE KdNr"
                .Columns("plose_ProduktCode").HeaderText = "ProduktCode"
                .Columns("plose_Produktbeschreibung").HeaderText = "Beschreibung"
                .Columns("plose_Produktbeschreibung").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
                .Columns("plose_Menge").HeaderText = "Menge"
                .Columns("plose_Preis").HeaderText = "Preis"
                .Columns("plose_NettobetragWaehrungAbbuchung").HeaderText = "Netto"
                .Columns("plose_MWSTBetragWaehrungAbbuchung").HeaderText = "MWST"
                .Columns("plose_BruttobetragWaehrungAbbuchung").HeaderText = "Brutto"

                '.Columns("VERAGLeistungsNr").ReadOnly = False
                '.Columns("VERAGKdNr").ReadOnly = False

                'For Each r As DataGridViewColumn In .Columns
                '    If r.Name = "VERAGLeistungsNr" Or r.Name = "VERAGKdNr" Then
                '        r.ReadOnly = False
                '    Else
                '        r.ReadOnly = True
                '    End If
                'Next


                Dim c As New DataGridViewTextBoxColumn
                c.Name = "VERAGKdNr"
                c.HeaderText = "VERAG KdNr"
                c.Width = 100
                .Columns.Insert(1, c)

                c = New DataGridViewTextBoxColumn
                c.Name = "VERAGLeistungsNr"
                c.HeaderText = "VERAG/PLOSE LeistungsNr."
                c.Width = 100
                .Columns.Insert(2, c)

                c = New DataGridViewTextBoxColumn
                c.Name = "KundeOffertenNr"
                c.HeaderText = "Kunde OffertenNr."
                c.Width = 100
                .Columns.Insert(3, c)

                c = New DataGridViewTextBoxColumn
                c.Name = "KundeLeistungsNr"
                c.HeaderText = "Kunde LeistungsNr."
                c.Width = 100
                .Columns.Insert(4, c)



                .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells

            End If

            Dim sumBto As Double = 0
            Dim sumNto As Double = 0
            For Each r As DataGridViewRow In .Rows
                sumBto += If(IsNumeric(r.Cells("plose_BruttobetragWaehrungAbbuchung").Value), CDbl(r.Cells("plose_BruttobetragWaehrungAbbuchung").Value), 0)
                sumNto += If(IsNumeric(r.Cells("plose_NettobetragWaehrungAbbuchung").Value), CDbl(r.Cells("plose_NettobetragWaehrungAbbuchung").Value), 0)
            Next

            txtAnzahl.Text = .Rows.Count
            txtPruefsummeNetto.Text = CDbl(sumNto).ToString("C2")
            txtPruefsummeBrutto.Text = CDbl(sumBto).ToString("C2")
            .ClearSelection()

        End With

    End Sub
    Sub initDgv_UTA()
        With MyDatagridview1
            .Columns.Clear()
            Exit Sub
            'MsgBox(.sql)

            .SET_SQL("  SELECT Adressen.AdressenNr, Adressen.[Name 1], Adressen.LandKz, Adressen.Ort,Offertenpositionen.OffertenNr, Offertenpositionen.LeistungsNr, Offertenpositionen.LeistungsBez, tblUTAFakturierwarenarten.Warenart, tblUTAImport.Fakturierwarenart
                        FROM tblUTAFakturierwarenarten 
                        INNER JOIN (((Adressen INNER JOIN tblUTAImport ON Adressen.UTAKundenNr = tblUTAImport.Kundennummer) 
                        INNER JOIN Offertenpositionen ON Adressen.AdressenNr = Offertenpositionen.KundenNr) 
                        INNER JOIN tblUTALeistungen ON (tblUTALeistungen.VERAG_LeistungsNr = Offertenpositionen.LeistungsNr) AND (tblUTALeistungen.VERAG_OffertenNr = Offertenpositionen.OffertenNr) AND (tblUTAImport.Lieferland = tblUTALeistungen.Lieferland) AND (tblUTAImport.Fakturierwarenart = tblUTALeistungen.Fakturierwarenart)) ON tblUTAFakturierwarenarten.Fakturierwarenart = tblUTALeistungen.Fakturierwarenart
                        group by Adressen.AdressenNr, Adressen.[Name 1], Adressen.LandKz, Adressen.Ort, Offertenpositionen.OffertenNr, Offertenpositionen.LeistungsNr, Offertenpositionen.LeistungsBez, tblUTAFakturierwarenarten.Warenart,tblUTAImport.Fakturierwarenart", "FMZOLL")
            .LOAD()
            'MsgBox(.GET_SQL())
            If .Columns.Count > 0 Then

                '.Columns("plose_POLSEKundennummer").HeaderText = "PLOSE KdNr"
                '.Columns("plose_ProduktCode").HeaderText = "ProduktCode"
                '.Columns("plose_Produktbeschreibung").HeaderText = "Beschreibung"
                '.Columns("plose_Produktbeschreibung").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
                '.Columns("plose_Menge").HeaderText = "Menge"
                '.Columns("plose_Preis").HeaderText = "Preis"
                '.Columns("plose_NettobetragWaehrungAbbuchung").HeaderText = "Netto"
                '.Columns("plose_MWSTBetragWaehrungAbbuchung").HeaderText = "MWST"
                '.Columns("plose_BruttobetragWaehrungAbbuchung").HeaderText = "Brutto"

                '.Columns("VERAGLeistungsNr").ReadOnly = False
                '.Columns("VERAGKdNr").ReadOnly = False

                'For Each r As DataGridViewColumn In .Columns
                '    If r.Name = "VERAGLeistungsNr" Or r.Name = "VERAGKdNr" Then
                '        r.ReadOnly = False
                '    Else
                '        r.ReadOnly = True
                '    End If
                'Next


                'Dim c As New DataGridViewTextBoxColumn
                'c.Name = "VERAGKdNr"
                'c.HeaderText = "VERAG KdNr"
                'c.Width = 100
                '.Columns.Insert(1, c)

                'c = New DataGridViewTextBoxColumn
                'c.Name = "VERAGLeistungsNr"
                'c.HeaderText = "VERAG/PLOSE LeistungsNr."
                'c.Width = 100
                '.Columns.Insert(2, c)

                'c = New DataGridViewTextBoxColumn
                'c.Name = "KundeOffertenNr"
                'c.HeaderText = "Kunde OffertenNr."
                'c.Width = 100
                '.Columns.Insert(3, c)

                'c = New DataGridViewTextBoxColumn
                'c.Name = "KundeLeistungsNr"
                'c.HeaderText = "Kunde LeistungsNr."
                'c.Width = 100
                '.Columns.Insert(4, c)



                .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells

            End If

            'Dim sumBto As Double = 0
            'Dim sumNto As Double = 0
            'For Each r As DataGridViewRow In .Rows
            '    sumBto += If(IsNumeric(r.Cells("plose_BruttobetragWaehrungAbbuchung").Value), CDbl(r.Cells("plose_BruttobetragWaehrungAbbuchung").Value), 0)
            '    sumNto += If(IsNumeric(r.Cells("plose_NettobetragWaehrungAbbuchung").Value), CDbl(r.Cells("plose_NettobetragWaehrungAbbuchung").Value), 0)
            'Next

            'txtAnzahl.Text = .Rows.Count
            'txtPruefsummeNetto.Text = CDbl(sumNto).ToString("C2")
            'txtPruefsummeBrutto.Text = CDbl(sumBto).ToString("C2")
            .ClearSelection()

        End With

    End Sub

    Sub initDgv_ASFINAG(abgerechnet As Boolean)

        dat_Sum_Von.Value = CDate(SQL.getValueTxtBySql("SELECT Abrechnungsdatum FROM Abrechnungsdatum", "ASFINAG"))
        Dim sqlString = "AND (TTRBody.abrechnungsdatum " & IIf(abgerechnet, "= '" & Datum_Abrechnungsdaten.Value.ToShortDateString & "')", "is null)")
        With MyDatagridview1
            .Columns.Clear()
            'MsgBox(.sql)

            .SET_SQL(" SELECT dbo.TTRBody.OBUID,dbo.TTRBody.CardNumber,dbo.TTRBody.receiptNumber,dbo.TTRBody.receiptNumber,dbo.TTRBody.VATAmount,dbo.TTRBody.amountInclVAT,dbo.TTRBody.abrechnungsdatum, dbo.tblWarenarten.WarenartDE, dbo.CLFArchiv.vehicleLicensePlate
                            FROM dbo.CLFArchiv RIGHT OUTER JOIN
                                dbo.TTRBody ON dbo.CLFArchiv.OBUID = dbo.TTRBody.InfoField LEFT OUTER JOIN
                                dbo.tblWarenarten ON dbo.TTRBody.ProductCode = dbo.tblWarenarten.ProductCode
                            WHERE (dbo.TTRBody.PKHistory = 0) AND (dbo.TTRBody.PKFileName LIKE N'" & checkifTestfiles() & ".%')" & sqlString & "
                            ORDER BY dbo.TTRBody.CardNumber, dbo.TTRBody.FileCreationDate, dbo.TTRBody.PKHistory, dbo.TTRBody.PKFileName, dbo.TTRBody.PKLine", "ASFINAG")
            .LOAD()
            'MsgBox(.GET_SQL())
            If .Columns.Count > 0 Then

                .Columns("WarenartDE").HeaderText = "Warenart"
                .Columns("vehicleLicensePlate").HeaderText = "LKW-KZ"
                .Columns("OBUID").HeaderText = "OBUID"
                .Columns("OBUID").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
                .Columns("CardNumber").HeaderText = "Kartennummer"
                .Columns("abrechnungsdatum").HeaderText = "Abrechnungsdatum"
                .Columns("receiptNumber").HeaderText = "Rechnugnsnummer"
                .Columns("VATAmount").HeaderText = "MWST"
                .Columns("amountInclVAT").HeaderText = "Brutto"

                '.Columns("VERAGLeistungsNr").ReadOnly = False
                '.Columns("VERAGKdNr").ReadOnly = False

                'For Each r As DataGridViewColumn In .Columns
                '    If r.Name = "VERAGLeistungsNr" Or r.Name = "VERAGKdNr" Then
                '        r.ReadOnly = False
                '    Else
                '        r.ReadOnly = True
                '    End If
                'Next


                'Dim c As New DataGridViewTextBoxColumn
                'c.Name = "VERAGKdNr"
                'c.HeaderText = "VERAG KdNr"
                'c.Width = 100
                '.Columns.Insert(1, c)

                'c = New DataGridViewTextBoxColumn
                'c.Name = "VERAGLeistungsNr"
                'c.HeaderText = "VERAG/PLOSE LeistungsNr."
                'c.Width = 100
                '.Columns.Insert(2, c)

                'c = New DataGridViewTextBoxColumn
                'c.Name = "KundeOffertenNr"
                'c.HeaderText = "Kunde OffertenNr."
                'c.Width = 100
                '.Columns.Insert(3, c)

                'c = New DataGridViewTextBoxColumn
                'c.Name = "KundeLeistungsNr"
                'c.HeaderText = "Kunde LeistungsNr."
                'c.Width = 100
                '.Columns.Insert(4, c)



                .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells

            End If

            Dim sumBto As Double = 0
            Dim sumNto As Double = 0
            For Each r As DataGridViewRow In .Rows
                sumBto += If(IsNumeric(r.Cells("amountInclVAT").Value), CDbl(r.Cells("amountInclVAT").Value), 0)
                sumNto += If(IsNumeric(r.Cells("amountInclVAT").Value AndAlso r.Cells("VATAmount").Value), CDbl(r.Cells("amountInclVAT").Value) - r.Cells("VATAmount").Value, 0)
            Next

            txtAnzahl.Text = .Rows.Count
            txtPruefsummeNetto.Text = CDbl(sumNto).ToString("C2")
            txtPruefsummeBrutto.Text = CDbl(sumBto).ToString("C2")
            .ClearSelection()

        End With

    End Sub


    Private Sub btn_Click(sender As Object, e As EventArgs) Handles btn.Click
        initLieferant("PLOSE", sender)
    End Sub

    Sub initLieferant(l As String, btn As Button)
        MyDatagridview1.DataSource = Nothing
        Me.LIEFERANT = l
        Panel3.Controls.Clear()

        For Each c As Button In FlowLayoutPanel.Controls
            If c Is btn Then
                c.BackColor = Color.Wheat
            Else
                c.BackColor = Color.FloralWhite
            End If
        Next

        Select Case Me.LIEFERANT
            Case "PLOSE"
                Panel4.Visible = True
                pnlAsfinag.Visible = False
                Dim c As New usrCntlMDMDatenverarbeitungAuswertungen_PLOSE(Me)
                Panel3.Controls.Add(c)
                c.Dock = DockStyle.Fill
            Case "UTA"
                Panel4.Visible = False
                pnlAsfinag.Visible = False
                'Dim c As New usrCntlMDMDatenverarbeitungAuswertungen_UTA(Me)
                'Panel3.Controls.Add(c)
                'c.Dock = DockStyle.Fill
            Case "ASFINAG"
                Panel4.Visible = False
                pnlAsfinag.Visible = True

        End Select

        init()
    End Sub



    Function genRGAtt_PLOSE() As Boolean
        Dim dt_Main As DataTable = SQL.loadDgvBySql_Param("SELECT [AdressenNr],PLOSEKundenNr FROM tblPLOSE_Details INNER JOIN Adressen ON plose_POLSEKundennummer=PLOSEKundenNr  where plose_Fakturiert = 0 AND  plose_ProduktCode NOT IN (" & ProduktCode_NOT_IN & " ) AND  plose_DatumTransaktion between '" & dat_Sum_Von.Value.ToShortDateString & "' and '" & dat_Sum_Bis.Value.ToShortDateString & "'  group by [AdressenNr],PLOSEKundenNr ", "FMZOLL")
        'MsgBox("Keine Daten!""SELECT [AdressenNr],PLOSEKundenNr FROM tblPLOSE_Details INNER JOIN Adressen ON plose_POLSEKundennummer=PLOSEKundenNr  where AND plose_Fakturiert = 0 AND  plose_DatumTransaktion between '" & dat_Sum_Von.Value.ToShortDateString & "' and '" & dat_Sum_Bis.Value.ToShortDateString & "'  group by [AdressenNr],PLOSEKundenNr ")
        If dt_Main Is Nothing OrElse dt_Main.Rows.Count = 0 Then
            MsgBox("Keine Daten!")
            Return False
        End If
        Dim cnt = 0
        If vbYes = MsgBox("Es wurden Daten von " & dt_Main.Rows.Count & " Kunden gefunden " & vbNewLine & " Möchten Sie die Anhänge erstellen?", vbYesNoCancel) Then
            Dim dir = "F:\FMZoll\Maut\PLOSE\" & Now.ToShortDateString

            If Directory.Exists(dir) Then dir &= "_" & Now.ToShortTimeString.Replace(":", "")
            Directory.CreateDirectory(dir)
            For Each R_PLOSE In dt_Main.Rows

                Dim SPEDBUCH As VERAG_PROG_ALLGEMEIN.cSpeditionsbuch = Nothing
                Dim verarbOK = True
                If Not genPLOSE_SPEDBUCH_ByKdNr(R_PLOSE("AdressenNr"), R_PLOSE("PLOSEKundenNr"), dat_Sum_Von.Value.ToShortDateString, dat_Sum_Bis.Value.ToShortDateString, SPEDBUCH) Then verarbOK = False
                If Not genPLOSE_RECHNUNG_BySPEDBUCH(R_PLOSE("AdressenNr"), R_PLOSE("PLOSEKundenNr"), SPEDBUCH, dat_Sum_Von.Value, dat_Sum_Bis.Value) Then verarbOK = False
                ' ANHÄNGE WERDEN NCIHT BENÖTIGT::genPLOSEAttachmentByKdNr(R_PLOSE("AdressenNr"), R_PLOSE("PLOSEKundenNr"), dat_Sum_Von.Value.ToShortDateString, dat_Sum_Bis.Value.ToShortDateString, dir)

                If verarbOK Then
                    'UPDATE Fakturiert
                    SQL.doSQL("UPDATE tblPLOSE_Details SET plose_FakturiertDatum=GETDATE() WHERE plose_Fakturiert = 0  AND plose_DatumTransaktion between '" & dat_Sum_Von.Value.ToShortDateString & "' and '" & dat_Sum_Bis.Value.ToShortDateString & "' AND plose_POLSEKundennummer='" & R_PLOSE("PLOSEKundenNr") & "'  ", "FMZOLL")
                End If

                If True Then 'cnt Mod 10 = 0 Then
                    txtPloseAnh_Einarbeitung.Text = cnt & " / " & dt_Main.Rows.Count
                    Dim proz As Double = (cnt / dt_Main.Rows.Count) * 100
                    pbPloseAnh_Proz.Value = proz
                    lblPloseAnh_Proz.Text = proz.ToString("N2") & " %"
                    'GroupBox12.Refresh()
                    My.Application.DoEvents()
                End If
                cnt += 1
            Next

            ' ANHÄNGE WERDEN NCIHT BENÖTIGT::
            'Alle Alangen im foglenden VZ löschen und die aktuellen kopieren:
            'Dim dirAnhang = "F:\FMZoll\Maut\PLOSE\Anlagen\"
            'If Directory.Exists(dirAnhang) Then 'Directory.Delete(dirAnhang, True)
            '    For Each f In Directory.GetFiles(dirAnhang)
            '        File.Delete(f)
            '    Next
            'End If
            'If Not Directory.Exists(dirAnhang) Then Directory.CreateDirectory(dirAnhang)

            'For Each f In Directory.GetFiles(dir)
            '    File.Copy(f, dirAnhang & (New FileInfo(f)).Name)
            'Next

            'IN FMZOLL / DB MautD einfügen --> Mautbericht
            'genPLOSEInsertMautD(dat_Sum_Von.Value.ToShortDateString, dat_Sum_Bis.Value.ToShortDateString)


            pbPloseAnh_Proz.Value = 100
            txtPloseAnh_Einarbeitung.Text = dt_Main.Rows.Count & " / " & dt_Main.Rows.Count
            lblPloseAnh_Proz.Text = "100.00 %"

            Return True
        End If
        Return False
    End Function

    Function genRGAtt_UTA() As Boolean
        Dim top = ""
        'top = " TOP 20 "
        Dim SQLStr = " 	SELECT " & top & " Kundennummer AS [Customer ID], KundenNr AS [Customer Nr], UTAExportCSV,Rechnungsdruck
                        FROM tblUTAFakturierwarenarten 
                        INNER JOIN (((Adressen INNER JOIN tblUTAImport ON Adressen.UTAKundenNr = tblUTAImport.Kundennummer) 
                        INNER JOIN Offertenpositionen ON Adressen.AdressenNr = Offertenpositionen.KundenNr)
                        INNER JOIN tblUTALeistungen ON (tblUTALeistungen.VERAG_LeistungsNr = Offertenpositionen.LeistungsNr) AND (tblUTALeistungen.VERAG_OffertenNr = Offertenpositionen.OffertenNr) AND (tblUTAImport.Lieferland = tblUTALeistungen.Lieferland) AND (tblUTAImport.Fakturierwarenart = tblUTALeistungen.Fakturierwarenart)) ON tblUTAFakturierwarenarten.Fakturierwarenart = tblUTALeistungen.Fakturierwarenart
                        group by Kundennummer, KundenNr, UTAExportCSV,Rechnungsdruck
                        "
        'Dim SQLStr = " 	SELECT TOP 3 [Customer ID],[Customer Nr], UTAExportCSV,Rechnungsdruck  , sum(  Gesamtbetrag_Brutto_in_Darstellwährung  )
        ' FROM(
        '              	    SELECT  Kundennummer AS [Customer ID], KundenNr AS [Customer Nr], UTAExportCSV,Rechnungsdruck  ,  (  Gesamtbetrag_Brutto_in_Darstellwährung  )
        '                    FROM tblUTAImport 
        '                    INNER JOIN  Adressen ON Adressen.UTAKundenNr = tblUTAImport.Kundennummer
        '     INNER JOIN Offertenpositionen ON Adressen.AdressenNr = Offertenpositionen.KundenNr  
        '  INNER JOIN tblUTALeistungen ON (tblUTALeistungen.VERAG_LeistungsNr = Offertenpositionen.LeistungsNr) AND (tblUTALeistungen.VERAG_OffertenNr = Offertenpositionen.OffertenNr) AND (tblUTAImport.Lieferland = tblUTALeistungen.Lieferland) AND (tblUTAImport.Fakturierwarenart = tblUTALeistungen.Fakturierwarenart)
        '  INNER JOIN tblUTAFakturierwarenarten ON tblUTAFakturierwarenarten.Fakturierwarenart = tblUTALeistungen.Fakturierwarenart
        '              	    ) as T1   /*WHERE Gesamtbetrag_Brutto_in_Darstellwährung <>0*/
        '                 group by [Customer ID],[Customer Nr], UTAExportCSV,Rechnungsdruck
        '                "
        Dim dt_Main As DataTable = SQL.loadDgvBySql_Param(SQLStr, "FMZOLL", 1200)
        'MsgBox("Keine Daten!""SELECT [AdressenNr],PLOSEKundenNr FROM tblPLOSE_Details INNER JOIN Adressen ON plose_POLSEKundennummer=PLOSEKundenNr  where AND plose_Fakturiert = 0 AND  plose_DatumTransaktion between '" & dat_Sum_Von.Value.ToShortDateString & "' and '" & dat_Sum_Bis.Value.ToShortDateString & "'  group by [AdressenNr],PLOSEKundenNr ")
        If dt_Main Is Nothing OrElse dt_Main.Rows.Count = 0 Then
            MsgBox("Keine Daten!")
            Return False
        End If
        Dim cnt = 0
        If vbYes = MsgBox("Es wurden Daten von " & dt_Main.Rows.Count & " Kunden gefunden " & vbNewLine & " Möchten Sie die Anhänge erstellen?", vbYesNoCancel) Then
            Dim dir = "F:\FMZoll\Maut\UTA\Archiv\" & Now.ToShortDateString

            If Directory.Exists(dir) Then dir &= "_" & Now.ToShortTimeString.Replace(":", "")
            Directory.CreateDirectory(dir)
            For Each R_PLOSE In dt_Main.Rows

                Dim SPEDBUCH As VERAG_PROG_ALLGEMEIN.cSpeditionsbuch = Nothing
                Dim verarbOK = True
                '   If Not genUTA_SPEDBUCH_ByKdNr(R_PLOSE("AdressenNr"), R_PLOSE("PLOSEKundenNr"), dat_Sum_Von.Value.ToShortDateString, dat_Sum_Bis.Value.ToShortDateString, SPEDBUCH) Then verarbOK = False
                '  If Not genUTA_RECHNUNG_BySPEDBUCH(R_PLOSE("AdressenNr"), R_PLOSE("PLOSEKundenNr"), SPEDBUCH, dat_Sum_Von.Value, dat_Sum_Bis.Value) Then verarbOK = False
                genUTAAttachmentByKdNr(R_PLOSE("Customer Nr"), R_PLOSE("Customer ID"), dir, datPloseAnhang.Value) 'R_PLOSE("AdressenNr"), R_PLOSE("PLOSEKundenNr"), dat_Sum_Von.Value.ToShortDateString, dat_Sum_Bis.Value.ToShortDateString, dir)

                If verarbOK Then
                    'UPDATE Fakturiert
                    '   SQL.doSQL("UPDATE tblPLOSE_Details SET plose_FakturiertDatum=GETDATE() WHERE plose_Fakturiert = 0  AND plose_DatumTransaktion between '" & dat_Sum_Von.Value.ToShortDateString & "' and '" & dat_Sum_Bis.Value.ToShortDateString & "' AND plose_POLSEKundennummer='" & R_PLOSE("PLOSEKundenNr") & "'  ", "FMZOLL")
                End If

                If True Then 'cnt Mod 10 = 0 Then
                    txtPloseAnh_Einarbeitung.Text = cnt & " / " & dt_Main.Rows.Count
                    Dim proz As Double = (cnt / dt_Main.Rows.Count) * 100
                    pbPloseAnh_Proz.Value = proz
                    lblPloseAnh_Proz.Text = proz.ToString("N2") & " %"
                    'GroupBox12.Refresh()
                    My.Application.DoEvents()
                End If
                cnt += 1
            Next

            ' ANHÄNGE WERDEN NCIHT BENÖTIGT::
            'Alle Alangen im foglenden VZ löschen und die aktuellen kopieren
            Dim dirAnhang = "F:\FMZoll\Maut\UTA\Anlagen\"
            If Directory.Exists(dirAnhang) Then 'Directory.Delete(dirAnhang, True)
                For Each f In Directory.GetFiles(dirAnhang)
                    File.Delete(f)
                Next
            End If
            If Not Directory.Exists(dirAnhang) Then Directory.CreateDirectory(dirAnhang)

            For Each f In Directory.GetFiles(dir)
                File.Copy(f, dirAnhang & (New FileInfo(f)).Name)
            Next

            'IN FMZOLL / DB MautD einfügen --> Mautbericht
            'genPLOSEInsertMautD(dat_Sum_Von.Value.ToShortDateString, dat_Sum_Bis.Value.ToShortDateString)


            pbPloseAnh_Proz.Value = 100
            txtPloseAnh_Einarbeitung.Text = dt_Main.Rows.Count & " / " & dt_Main.Rows.Count
            lblPloseAnh_Proz.Text = "100.00 %"

            Return True
        End If
        Return False
    End Function


    Function genPLOSEInsertMautD(von As Date, bis As Date) As Boolean
        Try
            pic.Visible = False
            Dim displayFilter = False
            Dim sqlstr As String = ""

            sqlstr &= " SELECT 'PLOSE',AdressenNr,plose_Kennzeichen,plose_DatumTransaktion,plp_Land,isnull([tblPLOSE_Produktbeschreibung].plp_Description_EN,plose_Produktbeschreibung) as plose_Produktbeschreibung ,isnull(plose_NummerKarteGeraet,plose_Kontonummer) as plose_NummerKarteGeraet ,plose_BeschreibungEinfahrt,plose_BeschreibungAusfahrt,plose_NettobetragWaehrungAbbuchung,(plose_BruttobetragWaehrungAbbuchung-plose_NettobetragWaehrungAbbuchung) as Steuer,plose_BruttobetragWaehrungAbbuchung "
            sqlstr &= " FROM tblPLOSE_Details INNER JOIN [tblPLOSE_Produktbeschreibung] on plose_ProduktCode=plp_ProductCode  INNER JOIN Adressen on plose_POLSEKundennummer=PLOSEKundenNr  and plp_LeistungsNr is not null   "
            sqlstr &= " WHERE 1=1  "
            sqlstr &= " AND plose_Fakturiert=0  AND  plose_ProduktCode NOT IN (" & ProduktCode_NOT_IN & " )  AND plp_Land NOT IN ('AT','DE') "
            sqlstr &= " AND plose_DatumTransaktion between '" & von.ToShortDateString & "' and '" & bis.ToShortDateString & "' "
            sqlstr &= " order by plp_Land, plose_DatumTransaktion"


            '  sqlstr &= " group by plose_ProduktCode" 
            '  MsgBox(sqlstr)
            Dim dt As DataTable = SQL.loadDgvBySql_Param(sqlstr, "FMZOLL")
            Dim sqlstrAT As String = ""

            sqlstrAT &= " SELECT 'PLOSE',AdressenNr,plose_Kennzeichen,plose_DatumTransaktion,plp_Land,'' as plose_Produktbeschreibung ,plose_NummerKarteGeraet as plose_NummerKarteGeraet ,'' as plose_BeschreibungEinfahrt,'' as plose_BeschreibungAusfahrt,sum(plose_NettobetragWaehrungAbbuchung) as plose_NettobetragWaehrungAbbuchung,sum(plose_BruttobetragWaehrungAbbuchung-plose_NettobetragWaehrungAbbuchung) as Steuer,sum(plose_BruttobetragWaehrungAbbuchung ) as plose_BruttobetragWaehrungAbbuchung "
            sqlstrAT &= " FROM tblPLOSE_Details INNER JOIN [tblPLOSE_Produktbeschreibung] on plose_ProduktCode=plp_ProductCode  INNER JOIN Adressen on plose_POLSEKundennummer=PLOSEKundenNr  and plp_LeistungsNr is not null  "
            sqlstrAT &= " WHERE 1=1  "
            sqlstrAT &= " AND plose_Fakturiert=0  AND  plose_ProduktCode NOT IN (" & ProduktCode_NOT_IN & " )  AND plp_Land IN ('AT','DE') "
            sqlstrAT &= " AND plose_DatumTransaktion between '" & von.ToShortDateString & "' and '" & bis.ToShortDateString & "' "
            sqlstrAT &= " group by plp_Land, AdressenNr, plose_Kennzeichen,plose_DatumTransaktion,plose_NummerKarteGeraet"
            sqlstrAT &= " order by plp_Land"


            '  sqlstr &= " group by plose_ProduktCode" 
            '  MsgBox(sqlstr)
            Dim dtAT As DataTable = SQL.loadDgvBySql_Param(sqlstrAT, "FMZOLL")


            'AT ---> Gruppiert
            If dtAT IsNot Nothing AndAlso dtAT.Rows.Count > 0 Then
                If dt Is Nothing OrElse dt.Rows.Count = 0 Then
                    dt = dtAT
                Else
                    For Each r In dtAT.Rows
                        dt.Rows.Add({r(0), r(1), r(2), r(3), r(4), r(5), r(6), r(7), r(8), r(9), r(10), r(11)})
                    Next
                End If
            End If

            Dim connectionString = ""
            If VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM Then
                connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\DEVELOPER\f\FMZoll\MautD.accdb"
            Else
                connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\FMZOLL.verag.ost.dmn\f\FMZoll\MautD.accdb"
            End If

            Dim con As New OleDbConnection(connectionString)
            Dim cmd As New OleDbCommand
            Dim var1 As String

            Dim adapter As OleDbDataAdapter = New OleDbDataAdapter()
            Dim reader As OleDbDataReader = Nothing



            If dt IsNot Nothing Then
                con.Open()
                For Each r In dt.Rows
                    Try
                        'Zeitstempel 

                        Dim SQLQuery = "INSERT INTO tblMautbericht (Datenquelle,[Customer No],[Licence Plate Number],[Transaction Date],[Transaction Country],[Product description],[Card Number],[Entry Terminal],[Exit Terminal],[Nett Amount],[VAT Amount],[Total Amount]) VALUES (@P1,@P2,@P3,@P4,@P5,@P6,@P7,@P8,@P9,@P10,@P11,@P12) "
                        '  "SELECT * FROM DBParent WHERE P_ID = " & UniqeID & ";"
                        Using Command As New OleDbCommand(SQLQuery, con)
                            'Command.Parameters.AddWithValue("@P1", r(0).ToString)
                            'Command.Parameters.AddWithValue("@P2", CInt(r(1)))
                            'Command.Parameters.AddWithValue("@P3", r(2).ToString)
                            'Command.Parameters.AddWithValue("@P4", CDate(r(3)))
                            'Command.Parameters.AddWithValue("@P5", r(4).ToString)
                            'Command.Parameters.AddWithValue("@P6", r(5).ToString)
                            'Command.Parameters.AddWithValue("@P7", r(6).ToString)
                            'Command.Parameters.AddWithValue("@P8", r(7).ToString)
                            'Command.Parameters.AddWithValue("@P9", r(8).ToString)
                            'Command.Parameters.AddWithValue("@P10", CDbl(r(9)))
                            'Command.Parameters.AddWithValue("@P11", CDbl(r(10)))
                            'Command.Parameters.AddWithValue("@P12", CDbl(r(11)))
                            '   .Parameters.AddWithValue("@P13", r(12))

                            Command.Parameters.AddWithValue("@P1", r(0))
                            Command.Parameters.AddWithValue("@P2", r(1))
                            Command.Parameters.AddWithValue("@P3", r(2))
                            Command.Parameters.AddWithValue("@P4", r(3))
                            Command.Parameters.AddWithValue("@P5", r(4))
                            Command.Parameters.AddWithValue("@P6", r(5))
                            Command.Parameters.AddWithValue("@P7", r(6))
                            Command.Parameters.AddWithValue("@P8", r(7))
                            Command.Parameters.AddWithValue("@P9", r(8))
                            Command.Parameters.AddWithValue("@P10", CDbl(r(9)))
                            Command.Parameters.AddWithValue("@P11", CDbl(r(10)))
                            Command.Parameters.AddWithValue("@P12", CDbl(r(11)))

                            Command.ExecuteNonQuery()
                            Command.Dispose()
                        End Using

                        'cmd = New OleDbCommand(SQLQuery, con)
                        'With cmd
                        '    .Parameters.AddWithValue("@P1", r(0))
                        '    .Parameters.AddWithValue("@P2", r(1))
                        '    .Parameters.AddWithValue("@P3", r(2))
                        '    .Parameters.AddWithValue("@P4", r(3))
                        '    .Parameters.AddWithValue("@P5", r(4))
                        '    .Parameters.AddWithValue("@P6", r(5))
                        '    .Parameters.AddWithValue("@P7", r(6))
                        '    .Parameters.AddWithValue("@P8", r(7))
                        '    .Parameters.AddWithValue("@P9", r(8))
                        '    .Parameters.AddWithValue("@P10", r(9))
                        '    .Parameters.AddWithValue("@P11", r(10))
                        '    .Parameters.AddWithValue("@P12", r(11))
                        '    '   .Parameters.AddWithValue("@P13", r(12))
                        '    cmd.Dispose()
                        '    .ExecuteNonQuery()
                        'End With

                    Catch ex2 As System.Exception
                        MsgBox("err: " & ex2.Message & ex2.StackTrace)

                    Finally
                        If reader IsNot Nothing Then reader.Close()
                    End Try


                Next
                con.Close()
            End If
            pic.Visible = True
            Return True

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

    End Function


    Function deleteMautD(Datenquelle As String) As Boolean
        Try
            Dim connectionString = ""
            If VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM Then
                connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\DEVELOPER\f\FMZoll\MautD.accdb"
            Else
                connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\FMZOLL.verag.ost.dmn\f\FMZoll\MautD.accdb"
            End If

            Dim con As New OleDbConnection(connectionString)
            Dim cmd As New OleDbCommand
            Dim var1 As String

            Dim adapter As OleDbDataAdapter = New OleDbDataAdapter()
            Dim reader As OleDbDataReader = Nothing


            Try
                con.Open()

                'Zeitstempel  
                Dim SQLQuery = "DELETE FROM tblMautbericht WHERE Datenquelle='" & Datenquelle & "' "
                Using Command As New OleDbCommand(SQLQuery, con)

                    Command.ExecuteNonQuery()
                    Command.Dispose()
                End Using

            Catch ex2 As System.Exception
                MsgBox("err: " & ex2.Message & ex2.StackTrace)

            Finally
                If reader IsNot Nothing Then reader.Close()
            End Try

            con.Close()

            Return True

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

    End Function

    Function genPLOSEAttachmentByKdNr(KdNr As String, PLOSEKundenNr As String, von As Date, bis As Date, dir As String)
        Try

            Dim displayFilter = False
            Dim sqlstr As String = ""

            sqlstr &= " SELECT 	 AdressenNr,tblPLOSE_Details.*,tblPLOSE_Produktbeschreibung.* "
            sqlstr &= " FROM tblPLOSE_Details INNER JOIN [tblPLOSE_Produktbeschreibung] on plose_ProduktCode=plp_ProductCode  INNER JOIN Adressen on plose_POLSEKundennummer=PLOSEKundenNr "
            sqlstr &= " WHERE 1=1 "
            sqlstr &= " AND plose_Fakturiert=0 "
            sqlstr &= " AND  plose_ProduktCode NOT IN (" & ProduktCode_NOT_IN & " ) "
            sqlstr &= " AND AdressenNr = '" & KdNr & "' "
            sqlstr &= " AND plose_DatumTransaktion between '" & von.ToShortDateString & "' and '" & bis.ToShortDateString & "' "

            '  sqlstr &= " group by plose_ProduktCode"
            sqlstr &= " order by plp_Land, plose_DatumTransaktion"

            Dim dt As DataTable = SQL.loadDgvBySql_Param(sqlstr, "FMZOLL")

            Dim rpt As New rptPLOSE_Anhang

            rpt.DataSource = dt

            rpt.txtKunde.Text = KdNr & " " & New VERAG_PROG_ALLGEMEIN.cAdressen(KdNr).FullName
            rpt.lblRgDatum.Text = datPloseAnhang.Value.ToShortDateString

            rpt.GroupHeaderKz.DataField = "plose_Kennzeichen" 'Gruppierung

            Dim sumNetto As Double = 0
            Dim sumMWST As Double = 0
            Dim sumBrutto As Double = 0

            Dim sumNettoKat As Double = 0
            Dim sumMWSTKat As Double = 0
            Dim sumBruttoKat As Double = 0

            Dim sumNettoGes As Double = 0
            Dim sumMWSTGes As Double = 0
            Dim sumBruttoGes As Double = 0

            Dim cntKat = 0
            Dim cnt = 0
            rpt.GroupFooterKat.Visible = False

            AddHandler rpt.Detail.Format, Sub()
                                              ' If cnt = 0 Then
                                              rpt.txtKunde.Text = SQL.isDbnullEmpty(rpt.Fields.Item("plose_POLSEKundennummer").Value, "") & " " & SQL.isDbnullEmpty(rpt.Fields.Item("plose_Firmenname").Value, "")
                                              ' End If

                                              '   rpt.txtProduktBeschreibung.Text = sql.isDbnullEmpty(rpt.Fields.Item("BC_DESCR").Value, "")
                                              Select Case "DE"
                                                  Case "DE" : rpt.txtProdukt.Text = SQL.isDbnullEmpty(rpt.Fields.Item("plp_Description_DE").Value, "") 'sql.isDbnullEmpty(rpt.Fields.Item("plose_ProduktCode").Value, "") & " - " & sql.isDbnullEmpty(rpt.Fields.Item("plose_Produktbeschreibung").Value, "")
                                                  Case "IT" : rpt.txtProdukt.Text = SQL.isDbnullEmpty(rpt.Fields.Item("plp_Description_IT").Value, "") 'sql.isDbnullEmpty(rpt.Fields.Item("plose_ProduktCode").Value, "") & " - " & sql.isDbnullEmpty(rpt.Fields.Item("plose_Produktbeschreibung").Value, "")
                                                  Case Else : rpt.txtProdukt.Text = SQL.isDbnullEmpty(rpt.Fields.Item("plp_Description_EN").Value, "") 'sql.isDbnullEmpty(rpt.Fields.Item("plose_ProduktCode").Value, "") & " - " & sql.isDbnullEmpty(rpt.Fields.Item("plose_Produktbeschreibung").Value, "")
                                              End Select

                                              rpt.txtKartennummer.Text = SQL.isDbnullEmpty(rpt.Fields.Item("plose_NummerKarteGeraet").Value, "")
                                              rpt.txtEingang.Text = SQL.isDbnullEmpty(rpt.Fields.Item("plose_BeschreibungEinfahrt").Value, "")
                                              rpt.txtAusgang.Text = SQL.isDbnullEmpty(rpt.Fields.Item("plose_BeschreibungAusfahrt").Value, "")
                                              rpt.txtLand.Text = SQL.isDbnullEmpty(rpt.Fields.Item("plp_Land").Value, "")
                                              rpt.txtDatum.Text = SQL.isDbnullEmpty(rpt.Fields.Item("plose_DatumTransaktion").Value, "")

                                              rpt.txtNetto.Text = SQL.isDbnullEmptyDbl(rpt.Fields.Item("plose_NettobetragWaehrungAbbuchung").Value, 2, "")
                                              rpt.txtMWST.Text = SQL.isDbnullEmptyDbl(rpt.Fields.Item("plose_MWSTBetragWaehrungAbbuchung").Value, 2, "")
                                              rpt.txtBrutto.Text = SQL.isDbnullEmptyDbl(rpt.Fields.Item("plose_BruttobetragWaehrungAbbuchung").Value, 2, "")

                                              sumNetto += SQL.isDbnullEmptyDbl(rpt.Fields.Item("plose_NettobetragWaehrungAbbuchung").Value, 4, 0)
                                              sumMWST += SQL.isDbnullEmptyDbl(rpt.Fields.Item("plose_MWSTBetragWaehrungAbbuchung").Value, 4, 0)
                                              sumBrutto += SQL.isDbnullEmptyDbl(rpt.Fields.Item("plose_BruttobetragWaehrungAbbuchung").Value, 4, 0)
                                              cnt += 1
                                          End Sub

            AddHandler rpt.GroupHeaderKz.Format, Sub()
                                                     rpt.txtKennzeichen.Text = SQL.isDbnullEmpty(rpt.Fields.Item("plose_Kennzeichen").Value, "")
                                                     If rpt.txtKennzeichen.Text = "" Then rpt.lblKennzeichen.Visible = False
                                                 End Sub
            AddHandler rpt.GroupHeaderKat.Format, Sub()
                                                      rpt.lblKategorie.Text = "MAUT REPORT"
                                                  End Sub

            AddHandler rpt.GroupFooterKz.Format, Sub()
                                                     rpt.txtNettoKzSum.Text = sumNetto.ToString("N2")
                                                     rpt.txtMWSTKzSum.Text = sumMWST.ToString("N2")
                                                     rpt.txtBruttoKzSum.Text = sumBrutto.ToString("N2")

                                                     rpt.lblSummeKennzeichen.Text = rpt.lblSummeKennzeichen.Text.Replace("Kennzeichen", SQL.isDbnullEmpty(rpt.Fields.Item("plose_Kennzeichen").Value, ""))
                                                 End Sub



            AddHandler rpt.GroupFooterKat.Format, Sub()
                                                      sumNettoKat += sumNetto
                                                      sumMWSTKat += sumMWST
                                                      sumBruttoKat += sumBrutto
                                                      sumNetto = 0
                                                      sumMWST = 0
                                                      sumBrutto = 0

                                                      rpt.txtNettoKatSum.Text = sumNettoKat.ToString("N2")
                                                      rpt.txtMWSTKatSum.Text = sumMWSTKat.ToString("N2")
                                                      rpt.txtBruttoKatSum.Text = sumBruttoKat.ToString("N2")
                                                      cntKat += 1
                                                  End Sub
            AddHandler rpt.ReportFooter1.Format, Sub()
                                                     sumNettoGes += sumNettoKat
                                                     sumMWSTGes += sumMWSTKat
                                                     sumBruttoGes += sumBruttoKat
                                                     sumNettoKat = 0
                                                     sumMWSTKat = 0
                                                     sumBruttoKat = 0

                                                     rpt.txtNettoGesSum.Text = sumNettoGes.ToString("N2")
                                                     rpt.txtMWSTGEsSum.Text = sumMWSTGes.ToString("N2")
                                                     rpt.txtBruttoGesSum.Text = sumBruttoGes.ToString("N2")



                                                     'If cntKat <= 1 Then
                                                     '    rpt.GroupFooterKat.Visible = False
                                                     'End If
                                                 End Sub

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



            Dim tmpPath = dir & "\" & KdNr & "_VERAG_Report.pdf"
            Dim p As New GrapeCity.ActiveReports.Export.Pdf.Section.PdfExport
            rpt.Run(False)
            p.NeverEmbedFonts = ""
            p.Export(rpt.Document, tmpPath)

            rpt.Dispose()

            Return tmpPath

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

    End Function
    Function genUTAAttachmentByKdNr(KdNr As String, UTAKdNr As String, dir As String, bis As Date) ', PLOSEKundenNr As String, von As Date, bis As Date, dir As String)
        Try

            Dim displayFilter = False
            Dim sqlstr As String = ""

            sqlstr &= " 
                        SELECT qryUTA_Fakturierungspositionen.KundenNr AS [Customer Nr], qryUTA_Fakturierungspositionen.Kundennummer AS [Customer ID], qryUTA_Fakturierungspositionen.[Name 1] AS [Customer name],  
                        cast([Belegdatum] + ' ' + dbo.timeserial(Left([Lieferzeit],2) , right(Left([Lieferzeit],4),2) , Right([Lieferzeit],2)) as datetime) AS [Transaction Date],
                        qryUTA_Fakturierungspositionen.Lieferzeit AS [Transaction Time], qryUTA_Fakturierungspositionen.Lieferland AS [Transaction Country], qryUTA_Fakturierungspositionen.Warenart AS [Product description], qryUTA_Fakturierungspositionen.Fakturierwarenart AS [Product Description ID], qryUTA_Fakturierungspositionen.Kartentyp AS [Card Type], qryUTA_Fakturierungspositionen.Kartennummer AS [Card number], 
                        isnull([KFZ_Kennzeichen_komprimiert],isnull([KFZ_Kennzeichen],isnull([Prägetext_i_d_R_KFZ_Kennzeichen],''))) AS LicencePlateNumber, qryUTA_Fakturierungspositionen.Autobahnauffahrt AS [Entry Terminal/Direction], qryUTA_Fakturierungspositionen.Autobahnausfahrt AS [Exit Terminal Description], qryUTA_Fakturierungspositionen.Gesamtbetrag_Brutto_in_Darstellwährung AS [Transaction Amount ( EUR )]
                        FROM 
                        (SELECT Adressen.AdressenNr, Adressen.[Name 1], Adressen.LandKz, Adressen.Ort, Adressen.UTAExportCSV, Adressen.Rechnungsdruck, Offertenpositionen.KundenNr, Offertenpositionen.OffertenNr, Offertenpositionen.LeistungsNr, Offertenpositionen.LeistungsBez, tblUTAFakturierwarenarten.Warenart, tblUTAImport.*
                        FROM tblUTAFakturierwarenarten INNER JOIN (((Adressen INNER JOIN tblUTAImport ON Adressen.UTAKundenNr = tblUTAImport.Kundennummer) INNER JOIN Offertenpositionen ON Adressen.AdressenNr = Offertenpositionen.KundenNr) INNER JOIN tblUTALeistungen ON (tblUTALeistungen.VERAG_LeistungsNr = Offertenpositionen.LeistungsNr) AND (tblUTALeistungen.VERAG_OffertenNr = Offertenpositionen.OffertenNr) AND (tblUTAImport.Lieferland = tblUTALeistungen.Lieferland) AND (tblUTAImport.Fakturierwarenart = tblUTALeistungen.Fakturierwarenart)) ON tblUTAFakturierwarenarten.Fakturierwarenart = tblUTALeistungen.Fakturierwarenart
                            WHERE Offertenpositionen.KundenNr='" & KdNr & "'
                        ) as qryUTA_Fakturierungspositionen
                        WHERE (((qryUTA_Fakturierungspositionen.Gesamtbetrag_Brutto_in_Darstellwährung)<>0))
                        order by LicencePlateNumber, [Card Type]
                      "

            '  sqlstr &= " group by plose_ProduktCode"
            ' sqlstr &= " order by plp_Land, plose_DatumTransaktion"

            Dim dt As DataTable = SQL.loadDgvBySql_Param(sqlstr, "FMZOLL")
            If dt Is DBNull.Value Then Return ""
            If dt.Rows.Count = 0 Then Return ""

            Dim rpt As New rptPLOSE_Anhang

            rpt.DataSource = dt

            rpt.txtKunde.Text = KdNr & " " & New VERAG_PROG_ALLGEMEIN.cAdressen(KdNr).FullName
            rpt.lblRgDatum.Text = datPloseAnhang.Value.ToShortDateString

            rpt.GroupHeaderKz.DataField = "LicencePlateNumber" 'Gruppierung


            rpt.txtNettoKzSum.Visible = False
            rpt.txtNettoGesSum.Visible = False
            rpt.txtNetto.Visible = False
            rpt.txtNettoKatSum.Visible = False
            rpt.lblNetto.Visible = False

            rpt.txtMWSTKzSum.Visible = False
            rpt.txtMWSTGEsSum.Visible = False
            rpt.txtMWST.Visible = False
            rpt.txtMWSTKatSum.Visible = False
            rpt.lblMWST.Visible = False

            rpt.lblBrutto.Text = "Total Amount ( EUR )"
            rpt.Label4.Text = bis.ToShortDateString
            rpt.Label2.Text = "UTA-KundenNr:"
            rpt.TextBox1.Text = UTAKdNr
            rpt.Label1.Text = " UTA Fleet Management Service"

            rpt.lblSummeKennzeichen.Visible = False
            rpt.lblService.Visible = False

            'rpt.lblSummeKennzeichen.Location = New PointF(rpt.lblSummeKennzeichen.Location.X + 4.5, rpt.lblSummeKennzeichen.Location.Y)
            'rpt.lblSumKategorie.Location = New PointF(rpt.lblSumKategorie.Location.X + 4.5, rpt.lblSumKategorie.Location.Y)
            'rpt.lblGessumme.Location = New PointF(rpt.lblGessumme.Location.X + 4.5, rpt.lblGessumme.Location.Y)

            Dim sumNetto As Double = 0
            Dim sumMWST As Double = 0
            Dim sumBrutto As Double = 0

            Dim sumNettoKat As Double = 0
            Dim sumMWSTKat As Double = 0
            Dim sumBruttoKat As Double = 0

            Dim sumNettoGes As Double = 0
            Dim sumMWSTGes As Double = 0
            Dim sumBruttoGes As Double = 0

            Dim cntKat = 0
            Dim cnt = 0
            rpt.GroupFooterKat.Visible = False

            AddHandler rpt.Detail.Format, Sub()
                                              ' If cnt = 0 Then
                                              rpt.txtKunde.Text = SQL.isDbnullEmpty(rpt.Fields.Item("Customer ID").Value, "")
                                              rpt.txtKunde.Text &= " " & SQL.isDbnullEmpty(rpt.Fields.Item("Customer name").Value, "")
                                              ' End If

                                              '   rpt.txtProduktBeschreibung.Text = sql.isDbnullEmpty(rpt.Fields.Item("BC_DESCR").Value, "")
                                              Select Case "DE"
                                                  Case "DE" : rpt.txtProdukt.Text = SQL.isDbnullEmpty(rpt.Fields.Item("Product description").Value, "") 'sql.isDbnullEmpty(rpt.Fields.Item("plose_ProduktCode").Value, "") & " - " & sql.isDbnullEmpty(rpt.Fields.Item("plose_Produktbeschreibung").Value, "")
                                                  Case "IT" : rpt.txtProdukt.Text = SQL.isDbnullEmpty(rpt.Fields.Item("Product description").Value, "") 'sql.isDbnullEmpty(rpt.Fields.Item("plose_ProduktCode").Value, "") & " - " & sql.isDbnullEmpty(rpt.Fields.Item("plose_Produktbeschreibung").Value, "")
                                                  Case Else : rpt.txtProdukt.Text = SQL.isDbnullEmpty(rpt.Fields.Item("Product description").Value, "") 'sql.isDbnullEmpty(rpt.Fields.Item("plose_ProduktCode").Value, "") & " - " & sql.isDbnullEmpty(rpt.Fields.Item("plose_Produktbeschreibung").Value, "")
                                              End Select

                                              rpt.txtKartennummer.Text = SQL.isDbnullEmpty(rpt.Fields.Item("Card number").Value, "")
                                              rpt.txtEingang.Text = SQL.isDbnullEmpty(rpt.Fields.Item("Entry Terminal/Direction").Value, "")
                                              rpt.txtAusgang.Text = SQL.isDbnullEmpty(rpt.Fields.Item("Exit Terminal Description").Value, "")
                                              rpt.txtLand.Text = SQL.isDbnullEmpty(rpt.Fields.Item("Transaction Country").Value, "")
                                              rpt.txtDatum.Text = SQL.isDbnullEmpty(rpt.Fields.Item("Transaction Date").Value, "")
                                              rpt.txtEingang.Text = SQL.isDbnullEmpty(rpt.Fields.Item("Card Type").Value, "")

                                              rpt.txtNetto.Text = "" 'SQL.isDbnullEmptyDbl(rpt.Fields.Item("plose_NettobetragWaehrungAbbuchung").Value, 2, "")
                                              rpt.txtMWST.Text = "" 'SQL.isDbnullEmptyDbl(rpt.Fields.Item("plose_MWSTBetragWaehrungAbbuchung").Value, 2, "")
                                              rpt.txtBrutto.Text = SQL.isDbnullEmptyDbl(rpt.Fields.Item("Transaction Amount ( EUR )").Value, 2, "")

                                              sumNetto += 0 'SQL.isDbnullEmptyDbl(rpt.Fields.Item("plose_NettobetragWaehrungAbbuchung").Value, 4, 0)
                                              sumMWST += 0 'SQL.isDbnullEmptyDbl(rpt.Fields.Item("plose_MWSTBetragWaehrungAbbuchung").Value, 4, 0)
                                              sumBrutto += SQL.isDbnullEmptyDbl(rpt.Fields.Item("Transaction Amount ( EUR )").Value, 4, 0)
                                              cnt += 1
                                          End Sub

            AddHandler rpt.GroupHeaderKz.Format, Sub()
                                                     rpt.txtKennzeichen.Text = SQL.isDbnullEmpty(rpt.Fields.Item("LicencePlateNumber").Value, "")
                                                     If rpt.txtKennzeichen.Text = "" Then rpt.lblKennzeichen.Visible = False
                                                 End Sub
            AddHandler rpt.GroupHeaderKat.Format, Sub()
                                                      rpt.lblKategorie.Text = "MAUT REPORT"
                                                  End Sub

            AddHandler rpt.GroupFooterKz.Format, Sub()
                                                     rpt.txtNettoKzSum.Text = sumNetto.ToString("N2")
                                                     rpt.txtMWSTKzSum.Text = sumMWST.ToString("N2")
                                                     rpt.txtBruttoKzSum.Text = sumBrutto.ToString("N2")
                                                     sumNettoGes += sumNetto
                                                     sumMWSTGes += sumMWST
                                                     sumBruttoGes += sumBrutto

                                                     sumNetto = 0
                                                     sumMWST = 0
                                                     sumBrutto = 0

                                                     rpt.lblSummeKennzeichen.Text = rpt.lblSummeKennzeichen.Text.Replace("Kennzeichen", SQL.isDbnullEmpty(rpt.Fields.Item("LicencePlateNumber").Value, ""))
                                                 End Sub



            AddHandler rpt.GroupFooterKat.Format, Sub()
                                                      sumNettoKat += sumNetto
                                                      sumMWSTKat += sumMWST
                                                      sumBruttoKat += sumBrutto
                                                      sumNetto = 0
                                                      sumMWST = 0
                                                      sumBrutto = 0

                                                      rpt.txtNettoKatSum.Text = sumNettoKat.ToString("N2")
                                                      rpt.txtMWSTKatSum.Text = sumMWSTKat.ToString("N2")
                                                      rpt.txtBruttoKatSum.Text = sumBruttoKat.ToString("N2")
                                                      cntKat += 1
                                                  End Sub
            AddHandler rpt.ReportFooter1.Format, Sub()
                                                     'sumNettoGes += sumNettoKat
                                                     'sumMWSTGes += sumMWSTKat
                                                     'sumBruttoGes += sumBruttoKat
                                                     sumNettoKat = 0
                                                     sumMWSTKat = 0
                                                     sumBruttoKat = 0

                                                     sumNetto = 0
                                                     sumMWST = 0
                                                     sumBrutto = 0

                                                     rpt.txtNettoGesSum.Text = sumNettoGes.ToString("N2")
                                                     rpt.txtMWSTGEsSum.Text = sumMWSTGes.ToString("N2")
                                                     rpt.txtBruttoGesSum.Text = sumBruttoGes.ToString("N2")



                                                     'If cntKat <= 1 Then
                                                     '    rpt.GroupFooterKat.Visible = False
                                                     'End If
                                                 End Sub

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



            Dim tmpPath = dir & "\" & KdNr & "_Maut_UTA.pdf"
            Dim p As New GrapeCity.ActiveReports.Export.Pdf.Section.PdfExport
            rpt.Run(False)
            p.NeverEmbedFonts = ""
            p.Export(rpt.Document, tmpPath)

            rpt.Dispose()

            Return tmpPath

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

    End Function

    Function genPLOSE_SPEDBUCH_ByKdNr(KdNr As String, PLOSEKundenNr As String, von As Date, bis As Date, ByRef SPEDBUCH As VERAG_PROG_ALLGEMEIN.cSpeditionsbuch)
        Try

            'Dim displayFilter = False
            'Dim sqlstr As String = ""

            'sqlstr &= " SELECT 	 * "
            'sqlstr &= " FROM tblPLOSE_Details INNER JOIN [tblPLOSE_Produktbeschreibung] on plose_ProduktCode=plp_ProductCode "
            'sqlstr &= " WHERE 1=1 "
            'sqlstr &= " AND plose_Fakturiert=0 "
            'sqlstr &= " AND plose_POLSEKundennummer = '" & KdNr & "' "
            'sqlstr &= " AND plose_DatumTransaktion between '" & von.ToShortDateString & "' and '" & bis.ToShortDateString & "' "

            ''  sqlstr &= " group by plose_ProduktCode"
            'sqlstr &= " order by plp_Land, plose_DatumTransaktion"

            'Dim dt As DataTable = SQL.loadDgvBySql_Param(sqlstr, "FMZOLL")

            Dim AD As New VERAG_PROG_ALLGEMEIN.cAdressen(KdNr)
            SPEDBUCH = New VERAG_PROG_ALLGEMEIN.cSpeditionsbuch

            Dim OffertenNr = 80
            Dim Abfertigungsart = 10

            SPEDBUCH.FilialenNr = 4824
            SPEDBUCH.AbfertigungsNr = VERAG_PROG_ALLGEMEIN.cAllgemein.getMaxPosNrIncrement(SPEDBUCH.FilialenNr, Now.Year)
            SPEDBUCH.NewUNTER_NR()

            SPEDBUCH.Vermittler = AD.Ordnungsbegriff
            SPEDBUCH.VermittlerKundenNr = KdNr
            SPEDBUCH.VermittlerOffertenNr = OffertenNr
            SPEDBUCH.Abfertigungsdatum = datPloseAnhang.Value.ToShortDateString

            SPEDBUCH.Abfertigungsart = Abfertigungsart
            SPEDBUCH.Bar = 0
            SPEDBUCH.Fakturiert = 1
            SPEDBUCH.AnzahlSonstiges = 1
            SPEDBUCH.Abfertigungsanzahl = 1

            SPEDBUCH.AvisUhrzeit = Nothing
            SPEDBUCH.Umrechnungskurs = Nothing
            SPEDBUCH.veoerz_basbtg = Nothing
            SPEDBUCH.Sicherheitsbetrag = Nothing

            SPEDBUCH.Sachbearbeiter = VERAG_PROG_ALLGEMEIN.cAllgemein.USRKURZNAME


            Return SPEDBUCH.SAVE

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

    End Function


    Function genPLOSE_RECHNUNG_BySPEDBUCH(KdNr As String, PLOSEKundenNr As String, SPEDBUCH As VERAG_PROG_ALLGEMEIN.cSpeditionsbuch, von As Date, bis As Date)
        Try

            Dim AD As New VERAG_PROG_ALLGEMEIN.cAdressen(SPEDBUCH.VermittlerKundenNr)
            Dim KD As New VERAG_PROG_ALLGEMEIN.cKunde(SPEDBUCH.VermittlerKundenNr)
            Dim RG As New VERAG_PROG_ALLGEMEIN.cRechnungsausgang

            Dim OffertenNr = 80
            Dim Abfertigungsart = 10

            RG.FilialenNr = SPEDBUCH.FilialenNr
            RG.AbfertigungsNr = SPEDBUCH.AbfertigungsNr
            RG.SpeditionsbuchUnterNr = SPEDBUCH.UnterNr
            RG.UnterNr = RG.getMaxRGUnterNr()

            RG.Buchungsjahr = cRKSV.getGJ(datPloseAnhang.Value) 'If(Now.Month = 1, Now.Year - 1, Now.Year)
            RG.FilialenNr = SPEDBUCH.FilialenNr
            RG.Abfertigungsdatum = SPEDBUCH.Abfertigungsdatum
            RG.Sammelrechnung = 6 'MAUT/DIESEL
            RG.BelegartenKz = "AR"
            RG.BelegartenNr = 70
            RG.BelegartenBez = "Rechnung"
            RG.Vorzeichen = "+"

            RG.VermittlerKundenNr = AD.AdressenNr
            RG.VermittlerLandKz = AD.LandKz
            RG.VermittlerName_1 = AD.Name_1
            RG.VermittlerName_2 = AD.Name_2
            RG.VermittlerOffertenNr = OffertenNr
            RG.VermittlerOrt = (If(AD.LandKz, "") & " " & If(AD.PLZ, "") & " " & If(AD.Ort, ""))
            RG.VermittlerStraße = AD.Straße
            RG.Rechnung_an = 3
            RG.OffertenNr = OffertenNr

            RG.KundenNrZentrale = KD.KundenNrZentrale
            RG.RechnungsKundenNr = AD.AdressenNr
            RG.RechnungsLandKz = AD.LandKz
            RG.RechnungsName_1 = AD.Name_1
            RG.RechnungsName_2 = AD.Name_2
            RG.RechnungsOrt = (If(AD.LandKz, "") & " " & If(AD.PLZ, "") & " " & If(AD.Ort, ""))
            RG.RechnungsStraße = AD.Straße

            RG.RechnungsUstIdKz = AD.UstIdKz
            RG.RechnungsUstIdNr = AD.UstIdNr
            RG.RechnungsUstIdGeprüft = AD.UstIdGeprüft

            RG.Lastschrift = KD.Lastschrift
            RG.Kunden_SVS = KD.SVS
            RG.Steuerschlüssel = KD.Steuerschlüssel
            RG.Vorkasse = KD.Vorkasse
            RG.Vorlageprovision_Proz = KD.Vorlageprovision
            RG.Kreditaufwendungen_Proz = KD.Kreditaufwendungen
            RG.RechnungSprache = "DE"


            RG.Anlage_1 = ""
            RG.Anlage_2 = ""
            RG.Anlage_3 = ""
            RG.Anlage_4 = ""
            RG.Anlage_5 = ""
            RG.Anlage_6 = ""


            RG.Text = ""
            RG.EMailRechnungstext = Nothing ' ""

            RG.Firma_ID = 15
            RG.Nettozahlungsziel = KD.Zahlungsziel

            RG.SteuerpflichtigerGesamtbetrag = 0
            RG.SteuerfreierGesamtbetrag = 0
            RG.Status = 0

            RG.[Vorkosten] = 0
            RG.[Erlös] = 0
            RG.[Buchungsjahr] = 0
            RG.[Währungscode] = "EUR"
            RG.ReErfZeitstempel = Now


            RG.Sachbearbeiter = VERAG_PROG_ALLGEMEIN.cAllgemein.USRKURZNAME

            RG.Buchungsjahr = cRKSV.getGJ(RG.RechnungsDatum)

            Dim sqlstr As String = ""
            sqlstr &= " SELECT [plp_LeistungsNr],sum([plose_NettobetragWaehrungAbbuchung]) as plose_NettobetragWaehrungAbbuchung,sum([plose_MWSTBetragWaehrungAbbuchung]) as [plose_MWSTBetragWaehrungAbbuchung],sum([plose_BruttobetragWaehrungAbbuchung]) as [plose_BruttobetragWaehrungAbbuchung] "
            sqlstr &= " FROM tblPLOSE_Details INNER JOIN [tblPLOSE_Produktbeschreibung] on plose_ProduktCode=plp_ProductCode "
            sqlstr &= " WHERE 1=1 "
            sqlstr &= " AND plose_Fakturiert=0  "
            sqlstr &= " AND  plose_ProduktCode NOT IN (" & ProduktCode_NOT_IN & " )  "
            sqlstr &= " AND plose_POLSEKundennummer = '" & PLOSEKundenNr & "' "
            sqlstr &= " AND plp_LeistungsNr is not null "
            sqlstr &= " AND plose_DatumTransaktion between '" & von.ToShortDateString & "' and '" & bis.ToShortDateString & "' "

            sqlstr &= " group by [plp_LeistungsNr]"
            sqlstr &= " order by plp_LeistungsNr"

            Dim dt As DataTable = SQL.loadDgvBySql_Param(sqlstr, "FMZOLL")

            For Each r In dt.Rows
                Dim BLNr = r("plp_LeistungsNr")
                'Dim BProz = r("plose_BruttobetragWaehrungAbbuchung")

                Dim NettoBetrag As Double = r("plose_NettobetragWaehrungAbbuchung")
                Dim BruttoBetrag As Double = r("plose_BruttobetragWaehrungAbbuchung")
                Dim LeistungsNr As Integer = r("plp_LeistungsNr")

                Dim OFFERTE As New VERAG_PROG_ALLGEMEIN.cOfferte(KdNr, OffertenNr, True)

                allPlosePos(RG, OFFERTE, LeistungsNr, NettoBetrag, BruttoBetrag)

                'Rückvergütung Consortio !!
                If r("plp_LeistungsNr") = "190" Then '(PRODUCTCODE=301; VERAG-LEISTUNGSNR=190!!
                    rabattPlosePos(RG, OFFERTE, LeistungsNr, NettoBetrag, BruttoBetrag)
                End If
            Next


            Dim dtSt As DataTable = SQL.loadDgvBySql("SELECT TOP 1 isnull([Steuersatz %],0),isnull([Steuerbezeichnung],'')  FROM [Steuertabelle] WHERE [Steuerschlüssel]='" & RG.Steuerschlüssel & "'", "FMZOLL")
            If dtSt IsNot Nothing AndAlso dtSt.Rows.Count > 0 Then
                RG.Steuersatz_Proz = dtSt.Rows(0)(0)
            End If

            cFakturierung.setGesamtBetraege(RG)

            RG.Text = (cFakturierung.przRechnungstextTXT(RG, SPEDBUCH) & vbNewLine & cFakturierung.przRechnungstextZZ(RG)).Trim

            ' Call usrCntlFaktAbrechnung.przSVSRVS(RG)      ' SVS/RVS errechnen
            '  Call przSKR()         ' SKR errechnen

            'Call usrCntlFaktAbrechnung.przVL(RG)          ' Vorlageprovision errechnen
            'Call usrCntlFaktAbrechnung.przKapitalbereitstellung(RG) 'Kapitalbereitstellung errechnen

            ' boolFehler = fktBGeb(RECHNUNG.[RK_ID], RECHNUNG.Steuersatz_Proz, RECHNUNG.[Sammelrechnung], RECHNUNG.[BelegartenNr]) ' Bearbeitungsgebühr errechnen

            ' Call usrCntlFaktAbrechnung.przKA(RG)          ' Kreditaufwendungen errechnen
            Call usrCntlFaktAbrechnung.przFixeTaxe(RG)    ' Fixe Taxe errechnen
            Call usrCntlFaktAbrechnung.przPP(RG)          ' Porto/Papiere errechnen

            Call usrCntlFaktAbrechnung.przBS415(RG)       ' Bankspesen errechnen

            If RG.SAVE Then
                ' FAKTURIERT eintragen
                'For Each r In dt.Rows
                '    SQL.doSQL("UPDATE [tblPLOSE_Details]SET plose_Fakturiert=1, plose_FakturiertDatum='" & datPloseAnhang.Value & "' where plose_Id='" & r("plose_id") & "'", "FMZOLL")
                'Next
                Return True
            Else
                Return False
            End If

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

    End Function


    Function allPlosePos(ByRef RG As VERAG_PROG_ALLGEMEIN.cRechnungsausgang, OFFERTE As VERAG_PROG_ALLGEMEIN.cOfferte, LeistungsNr As Integer, NettoBetrag As Double, BruttoBetrag As Double)
        Try

            For Each o In OFFERTE.POSITIONEN
                If o.LeistungsNr = LeistungsNr Then

                    Dim POS As New VERAG_PROG_ALLGEMEIN.cRechnungsausgangPositionen()
                    Dim LEISTUNG As New VERAG_PROG_ALLGEMEIN.cLeistungen(o.LeistungsNr)
                    POS.LeistungsNr = o.LeistungsNr
                    POS.LeistungsBez = o.LeistungsBez

                    POS.BerechnungsartNr = o.BerechnungsartNr
                    'POS.Preis = BruttoBetrag
                    POS.Anzahl = 1
                    POS.Steuerpflichtig = LEISTUNG.Steuerpflichtig
                    POS.BGebBgl = NettoBetrag


                    If POS.Steuerpflichtig Then
                        POS.SteuerpflichtigerBetrag = NettoBetrag

                        POS.Preis = NettoBetrag
                    Else
                        POS.SteuerfreierBetrag = BruttoBetrag
                        POS.Preis = BruttoBetrag
                    End If

                    POS.BGebLeistungsNr = o.BGebLeistungsNr
                    POS.BGebProzent = o.BGebProzent
                    POS.BGebMinBetrag = o.BGebMinBetrag

                    RG.POSITIONEN.Add(POS)

                    If (If(POS.BGebLeistungsNr, 0) > 0) AndAlso (If(POS.BGebProzent, 0) > 0) AndAlso (If(POS.BGebBgl, 0) > 0) Then
                        allPlosePosBGeb(RG, OFFERTE, POS.BGebLeistungsNr, POS.BGebBgl, POS.BGebProzent)
                    End If

                    Return True
                End If
            Next
        Catch ex As Exception
            MsgBox(ex.Message & ex.StackTrace)
        End Try
        Return False
    End Function
    Function rabattPlosePos(ByRef RG As VERAG_PROG_ALLGEMEIN.cRechnungsausgang, OFFERTE As VERAG_PROG_ALLGEMEIN.cOfferte, LeistungsNr As Integer, NettoBetrag As Double, BruttoBetrag As Double)
        Try
            Dim POS As New VERAG_PROG_ALLGEMEIN.cRechnungsausgangPositionen()
            Dim LEISTUNG As New VERAG_PROG_ALLGEMEIN.cLeistungen(LeistungsNr)
            POS.LeistungsNr = LEISTUNG.LeistungsNr
            POS.LeistungsBez = "Rabatt " & LEISTUNG.LeistungsBez

            POS.BerechnungsartNr = LEISTUNG.BerechnungsartNr
            'POS.Preis = BruttoBetrag
            POS.Anzahl = 1
            POS.Steuerpflichtig = LEISTUNG.Steuerpflichtig
            ' POS.BGebBgl = NettoBetrag* -1

            If POS.Steuerpflichtig Then
                POS.SteuerpflichtigerBetrag = NettoBetrag * -1

                POS.Preis = NettoBetrag
            Else
                POS.SteuerfreierBetrag = BruttoBetrag * -1
                POS.Preis = BruttoBetrag * -1
            End If

            RG.POSITIONEN.Add(POS)

            Return True

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

    Function allPlosePosBGeb(ByRef RG As VERAG_PROG_ALLGEMEIN.cRechnungsausgang, OFFERTE As VERAG_PROG_ALLGEMEIN.cOfferte, BGebLeistungsNr As Integer, BGebBgl As Double, BGebProzent As Double)
        Try
            Dim Betrag As Double = Math.Round(BGebBgl * BGebProzent, 1)
            For Each o In OFFERTE.POSITIONEN
                If o.LeistungsNr = BGebLeistungsNr Then

                    'Falls schon vorhanden...
                    Dim POS = RG.POSITIONEN.Find(Function(x) x.LeistungsNr = BGebLeistungsNr) 'And x.BerechnungsartNr = 9)
                    If POS Is Nothing Then
                        POS = New VERAG_PROG_ALLGEMEIN.cRechnungsausgangPositionen()
                        POS.Preis = 0
                        POS.SteuerpflichtigerBetrag = 0
                        POS.SteuerfreierBetrag = 0
                        Dim LEISTUNG As New VERAG_PROG_ALLGEMEIN.cLeistungen(o.LeistungsNr)
                        POS.Steuerpflichtig = LEISTUNG.Steuerpflichtig

                        POS.LeistungsNr = o.LeistungsNr
                        POS.LeistungsBez = o.LeistungsBez

                        POS.BerechnungsartNr = o.BerechnungsartNr
                        POS.Anzahl = 1
                        '   POS.BGebLeistungsNr = BGebLeistungsNr

                        RG.POSITIONEN.Add(POS)
                    End If

                    POS.Preis += Betrag

                    If POS.Steuerpflichtig Then
                        POS.SteuerpflichtigerBetrag += Betrag
                    Else
                        POS.SteuerfreierBetrag += Betrag
                    End If

                    ' RG.POSITIONEN.Add(POS)
                    Return True

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


    Private Sub dat_Sum_Von_ValueChanged(sender As Object, e As EventArgs) Handles dat_Sum_Von.ValueChanged, dat_Sum_Bis.ValueChanged
        init()
    End Sub

    Private Sub cbx_CheckedChanged(sender As Object, e As EventArgs) Handles cbx.CheckedChanged
        Panel2.Enabled = cbx.Checked
    End Sub


    Function pruefData_PLOSE() As Boolean
        pruefData_PLOSE = True
        Try
            Dim VERAGKdNr_DT As DataTable = SQL.loadDgvBySql("SELECT AdressenNr,PLOSEKundenNr FROM Adressen WHERE PLOSEKundenNr is not null", "FMZOLL")
            Dim VERAGLeistungsNr_DT = SQL.loadDgvBySql("SELECT  [plp_LeistungsNr],plp_ProductCode   FROM [tblPLOSE_Produktbeschreibung] where plp_ProductCode is not null and plp_Firma IN ('PSS','PU') ", "FMZOLL")
            'Dim OffertenNr_DT = SQL.loadDgvBySql("SELECT KundenNr,OffertenNr FROM [Offerten] where  OffertenNr = 80 ", "FMZOLL")
            '   Dim KundeLeistungsNr_DT = SQL.loadDgvBySql("SELECT [LeistungsNr],KundenNr FROM [Offertenpositionen] where  OffertenNr = 80", "FMZOLL")

            Dim VERAGKdNr = -1
            Dim VERAGLeistungsNr = -1
            Dim found = False
            Dim results As DataRow()

            Dim cnt = 0

            For Each r As DataGridViewRow In MyDatagridview1.Rows
                'KUNDEN-NR / PLOSE KD-NR
                results = VERAGKdNr_DT.Select("PLOSEKundenNr = '" & r.Cells("plose_POLSEKundennummer").Value & "'")
                If results.Length > 0 Then
                    'Gefunden!
                    r.Cells("VERAGKdNr").Value = results(0)("PLOSEKundenNr")
                    r.Cells("VERAGKdNr").Style.BackColor = Color.MintCream
                    VERAGKdNr = results(0)("AdressenNr")
                    found = True
                Else
                    r.Cells("VERAGKdNr").Style.BackColor = Color.PapayaWhip
                    pruefData_PLOSE = False
                End If

                'KUNDEN-NR / PLOSE KD-NR
                'Default -> Nicht gefunden 
                'r.Cells("VERAGKdNr").Style.BackColor = Color.PapayaWhip
                'found = False
                'For Each k In VERAGKdNr_DT.Rows
                '    If r.Cells("plose_POLSEKundennummer").Value = k("PLOSEKundenNr") Then
                '        'Gefunden!
                '        r.Cells("VERAGKdNr").Value = k("PLOSEKundenNr")
                '        r.Cells("VERAGKdNr").Style.BackColor = Color.MintCream
                '        VERAGKdNr = k("AdressenNr")
                '        found = True
                '        Exit For
                '    End If
                'Next
                'If Not found Then pruefData_PLOSE = False

                'VERAG/PLOSE LEISTUNG
                results = VERAGLeistungsNr_DT.Select("plp_ProductCode = '" & r.Cells("plose_ProduktCode").Value & "' AND plp_LeistungsNr is not null")
                If results.Length > 0 Then
                    'Gefunden!
                    VERAGLeistungsNr = results(0)("plp_LeistungsNr")
                    r.Cells("VERAGLeistungsNr").Value = results(0)("plp_LeistungsNr")
                    r.Cells("VERAGLeistungsNr").Style.BackColor = Color.MintCream
                    found = True
                Else
                    r.Cells("VERAGLeistungsNr").Style.BackColor = Color.PapayaWhip
                    pruefData_PLOSE = False
                End If


                'VERAG OFFERT 80
                'Default -> Nicht gefunden
                Dim OffertenNr_DT = SQL.loadDgvBySql("SELECT KundenNr,OffertenNr FROM [Offerten] where  OffertenNr = 80  AND KundenNr = '" & VERAGKdNr & "'", "FMZOLL")
                results = OffertenNr_DT.Select("KundenNr = '" & VERAGKdNr & "'")
                If results.Length > 0 Then
                    'Gefunden!
                    r.Cells("KundeOffertenNr").Value = results(0)("OffertenNr")
                    r.Cells("KundeOffertenNr").Style.BackColor = Color.MintCream
                Else
                    pruefData_PLOSE = False
                    r.Cells("KundeOffertenNr").Style.BackColor = Color.PapayaWhip
                End If



                'VERAG LEISTUNGS-NR
                'Default -> Nicht gefunden 
                Dim KundeLeistungsNr_DT = SQL.loadDgvBySql("SELECT [LeistungsNr],KundenNr FROM [Offertenpositionen] where  OffertenNr = 80 AND KundenNr = '" & VERAGKdNr & "' AND LeistungsNr = '" & VERAGLeistungsNr & "'", "FMZOLL")
                results = KundeLeistungsNr_DT.Select("KundenNr = '" & VERAGKdNr & "' AND LeistungsNr = '" & VERAGLeistungsNr & "'")
                If results.Length > 0 Then
                    'Gefunden!
                    r.Cells("KundeLeistungsNr").Value = VERAGLeistungsNr
                    r.Cells("KundeLeistungsNr").Style.BackColor = Color.MintCream
                Else
                    r.Cells("KundeLeistungsNr").Style.BackColor = Color.PapayaWhip
                    pruefData_PLOSE = False
                End If


                If cnt Mod 5 = 0 Then
                    lblProzPruef.Text = CInt(cnt / MyDatagridview1.Rows.Count() * 100) & " %"
                    lblProzPruef.Refresh()
                    Me.Refresh()
                End If

                cnt += 1

            Next
            lblProzPruef.Text = CInt(cnt / MyDatagridview1.Rows.Count() * 100) & " %" '100
        Catch ex As Exception
            MsgBox(ex.Message & ex.StackTrace)
            pruefData_PLOSE = False
        End Try
    End Function

    Function pruefData_ASFINAG() As Boolean
        pruefData_ASFINAG = True
        Try

            Dim SQLAbrechnungsparameter = ""
            If MsgBox("Prüfung auf Inkonsistenz der Kartennummern mit Abrechnungsdatum vom " & Datum_Abrechnungsdaten.Value.ToShortDateString & " ?", vbYesNoCancel) = MsgBoxResult.Ok Then
                SQLAbrechnungsparameter = " AND (TTRBody.abrechnungsdatum = '" & Datum_Abrechnungsdaten.Value.ToShortDateString & "') "
            End If

            Dim dtAsfinagKartenpruef As DataTable = SQL.loadDgvBySql("
                        SELECT dbo.TTRBody.CardNumber, Kreditkarten.KartenNr, Kreditkarten.AdressenNr, (SELECT Offerten.OffertenNr FROM [VERAG].[dbo].[Offerten] WHERE (((Offerten.KundenNr)=isnull([Kreditkarten].[AdressenNr],0)) AND ((Offerten.OffertenNr)=11))) AS Offerte_11
                            FROM dbo.CLFArchiv 
                            RIGHT OUTER JOIN dbo.TTRBody ON dbo.CLFArchiv.OBUID = dbo.TTRBody.InfoField 
							LEFT OUTER JOIN dbo.tblWarenarten ON dbo.TTRBody.ProductCode = dbo.tblWarenarten.ProductCode
                            LEFT JOIN [VERAG].[dbo].[Kreditkarten] on dbo.TTRBody.CardNumber = Kreditkarten.KartenNr
                            WHERE (dbo.TTRBody.PKHistory = 0) AND (dbo.TTRBody.PKFileName LIKE N'" & checkifTestfiles() & ".%')" & SQLAbrechnungsparameter &
                            "GROUP BY dbo.TTRBody.CardNumber, Kreditkarten.KartenNr, Kreditkarten.AdressenNr
                            HAVING dbo.TTRBody.CardNumber is null or (dbo.TTRBody.CardNumber is not null  AND ((Kreditkarten.AdressenNr) Is Not Null) AND (((SELECT Offerten.OffertenNr FROM  [VERAG].[dbo].[Offerten] WHERE (((Offerten.KundenNr)=isnull([Kreditkarten].[AdressenNr],0)) AND ((Offerten.OffertenNr)=11)))) Is Null))
                            ORDER BY dbo.TTRBody.CardNumber", "ASFINAG")


            Dim VERAGKdNr = -1
            Dim VERAGLeistungsNr = -1
            Dim found = False
            Dim results As DataRow()

            Dim cnt = 0

            For Each r As DataGridViewRow In MyDatagridview1.Rows
                'KUNDEN-NR / PLOSE KD-NR
                'results = dtAsfinagKartenpruef.Select("PLOSEKundenNr = '" & r.Cells("plose_POLSEKundennummer").Value & "'")
                'If results.Length > 0 Then
                '    'Gefunden!
                '    'r.Cells("VERAGKdNr").Value = results(0)("PLOSEKundenNr")
                '    'r.Cells("VERAGKdNr").Style.BackColor = Color.MintCream
                '    VERAGKdNr = results(0)("AdressenNr")
                '    found = True
                'Else
                '    r.Cells("VERAGKdNr").Style.BackColor = Color.PapayaWhip
                '    pruefData_ASFINAG = False
                'End If

                'KUNDEN-NR / PLOSE KD-NR
                'Default -> Nicht gefunden 
                'r.Cells("VERAGKdNr").Style.BackColor = Color.PapayaWhip
                'found = False
                'For Each k In VERAGKdNr_DT.Rows
                '    If r.Cells("plose_POLSEKundennummer").Value = k("PLOSEKundenNr") Then
                '        'Gefunden!
                '        r.Cells("VERAGKdNr").Value = k("PLOSEKundenNr")
                '        r.Cells("VERAGKdNr").Style.BackColor = Color.MintCream
                '        VERAGKdNr = k("AdressenNr")
                '        found = True
                '        Exit For
                '    End If
                'Next
                'If Not found Then pruefData_PLOSE = False

                'VERAG/PLOSE LEISTUNG
                'results = VERAGLeistungsNr_DT.Select("plp_ProductCode = '" & r.Cells("plose_ProduktCode").Value & "' AND plp_LeistungsNr is not null")
                'If results.Length > 0 Then
                '    'Gefunden!
                '    VERAGLeistungsNr = results(0)("plp_LeistungsNr")
                '    r.Cells("VERAGLeistungsNr").Value = results(0)("plp_LeistungsNr")
                '    r.Cells("VERAGLeistungsNr").Style.BackColor = Color.MintCream
                '    found = True
                'Else
                '    r.Cells("VERAGLeistungsNr").Style.BackColor = Color.PapayaWhip
                '    pruefData_ASFINAG = False
                'End If


                ''VERAG OFFERT 80
                ''Default -> Nicht gefunden
                'Dim OffertenNr_DT = SQL.loadDgvBySql("SELECT KundenNr,OffertenNr FROM [Offerten] where  OffertenNr = 80  AND KundenNr = '" & VERAGKdNr & "'", "FMZOLL")
                'results = OffertenNr_DT.Select("KundenNr = '" & VERAGKdNr & "'")
                'If results.Length > 0 Then
                '    'Gefunden!
                '    r.Cells("KundeOffertenNr").Value = results(0)("OffertenNr")
                '    r.Cells("KundeOffertenNr").Style.BackColor = Color.MintCream
                'Else
                '    pruefData_ASFINAG = False
                '    r.Cells("KundeOffertenNr").Style.BackColor = Color.PapayaWhip
                'End If



                ''VERAG LEISTUNGS-NR
                ''Default -> Nicht gefunden 
                'Dim KundeLeistungsNr_DT = SQL.loadDgvBySql("SELECT [LeistungsNr],KundenNr FROM [Offertenpositionen] where  OffertenNr = 80 AND KundenNr = '" & VERAGKdNr & "' AND LeistungsNr = '" & VERAGLeistungsNr & "'", "FMZOLL")
                'results = KundeLeistungsNr_DT.Select("KundenNr = '" & VERAGKdNr & "' AND LeistungsNr = '" & VERAGLeistungsNr & "'")
                'If results.Length > 0 Then
                '    'Gefunden!
                '    r.Cells("KundeLeistungsNr").Value = VERAGLeistungsNr
                '    r.Cells("KundeLeistungsNr").Style.BackColor = Color.MintCream
                'Else
                '    r.Cells("KundeLeistungsNr").Style.BackColor = Color.PapayaWhip
                '    pruefData_ASFINAG = False
                'End If


                'If cnt Mod 5 = 0 Then
                '    lblProzPruef.Text = CInt(cnt / MyDatagridview1.Rows.Count() * 100) & " %"
                '    lblProzPruef.Refresh()
                '    Me.Refresh()
                'End If

                cnt += 1

            Next

            MyDatagridview1.ClearSelection()
            MyDatagridview1.DataSource = dtAsfinagKartenpruef
            Dim count = MyDatagridview1.Rows.Count()
            If count > 0 Then lblProzPruef.Text = CInt(cnt / count * 100) & " %" '100
        Catch ex As Exception
            MsgBox(ex.Message & ex.StackTrace)
            pruefData_ASFINAG = False
        End Try
    End Function

    Function pruefData_PLOSE_old() As Boolean
        pruefData_PLOSE_old = True
        Try
            Dim cnt = 0

            For Each r As DataGridViewRow In MyDatagridview1.Rows
                Dim VERAGKdNr = SQL.getValueTxtBySql("SELECT TOP 1 AdressenNr FROM Adressen WHERE PLOSEKundenNr='" & r.Cells("plose_POLSEKundennummer").Value & "'", "FMZOLL")

                If VERAGKdNr <> "" Then
                    r.Cells("VERAGKdNr").Value = VERAGKdNr
                    r.Cells("VERAGKdNr").Style.BackColor = Color.MintCream
                Else
                    pruefData_PLOSE_old = False
                    r.Cells("VERAGKdNr").Style.BackColor = Color.PapayaWhip
                End If
                Dim VERAGLeistungsNr = SQL.getValueTxtBySql("SELECT TOP (1) [plp_LeistungsNr]   FROM [tblPLOSE_Produktbeschreibung] where plp_ProductCode='" & r.Cells("plose_ProduktCode").Value & "' and plp_Firma IN ('PSS','PU') ", "FMZOLL")
                If VERAGLeistungsNr <> "" Then
                    r.Cells("VERAGLeistungsNr").Value = VERAGLeistungsNr
                    r.Cells("VERAGLeistungsNr").Style.BackColor = Color.MintCream
                Else
                    pruefData_PLOSE_old = False
                    r.Cells("VERAGLeistungsNr").Style.BackColor = Color.PapayaWhip
                End If


                Dim OffertenNr = SQL.getValueTxtBySql("SELECT TOP 1 OffertenNr FROM [Offerten] where KundenNr='" & VERAGKdNr & "' AND OffertenNr = 80 ", "FMZOLL")
                If OffertenNr <> "" Then
                    r.Cells("KundeOffertenNr").Value = OffertenNr
                    r.Cells("KundeOffertenNr").Style.BackColor = Color.MintCream
                Else
                    pruefData_PLOSE_old = False
                    r.Cells("KundeOffertenNr").Style.BackColor = Color.PapayaWhip
                End If

                If VERAGLeistungsNr <> "" Then

                    Dim KundeLeistungsNr = SQL.getValueTxtBySql("SELECT TOP 1 [LeistungsNr] FROM [Offertenpositionen] where LeistungsNr='" & VERAGLeistungsNr & "' and KundenNr='" & VERAGKdNr & "'  AND OffertenNr = 80", "FMZOLL")
                    If KundeLeistungsNr <> "" Then
                        r.Cells("KundeLeistungsNr").Value = VERAGLeistungsNr
                        r.Cells("KundeLeistungsNr").Style.BackColor = Color.MintCream
                    Else
                        pruefData_PLOSE_old = False
                        r.Cells("KundeLeistungsNr").Style.BackColor = Color.PapayaWhip
                    End If
                Else
                    pruefData_PLOSE_old = False
                    r.Cells("KundeLeistungsNr").Style.BackColor = Color.PapayaWhip
                End If


                If cnt Mod 5 = 0 Then
                    lblProzPruef.Text = CInt(cnt / MyDatagridview1.Rows.Count() * 100) & " %"
                    lblProzPruef.Refresh()
                    Me.Refresh()
                End If

                cnt += 1

            Next
            lblProzPruef.Text = CInt(cnt / MyDatagridview1.Rows.Count() * 100) & " %" '100


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


    Private Sub MyDatagridview1_SelectionChanged(sender As Object, e As EventArgs) Handles MyDatagridview1.SelectionChanged
        If MyDatagridview1.SelectedRows.Count > 0 Then
            If MyDatagridview1.Columns("VERAGKdNr") IsNot Nothing Then
                If MyDatagridview1.SelectedRows(0).Cells("VERAGKdNr").Value <> "" Then
                    btnKunde.Enabled = True
                Else
                    btnKunde.Enabled = False
                End If
            End If
        End If
    End Sub

    Private Sub btnKunde_Click(sender As Object, e As EventArgs) Handles btnKunde.Click
        If MyDatagridview1.SelectedRows.Count > 0 Then
            If MyDatagridview1.Columns("VERAGKdNr") IsNot Nothing Then
                If MyDatagridview1.SelectedRows(0).Cells("VERAGKdNr").Value <> "" Then
                    cProgramFunctions.openKundenblatt(MyDatagridview1.SelectedRows(0).Cells("VERAGKdNr").Value, Me.FindForm)
                End If
            End If
        End If
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If vbYes = MsgBox("Möchten Sie den Vorgang wirklich manuell ausgeführen (wird bei Rechnungserstellung automatisch ausgeführt)", vbYesNoCancel) Then
            MautD_Befuellen()
        End If
    End Sub

    Function MautD_Befuellen() As Boolean
        Select Case LIEFERANT
            Case "PLOSE" : deleteMautD("PLOSE") : Return genPLOSEInsertMautD(dat_Sum_Von.Value.ToShortDateString, dat_Sum_Bis.Value.ToShortDateString)
        End Select
        Return False
    End Function


    Sub setFakturiertPLOSE()
        PictureBox1.Visible = False
        If SQL.doSQL("UPDATE tblPLOSE_Details SET plose_Fakturiert=1 WHERE plose_Fakturiert = 0 AND plose_DatumTransaktion between '" & dat_Sum_Von.Value.ToShortDateString & "' and '" & dat_Sum_Bis.Value.ToShortDateString & "'   ", "FMZOLL") Then
            PictureBox1.Visible = True
        End If

    End Sub

    Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
        If vbYes = MsgBox("Möchten Sie den Vorgang wirklich manuell ausgeführen (wird bei Rechnungserstellung automatisch ausgeführt)", vbYesNoCancel) Then
            Select Case LIEFERANT
                Case "PLOSE" : setFakturiertPLOSE()
            End Select
        End If
    End Sub

    Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
        Try

            Dim connectionString = ""
            If VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM Then
                connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\DEVELOPER\f\FMZoll\MautD.accdb"
            Else
                connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\FMZOLL.verag.ost.dmn\f\FMZoll\MautD.accdb"
            End If

            Dim con As New OleDbConnection(connectionString)
            Dim cmd As New OleDbCommand
            Dim var1 As String

            Dim adapter As OleDbDataAdapter = New OleDbDataAdapter()
            Dim reader As OleDbDataReader = Nothing


            Dim ergebnis = ""

            con.Open()
            Try
                'Zeitstempel 
                Dim SQLQuery = "SELECT COUNT(*) FROM tblMautbericht "

                Using Command As New OleDbCommand(SQLQuery, con)

                    ergebnis = Command.ExecuteScalar
                    Command.Dispose()
                End Using



            Catch ex2 As System.Exception
                MsgBox("err: " & ex2.Message & ex2.StackTrace)

            Finally
                If reader IsNot Nothing Then reader.Close()
            End Try


            con.Close()


            MsgBox("Ergebnis: " & ergebnis)
        Catch ex As System.Exception
            MsgBox(ex.Message & ex.StackTrace)
        End Try

    End Sub

    Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
        initLieferant("UTA", sender)
    End Sub

    Private Sub Button8_Click(sender As Object, e As EventArgs) Handles Button8.Click
        initLieferant("ASFINAG", sender)
    End Sub

    Private Sub Button9_Click(sender As Object, e As EventArgs) Handles Button9.Click
        If CDate(Datum_Abrechnungsdaten.Value) <= Today.AddDays(1) Then
            If MsgBox("Möchten Sie das Abrechnungsdatum auf " & Datum_Abrechnungsdaten.Value.ToShortDateString & " setzen?", vbYesNoCancel) = MsgBoxResult.Yes Then

                'SQL.doSQL("DELETE * from tblAsfinagMaut", "FMZOLL")

                SQL.doSQL("Update Abrechnungsdatum SET Abrechnungsdatum = '" & Datum_Abrechnungsdaten.Value.ToShortDateString & "'", "ASFINAG")
                If SQL.doSQL("UPDATE dbo.TTRBody SET Abrechnungsdatum = '" & Datum_Abrechnungsdaten.Value.ToShortDateString & "' WHERE (PKHistory = 0) AND (PKFileName LIKE N'" & checkifTestfiles() & ".%') AND (FileCreationDate <= '" & Datum_Abrechnungsdaten.Value.ToShortDateString & "') AND (abrechnungsdatum IS NULL)", "ASFINAG") Then MsgBox("Abrechnungsdatum gesetzt!")

                Dim dt As DataTable = SQL.loadDgvBySql("SELECT *  FROM tblAsfinagMaut", "FMZOLL")

                initDgv_ASFINAG(Not cbxNichtabgerechnet.Checked)
            End If
        Else
            MsgBox("Datum muss kleiner/gleich Tagesdatum sein")
        End If
    End Sub

    Private Sub Button10_Click(sender As Object, e As EventArgs) Handles Button10.Click
        If CDate(Datum_Abrechnungsdaten.Value) <= Today.AddDays(1) Then
            If MsgBox("Möchten Sie das Abrechnungsdatum vom " & Datum_Abrechnungsdaten.Value.ToShortDateString & "zurücksetzen?", vbYesNoCancel) = MsgBoxResult.Ok Then
                If SQL.doSQL("UPDATE dbo.TTRBody SET Abrechnungsdatum = 'NULL' WHERE Abrechnungsdatum = '" & Datum_Abrechnungsdaten.Value.ToShortDateString & "' AND (PKHistory = 0) AND (PKFileName LIKE N'" & checkifTestfiles() & ".%')", "ASFINAG") Then MsgBox("Abrechnungsdatum zurückgesetzt!")
            End If
        Else
            MsgBox("Datum muss kleiner/gleich Tagesdatum sein")
        End If
    End Sub

    Private Sub Datum_Abrechnungsdaten_ValueChanged(sender As Object, e As EventArgs) Handles Datum_Abrechnungsdaten.ValueChanged
        If Datum_Abrechnungsdaten IsNot Nothing Then
            cbxNichtabgerechnet.Checked = False
        End If
    End Sub

    Private Function checkifTestfiles() As String

        If cbxTestdaten.Checked Then

            Return "TEPVGTTR"
        Else
            Return "LEPVGTTR"

        End If

    End Function


End Class
