Imports System.Data.SqlClient
Imports System.Reflection
Imports java.lang
Imports TELOTEC_Worker
Imports VERAG_PROG_ALLGEMEIN

Public Class cImporter_DHFToVERAG

    Private SQL As New VERAG_PROG_ALLGEMEIN.SQL
    Private Const EZOLL_DB As String = "EZOLL"


    ' =====================================================================
    ' MAIN ENTRY
    ' =====================================================================
    Public Function ImportEZOLLByLRN(CRN As String, EZOLL_DB As String, Optional overwrite As Boolean = True, Optional freshInsert As Boolean = False) As Boolean
        Try
            If String.IsNullOrWhiteSpace(CRN) Then Return False

            ' ---------------------------------------------------------------
            ' BASIS-REFERENZ (zsAnmRefs)
            ' ---------------------------------------------------------------
            Dim dtRefs As DataTable =
                SQL.loadDgvBySql(
                    "SELECT TOP 1 * FROM zsAnmRefs WHERE   CRN='" & CRN & "' ORDER BY GeaendertAm DESC",
                    EZOLL_DB)

            If dtRefs Is Nothing OrElse dtRefs.Rows.Count = 0 Then Return False
            Dim rRef = dtRefs.Rows(0)

            Dim LizenzNr = rRef("LizenzNr")
            Dim OperatorID = rRef("OperatorID")
            Dim VorgangID = rRef("VorgangID")
            Dim AnmID = rRef("AnmID")
            '  MsgBox(AnmID)
            Dim LRN As String = ToStringSafe(rRef("LRN"))


            ' ---------------------------------------------------------------
            ' DUPLIKAT
            ' ---------------------------------------------------------------
            If Not overwrite AndAlso ExistsInVERAG(CRN) Then Return False

            ' ---------------------------------------------------------------
            ' HEADER (zsAnmHea)
            ' ---------------------------------------------------------------
            Dim dtHea = SQL.loadDgvBySql(
                $"SELECT * FROM zsAnmHea WHERE LizenzNr='{LizenzNr}' AND OperatorID={OperatorID} AND VorgangID='{VorgangID}' AND AnmID={AnmID}",
                EZOLL_DB)

            If dtHea.Rows.Count = 0 Then Return False
            Dim h = dtHea.Rows(0)

            Dim ZA As cVERAG_CustomsDeclarations = cVERAG_CustomsDeclarations.loadByMRN(CRN, False)

            ZA.za_System = "DHF"
            If EZOLL_DB = "EZOLL_UNISPED" Then ZA.za_System = "DHF_UNISPED"
            ZA.za_CustomsSystem = "ACCS"
            ZA.za_CustomsSystemCountry = "AT"
            ZA.za_REGIME = "IMPORT"
            ZA.za_IsExternalSystem = False
            ZA.za_IsFinalDeclaration = True

            ZA.za_MRN = CRN
            ZA.za_LRN = LRN

            getFirmaNLFrom_OP(OperatorID, ZA.za_Firma, ZA.za_Niederlassung)

            VERAG_PROG_ALLGEMEIN.cProgramFunctions.tryGetFirmaNiederlassung(ZA.za_Firma, ZA.za_Niederlassung, "", LRN)
            VERAG_PROG_ALLGEMEIN.cProgramFunctions.tryGetAvisoId_SndId_ByLRN(ZA.za_LRN, ZA.za_AvisoId, ZA.za_SendungsId)


            ZA.za_DeclarationDate = ToNullableDate(h("DecDT"))
            ZA.za_AcceptanceDate = ToNullableDate(h("AccDT"))
            ZA.za_ReleaseDate = ToNullableDate(h("DecDT"))

            ZA.za_TotGrossMass = ToNullableDecimal(h("TotGross"))


            ''ZA.za_CountryDispatch = ToStringSafe(h("Locs_Disp"))
            '    ZA.za_CountryDestination = ToStringSafe(h("Locs_Dest"))
            ZA.za_CountryImport = "AT"

            '  ZA.za_MainProcedure = Left(ToStringSafe(h("ProcCd")), 2)


            '   ZA.za_WarehouseCode = ToStringSafe(h("Locs_GdsLocCd"))

            ' ---------------------------------------------------------------
            ' TRANSPORT (zsAnmTransp)
            ' ---------------------------------------------------------------
            Dim dtTransp = SQL.loadDgvBySql(
                $"SELECT * FROM zsAnmTransp WHERE LizenzNr='{LizenzNr}' AND OperatorID={OperatorID} AND VorgangID='{VorgangID}' AND AnmID={AnmID}",
                EZOLL_DB)

            If dtTransp.Rows.Count > 0 Then
                ZA.za_MeansOfTransport_Vehicle = ToStringSafe(dtTransp.Rows(0)("DepIdnt"))
                ZA.za_TransportModeInland = ToStringSafe(dtTransp.Rows(0)("InMo"))
                ZA.za_TransportModeBorder = ToStringSafe(dtTransp.Rows(0)("BordMo"))
            End If

            ' ---------------------------------------------------------------
            ' TRANSPORT (zsAnmTransp)
            ' ---------------------------------------------------------------
            Dim dtAnmRepresent = SQL.loadDgvBySql(
                $"SELECT * FROM [zsAnmRepresent] WHERE LizenzNr='{LizenzNr}' AND OperatorID={OperatorID} AND VorgangID='{VorgangID}' AND AnmID={AnmID}",
                EZOLL_DB)

            If dtAnmRepresent.Rows.Count > 0 Then
                ZA.za_Sachbearbeiter = ToStringSafe(dtAnmRepresent.Rows(0)("Na"))
            End If

            ' ---------------------------------------------------------------
            ' VALUE DATA (zsAnmValData)
            ' ---------------------------------------------------------------
            Dim dtVal = SQL.loadDgvBySql(
                $"SELECT * FROM zsAnmValData WHERE LizenzNr='{LizenzNr}' AND OperatorID={OperatorID} AND VorgangID='{VorgangID}' AND AnmID={AnmID}",
                EZOLL_DB)

            If dtVal.Rows.Count > 0 Then
                ZA.za_InvoiceAmount = ToNullableDecimal(dtVal.Rows(0)("InvVal"))
                ZA.za_InvoiceCurrency = ToStringSafe(dtVal.Rows(0)("InvCurr"))
            End If

            ' ---------------------------------------------------------------
            ' PARTIES
            ' ---------------------------------------------------------------
            AddPartyFromEZOLL(ZA, "IMPORTER", "zsAnmConeeTra", LizenzNr, OperatorID, VorgangID, AnmID)
            AddPartyFromEZOLL(ZA, "EXPORTER", "zsAnmConorTra", LizenzNr, OperatorID, VorgangID, AnmID)
            AddPartyFromEZOLL(ZA, "DECLARANT", "zsAnmDeclarant", LizenzNr, OperatorID, VorgangID, AnmID)
            LoadPartiesFromEZOLL(ZA, LizenzNr, OperatorID, VorgangID, AnmID)

            ' ---------------------------------------------------------------
            ' DOCUMENTS
            ' ---------------------------------------------------------------
            LoadEZOLL_HeaderDocuments_FromZsAnmDocument(ZA, LizenzNr, OperatorID, VorgangID, AnmID)

            ' ---------------------------------------------------------------
            ' DUTIES
            ' ---------------------------------------------------------------
            LoadEZOLL_Duties(ZA, LizenzNr, OperatorID, VorgangID, AnmID)


            ' ---------------------------------------------------------------
            ' POSITIONEN (zsAnmGdsitem)
            ' ---------------------------------------------------------------
            Dim dtItems = SQL.loadDgvBySql(
                $"SELECT * FROM zsAnmGdsitem WHERE LizenzNr='{LizenzNr}' AND OperatorID={OperatorID} AND VorgangID='{VorgangID}' AND AnmID={AnmID} ORDER BY GdsItemID",
                EZOLL_DB)

            For Each r In dtItems.Rows
                Dim it As New cVERAG_CustomsDeclarations_Item

                it.zaItem_PosNo = r("GdsItemID")
                it.zaItem_HSCode = ToStringSafe(r("ComCd"))
                it.zaItem_Description = ToStringSafe(r("GdsDes"))
                it.zaItem_OriginCountry = ToStringSafe(r("Orig"))
                it.zaItem_NetMass = ToNullableDecimal(r("Net"))
                it.zaItem_InvoiceValueEUR = ToNullableDecimal(r("ItVal"))
                it.zaItem_StatisticalValueEUR = ToNullableDecimal(r("StatVal"))

                LoadEZOLL_HSAddCodes(it, LizenzNr, OperatorID, VorgangID, AnmID, r("GdsItemID"))
                LoadEZOLL_ItemDocuments(it, LizenzNr, OperatorID, VorgangID, AnmID)

                it.zaItem_MainProcedure = ToStringSafe(r("ProcCd"))
                it.zaItem_AdditionalProc = ToStringSafe(r("ProcAddCd"))
                it.zaItem_PreferenceCode = ToStringSafe(r("Pref"))
                it.zaItem_QuotaNo = ToStringSafe(r("Quota"))
                ' -------------------------------
                ' POSITIONS-DOKUMENTE
                ' -------------------------------
                Dim dtDocs = SQL.loadDgvBySql(
                    $"SELECT * FROM zsAnmGdsItemDocCerts WHERE LizenzNr='{LizenzNr}' AND OperatorID={OperatorID} AND VorgangID='{VorgangID}' AND AnmID={AnmID} AND GdsItemID={r("GdsItemID")}",
                    EZOLL_DB)

                'For Each d In dtDocs.Rows
                '    Dim doc As New cVERAG_CustomsDeclarations_Document With {
                '        .zaDoc_Code = ToStringSafe(d("DocCd")),
                '        .zaDoc_Reference = ToStringSafe(d("DRef")),
                '        .zaDoc_Date = ToNullableDate(d("IssD"))
                '    }
                '    it.Documents.Add(doc)
                'Next

                ZA.Items.Add(it)
            Next

            ' ================================================================
            'CBAM WARNING
            ' ================================================================
            If freshInsert Then
                ZA.checkfreshCBAMWarning()
            End If

            ' SAVE
            Dim saved = ZA.SAVE()
            ' ======KAFKA==========================================================
            If freshInsert Then cDakosyEZA_Greenpulse.INSERT_KAFKA(ZA)
            ' ================================================================
            Return saved

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

    Private Sub LoadEZOLL_Duties(ByRef ZA As cVERAG_CustomsDeclarations,
                             LizenzNr As String,
                             OperatorID As Integer,
                             VorgangID As String,
                             AnmID As Integer)

        Dim sql As String =
            " SELECT d.GdsItemID,
                     dc.Ty,
                     dc.Amnt,
                     dc.Curr,
                     dc.Base,
                     dc.RateUsed,
                     h.DefPayRef
              FROM zzAktivitaet a
              INNER JOIN ztIMsgGdsItem i
                 ON a.LizenzNr=i.LizenzNr AND a.OperatorID=i.OperatorID AND a.IMsgID=i.IMsgID
              INNER JOIN ztIMsgGdsItemDutyCalc dc
                 ON i.LizenzNr=dc.LizenzNr AND i.OperatorID=dc.OperatorID
                AND i.IMsgID=dc.IMsgID AND i.GdsItemID=dc.GdsItemID
              INNER JOIN zsAnmGdsItem d
                 ON a.LizenzNr=d.LizenzNr AND a.OperatorID=d.OperatorID
                AND a.VorgangID=d.VorgangID AND a.AnmID=d.AnmID
                AND i.ItNr=d.ItNr
              INNER JOIN zsAnmHea h
                 ON d.LizenzNr=h.LizenzNr AND d.OperatorID=h.OperatorID
                AND d.VorgangID=h.VorgangID AND d.AnmID=h.AnmID
              WHERE a.MsgTyp='EZ922'
                AND NOT EXISTS (
                    SELECT 1 FROM zzAktivitaet b
                    WHERE b.MsgTyp='EZ922'
                      AND a.LizenzNr=b.LizenzNr
                      AND a.OperatorID=b.OperatorID
                      AND a.VorgangID=b.VorgangID
                      AND a.AnmID=b.AnmID
                      AND a.AktivitaetID < b.AktivitaetID
                )
                AND dc.Amnt IS NOT NULL
                AND d.LizenzNr=@liz
                AND d.OperatorID=@op
                AND d.VorgangID=@vg
                AND d.AnmID=@anm"

        Dim p As New List(Of SQLVariable) From {
        New SQLVariable("liz", LizenzNr),
        New SQLVariable("op", OperatorID),
        New SQLVariable("vg", VorgangID),
        New SQLVariable("anm", AnmID)
    }

        Dim dt = (New VERAG_PROG_ALLGEMEIN.SQL).loadDgvBySql_Param(sql, "EZOLL", , p)
        If dt Is Nothing OrElse dt.Rows.Count = 0 Then Exit Sub

        For Each r As DataRow In dt.Rows

            Dim duty As New cVERAG_CustomsDeclarations_Duty

            duty.zaDuty_DutyType = ToStringSafe(r("Ty"))
            duty.zaDuty_AmountEUR = ToNullableDecimal(r("Amnt"))
            duty.zaDuty_Currency = If(ToStringSafe(r("Curr")) = "", "EUR", ToStringSafe(r("Curr")))

            '    duty.zaDuty_BaseAmount = ToNullableDecimal(r("Base"))
            '   duty.zaDuty_Rate = ToNullableDecimal(r("RateUsed"))

            duty.zaDuty_AccountNo = ToStringSafe(r("DefPayRef"))

            ZA.Duties.Add(duty)

        Next

    End Sub


    Private Sub LoadEZOLL_ItemDocuments(ByRef IT As cVERAG_CustomsDeclarations_Item,
                                      LizenzNr As String,
                                      OperatorID As Integer,
                                      VorgangID As String,
                                      AnmID As Integer)

        Dim sql As String =
        "SELECT * FROM zsAnmGdsItemDocCerts " &
        "WHERE LizenzNr=@liz " &
        "  AND OperatorID=@op " &
        "  AND VorgangID=@vg " &
        "  AND AnmID=@anm " &
        "ORDER BY DocCertsID"

        Dim p As New List(Of SQLVariable) From {
        New SQLVariable("liz", LizenzNr),
        New SQLVariable("op", OperatorID),
        New SQLVariable("vg", VorgangID),
        New SQLVariable("anm", AnmID)
    }

        Dim dt = (New VERAG_PROG_ALLGEMEIN.SQL).loadDgvBySql_Param(sql, EZOLL_DB, , p)
        If dt Is Nothing OrElse dt.Rows.Count = 0 Then Exit Sub

        For Each r As DataRow In dt.Rows

            Dim doc As New cVERAG_CustomsDeclarations_Document

            ' ------------------------------------------------------------
            ' Kerndaten
            ' ------------------------------------------------------------
            doc.zaDoc_Code = ToStringSafe(r("DocCd"))
            doc.zaDoc_Reference = ToStringSafe(r("DRef"))
            doc.zaDoc_Date = ToStringSafe(r("IssD"))

            doc.zaDoc_Presentation = ToStringSafe(r("Avail"))
            doc.zaDoc_Description = ToStringSafe(r("DTy"))

            ' ------------------------------------------------------------
            ' Zusatzinformationen (optional, aber sauber)
            ' ------------------------------------------------------------
            'doc.zaDoc_DepreciationAmount = ToNullableDecimal(r("Quant"))
            doc.zaDoc_DepreciationUnitmeasurement = ToStringSafe(r("Unit"))
            doc.zaDoc_DepreciationUnitmeasurementQualifier = ToStringSafe(r("WOUnit"))

            IT.Documents.Add(doc)
        Next

    End Sub

    ' =====================================================================
    ' HELPER
    ' ===================================================================== 
    Private Sub AddPartyFromEZOLL(ByRef ZA As cVERAG_CustomsDeclarations,
                                 role As String,
                                 tableName As String,
                                 LizenzNr As String, OperatorID As String, VorgangID As String, AnmID As String)

        Dim dt = SQL.loadDgvBySql(
            $"SELECT * FROM {tableName} WHERE LizenzNr='{LizenzNr}' AND OperatorID={OperatorID} AND VorgangID='{VorgangID}' AND AnmID={AnmID}",
            EZOLL_DB)

        If dt.Rows.Count = 0 Then Exit Sub
        Dim r = dt.Rows(0)


        Dim p As New cVERAG_CustomsDeclarations_Parties With {
            .zaParty_Role = role,
            .zaParty_Name = ToStringSafe(r("Na")),
            .zaParty_Street = ToStringSafe(r("Strt")),
            .zaParty_PostalCode = ToStringSafe(r("Pst")),
            .zaParty_City = ToStringSafe(r("Cty")),
            .zaParty_Country = ToStringSafe(r("Ctry")),
            .zaParty_EORI = ToStringSafe(r("TIN"))
        }
        If role = "DECLARANT" Then
            ZA.za_RepresentationCode = ToStringSafe(r("DecRep"))
        End If

        If role = "IMPORTER" Or role = "CONSINEE" Then
            ZA.za_CountryDestination = p.zaParty_Country
        End If

        If role = "EXPORTER" Or role = "CONSINOR" Then
            ZA.za_CountryDispatch = p.zaParty_Country
        End If

        ZA.Parties.Add(p)
    End Sub
    Private Sub getFirmaNLFrom_OP(OperatorID As String, ByRef Firma As String, ByRef NL As String)

        Select Case OperatorID
            Case 1 : Firma = "VERAG" : NL = "SUB"
            Case 2 : Firma = "VERAG" : NL = "SBG"
            Case 3 : Firma = "VERAG" : NL = "NKD"
            Case 4 : Firma = "VERAG" : NL = "SUB"
            Case 5 : Firma = "ATILLA" : NL = "SUB"
            Case 6 : Firma = "VERAG" : NL = "SUB"
            Case 8 : Firma = "DURMAZ" : NL = "SUB"
        End Select
    End Sub

    Private Sub LoadEZOLL_HSAddCodes(ByRef item As cVERAG_CustomsDeclarations_Item,
                                LizenzNr As String,
                                OperatorID As Integer,
                                VorgangID As String,
                                AnmID As Integer,
                                GdsItemID As Integer)

        Dim sql As String =
        "SELECT AddCd " &
        "FROM zsAnmGdsItemComCdAdd " &
        "WHERE LizenzNr=@liz " &
        "  AND OperatorID=@op " &
        "  AND VorgangID=@vg " &
        "  AND AnmID=@anm " &
        "  AND GdsItemID=@gid " &
        "ORDER BY sequenceNumber"

        Dim p As New List(Of SQLVariable) From {
        New SQLVariable("liz", LizenzNr),
        New SQLVariable("op", OperatorID),
        New SQLVariable("vg", VorgangID),
        New SQLVariable("anm", AnmID),
        New SQLVariable("gid", GdsItemID)
    }

        Dim dt = (New VERAG_PROG_ALLGEMEIN.SQL).loadDgvBySql_Param(sql, EZOLL_DB, , p)
        If dt Is Nothing OrElse dt.Rows.Count = 0 Then Exit Sub

        Dim idx As Integer = 1

        For Each r As DataRow In dt.Rows
            If idx > 10 Then Exit For   ' VERAG-Modell: max. 10 Zusatzcodes

            Dim code As String = ToStringSafe(r("AddCd"))
            If String.IsNullOrWhiteSpace(code) Then Continue For

            Select Case idx
                Case 1 : item.zaItem_HSAddCodes1 = code
                Case 2 : item.zaItem_HSAddCodes2 = code
                Case 3 : item.zaItem_HSAddCodes3 = code
                Case 4 : item.zaItem_HSAddCodes4 = code
                Case 5 : item.zaItem_HSAddCodes5 = code
                Case 6 : item.zaItem_HSAddCodes6 = code
                Case 7 : item.zaItem_HSAddCodes7 = code
                Case 8 : item.zaItem_HSAddCodes8 = code
                Case 9 : item.zaItem_HSAddCodes9 = code
                Case 10 : item.zaItem_HSAddCodes10 = code
            End Select

            idx += 1
        Next

    End Sub

    Private Sub LoadEZOLL_HeaderDocuments_FromZsAnmDocument(
       ByRef ZA As cVERAG_CustomsDeclarations,
        LizenzNr As String,
        OperatorID As Integer,
        VorgangID As String,
        AnmID As Integer)

        Dim sql As String =
        "SELECT * FROM zsAnmDocument " &
        "WHERE LizenzNr=@liz " &
        "  AND OperatorID=@op " &
        "  AND VorgangID=@vg " &
        "  AND AnmID=@anm " &
        "  AND ISNULL(KzDeleted,0)=0 " &
        "ORDER BY sequenceNumber"

        Dim p As New List(Of SQLVariable) From {
        New SQLVariable("liz", LizenzNr),
        New SQLVariable("op", OperatorID),
        New SQLVariable("vg", VorgangID),
        New SQLVariable("anm", AnmID)
    }

        Dim dt = (New VERAG_PROG_ALLGEMEIN.SQL).loadDgvBySql_Param(sql, EZOLL_DB, , p)
        If dt Is Nothing OrElse dt.Rows.Count = 0 Then Exit Sub

        For Each r As DataRow In dt.Rows

            Dim doc As New cVERAG_CustomsDeclarations_Document

            ' ------------------------------------------------------------
            ' Kerndaten
            ' ------------------------------------------------------------
            doc.zaDoc_Code = ToStringSafe(r("type"))


            doc.zaDoc_Reference = ToStringSafe(r("referenceNumber"))
            If r("validityDate") IsNot Nothing AndAlso r("validityDate") IsNot DBNull.Value Then
                doc.zaDoc_Date = ToNullableDate(r("validityDate"))
            End If
            'doc.zaDoc_Section = ToStringSafe(r("DocumentTypID"))
            doc.zaDoc_Description = ToStringSafe(r("text"))

            ' ------------------------------------------------------------
            ' Zusatzinformationen (optional, aber strukturell korrekt)
            ' ------------------------------------------------------------
            doc.zaDoc_Presentation = ToStringSafe(r("typeOfPackages"))

            If r("amount") IsNot Nothing AndAlso r("amount") IsNot DBNull.Value Then
                doc.zaDoc_DepreciationAmount = ToNullableDecimal(r("amount"))
            End If
            doc.zaDoc_DepreciationUnitmeasurement =
            ToStringSafe(r("measurementUnitAndQualifier"))

            ' ------------------------------------------------------------
            ' Freitext / Hinweise
            ' ------------------------------------------------------------
            If Not IsDBNull(r("text")) AndAlso ToStringSafe(r("text")) <> "" Then
                doc.zaDoc_Reference =
                (doc.zaDoc_Reference & " " & ToStringSafe(r("text"))).Trim()
            End If

            ZA.Documents.Add(doc)
        Next

    End Sub

    Private Sub LoadPartiesFromEZOLL(ByRef ZA As cVERAG_CustomsDeclarations,
                                 LizenzNr As String,
                                 OperatorID As Integer,
                                 VorgangID As String,
                                 AnmID As Integer)

        Dim sqlAdr As String =
        "SELECT * FROM  zsAnmAdr " &
        "WHERE LizenzNr=@liz AND OperatorID=@op AND VorgangID=@vg AND AnmID=@anm"

        Dim p As New List(Of SQLVariable) From {
        New SQLVariable("liz", LizenzNr),
        New SQLVariable("op", OperatorID),
        New SQLVariable("vg", VorgangID),
        New SQLVariable("anm", AnmID)
    }

        Dim dtAdr = SQL.loadDgvBySql_Param(sqlAdr, EZOLL_DB, , p)
        If dtAdr Is Nothing OrElse dtAdr.Rows.Count = 0 Then Exit Sub

        For Each r As DataRow In dtAdr.Rows

            Dim party As New cVERAG_CustomsDeclarations_Parties

            party.zaParty_Role = ToStringSafe(r("AdressTypID"))

            party.zaParty_EORI = ToStringSafe(r("identificationNumber"))
            party.zaParty_Name = ToStringSafe(r("name"))
            party.zaParty_Street = ToStringSafe(r("streetAndNumber"))
            party.zaParty_PostalCode = ToStringSafe(r("postcode"))
            party.zaParty_City = ToStringSafe(r("city"))
            party.zaParty_Country = ToStringSafe(r("country"))

            party.zaParty_ContactName = ToStringSafe(r("Contactname"))
            party.zaParty_Phone = ToStringSafe(r("ContactphoneNumber"))
            party.zaParty_Email = ToStringSafe(r("ContacteMailAdress"))

            ZA.Parties.Add(party)
        Next

    End Sub
    Private Function ExistsInVERAG(CRN As String) As Boolean
        Dim sql =
            "SELECT TOP 1 1 FROM tblVERAG_CustomsDeclarations " &
            "WHERE za_System LIKE 'DHF%' AND (za_MRN=@CRN )"

        Dim p As New List(Of SQLVariable) From {
            New SQLVariable("CRN", CRN)
        }

        Dim dt = New SQL().loadDgvBySql_Param(sql, "VERAG", , p)
        Return dt IsNot Nothing AndAlso dt.Rows.Count > 0
    End Function

    ' =====================================================================
    ' PARTY HELPER
    ' =====================================================================
    Private Sub AddParty(ByRef za As cVERAG_CustomsDeclarations,
                         eori As String,
                         role As String,
                         name As Object,
                         street As Object,
                         plz As Object,
                         city As Object,
                         country As Object,
                         uid As Object)

        If String.IsNullOrWhiteSpace(ToStringSafe(name)) Then Exit Sub

        Dim p As New cVERAG_CustomsDeclarations_Parties With {
            .zaParty_EORI = eori,
            .zaParty_Role = role,
            .zaParty_Name = ToStringSafe(name),
            .zaParty_Street = ToStringSafe(street),
            .zaParty_PostalCode = ToStringSafe(plz),
            .zaParty_City = ToStringSafe(city),
            .zaParty_Country = ToStringSafe(country),
            .zaParty_VATNumber = ToStringSafe(uid)
        }

        za.Parties.Add(p)
    End Sub













    ' =========================================================================
    '  Small helpers (falls du sie schon hast, kannst du diese entfernen)
    ' =========================================================================
    Private Function ToStringSafe(v As Object) As String
        If v Is Nothing Then Return Nothing
        If v Is DBNull.Value Then Return Nothing
        Dim s As String = TryCast(v, String)
        If s IsNot Nothing Then Return s
        Return Convert.ToString(v, Globalization.CultureInfo.InvariantCulture)
    End Function

    Private Function ToInt(v As Object) As Integer
        If v Is Nothing Then Return 0
        If v Is DBNull.Value Then Return 0
        Dim s = Convert.ToString(v, Globalization.CultureInfo.InvariantCulture)
        Dim i As Integer
        If Integer.TryParse(s, Globalization.NumberStyles.Any, Globalization.CultureInfo.InvariantCulture, i) Then Return i
        Return 0
    End Function

    Private Function ToNullableDecimal(v As Object) As Decimal?
        If v Is Nothing Then Return Nothing
        If v Is DBNull.Value Then Return Nothing
        Dim s = Convert.ToString(v, Globalization.CultureInfo.InvariantCulture)
        Dim d As Decimal
        If Decimal.TryParse(s, Globalization.NumberStyles.Any, Globalization.CultureInfo.InvariantCulture, d) Then Return d
        Return Nothing
    End Function

    Private Function ToNullableDate(v As Object) As Date?
        If v Is Nothing Then Return Nothing
        If v Is DBNull.Value Then Return Nothing
        If TypeOf v Is Date Then Return CType(v, Date)

        Dim s = Convert.ToString(v, Globalization.CultureInfo.InvariantCulture)
        Dim dt As Date
        If Date.TryParse(s, Globalization.CultureInfo.InvariantCulture, Globalization.DateTimeStyles.None, dt) Then Return dt
        Return Nothing
    End Function

    Private Function ToNullableBool(v As Object) As Boolean?
        If v Is Nothing Then Return Nothing
        If v Is DBNull.Value Then Return Nothing
        If TypeOf v Is Boolean Then Return CType(v, Boolean)

        Dim s = Convert.ToString(v, Globalization.CultureInfo.InvariantCulture).Trim().ToLowerInvariant()
        If s = "J" OrElse s = "1" OrElse s = "true" OrElse s = "y" OrElse s = "yes" Then Return True
        If s = "N" OrElse s = "0" OrElse s = "false" OrElse s = "n" OrElse s = "no" Then Return False
        Return Nothing
    End Function
End Class