Files
SDL/VERAG_PROG_ALLGEMEIN/VERAG_Zollanmeldung/cVERAG_CustomsDeclarations.vb
2026-10-22 14:51:49 +02:00

2032 lines
105 KiB
VB.net
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

Imports System.Data.SqlClient
Imports System.Reflection
Imports System.Runtime.InteropServices.ComTypes
Imports System.Windows.Forms
Imports com.sun.tools.javac.util
Imports java.lang.ProcessBuilder
Imports Org.BouncyCastle.Crypto.Agreement
Imports sun.util.resources.cldr.aa
Imports VERAG_PROG_ALLGEMEIN.TESTJSON
' ==========================================================================
' MASTER CLASS
' Customs Declaration (Header + Items + Duties + Documents)
' ==========================================================================
Public Class cVERAG_CustomsDeclarations
Public Property za_Id As Integer
Public Property za_System As String ' z.B. "DAKOSY"
Public Property za_CustomsSystem As String ' z.B. "ATLAS"
Public Property za_CustomsSystemCountry As String ' z.B. "DE"
Public Property za_IsExternalSystem As Boolean = False
Public Property za_IsFinalDeclaration As Boolean = False
Public Property za_UCR As String
Public Property za_Mandant_ID As String
Public Property za_Bereich_ID As String
Public Property za_Firma As String
Public Property za_Niederlassung As String
Public Property za_MRN As String
Public Property za_LRN As String
Public Property za_DeclarationNo As String
Public Property za_ReferenceCustomer As String
Public Property za_REGIME As String ' IMPORT, EXPORT, ...
Public Property za_RegistrationType As String
Public Property za_MainProcedure As String
Public Property za_AdditionalProcedure As String
Public Property za_DeclarationDate As Date?
Public Property za_ReleaseDate As Date?
Public Property za_AcceptanceDate As Date?
Public Property za_CustomsOffice As String
Public Property za_EntryCustomsOffice As String
Public Property za_RepresentationCode As String
Public Property za_TransportModeInland As String
Public Property za_TransportModeBorder As String
Public Property za_MeansOfTransport_Vehicle As String
Public Property za_MeansOfTransport_Type As String
Public Property za_MeansOfTransport_Nationality As String
Public Property za_ContainerNr1 As String
Public Property za_ContainerNr2 As String
Public Property za_ContainerNr3 As String
Public Property za_ContainerNr4 As String
Public Property za_ContainerNr5 As String
Public Property za_ContainerNr6 As String
Public Property za_ContainerNr7 As String
Public Property za_ContainerNr8 As String
Public Property za_ContainerNr9 As String
Public Property za_CountryDispatch As String
Public Property za_CountryDestination As String
Public Property za_CountryDestinationState As String
Public Property za_CountryImport As String
Public Property za_WarehouseCode As String
Public Property za_Incoterms As String
Public Property za_IncotermsPlace As String
Public Property za_InvoiceAmount As Decimal?
Public Property za_InvoiceCurrency As String
Public Property za_FiscalRepFlag As Boolean?
Public Property za_TaxDeduction As Boolean?
Public Property za_ApplicantTaxOffice As String
Public Property za_ApplicantVATNo As String
Public Property za_DV1Flag As Boolean?
Public Property za_PrevDocument_Type As String
Public Property za_PrevDocument_No As String
Public Property za_AvisoId As Integer?
Public Property za_SendungsId As Integer?
Public Property za_Remarks As String
Public Property za_Sachbearbeiter As String
Public Property za_SachbearbeiterId As String
Public Property za_TotGrossMass As Decimal?
' EXPORT: optionale Kopfdaten
Public Property za_ExportDeclarationType As String
Public Property za_ExportSecurity As String
Public Property za_ExportPartyConstellation As String
Public Property za_ExportStatus As String
Public Property za_ExportExitDate As Date?
Public Property za_ExportExitOfficeDeclared As String
Public Property za_ExportExitOfficeActual As String
Public Property za_ExportPresentationOffice As String
Public Property za_ExportRegistrationExternal As String
Public Property za_ExportNatureOfTransaction As String
Public Property za_ExportLocationType As String
Public Property za_ExportLocationQualifier As String
Public Property za_ExportLocationIdentifier As String
Public Property za_ExportLocationAuthorisation As String
Public Property za_ExportLocationStreet As String
Public Property za_ExportLocationPostcode As String
Public Property za_ExportLocationCity As String
Public Property za_ExportLocationCountry As String
Public Property za_ExportPresentationStart As Date?
Public Property za_ExportLoadingEnd As Date?
Public Property za_ExportContainerIndicator As String
Public Property za_ExportBorderVehicle As String
Public Property za_ExportBorderVehicleType As String
Public Property za_ExportBorderVehicleNationality As String
Public Property za_ExportExitConfirmationDate As Date?
' NCTS: optionale Kopfdaten
Public Property za_TransitType As String
Public Property za_TransitStatus As String
Public Property za_TransitDepartureOffice As String
Public Property za_TransitDestinationOffice As String
Public Property za_TransitLimitDate As Date?
Public Property za_TransitArrivalDate As Date?
Public Property za_TransitCompletionDate As Date?
Public Property za_TransitReducedDataset As Boolean?
Public Property za_TransitSecurityCode As String
Public Property za_TransitLocationType As String
Public Property za_TransitLocationQualifier As String
Public Property za_TransitLocationIdentifier As String
Public Property za_TransitSealNumbers As String
Public Property za_TransitContainerIndicator As Boolean?
Public Property za_TransitBorderVehicle As String
Public Property za_TransitBorderVehicleType As String
Public Property za_TransitBorderVehicleNationality As String
Public Property HouseConsignments As New List(Of cVERAG_CustomsDeclarations_HouseConsignment)
Public Property TransitGuarantees As New List(Of cVERAG_CustomsDeclarations_TransitGuarantee)
Public Property TransitOffices As New List(Of cVERAG_CustomsDeclarations_TransitOffice)
Public Property Parties As New List(Of cVERAG_CustomsDeclarations_Parties)
Public Property Items As New List(Of cVERAG_CustomsDeclarations_Item)
Public Property Duties As New List(Of cVERAG_CustomsDeclarations_Duty)
Public Property Documents As New List(Of cVERAG_CustomsDeclarations_Document)
Public Property hasEntry As Boolean = False
Public Shared IMPORTER_ROLES As String() = {"CN", "IM", "IMP", "IMPORTER", "CONSIGNEE"}
Public Shared EXPORTER_ROLES As String() = {"CZ", "EX", "EXP", "EXPORTER", "CONSIGNOR"}
Public Shared DECLARANT_ROLES As String() = {"CB", "DT", "ANM", "DEC", "VERTRETER", "DEKLARANT", "DECLARANT"}
Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
Public Function getParameterList() As List(Of SQLVariable)
Return New List(Of SQLVariable) From {
New SQLVariable("za_Id", za_Id,, True),
New SQLVariable("za_System", za_System),
New SQLVariable("za_CustomsSystem", za_CustomsSystem),
New SQLVariable("za_CustomsSystemCountry", za_CustomsSystemCountry),
New SQLVariable("za_IsExternalSystem", za_IsExternalSystem),
New SQLVariable("za_IsFinalDeclaration", za_IsFinalDeclaration),
New SQLVariable("za_UCR", za_UCR),
New SQLVariable("za_Mandant_ID", za_Mandant_ID),
New SQLVariable("za_Bereich_ID", za_Bereich_ID),
New SQLVariable("za_Firma", za_Firma),
New SQLVariable("za_Niederlassung", za_Niederlassung),
New SQLVariable("za_MRN", za_MRN),
New SQLVariable("za_LRN", za_LRN),
New SQLVariable("za_DeclarationNo", za_DeclarationNo),
New SQLVariable("za_ReferenceCustomer", za_ReferenceCustomer),
New SQLVariable("za_REGIME", za_REGIME),
New SQLVariable("za_RegistrationType", za_RegistrationType),
New SQLVariable("za_MainProcedure", za_MainProcedure),
New SQLVariable("za_AdditionalProcedure", za_AdditionalProcedure),
New SQLVariable("za_DeclarationDate", za_DeclarationDate),
New SQLVariable("za_ReleaseDate", za_ReleaseDate),
New SQLVariable("za_AcceptanceDate", za_AcceptanceDate),
New SQLVariable("za_CustomsOffice", za_CustomsOffice),
New SQLVariable("za_EntryCustomsOffice", za_EntryCustomsOffice),
New SQLVariable("za_RepresentationCode", za_RepresentationCode),
New SQLVariable("za_TransportModeInland", za_TransportModeInland),
New SQLVariable("za_TransportModeBorder", za_TransportModeBorder),
New SQLVariable("za_MeansOfTransport_Vehicle", za_MeansOfTransport_Vehicle),
New SQLVariable("za_MeansOfTransport_Type", za_MeansOfTransport_Type),
New SQLVariable("za_MeansOfTransport_Nationality", za_MeansOfTransport_Nationality),
New SQLVariable("za_ContainerNr1", za_ContainerNr1),
New SQLVariable("za_ContainerNr2", za_ContainerNr2),
New SQLVariable("za_ContainerNr3", za_ContainerNr3),
New SQLVariable("za_ContainerNr4", za_ContainerNr4),
New SQLVariable("za_ContainerNr5", za_ContainerNr5),
New SQLVariable("za_ContainerNr6", za_ContainerNr6),
New SQLVariable("za_ContainerNr7", za_ContainerNr7),
New SQLVariable("za_ContainerNr8", za_ContainerNr8),
New SQLVariable("za_ContainerNr9", za_ContainerNr9),
New SQLVariable("za_CountryDispatch", za_CountryDispatch),
New SQLVariable("za_CountryDestination", za_CountryDestination),
New SQLVariable("za_CountryDestinationState", za_CountryDestinationState),
New SQLVariable("za_CountryImport", za_CountryImport),
New SQLVariable("za_WarehouseCode", za_WarehouseCode),
New SQLVariable("za_Incoterms", za_Incoterms),
New SQLVariable("za_IncotermsPlace", za_IncotermsPlace),
New SQLVariable("za_InvoiceAmount", za_InvoiceAmount),
New SQLVariable("za_InvoiceCurrency", za_InvoiceCurrency),
New SQLVariable("za_FiscalRepFlag", za_FiscalRepFlag),
New SQLVariable("za_TaxDeduction", za_TaxDeduction),
New SQLVariable("za_ApplicantTaxOffice", za_ApplicantTaxOffice),
New SQLVariable("za_ApplicantVATNo", za_ApplicantVATNo),
New SQLVariable("za_DV1Flag", za_DV1Flag),
New SQLVariable("za_PrevDocument_Type", za_PrevDocument_Type),
New SQLVariable("za_PrevDocument_No", za_PrevDocument_No),
New SQLVariable("za_AvisoId", za_AvisoId),
New SQLVariable("za_SendungsId", za_SendungsId),
New SQLVariable("za_Remarks", za_Remarks),
New SQLVariable("za_Sachbearbeiter", za_Sachbearbeiter),
New SQLVariable("za_SachbearbeiterId", za_SachbearbeiterId),
New SQLVariable("za_TotGrossMass", za_TotGrossMass),
New SQLVariable("za_ExportDeclarationType", za_ExportDeclarationType),
New SQLVariable("za_ExportSecurity", za_ExportSecurity),
New SQLVariable("za_ExportPartyConstellation", za_ExportPartyConstellation),
New SQLVariable("za_ExportStatus", za_ExportStatus),
New SQLVariable("za_ExportExitDate", za_ExportExitDate),
New SQLVariable("za_ExportExitOfficeDeclared", za_ExportExitOfficeDeclared),
New SQLVariable("za_ExportExitOfficeActual", za_ExportExitOfficeActual),
New SQLVariable("za_ExportPresentationOffice", za_ExportPresentationOffice),
New SQLVariable("za_ExportRegistrationExternal", za_ExportRegistrationExternal),
New SQLVariable("za_ExportNatureOfTransaction", za_ExportNatureOfTransaction),
New SQLVariable("za_ExportLocationType", za_ExportLocationType),
New SQLVariable("za_ExportLocationQualifier", za_ExportLocationQualifier),
New SQLVariable("za_ExportLocationIdentifier", za_ExportLocationIdentifier),
New SQLVariable("za_ExportLocationAuthorisation", za_ExportLocationAuthorisation),
New SQLVariable("za_ExportLocationStreet", za_ExportLocationStreet),
New SQLVariable("za_ExportLocationPostcode", za_ExportLocationPostcode),
New SQLVariable("za_ExportLocationCity", za_ExportLocationCity),
New SQLVariable("za_ExportLocationCountry", za_ExportLocationCountry),
New SQLVariable("za_ExportPresentationStart", za_ExportPresentationStart),
New SQLVariable("za_ExportLoadingEnd", za_ExportLoadingEnd),
New SQLVariable("za_ExportContainerIndicator", za_ExportContainerIndicator),
New SQLVariable("za_ExportBorderVehicle", za_ExportBorderVehicle),
New SQLVariable("za_ExportBorderVehicleType", za_ExportBorderVehicleType),
New SQLVariable("za_ExportBorderVehicleNationality", za_ExportBorderVehicleNationality),
New SQLVariable("za_ExportExitConfirmationDate", za_ExportExitConfirmationDate),
New SQLVariable("za_TransitType", za_TransitType),
New SQLVariable("za_TransitStatus", za_TransitStatus),
New SQLVariable("za_TransitDepartureOffice", za_TransitDepartureOffice),
New SQLVariable("za_TransitDestinationOffice", za_TransitDestinationOffice),
New SQLVariable("za_TransitLimitDate", za_TransitLimitDate),
New SQLVariable("za_TransitArrivalDate", za_TransitArrivalDate),
New SQLVariable("za_TransitCompletionDate", za_TransitCompletionDate),
New SQLVariable("za_TransitReducedDataset", za_TransitReducedDataset),
New SQLVariable("za_TransitSecurityCode", za_TransitSecurityCode),
New SQLVariable("za_TransitLocationType", za_TransitLocationType),
New SQLVariable("za_TransitLocationQualifier", za_TransitLocationQualifier),
New SQLVariable("za_TransitLocationIdentifier", za_TransitLocationIdentifier),
New SQLVariable("za_TransitSealNumbers", za_TransitSealNumbers),
New SQLVariable("za_TransitContainerIndicator", za_TransitContainerIndicator),
New SQLVariable("za_TransitBorderVehicle", za_TransitBorderVehicle),
New SQLVariable("za_TransitBorderVehicleType", za_TransitBorderVehicleType),
New SQLVariable("za_TransitBorderVehicleNationality", za_TransitBorderVehicleNationality)
}
End Function
Public Function getInsertCmd() As String
Dim f As String = "", v As String = ""
For Each i In getParameterList()
If Not i.isPrimaryParam Then
f &= "[" & i.Text & "],"
v &= "@" & i.Scalarvariable & ","
End If
Next
Return "INSERT INTO tblVERAG_CustomsDeclarations (" &
f.TrimEnd(","c) & ") VALUES (" & v.TrimEnd(","c) & ")"
End Function
Public Function getUpdateCmd() As String
Dim s As String = ""
For Each i In getParameterList()
If Not i.isPrimaryParam Then
s &= "[" & i.Text & "]=@" & i.Scalarvariable & ","
End If
Next
Return "UPDATE tblVERAG_CustomsDeclarations SET " &
s.TrimEnd(","c) & " WHERE za_Id=@za_Id"
End Function
Public Sub LOAD()
Try
hasEntry = False
Using conn = SQL.GetNewOpenConnectionFMZOLL()
Using cmd As New SqlCommand(
"SELECT * FROM tblVERAG_CustomsDeclarations WHERE za_Id=@_BASE_id", conn)
cmd.Parameters.AddWithValue("@_BASE_id", za_Id)
Dim dr = cmd.ExecuteReader()
If dr.Read Then
For Each li In getParameterList()
Dim pi = Me.GetType.GetProperty(li.Scalarvariable)
If dr.Item(li.Text) Is DBNull.Value Then
pi.SetValue(Me, Nothing)
Else
pi.SetValue(Me, dr.Item(li.Text))
End If
Next
hasEntry = True
End If
dr.Close()
End Using
End Using
Parties = cVERAG_CustomsDeclarations_Parties.LOAD_BY_ZAID(za_Id)
Items = cVERAG_CustomsDeclarations_Item.LOAD_BY_ZAID(za_Id)
Duties = cVERAG_CustomsDeclarations_Duty.LOAD_HEAD_BY_ZAID(za_Id)
Documents = cVERAG_CustomsDeclarations_Document.LOAD_HEAD_BY_ZAID(za_Id)
Catch ex As Exception
cErrorHandler.ERR(ex.Message, ex.StackTrace, MethodInfo.GetCurrentMethod.Name)
End Try
End Sub
Public Shared Function LOAD_List_CBAM(EORI() As String, ImportCountry As String, datFrom As Date, datTo As Date, Optional CustomsSystem As String = "", Optional loadAll As Boolean = True, Optional indirect As Boolean = False) As List(Of cVERAG_CustomsDeclarations)
Dim LIST As New List(Of cVERAG_CustomsDeclarations)
Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
Try
' ------------------------------------------------------------
' CBAM Pattern (HSCode)
' ------------------------------------------------------------
Dim cbamWhere As String = VERAG_PROG_ALLGEMEIN.cGreendeal_CBAM_Trn.BuildCBAMPatternWhereClause("i.zaItem_HSCode")
Dim cbamWhereSnd As String = " AND " & cbamWhere.Replace("i.zaItem_HSCode", "zaItem_HSCode") &
" AND zaItem_OriginCountry NOT IN (
'EU','AT','BE','BG','HR','CY','CZ','DK','EE','FI','FR',
'DE','GR','HU','IE','IT','LV','LT','LU','MT','NL',
'PL','PT','RO','SK','SI','ES','SE',
'CH','NO','IS','LI','XI'
)"
Dim cbamWhereISOCntry As String = " i.zaItem_OriginCountry NOT IN (
/*EU-27 (ISO2)*/
'EU','AT','BE','BG','HR','CY','CZ','DK','EE','FI','FR',
'DE','GR','HU','IE','IT','LV','LT','LU','MT','NL',
'PL','PT','RO','SK','SI','ES','SE',
/*Nicht CBAM-pflichtig (EU-ETS verknüpft / Ausnahmen)*/
'CH', /* Schweiz */
'NO', /* Norwegen */
'IS', /* Island */
'LI', /* Liechtenstein */
'XI' /* Nordirland (NI-Protokoll; im Warenverkehr EU-behandelt) */
) "
' ------------------------------------------------------------
' SQL: ZA-IDs ermitteln
' ------------------------------------------------------------
Dim eoriIn As String =
String.Join(",", EORI.
Where(Function(x) Not String.IsNullOrWhiteSpace(x)).
Select(Function(x) "'" & x.Replace("'", "''") & "'"))
Dim sqlstr As String =
"SELECT DISTINCT z.* " &
"FROM VERAG.dbo.tblVERAG_CustomsDeclarations z " &
"INNER JOIN VERAG.dbo.tblVERAG_CustomsDeclarations_Items i " &
" ON z.za_Id = i.zaItem_zaId " &
"LEFT JOIN VERAG.dbo.tblVERAG_CustomsDeclarations_Parties p " &
" ON z.za_Id = p.zaParty_zaId " &
"WHERE z.za_REGIME = 'IMPORT' " &
" AND z.za_IsFinalDeclaration = 1 " &
" AND cast(z.za_DeclarationDate as date) >= @dateFrom " &
" AND cast(z.za_DeclarationDate as date) <= @dateTo " &
If(eoriIn <> "", " AND p.zaParty_EORI IN (" & eoriIn & ") ", "") &
" AND " & cbamWhere &
" AND " & cbamWhereISOCntry
If indirect Then
sqlstr &= " AND (
(za_System IN('DHF','DHF_UNISPED') AND za_RepresentationCode=3) OR
(za_System IN('TELOTEC') AND za_RepresentationCode=3) OR
(za_System IN('DAKOSY') AND za_RepresentationCode=2)
)"
End If
If ImportCountry <> "" Then
sqlstr &= " AND z.za_CountryImport = @importCountry "
End If
If CustomsSystem <> "" Then
sqlstr &= " AND z.za_System = @sys "
End If
Using conn = SQL.GetNewOpenConnectionFMZOLL()
Using cmd As New SqlCommand(sqlstr, conn)
' cmd.Parameters.AddWithValue("@eori", EORI)
cmd.Parameters.AddWithValue("@dateFrom", datFrom.ToShortDateString)
cmd.Parameters.AddWithValue("@dateTo", datTo.ToShortDateString)
If ImportCountry <> "" Then
cmd.Parameters.AddWithValue("@importCountry", ImportCountry)
End If
If CustomsSystem <> "" Then
cmd.Parameters.AddWithValue("@sys", CustomsSystem)
End If
Using dr = cmd.ExecuteReader()
While dr.Read()
Dim CD As New cVERAG_CustomsDeclarations
CD.hasEntry = False
' ------------------------------------------------
' DIREKTE BEFÜLLUNG (wie gewünscht)
' ------------------------------------------------
For Each li In CD.getParameterList()
Dim pi = CD.GetType().GetProperty(li.Scalarvariable)
If pi Is Nothing Then Continue For
If dr.Item(li.Text) Is DBNull.Value Then
pi.SetValue(CD, Nothing)
Else
pi.SetValue(CD, dr.Item(li.Text))
End If
Next
CD.hasEntry = True
' ------------------------------------------------
' OPTIONALES NACHLADEN
' ------------------------------------------------
If loadAll Then
CD.Parties = cVERAG_CustomsDeclarations_Parties.LOAD_BY_ZAID(CD.za_Id)
CD.Items = cVERAG_CustomsDeclarations_Item.LOAD_BY_ZAID(CD.za_Id, cbamWhereSnd)
CD.Duties = cVERAG_CustomsDeclarations_Duty.LOAD_HEAD_BY_ZAID(CD.za_Id)
CD.Documents = cVERAG_CustomsDeclarations_Document.LOAD_HEAD_BY_ZAID(CD.za_Id)
End If
LIST.Add(CD)
End While
End Using
End Using
End Using
Catch ex As Exception
cErrorHandler.ERR(ex.Message, ex.StackTrace, Reflection.MethodInfo.GetCurrentMethod.Name)
End Try
Return LIST
End Function
Public Shared Function loadByMRN(MRN As String, loadall As Boolean) As cVERAG_CustomsDeclarations
Dim ZA As New cVERAG_CustomsDeclarations
If If(MRN, "") = "" Then Return ZA
Try
ZA.hasEntry = False
Using conn = SQL.GetNewOpenConnectionFMZOLL()
Using cmd As New SqlCommand(
"SELECT * FROM tblVERAG_CustomsDeclarations WHERE za_MRN=@_BASE_id", conn)
cmd.Parameters.AddWithValue("@_BASE_id", MRN)
Dim dr = cmd.ExecuteReader()
If dr.Read Then
For Each li In ZA.getParameterList()
Dim pi = ZA.GetType.GetProperty(li.Scalarvariable)
If dr.Item(li.Text) Is DBNull.Value Then
pi.SetValue(ZA, Nothing)
Else
pi.SetValue(ZA, dr.Item(li.Text))
End If
Next
ZA.hasEntry = True
End If
dr.Close()
End Using
End Using
If loadall Then
ZA.Parties = cVERAG_CustomsDeclarations_Parties.LOAD_BY_ZAID(ZA.za_Id)
ZA.Items = cVERAG_CustomsDeclarations_Item.LOAD_BY_ZAID(ZA.za_Id)
ZA.Duties = cVERAG_CustomsDeclarations_Duty.LOAD_HEAD_BY_ZAID(ZA.za_Id)
ZA.Documents = cVERAG_CustomsDeclarations_Document.LOAD_HEAD_BY_ZAID(ZA.za_Id)
End If
Catch ex As Exception
cErrorHandler.ERR(ex.Message, ex.StackTrace, MethodInfo.GetCurrentMethod.Name)
End Try
Return ZA
End Function
Public Shared Function loadBySendungsID(za_SendungsId As String, loadall As Boolean) As cVERAG_CustomsDeclarations
Dim ZA As New cVERAG_CustomsDeclarations
If If(za_SendungsId, "") = "" Then Return ZA
Try
ZA.hasEntry = False
Using conn = SQL.GetNewOpenConnectionFMZOLL()
Using cmd As New SqlCommand(
"SELECT * FROM tblVERAG_CustomsDeclarations WHERE za_SendungsId=@_BASE_id", conn)
cmd.Parameters.AddWithValue("@_BASE_id", za_SendungsId)
Dim dr = cmd.ExecuteReader()
If dr.Read Then
For Each li In ZA.getParameterList()
Dim pi = ZA.GetType.GetProperty(li.Scalarvariable)
If dr.Item(li.Text) Is DBNull.Value Then
pi.SetValue(ZA, Nothing)
Else
pi.SetValue(ZA, dr.Item(li.Text))
End If
Next
ZA.hasEntry = True
End If
dr.Close()
End Using
End Using
If loadall Then
ZA.Parties = cVERAG_CustomsDeclarations_Parties.LOAD_BY_ZAID(ZA.za_Id)
ZA.Items = cVERAG_CustomsDeclarations_Item.LOAD_BY_ZAID(ZA.za_Id)
ZA.Duties = cVERAG_CustomsDeclarations_Duty.LOAD_HEAD_BY_ZAID(ZA.za_Id)
ZA.Documents = cVERAG_CustomsDeclarations_Document.LOAD_HEAD_BY_ZAID(ZA.za_Id)
End If
Catch ex As Exception
cErrorHandler.ERR(ex.Message, ex.StackTrace, MethodInfo.GetCurrentMethod.Name)
End Try
Return ZA
End Function
Public Sub checkfreshCBAMWarning()
Try
Dim CBAM_ITEMS As New List(Of cVERAG_CustomsDeclarations_Item)
If hasCBAM(CBAM_ITEMS) Then
Dim vertreterEORI As String = Me.Parties.Where(Function(p) DECLARANT_ROLES.Contains(p.zaParty_Role)).Select(Function(p) p.zaParty_EORI).FirstOrDefault()
Dim vertreterString As String = Me.Parties.Where(Function(p) DECLARANT_ROLES.Contains(p.zaParty_Role)).Select(Function(p) p.zaParty_Name).FirstOrDefault()
Dim importerEORI As String = Me.Parties.Where(Function(p) IMPORTER_ROLES.Contains(p.zaParty_Role)).Select(Function(p) p.zaParty_EORI).FirstOrDefault()
Dim ImporterString As String = Me.Parties.Where(Function(p) IMPORTER_ROLES.Contains(p.zaParty_Role)).Select(Function(p) p.zaParty_Name).FirstOrDefault()
Dim ExporterEORI As String = Me.Parties.Where(Function(p) EXPORTER_ROLES.Contains(p.zaParty_Role)).Select(Function(p) p.zaParty_EORI).FirstOrDefault()
Dim ExporterString As String = Me.Parties.Where(Function(p) EXPORTER_ROLES.Contains(p.zaParty_Role)).Select(Function(p) p.zaParty_Name).FirstOrDefault()
Dim KD As cKunde = Nothing
Dim AD As cAdressen = Nothing
If If(importerEORI, "") <> "" Then
KD = cKunde.LOAD_ByEORI(importerEORI, If(za_Firma, ""))
If KD Is Nothing Then KD = cKunde.LOAD_ByEORI(importerEORI) 'Wenn kein Kunde mit Firma gefunden wurde, nur nach EORI suchen (default VERAG)
AD = New cAdressen(KD.KundenNr)
End If
If AD IsNot Nothing Then
ImporterString = AD.Name_1 & " " & If(AD.Name_2, "") & "<br/>" & If(AD.LandKz, "") & " " & If(AD.PLZ, "") & " " & If(AD.Ort, "")
End If
Dim KD_EX As cKunde = Nothing
Dim AD_EX As cAdressen = Nothing
If If(ExporterEORI, "") <> "" Then
KD_EX = cKunde.LOAD_ByEORI(ExporterEORI, If(za_Firma, ""))
If KD_EX Is Nothing Then KD_EX = cKunde.LOAD_ByEORI(ExporterEORI) 'Wenn kein Kunde mit Firma gefunden wurde, nur nach EORI suchen (default VERAG)
AD_EX = New cAdressen(KD_EX.KundenNr)
End If
If AD_EX IsNot Nothing Then
ExporterString = AD_EX.Name_1 & " " & If(AD_EX.Name_2, "") & "<br/>" & If(AD_EX.LandKz, "") & " " & If(AD_EX.PLZ, "") & " " & If(AD_EX.Ort, "")
End If
If isIndirect() Then
Dim vertretenerEORI = ""
Dim vertretenerString = ""
If importerEORI IsNot Nothing Then
vertretenerEORI = importerEORI
vertretenerString = ImporterString
Else
vertretenerEORI = ExporterEORI
vertretenerString = ExporterString
End If
Dim KD_IND As cKunde = Nothing
Dim AD_IND As cAdressen = Nothing
Dim ERW_IND As cKundenErweitert = Nothing
Dim VERTR_IND As List(Of cKundenVertraege) = Nothing
If If(ExporterEORI, "") <> "" Then
KD_IND = cKunde.LOAD_ByEORI(ExporterEORI, If(za_Firma, ""))
If KD_IND Is Nothing Then KD_IND = cKunde.LOAD_ByEORI(ExporterEORI) 'Wenn kein Kunde mit Firma gefunden wurde, nur nach EORI suchen (default VERAG)
AD_IND = New cAdressen(KD_IND.KundenNr)
End If
If AD_IND IsNot Nothing Then
vertretenerString = AD_IND.Name_1 & " " & If(AD_IND.Name_2, "") & "<br/>" & If(AD_IND.LandKz, "") & " " & If(AD_IND.PLZ, "") & " " & If(AD_IND.Ort, "")
ERW_IND = New cKundenErweitert(AD.AdressenNr)
VERTR_IND = cKundenVertraege.LOAD_LISTOF(AD.AdressenNr)
End If
'==================>> INDIRECT <<=========================
Dim itemsHtml As String =
String.Join("", CBAM_ITEMS.Select(Function(i) "<tr>" &
"<td>" & i.zaItem_PosNo.ToString & "</td>" &
"<td>" & If(i.zaItem_HSCode, "") & "</td>" &
"<td>" & If(i.zaItem_Description, "") & "</td>" &
"</tr>"
))
Dim dateCBAM = If(If(za_ReleaseDate, za_DeclarationDate), Now)
Dim eigenmasseSumme_YEAR As Decimal = getCBAM_KG(vertretenerEORI, CDate("01.01." & dateCBAM.Year), CDate("31.12." & dateCBAM.Year), za_MRN) / 1000
Dim quarter As Integer = Math.Ceiling(dateCBAM.Month / 3.0)
Dim CountryOfOrigin As String = If(CBAM_ITEMS.FirstOrDefault()?.zaItem_OriginCountry, "")
createOrUpdateKundenSicherheitseintrag(KD_IND, CountryOfOrigin, vertretenerEORI, quarter, dateCBAM.Year)
'Prüft, ob Vertrag vorliegt:
Dim hasValidVertrag_CBAM As Boolean =
VERTR_IND.Any(Function(v) _
v.kv_vertragArtId = 8 AndAlso
v.kv_gueltig AndAlso
(Not v.kv_gueltigBis_Datum.HasValue OrElse
v.kv_gueltigBis_Datum.Value.Date <= dateCBAM)
)
Dim vertragHinweisHtml As String =
If(Not hasValidVertrag_CBAM,
"<div style='margin:15px 0; padding:12px; border:2px solid #b00020; " &
"background-color:#fdeaea; color:#b00020; font-weight:bold; font-size:13pt'>" &
"⚠️ ACHTUNG: Es liegt kein gültiger CBAM-Vertrag vor!" &
"</div>",
"")
Dim bodyHtml As String =
"<html><body style='font-family:Segoe UI, Arial, sans-serif; font-size:12pt; color:#222'>" &
"<h2 style='color:#b00020'>CBAM-Warnmeldung bei Zollanmeldung " & Me.za_MRN & "</h2>" &
"<p>" &
"Bei der Zollanmeldung mit der MRN <b>" & Me.za_MRN & "</b> wurden CBAM-relevante Warenpositionen erkannt.<br/>" &
"Bitte prüfen Sie diese Anmeldung im Hinblick auf die CBAM-Meldepflicht." &
"</p>" &
vertragHinweisHtml & ' <<< HIER die Einblendung abhängig von vertrag99
"<h3>Erkannte CBAM-Positionen</h3>" &
"<table cellpadding='6' cellspacing='0' border='1' style='border-collapse:collapse; width:100%'>" &
"<tr style='background-color:#f0f0f0'>" &
"<th align='left'>PosNr</th>" &
"<th align='left'>HS-Code</th>" &
"<th align='left'>Beschreibung</th>" &
"</tr>" &
itemsHtml &
"</table>" &
"<p>" &
"<b>Ind.Vertreter:</b><br/>" &
If(vertreterEORI, "") & "<br>" & If(vertreterString, "") &
"</p>" &
"<p>" &
"<b>Kunde:</b><br/>" &
If(vertretenerEORI, "") & "<br>" & If(vertretenerString, "") &
"</p>" &
"<p>" &
"<b>Importeur:</b><br/>" &
If(importerEORI, "") & "<br>" & If(ImporterString, "") &
"</p>" &
"<p>" &
"<b>Exporteur:</b><br/>" &
If(ExporterEORI, "") & "<br>" & If(ExporterString, "") &
"</p>" &
"<br/><p><b>VERAG – CBAM Compliance Services</b></p>" &
"</body></html>"
Dim empfanegerMail As String = ""
empfanegerMail = cMitarbeiter.GetEMailRecipientForEmailNotification("CBAM-WARNUNG")
If empfanegerMail <> "" Then
VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(empfanegerMail, "CBAM WARNUNG - " & Me.za_MRN, bodyHtml, "cbam@verag.ag")
End If
'VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail("al@verag.ag", "CBAM WARNUNG",
' "CBAM-Warnmeldung bei Zollanmeldung " & Me.za_MRN & vbNewLine &
' "Bei der Zollanmeldung mit der MRN " & Me.za_MRN & " wurden CBAM-relevante Warenpositionen erkannt." & vbCrLf &
' "Bitte prüfen Sie diese Anmeldung im Hinblick auf die CBAM-Meldepflicht." & vbCrLf & vbCrLf &
' "Erkannte CBAM-Positionen:" & vbCrLf &
' String.Join(vbCrLf, CBAM_ITEMS.Select(Function(i) " - PosNr: " & i.zaItem_PosNo.ToString & " | HS-Code: " & If(i.zaItem_HSCode, "") & " | Beschreibung: " & If(i.zaItem_Description, "")))
' )
''=========================================================
Else
'==================>> DIRECT <<=========================
Try
If KD IsNot Nothing Then
Dim ERW As New cKundenErweitert(KD.KundenNr)
Select Case ERW.kde_CBAM_Status
Case "", "50to" ' Nur hier wird eine Warnung gesendet!! -> WEnn der Kunde bereits Registriert ist, nicht notwendig.
Dim dateCBAM = If(If(za_ReleaseDate, za_DeclarationDate), Now)
Dim CountryOfOrigin As String = If(CBAM_ITEMS.FirstOrDefault()?.zaItem_OriginCountry, "")
Dim quarter As Integer = Math.Ceiling(dateCBAM.Month / 3.0)
createOrUpdateKundenSicherheitseintrag(KD, CountryOfOrigin, importerEORI, quarter, dateCBAM.Year)
Dim eigenmasseSumme_Shipment As Decimal = CBAM_ITEMS.Sum(Function(i) If(i.zaItem_NetMass, 0D)) / 1000
Dim eigenmasseSumme_YEAR As Decimal = getCBAM_KG(importerEORI, CDate("01.01." & dateCBAM.Year), CDate("31.12." & dateCBAM.Year)) / 1000
Dim WarnLevel As String = ""
Dim Schwellenwert As Decimal = 0
Dim Warn1 As Decimal = If(If(ERW.kde_CBAM_Warn1, 0) > 0, ERW.kde_CBAM_Warn1, 30)
Dim Warn2 As Decimal = If(If(ERW.kde_CBAM_Warn2, 0) > 0, ERW.kde_CBAM_Warn2, 40)
Dim Warn50to As Decimal = 50
'geprüft werden die bisherigen CBAM Waren im Jahr + die aktuelle Sendung
If eigenmasseSumme_YEAR < Warn50to And (eigenmasseSumme_Shipment + eigenmasseSumme_YEAR) >= Warn50to Then
'--> WARN 2 überschritten
WarnLevel = "3"
Schwellenwert = 50
End If
'geprüft werden die bisherigen CBAM Waren im Jahr + die aktuelle Sendung
If eigenmasseSumme_YEAR < Warn2 And (eigenmasseSumme_Shipment + eigenmasseSumme_YEAR) >= Warn2 Then
'--> WARN 2 überschritten
WarnLevel = "2"
Schwellenwert = Warn2
End If
'geprüft werden die bisherigen CBAM Waren im Jahr + die aktuelle Sendung
If eigenmasseSumme_YEAR < Warn1 And (eigenmasseSumme_Shipment + eigenmasseSumme_YEAR) >= Warn1 Then
'--> WARN 1 überschritten
WarnLevel = "1"
Schwellenwert = Warn1
End If
'===========>>>> WARNUNG <<<<<<<=================================
If WarnLevel <> "" Then
Dim bodyHtml As String =
"<html><body style='font-family:Segoe UI, Arial, sans-serif; font-size:12pt; color:#222'>" &
"<h2 style='color:#b00020'>CBAM-Warnmeldung zu Ihrer Zollanmeldung " & Me.za_MRN & "</h2>" &
"<p>" &
"Laut unserem System wurden in der Zollanmeldung mit der MRN <b>" & Me.za_MRN & "</b> " &
"CBAM-pflichtige Warenpositionen erkannt.<br/>" &
"Für Ihr Unternehmen liegen uns derzeit keine Informationen über eine gültige CBAM-Registrierung vor." &
"</p>" &
"<p style='font-style:italic; color:#444'>" &
"Falls Sie uns Ihre CBAM-Antrags- oder Registriernummer bereits übermittelt haben, " &
"betrachten Sie diese Nachricht bitte als gegenstandslos." &
"</p>" &
"<table cellpadding='6' cellspacing='0' border='1' style='border-collapse:collapse'>" &
"<tr><td><b>Warnstufe</b></td><td>" & WarnLevel & If(WarnLevel = 3, " - <span style='color:#b00020'><b>ÜBERSCHREITUNG!</b></span>", "") & "</td></tr>" &
"<tr><td><b>Schwellenwert</b></td><td>" & Schwellenwert.ToString("N0") & " Tonnen</td></tr>" &
"</table><br/>" &
"<p>" &
"<b>Importeur:</b><br/>" &
If(importerEORI, "") & "<br>" & If(ImporterString, "") &
"</p>" &
"<p>" &
"Bei Überschreitung einer jährlichen Gesamtmenge von <b>50 Tonnen CBAM-pflichtiger Waren</b> (Jahressumme) " &
"ist eine gültige CBAM-Registrierung zwingend erforderlich.<br/>" &
"Ohne gültige Registrierung kann es zu Zollblockaden oder Abfertigungsstopps kommen." &
"</p>" &
"<p>" &
"Bitte teilen Sie uns kurzfristig unter " &
"<a href='mailto:cbam@verag.ag'>cbam@verag.ag</a> mit, wie Sie weiter vorgehen möchten " &
"(z. B. bestehende Registrierung, Beantragung mit VERAG oder Bevollmächtigung)." &
"</p>" &
"<p><b>VERAG DCS – CBAM Compliance Services</b></p>" &
"<p>VERAG Spedition AG<br>A-4975 Suben, Suben 100</p>" &
"</body></html>"
'"<b>Exporteur:</b><br/>" &
' If (ExporterEORI, "") & "<br>" & If(ExporterString, "") &
' "</p>" &
' "<p style='color:#b00020'><b>WICHTIG</b></p>" &
' "<p>" &
' VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(If(AD.E_Mail, ""), "CBAM-WARNUNG – " & If(WarnLevel = 3, " ACHTUNG: Überschreitung 50to! ", "Überschreitung der Meldeschwelle"), bodyHtml, "cbam@verag.ag", (WarnLevel = 3), "cbam@verag.ag",, "al@verag.ag")
VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(If(AD.E_Mail, ""), "CBAM-WARNUNG – " & If(WarnLevel = 3, " ACHTUNG: Überschreitung 50to! ", "Überschreitung der Meldeschwelle"), bodyHtml, "cbam@verag.ag", (WarnLevel = 3), False, "cbam@verag.ag;" & If(AD.E_Mail2, ""), "al@verag.ag")
'VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(
' "al@verag.ag",
' "CBAM-WARNUNG – Überschreitung der Meldeschwelle",
' "CBAM-Warnmeldung zu Ihrer Zollanmeldung " & Me.za_MRN & vbCrLf & vbCrLf &
' "Laut unserem System wurden in der Zollanmeldung mit der MRN " & Me.za_MRN & " CBAM-pflichtige Warenpositionen erkannt." & vbCrLf &
' "Für Ihr Unternehmen liegen uns derzeit keine Informationen über eine gültige CBAM-Registrierung vor." & vbCrLf & vbCrLf &
' "Der für diese Sendung relevante Schwellenwert wurde überschritten." & vbCrLf &
' "Aktuelle Warnstufe: " & WarnLevel & vbCrLf &
' "Angewendeter Schwellenwert: " & Schwellenwert.ToString("N0") & " Tonnen" & vbCrLf & vbCrLf &
' "Importeur: " & importerEORI & " - " & AD.Name_1 & " " & If(AD.Name_2, "") & " " & If(AD.LandKz, "") & " " & If(AD.PLZ, "") & " " & If(AD.Ort, "") & vbCrLf &
' "WICHTIG:" & vbCrLf &
' "Bei Überschreitung einer jährlichen Gesamtmenge von 50 Tonnen CBAM-pflichtiger Waren ist eine gültige CBAM-Registrierung zwingend erforderlich." & vbCrLf &
' "Ohne gültige Registrierung kann es zu Zollblockaden oder Abfertigungsstopps kommen." & vbCrLf & vbCrLf &
' "Bitte teilen Sie uns kurzfristig unter cbam@verag.ag mit, wie Sie weiter vorgehen möchten (z. B. bestehende Registrierung, Beantragung mit VERAG oder Bevollmächtigung)." & vbCrLf & vbCrLf &
' "VERAG – CBAM Compliance Services"
' )
End If
'================================================================
End Select
End If
'=========================================================
Catch ex As Exception
cErrorHandler.ERR(ex.Message, ex.StackTrace, Reflection.MethodInfo.GetCurrentMethod.Name)
End Try
End If
End If
Catch ex As Exception
cErrorHandler.ERR(ex.Message, ex.StackTrace, Reflection.MethodInfo.GetCurrentMethod.Name)
End Try
End Sub
Public Function GetInvoiceListString() As String
If Documents Is Nothing OrElse Documents.Count = 0 Then Return ""
Dim result = Documents.
Where(Function(d) Not d Is Nothing AndAlso
(d.zaDoc_Code = "N380" OrElse d.zaDoc_Code = "N325")).
Select(Function(d)
Dim datum As String = If(String.IsNullOrWhiteSpace(d.zaDoc_Date), "", d.zaDoc_Date.Trim())
Dim ref As String = If(String.IsNullOrWhiteSpace(d.zaDoc_Reference), "", d.zaDoc_Reference.Trim())
' Format: "Datum Referenz"
Return (datum & " " & ref).Trim()
End Function).
Where(Function(s) Not String.IsNullOrWhiteSpace(s)).
Distinct().
ToList()
Return String.Join(", ", result)
End Function
Private Function createOrUpdateKundenSicherheitseintrag(KUNDE As cKunde, CountryOfOrigin As String, EORI As String, cbamQquarter As Integer, cbamYear As Integer)
Dim von As Date
Dim bis As Date
Dim CBAMZertifikatKosten As Double = 0
If CountryOfOrigin = "" Then Return False
Select Case cbamQquarter
Case "1"
von = New Date(cbamYear, 1, 1)
bis = New Date(cbamYear, 3, 31)
CBAMZertifikatKosten = 75.36
Case "2"
von = New Date(cbamYear, 4, 1)
bis = New Date(cbamYear, 6, 30)
CBAMZertifikatKosten = 75.28
Case "3"
von = New Date(cbamYear, 7, 1)
bis = New Date(cbamYear, 9, 30)
CBAMZertifikatKosten = 82.32
Case "4"
von = New Date(cbamYear, 10, 1)
bis = New Date(cbamYear, 12, 31)
CBAMZertifikatKosten = 0
End Select
Dim EORI_ = {EORI}
Dim LIST As List(Of VERAG_PROG_ALLGEMEIN.cVERAG_CustomsDeclarations) = VERAG_PROG_ALLGEMEIN.cVERAG_CustomsDeclarations.LOAD_List_CBAM(EORI_, CountryOfOrigin, von, bis,, True)
Dim grouped = From za In LIST
Where za.Items IsNot Nothing
From it In za.Items
Let tarif = If(it.zaItem_HSCode IsNot Nothing AndAlso it.zaItem_HSCode.Length >= 8,
it.zaItem_HSCode.Substring(0, 8),
it.zaItem_HSCode)
Let country = it.zaItem_OriginCountry
Group By tarif, country
Into grp = Group
Select New With {
.Tarif = tarif,
.Country = country,
.Eigenmasse = grp.Sum(Function(x) If(x.it.zaItem_NetMass, 0D)),
.Rohmasse = grp.Sum(Function(x) If(x.it.zaItem_GrossMass, 0D)),
.RechnungswertEUR = grp.Sum(Function(x) If(x.it.zaItem_InvoiceValueEUR, 0D))
}
If grouped.Count < 1 Then
Return False
End If
Dim gesamtBetrag As Double = 0
Dim cost As Double = 0
Dim emission As Double = 0
Dim benchmark As Double = 0
For Each r In grouped
cATEZ_Greenpulse_CBAM_CostCalculation.calcCBAM_ByCertificatePrice(r.Tarif, r.Rohmasse, r.Country, CBAMZertifikatKosten, cbamYear, cost, emission, benchmark)
gesamtBetrag += cost
Next
If gesamtBetrag <> 0 Then
Dim Kunde_Sicherheit As New cKundenSicherheiten(KUNDE.KundenNr, cbamQquarter, cbamYear)
If Kunde_Sicherheit.hasEntry Then
Kunde_Sicherheit.sc_Betrag = gesamtBetrag
Kunde_Sicherheit.SAVE()
Else
Kunde_Sicherheit.sc_Waehrung = "EUR"
Kunde_Sicherheit.sc_Bemerkung = "CBAM Kosten Q" & cbamQquarter & " " & cbamYear & " / verw. Preis: " & CBAMZertifikatKosten.ToString("N2")
Kunde_Sicherheit.sc_Art = "BANKGARANTIE"
Kunde_Sicherheit.sc_Betrag = gesamtBetrag
Kunde_Sicherheit.sc_gueltigVon = New Date(2026, 1, 1)
Kunde_Sicherheit.sc_gueltigBis = New Date(2027, 12, 31)
Kunde_Sicherheit.sc_datum = Today()
Kunde_Sicherheit.sc_Mitarbeiter = "AUTO"
Kunde_Sicherheit.sc_dsId = -1
Kunde_Sicherheit.SAVE()
End If
End If
End Function
Public Function getCBAM_KG(EORI As String, von As Date, bis As Date, Optional without_MRN As String = "", Optional isDeclarant As Boolean = False) As Decimal
Try
If EORI = "" Then Return 0
Dim sqlstr = "SELECT SUM(i.zaItem_NetMass) AS CBAM_Eigenmasse_kg
FROM VERAG.dbo.tblVERAG_CustomsDeclarations_Items i
JOIN VERAG.dbo.tblVERAG_CustomsDeclarations z
ON z.za_Id = i.zaItem_zaId
JOIN VERAG.dbo.tblVERAG_CustomsDeclarations_Parties p
ON p.zaParty_zaId = z.za_Id
AND p.zaParty_EORI = '" & EORI & "'
" & If(isDeclarant, "AND (p.zaParty_Role IN ('CB','DT','DEKLARANT','DECLARANT') ",
" AND (p.zaParty_Role IN ('CN','IM','IMP','IMPORTER','CONSIGNEE') OR
p.zaParty_Role IN ('CZ','EX','EXP','EXPORTER','CONSIGNOR'))") & "
WHERE z.za_ReleaseDate BETWEEN '" & von.ToShortDateString & "' AND '" & bis.ToShortDateString & "'
AND i.zaItem_OriginCountry NOT IN (
'EU','AT','BE','BG','HR','CY','CZ','DK','EE','FI','FR',
'DE','GR','HU','IE','IT','LV','LT','LU','MT','NL',
'PL','PT','RO','SK','SI','ES','SE',
'CH','NO','IS','LI','XI'
)
AND EXISTS (
SELECT 1
FROM VERAG.dbo.tblGreendeal_CBAM_Trn t
WHERE
i.zaItem_HSCode LIKE t.trnPattern
AND t.is_active = 1
AND ISNULL(t.is_exclusion,0) = 0
AND (t.start_date IS NULL OR t.start_date <= z.za_ReleaseDate)
AND (t.end_date IS NULL OR t.end_date >= z.za_ReleaseDate)
) "
If without_MRN <> "" Then sqlstr &= " and za_MRN <>'" & without_MRN & "'"
Return SQL.getValueTxtBySql(sqlstr, "FMZOLL",,, 0)
Catch ex As Exception
cErrorHandler.ERR(ex.Message, ex.StackTrace, Reflection.MethodInfo.GetCurrentMethod.Name)
End Try
Return 0
End Function
Public Function isIndirect() As Boolean
If Me.za_System Is Nothing Then Return False
If Me.za_RepresentationCode Is Nothing Then Return False
If Me.za_System.Contains("DHF") AndAlso Me.za_RepresentationCode = 3 Then Return True
If Me.za_System.Contains("TELOTEC") AndAlso Me.za_RepresentationCode = 3 Then Return True
If Me.za_System.Contains("DAKOSY") AndAlso Me.za_RepresentationCode = 2 Then Return True
Return False
End Function
Public Function hasCBAM(Optional ByRef CBAM_ITEMS As List(Of cVERAG_CustomsDeclarations_Item) = Nothing) As Boolean
Dim LIST As New List(Of cVERAG_CustomsDeclarations)
Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
Try
CBAM_ITEMS = getCBAM_ITEMS()
If CBAM_ITEMS IsNot Nothing AndAlso CBAM_ITEMS.Count > 0 Then
Return True
End If
Catch ex As Exception
cErrorHandler.ERR(ex.Message, ex.StackTrace, Reflection.MethodInfo.GetCurrentMethod.Name)
End Try
Return False
End Function
Public Function getCBAM_ITEMS() As List(Of cVERAG_CustomsDeclarations_Item)
Dim LIST As New List(Of cVERAG_CustomsDeclarations)
Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
Try
' ------------------------------------------------------------
' CBAM Pattern (HSCode)
' ------------------------------------------------------------
Dim cbamHsCodes = VERAG_PROG_ALLGEMEIN.cGreendeal_CBAM_Trn.LoadCBAMTariffNumbers()
If Items Is Nothing OrElse cbamHsCodes Is Nothing OrElse cbamHsCodes.Count = 0 Then Return Nothing
' Performance: HashSet für Prefix-Liste
Dim prefixes As HashSet(Of String) =
New HashSet(Of String)(cbamHsCodes)
Dim excludedCountries As New HashSet(Of String) From {
"EU", "AT", "BE", "BG", "HR", "CY", "CZ", "DK", "EE", "FI", "FR",
"DE", "GR", "HU", "IE", "IT", "LV", "LT", "LU", "MT", "NL",
"PL", "PT", "RO", "SK", "SI", "ES", "SE",
"CH", "NO", "IS", "LI", "XI"
}
Return Me.Items.
Where(Function(it)
Dim hs As String = If(it.zaItem_HSCode, "").Trim()
If hs = "" Then Return False
Dim origin As String = If(it.zaItem_OriginCountry, "").Trim().ToUpper()
If origin <> "" AndAlso excludedCountries.Contains(origin) Then Return False
For Each p In prefixes
If hs.StartsWith(p) Then
Return True
End If
Next
End Function).ToList()
Catch ex As Exception
cErrorHandler.ERR(ex.Message, ex.StackTrace, Reflection.MethodInfo.GetCurrentMethod.Name)
End Try
Return Nothing
End Function
Public Sub LOAD_TRANSIT()
If za_Id <= 0 Then Return
HouseConsignments = cVERAG_NCTS_Repository.LoadHouses(za_Id)
TransitGuarantees = cVERAG_NCTS_Repository.LoadGuarantees(za_Id)
TransitOffices = cVERAG_NCTS_Repository.LoadOffices(za_Id)
Dim byId = HouseConsignments.ToDictionary(Function(h) h.zaHC_Id, Function(h) h.zaHC_Number)
For Each it In Items
If it.zaItem_HouseConsignmentId.HasValue AndAlso byId.ContainsKey(it.zaItem_HouseConsignmentId.Value) Then
it.zaItem_HouseConsignmentNumber = byId(it.zaItem_HouseConsignmentId.Value)
End If
Next
End Sub
' Separat nach SAVE(): ersetzt die NCTS-Kinddaten inkl. HC-Verknüpfung.
Public Sub SAVE_TRANSIT()
If za_Id <= 0 Then Throw New InvalidOperationException("Zuerst SAVE() aufrufen.")
cVERAG_NCTS_Repository.SaveTransit(za_Id, HouseConsignments, TransitGuarantees, TransitOffices, Items)
End Sub
' Alle Standarddaten inkl. Packages in EINER Transaktion speichern.
Public Function SAVE() As Boolean
cVERAG_CustomsDeclarations_SaveRepository.Save(Me)
Return za_Id > 0
End Function
End Class
Public Class cVERAG_CustomsDeclarations_Parties
Public Property zaParty_Id As Integer
Public Property zaParty_zaId As Integer
Public Property zaParty_Role As String
Public Property zaParty_EORI As String
Public Property zaParty_SubsidiaryNumber As String
Public Property zaParty_EORI_NL As String
Public Property zaParty_Name As String
Public Property zaParty_Street As String
Public Property zaParty_PostalCode As String
Public Property zaParty_City As String
Public Property zaParty_Country As String
Public Property zaParty_TIN As String
Public Property zaParty_VATNumber As String
Public Property zaParty_TaxOffice As String
Public Property zaParty_ContactName As String
Public Property zaParty_Phone As String
Public Property zaParty_Email As String
Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
Public Function getParameterList() As List(Of SQLVariable)
Return New List(Of SQLVariable) From {
New SQLVariable("zaParty_Id", zaParty_Id,, True),
New SQLVariable("zaParty_zaId", zaParty_zaId),
New SQLVariable("zaParty_Role", zaParty_Role),
New SQLVariable("zaParty_EORI", zaParty_EORI),
New SQLVariable("zaParty_SubsidiaryNumber", zaParty_SubsidiaryNumber),
New SQLVariable("zaParty_EORI_NL", zaParty_EORI_NL),
New SQLVariable("zaParty_Name", zaParty_Name),
New SQLVariable("zaParty_Street", zaParty_Street),
New SQLVariable("zaParty_PostalCode", zaParty_PostalCode),
New SQLVariable("zaParty_City", zaParty_City),
New SQLVariable("zaParty_Country", zaParty_Country),
New SQLVariable("zaParty_VATNumber", zaParty_VATNumber),
New SQLVariable("zaParty_TaxOffice", zaParty_TaxOffice),
New SQLVariable("zaParty_TIN", zaParty_TIN),
New SQLVariable("zaParty_ContactName", zaParty_ContactName),
New SQLVariable("zaParty_Phone", zaParty_Phone),
New SQLVariable("zaParty_Email", zaParty_Email)
}
End Function
Public Function getInsertCmd() As String
Dim f As String = "", v As String = ""
For Each i In getParameterList()
If Not i.isPrimaryParam Then
f &= "[" & i.Text & "],"
v &= "@" & i.Scalarvariable & ","
End If
Next
Return "INSERT INTO tblVERAG_CustomsDeclarations_Parties (" &
f.TrimEnd(","c) & ") VALUES (" & v.TrimEnd(","c) & ")"
End Function
Public Shared Sub REPLACE_ALL(zaId As Integer, list As List(Of cVERAG_CustomsDeclarations_Parties))
Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
SQL.doSQL("DELETE FROM tblVERAG_CustomsDeclarations_Parties WHERE zaParty_zaId=" & zaId, "FMZOLL")
For Each p In list
p.zaParty_zaId = zaId
p.zaParty_Id = SQL.doSQLVarListID(p.zaParty_Id, p.getInsertCmd(), "FMZOLL", , p.getParameterList())
Next
End Sub
Public Shared Function LOAD_BY_ZAID(zaId As Integer) As List(Of cVERAG_CustomsDeclarations_Parties)
Dim result As New List(Of cVERAG_CustomsDeclarations_Parties)
Try
Using conn As SqlConnection = SQL.GetNewOpenConnectionFMZOLL()
Using cmd As New SqlCommand(
"SELECT * FROM tblVERAG_CustomsDeclarations_Parties WHERE zaParty_zaId=@zaId",
conn)
cmd.Parameters.AddWithValue("@zaId", zaId)
Using dr As SqlDataReader = cmd.ExecuteReader()
While dr.Read()
Dim obj As New cVERAG_CustomsDeclarations_Parties
For Each li In obj.getParameterList()
Dim propInfo As PropertyInfo =
obj.GetType().GetProperty(li.Scalarvariable)
If dr.Item(li.Text) Is DBNull.Value Then
propInfo.SetValue(obj, Nothing)
Else
propInfo.SetValue(obj, dr.Item(li.Text))
End If
Next
result.Add(obj)
End While
End Using
End Using
End Using
Catch ex As Exception
VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(
ex.Message,
ex.StackTrace,
System.Reflection.MethodInfo.GetCurrentMethod.Name)
End Try
Return result
End Function
End Class
' ##########################################################
' ITEMS
' ##########################################################
Public Class cVERAG_CustomsDeclarations_Item
Public Property zaItem_Id As Integer
Public Property zaItem_zaId As Integer
Public Property zaItem_PosNo As Integer
Public Property zaItem_HouseConsignmentId As Integer?
Public Property zaItem_HouseConsignmentNumber As Integer? ' Transient mapping before SAVE_TRANSIT
Public Property zaItem_ExportUCR As String
Public Property zaItem_ExportRegionDispatch As String
Public Property zaItem_ExportCountry As String
Public Property zaItem_ExportNatureOfTransaction As String
Public Property zaItem_ExportStatCurrency As String
Public Property zaItem_ExportCUSCode As String
Public Property zaItem_ExportRegistrationExternal As String
Public Property zaItem_ArticleCode As String
Public Property zaItem_HSCode As String
Public Property zaItem_HSAddition1 As String
Public Property zaItem_HSAddition2 As String
Public Property zaItem_HSAddCodes1 As String
Public Property zaItem_HSAddCodes2 As String
Public Property zaItem_HSAddCodes3 As String
Public Property zaItem_HSAddCodes4 As String
Public Property zaItem_HSAddCodes5 As String
Public Property zaItem_HSAddCodes6 As String
Public Property zaItem_HSAddCodes7 As String
Public Property zaItem_HSAddCodes8 As String
Public Property zaItem_HSAddCodes9 As String
Public Property zaItem_HSAddCodes10 As String
Public Property zaItem_Description As String
Public Property Packages As New List(Of cVERAG_CustomsDeclarations_ItemPackage)
Public Property zaItem_PackageColli As String
Public Property zaItem_PackageType As String
Public Property zaItem_PackageMark As String
Public Property zaItem_OriginCountry As String
Public Property zaItem_PreferentialCountry As String
Public Property zaItem_PreferenceCode As String
Public Property zaItem_QuotaNo As String
Public Property zaItem_MainProcedure As String
Public Property zaItem_AdditionalProc As String
Public Property zaItem_PrevProcedure As String
Public Property zaItem_GrossMass As Decimal?
Public Property zaItem_NetMass As Decimal?
Public Property zaItem_SuppUnitCode As String
Public Property zaItem_SuppQuantity As Decimal?
Public Property zaItem_StatisticalValueEUR As Decimal?
Public Property zaItem_CustomsValueEUR As Decimal?
Public Property zaItem_InvoiceCurrency As String
Public Property zaItem_InvoiceValueForeign As Decimal?
Public Property zaItem_InvoiceValueEUR As Decimal?
Public Property zaItem_BeguenstigungCode As String
Public Property zaItem_DV1Flag As Boolean?
Public Property zaItem_PosAddition As String
Public Property zaItem_Remarks As String
Public Property Documents As New List(Of cVERAG_CustomsDeclarations_Document)
' Duties auf Positionsebene; werden mit zaDuty_zaItemId = zaItem_Id gespeichert
Public Property Duties As New List(Of cVERAG_CustomsDeclarations_Duty)
Public Property hasEntry As Boolean = False
Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
Public Function getParameterList() As List(Of SQLVariable)
Return New List(Of SQLVariable) From {
New SQLVariable("zaItem_Id", zaItem_Id,, True),
New SQLVariable("zaItem_zaId", zaItem_zaId),
New SQLVariable("zaItem_PosNo", zaItem_PosNo),
New SQLVariable("zaItem_HouseConsignmentId", zaItem_HouseConsignmentId),
New SQLVariable("zaItem_ExportUCR", zaItem_ExportUCR),
New SQLVariable("zaItem_ExportRegionDispatch", zaItem_ExportRegionDispatch),
New SQLVariable("zaItem_ExportCountry", zaItem_ExportCountry),
New SQLVariable("zaItem_ExportNatureOfTransaction", zaItem_ExportNatureOfTransaction),
New SQLVariable("zaItem_ExportStatCurrency", zaItem_ExportStatCurrency),
New SQLVariable("zaItem_ExportCUSCode", zaItem_ExportCUSCode),
New SQLVariable("zaItem_ExportRegistrationExternal", zaItem_ExportRegistrationExternal),
New SQLVariable("zaItem_ArticleCode", zaItem_ArticleCode),
New SQLVariable("zaItem_HSCode", zaItem_HSCode),
New SQLVariable("zaItem_HSAddition1", zaItem_HSAddition1),
New SQLVariable("zaItem_HSAddition2", zaItem_HSAddition2),
New SQLVariable("zaItem_HSAddCodes1", zaItem_HSAddCodes1),
New SQLVariable("zaItem_HSAddCodes2", zaItem_HSAddCodes2),
New SQLVariable("zaItem_HSAddCodes3", zaItem_HSAddCodes3),
New SQLVariable("zaItem_HSAddCodes4", zaItem_HSAddCodes4),
New SQLVariable("zaItem_HSAddCodes5", zaItem_HSAddCodes5),
New SQLVariable("zaItem_HSAddCodes6", zaItem_HSAddCodes6),
New SQLVariable("zaItem_HSAddCodes7", zaItem_HSAddCodes7),
New SQLVariable("zaItem_HSAddCodes8", zaItem_HSAddCodes8),
New SQLVariable("zaItem_HSAddCodes9", zaItem_HSAddCodes9),
New SQLVariable("zaItem_HSAddCodes10", zaItem_HSAddCodes10),
New SQLVariable("zaItem_Description", zaItem_Description),
New SQLVariable("zaItem_PackageColli", zaItem_PackageColli),
New SQLVariable("zaItem_PackageType", zaItem_PackageType),
New SQLVariable("zaItem_PackageMark", zaItem_PackageMark),
New SQLVariable("zaItem_OriginCountry", zaItem_OriginCountry),
New SQLVariable("zaItem_PreferentialCountry", zaItem_PreferentialCountry),
New SQLVariable("zaItem_PreferenceCode", zaItem_PreferenceCode),
New SQLVariable("zaItem_QuotaNo", zaItem_QuotaNo),
New SQLVariable("zaItem_MainProcedure", zaItem_MainProcedure),
New SQLVariable("zaItem_AdditionalProc", zaItem_AdditionalProc),
New SQLVariable("zaItem_PrevProcedure", zaItem_PrevProcedure),
New SQLVariable("zaItem_GrossMass", zaItem_GrossMass),
New SQLVariable("zaItem_NetMass", zaItem_NetMass),
New SQLVariable("zaItem_SuppUnitCode", zaItem_SuppUnitCode),
New SQLVariable("zaItem_SuppQuantity", zaItem_SuppQuantity),
New SQLVariable("zaItem_StatisticalValueEUR", zaItem_StatisticalValueEUR),
New SQLVariable("zaItem_CustomsValueEUR", zaItem_CustomsValueEUR),
New SQLVariable("zaItem_InvoiceCurrency", zaItem_InvoiceCurrency),
New SQLVariable("zaItem_InvoiceValueForeign", zaItem_InvoiceValueForeign),
New SQLVariable("zaItem_InvoiceValueEUR", zaItem_InvoiceValueEUR),
New SQLVariable("zaItem_BeguenstigungCode", zaItem_BeguenstigungCode),
New SQLVariable("zaItem_DV1Flag", zaItem_DV1Flag),
New SQLVariable("zaItem_PosAddition", zaItem_PosAddition),
New SQLVariable("zaItem_Remarks", zaItem_Remarks)
}
End Function
Public Function getInsertCmd() As String
Dim f As String = "", v As String = ""
For Each i In getParameterList()
If Not i.isPrimaryParam Then
f &= "[" & i.Text & "],"
v &= "@" & i.Scalarvariable & ","
End If
Next
Return "INSERT INTO tblVERAG_CustomsDeclarations_Items (" &
f.TrimEnd(","c) & ") VALUES (" & v.TrimEnd(","c) & ")"
End Function
' ---------- DELETE + INSERT ----------
' Auch direkte Aufrufer speichern Positionen, Dokumente, Abgaben und Packstücke atomar.
Public Shared Sub REPLACE_ALL(zaId As Integer, list As List(Of cVERAG_CustomsDeclarations_Item))
cVERAG_CustomsDeclarations_SaveRepository.ReplaceItems(zaId, list)
End Sub
Public Shared Function LOAD_BY_ZAID(zaId As Integer, Optional where As String = "") As List(Of cVERAG_CustomsDeclarations_Item)
Dim result As New List(Of cVERAG_CustomsDeclarations_Item)
Try
Using conn As SqlConnection = SQL.GetNewOpenConnectionFMZOLL()
Using cmd As New SqlCommand(
"SELECT * FROM tblVERAG_CustomsDeclarations_Items WHERE zaItem_zaId=@zaId " & where, conn)
cmd.Parameters.AddWithValue("@zaId", zaId)
Using dr As SqlDataReader = cmd.ExecuteReader()
While dr.Read()
Dim it As New cVERAG_CustomsDeclarations_Item
it.hasEntry = False
For Each li In it.getParameterList()
Dim pi As PropertyInfo =
it.GetType().GetProperty(li.Scalarvariable)
If dr.Item(li.Text) Is DBNull.Value Then
pi.SetValue(it, Nothing)
Else
pi.SetValue(it, dr.Item(li.Text))
End If
Next
it.hasEntry = True
result.Add(it)
End While
End Using
End Using
End Using
' ===== Documents und Duties NACHLADEN (pro Item) =====
For Each it In result
it.Documents =
cVERAG_CustomsDeclarations_Document.LOAD_ITEM_BY_ITEMID(zaId, it.zaItem_Id)
it.Duties =
cVERAG_CustomsDeclarations_Duty.LOAD_ITEM_BY_ITEMID(zaId, it.zaItem_Id)
it.Packages = cVERAG_CustomsDeclarations_ItemPackage.LOAD_ITEM(it.zaItem_Id)
Next
Catch ex As Exception
VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
End Try
Return result
End Function
Public Function GetInvoiceListString() As String
If Documents Is Nothing OrElse Documents.Count = 0 Then Return ""
Dim result = Documents.
Where(Function(d) Not d Is Nothing AndAlso
(d.zaDoc_Code = "N380" OrElse d.zaDoc_Code = "N325")).
Select(Function(d)
Dim datum As String = If(String.IsNullOrWhiteSpace(d.zaDoc_Date), "", d.zaDoc_Date.Trim())
Dim ref As String = If(String.IsNullOrWhiteSpace(d.zaDoc_Reference), "", d.zaDoc_Reference.Trim())
' Format: "Datum Referenz"
Return (datum & " " & ref).Trim()
End Function).
Where(Function(s) Not String.IsNullOrWhiteSpace(s)).
Distinct().
ToList()
Return String.Join(", ", result)
End Function
End Class
' ##########################################################
' DUTIES
' ##########################################################
Public Class cVERAG_CustomsDeclarations_Duty
Public Property zaDuty_Id As Integer
Public Property zaDuty_zaId As Integer
' NULL = Duty auf Kopfebene; Wert = Duty gehört zur jeweiligen Position
Public Property zaDuty_zaItemId As Integer?
Public Property zaDuty_AccountType As String
Public Property zaDuty_AccountHeadCustoms As String
Public Property zaDuty_ApplicationType As String
Public Property zaDuty_AccountNo As String
Public Property zaDuty_AccountEORI As String
Public Property zaDuty_AccountHolderName As String
Public Property zaDuty_DutyType As String
Public Property zaDuty_BIN As String
Public Property zaDuty_AmountEUR As Decimal?
Public Property zaDuty_AmountForeign As Decimal?
Public Property zaDuty_Currency As String
Public Property zaDuty_LimitDate As Date?
Public Property zaDuty_Prozentsatz As Decimal?
Public Property hasEntry As Boolean = False
Public Function getParameterList() As List(Of SQLVariable)
Return New List(Of SQLVariable) From {
New SQLVariable("zaDuty_Id", zaDuty_Id,, True),
New SQLVariable("zaDuty_zaId", zaDuty_zaId),
New SQLVariable("zaDuty_zaItemId", zaDuty_zaItemId),
New SQLVariable("zaDuty_AccountType", zaDuty_AccountType),
New SQLVariable("zaDuty_AccountHeadCustoms", zaDuty_AccountHeadCustoms),
New SQLVariable("zaDuty_ApplicationType", zaDuty_ApplicationType),
New SQLVariable("zaDuty_AccountNo", zaDuty_AccountNo),
New SQLVariable("zaDuty_AccountEORI", zaDuty_AccountEORI),
New SQLVariable("zaDuty_AccountHolderName", zaDuty_AccountHolderName),
New SQLVariable("zaDuty_DutyType", zaDuty_DutyType),
New SQLVariable("zaDuty_BIN", zaDuty_BIN),
New SQLVariable("zaDuty_AmountEUR", zaDuty_AmountEUR),
New SQLVariable("zaDuty_AmountForeign", zaDuty_AmountForeign),
New SQLVariable("zaDuty_Currency", zaDuty_Currency),
New SQLVariable("zaDuty_LimitDate", zaDuty_LimitDate),
New SQLVariable("zaDuty_Prozentsatz", zaDuty_Prozentsatz)
}
End Function
Public Function getInsertCmd() As String
Dim f As String = "", v As String = ""
For Each i In getParameterList()
If Not i.isPrimaryParam Then
f &= "[" & i.Text & "],"
v &= "@" & i.Scalarvariable & ","
End If
Next
Return "INSERT INTO tblVERAG_CustomsDeclarations_Duties (" &
f.TrimEnd(","c) & ") VALUES (" & v.TrimEnd(","c) & ")"
End Function
' ---------- DELETE + INSERT ----------
Public Shared Sub REPLACE_HEAD(zaId As Integer, list As List(Of cVERAG_CustomsDeclarations_Duty))
Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
' Nur Header-Duties löschen
SQL.doSQL("DELETE FROM tblVERAG_CustomsDeclarations_Duties WHERE zaDuty_zaId=" & zaId & " AND zaDuty_zaItemId IS NULL", "FMZOLL")
If list Is Nothing Then Exit Sub
For Each d In list
d.zaDuty_zaId = zaId
d.zaDuty_zaItemId = Nothing
d.zaDuty_Id = SQL.doSQLVarListID(d.zaDuty_Id, d.getInsertCmd(), "FMZOLL", , d.getParameterList())
Next
End Sub
Public Shared Sub INSERT_ITEM(zaId As Integer, itemId As Integer, list As List(Of cVERAG_CustomsDeclarations_Duty))
Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
If list Is Nothing Then Exit Sub
For Each d In list
d.zaDuty_zaId = zaId
d.zaDuty_zaItemId = itemId
d.zaDuty_Id = SQL.doSQLVarListID(d.zaDuty_Id, d.getInsertCmd(), "FMZOLL", , d.getParameterList())
Next
End Sub
Public Shared Function LOAD_HEAD_BY_ZAID(zaId As Integer) As List(Of cVERAG_CustomsDeclarations_Duty)
Return LOAD_BY_WHERE(zaId, " AND zaDuty_zaItemId IS NULL")
End Function
Public Shared Function LOAD_ITEM_BY_ITEMID(zaId As Integer, itemId As Integer) As List(Of cVERAG_CustomsDeclarations_Duty)
Return LOAD_BY_WHERE(zaId, " AND zaDuty_zaItemId=" & itemId)
End Function
Public Shared Function LOAD_BY_ZAID(zaId As Integer) As List(Of cVERAG_CustomsDeclarations_Duty)
' Kompatibilität: lädt weiterhin alle Duties zur Anmeldung
Return LOAD_BY_WHERE(zaId, "")
End Function
Private Shared Function LOAD_BY_WHERE(zaId As Integer, Optional where As String = "") As List(Of cVERAG_CustomsDeclarations_Duty)
Dim result As New List(Of cVERAG_CustomsDeclarations_Duty)
Try
Using conn As SqlConnection = SQL.GetNewOpenConnectionFMZOLL()
Using cmd As New SqlCommand(
"SELECT * FROM tblVERAG_CustomsDeclarations_Duties WHERE zaDuty_zaId=@zaId " & where,
conn)
cmd.Parameters.AddWithValue("@zaId", zaId)
Using dr As SqlDataReader = cmd.ExecuteReader()
While dr.Read
Dim d As New cVERAG_CustomsDeclarations_Duty
d.hasEntry = False
For Each li In d.getParameterList()
Dim pi As PropertyInfo =
d.GetType().GetProperty(li.Scalarvariable)
If pi Is Nothing Then Continue For
If dr.Item(li.Text) Is DBNull.Value Then
pi.SetValue(d, Nothing)
Else
pi.SetValue(d, dr.Item(li.Text))
End If
Next
d.hasEntry = True
result.Add(d)
End While
End Using
End Using
End Using
Catch ex As Exception
VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(
ex.Message,
ex.StackTrace,
System.Reflection.MethodInfo.GetCurrentMethod.Name)
End Try
Return result
End Function
End Class
' ##########################################################
' DOCUMENTS (HEAD + ITEM)
' ##########################################################
Public Class cVERAG_CustomsDeclarations_Document
Public Property zaDoc_Id As Integer
Public Property zaDoc_zaId As Integer
Public Property zaDoc_ItemId As Integer?
Public Property zaDoc_Date As String
Public Property zaDoc_Section As String
Public Property zaDoc_Code As String
Public Property zaDoc_Presentation As String
Public Property zaDoc_DepreciationAmount As String
Public Property zaDoc_DepreciationUnitmeasurement As String
Public Property zaDoc_DepreciationUnitmeasurementQualifier As String
Public Property zaDoc_Reference As String
Public Property zaDoc_Description As String
Public Property hasEntry As Boolean = False
Public Function getParameterList() As List(Of SQLVariable)
Return New List(Of SQLVariable) From {
New SQLVariable("zaDoc_Id", zaDoc_Id,, True),
New SQLVariable("zaDoc_zaId", zaDoc_zaId),
New SQLVariable("zaDoc_ItemId", zaDoc_ItemId),
New SQLVariable("zaDoc_Date", zaDoc_Date),
New SQLVariable("zaDoc_Section", zaDoc_Section),
New SQLVariable("zaDoc_Code", zaDoc_Code),
New SQLVariable("zaDoc_Reference", zaDoc_Reference),
New SQLVariable("zaDoc_Presentation", zaDoc_Presentation),
New SQLVariable("zaDoc_DepreciationAmount", zaDoc_DepreciationAmount),
New SQLVariable("zaDoc_DepreciationUnitmeasurement", zaDoc_DepreciationUnitmeasurement),
New SQLVariable("zaDoc_DepreciationUnitmeasurementQualifier", zaDoc_DepreciationUnitmeasurementQualifier),
New SQLVariable("zaDoc_Description", zaDoc_Description)
}
End Function
Public Function getInsertCmd() As String
Dim f As String = "", v As String = ""
For Each i In getParameterList()
If Not i.isPrimaryParam Then
f &= "[" & i.Text & "],"
v &= "@" & i.Scalarvariable & ","
End If
Next
Return "INSERT INTO tblVERAG_CustomsDeclarations_Documents (" &
f.TrimEnd(","c) & ") VALUES (" & v.TrimEnd(","c) & ")"
End Function
' ---------- DELETE + INSERT ----------
Public Shared Sub REPLACE_HEAD(zaId As Integer, list As List(Of cVERAG_CustomsDeclarations_Document))
Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
SQL.doSQL(
"DELETE FROM tblVERAG_CustomsDeclarations_Documents
WHERE zaDoc_zaId=" & zaId & " AND zaDoc_ItemId IS NULL",
"FMZOLL")
For Each d In list
d.zaDoc_zaId = zaId
d.zaDoc_ItemId = Nothing
d.zaDoc_Id = SQL.doSQLVarListID(d.zaDoc_Id, d.getInsertCmd(), "FMZOLL", , d.getParameterList())
Next
End Sub
Public Shared Sub INSERT_ITEM(zaId As Integer, itemId As Integer, list As List(Of cVERAG_CustomsDeclarations_Document))
Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
For Each d In list
d.zaDoc_zaId = zaId
d.zaDoc_ItemId = itemId
d.zaDoc_Id = SQL.doSQLVarListID(d.zaDoc_Id, d.getInsertCmd(), "FMZOLL", , d.getParameterList())
Next
End Sub
Public Shared Function LOAD_HEAD_BY_ZAID(zaId As Integer) As List(Of cVERAG_CustomsDeclarations_Document)
Return LOAD_BY_SQL(
"SELECT * FROM tblVERAG_CustomsDeclarations_Documents
WHERE zaDoc_zaId=" & zaId & " AND zaDoc_ItemId IS NULL")
End Function
Public Shared Function LOAD_ITEM_BY_ITEMID(zaId As Integer, itemId As Integer) As List(Of cVERAG_CustomsDeclarations_Document)
Return LOAD_BY_SQL(
"SELECT * FROM tblVERAG_CustomsDeclarations_Documents
WHERE zaDoc_zaId=" & zaId & " AND zaDoc_ItemId=" & itemId)
End Function
Private Shared Function LOAD_BY_SQL(sqlstr As String) _
As List(Of cVERAG_CustomsDeclarations_Document)
Dim result As New List(Of cVERAG_CustomsDeclarations_Document)
Try
Using conn As SqlConnection = SQL.GetNewOpenConnectionFMZOLL()
Using cmd As New SqlCommand(sqlstr, conn)
Using dr As SqlDataReader = cmd.ExecuteReader()
While dr.Read()
Dim d As New cVERAG_CustomsDeclarations_Document
d.hasEntry = False
' ===== DEINE LOAD-VORLAGE (1:1, kombiniert) =====
For Each li In d.getParameterList()
Dim pi As PropertyInfo =
d.GetType().GetProperty(li.Scalarvariable)
If dr.Item(li.Text) Is DBNull.Value Then
pi.SetValue(d, Nothing)
Else
pi.SetValue(d, dr.Item(li.Text))
End If
Next
d.hasEntry = True
result.Add(d)
End While
End Using
End Using
End Using
Catch ex As Exception
VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(
ex.Message,
ex.StackTrace,
System.Reflection.MethodInfo.GetCurrentMethod.Name)
End Try
Return result
End Function
End Class
' ==========================================================================
' NCTS-Erweiterung. Die vorhandene SAVE()-Methode speichert weiterhin Importdaten.
' Für Transit nach SAVE() zusätzlich SAVE_TRANSIT() aufrufen.
' ==========================================================================
Public Class cVERAG_CustomsDeclarations_HouseConsignment
Public Property zaHC_Id As Integer
Public Property zaHC_Number As Integer
Public Property zaHC_Reference As String
Public Property zaHC_UCR As String
Public Property zaHC_CountryDispatch As String
Public Property zaHC_CountryDestination As String
Public Property zaHC_GrossMass As Decimal?
End Class
Public Class cVERAG_CustomsDeclarations_TransitGuarantee
Public Property zaGRT_Type As String
Public Property zaGRT_GRN As String
Public Property zaGRT_Reference As String
Public Property zaGRT_Amount As Decimal?
Public Property zaGRT_Currency As String
Public Property zaGRT_AmountForeign As Decimal?
Public Property zaGRT_CurrencyForeign As String
Public Property zaGRT_ExchangeRateToEUR As Decimal?
End Class
Public Class cVERAG_CustomsDeclarations_TransitOffice
Public Property zaTO_Sequence As Integer
Public Property zaTO_Office As String
Public Property zaTO_ExpectedArrival As Date?
End Class
Public NotInheritable Class cVERAG_NCTS_Repository
Private Sub New()
End Sub
Private Shared Function Db(v As Object) As Object
Return If(v Is Nothing, CType(DBNull.Value, Object), v)
End Function
Private Shared Sub Add(cmd As SqlCommand, name As String, value As Object)
cmd.Parameters.AddWithValue(name, Db(value))
End Sub
Private Shared Function OpenConnection() As SqlConnection
Return (New VERAG_PROG_ALLGEMEIN.SQL).GetNewOpenConnectionFMZOLL()
End Function
Public Shared Function LoadHouses(zaId As Integer) As List(Of cVERAG_CustomsDeclarations_HouseConsignment)
Dim result As New List(Of cVERAG_CustomsDeclarations_HouseConsignment)
Using cn = OpenConnection(), cmd As New SqlCommand("SELECT * FROM dbo.tblVERAG_CustomsDeclarations_HouseConsignments WHERE zaHC_zaId=@id ORDER BY zaHC_Number", cn)
Add(cmd, "@id", zaId)
Using r = cmd.ExecuteReader()
While r.Read()
result.Add(New cVERAG_CustomsDeclarations_HouseConsignment With {
.zaHC_Id = CInt(r("zaHC_Id")), .zaHC_Number = CInt(r("zaHC_Number")),
.zaHC_Reference = If(r.IsDBNull(r.GetOrdinal("zaHC_Reference")), Nothing, CStr(r("zaHC_Reference"))),
.zaHC_UCR = If(r.IsDBNull(r.GetOrdinal("zaHC_UCR")), Nothing, CStr(r("zaHC_UCR"))),
.zaHC_CountryDispatch = If(r.IsDBNull(r.GetOrdinal("zaHC_CountryDispatch")), Nothing, CStr(r("zaHC_CountryDispatch"))),
.zaHC_CountryDestination = If(r.IsDBNull(r.GetOrdinal("zaHC_CountryDestination")), Nothing, CStr(r("zaHC_CountryDestination"))),
.zaHC_GrossMass = If(r.IsDBNull(r.GetOrdinal("zaHC_GrossMass")), CType(Nothing, Decimal?), CDec(r("zaHC_GrossMass")))})
End While
End Using
End Using
Return result
End Function
Public Shared Function LoadGuarantees(zaId As Integer) As List(Of cVERAG_CustomsDeclarations_TransitGuarantee)
Dim result As New List(Of cVERAG_CustomsDeclarations_TransitGuarantee)
Using cn = OpenConnection(), cmd As New SqlCommand("SELECT * FROM dbo.tblVERAG_CustomsDeclarations_TransitGuarantees WHERE zaGRT_zaId=@id ORDER BY zaGRT_Id", cn)
Add(cmd, "@id", zaId)
Using r = cmd.ExecuteReader()
While r.Read()
result.Add(New cVERAG_CustomsDeclarations_TransitGuarantee With {
.zaGRT_Type = If(r.IsDBNull(r.GetOrdinal("zaGRT_Type")), Nothing, CStr(r("zaGRT_Type"))),
.zaGRT_GRN = If(r.IsDBNull(r.GetOrdinal("zaGRT_GRN")), Nothing, CStr(r("zaGRT_GRN"))),
.zaGRT_Reference = If(r.IsDBNull(r.GetOrdinal("zaGRT_Reference")), Nothing, CStr(r("zaGRT_Reference"))),
.zaGRT_Amount = If(r.IsDBNull(r.GetOrdinal("zaGRT_Amount")), CType(Nothing, Decimal?), CDec(r("zaGRT_Amount"))),
.zaGRT_Currency = If(r.IsDBNull(r.GetOrdinal("zaGRT_Currency")), Nothing, CStr(r("zaGRT_Currency"))),
.zaGRT_AmountForeign = If(r.IsDBNull(r.GetOrdinal("zaGRT_AmountForeign")), CType(Nothing, Decimal?), CDec(r("zaGRT_AmountForeign"))),
.zaGRT_CurrencyForeign = If(r.IsDBNull(r.GetOrdinal("zaGRT_CurrencyForeign")), Nothing, CStr(r("zaGRT_CurrencyForeign"))),
.zaGRT_ExchangeRateToEUR = If(r.IsDBNull(r.GetOrdinal("zaGRT_ExchangeRateToEUR")), CType(Nothing, Decimal?), CDec(r("zaGRT_ExchangeRateToEUR")))})
End While
End Using
End Using
Return result
End Function
Public Shared Function LoadOffices(zaId As Integer) As List(Of cVERAG_CustomsDeclarations_TransitOffice)
Dim result As New List(Of cVERAG_CustomsDeclarations_TransitOffice)
Using cn = OpenConnection(), cmd As New SqlCommand("SELECT * FROM dbo.tblVERAG_CustomsDeclarations_TransitOffices WHERE zaTO_zaId=@id ORDER BY zaTO_Sequence", cn)
Add(cmd, "@id", zaId)
Using r = cmd.ExecuteReader()
While r.Read()
result.Add(New cVERAG_CustomsDeclarations_TransitOffice With {
.zaTO_Sequence = CInt(r("zaTO_Sequence")), .zaTO_Office = CStr(r("zaTO_Office")),
.zaTO_ExpectedArrival = If(r.IsDBNull(r.GetOrdinal("zaTO_ExpectedArrival")), CType(Nothing, Date?), CDate(r("zaTO_ExpectedArrival")))})
End While
End Using
End Using
Return result
End Function
Public Shared Sub SaveTransit(zaId As Integer, houses As List(Of cVERAG_CustomsDeclarations_HouseConsignment), guarantees As List(Of cVERAG_CustomsDeclarations_TransitGuarantee), offices As List(Of cVERAG_CustomsDeclarations_TransitOffice), items As List(Of cVERAG_CustomsDeclarations_Item))
Using cn = OpenConnection(), tx = cn.BeginTransaction()
Try
' Zuerst alte HC-Verweise lösen, dann HC neu aufbauen.
Execute(cn, tx, "UPDATE dbo.tblVERAG_CustomsDeclarations_Items SET zaItem_HouseConsignmentId=NULL WHERE zaItem_zaId=@id", zaId)
Execute(cn, tx, "DELETE FROM dbo.tblVERAG_CustomsDeclarations_HouseConsignments WHERE zaHC_zaId=@id", zaId)
Execute(cn, tx, "DELETE FROM dbo.tblVERAG_CustomsDeclarations_TransitGuarantees WHERE zaGRT_zaId=@id", zaId)
Execute(cn, tx, "DELETE FROM dbo.tblVERAG_CustomsDeclarations_TransitOffices WHERE zaTO_zaId=@id", zaId)
Dim houseIds As New Dictionary(Of Integer, Integer)
For Each h In If(houses, New List(Of cVERAG_CustomsDeclarations_HouseConsignment))
Using cmd As New SqlCommand("INSERT INTO dbo.tblVERAG_CustomsDeclarations_HouseConsignments (zaHC_zaId,zaHC_Number,zaHC_Reference,zaHC_UCR,zaHC_CountryDispatch,zaHC_CountryDestination,zaHC_GrossMass) OUTPUT INSERTED.zaHC_Id VALUES (@id,@n,@r,@u,@d,@c,@m)", cn, tx)
Add(cmd, "@id", zaId) : Add(cmd, "@n", h.zaHC_Number) : Add(cmd, "@r", h.zaHC_Reference)
Add(cmd, "@u", h.zaHC_UCR) : Add(cmd, "@d", h.zaHC_CountryDispatch)
Add(cmd, "@c", h.zaHC_CountryDestination) : Add(cmd, "@m", h.zaHC_GrossMass)
h.zaHC_Id = CInt(cmd.ExecuteScalar())
houseIds.Add(h.zaHC_Number, h.zaHC_Id)
End Using
Next
For Each it In If(items, New List(Of cVERAG_CustomsDeclarations_Item))
If it.zaItem_HouseConsignmentNumber.HasValue Then
If Not houseIds.ContainsKey(it.zaItem_HouseConsignmentNumber.Value) Then Throw New InvalidOperationException("Unbekannte House-Nummer: " & it.zaItem_HouseConsignmentNumber.Value)
Using cmd As New SqlCommand("UPDATE dbo.tblVERAG_CustomsDeclarations_Items SET zaItem_HouseConsignmentId=@hc WHERE zaItem_Id=@item AND zaItem_zaId=@id", cn, tx)
Add(cmd, "@hc", houseIds(it.zaItem_HouseConsignmentNumber.Value)) : Add(cmd, "@item", it.zaItem_Id) : Add(cmd, "@id", zaId)
If cmd.ExecuteNonQuery() <> 1 Then Throw New InvalidOperationException("Position nicht gefunden: " & it.zaItem_Id)
End Using
End If
Next
For Each g In If(guarantees, New List(Of cVERAG_CustomsDeclarations_TransitGuarantee))
Using cmd As New SqlCommand("INSERT INTO dbo.tblVERAG_CustomsDeclarations_TransitGuarantees (zaGRT_zaId,zaGRT_Type,zaGRT_GRN,zaGRT_Reference,zaGRT_Amount,zaGRT_Currency,zaGRT_AmountForeign,zaGRT_CurrencyForeign,zaGRT_ExchangeRateToEUR) VALUES (@id,@t,@g,@r,@a,@c,@af,@cf,@rate)", cn, tx)
Add(cmd, "@id", zaId) : Add(cmd, "@t", g.zaGRT_Type) : Add(cmd, "@g", g.zaGRT_GRN)
Add(cmd, "@r", g.zaGRT_Reference) : Add(cmd, "@a", g.zaGRT_Amount) : Add(cmd, "@c", "EUR")
Add(cmd, "@af", g.zaGRT_AmountForeign) : Add(cmd, "@cf", g.zaGRT_CurrencyForeign) : Add(cmd, "@rate", g.zaGRT_ExchangeRateToEUR)
cmd.ExecuteNonQuery()
End Using
Next
For Each o In If(offices, New List(Of cVERAG_CustomsDeclarations_TransitOffice))
Using cmd As New SqlCommand("INSERT INTO dbo.tblVERAG_CustomsDeclarations_TransitOffices (zaTO_zaId,zaTO_Sequence,zaTO_Office,zaTO_ExpectedArrival) VALUES (@id,@n,@o,@d)", cn, tx)
Add(cmd, "@id", zaId) : Add(cmd, "@n", o.zaTO_Sequence)
Add(cmd, "@o", o.zaTO_Office) : Add(cmd, "@d", o.zaTO_ExpectedArrival)
cmd.ExecuteNonQuery()
End Using
Next
tx.Commit()
Catch
tx.Rollback()
Throw
End Try
End Using
End Sub
Private Shared Sub Execute(cn As SqlConnection, tx As SqlTransaction, sqlText As String, zaId As Integer)
Using cmd As New SqlCommand(sqlText, cn, tx)
Add(cmd, "@id", zaId)
cmd.ExecuteNonQuery()
End Using
End Sub
End Class
' Gemeinsame Packstücke für IMPORT, EXPORT und TRANSIT.
' Bei TRANSIT wird die House-Consignment-Zuordnung über die Warenposition hergestellt.
' Bestehende zaItem_Package*-Felder bleiben für ältere Datensätze erhalten;
' neue Packstücke ausschließlich über Packages speichern, nicht parallel duplizieren.
Public Class cVERAG_CustomsDeclarations_ItemPackage
Public Property zaPkg_Id As Integer
Public Property zaPkg_zaItemId As Integer
Public Property zaPkg_Type As String
Public Property zaPkg_Number As Integer?
Public Property zaPkg_Marks As String
Public Shared Function LOAD_ITEM(itemId As Integer) As List(Of cVERAG_CustomsDeclarations_ItemPackage)
Dim result As New List(Of cVERAG_CustomsDeclarations_ItemPackage)
Dim sql As New VERAG_PROG_ALLGEMEIN.SQL
Using cn As SqlConnection = SQL.GetNewOpenConnectionFMZOLL()
Using cmd As New SqlCommand("SELECT zaPkg_Id,zaPkg_zaItemId,zaPkg_Type,zaPkg_Number,zaPkg_Marks FROM dbo.tblVERAG_CustomsDeclarations_ItemPackages WHERE zaPkg_zaItemId=@id ORDER BY zaPkg_Id", cn)
cmd.Parameters.AddWithValue("@id", itemId)
Using dr As SqlDataReader = cmd.ExecuteReader()
While dr.Read()
Dim pkg As New cVERAG_CustomsDeclarations_ItemPackage With {
.zaPkg_Id = CInt(dr("zaPkg_Id")),
.zaPkg_zaItemId = CInt(dr("zaPkg_zaItemId")),
.zaPkg_Type = If(dr.IsDBNull(dr.GetOrdinal("zaPkg_Type")), Nothing, CStr(dr("zaPkg_Type"))),
.zaPkg_Marks = If(dr.IsDBNull(dr.GetOrdinal("zaPkg_Marks")), Nothing, CStr(dr("zaPkg_Marks")))
}
If Not dr.IsDBNull(dr.GetOrdinal("zaPkg_Number")) Then pkg.zaPkg_Number = CInt(dr("zaPkg_Number"))
result.Add(pkg)
End While
End Using
End Using
End Using
Return result
End Function
Public Shared Sub INSERT_ITEM(itemId As Integer, packages As List(Of cVERAG_CustomsDeclarations_ItemPackage))
If packages Is Nothing OrElse packages.Count = 0 Then Return
Dim sql As New VERAG_PROG_ALLGEMEIN.SQL
Using cn As SqlConnection = SQL.GetNewOpenConnectionFMZOLL()
For Each pkg In packages
Using cmd As New SqlCommand("INSERT INTO dbo.tblVERAG_CustomsDeclarations_ItemPackages (zaPkg_zaItemId,zaPkg_Type,zaPkg_Number,zaPkg_Marks) VALUES (@id,@type,@number,@marks); SELECT CAST(SCOPE_IDENTITY() AS int)", cn)
cmd.Parameters.AddWithValue("@id", itemId)
cmd.Parameters.AddWithValue("@type", If(CType(pkg.zaPkg_Type, Object), DBNull.Value))
cmd.Parameters.AddWithValue("@number", If(CType(pkg.zaPkg_Number, Object), DBNull.Value))
cmd.Parameters.AddWithValue("@marks", If(CType(pkg.zaPkg_Marks, Object), DBNull.Value))
pkg.zaPkg_Id = CInt(cmd.ExecuteScalar())
pkg.zaPkg_zaItemId = itemId
End Using
Next
End Using
End Sub
End Class
' Atomarer Speicherpfad für Kopf/Parties/Items/Documents/Duties/Packages.
' NCTS-HouseConsignments/Guarantees/Offices bleiben vorerst bei SAVE_TRANSIT().
Public NotInheritable Class cVERAG_CustomsDeclarations_SaveRepository
Private Sub New()
End Sub
Private Shared Function Db(value As Object) As Object
Return If(value Is Nothing, CType(DBNull.Value, Object), value)
End Function
Private Shared Sub Execute(cn As SqlConnection, tx As SqlTransaction, statement As String, id As Integer)
Using cmd As New SqlCommand(statement, cn, tx)
cmd.Parameters.Add("@id", SqlDbType.Int).Value = id
cmd.ExecuteNonQuery()
End Using
End Sub
Private Shared Function WriteObject(cn As SqlConnection, tx As SqlTransaction, tableName As String, obj As Object, values As List(Of SQLVariable), Optional existingId As Integer = 0) As Integer
Dim fields = values.Where(Function(v) Not v.isPrimaryParam).ToList()
Dim pk = values.First(Function(v) v.isPrimaryParam).Text
Dim sqlText As String
If existingId > 0 Then
sqlText = "UPDATE dbo.[" & tableName & "] SET " & String.Join(",", fields.Select(Function(v) "[" & v.Text & "]= @" & v.Text)) & " WHERE [" & pk & "]= @__id"
Else
sqlText = "INSERT INTO dbo.[" & tableName & "] (" & String.Join(",", fields.Select(Function(v) "[" & v.Text & "]")) & ") OUTPUT INSERTED.[" & pk & "] VALUES (" & String.Join(",", fields.Select(Function(v) "@" & v.Text)) & ")"
End If
Using cmd As New SqlCommand(sqlText, cn, tx)
For Each field In fields
Dim prop = obj.GetType().GetProperty(field.Scalarvariable)
If prop Is Nothing Then Throw New InvalidOperationException("Fehlende Eigenschaft: " & field.Scalarvariable)
cmd.Parameters.AddWithValue("@" & field.Text, Db(prop.GetValue(obj)))
Next
If existingId > 0 Then
cmd.Parameters.Add("@__id", SqlDbType.Int).Value = existingId
If cmd.ExecuteNonQuery() <> 1 Then Throw New InvalidOperationException("Datensatz nicht gefunden: " & tableName & " / " & existingId)
Return existingId
End If
Return CInt(cmd.ExecuteScalar())
End Using
End Function
Private Shared Sub InsertPackages(cn As SqlConnection, tx As SqlTransaction, it As cVERAG_CustomsDeclarations_Item)
Dim packages = it.Packages
' Kompatibilität: bestehende Aufrufer befüllen weiterhin nur die drei Legacy-Felder.
If packages Is Nothing OrElse packages.Count = 0 Then
If Not String.IsNullOrWhiteSpace(it.zaItem_PackageType) OrElse Not String.IsNullOrWhiteSpace(it.zaItem_PackageColli) OrElse Not String.IsNullOrWhiteSpace(it.zaItem_PackageMark) Then
Dim n As Integer
Dim parsed As Integer? = If(Integer.TryParse(it.zaItem_PackageColli, n), CType(n, Integer?), Nothing)
packages = New List(Of cVERAG_CustomsDeclarations_ItemPackage) From {New cVERAG_CustomsDeclarations_ItemPackage With {.zaPkg_Type = it.zaItem_PackageType, .zaPkg_Number = parsed, .zaPkg_Marks = it.zaItem_PackageMark}}
it.Packages = packages
End If
End If
If packages Is Nothing Then Return
For Each pkg In packages
Using cmd As New SqlCommand("INSERT INTO dbo.tblVERAG_CustomsDeclarations_ItemPackages (zaPkg_zaItemId,zaPkg_Type,zaPkg_Number,zaPkg_Marks) OUTPUT INSERTED.zaPkg_Id VALUES (@item,@type,@number,@marks)", cn, tx)
cmd.Parameters.Add("@item", SqlDbType.Int).Value = it.zaItem_Id
cmd.Parameters.AddWithValue("@type", Db(pkg.zaPkg_Type))
cmd.Parameters.AddWithValue("@number", Db(pkg.zaPkg_Number))
cmd.Parameters.AddWithValue("@marks", Db(pkg.zaPkg_Marks))
pkg.zaPkg_Id = CInt(cmd.ExecuteScalar())
pkg.zaPkg_zaItemId = it.zaItem_Id
End Using
Next
End Sub
Private Shared Sub ReplaceItemsInTransaction(cn As SqlConnection, tx As SqlTransaction, zaId As Integer, items As List(Of cVERAG_CustomsDeclarations_Item))
Execute(cn, tx, "DELETE FROM dbo.tblVERAG_CustomsDeclarations_ItemPackages WHERE zaPkg_zaItemId IN (SELECT zaItem_Id FROM dbo.tblVERAG_CustomsDeclarations_Items WHERE zaItem_zaId=@id)", zaId)
Execute(cn, tx, "DELETE FROM dbo.tblVERAG_CustomsDeclarations_Documents WHERE zaDoc_zaId=@id AND zaDoc_ItemId IS NOT NULL", zaId)
Execute(cn, tx, "DELETE FROM dbo.tblVERAG_CustomsDeclarations_Duties WHERE zaDuty_zaId=@id AND zaDuty_zaItemId IS NOT NULL", zaId)
Execute(cn, tx, "DELETE FROM dbo.tblVERAG_CustomsDeclarations_Items WHERE zaItem_zaId=@id", zaId)
If items Is Nothing Then Return
For Each it In items
it.zaItem_zaId = zaId
' Die alten Item-IDs sind nach DELETE ungültig. Auch NCTS-FK muss gültig sein.
it.zaItem_Id = WriteObject(cn, tx, "tblVERAG_CustomsDeclarations_Items", it, it.getParameterList())
If it.Documents IsNot Nothing Then
For Each doc In it.Documents
doc.zaDoc_zaId = zaId : doc.zaDoc_ItemId = it.zaItem_Id
doc.zaDoc_Id = WriteObject(cn, tx, "tblVERAG_CustomsDeclarations_Documents", doc, doc.getParameterList())
Next
End If
If it.Duties IsNot Nothing Then
For Each duty In it.Duties
duty.zaDuty_zaId = zaId : duty.zaDuty_zaItemId = it.zaItem_Id
duty.zaDuty_Id = WriteObject(cn, tx, "tblVERAG_CustomsDeclarations_Duties", duty, duty.getParameterList())
Next
End If
InsertPackages(cn, tx, it)
Next
End Sub
Public Shared Sub ReplaceItems(zaId As Integer, items As List(Of cVERAG_CustomsDeclarations_Item))
Dim sql As New VERAG_PROG_ALLGEMEIN.SQL
Using cn As SqlConnection = SQL.GetNewOpenConnectionFMZOLL()
Using tx = cn.BeginTransaction()
Try
ReplaceItemsInTransaction(cn, tx, zaId, items)
tx.Commit()
Catch
tx.Rollback()
Throw
End Try
End Using
End Using
End Sub
Public Shared Sub Save(za As cVERAG_CustomsDeclarations)
Dim sql As New VERAG_PROG_ALLGEMEIN.SQL
Using cn As SqlConnection = SQL.GetNewOpenConnectionFMZOLL()
Using tx = cn.BeginTransaction()
Try
Dim exists As Boolean = False
If za.za_Id > 0 Then
Using cmd As New SqlCommand("SELECT COUNT(1) FROM dbo.tblVERAG_CustomsDeclarations WITH (UPDLOCK,HOLDLOCK) WHERE za_Id=@id", cn, tx)
cmd.Parameters.Add("@id", SqlDbType.Int).Value = za.za_Id
exists = CInt(cmd.ExecuteScalar()) > 0
End Using
End If
za.za_Id = WriteObject(cn, tx, "tblVERAG_CustomsDeclarations", za, za.getParameterList(), If(exists, za.za_Id, 0))
Execute(cn, tx, "DELETE FROM dbo.tblVERAG_CustomsDeclarations_Parties WHERE zaParty_zaId=@id", za.za_Id)
If za.Parties IsNot Nothing Then
For Each party In za.Parties
party.zaParty_zaId = za.za_Id
party.zaParty_Id = WriteObject(cn, tx, "tblVERAG_CustomsDeclarations_Parties", party, party.getParameterList())
Next
End If
Execute(cn, tx, "DELETE FROM dbo.tblVERAG_CustomsDeclarations_Documents WHERE zaDoc_zaId=@id AND zaDoc_ItemId IS NULL", za.za_Id)
If za.Documents IsNot Nothing Then
For Each doc In za.Documents
doc.zaDoc_zaId = za.za_Id : doc.zaDoc_ItemId = Nothing
doc.zaDoc_Id = WriteObject(cn, tx, "tblVERAG_CustomsDeclarations_Documents", doc, doc.getParameterList())
Next
End If
ReplaceItemsInTransaction(cn, tx, za.za_Id, za.Items)
Execute(cn, tx, "DELETE FROM dbo.tblVERAG_CustomsDeclarations_Duties WHERE zaDuty_zaId=@id AND zaDuty_zaItemId IS NULL", za.za_Id)
If za.Duties IsNot Nothing Then
For Each duty In za.Duties
duty.zaDuty_zaId = za.za_Id : duty.zaDuty_zaItemId = Nothing
duty.zaDuty_Id = WriteObject(cn, tx, "tblVERAG_CustomsDeclarations_Duties", duty, duty.getParameterList())
Next
End If
tx.Commit()
za.hasEntry = True
Catch
tx.Rollback()
Throw
End Try
End Using
End Using
End Sub
End Class