Imports System.Data.OleDb
Imports System.DirectoryServices.ActiveDirectory
Imports System.IO
Imports Chilkat
Imports com.sun.jdi
Imports com.sun.net.httpserver.Authenticator
Imports DAKOSY_Worker.NichtAbschliessendeFestsetzung
Imports sun.nio.cs.ext
Imports VERAG_PROG_ALLGEMEIN

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'"
    Dim datum As Date = Nothing
    Dim test As Boolean = True

    Private Sub frmPloseDatenverarbetiung_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Me.Top = 0
        Me.Height = My.Computer.Screen.WorkingArea.Height

        VERAG_PROG_ALLGEMEIN.cProgramFunctions.SetDoubleBuffered(MyDatagridview1)

    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 "UTA" : genSummenbericht_UTA()
            Case "IDS" : MsgBox("Nicht verfügbar!") : Exit Sub
            Case "MSE" : genSummenbericht_MSE()
            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 "UTA" : pruef = pruefData_UTA()
            Case "IDS" : MsgBox("Nicht verfügbar!") : Exit Sub
            Case "MSE" : pruef = pruefData_MSE()
            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(cbxASFINAGAbgerechnet.Checked, cbxBelegeerstellt.Checked)
                btnDatenLaden.Text = "Daten laden"
            Case "IDS"  'MsgBox("Nicht verfügbar!")
                btnDatenLaden.Text = "Daten laden"
            Case "MSE" : initDgv_MSE()
                btnDatenLaden.Text = "Daten laden"
        End Select
    End Sub

    Private Sub btnREerstellen_Click_1(sender As Object, e As EventArgs) Handles btnREerstellen.Click
        Dim errorTmp = False
        Select Case LIEFERANT
            Case "PLOSE"
                If genRGAtt_PLOSE() Then
                    If MautD_Befuellen() Then
                        setFakturiert(LIEFERANT)
                    End If
                End If
            Case "UTA"
                If genRGAtt_UTA() Then
                    If Not test AndAlso MautD_Befuellen() Then
                        setFakturiert(LIEFERANT)
                    End If
                End If

            Case "IDS"
                MsgBox("Nicht verfügbar!")
            Case "MSE"
                If genRGAtt_MSE() Then
                    If Not test AndAlso MautD_Befuellen() Then
                        setFakturiert(LIEFERANT)
                    End If
                End If

            Case "ASFINAG"
                Dim abrechnungsDatum As DateTime = Now()
                If datum = Nothing Then
                    datum = SQL.getValueTxtBySql("select top (1) Abrechnungsdatum from  Abrechnungsdatum", "ASFINAG")
                End If

                Dim inputKdNr = "" 'InputBox("Wenn einzelner Kunde abgerechnet werde soll, bitte KdNr eingeben" & vbNewLine & "Wenn keine KdNr angegeben wird, dann werden alle Kunden abgerechnet:", "Asfinag abrechen")

                If genRGAtt_ASFINAG(abrechnungsDatum, datum, inputKdNr) Then
                    MautD_Befuellen(inputKdNr)
                End If
                initDgv_ASFINAG(cbxASFINAGAbgerechnet.Checked, cbxBelegeerstellt.Checked)

        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 = ""

        If datum = Nothing Then
            datum = SQL.getValueTxtBySql("select top (1) Abrechnungsdatum from  Abrechnungsdatum", "ASFINAG")
        End If

        'umschreiben, damit er die Daten nicht aus TTRBody sondern tblMautAsfinag holt.... 

        ' 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.ToShortDateString & "')
        '             ORDER BY dbo.TTRBody.CardNumber"


        '      sqlstr &= "select [cardnumber] as CardNumber
        ',Adressen.AdressenNr AS KundenNr
        ',Adressen.[Name 1]
        '    ,[licenceplate] as vehicleLicensePlate
        '    ,[turnoverdate] as DeliveryDate
        '    ,[contractPartner] as ProductCode
        '    ,[netAmount]
        '    ,[VATamount]
        '    ,[additionalData]
        '    ,[totalAmount] as amountInclVAT
        'FROM [VERAG].[dbo].[tblAsfinagMaut]
        'INNER JOIN [VERAG].[dbo].Kreditkarten ON cardnumber = Kreditkarten.KartenNr
        'INNER JOIN [VERAG].[dbo].Adressen ON Adressen.AdressenNr = Kreditkarten.AdressenNr"



        sqlstr &= "select [cardnumber] as CardNumber
		,Adressen.AdressenNr AS KundenNr
		,Adressen.[Name 1]
        ,[contractPartner] as ProductCode
        ,sum([netAmount]) as Netamount
        ,sum([VATamount]) as VATAmount
        ,sum([totalAmount]) as amountInclVAT
        FROM [VERAG].[dbo].[tblAsfinagMaut]
        INNER JOIN [VERAG].[dbo].Kreditkarten ON cardnumber = Kreditkarten.KartenNr
        INNER JOIN [VERAG].[dbo].Adressen ON Adressen.AdressenNr = Kreditkarten.AdressenNr
        group by  Adressen.AdressenNr,Adressen.[Name 1], contractPartner,CardNumber
		order by Adressen.AdressenNr"

        Dim dt As DataTable = SQL.loadDgvBySql_Param(sqlstr, "FMZOLL")
        '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.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 genSummenbericht_UTA()
        Dim displayFilter = False
        Dim sqlstr As String = ""

        sqlstr &= "SELECT Kundennummer, 
                        KundenNr, 
                        [Name 1], 
                        LandKz, 
                        Ort, 
                        Lieferland, 
                        Kartennummer, 
                        Sum(Gesamtbetrag_Netto_in_Darstellwährung) AS SummevonGesamtbetrag_Netto_in_Darstellwährung, 
                        Sum(Gesamtbetrag_Brutto_in_Darstellwährung) AS SummevonGesamtbetrag_Brutto_in_Darstellwährung 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, 
                        tblUTAImportNew.*
            FROM tblUTAFakturierwarenarten 
            INNER JOIN (((Adressen INNER JOIN tblUTAImportNew ON Adressen.UTAKundenNr = tblUTAImportNew.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 (tblUTAImportNew.Lieferland = tblUTALeistungen.Lieferland) 
                        AND (tblUTAImportNew.Fakturierwarenart = tblUTALeistungen.Fakturierwarenart)) ON tblUTAFakturierwarenarten.Fakturierwarenart = tblUTALeistungen.Fakturierwarenart) 
            as temp
            where temp.abgerechnet <> 1
            GROUP BY Kundennummer, KundenNr, [Name 1], LandKz, Ort, Lieferland, Kartennummer"

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


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

        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 = "UTA Summenbericht " & CDate(Now.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("Kartennummer").Value, "") & " - " & SQL.isDbnullEmpty(rpt.Fields.Item("Lieferland").Value, "")

                                          rpt.lblNetto.Text = SQL.isDbnullEmptyDbl(rpt.Fields.Item("SummevonGesamtbetrag_Netto_in_Darstellwährung").Value, 2, "")
                                          rpt.lblMWST.Text = SQL.isDbnullEmptyDbl(CDbl(rpt.Fields.Item("SummevonGesamtbetrag_Brutto_in_Darstellwährung").Value) - CDbl(rpt.Fields.Item("SummevonGesamtbetrag_Netto_in_Darstellwährung").Value), 2, "")
                                          rpt.lblBrutto.Text = SQL.isDbnullEmptyDbl(rpt.Fields.Item("SummevonGesamtbetrag_Brutto_in_Darstellwährung").Value, 2, "")


                                          rpt.lblSumNet.Text = SQL.isDbnullEmptyDbl(rpt.Fields.Item("SummevonGesamtbetrag_Netto_in_Darstellwährung").Value, 2, "")
                                          rpt.lblSumVat.Text = SQL.isDbnullEmptyDbl(CDbl(rpt.Fields.Item("SummevonGesamtbetrag_Brutto_in_Darstellwährung").Value) - CDbl(rpt.Fields.Item("SummevonGesamtbetrag_Netto_in_Darstellwährung").Value), 2, "")
                                          rpt.lblSumBrt.Text = SQL.isDbnullEmptyDbl(rpt.Fields.Item("SummevonGesamtbetrag_Brutto_in_Darstellwährung").Value, 2, "")

                                          sumNetto += SQL.isDbnullEmptyDbl(rpt.Fields.Item("SummevonGesamtbetrag_Netto_in_Darstellwährung").Value, 4, 0)
                                          sumMWST += SQL.isDbnullEmptyDbl(CDbl(rpt.Fields.Item("SummevonGesamtbetrag_Brutto_in_Darstellwährung").Value) - CDbl(rpt.Fields.Item("SummevonGesamtbetrag_Netto_in_Darstellwährung").Value), 4, 0)
                                          sumBrutto += SQL.isDbnullEmptyDbl(rpt.Fields.Item("SummevonGesamtbetrag_Brutto_in_Darstellwährung").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 genSummenbericht_MSE()
        Dim displayFilter = False
        Dim sqlstr As String = ""

        sqlstr &= " SELECT Adressen.AdressenNr as KundenNr, Adressen.[Name 1] as Name, trans.transaction_country AS Country,trans.device_product_type AS CardType, 
                    /*trans.device_product_number AS CardNr,*/
                        Sum(trans.transaction_gross_amount) AS [Transaction Amount], 
                        Sum(trans.total_gross_amount) AS [Total Amount]
                       FROM [VERAG].[dbo].[tblMSESettlements] as bills 
                       left join [VERAG].[dbo].[tblMSETransactions] as trans on bills.[transaction_id] = trans.[transaction_id] 
                       left join [VERAG].[dbo].[tblMSECustomers] as cust on cust.partner_customer_number = trans.partner_haulier_id
                       left join [VERAG].[dbo].[tblMSEInvoices] as inv on inv.[invoice_id] = bills.[invoice_number] and inv.customer_number = cust.[customer_id] and trans.transaction_country = inv.country
                       left join adressen ON cust.[customer_id] = Adressen.MSEKundenNr 
                       where bills.invoice_date = '" & DateTimePicker2.Text & "' and trans.charged <> 1 
                       GROUP BY Adressen.AdressenNr, Adressen.[Name 1], trans.transaction_country, trans.device_product_type--, trans.device_product_number 
                       order by KundenNr"

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


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

        Dim rpt As New rptASFINAG_TransaktionenSumary

        rpt.DataSource = dt

        'If cbxProdukt.Checked Then

        'Else
        '    rpt.GroupHeader2.Visible = False
        '    rpt.GroupFooter2.Visible = False
        'End If



        Dim sum = 0
        rpt.lblUeberschrift.Text = "MSE Summenbericht " & CDate(Now.ToShortDateString)
        rpt.lblSachbearbeiter.Text = VERAG_PROG_ALLGEMEIN.cAllgemein.USRNAME
        rpt.lblBrutto.Text = "Total Amount"
        rpt.lblNetto.Text = "Transaction Amount"
        rpt.Label4.Text = rpt.lblNetto.Text
        rpt.Label2.Visible = False
        rpt.Label14.Text = rpt.lblBrutto.Text
        '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").Value, "")
                                          rpt.lblKartennr.Text = SQL.isDbnullEmpty(rpt.Fields.Item("CardType").Value, "") & "  - " & SQL.isDbnullEmpty(rpt.Fields.Item("Country").Value, "") '& "  - " & SQL.isDbnullEmpty(rpt.Fields.Item("CardNr").Value, "")

                                          rpt.lblNetto.Text = SQL.isDbnullEmptyDbl(rpt.Fields.Item("Transaction Amount").Value, 2, "")
                                          rpt.lblMWST.Text = "" 'SQL.isDbnullEmptyDbl(CDbl(rpt.Fields.Item("SummevonGesamtbetrag_Brutto_in_Darstellwährung").Value) - CDbl(rpt.Fields.Item("SummevonGesamtbetrag_Netto_in_Darstellwährung").Value), 2, "")
                                          rpt.lblBrutto.Text = SQL.isDbnullEmptyDbl(rpt.Fields.Item("Total Amount").Value, 2, "")


                                          rpt.lblSumNet.Text = SQL.isDbnullEmptyDbl(rpt.Fields.Item("Transaction Amount").Value, 2, "")
                                          rpt.lblSumVat.Text = "" 'SQL.isDbnullEmptyDbl(CDbl(rpt.Fields.Item("SummevonGesamtbetrag_Brutto_in_Darstellwährung").Value) - CDbl(rpt.Fields.Item("SummevonGesamtbetrag_Netto_in_Darstellwährung").Value), 2, "")
                                          rpt.lblSumBrt.Text = SQL.isDbnullEmptyDbl(rpt.Fields.Item("Total Amount").Value, 2, "")

                                          sumNetto += SQL.isDbnullEmptyDbl(rpt.Fields.Item("Transaction Amount").Value, 4, 0)
                                          'sumMWST += SQL.isDbnullEmptyDbl(CDbl(rpt.Fields.Item("SummevonGesamtbetrag_Brutto_in_Darstellwährung").Value) - CDbl(rpt.Fields.Item("SummevonGesamtbetrag_Netto_in_Darstellwährung").Value), 4, 0)
                                          sumBrutto += SQL.isDbnullEmptyDbl(rpt.Fields.Item("Total Amount").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 Kundennummer, KundenNr, [Name 1], LandKz, Ort, /*Lieferland, Kartennummer,*/ Sum(Gesamtbetrag_Netto_in_Darstellwährung) AS Netto, Sum(Gesamtbetrag_Brutto_in_Darstellwährung) AS Brutto 
                        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, tblUTAImportNew.*
                        FROM tblUTAFakturierwarenarten 
                        INNER JOIN (((Adressen 
                        		INNER JOIN tblUTAImportNew ON Adressen.UTAKundenNr = tblUTAImportNew.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 (tblUTAImportNew.Lieferland = tblUTALeistungen.Lieferland) 
                        		AND (tblUTAImportNew.Fakturierwarenart = tblUTALeistungen.Fakturierwarenart)) 
                        		ON tblUTAFakturierwarenarten.Fakturierwarenart = tblUTALeistungen.Fakturierwarenart) as temp
                        where temp.abgerechnet <> 1
                        GROUP BY Kundennummer, KundenNr, [Name 1], LandKz, Ort", "FMZOLL")
            .LOAD()
            'MsgBox(.GET_SQL())
            If .Columns.Count > 0 Then

                .Columns("KundenNr").HeaderText = "KdNr"
                .Columns("Name 1").HeaderText = "Kunde"
                .Columns("LandKz").Width = 75
                .Columns("LandKz").HeaderText = "Land"
                .Columns("Ort").HeaderText = "Ort"
                .Columns("Ort").Width = 100
                '.Columns("Lieferland").HeaderText = "Land"
                .Columns("Name 1").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill


                '.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("Brutto").Value), CDbl(r.Cells("Brutto").Value), 0)
                sumNto += If(IsNumeric(r.Cells("Netto").Value), CDbl(r.Cells("Netto").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_MSE()
        With MyDatagridview1
            .Columns.Clear()
            'Exit Sub
            'MsgBox(.sql)

            .SET_SQL("    SELECT Adressen.AdressenNr as KundenNr, Adressen.[Name 1] as Name, trans.transaction_country AS Country,trans.device_product_type AS CardType, 
                            Sum(trans.transaction_gross_amount) As [Transaktionsbetrag],
                            Sum(trans.msts_fee_amount) As [Transaktionskosten],
                            Sum(trans.total_gross_amount)  As [Gesamtbetrag]
                             FROM [VERAG].[dbo].[tblMSESettlements] as bills 
                             left join [VERAG].[dbo].[tblMSETransactions] as trans on bills.[transaction_id] = trans.[transaction_id] 
                             left join [VERAG].[dbo].[tblMSECustomers] as cust on cust.partner_customer_number = trans.partner_haulier_id
                             left join [VERAG].[dbo].[tblMSEInvoices] as inv on inv.[invoice_id] = bills.[invoice_number] and inv.customer_number = cust.[customer_id] and trans.transaction_country = inv.country
                            Left Join adressen ON cust.[customer_id] = Adressen.MSEKundenNr 
                             where bills.invoice_date =  '" & DateTimePicker2.Text & "' and trans.charged <> 1 
                             GROUP BY Adressen.AdressenNr, Adressen.[Name 1], trans.transaction_country, trans.device_product_type", "FMZOLL")

            .LOAD()

            If .Columns.Count > 0 Then

                '.Columns("AdressenNr").HeaderText = "KdNr"
                '.Columns("Name 1").HeaderText = "Kunde"
                '.Columns("LandKz").HeaderText = "Land"
                .Columns("Name").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill

                '.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 sumGes As Double = 0
            Dim sumFee As Double = 0
            Dim sumTr As Double = 0
            For Each r As DataGridViewRow In .Rows
                sumGes += If(IsNumeric(r.Cells("Gesamtbetrag").Value), CDbl(r.Cells("Gesamtbetrag").Value), 0)
                sumTr += If(IsNumeric(r.Cells("Transaktionsbetrag").Value), CDbl(r.Cells("Transaktionsbetrag").Value), 0)
                sumFee += If(IsNumeric(r.Cells("Transaktionskosten").Value), CDbl(r.Cells("Transaktionskosten").Value), 0)
            Next

            txtAnzahl.Text = .Rows.Count
            txtPruefsummeNetto.Text = CDbl(sumTr).ToString("C2")
            txtPruefsummeBrutto.Text = CDbl(sumGes).ToString("C2")
            txtTTRSum.Text = CDbl(sumFee).ToString("C2")

            lblTTRSum.Visible = True
            txtTTRSum.Visible = True

            lblTTRSum.Text = "Tr-Kosten"


            .ClearSelection()

        End With

    End Sub

    Sub initDgv_ASFINAG(abgerechnet As Boolean, belegeErstellt As Boolean)

        'datum = CDate(SQL.getValueTxtBySql("SELECT Abrechnungsdatum FROM Abrechnungsdatum", "ASFINAG"))
        Dim sqlString = " AND  (TTRBody.abrechnungsdatum " & IIf(abgerechnet, "is not null)", "is null)")
        sqlString &= " AND (TTRBody.belegerstellungsdatum " & IIf(belegeErstellt, "is not null)", "is null)")
        With MyDatagridview1
            .Columns.Clear()
            'MsgBox(.sql)

            .SET_SQL(" SELECT dbo.TTRBody.OBUID,dbo.TTRBody.CardNumber,dbo.TTRBody.receiptNumber,dbo.TTRBody.VATAmount,dbo.TTRBody.amountInclVAT,dbo.TTRBody.abrechnungsdatum,dbo.TTRBody.belegerstellungsdatum, dbo.tblWarenarten.WarenartDE, dbo.CLFArchiv.vehicleLicensePlate
                            FROM dbo.CLFArchiv 
                            RIGHT OUTER JOIN dbo.TTRBody ON dbo.CLFArchiv.OBUID = dbo.TTRBody.OBUID 
                            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("belegerstellungsdatum").HeaderText = "Belegerstellung am"
                .Columns("receiptNumber").HeaderText = "Rechnungsnummer"
                .Columns("VATAmount").HeaderText = "MWST"
                .Columns("amountInclVAT").HeaderText = "Brutto"

                .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

        cbxASFINAGAbgerechnet.Visible = False
        cbxBelegeerstellt.Visible = False
        cbxTestdaten.Visible = False
        pnlAsfinag.Visible = False
        Panel4.Visible = False
        Panel5.Visible = False


        Select Case Me.LIEFERANT
            Case "PLOSE"
                Panel4.Visible = True
                Dim c As New usrCntlMDMDatenverarbeitungAuswertungen_divers(Me, Me.LIEFERANT)
                Panel3.Controls.Add(c)
                c.Dock = DockStyle.Fill
            Case "UTA"
                Dim c As New usrCntlMDMDatenverarbeitungAuswertungen_divers(Me, Me.LIEFERANT)
                Panel3.Controls.Add(c)
                c.Dock = DockStyle.Fill
            Case "ASFINAG"
                cbxASFINAGAbgerechnet.Visible = True
                cbxBelegeerstellt.Visible = True
                If VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("ADMIN", Me.FindForm) Then
                    'cbxTestdaten.Visible = True
                End If
                pnlAsfinag.Visible = True
                Exit Sub
            Case "IDS"
                MsgBox("Noch nicht verfürbar!")

            Case "MSE"
                Panel5.Visible = True
                Dim c As New usrCntlMDMDatenverarbeitungAuswertungen_divers(Me, Me.LIEFERANT)
                Panel3.Controls.Add(c)
                c.Dock = DockStyle.Fill
        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 gen_SPEDBUCH_ByKdNr(R_PLOSE("AdressenNr"), SPEDBUCH, "PLOSE", R_PLOSE("PLOSEKundenNr"), dat_Sum_Von.Value.ToShortDateString, dat_Sum_Bis.Value.ToShortDateString) Then verarbOK = False
                If Not gen_RECHNUNG_BySPEDBUCH(R_PLOSE("AdressenNr"), SPEDBUCH, "PLOSE", R_PLOSE("PLOSEKundenNr"), 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 Kundennummer AS [Customer ID], KundenNr AS [Customer Nr], UTAExportCSV,Rechnungsdruck
                        FROM tblUTAFakturierwarenarten 
                        INNER JOIN (((Adressen INNER JOIN tblUTAImportNew ON Adressen.UTAKundenNr = tblUTAImportNew.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 (tblUTAImportNew.Lieferland = tblUTALeistungen.Lieferland) AND (tblUTAImportNew.Fakturierwarenart = tblUTALeistungen.Fakturierwarenart)) ON tblUTAFakturierwarenarten.Fakturierwarenart = tblUTALeistungen.Fakturierwarenart
                        where abgerechnet <> 1                        
                        group by Kundennummer, KundenNr, UTAExportCSV,Rechnungsdruck"

        Dim dt_Main As DataTable = SQL.loadDgvBySql_Param(SQLStr, "FMZOLL", 1200)


        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\" & IIf(VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM, "Test", "") & Now.ToShortDateString

            If Directory.Exists(dir) Then dir &= "_" & Now.ToShortTimeString.Replace(":", "")
            Directory.CreateDirectory(dir)


            Dim displayView = New DataView(dt_Main, "UTAExportCSV = 1", "Customer ID", DataViewRowState.CurrentRows)
            Dim distinctDT_CSV As DataTable = displayView.ToTable(True, "Customer ID", "Customer Nr")


            For Each csv As DataRow In distinctDT_CSV.Rows

                Dim dt_CSV_selected = SQL.loadDgvBySql_Param("SELECT * FROM tblUTAImportNew where Kundennummer = " & csv.Item("Customer ID"), "FMZOLL")
                dt_CSV_selected.ParentRelations.Clear()
                dt_CSV_selected.ChildRelations.Clear()
                dt_CSV_selected.Constraints.Clear()
                dt_CSV_selected.Columns.Remove("upsize_ts")


                Dim fn As String = dir & "\" & csv.Item(1) & "_Maut_UTA.csv"
                Dim outFile As System.IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(fn, False)
                Dim clmns As String = ""
                For i = 0 To dt_CSV_selected.Columns.Count - 1
                    clmns &= dt_CSV_selected.Columns(i).ColumnName.ToString().Replace(";", ",") & ";"
                Next
                outFile.WriteLine(clmns)
                For i = 0 To dt_CSV_selected.Rows.Count - 1
                    clmns = ""
                    For j = 0 To dt_CSV_selected.Columns.Count - 1
                        clmns &= dt_CSV_selected.Rows(i)(j).ToString.Replace(";", ",") & ";"
                    Next
                    outFile.WriteLine(clmns)

                Next
                outFile.Close()
            Next


            For Each UTA In dt_Main.Rows

                Dim SPEDBUCH As VERAG_PROG_ALLGEMEIN.cSpeditionsbuch = Nothing
                Dim verarbOK = True

                If Not gen_SPEDBUCH_ByKdNr(UTA("Customer ID"), SPEDBUCH, "UTA") Then verarbOK = False
                If Not gen_RECHNUNG_BySPEDBUCH(UTA("Customer ID"), SPEDBUCH, "UTA") Then verarbOK = False

                genUTAAttachmentByKdNr(UTA("Customer Nr"), UTA("Customer ID"), dir, datPloseAnhang.Value)

                If verarbOK Then
                    'UPDATE Fakturiert
                    SQL.doSQL("UPDATE [tblUTAImportNew] set abgerechnetDatum=GETDATE() where abgerechnetDatum is null and Kundennummer = " & UTA("Customer ID"), "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 genRGAtt_MSE() As Boolean
        Dim top = ""
        'top = " TOP 20 "
        Dim sqlWhere = IIf(test, " and (cust.[customer_id] = 12229 or cust.[customer_id] = 13236 or cust.[customer_id] = 11836 or cust.[customer_id] = 14385)", "") 'zum testem

        Dim SQLStr = " 	SELECT distinct cust.customer_id as [Customer ID], Adressen.AdressenNr AS [Customer Nr], Adressen.MSEExportCSV, Adressen.Rechnungsdruck
                        FROM [VERAG].[dbo].[tblMSESettlements] as bills 
                        left join [VERAG].[dbo].[tblMSETransactions] as trans on bills.[transaction_id] = trans.[transaction_id] 
                        left join [VERAG].[dbo].[tblMSECustomers] as cust on cust.partner_customer_number = trans.partner_haulier_id
                        left join [VERAG].[dbo].[tblMSEInvoices] as inv on inv.[invoice_id] = bills.[invoice_number] and inv.customer_number = cust.[customer_id] and trans.transaction_country = inv.country
                        left join adressen ON cust.[customer_id] = Adressen.MSEKundenNr 
                        where bills.invoice_date = '" & DateTimePicker2.Text & "' and trans.charged <> 1 and  (trans.transaction_gross_amount <> 0 or trans.[msts_fee_amount] <> 0) " & sqlWhere & "
                        order by cust.customer_id"

        Dim dt_Main As DataTable = SQL.loadDgvBySql_Param(SQLStr, "FMZOLL", 1200)


        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 = IIf(test, "C:\Users\d.breimaier\Desktop\MSE\", "F:\FMZoll\MSE\Archiv\" & IIf(VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM, "Test", "") & Now.ToShortDateString)

            If Directory.Exists(dir) Then dir &= "_" & Now.ToShortTimeString.Replace(":", "")
            Directory.CreateDirectory(dir)


            Dim displayView = New DataView(dt_Main, "MSEExportCSV = 1", "Customer ID", DataViewRowState.CurrentRows)
            Dim distinctDT_CSV As DataTable = displayView.ToTable(True, "Customer ID", "Customer Nr")


            For Each csv As DataRow In distinctDT_CSV.Rows

                Dim dt_CSV_selected = SQL.loadDgvBySql_Param("
                                SELECT controller_id as [Controller ID], 'VERAG 360 GmbH' as [Controller Name] , inv.[invoice_id] as [Invoice ID], inv.invoice_date as [Invoice Date], 
                                cust.customer_id as [Customer ID], cust.partner_customer_number as [Customer No], cust.customer_name as [Customer name], bills.specification_page_name as [Specification Page], bills.specification_page_id as [Specification ID], trans.purchase_datetime as [Transaction date], trans.transaction_id as [Transaction ID], 
                                trans.supplier_name as [Transaction Supplier/Terminal], trans.transaction_country as [Transaction Country], trans.transaction_product_name as [Product description], trans.transaction_product_id as [Product Description ID], trans.device_product_type as [Card Type], trans.device_product_number as [Card number], trans.license_plate_number as [Load File Licence Plate Number],
                                '' as [Card Licence Plate Number], trans.license_plate_number as [Truck Licence Plate Number], '' as [Truck Fleet Code], '' as [Truck Driver Name], trans.entry_point_name as [Entry Terminal/Direction], trans.entry_datetime as [Start date], trans.entry_datetime as [Start Time], trans.exit_point_name as [Exit Terminal Description], trans.exit_datetime as [End Date], trans.exit_datetime as [End Time],
                                ''  as [Eurovignet K-Number], '' as [LKW-Kostenstelle], trans.original_net_amount as [Original Nett Amount], trans.original_vat_amount as [Original VAT Amount], trans.original_gross_amount as [Original Amount], trans.original_currency as [Original Currency],
                                 trans.transaction_gross_amount as [Transaction Amount ( EUR )], trans.msts_fee_amount as [Admin Fee Amount ( EUR )], '' as [Fees and Costs Amount ( EUR )], trans.msts_vat_amount as [VAT Amount ( EUR )],trans.total_gross_amount as [Total Amount ( EUR )], ''  as [Total Dutch VAT ( EUR )], '' as [Total Foreign VAT ( EUR )], trans.[USteuer_EUR] as [USteuer_EUR]
                                FROM [VERAG].[dbo].[tblMSESettlements] as bills 
                                left join [VERAG].[dbo].[tblMSETransactions] as trans on bills.[transaction_id] = trans.[transaction_id] 
                                left join [VERAG].[dbo].[tblMSECustomers] as cust on cust.partner_customer_number = trans.partner_haulier_id
                                left join [VERAG].[dbo].[tblMSEInvoices] as inv on inv.[invoice_id] = bills.[invoice_number] and inv.customer_number = cust.[customer_id] and trans.transaction_country = inv.country
                                where bills.invoice_date = '" & DateTimePicker2.Text & "' and trans.charged <> 1 and (trans.transaction_gross_amount <> 0 or [msts_fee_amount] <> 0) and cust.[customer_id] = " & csv.Item("Customer ID"), "FMZOLL")
                dt_CSV_selected.ParentRelations.Clear()
                dt_CSV_selected.ChildRelations.Clear()
                dt_CSV_selected.Constraints.Clear()


                Dim fn As String = dir & "\" & csv.Item("Customer ID") & "_Maut_MSE.csv"
                Dim outFile As System.IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(fn, False)
                Dim clmns As String = ""
                For i = 0 To dt_CSV_selected.Columns.Count - 1
                    clmns &= dt_CSV_selected.Columns(i).ColumnName.ToString().Replace(";", ", ") & ";"
                Next
                outFile.WriteLine(clmns)
                For i = 0 To dt_CSV_selected.Rows.Count - 1
                    clmns = ""
                    For j = 0 To dt_CSV_selected.Columns.Count - 1
                        clmns &= dt_CSV_selected.Rows(i)(j).ToString.Replace(";", ", ") & ";"
                    Next
                    outFile.WriteLine(clmns)

                Next
                outFile.Close()
            Next


            For Each MSE In dt_Main.Rows

                Dim SPEDBUCH As VERAG_PROG_ALLGEMEIN.cSpeditionsbuch = Nothing
                Dim verarbOK = IIf(test, False, True)

                If Not gen_SPEDBUCH_ByKdNr(MSE("Customer Nr"), SPEDBUCH, "MSE") Then verarbOK = False
                If Not gen_RECHNUNG_BySPEDBUCH(MSE("Customer Nr"), SPEDBUCH, "MSE") Then verarbOK = False

                genMSEAttachmentByKdNr(MSE("Customer Nr"), MSE("Customer ID"), dir, datPloseAnhang.Value)

                If verarbOK Then
                    'Update Fakturiert
                    SQL.doSQL("UPDATE [tblMSETransactions] Set chargedDatetime = GETDATE() 
                        FROM [VERAG].[dbo].[tblMSESettlements] as bills 
                        inner join [VERAG].[dbo].[tblMSETransactions] as trans on bills.[transaction_id] = trans.[transaction_id] 
                        inner join [VERAG].[dbo].[tblMSECustomers] as cust on cust.partner_customer_number = trans.partner_haulier_id
                        where bills.invoice_date = '" & DateTimePicker2.Text & "' and trans.chargedDatetime is null and cust.[customer_id] = " & MSE("Customer ID"), "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

            If test Then Return True

            ' ANHÄNGE WERDEN NCIHT BENÖTIGT::
            'Alle Alangen im foglenden VZ löschen und die aktuellen kopieren
            Dim dirAnhang = "F:\FMZoll\MSE\Anlagen\" & IIf(VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM, "Test", "") & Now.ToShortDateString
            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_ASFINAG(belegerstellungsdatum As DateTime, abrechnungsdatum As Date, inputKdNr As String) As Boolean

        If cbxASFINAGAbgerechnet.Checked = False Then
            MsgBox("Bitte abgerechnete Daten auswählen!")
            Return False
        End If
        Dim sqlWhere As String = ""
        If inputKdNr <> "" Then
            sqlWhere &= " AND Adressen.AdressenNr=" & inputKdNr
        End If


        Dim dt_Main As DataTable = SQL.loadDgvBySql_Param("SELECT KundenNr, cardnumber FROM (SELECT Kreditkarten.KartenNr AS Kartennummer, Adressen.AdressenNr AS KundenNr FROM Adressen INNER JOIN Kreditkarten ON Adressen.AdressenNr = Kreditkarten.AdressenNr) as KUK INNER JOIN [tblAsfinagMaut] as Maut ON KUK.Kartennummer = Maut.cardnumber INNER JOIN Adressen ON KUK.KundenNr = Adressen.AdressenNr where Maut.receiptCreated = 0" & sqlWhere & "Group by KundenNr, cardnumber ", "FMZOLL")

        If dt_Main Is Nothing OrElse dt_Main.Rows.Count = 0 Then
            MsgBox("Keine Abrechnungsdaten vorhanden" & IIf(inputKdNr <> "", " für KundenNr: " & inputKdNr, "!"))
            Return False
        End If


        Dim dt_Main_PDF As DataTable = SQL.loadDgvBySql_Param("SELECT Maut.cardnumber, Maut.licenceplate, Maut.turnoverdate, Maut.contractPartner, Maut.netAmount, Maut.VATamount, Maut.totalAmount, Maut.[additionalData],Maut.receiptNumber, KUK.KundenNr, KUK.[Name 1] FROM (
                                                            SELECT Kreditkarten.KartenNr AS Kartennummer, Adressen.AdressenNr AS KundenNr, Adressen.[Name 1]
                                                            FROM Adressen INNER JOIN Kreditkarten ON Adressen.AdressenNr = Kreditkarten.AdressenNr) as KUK
                                                            INNER JOIN [tblAsfinagMaut] as Maut ON KUK.Kartennummer = Maut.cardnumber
                                                            INNER JOIN Adressen ON KUK.KundenNr = Adressen.AdressenNr
                                                            WHERE 1 = 1" & sqlWhere, "FMZOLL")


        Dim dt_Main_CSV As DataTable = SQL.loadDgvBySql_Param("SELECT Adressen.AdressenNr, Maut.*
                                                                FROM Adressen INNER JOIN (Kreditkarten INNER JOIN tblAsfinagMaut as Maut ON Kreditkarten.KartenNr = Maut.cardnumber) ON Adressen.AdressenNr = Kreditkarten.AdressenNr
                                                                WHERE Adressen.ASFINAGExportCSV = 1 " & sqlWhere & "
                                                                ORDER BY Adressen.AdressenNr, Maut.cardnumber, Maut.licenceplate, Maut.turnoverdate", "FMZOLL")

        Dim cnt = 0

        Dim displayViewKunden = New DataView(dt_Main, "", "KundenNr", DataViewRowState.CurrentRows)
        Dim distinctDT_distKunden As DataTable = displayViewKunden.ToTable(True, "KundenNr")

        Dim Info As String = ""
        If inputKdNr = "" Then
            Info = "Es wurden " & MyDatagridview1.Rows.Count & " Transaktionen von " & dt_Main.Rows.Count & " Kunden gefunden"
        Else
            Dim countTrans = SQL.getValueTxtBySql("SELECT count(cardnumber) FROM (SELECT Kreditkarten.KartenNr AS Kartennummer, Adressen.AdressenNr AS KundenNr FROM Adressen INNER JOIN Kreditkarten ON Adressen.AdressenNr = Kreditkarten.AdressenNr) as KUK INNER JOIN [tblAsfinagMaut] as Maut ON KUK.Kartennummer = Maut.cardnumber INNER JOIN Adressen ON KUK.KundenNr = Adressen.AdressenNr where Maut.receiptCreated = 0" & sqlWhere, "FMZOLL")
            Info = "Es wurden " & countTrans & " Transaktionen von " & dt_Main.Rows.Count & " Kunden gefunden "
        End If

        If vbYes = MsgBox(Info & vbNewLine & "Möchten Sie die Rechnungen + Anhänge erstellen?", vbYesNoCancel) Then
            Dim dir = "F:\FMZoll\Maut\AT\Anlagen" & IIf(VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM, "\Test", "") '"C:\Users\d.breimaier\Desktop\Asfinag\Mautberichte"   

            If Not Directory.Exists(dir) Then
                Directory.CreateDirectory(dir)
            End If


            If dt_Main_PDF IsNot Nothing AndAlso dt_Main_PDF.Rows.Count > 0 Then

                Dim displayView = New DataView(dt_Main_PDF, "", "KundenNr", DataViewRowState.CurrentRows)
                Dim distinctDT_PDF As DataTable = displayView.ToTable(True, "KundenNr")


                For Each pdf As DataRow In distinctDT_PDF.Rows

                    Dim dt_PDF_selected = dt_Main_PDF.Select("KundenNr ='" & pdf.Item(0) & "'").CopyToDataTable

                    genASFINAGAttachmentByKdNr(pdf.Item(0), dt_PDF_selected, dir & "\" & pdf.Item(0) & "_Maut_AT.pdf")

                Next

            End If


            If dt_Main_CSV IsNot Nothing AndAlso dt_Main_CSV.Rows.Count > 0 Then

                Dim displayView = New DataView(dt_Main_CSV, "", "AdressenNr", DataViewRowState.CurrentRows)
                Dim distinctDT_CSV As DataTable = displayView.ToTable(True, "AdressenNr")


                For Each csv As DataRow In distinctDT_CSV.Rows

                    Dim dt_CSV_selected = dt_Main_CSV.Select("AdressenNr ='" & csv.Item(0) & "'").CopyToDataTable


                    Dim fn As String = dir & "\" & csv.Item(0) & "_Maut_AT.csv"
                    Dim outFile As System.IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(fn, False)
                    Dim clmns As String = ""
                    For i = 0 To dt_CSV_selected.Columns.Count - 1
                        clmns &= dt_CSV_selected.Columns(i).ColumnName.ToString().Replace(";", ",") & ";"
                    Next
                    outFile.WriteLine(clmns)
                    For i = 0 To dt_CSV_selected.Rows.Count - 1
                        clmns = ""
                        For j = 0 To dt_CSV_selected.Columns.Count - 1
                            clmns &= dt_CSV_selected.Rows(i)(j).ToString.Replace(";", ",") & ";"
                        Next
                        outFile.WriteLine(clmns)

                    Next
                    outFile.Close()
                Next
            End If



            For Each R_ASFINAG In distinctDT_distKunden.Rows
                Dim SPEDBUCH As VERAG_PROG_ALLGEMEIN.cSpeditionsbuch = Nothing
                Dim verarbOK = True
                If Not gen_SPEDBUCH_ByKdNr(R_ASFINAG("KundenNr"), SPEDBUCH, "ASFINAG") Then verarbOK = False
                If Not gen_RECHNUNG_BySPEDBUCH(R_ASFINAG("KundenNr"), SPEDBUCH, "ASFINAG") Then verarbOK = False

                If verarbOK Then

                    If inputKdNr <> "" Then
                        Dim result As DataRow() = dt_Main.Select("KundenNr ='" & R_ASFINAG("KundenNr") & "'")
                        For Each row As DataRow In result
                            SQL.doSQL("UPDATE dbo.TTRBody SET belegerstellungsdatum = '" & belegerstellungsdatum & "' WHERE (PKHistory = 0) AND (PKFileName LIKE N'" & checkifTestfiles() & ".%') AND (FileCreationDate <='" & belegerstellungsdatum & "') AND (abrechnungsdatum = '" & abrechnungsdatum & "') And belegerstellungsdatum is null And CardNumber = " & row.Item("cardnumber") & "", "ASFINAG")
                        Next

                    Else
                        SQL.doSQL("UPDATE dbo.TTRBody SET belegerstellungsdatum = '" & belegerstellungsdatum & "' WHERE (PKHistory = 0) AND (PKFileName LIKE N'" & checkifTestfiles() & ".%') AND (FileCreationDate <='" & belegerstellungsdatum & "') AND (abrechnungsdatum = '" & abrechnungsdatum & "') And belegerstellungsdatum is null", "ASFINAG")
                    End If


                    Dim results As DataRow() = dt_Main.Select("KundenNr ='" & R_ASFINAG("KundenNr") & "'")
                    For Each r As DataRow In results
                        SQL.doSQL("UPDATE [tblAsfinagMaut] SET receiptCreated = 1 WHERE cardnumber = " & r.Item("cardnumber") & " AND receiptCreated = 0", "FMZOLL")
                    Next
                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)
            Dim dirCSV = "F:\FMZoll\Maut\Anlagen\" & IIf(VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM, "Test\", "")

            If Not Directory.Exists(dirCSV) Then
                Directory.CreateDirectory(dirCSV)
            End If

            For Each f In Directory.GetFiles(dir)
                If f.EndsWith(".csv") Then File.Copy(f, dirCSV & (New FileInfo(f)).Name, True)
            Next

            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=\\FMZOLL.verag.ost.dmn\f\FMZoll\MautD_Test.accd"
            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
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try
        Return False

    End Function


    Function genASFINAGInsertMautAT(kdNr) As Boolean
        Try
            pic.Visible = False
            Dim displayFilter = False
            Dim sqlstr As String = ""

            Dim sqlWhere As String = ""
            If kdNr <> "" Then
                sqlWhere &= " AND Adressen.AdressenNr=" & kdNr
            End If


            sqlstr = " select 
                        'AT'
                        ,Adressen.AdressenNr
                        ,licenceplate
                        ,turnoverdate
                        ,'AT'
                        ,contractPartner as ProductCode
                        ,[cardnumber] as CardNumber
                        ,[netAmount] as Netamount
                        ,[VATamount] as VATAmount
                        ,[totalAmount] as totalAmount
                         FROM [VERAG].[dbo].[tblAsfinagMaut]
                         INNER JOIN [VERAG].[dbo].Kreditkarten ON cardnumber = Kreditkarten.KartenNr
                         INNER JOIN [VERAG].[dbo].Adressen ON Adressen.AdressenNr = Kreditkarten.AdressenNr
                         WHERE 1 = 1 " & sqlWhere & "
		                 order by Adressen.AdressenNr"



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

            sqlstrAT &= "select  'AT'
                        ,Adressen.AdressenNr
                        ,licenceplate
                        ,turnoverdate
                        ,'AT' as land
                        ,'' as ProductCode
                        ,[cardnumber] as CardNumber
                        ,sum([netAmount]) as Netamount
                        ,sum([VATamount]) as VATAmount
                        ,sum([totalAmount]) as totalAmount
                         FROM [VERAG].[dbo].[tblAsfinagMaut]
                         INNER JOIN [VERAG].[dbo].Kreditkarten ON cardnumber = Kreditkarten.KartenNr
                         INNER JOIN [VERAG].[dbo].Adressen ON Adressen.AdressenNr = Kreditkarten.AdressenNr
                         WHERE 1 = 1 " & sqlWhere & "
						 group by Adressen.AdressenNr, licenceplate,turnoverdate,CardNumber
		                 order by Adressen.AdressenNr"

            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)})
            '        Next
            '    End If
            'End If

            Dim connectionString = ""
            If VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM Then
                connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\FMZOLL.verag.ost.dmn\f\FMZoll\MautD_Test.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],[Nett Amount],[VAT Amount],[Total Amount]) VALUES (@P1,@P2,@P3,@P4,@P5,@P6,@P7,@P8,@P9,@P10) "
                        '  "SELECT * FROM DBParent WHERE P_ID = " & UniqeID & ";"
                        Using Command As New OleDbCommand(SQLQuery, con)

                            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", CDbl(r(7)))
                            Command.Parameters.AddWithValue("@P9", CDbl(r(8)))
                            Command.Parameters.AddWithValue("@P10", CDbl(r(9)))

                            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


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

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

    End Function


    Function genUTAInsertMaut(kdNr) As Boolean
        Try
            pic.Visible = False
            Dim displayFilter = False
            Dim sqlstr As String = ""

            Dim sqlWhere As String = ""
            If kdNr <> "" Then
                sqlWhere &= " AND Adressen.AdressenNr=" & kdNr
            End If


            sqlstr = "SELECT qryUTA_Fakturierungspositionen.KundenNr AS [Customer No],
						isnull([KFZ_Kennzeichen_komprimiert],isnull([KFZ_Kennzeichen],isnull([Prägetext_i_d_R_KFZ_Kennzeichen],''))) AS LicencePlateNumber, 
						cast([Belegdatum] as datetime) AS [Transaction Date],
						 qryUTA_Fakturierungspositionen.Lieferland AS [Transaction Country],
						 qryUTA_Fakturierungspositionen.Warenart AS [Product description],
						 qryUTA_Fakturierungspositionen.Kartennummer AS [Card number], 
						 qryUTA_Fakturierungspositionen.Autobahnauffahrt AS [Entry Terminal],
						 qryUTA_Fakturierungspositionen.Autobahnausfahrt AS [Exit Terminal],
						  qryUTA_Fakturierungspositionen.Gesamtbetrag_Brutto_in_Darstellwährung AS [Total Amount],
						  qryUTA_Fakturierungspositionen.Gesamtbetrag_Netto_in_Darstellwährung AS [Nett Amount],
						  qryUTA_Fakturierungspositionen.Gesamtbetrag_Umsatzsteuer_in_Darstellwährung AS [VAT Amount]

                        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, tblUTAImportNew.*
                        FROM tblUTAFakturierwarenarten INNER JOIN (((Adressen INNER JOIN tblUTAImportNew ON Adressen.UTAKundenNr = tblUTAImportNew.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 (tblUTAImportNew.Lieferland = tblUTALeistungen.Lieferland) AND (tblUTAImportNew.Fakturierwarenart = tblUTALeistungen.Fakturierwarenart)) ON tblUTAFakturierwarenarten.Fakturierwarenart = tblUTALeistungen.Fakturierwarenart
                            WHERE Offertenpositionen.KundenNr=" & sqlWhere & " 
                        ) as qryUTA_Fakturierungspositionen
                        WHERE (((qryUTA_Fakturierungspositionen.Gesamtbetrag_Brutto_in_Darstellwährung)<>0))
                        order by KundenNr, LicencePlateNumber, Belegdatum, "



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




            Dim connectionString = ""
            If VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM Then
                connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\FMZOLL.verag.ost.dmn\f\FMZoll\MautD_Test.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) "
                        '  "SELECT * FROM DBParent WHERE P_ID = " & UniqeID & ";"
                        Using Command As New OleDbCommand(SQLQuery, con)

                            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", CDbl(r(7)))
                            Command.Parameters.AddWithValue("@P9", CDbl(r(8)))
                            Command.Parameters.AddWithValue("@P10", CDbl(r(9)))

                            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


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

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

    End Function


    Function genMSEInsertMaut(kdNr) As Boolean
        Try
            pic.Visible = False
            Dim displayFilter = False
            Dim sqlstr As String = ""

            Dim sqlWhere As String = ""
            If kdNr <> "" Then
                sqlWhere &= " AND Adressen.AdressenNr=" & kdNr
            End If


            sqlstr = " Select 'MSE',adressen.AdressenNr As [Customer No],
                    trans.license_plate_number as [Licence Plate Number],
                    cast(trans.[purchase_datetime] as Date) as [Transaction Date], 
                    trans.transaction_country As [Transaction Country],trans.device_product_type As [Product description],
                    trans.device_product_number as [Card Number], 
                    trans.entry_point_name as [Entry Terminal],
                    trans.exit_point_name as [Exit Terminal], 
                    case when trans.device_product_type like '%System Fee' then (msts_fee_amount + transaction_gross_amount) - trans.USteuer_EUR else transaction_gross_amount - trans.USteuer_EUR End As [Nett Amount],
                    trans.USteuer_EUR As [VAT Amount], 
                    case when trans.device_product_type like '%System Fee' then msts_fee_amount + transaction_gross_amount else transaction_gross_amount End as [Total Amount]
                       From [VERAG].[dbo].[tblMSESettlements] as bills 
                       left Join [VERAG].[dbo].[tblMSETransactions] as trans on bills.[transaction_id] = trans.[transaction_id] 
                       left Join [VERAG].[dbo].[tblMSECustomers] as cust on cust.partner_customer_number = trans.partner_haulier_id
                       left Join [VERAG].[dbo].[tblMSEInvoices] as inv on inv.[invoice_id] = bills.[invoice_number] And inv.customer_number = cust.[customer_id] And trans.transaction_country = inv.country
                       Left Join adressen ON cust.[customer_id] = Adressen.MSEKundenNr 
                       where bills.invoice_date = '" & DateTimePicker2.Text & "' and trans.chargedDatetime is not null " & sqlWhere &
                        "order by Adressen.AdressenNr "

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

            Dim connectionString = ""
            If VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM Then
                connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\FMZOLL.verag.ost.dmn\f\FMZoll\MautD_Test.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))
                            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

                    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
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        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=\\FMZOLL.verag.ost.dmn\f\FMZoll\MautD_Test.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
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        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
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        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] 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, tblUTAImportNew.*
                        FROM tblUTAFakturierwarenarten INNER JOIN (((Adressen INNER JOIN tblUTAImportNew ON Adressen.UTAKundenNr = tblUTAImportNew.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 (tblUTAImportNew.Lieferland = tblUTALeistungen.Lieferland) AND (tblUTAImportNew.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
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try
        Return ""

    End Function

    Function genMSEAttachmentByKdNr(KdNr As String, MSEKdNr As String, dir As String, bis As Date)
        Try

            Dim displayFilter = False
            Dim sqlstr As String = ""

            sqlstr &= "Select cust.customer_id as [Customer ID], cust.partner_customer_number as [Customer No], cust.customer_name as [Customer name], 
                                trans.supplier_name as [Transaction Supplier/Terminal], trans.transaction_country as [Transaction Country], trans.transaction_product_name as [Product description], trans.purchase_datetime as [Transaction date],trans.device_product_type as [Card Type], trans.device_product_number as [Card number], trans.license_plate_number as [LicencePlateNumber],
                                 trans.entry_point_name as [Entry Terminal/Direction], trans.entry_datetime as [Start date], trans.entry_datetime as [Start Time], trans.exit_point_name as [Exit Terminal Description], trans.exit_datetime as [End Date], trans.exit_datetime as [End Time],
                                 trans.original_net_amount as [Original Nett Amount], trans.original_vat_amount as [Original VAT Amount], trans.original_gross_amount as [Original Amount], trans.original_currency as [Original Currency],
                            case when trans.device_product_type like '%System Fee' then msts_fee_amount + transaction_gross_amount
                                else transaction_gross_amount End as [Transaction Amount ( EUR )], 
                               trans.msts_fee_amount as [Admin Fee Amount ( EUR )], '' as [Fees and Costs Amount ( EUR )], 
                               trans.msts_vat_amount as [VAT Amount ( EUR )],trans.total_gross_amount as [Total Amount ( EUR )], 
                            ''  as [Total Dutch VAT ( EUR )],
                            '' as [Total Foreign VAT ( EUR )], trans.[USteuer_EUR] as [USteuer_EUR]

                                FROM [VERAG].[dbo].[tblMSESettlements] as bills 
                                left join [VERAG].[dbo].[tblMSETransactions] as trans on bills.[transaction_id] = trans.[transaction_id] 
                                left join [VERAG].[dbo].[tblMSECustomers] as cust on cust.partner_customer_number = trans.partner_haulier_id
                                left join [VERAG].[dbo].[tblMSEInvoices] as inv on inv.[invoice_id] = bills.[invoice_number] and inv.customer_number = cust.[customer_id] and trans.transaction_country = inv.country
                                where bills.invoice_date = '" & DateTimePicker2.Text & "' and (trans.transaction_gross_amount <> 0 or [msts_fee_amount] <> 0) and cust.[customer_id] = " & MSEKdNr & " order by trans.license_plate_number"

            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 = "Transaction Amount(EUR)"
            rpt.Label4.Text = bis.ToShortDateString
            rpt.Label2.Text = "MSE-KundenNr:"
            rpt.TextBox1.Text = MSEKdNr
            rpt.Label1.Text = " MSE 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("Transaction Amount ( EUR )").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("Transaction Amount ( EUR )").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_MSE.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
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try
        Return ""

    End Function


    Function genASFINAGAttachmentByKdNr(KdNr As Integer, dt As DataTable, tmpPath As String)
        Try


            If dt Is DBNull.Value Then Return ""
            If dt.Rows.Count = 0 Then Return ""

            Dim rpt As New rptASFINAG_Anhang

            rpt.DataSource = dt

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

            rpt.GroupHeaderKz.DataField = "licenceplate" '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 = " ASFINAG"

            ' 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("KundenNr").Value, "")
                                              rpt.txtKunde.Text &= " " & SQL.isDbnullEmpty(rpt.Fields.Item("Name 1").Value, "")
                                              rpt.txtLand.Text = "AT"
                                              ' End If

                                              '   rpt.txtProduktBeschreibung.Text = sql.isDbnullEmpty(rpt.Fields.Item("BC_DESCR").Value, "")
                                              rpt.txtProdukt.Text = SQL.isDbnullEmpty(rpt.Fields.Item("contractPartner").Value, "") 'sql.isDbnullEmpty(rpt.Fields.Item("plose_ProduktCode").Value, "") & " - " & sql.isDbnullEmpty(rpt.Fields.Item("plose_Produktbeschreibung").Value, "")


                                              rpt.txtKartennummer.Text = SQL.isDbnullEmpty(rpt.Fields.Item("cardnumber").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("turnoverdate").Value, "")
                                              rpt.txtEingang.Text = SQL.isDbnullEmpty(rpt.Fields.Item("receiptNumber").Value, "")

                                              rpt.txtNetto.Text = SQL.isDbnullEmptyDbl(rpt.Fields.Item("netAmount").Value, 2, "")
                                              rpt.txtMWST.Text = SQL.isDbnullEmptyDbl(rpt.Fields.Item("VATamount").Value, 2, "")
                                              rpt.txtBrutto.Text = SQL.isDbnullEmptyDbl(rpt.Fields.Item("totalAmount").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("totalAmount").Value, 4, 0)
                                              cnt += 1
                                          End Sub

            AddHandler rpt.GroupHeaderKz.Format, Sub()
                                                     rpt.txtKennzeichen.Text = SQL.isDbnullEmpty(rpt.Fields.Item("licenceplate").Value, "")
                                                     If rpt.txtKennzeichen.Text = "" Then rpt.lblKennzeichen.Visible = False
                                                 End Sub
            AddHandler rpt.GroupHeaderKat.Format, Sub()
                                                      rpt.lblKategorie.Text = "MAUTGEBÜHR"
                                                  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("licenceplate").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 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
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try
        Return ""

    End Function


    Function gen_SPEDBUCH_ByKdNr(KdNr As String, ByRef SPEDBUCH As VERAG_PROG_ALLGEMEIN.cSpeditionsbuch, Lieferant As String, Optional PLOSEKundenNr As String = "", Optional von As Date = Nothing, Optional bis As Date = Nothing)
        Try

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

            Dim OffertenNr As Integer
            Dim Abfertigungsart As Integer

            Select Case Lieferant
                Case "PLOSE" : OffertenNr = 80 : Abfertigungsart = 10 : SPEDBUCH.FilialenNr = 4824
                Case "ASFINAG" : OffertenNr = 11 : Abfertigungsart = 10 : SPEDBUCH.FilialenNr = 4814
                Case "UTA" : OffertenNr = 30 : Abfertigungsart = 10 : SPEDBUCH.FilialenNr = 4823
                Case "MSE" : OffertenNr = 23 : Abfertigungsart = 10 : SPEDBUCH.FilialenNr = 4821
            End Select

            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 IIf(test, True, SPEDBUCH.SAVE)

        Catch ex As System.Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        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 OFFERTE As New VERAG_PROG_ALLGEMEIN.cOfferte(KdNr, OffertenNr, True)

    '        RG.LOAD_OFFERT_POSITIONEN() ' --> OFFERTE MIT ANZAHL >0 und Preis >0 

    '        ' RG.LOAD_POSITIONEN_FROM_OFFERTE(OFFERTE)

    '        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")


    '            allPos(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.przFixeTaxe(RG)    ' Fixe Taxe errechnen
    '        Call usrCntlFaktAbrechnung.przPP(RG)          ' Porto/Papiere errechnen

    '        Call usrCntlFaktAbrechnung.przBS415(RG)       ' Bankspesen errechnen

    '        If RG.SAVE Then
    '            Return True
    '        Else
    '            Return False
    '        End If

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

    'End Function

    Function gen_RECHNUNG_BySPEDBUCH(KdNr As String, SPEDBUCH As VERAG_PROG_ALLGEMEIN.cSpeditionsbuch, Lieferant As String, Optional PLOSEKundenNr As String = "", Optional von As Date = Nothing, Optional bis As Date = Nothing)
        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 As Integer
            Dim Abfertigungsart As Integer

            Select Case Lieferant
                Case "PLOSE" : OffertenNr = 80 : Abfertigungsart = 10 : RG.Anlage_1 = ""
                Case "ASFINAG" : OffertenNr = 11 : Abfertigungsart = 10 : RG.Anlage_1 = "Email Anhang"
                Case "UTA" : OffertenNr = 30 : Abfertigungsart = 10 : RG.Anlage_1 = "Email Anhang"
                Case "MSE" : OffertenNr = 23 : Abfertigungsart = 10 : RG.Anlage_1 = "Email Anhang"

            End Select

            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_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 '<= Status während der Erfassung über die Maut/Diesel-Schnittstelle - Nach Abschluss der Datenübernahme Änderung auf 0 20231220 -> gleich auf 0 setzen!

            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 = ""
            Dim useNettogesamtbetrag As Boolean = False

            Select Case Lieferant
                Case "PLOSE"

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

                    RG.LOAD_OFFERT_POSITIONEN() ' --> OFFERTE MIT ANZAHL >0 und Preis >0 

                    ' RG.LOAD_POSITIONEN_FROM_OFFERTE(OFFERTE)

                    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")


                        allPos(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



                Case "ASFINAG"
                    useNettogesamtbetrag = True

                    sqlstr = "SELECT '135' as LeistungsNr, 'MAUT AT lt. Auslage' as ProductCode, sum([netAmount]) as Netto ,sum([VATamount]) as Vatamount ,sum([totalAmount]) as Brutto FROM Kreditkarten INNER JOIN tblAsfinagMaut ON Kreditkarten.KartenNr = tblAsfinagMaut.cardnumber Where Kreditkarten.AdressenNr= '" & KD.KundenNr & "' and tblAsfinagMaut.VATamount <> 0 group by Kreditkarten.AdressenNr
                                    UNION
                              SELECT '153' as LeistungsNr, 'MAUT AT lt. Auslage' as ProductCode, sum([netAmount]) as Netto ,sum([VATamount]) as Vatamount ,sum([totalAmount]) as Brutto FROM Kreditkarten INNER JOIN tblAsfinagMaut ON Kreditkarten.KartenNr = tblAsfinagMaut.cardnumber Where Kreditkarten.AdressenNr= '" & KD.KundenNr & "' and tblAsfinagMaut.VATamount = 0 group by Kreditkarten.AdressenNr"

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

                    For Each r In dt.Rows


                        Dim NettoBetrag As Double = r("Netto")
                        Dim BruttoBetrag As Double = r("Brutto")
                        Dim LeistungsNr As Integer = r("LeistungsNr")
                        Dim OFFERTE As New VERAG_PROG_ALLGEMEIN.cOfferte(KdNr, OffertenNr, True)

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

                    Next



                Case "UTA"

                    useNettogesamtbetrag = False

                    sqlstr = " SELECT Adressen.AdressenNr, Adressen.[Name 1], Adressen.LandKz, Adressen.Ort,Offertenpositionen.OffertenNr, Offertenpositionen.LeistungsNr, Offertenpositionen.LeistungsBez, tblUTAFakturierwarenarten.Warenart, tblUTAImportNew.Fakturierwarenart,sum(tblUTAImportNew.Gesamtbetrag_Netto_in_Lieferlandwährung) as Netto ,sum(tblUTAImportNew.Gesamtbetrag_Brutto_in_Lieferlandwährung) as Brutto
                        FROM tblUTAFakturierwarenarten 
                        INNER JOIN (((Adressen INNER JOIN tblUTAImportNew ON Adressen.UTAKundenNr = tblUTAImportNew.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 (tblUTAImportNew.Lieferland = tblUTALeistungen.Lieferland) AND (tblUTAImportNew.Fakturierwarenart = tblUTALeistungen.Fakturierwarenart)) ON tblUTAFakturierwarenarten.Fakturierwarenart = tblUTALeistungen.Fakturierwarenart
                        where Offertenpositionen.LeistungsNr is not null AND Offertenpositionen.OffertenNr = " & OffertenNr & " AND Offertenpositionen.KundenNr  = " & KdNr &
                        "group by Adressen.AdressenNr, Adressen.[Name 1], Adressen.LandKz, Adressen.Ort, Offertenpositionen.OffertenNr, Offertenpositionen.LeistungsNr, Offertenpositionen.LeistungsBez, tblUTAFakturierwarenarten.Warenart,tblUTAImportNew.Fakturierwarenart"

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

                    For Each r In dt.Rows


                        Dim NettoBetrag As Double = r("Netto")
                        Dim BruttoBetrag As Double = r("Brutto")
                        Dim UstBetrag As Double = BruttoBetrag = NettoBetrag
                        Dim LeistungsNr As Integer = r("LeistungsNr")
                        Dim OFFERTE As New VERAG_PROG_ALLGEMEIN.cOfferte(KdNr, OffertenNr, True)

                        allPos(RG, OFFERTE, LeistungsNr, NettoBetrag, BruttoBetrag, UstBetrag)

                    Next



                Case "MSE"
                    'des is da schass!!!!
                    '                Case 23 'MSE Maut
                    '5070                             Select Case ![LeistungsNr]
                    '                                     Case 134  'Frejus - Tunnelmaut (20.01.2011)
                    '5080                                     Set rst = OpenParameterQuery("qryReErfSchOpt6BeträgeLNr134", eOpensnapshot, "prmAdressenNr:=" & rstRK![RechnungsKundenNr])
                    '5090                                     If Not rst.EOF Then
                    '5100                                         ![Anzahl] = 1
                    '5110                                         ![Preis] = rst![SummevonTransaction Amount ( EUR )] + rst![SummevonFees And Costs Amount ( EUR )]
                    '5120                                         If Not IsNull(![BGebLeistungsNr]) Then
                    '5130                                             ![BGebBgl] = ![Preis] - rst![SummevonUSteuer_EUR]
                    '5140                                         End If
                    '5150                                     End If
                    '5160                                     rst.Close
                    '5170                                     Set rst = Nothing

                    'qryReErfSchOpt6BeträgeLNr134



                    '5180                                 Case 141  'MSC Ressa - alle Länder
                    '5190                                     Set rst = OpenParameterQuery("qryReErfSchOpt6BeträgeLNr141", eOpensnapshot, "prmAdressenNr:=" & rstRK![RechnungsKundenNr])
                    '5200                                     If Not rst.EOF Then
                    '5210                                         ![Anzahl] = 1
                    '5220                                         ![Preis] = rst![SummevonTransaction Amount ( EUR )] + rst![SummevonFees And Costs Amount ( EUR )]
                    '5230                                         If Not IsNull(![BGebLeistungsNr]) Then
                    '5240                                             ![BGebBgl] = ![Preis] - rst![SummevonUSteuer_EUR]
                    '5250                                         End If
                    '5260                                     End If
                    '5270                                     rst.Close
                    '5280                                     Set rst = Nothing

                    'qryReErfSchOpt6BeträgeLNr141


                    '5290                                 Case Else 'alle anderen MSE Transactions
                    '5300                                     Set rst = OpenParameterQuery("qryReErfSchOpt6Beträge", eOpensnapshot, "prmAdressenNr:=" & rstRK![RechnungsKundenNr], "prmLeistungsNr:=" & ![LeistungsNr])
                    '5310                                     If Not rst.EOF Then
                    '5320                                         ![Anzahl] = 1
                    '5330                                         ![Preis] = rst![SummevonTransaction Amount ( EUR )] + rst![SummevonFees And Costs Amount ( EUR )]
                    '5340                                         If Not IsNull(![BGebLeistungsNr]) Then
                    '5350                                             ![BGebBgl] = ![Preis] - rst![SummevonUSteuer_EUR]
                    '5360                                         End If
                    '5370                                     End If
                    '5380                                     rst.Close
                    '5390                                     Set rst = Nothing
                    '5400                             End Select

                    'qryReErfSchOpt6Beträge



                    useNettogesamtbetrag = False
                    'alles steuerfrei also Brutto = Netto
                    sqlstr = "select customer_id, LeistungsNr,  sum(Netto) as Netto, Sum (Brutto) as Brutto, Sum (UST) as UST from (select cust.[customer_id], trans.device_product_type, Offertenpositionen.LeistungsNr , 
                                case when trans.device_product_type like '%System Fee' then sum(msts_fee_amount) + sum(transaction_gross_amount) 
                                else sum(transaction_gross_amount) End as Netto,
                                case when trans.device_product_type like '%System Fee' then sum(msts_fee_amount) + sum(transaction_gross_amount) 
                                else sum(transaction_gross_amount) End as Brutto,
                                sum(USteuer_EUR) as UST
                                FROM [VERAG].[dbo].[tblMSESettlements] as bills 
                                left join [VERAG].[dbo].[tblMSETransactions] as trans on bills.[transaction_id] = trans.[transaction_id] 
                                left join [VERAG].[dbo].[tblMSECustomers] as cust on cust.partner_customer_number = trans.partner_haulier_id
                                left JOIN tblMSELeistungen ON (tblMSELeistungen.[Card Type] = trans.device_product_type)  AND (tblMSELeistungen.[Transaction Country] = trans.transaction_country)
                                left JOIN Offertenpositionen ON cust.partner_customer_number = Offertenpositionen.KundenNr and tblMSELeistungen.LeistungsNr  = Offertenpositionen.LeistungsNr and Offertenpositionen.OffertenNr = " & OffertenNr & "
                                where bills.invoice_date = '" & DateTimePicker2.Text & "' and trans.charged = 0 and  cust.[partner_customer_number] = " & KdNr & "
                                group by cust.[customer_id], trans.device_product_type, Offertenpositionen.LeistungsNr , Offertenpositionen.LeistungsBez ) as temp group by customer_id, LeistungsNr"

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

                    For Each r In dt.Rows


                        Dim NettoBetrag As Double = r("Netto")
                        Dim BruttoBetrag As Double = r("Brutto")
                        Dim UstBetrag As Double = r("UST")
                        Dim LeistungsNr As Integer = r("LeistungsNr")
                        Dim OFFERTE As New VERAG_PROG_ALLGEMEIN.cOfferte(KdNr, OffertenNr, True)

                        allPos(RG, OFFERTE, LeistungsNr, NettoBetrag, BruttoBetrag, UstBetrag)

                    Next

            End Select


            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,, useNettogesamtbetrag)

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

            Call usrCntlFaktAbrechnung.przFixeTaxe(RG)    ' Fixe Taxe errechnen
            Call usrCntlFaktAbrechnung.przPP(RG)          ' Porto/Papiere errechnen
            Call usrCntlFaktAbrechnung.przBS415(RG)       ' Bankspesen errechnen

            Return IIf(test, True, RG.SAVE)

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

    End Function


    Function allPos(ByRef RG As VERAG_PROG_ALLGEMEIN.cRechnungsausgang, OFFERTE As VERAG_PROG_ALLGEMEIN.cOfferte, LeistungsNr As Integer, NettoBetrag As Double, BruttoBetrag As Double, Optional UstBetrag As Double = 0)
        Try

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

                    'Dim PARK = RECHNUNG.POSITIONEN.FindAll(Function(x) (x.LeistungsNr = 313 Or x.LeistungsNr = 312))
                    'If PARK Is Nothing Then

                    'End If

                    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
                    'Berrechnunggebühr wird immer vom übergebenen Betrag abzüglich UST berechnet (Nettobetrag)!
                    POS.BGebBgl = IIf(LIEFERANT = "UTA", BruttoBetrag - UstBetrag, NettoBetrag - UstBetrag)


                    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
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        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
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        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
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        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, DateTimePicker2.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 order by PLOSEKundenNr", "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') order by plp_ProductCode ", "FMZOLL")
            Dim OffertenNr_DT = SQL.loadDgvBySql("SELECT KundenNr,OffertenNr FROM [Offerten] where  OffertenNr = 80 order by KundenNr", "FMZOLL")
            Dim KundeLeistungsNr_DT = SQL.loadDgvBySql("SELECT [LeistungsNr],KundenNr FROM [Offertenpositionen] where  OffertenNr = 80 order by KundenNr", "FMZOLL")

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

            Dim cnt = 0
            Dim cntTotal = MyDatagridview1.Rows.Count()

            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



                '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 / cntTotal * 100) & " %"
                    lblProzPruef.Refresh()
                    'Me.Refresh()
                End If

                cnt += 1

            Next

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

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

    Function pruefData_ASFINAG() As Boolean
        pruefData_ASFINAG = True
        Try

            '     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 dtAsfinagKartenpruef As DataTable = SQL.loadDgvBySql("
                        SELECT 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.tblAsfinagMaut 
                            LEFT JOIN [dbo].[Kreditkarten] on cardnumber= Kreditkarten.KartenNr
                            GROUP BY cardnumber, Kreditkarten.KartenNr, Kreditkarten.AdressenNr
                            HAVING cardnumber is null or (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 cardnumber", "FMZOLL")


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

            Dim cnt = MyDatagridview1.Rows.Count

            MyDatagridview1.ClearSelection()
            MyDatagridview1.DataSource = dtAsfinagKartenpruef
            Dim count = MyDatagridview1.Rows.Count()
            If count > 0 Then
                lblProzPruef.Text = CInt(cnt / count * 100) & " %"
            Else
                cbxASFINAGAbgerechnet.Checked = True
            End If
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
            pruefData_ASFINAG = False
        End Try
    End Function


    Function pruefData_UTA() As Boolean
        pruefData_UTA = True
        Try

            Dim dtUTAKundennummern As DataTable = SQL.loadDgvBySql("SELECT Distinct(tblUTAImportNew.Kundennummer)
            FROM tblUTAImportNew LEFT JOIN Adressen ON tblUTAImportNew.Kundennummer = Adressen.UTAKundenNr
            GROUP BY tblUTAImportNew.Kundennummer, Adressen.UTAKundenNr
            HAVING (((Adressen.UTAKundenNr) Is Null))", "FMZOLL")

            If dtUTAKundennummern.Rows.Count > 0 Then

                pruefData_UTA = False

                If dtUTAKundennummern.Rows.Count = 1 AndAlso dtUTAKundennummern.Rows(0).Item("Kundennummer") = 868070 Then pruefData_UTA = True 'ist VERAG -> OK

            End If


            Dim dtUTAFakturierwarenarten As DataTable = SQL.loadDgvBySql("SELECT tblUTAImportNew.Fakturierwarenart, tblUTAImportNew.Lieferland
            FROM tblUTAImportNew LEFT JOIN tblUTALeistungen ON (tblUTAImportNew.Fakturierwarenart = tblUTALeistungen.Fakturierwarenart) AND (tblUTAImportNew.Lieferland = tblUTALeistungen.Lieferland)
            GROUP BY tblUTAImportNew.Fakturierwarenart, tblUTAImportNew.Lieferland, tblUTALeistungen.Fakturierwarenart, tblUTALeistungen.Lieferland
            HAVING (((tblUTALeistungen.Fakturierwarenart) Is Null) AND ((tblUTALeistungen.Lieferland) Is Null))", "FMZOLL")


            If dtUTAFakturierwarenarten.Rows.Count > 0 Then

                pruefData_UTA = False

            End If

            Dim dtUTAOffertenPositionen As DataTable = SQL.loadDgvBySql("SELECT * FROM vwUTA_PrüfungInkonsistenzVERAGOffertenpositionen2_new", "FMZOLL")

            If dtUTAOffertenPositionen.Rows.Count > 0 Then

                pruefData_UTA = False

            End If

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

    Function pruefData_MSE() As Boolean
        pruefData_MSE = True
        Try

            Dim fehlendeKundenr As Integer = CInt((New SQL).getValueTxtBySql("select count(*) from (SELECT cust.customer_id, cust.customer_name, Adressen.AdressenNr,  (SELECT Offerten.OffertenNr FROM Offerten WHERE (((Offerten.KundenNr)=isnull(Adressen.[AdressenNr],0)) AND ((Offerten.OffertenNr)=23))) AS Offerte_23
                                      FROM [VERAG].[dbo].[tblMSESettlements] as bills 
                                      left join [VERAG].[dbo].[tblMSETransactions] as trans on bills.[transaction_id] = trans.[transaction_id] 
                                      left join [VERAG].[dbo].[tblMSECustomers] as cust on cust.partner_customer_number = trans.partner_haulier_id
                                      left join [VERAG].[dbo].[tblMSEInvoices] as inv on inv.[invoice_id] = bills.[invoice_number] and inv.customer_number = cust.[customer_id] and trans.transaction_country = inv.country
                                      left join adressen ON cust.[customer_id] = Adressen.MSEKundenNr 
                                      WHERE bills.[invoice_date] = '" & DateTimePicker2.Text & "'      
                                      GROUP BY cust.customer_id, cust.customer_name, Adressen.AdressenNr
                                      HAVING (((cust.customer_id) Is Not Null) AND ((Adressen.AdressenNr) Is Null)) OR (((cust.customer_id) Is Not Null) AND ((Adressen.AdressenNr) Is Not Null) AND (((SELECT Offerten.OffertenNr FROM Offerten WHERE (((Offerten.KundenNr)=isnull(Adressen.[AdressenNr],0)) AND ((Offerten.OffertenNr)=23)))) Is Null)))as a", "FMZOLL"))

            If fehlendeKundenr > 0 Then
                pruefData_MSE = False
                MsgBox("Es sind " & fehlendeKundenr & " Kunden nicht der MSE-KundenNr bzw. fehlt die Offerte verknüpft!" & vbNewLine & "Diese Kunden (von Rechnung " & DateTimePicker2.Text & ") müssen aktualisiert werden. (bitte an Administrator wenden).")
                Return False
            End If

            Dim sqlStringfalscheLeistungsNr = "select count (*) from (Select trans.device_product_type, trans.transaction_country,trans.transaction_product_name, trans.transaction_product_id, cust.[customer_id], trans.partner_haulier_id, cust.customer_name, 
                          sum(trans.transaction_gross_amount) As [Summe Transaction Amount ( EUR )], 
                          sum(trans.msts_fee_amount) As [Summe Admin Fee Amount ( EUR )], 
                          sum(trans.msts_fee_amount) As [Summe Fees And Costs Amount ( EUR )], 
                          sum(trans.msts_vat_amount) As [Summe VAT Amount ( EUR )], 
                          sum(trans.transaction_gross_amount) As [Summe Total Amount ( EUR )]
                          From [VERAG].[dbo].[tblMSESettlements] as bills 
                          Left Join [VERAG].[dbo].[tblMSETransactions] as trans on bills.[transaction_id] = trans.[transaction_id] 
                          Left Join [VERAG].[dbo].[tblMSECustomers] as cust on cust.partner_customer_number = trans.partner_haulier_id
                          Left Join [VERAG].[dbo].[tblMSEInvoices] as inv on inv.[invoice_id] = bills.[invoice_number] And inv.customer_number = cust.[customer_id] And trans.transaction_country = inv.country
                          Left Join tblMSELeistungen ON trans.device_product_type = tblMSELeistungen.[Card Type] And trans.transaction_country = tblMSELeistungen.[Transaction Country]
                          WHERE((trans.transaction_gross_amount <> 0) And tblMSELeistungen.LeistungsNr Is Null) And bills.[invoice_date] = '" & DateTimePicker2.Text & "'                        
                          GROUP by trans.device_product_type, trans.transaction_country, trans.transaction_product_name, trans.transaction_product_id, cust.[customer_id], trans.partner_haulier_id, cust.customer_name) as a"

            Dim falscheLeistungsnummern As Integer = CInt((New SQL).getValueTxtBySql(sqlStringfalscheLeistungsNr, "FMZOLL"))


            If falscheLeistungsnummern > 0 Then
                If Not SQL.doSQL("update [VERAG].[dbo].[tblMSETransactions] set device_product_type = 'HUGO SIM renewal cost' where transaction_product_id = 453 and transaction_product_name like 'HUGO SIM renewal cost%'", "FMZOLL") Then
                    MsgBox("Fehler beim Setzen der HUGO SIM renewal cost")
                    Return False
                End If

                falscheLeistungsnummern = CInt((New SQL).getValueTxtBySql(sqlStringfalscheLeistungsNr, "FMZOLL"))
                If falscheLeistungsnummern > 0 Then
                    pruefData_MSE = False
                    MsgBox("Es fehlen " & falscheLeistungsnummern & " Leistungsnummern!" & vbNewLine & "Diese Leistungssnummern (von Rechnung " & DateTimePicker2.Text & ") müssen nachgetragen werden. (bitte an Administrator wenden, tblMSELeistungen).")
                    Return False
                End If


            End If

            Dim nichtAufAbgerechnetGesetzteTransactionen As Integer = 0

            nichtAufAbgerechnetGesetzteTransactionen = CInt((New SQL).getValueTxtBySql("select count (*) FROM [VERAG].[dbo].[tblMSESettlements] as bills inner join [VERAG].[dbo].[tblMSETransactions] as trans on bills.[transaction_id] = trans.[transaction_id]  where trans.[transaction_status] <> 'Billed' and [invoice_date] = '" & DateTimePicker2.Text & "'", "FMZOLL"))

            If nichtAufAbgerechnetGesetzteTransactionen > 0 Then
                Dim hint As String = ""
                pruefData_MSE = False
                If nichtAufAbgerechnetGesetzteTransactionen > 500 Then
                    hint = "Batch-Nr: "
                    hint &= SQL.getValueTxtBySql("select distinct(trans.batch_seq_nr) FROM [VERAG].[dbo].[tblMSESettlements] as bills inner join [VERAG].[dbo].[tblMSETransactions] as trans on bills.[transaction_id] = trans.[transaction_id]  where trans.[transaction_status] <> 'Billed' and [invoice_date] = '" & DateTimePicker2.Text & "'", "FMZOLL")
                End If
                MsgBox("Es sind " & nichtAufAbgerechnetGesetzteTransactionen & " Transaktionen in der Datenbank, die noch nicht auf VERRECHNET gesetzt sind!" & vbNewLine & "Diese Transaktionen (von Rechnung " & DateTimePicker2.Text & ") müssen aktualisiert werden. (bitte an Administrator wenden)." & IIf(hint <> "", vbNewLine & hint, ""))
            End If


            'das muss die letzte Prüfung sein, da uU eine Transaktion fehlen kann!
            Dim fehlendeTransactionen As Integer = 0

            fehlendeTransactionen = CInt((New SQL).getValueTxtBySql("select count(*) FROM [VERAG].[dbo].[tblMSESettlements] where [invoice_date] = '" & DateTimePicker2.Text & "' AND [transaction_id] not in (select [transaction_id] from [VERAG].[dbo].[tblMSETransactions]) ", "FMZOLL"))

            If fehlendeTransactionen > 0 Then
                pruefData_MSE = False
                Dim hint As String = ""
                If fehlendeTransactionen > 500 Then
                    hint = "Batch-Nr: "
                    hint &= SQL.getValueTxtBySql("select distinct(trans.batch_seq_nr) FROM [VERAG].[dbo].[tblMSESettlements] as settle INNER JOIN [VERAG].[dbo].[tblMSETransactions] as trans on trans.transaction_id = settle.transaction_id where [invoice_date] = '" & DateTimePicker2.Text & "' AND trans.[transaction_id] not in (select [transaction_id] from [VERAG].[dbo].[tblMSETransactions]) ", "FMZOLL")
                End If
                MsgBox("Es fehlen " & fehlendeTransactionen & " Transaktionen in der Datenbank!" & vbNewLine & "Diese Transaktionen (von Rechnung " & DateTimePicker2.Text & ") müssen nachgeladen werden (bitte an Administrator wenden)." & IIf(hint <> "", vbNewLine & hint, ""))
            End If

        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
            pruefData_MSE = 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
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
            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 IsNumeric(MyDatagridview1.SelectedRows(0).Cells("VERAGKdNr").Value) AndAlso MyDatagridview1.SelectedRows(0).Cells("VERAGKdNr").Value > 0 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 IsNumeric(MyDatagridview1.SelectedRows(0).Cells("VERAGKdNr").Value) AndAlso MyDatagridview1.SelectedRows(0).Cells("VERAGKdNr").Value > 0 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(Optional kdNr = "") As Boolean
        Select Case LIEFERANT
            Case "PLOSE" : deleteMautD("PLOSE") : Return genPLOSEInsertMautD(dat_Sum_Von.Value.ToShortDateString, dat_Sum_Bis.Value.ToShortDateString)
            Case "ASFINAG" : deleteMautD("AT") : Return genASFINAGInsertMautAT(kdNr)
            Case "UTA" : deleteMautD("UTA") : Return genUTAInsertMaut(kdNr)
            Case "MSE" : deleteMautD("MSE") : Return genMSEInsertMaut(kdNr)
        End Select
        Return False
    End Function


    Sub setFakturiert(Lieferant As String)
        PictureBox1.Visible = False

        Select Case Lieferant
            Case "PLOSE"
                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
            Case "UTA"
                If SQL.doSQL("UPDATE [tblUTAImportNew] set abgerechnet=1 where abgerechnetDatum is not null and abgerechnet <> 1", "FMZOLL") Then
                    PictureBox1.Visible = True
                End If
            Case "MSE"
                If SQL.doSQL("UPDATE [VERAG].[dbo].[tblMSETransactions] Set charged = 1 
                        FROM [VERAG].[dbo].[tblMSESettlements] as bills 
                        inner join [VERAG].[dbo].[tblMSETransactions] as trans on bills.[transaction_id] = trans.[transaction_id] 
                        inner join [VERAG].[dbo].[tblMSECustomers] as cust on cust.partner_customer_number = trans.partner_haulier_id
                        where bills.invoice_date = '" & DateTimePicker2.Text & "' and trans.chargedDatetime is not null and charged <> 1 ") Then
                    PictureBox1.Visible = True
                End If
            Case Else
                MsgBox("Funktion setFaktiuriert für den Lieferant " & Lieferant & " nicht definiert!")
        End Select



    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" : setFakturiert(LIEFERANT)
                Case "UTA" : setFakturiert(LIEFERANT)
                Case "MSE" : setFakturiert(LIEFERANT)
                Case "ASFINAG" : setFakturiert_ASFINAG()
            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
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        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 Button4_Click_1(sender As Object, e As EventArgs) Handles Button4.Click
        initLieferant("IDS", sender)
    End Sub

    Private Sub Button9_Click(sender As Object, e As EventArgs) Handles Button9.Click
        initLieferant("MSE", sender)
    End Sub

    Private Function setFakturiert_ASFINAG() As Boolean
        'Abrechnungsdatum setzen

        If cbxASFINAGAbgerechnet.Checked = True Then
            cbxASFINAGAbgerechnet.Checked = False
        End If

        If MyDatagridview1.Rows.Count = 0 Then
            MsgBox("Keine Daten zum Abrechnen vorhanden!")
            Return False
        End If

        Dim f As New frmDatumsabfrage()
        f.ShowDialog()
        If f.DialogResult = DialogResult.OK Then
            datum = f.Datum
            SQL.doSQL("DELETE FROM tblAsfinagMaut", "FMZOLL")
            If SQL.doSQL("Update Abrechnungsdatum SET Abrechnungsdatum = '" & f.Datum.ToShortDateString & "'", "ASFINAG") Then
                If SQL.doSQL("UPDATE dbo.TTRBody SET Abrechnungsdatum = '" & f.Datum.ToShortDateString & "' WHERE (PKHistory = 0) AND (PKFileName LIKE N'" & checkifTestfiles() & ".%') AND (FileCreationDate <= '" & f.Datum.ToShortDateString & "') AND abrechnungsdatum IS NULL AND belegerstellungsdatum IS NULL", "ASFINAG") Then

                    Dim dt As DataTable = SQL.loadDgvBySql("Select dbo.TTRBody.OBUID, dbo.TTRBody.CardNumber, dbo.TTRBody.receiptNumber, dbo.TTRBody.VATAmount, dbo.TTRBody.amountInclVAT, dbo.TTRBody.DeliveryDate,dbo.TTRBody.abrechnungsdatum,dbo.TTRBody.belegerstellungsdatum, dbo.tblWarenarten.WarenartDE, dbo.CLFArchiv.vehicleLicensePlate, dbo.TTRBody.InfoField, dbo.TTRBody.ProductCode, dbo.TTRBody.Town, dbo.TTRBody.PKFileName 
                            From dbo.CLFArchiv 
                            RIGHT OUTER Join dbo.TTRBody ON dbo.CLFArchiv.OBUID = dbo.TTRBody.OBUID 
                            LEFT OUTER Join dbo.tblWarenarten ON dbo.TTRBody.ProductCode = dbo.tblWarenarten.ProductCode
                            Where (dbo.TTRBody.PKHistory = 0) And (dbo.TTRBody.PKFileName Like N'" & checkifTestfiles() & ".%') AND TTRBody.abrechnungsdatum = '" & f.Datum.ToShortDateString & "'
                            Order By dbo.TTRBody.CardNumber, dbo.TTRBody.FileCreationDate, dbo.TTRBody.PKHistory, dbo.TTRBody.PKFileName, dbo.TTRBody.PKLine", "ASFINAG")
                    If dt.Rows.Count = 0 Then
                        MsgBox("Es wurden keine Daten in tblAsfinagMaut geschrieben!")
                        Return False
                    End If
                    For Each row As DataRow In dt.Rows
                        Dim maut As New VERAG_PROG_ALLGEMEIN.cAsfinagMaut()
                        maut.cardnumber = row.Item("CardNumber")
                        maut.licenceplate = IIf(Not IsDBNull(row.Item("vehicleLicensePlate")), row.Item("vehicleLicensePlate"), row.Item("InfoField"))
                        maut.turnoverdate = row.Item("DeliveryDate")
                        maut.contractPartner = "ASFINAG " & IIf(Not IsDBNull(row.Item("WarenartDE")), row.Item("WarenartDE"), "Product Code " & row.Item("ProductCode"))
                        maut.netAmount = CDbl(row.Item("amountInclVAT")) - CDbl(row.Item("VATAmount"))
                        maut.VATamount = CDbl(row.Item("VATAmount"))
                        maut.totalAmount = CDbl(row.Item("amountInclVAT"))
                        maut.additionalData = row.Item("Town") 'wird nicht mehr verwendet????
                        maut.receiptnumber = row.Item("receiptNumber")
                        maut.receiptCreated = IIf(IsDBNull(row.Item("belegerstellungsdatum")), False, True)
                        maut.SAVE()
                    Next

                    Dim pruefSumTTR = SQL.getValueTxtBySql("select sum(checksumAmounntInclVAT) from [ASFINAG].[dbo].[TTRTrailer] where PKHistory = 0 and [TTRTrailer].PKFileName in (select distinct([TTRBody].PKFileName) as Test from [ASFINAG].[dbo].[TTRBody] where (TTRBody.PKHistory = 0) And (TTRBody.PKFileName Like N'" & checkifTestfiles() & ".%') AND TTRBody.abrechnungsdatum = '" & f.Datum.ToShortDateString & "')", "ASFINAG")
                    If pruefSumTTR IsNot Nothing AndAlso IsNumeric(pruefSumTTR) Then
                        txtTTRSum.Text = CDbl(pruefSumTTR).ToString("C2")
                        lblTTRSum.Visible = True
                        txtTTRSum.Visible = True
                        lblTTRSum.Text = "Prüfsumme TTR:"
                    Else
                        lblTTRSum.Visible = False
                        txtTTRSum.Visible = False
                    End If


                    MsgBox("Abrechnungsdatum gesetzt!")
                End If
            End If



                cbxASFINAGAbgerechnet.Checked = True
            'initDgv_ASFINAG(Not cbxASFINAGNichtAbgerechnet.Checked)
        End If


    End Function


    Private Sub Button10_Click(sender As Object, e As EventArgs) Handles bntDatumzuruecksetzen.Click
        If cbxASFINAGAbgerechnet.Checked = False Then
            cbxASFINAGAbgerechnet.Checked = True
        End If

        If MyDatagridview1.Rows.Count = 0 Then
            MsgBox("keine Daten zum zurücksetzen vorhanden!")
            Exit Sub
        End If

        Dim datumDel = CDate(SQL.getValueTxtBySql("Select Abrechnungsdatum FROM Abrechnungsdatum", "ASFINAG"))

        If MsgBox("Möchten Sie das Abrechnungsdatum vom " & datumDel.ToShortDateString & " zurücksetzen?" & vbNewLine & "Nur für Transaktionen möglich, zu denen es noch keine Rechnung erstellt wurde!", vbYesNoCancel) = MsgBoxResult.Yes Then
            If SQL.doSQL("UPDATE dbo.TTRBody Set Abrechnungsdatum = NULL WHERE Abrechnungsdatum = '" & datumDel & "' AND (PKHistory = 0) AND (PKFileName LIKE '%" & checkifTestfiles() & ".%') AND belegerstellungsdatum IS NULL", "ASFINAG") Then
                If SQL.doSQL("DELETE FROM tblAsfinagMaut", "FMZOLL") Then
                    MsgBox("Abrechnungsdatum zurückgesetzt!")
                End If
                cbxASFINAGAbgerechnet.Checked = False

                'initDgv_ASFINAG(cbxASFINAGNichtAbgerechnet.Checked)
            End If
        End If


    End Sub

    Private Function checkifTestfiles() As String

        If cbxTestdaten.Checked Then

            Return "TEPVGTTR"
        Else
            Return "LEPVGTTR"

        End If

    End Function

    Private Sub cbxASFINAGabgerechnet_CheckedChanged(sender As Object, e As EventArgs) Handles cbxASFINAGAbgerechnet.CheckedChanged
        If Me.LIEFERANT = "ASFINAG" Then
            If Not cbxASFINAGAbgerechnet.Checked Then cbxBelegeerstellt.Checked = False
            initDgv_ASFINAG(cbxASFINAGAbgerechnet.Checked, cbxBelegeerstellt.Checked)
        End If
    End Sub

    Private Sub bntDatumsetzen_Click(sender As Object, e As EventArgs) Handles bntDatumsetzen.Click
        setFakturiert_ASFINAG()
    End Sub

    Private Sub cbxBelegeerstellt_CheckedChanged(sender As Object, e As EventArgs) Handles cbxBelegeerstellt.CheckedChanged
        If Me.LIEFERANT = "ASFINAG" Then


            If cbxBelegeerstellt.Checked Then
                Panel2.Enabled = False
                bntDatumsetzen.Enabled = False
                bntDatumzuruecksetzen.Enabled = False
            Else
                Panel2.Enabled = True
                bntDatumsetzen.Enabled = True
                bntDatumzuruecksetzen.Enabled = True
            End If

        End If
    End Sub

    Private Sub PictureBox5_Click(sender As Object, e As EventArgs) Handles PictureBox5.Click
        Dim webAddress As String = "https://wiki.verag.ag/de/software/sdl/funktionen"
        Process.Start(webAddress)
    End Sub


End Class
