VERSION 1.0 CLASS
BEGIN
  MultiUse = -1  'True
  Persistable = 0  'NotPersistable
  DataBindingBehavior = 0  'vbNone
  DataSourceBehavior  = 0  'vbNone
  MTSTransactionMode  = 0  'NotAnMTSObject
END
Attribute VB_Name = "DPC_Interface"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = True
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = False
  Option Explicit

Private Const SEP = "®©"
Private Const C_SEP As String = "@@"
Private Const SEP1 As String = "®"
Private Const SEP2 As String = "©"
Private Const CL_COLOR_ENABLED As Long = &H80000005
Private Const CL_COLOR_DISABLED As Long = &H8000000F
Private Const SCREEN_NAME As String = "DPC_Interface"
Private Const SW_SHOWNORMAL = 1

Private Const LOCALE_SDECIMAL = &HE ' Decimal separator
Private Const LOCALE_STHOUSAND = &HF ' Thousand separator
Private Const LOCALE_USER_DEFAULT = &H400
Private Const C_ERRORRAISE As Long = 2500
Private Const C_MSG_ID_BASE As Long = 9700

Private Const ROWIDTRANSTATUS_NEW = "NEW"
Private Const ROWIDTRANSTATUS_OK = "OK"
Private Const ROWIDTRANSTATUS_ERROR = "ERROR"

' FTP settings
Private Const FTP_PASIVE As Boolean = True

Private mb_Initialized              As Boolean

Dim mb_copyAbort As Boolean         ' Global flag for file transfer operation
Dim ms_copyFile As String           ' Actualy transfering file
Dim mb_runCancel As Boolean         ' Global flag
Dim ms_FTPRoot As String            ' root directory for opened FTP session

Dim ms_TempDir As String

Private Enum ArmErr
    DBCnxFailed = vbObjectError + 1             ' Unable to connect to the database
    CPTAlreadyInitialized = vbObjectError + 2   ' We try to initialize a component that is already initialized
    CPTNotInitialized = vbObjectError + 3       ' We try to use or free that is not initialized yet
    InvalidArgument = vbObjectError + 4
    PropertyNotSet = vbObjectError + 5
    SQLFailure = vbObjectError + 6               ' A SQL runtime error has occured : syntax wrong....
    SQLBadRowAffectedCount = vbObjectError + 7   ' A SQL request has not affected the expected rowcount (ex: one Update do nothing)
    SQLBadRowExpectedCount = vbObjectError + 8   ' A SQL request does not return the expected rowcount : select an item return nothing...
    DrivingError = vbObjectError + 9
    CompFncFailed = vbObjectError + 10           ' when component function fail
    GridLoadFailed = vbObjectError + 11          ' load function failed ... bad sql
    QuietException = vbObjectError + 12          ' do not display error message
    SQLTableReferenceConstraint = vbObjectError + 13 ' A SQL request cannot be executed : Table reference constraint
    DuplicityDetected = vbObjectError + 2301     ' detected row with same unique id
End Enum

Private Enum ArmCusErr
    DuplicityDetected = C_ERRORRAISE + 2301                ' detected row with same unique id
End Enum

#If ENV = LIVE Then
Private mo_FSO As Object
Private mo_Db As Object
Private mo_DbBaeurer As Object
Private mo_Shell As Object
#Else
Private mo_FSO As Scripting.FileSystemObject
Private mo_Db As ARMSYSCOMLib.ArmDb
Private mo_DbBaeurer As ARMSYSCOMLib.ArmDb
Private mo_Shell As Object
#End If

Private mo_Tools As DPC_Tools

Private ml_U_Code As Long
Private ms_Language_Code As String
Private ms_CT_Code As String
Private ValidityDate As Date

Private ms_BaeurerServer As String
Private ms_BaeurerDatabase As String
Private ms_BaeurerLoginName As String
Private ms_BaeurerPassword As String
Private ml_BaeurerFi_Nr As Long
Private ms_BaeurerSource As String
Private ms_BaeurerLang As String
Private ms_PC_Name As String
Private mo_Generate As DPC_Generate
Private ml_BaeurerConnectID As Long

'Private me_RawMaterial As eDPCBOMMaterial
'Private ms_NewIdentNr As String
'Private ms_MaterialName As String
'Private md_CoilWidth As Double
'Private md_CoilThickness As Double
'Private ms_Material As String
'
'Private md_InlayLength As Double
'Private md_InlayWidth As Double

Private mta_XmlSql() As TXmlSql

Private Type TXmlSql
  Request As String
  Cursor As Long
  ATS_Id As Long
  ATS_Type As eDPCXmlSqlType
  ATS_Node As String
  ATS_IsSubNode As Boolean
  ATS_IsMaster As Boolean
  ATS_ImportName As String
  ATS_Profile As String
  ATS_Version As Long
End Type

'logging variables ...
Private Type DPCLogInterface
    ILO_Interface As eDPCXmlExportType
    ILO_MasterId As String
    ILO_Status As Integer
    ILO_RespMsg As String
    ILO_Error As String
    ILO_Connection As String
    ILO_XMLSent As String
    ILO_DateSent As Date
    ILO_XMLResponse As String
    ILO_Performance As Double
End Type

Dim mo_ILO As DPCLogInterface

' remarks - need DB user to write export tables and read all other
' when the result is ready ? which status to check ?
' how to send the same article to secretbox again ?
' is it possible to update article ?
' Link BOM to agpos fuer material abbuchung
' definier ag bennenung (nr:benennng)
' abw_plus = 500%

Public Property Set ArmDb(ByVal ao_Db As Object)
On Error GoTo ErrHandler
  
  Set mo_Db = ao_Db
  Exit Property
ErrHandler:
  Call errorHandler("ArmDb.Set")
End Property

Public Property Get ArmDbBaeurer() As Object
On Error GoTo ErrHandler
  
  Set ArmDbBaeurer = mo_DbBaeurer
  Exit Property
ErrHandler:
  Call errorHandler("ArmDbBaeurer.Get")
End Property

Public Property Set Tools(ByRef ao_Tools As Object)
On Error GoTo errorHandler

  Set mo_Tools = ao_Tools
  Exit Property
errorHandler:
  Call errorHandler("Tools.Set")
End Property

Property Let U_Code(al_Code As Long)
On Error GoTo ErrHandler
  
  ml_U_Code = al_Code
  Exit Property
ErrHandler:
  Call errorHandler("U_Code.Let")
End Property

Property Let Language_Code(as_Language_Code As String)
On Error GoTo ErrHandler
  
  ms_Language_Code = as_Language_Code
  Exit Property
ErrHandler:
  Call errorHandler("Language_Code.Let")
End Property

Property Let CT_Code(as_Value As String)
On Error GoTo ErrHandler
  
  ms_CT_Code = as_Value
  Exit Property
ErrHandler:
  Call errorHandler("CT_Code.Let")
End Property


Public Sub Load_A_COM()
On Error GoTo errorHandler

Dim ls_Connect() As String
Dim lo_NetObject As Object

  If mo_Db Is Nothing Then
      Call Err.Raise(ArmErr.PropertyNotSet)
  End If
  If mo_Tools Is Nothing Then
      Call Err.Raise(ArmErr.PropertyNotSet)
  End If
  
  Set mo_FSO = CreateObject("Scripting.FileSystemObject")
  Set mo_Shell = CreateObject("WSCript.Shell")
  If mo_Shell Is Nothing Then
      Call Err.Raise(666, "CreateObject()", "Cannot create WSCript.Shell.")
  End If

  Set lo_NetObject = CreateObject("WScript.Network")
  ms_PC_Name = Left(lo_NetObject.ComputerName, 50)
  Set lo_NetObject = Nothing
  
  ms_TempDir = mo_Tools.GetAndCreateTempDir(mo_FSO, SCREEN_NAME)
  
#If ENV = LIVE Then
    Set mo_DbBaeurer = CreateObject("ArmSysCOM.ArmDb")
#Else
    Set mo_DbBaeurer = New ARMSYSCOMLib.ArmDb
#End If
  
  Set mo_Generate = New DPC_Generate
  Set mo_Generate.ArmDb = mo_Db
  Set mo_Generate.Tools = mo_Tools
  
  ls_Connect = Split(mo_Tools.GetAConfigData("DPC_BaeurerConnection"), SEP)
  If UBound(ls_Connect) = 5 Then
    ms_BaeurerServer = ls_Connect(0)
    ms_BaeurerDatabase = ls_Connect(1)
    ms_BaeurerLoginName = ls_Connect(2)
    ms_BaeurerPassword = ls_Connect(3)
    ms_BaeurerSource = ls_Connect(4)
    ml_BaeurerFi_Nr = Val(ls_Connect(5))
    ms_BaeurerLang = "de_de"
  Else
      Err.Raise ArmErr.PropertyNotSet, "Split(mo_Tools.GetAConfigData(""DPC_BaeurerConnection"")", "Missing or invalid configuration"
  End If
  ml_BaeurerConnectID = 0
'    ms_BaeurerServer = "10.68.16.40\LIVE_SAGE"
'    ms_BaeurerDatabase = "test70"
'    ms_BaeurerLoginName = "test70"
'    ms_BaeurerPassword = "erp"
'    ms_BaeurerSource = "Capture"
'    ml_BaeurerFi_Nr = 1
  If ms_Language_Code = "" Then ms_Language_Code = "E"
  Exit Sub
errorHandler:
  Call errorHandler("Load_A_Com")
End Sub

Public Sub Unload_A_COM()
On Error GoTo errorHandler

Dim ll_Idx As Long

  Call mo_Tools.DeleteTemporaryFolder(mo_FSO, SCREEN_NAME)
  If mo_DbBaeurer.CursorCount > 0 Then
    For ll_Idx = 0 To mo_DbBaeurer.CursorCount - 1
      Debug.Print "Baeurer Cursor #" & (ll_Idx + 1) & "-" & mo_DbBaeurer.Cursors(ll_Idx) & mo_DbBaeurer.SQLRequest(mo_DbBaeurer.Cursors(ll_Idx))
    Next
  End If
  Call mo_DbBaeurer.Disconnect
  Set mo_FSO = Nothing
  Set mo_Db = Nothing
  Set mo_DbBaeurer = Nothing
  Exit Sub
errorHandler:
  Call errorHandler("Unload_A_Com")
End Sub

Private Sub Bae_LoadGrid(ByVal ao_grid As ArmGrid, ByVal ac_Cursor As Long)
On Error GoTo errorHandler

  ao_grid.Redraw = False
  Call mo_DbBaeurer.First(ac_Cursor)
  While Not mo_DbBaeurer.EOF(ac_Cursor)
    Call ao_grid.AddLine(Array(mo_DbBaeurer.GetFields(ac_Cursor, 0), mo_DbBaeurer.GetFields(ac_Cursor, 1)))
    Call mo_DbBaeurer.Next(ac_Cursor)
  Wend
  ao_grid.Redraw = True
  Exit Sub
errorHandler:
  Call errorHandler("Bae_LoadGrid")
End Sub

Private Function Bae_LoadBaeurerReferenceCursor(ByVal ao_Db As Object, ByVal ae_Reference As eDPCBaeurerReference, ByVal as_code As String, ByVal av_Param As Variant) As Long
On Error GoTo errorHandler

Dim ls_Req As String
Dim ll_Idx As Long
  
  Bae_LoadBaeurerReferenceCursor = 0
  ls_Req = ""
  If ae_Reference = eDPCBaeurerReference.brOrderType Then
    ls_Req = "SELECT v902.auf_art as Code, v9022.txt AS Text "
    ls_Req = ls_Req & "FROM v902 "
    ls_Req = ls_Req & "INNER JOIN v9022 ON (v9022.auf_art=v902.auf_art AND v9022.fi_nr=v902.fi_nr and v9022.lang=$lang$) "
    ls_Req = ls_Req & "WHERE v902.fi_nr=$fi_nr$ AND "
    ls_Req = ls_Req & "((v902.auf_art=$Code$) OR ($Code$ IS NULL))"
  ElseIf ae_Reference = eDPCBaeurerReference.brPartner Then
    ls_Req = "SELECT g620.ansprnr as Code, g620.name_1 AS Text "
    ls_Req = ls_Req & "FROM g620 "
    ls_Req = ls_Req & "WHERE g620.fi_nr=$fi_nr$ AND "
    ls_Req = ls_Req & "g620.konto=$konto$ AND "
    ls_Req = ls_Req & "((g620.ansprnr=$Code$) OR ($Code$ IS NULL))"
  ElseIf ae_Reference = eDPCBaeurerReference.brDeliveryCondition Then
    ls_Req = "SELECT v908.lb as Code, v9082.txt AS Text "
    ls_Req = ls_Req & "FROM v908 "
    ls_Req = ls_Req & "INNER JOIN v9082 ON (v9082.lb=v908.lb AND v9082.fi_nr=v908.fi_nr and v9082.lang_ext=$lang$) "
    ls_Req = ls_Req & "WHERE v908.fi_nr=$fi_nr$ AND "
    ls_Req = ls_Req & "((v908.lb=$Code$) OR ($Code$ IS NULL))"
  ElseIf ae_Reference = eDPCBaeurerReference.brDeliveryType Then
    ls_Req = "SELECT v907.vers_art as Code, v9072.txt AS Text "
    ls_Req = ls_Req & "FROM v907 "
    ls_Req = ls_Req & "INNER JOIN v9072 ON (v9072.vers_art=v907.vers_art AND v9072.fi_nr=v907.fi_nr and v9072.lang_ext=$lang$) "
    ls_Req = ls_Req & "WHERE (v907.fi_nr=$fi_nr$) AND "
    ls_Req = ls_Req & "((v907.vers_art=$Code$) OR ($Code$ IS NULL))"
  ElseIf ae_Reference = eDPCBaeurerReference.brClerkInCharge Then
    ls_Req = "SELECT g915.sb_schl as Code, g915.sb_name AS Text "
    ls_Req = ls_Req & "FROM g915 "
    ls_Req = ls_Req & "WHERE g915.fi_nr=$fi_nr$ AND "
    ls_Req = ls_Req & "((g915.sb_schl=$Code$) OR ($Code$ IS NULL))"
  ElseIf ae_Reference = eDPCBaeurerReference.brPackType Then
    ls_Req = "SELECT g741.ausprid as Code, g7412.txt AS Text "
    ls_Req = ls_Req & "FROM g741 "
    ls_Req = ls_Req & "INNER JOIN g7412 ON (g741.kritnr = g7412.kritnr AND g741.ausprid = g7412.ausprid AND g7412.lang_ext=$lang$) "
    ls_Req = ls_Req & "INNER JOIN g730 ON (g7412.kritnr = g730.kritnr) "
    ls_Req = ls_Req & "WHERE g730.fldname = 'VERP_ART' AND "
    ls_Req = ls_Req & "((g741.ausprid=$Code$) OR ($Code$ IS NULL))"
  ElseIf ae_Reference = eDPCBaeurerReference.brKonto Then
    ls_Req = "SELECT v600.konto as Code, g693.name_1 AS Text "
    ls_Req = ls_Req & "FROM g600 "
    ls_Req = ls_Req & "INNER JOIN v600 ON (g600.konto = v600.konto) "
    ls_Req = ls_Req & "INNER JOIN g693 ON (g600.adressid = g693.adressid) "
    ls_Req = ls_Req & "WHERE (g600.fi_nr=$fi_nr$) AND "
    ls_Req = ls_Req & "(g600.satzart = 1) AND "
    ls_Req = ls_Req & "((g600.konto=$Code$) OR ($Code$ IS NULL))"
  End If
  
  If ls_Req <> "" Then
    If IsArray(av_Param) Then
      For ll_Idx = 0 To UBound(av_Param) Step 2
        ls_Req = Replace(ls_Req, av_Param(ll_Idx), av_Param(ll_Idx + 1), , , vbTextCompare)
      Next
    End If
    ls_Req = Replace(ls_Req, "$fi_nr$", mo_Tools.SqlInt(ml_BaeurerFi_Nr), , , vbTextCompare)
    ls_Req = Replace(ls_Req, "$Code$", as_code, , , vbTextCompare)
    ls_Req = Replace(ls_Req, "$lang$", mo_Tools.SQLStr(ms_BaeurerLang), , , vbTextCompare)
    Bae_LoadBaeurerReferenceCursor = mo_Tools.OpenSQLSafe(ao_Db, ls_Req)
  End If
  Exit Function
errorHandler:
  Call errorHandler("Bae_LoadBaeurerReferenceCursor")
End Function

Public Function Bae_LoadBaeurerReferenceText(ByVal ae_Reference As eDPCBaeurerReference, ByVal as_code As String, ByVal av_Param As Variant) As String
On Error GoTo errorHandler

Dim lc_Cursor As Long

  Bae_LoadBaeurerReferenceText = ""
  If Not mo_Tools.ReconnectSafe(mo_DbBaeurer, ms_BaeurerServer, ms_BaeurerDatabase, ms_BaeurerLoginName, ms_BaeurerPassword, ms_BaeurerSource) Then
    Exit Function
  End If
  
  lc_Cursor = Bae_LoadBaeurerReferenceCursor(mo_DbBaeurer, ae_Reference, as_code, av_Param)
  If lc_Cursor <> 0 Then
    If mo_DbBaeurer.RowCount(lc_Cursor) = 1 Then
      Bae_LoadBaeurerReferenceText = mo_DbBaeurer.GetFields(lc_Cursor, "Text")
    End If
    Call mo_DbBaeurer.Close(lc_Cursor)
  End If
  Exit Function
errorHandler:
  Call errorHandler("Bae_LoadBaeurerReferenceText")
End Function


Public Sub Bae_LoadBaeurerReferenceGrid(ByVal ao_grid As ArmGrid, ByVal ae_Reference As eDPCBaeurerReference, ByVal av_Param As Variant)
On Error GoTo errorHandler

Dim lc_Cursor As Long

  If Not mo_Tools.ReconnectSafe(mo_DbBaeurer, ms_BaeurerServer, ms_BaeurerDatabase, ms_BaeurerLoginName, ms_BaeurerPassword, ms_BaeurerSource) Then
    Exit Sub
  End If
  
  lc_Cursor = Bae_LoadBaeurerReferenceCursor(mo_DbBaeurer, ae_Reference, "NULL", av_Param)
  Call ao_grid.ClearGrid
  If lc_Cursor <> 0 Then
    Call Bae_LoadGrid(ao_grid, lc_Cursor)
    Call mo_DbBaeurer.Close(lc_Cursor)
  End If
  Exit Sub
errorHandler:
  Call errorHandler("Bae_LoadBaeurerReferenceGrid")
End Sub

Public Function Bae_SaveXMLDocument(ByVal ao_XML As Object, ByVal as_FileName As String) As String
On Error GoTo errorHandler

Dim lo_shell As Object
Dim ls_XmlPath As String

  Set lo_shell = CreateObject("WSCript.Shell")
  If lo_shell Is Nothing Then
      Call Err.Raise(666, "CreateObject()", "Cannot create WSCript.Shell.")
  End If
  
  ls_XmlPath = ms_TempDir & "\" & as_FileName & ".xml"
  Call ao_XML.Save(ls_XmlPath)
  Call lo_shell.Run("""" & ls_XmlPath & """")
  Set lo_shell = Nothing
  Bae_SaveXMLDocument = ms_TempDir & "\" & as_FileName & ".xml"
  Exit Function
errorHandler:
  Call errorHandler("Bae_SaveXMLDocument")
End Function

Public Function SAP_SaveXMLDocument(ByVal ao_XML As Object, ByVal as_FileName As String, ByVal as_ATI_Name As String, Optional ab_OnlyValidate = True, Optional ab_OnlySave = False) As String
On Error GoTo errorHandler

Dim lo_shell As Object
Dim ls_XmlPath As String
Dim lo_XmlIndentedDocument As MSXML2.DOMDocument
Dim lo_XmlIndenter As MSXML2.DOMDocument
Dim ls_ValidationXSD As String
Dim ls_FormatterXML As String

  Set lo_shell = CreateObject("WSCript.Shell")
  If lo_shell Is Nothing Then
      Call Err.Raise(666, "CreateObject()", "Cannot create WSCript.Shell.")
  End If
  
  Set lo_XmlIndentedDocument = CreateObject("MSXML2.DOMDocument")
  Set lo_XmlIndenter = CreateObject("MSXML2.DOMDocument")

  lo_XmlIndenter.async = False
  
  Call LoadXMLFiles(as_ATI_Name, ls_ValidationXSD, ls_FormatterXML)
  
  Call lo_XmlIndenter.Load(ls_FormatterXML)

  Call ao_XML.transformNodeToObject(lo_XmlIndenter, lo_XmlIndentedDocument)
  
  If ab_OnlyValidate = False Then
    ls_XmlPath = App.Path & "\" & as_FileName & ".xml"
    Call lo_XmlIndentedDocument.Save(ls_XmlPath)
    Call lo_shell.Run("""" & ls_XmlPath & """")
  End If
  
  If ab_OnlySave = False Then
    Call ValidateXMLFile(lo_XmlIndentedDocument.xml, "", ls_ValidationXSD, True)
  End If
    
  SAP_SaveXMLDocument = lo_XmlIndentedDocument.xml
  
  Set lo_shell = Nothing
  Exit Function
errorHandler:
  Call errorHandler("SAP_SaveXMLDocument")
End Function

Public Function LoadXMLFiles(ByVal as_ATI_Name As String, ByRef as_SchemaFile As String, ByRef as_FormatterFile As String) As Boolean
On Error GoTo ErrHandler

Dim ls_path As String
Dim lc_Cursor As Long
Dim ls_Request As String
Dim ls_Schema As String
Dim ls_SchemaName As String
Dim ls_Formatter As String
Dim ls_FormatterName As String

  LoadXMLFiles = False
  
  ls_Request = "SELECT ATI_Schema,ATI_SchemaName, ATI_Formatter,ATI_FormatterName FROM DPC_AttribInterface WHERE ATI_Name = $ATI_Name$"
  
  ls_Request = Replace(ls_Request, "$ATI_Name$", mo_Tools.SQLStr(as_ATI_Name), , , vbTextCompare)
  
  lc_Cursor = mo_Tools.OpenSQLSafe(mo_Db, ls_Request)
  If mo_Db.RowCount(lc_Cursor) = 1 Then
    ls_Schema = mo_Db.GetFields(lc_Cursor, "ATI_Schema")
    ls_SchemaName = mo_Db.GetFields(lc_Cursor, "ATI_SchemaName")
    ls_Formatter = mo_Db.GetFields(lc_Cursor, "ATI_Formatter")
    ls_FormatterName = mo_Db.GetFields(lc_Cursor, "ATI_FormatterName")
  Else
    Err.Raise ArmErr.InvalidArgument, "as_ATI_Name", "Invalid ATI_Name: " & as_ATI_Name
  End If
  
  Call mo_Db.Close(lc_Cursor)
  
  ls_path = App.Path & "\Download\XMLSchema\"
    
  If Not mo_FSO.FolderExists(ls_path) Then
    Call mo_FSO.CreateFolder(ls_path)
  End If
  
  as_SchemaFile = ls_path & ls_SchemaName
  
  If Not mo_FSO.FileExists(as_SchemaFile) Then
    If Not mo_Db.BlobToFileSQL("SELECT F_Data_File FROM A_Files WHERE F_File_Key='" & ls_Schema & "'", as_SchemaFile, True, False) Then
      Err.Raise ArmErr.CompFncFailed, "BlobToFileSQL", "File download failed A_File_Key:" & ls_Schema & "," & mo_Db.LastErrorMessage
      Exit Function
    End If
  End If
    
  If Len(ls_FormatterName) > 0 Then
    as_FormatterFile = ls_path & ls_FormatterName
    
    If Not mo_FSO.FileExists(as_FormatterFile) Then
      If Not mo_Db.BlobToFileSQL("SELECT F_Data_File FROM A_Files WHERE F_File_Key='" & ls_Formatter & "'", as_FormatterFile, True, False) Then
        Err.Raise ArmErr.CompFncFailed, "BlobToFileSQL", "File download failed A_File_Key:" & ls_Formatter & "," & mo_Db.LastErrorMessage
        Exit Function
      End If
    End If
  End If
  
  LoadXMLFiles = True
  
  Exit Function
  
ErrHandler:
  
  If lc_Cursor <> 0 Then
      Call mo_Db.Close(lc_Cursor)
  End If

  LoadXMLFiles = False
  Call errorHandler("LoadXMLFiles")
End Function

Function ValidateXMLFile(ByVal ls_strXmlFile As String, ls_strUrn As String, ls_strXsdFile As String, Optional ab_ParseString = False) As Boolean
On Error GoTo errorHandler
Dim ls_Desc As String
    
   'Create an XML DOMDocument object.
   Dim lo_Schema As Object
   Dim lo_XMLDoc As Object
    
   ValidateXMLFile = False
   
   Set lo_Schema = CreateObject("MSXML2.XMLSchemaCache.4.0")
   Call lo_Schema.Add(ls_strUrn, ls_strXsdFile)

   ' Create an XML DOMDocument object.
   Set lo_XMLDoc = CreateObject("MSXML2.DOMDocument.4.0")

   ' Assign the schema cache to the DOM document.
   ' schemas collection.
   Set lo_XMLDoc.schemas = lo_Schema

   lo_XMLDoc.async = False
   
   If ab_ParseString = False Then
        lo_XMLDoc.Load ls_strXmlFile
   Else
        lo_XMLDoc.loadXML ls_strXmlFile
   End If

   ' Return validation results in message to the user.
   If lo_XMLDoc.parseError.errorCode <> 0 Then
        
        If ab_ParseString = False Then
            ls_Desc = "Validation failed on " & ls_strXmlFile & vbCrLf
        Else
            ls_Desc = "Validation failed" & vbCrLf
        End If
        
        ls_Desc = ls_Desc & "Reason: " & lo_XMLDoc.parseError.reason & _
             vbCrLf & "Source: " & _
             lo_XMLDoc.parseError.srcText & _
             vbCrLf & "Line: " & _
             lo_XMLDoc.parseError.line & vbCrLf
             
             Err.Raise ArmErr.CompFncFailed, "ValidateXMLFile", ls_Desc
             
    Else
        ValidateXMLFile = True
    End If
    
    Set lo_Schema = Nothing
    Set lo_XMLDoc = Nothing
    
    Exit Function
errorHandler:
  
    Set lo_Schema = Nothing
    Set lo_XMLDoc = Nothing
  
  Call errorHandler("ValidateXMLFile")
End Function

Public Function Bae_CreateXMLDocument(ByVal ao_Db As Object, ByVal ae_ATR_Id As eDPCXmlExportType, ByVal as_Key As String, ByRef al_Version As Long, ByVal ao_CustomData As Dictionary) As Object
On Error GoTo errorHandler

Dim lo_parentNode As Object
Dim lo_MainNode As Object
Dim lc_CursorMaster As Long
Dim lc_CursorXML As Long
Dim ll_ATS_Id As Long
Dim lt_XmlSql As TXmlSql
Dim lt_XmlMaster As TXmlSql
Dim lo_XMLDoc As MSXML2.DOMDocument

  Set lo_XMLDoc = CreateObject("MSXML2.DOMDocument")
  lo_XMLDoc.async = False
  
  Set lo_parentNode = lo_MainNode
  lc_CursorXML = Bae_GetXmlCursor(ae_ATR_Id)
  Call InitSqlData(ao_Db, lc_CursorXML, as_Key)
  
  lt_XmlMaster = GetXmlMasterSql
  al_Version = lt_XmlMaster.ATS_Version
  
  Set lo_MainNode = AppendElement(lo_XMLDoc, Nothing, "Data", "")
  Set lo_MainNode = AppendElement(lo_XMLDoc, lo_MainNode, lt_XmlMaster.ATS_ImportName, "")
  
  Call AppendElement(lo_XMLDoc, lo_MainNode, "heute", Bae_FormatXMLDateTime(Now))
  Call AppendElement(lo_XMLDoc, lo_MainNode, "profil", lt_XmlMaster.ATS_Profile)
  
  lc_CursorMaster = lt_XmlMaster.Cursor
  If ao_Db.RowCount(lc_CursorMaster) = 0 Then
    Set lo_parentNode = AppendElement(lo_XMLDoc, lo_MainNode, lt_XmlMaster.ATS_Node, "")
  Else
    Call ao_Db.First(lc_CursorMaster)
    While Not ao_Db.EOF(lc_CursorMaster)
      Set lo_parentNode = AppendElement(lo_XMLDoc, lo_MainNode, lt_XmlMaster.ATS_Node, "")
    
      Call mo_Db.First(lc_CursorXML)
      While Not mo_Db.EOF(lc_CursorXML)
      
        ll_ATS_Id = mo_Db.GetFields(lc_CursorXML, "ATS_Id")
        lt_XmlSql = GetXmlSql(ll_ATS_Id)
        If ll_ATS_Id = lt_XmlMaster.ATS_Id Then
          Call Bae_CreateXMLNode(lc_CursorXML, ao_Db, lc_CursorMaster, lo_XMLDoc, lo_parentNode, ao_CustomData)
          Call mo_Db.Next(lc_CursorXML)
        Else
          If lt_XmlSql.ATS_Type = eDPCXmlSqlType.stList Then
            Call CreateXMLGroupList(lc_CursorXML, ao_Db, ll_ATS_Id, lo_XMLDoc, lo_parentNode, ao_CustomData)
          ElseIf lt_XmlSql.ATS_Type = eDPCXmlSqlType.stFlat Then
            Call CreateXMLGroupFlat(lc_CursorXML, ao_Db, ll_ATS_Id, lo_XMLDoc, lo_parentNode, ao_CustomData)
          End If
        End If
      Wend
      Call ao_Db.Next(lc_CursorMaster)
    Wend
  End If
  Call mo_Db.Close(lc_CursorXML)
  Call CloseSqlData(ao_Db)
  Set Bae_CreateXMLDocument = lo_XMLDoc
  Exit Function
errorHandler:

  Call LogInterface(mo_Db, ml_U_Code)
  
  Call errorHandler("Bae_CreateXMLDocument")
End Function

Private Function CreateXMLGroupFlat(ByVal ac_CursorXML As Long, ByVal ao_DbData As Object, ByVal al_ATS_Id As Long, ByVal ao_XMLDoc As Object, ByVal ao_parentNode As Object, ByVal ao_CustomData As Dictionary)
On Error GoTo errorHandler

Dim ll_RecIdx As Long
Dim lo_CurrentNode As Object
Dim ls_NodeName As String
Dim lt_XmlSql As TXmlSql
Dim lc_CursorData As Long

  lt_XmlSql = GetXmlSql(al_ATS_Id)
  lc_CursorData = lt_XmlSql.Cursor

  ls_NodeName = Trim(mo_Db.GetFields(ac_CursorXML, "ATS_Node"))
  If mo_Db.GetFields(ac_CursorXML, "ATS_IsSubNode") = "X" Then
    ls_NodeName = Replace(ls_NodeName, "$N$", CStr(ll_RecIdx), , , vbTextCompare)
    Set lo_CurrentNode = AppendElement(ao_XMLDoc, ao_parentNode, ls_NodeName, "")
  Else
    Set lo_CurrentNode = ao_parentNode
  End If
  While (Not mo_Db.EOF(ac_CursorXML)) And (al_ATS_Id = mo_Db.GetFields(ac_CursorXML, "ATS_Id"))
    ll_RecIdx = mo_Db.GetFields(ac_CursorXML, "ATR_RecIdx")
    If (ll_RecIdx > 0) And (ll_RecIdx <= ao_DbData.RowCount(lc_CursorData)) Then
      mo_Db.Position(lc_CursorData) = ll_RecIdx - 1
      Call Bae_CreateXMLNode(ac_CursorXML, ao_DbData, lc_CursorData, ao_XMLDoc, lo_CurrentNode, ao_CustomData)
    Else
      Call Bae_CreateXMLNode(ac_CursorXML, ao_DbData, 0, ao_XMLDoc, lo_CurrentNode, ao_CustomData)
    End If
    Call mo_Db.Next(ac_CursorXML)
  Wend
  Exit Function
errorHandler:
  Call errorHandler("CreateXMLGroupFlat")
End Function

Private Function CreateXMLGroupList(ByVal ac_CursorXML As Long, ByVal ao_DbData As Object, ByVal al_ATS_Id As Long, ByVal ao_XMLDoc As Object, ByVal ao_parentNode As Object, ByVal ao_CustomData As Dictionary)
On Error GoTo errorHandler

Dim ll_XMLPosition As Long
Dim ll_RecIdx As Long
Dim lo_CurrentNode As Object
Dim ls_NodeName As String
Dim lt_XmlSql As TXmlSql
Dim lc_CursorData As Long

  lt_XmlSql = GetXmlSql(al_ATS_Id)
  lc_CursorData = lt_XmlSql.Cursor
  
  ll_XMLPosition = mo_Db.Position(ac_CursorXML)
  
  If mo_Db.RowCount(lc_CursorData) = 0 Then
    'skip group if no data
    While (Not mo_Db.EOF(ac_CursorXML)) And (al_ATS_Id = mo_Db.GetFields(ac_CursorXML, "ATS_Id"))
      Call mo_Db.Next(ac_CursorXML)
    Wend
  Else
    Call ao_DbData.First(lc_CursorData)
    While Not ao_DbData.EOF(lc_CursorData)
      mo_Db.Position(ac_CursorXML) = ll_XMLPosition
      ll_RecIdx = mo_Db.Position(lc_CursorData) + 1
      ls_NodeName = Trim(mo_Db.GetFields(ac_CursorXML, "ATS_Node"))
      
      If mo_Db.GetFields(ac_CursorXML, "ATS_IsSubNode") = "X" Then
        ls_NodeName = Replace(ls_NodeName, "$N$", CStr(ll_RecIdx), , , vbTextCompare)
        Set lo_CurrentNode = AppendElement(ao_XMLDoc, ao_parentNode, ls_NodeName, "")
      Else
        Set lo_CurrentNode = ao_parentNode
      End If
      
      While (Not mo_Db.EOF(ac_CursorXML)) And (al_ATS_Id = mo_Db.GetFields(ac_CursorXML, "ATS_Id"))
        
        Call Bae_CreateXMLNode(ac_CursorXML, ao_DbData, lc_CursorData, ao_XMLDoc, lo_CurrentNode, ao_CustomData)
        
        Call mo_Db.Next(ac_CursorXML)
      Wend
      Call ao_DbData.Next(lc_CursorData)
    Wend
  End If
  Exit Function
errorHandler:
  Call errorHandler("CreateXMLGroupList")
End Function

'Private Function ReplaceMaterialValues(ByVal as_Value As String) As String
'On Error GoTo errorHandler
'
'  If me_RawMaterial = eDPCBOMMaterial.bcCoil Then
'    as_Value = Replace(as_Value, "$IdentNr$", FormatXML(ms_NewIdentNr, "C", 0), , , vbTextCompare)
'    as_Value = Replace(as_Value, "$ben$", FormatXML(ms_MaterialName, "C", 0), , , vbTextCompare)
'    as_Value = Replace(as_Value, "$werkstoff$", FormatXML(ms_Material, "C", 0), , , vbTextCompare)
'    as_Value = Replace(as_Value, "$breiteb$", FormatXML(md_CoilWidth, "N", 2), , , vbTextCompare)
'    as_Value = Replace(as_Value, "$matdicke$", FormatXML(md_CoilThickness, "N", 2), , , vbTextCompare)
'
'
'  ElseIf me_RawMaterial = eDPCBOMMaterial.bcInlay Then
'    as_Value = Replace(as_Value, "$IdentNr$", FormatXML(ms_NewIdentNr, "C", 0), , , vbTextCompare)
'    as_Value = Replace(as_Value, "$ben$", FormatXML(ms_MaterialName, "C", 0), , , vbTextCompare)
'  End If
'  ReplaceMaterialValues = as_Value
'  Exit Function
'errorHandler:
'  Call errorHandler("ReplaceMaterialValues")
'End Function

Private Function Bae_ReplaceCustomData(ByVal as_Value As String, ByVal ao_CustomData As Dictionary, ByVal as_DataType As String, ByVal al_DataLength As Long, al_DataPrecision As Long) As String
On Error GoTo errorHandler

Dim ll_Idx As Long

  For ll_Idx = 0 To ao_CustomData.Count - 1
    If StrComp(as_Value, ao_CustomData.keys(ll_Idx), vbTextCompare) = 0 Then
      as_Value = Replace(as_Value, ao_CustomData.keys(ll_Idx), Bae_FormatXML(ao_CustomData.Items(ll_Idx), as_DataType, al_DataPrecision), , , vbTextCompare)
      Exit For
    End If
  Next
  Bae_ReplaceCustomData = as_Value
  Exit Function
errorHandler:
  Call errorHandler("Bae_ReplaceCustomData")
End Function

Private Function Bae_CreateXMLNode(ByVal ac_CursorXML As Long, ByVal ao_Db As Object, ByVal ac_CursorData As Long, ByVal ao_XMLDoc As Object, ByVal ao_parentNode As Object, ByVal ao_CustomData As Dictionary)
On Error GoTo errorHandler

Dim ls_DataType As String
Dim ll_DataLength As Long
Dim ll_DataPrecision As Long
Dim ls_Name As String
Dim ll_Idx As Long
Dim ls_Value As String
Dim ls_Default As String
Dim ls_CodeLookup As String
Dim le_ATR_Type As eDPCXmlExportType

  ls_Default = Trim(mo_Db.GetFields(ac_CursorXML, "ATR_DefaultValue"))
  ls_Value = Trim(mo_Db.GetFields(ac_CursorXML, "ATR_Value"))
  ls_DataType = Trim(mo_Db.GetFields(ac_CursorXML, "ATR_DataType"))
  ll_DataLength = Trim(mo_Db.GetFields(ac_CursorXML, "ATR_DataLength"))
  ll_DataPrecision = Trim(mo_Db.GetFields(ac_CursorXML, "ATR_DataPrecision"))
  ls_CodeLookup = Trim(mo_Db.GetFields(ac_CursorXML, "AC_CodeLookup"))
  le_ATR_Type = mo_Db.GetFields(ac_CursorXML, "ATR_Type")
  
  If Left(ls_Default, 1) = "'" And right(ls_Default, 1) = "'" Then
    ls_Default = Mid(ls_Default, 2, Len(ls_Default) - 2)
  End If
  
  If ls_Value = "" Then
    ls_Value = ls_Default
  Else
    If ac_CursorData = 0 Then
      ls_Value = ""
    Else
      ls_Value = Replace(ls_Value, "$RowIndex$", CStr(ao_Db.Position(ac_CursorData) + 1), , , vbTextCompare)
      If Not ao_CustomData Is Nothing Then
        ls_Value = Bae_ReplaceCustomData(ls_Value, ao_CustomData, ls_DataType, ll_DataLength, ll_DataPrecision)
      End If
      For ll_Idx = 0 To ao_Db.FieldCount(ac_CursorData) - 1
        ls_Name = "$" & ao_Db.GetFieldName(ac_CursorData, ll_Idx) & "$"
        If StrComp(ls_Value, ls_Name, vbTextCompare) = 0 Then
          If ls_CodeLookup = "" Then
            ls_Value = Bae_FormatXML(ao_Db.GetFields(ac_CursorData, ll_Idx), ls_DataType, ll_DataPrecision)
          Else
            ls_Value = mo_Tools.ConvertCodeToBaeurer(mo_Db, mo_Tools.GetConversionCode(ls_CodeLookup), ao_Db.GetFields(ac_CursorData, ll_Idx))
            ls_Value = Bae_FormatXML(ls_Value, ls_DataType, ll_DataPrecision)
          End If
          Exit For
        ElseIf InStr(1, ls_Value, ls_Name, vbTextCompare) > 0 Then
          If ao_Db.GetFieldType(ac_CursorData, ll_Idx) = ArmSysType.DBTYPE_I4 Then
            ls_Value = Replace(ls_Value, ls_Name, Bae_FormatXML(ao_Db.GetFields(ac_CursorData, ll_Idx), "N", 0), , , vbTextCompare)
          ElseIf (ao_Db.GetFieldType(ac_CursorData, ll_Idx) = ArmSysType.DBTYPE_R4) Or (ao_Db.GetFieldType(ac_CursorData, ll_Idx) = ArmSysType.DBTYPE_R8) Then
            ls_Value = Replace(ls_Value, ls_Name, Bae_FormatXML(ao_Db.GetFields(ac_CursorData, ll_Idx), "N", 2), , , vbTextCompare)
          ElseIf (ao_Db.GetFieldType(ac_CursorData, ll_Idx) = ArmSysType.DBTYPE_DATE) Then
            ls_Value = Replace(ls_Value, ls_Name, Bae_FormatXML(ao_Db.GetFields(ac_CursorData, ll_Idx), "D", 0), , , vbTextCompare)
          Else
            ls_Value = Replace(ls_Value, ls_Name, Bae_FormatXML(ao_Db.GetFields(ac_CursorData, ll_Idx), "C", 0), , , vbTextCompare)
          End If
        End If
      Next
    End If
    If Left(ls_Value, 1) = "$" And right(ls_Value, 1) = "$" Then
      ls_Value = ls_Default
    End If
  End If
  Call AppendElement(ao_XMLDoc, ao_parentNode, mo_Db.GetFields(ac_CursorXML, "ATR_B7Name"), ls_Value)
  Exit Function
errorHandler:
  Call errorHandler("Bae_CreateXMLNode")
End Function

Private Function SAP_CreateXMLNode(ByVal as_Name As String, ByVal ac_CursorXML As Long, ByVal av_Value As Variant, ByVal ao_XMLDoc As Object, ByVal ao_parentNode As Object)
On Error GoTo errorHandler

Dim ls_DataType As String
Dim ll_DataLength As Long
Dim ll_DataPrecision As Long
Dim ls_Name As String
Dim ll_Idx As Long
Dim ls_Value As String
Dim ls_Default As String
Dim ls_CodeLookup As String
Dim ls_AtrName As String

  If mo_Db.Find(ac_CursorXML, "ATR_Name", as_Name, 0, 1) < 0 Then
       Err.Raise ArmErr.SQLBadRowExpectedCount, "Find", "No SQL Data for XML export found. ATR_B7Name missing:" + as_Name
       Exit Function
  End If

  ls_AtrName = Trim(mo_Db.GetFields(ac_CursorXML, "ATR_Name"))
  ls_Default = Trim(mo_Db.GetFields(ac_CursorXML, "ATR_DefaultValue"))
  ls_Value = Trim(mo_Db.GetFields(ac_CursorXML, "ATR_Value"))
  ls_DataType = Trim(mo_Db.GetFields(ac_CursorXML, "ATR_DataType"))
  ll_DataLength = Trim(mo_Db.GetFields(ac_CursorXML, "ATR_DataLength"))
  ll_DataPrecision = Trim(mo_Db.GetFields(ac_CursorXML, "ATR_DataPrecision"))
  ls_CodeLookup = Trim(mo_Db.GetFields(ac_CursorXML, "AC_CodeLookup"))
  
  If Left(ls_Default, 1) = "'" And right(ls_Default, 1) = "'" Then
    ls_Default = Mid(ls_Default, 2, Len(ls_Default) - 2)
  End If
  
  If ls_Value = "" Then
    ls_Value = ls_Default
  Else
    If ls_CodeLookup = "" Then
      ls_Value = SAP_FormatXML(av_Value, ls_DataType, ll_DataPrecision)
    Else
      ls_Value = ConvertCodeToAMC(ls_CodeLookup, av_Value)
      ls_Value = SAP_FormatXML(ls_Value, ls_DataType, ll_DataPrecision)
    End If
  End If
  
  If Len(ls_Value) > ll_DataLength Then
    ls_Value = Left(ls_Value, ll_DataLength)
  End If
  
  Call AppendElement(ao_XMLDoc, ao_parentNode, mo_Db.GetFields(ac_CursorXML, "ATR_B7Name"), ls_Value)
  Exit Function
errorHandler:
  Call errorHandler("SAP_CreateXMLNode ATR_Name=" & ls_AtrName)
End Function

Private Function Bae_FormatXML(ByVal av_Data As Variant, ByVal as_DataType As String, ByVal al_DataPrecision As Long)
On Error GoTo errorHandler

  Bae_FormatXML = ""
  Select Case UCase(as_DataType)
  Case "N"
    If al_DataPrecision = 0 Then
      Bae_FormatXML = BAE_FormatXMLInt(Val(av_Data))
    Else
      Bae_FormatXML = BAE_FormatXMLFloat(av_Data, al_DataPrecision)
    End If
  Case "D"
    Bae_FormatXML = Bae_FormatXMLDateTime(av_Data)
  Case Else
    Bae_FormatXML = CStr(av_Data)
  End Select
  Exit Function
errorHandler:
  Call errorHandler("Bae_FormatXML")
End Function

Private Function SAP_FormatXML(ByVal av_Data As Variant, ByVal as_DataType As String, ByVal al_DataPrecision As Long)
On Error GoTo errorHandler

  SAP_FormatXML = ""
  Select Case UCase(as_DataType)
  Case "N"
    If al_DataPrecision = 0 Then
      SAP_FormatXML = SAP_FormatXMLInt(Val(av_Data))
    Else
      SAP_FormatXML = SAP_FormatXMLFloat(av_Data, 2)
    End If
  Case "D"
    SAP_FormatXML = SAP_FormatXMLDateTime(av_Data)
  Case Else
    SAP_FormatXML = CStr(av_Data)
  End Select
  Exit Function
errorHandler:
  Call errorHandler("SAP_FormatXML")
End Function

Private Function Bae_GetXmlCursor(ByVal ae_ATR_Type As eDPCXmlExportType) As Long
On Error GoTo errorHandler

Dim ls_Request As String

  ls_Request = "exec DPC_AttribXML_lst $ATR_Type$"

  ls_Request = Replace(ls_Request, "$ATR_Type$", mo_Tools.SqlInt(ae_ATR_Type), , , vbTextCompare)
  Bae_GetXmlCursor = mo_Tools.OpenSQLSafe(mo_Db, ls_Request)
  
  Exit Function
errorHandler:
  Call errorHandler("Bae_GetXmlCursor")
End Function

Private Function SAP_GetXmlCursor(ByVal ae_ATR_Type As eDPCXmlExportType) As Long
On Error GoTo errorHandler

Dim ls_Request As String

  ls_Request = "exec DPC_AttribXML_SAP_lst $ATR_Type$"
  ls_Request = Replace(ls_Request, "$ATR_Type$", mo_Tools.SqlInt(ae_ATR_Type), , , vbTextCompare)
  SAP_GetXmlCursor = mo_Tools.OpenSQLSafe(mo_Db, ls_Request)
  Exit Function
errorHandler:
  Call errorHandler("SAP_GetXmlCursor")
End Function

Private Sub InitSqlData(ByVal ao_Db As Object, ByVal ac_XmlCursor As Long, ByVal as_Key As String)
On Error GoTo errorHandler

Dim ll_Idx As Long
Dim lc_Cursor As Long
Dim ll_RowCount As Long
Dim ls_Request As String

  ReDim mta_XmlSql(-1 To -1)
  lc_Cursor = mo_Db.Distinct(ac_XmlCursor, Array("ATS_Id", "ATS_Sql", "ATS_Type", "ATS_Node", "ATS_IsSubNode", "ATS_IsMaster", "ATS_ImportName", "ATS_Profile", "ATS_Version"), False)
  ll_RowCount = mo_Db.RowCount(lc_Cursor)
  If ll_RowCount > 0 Then
    ReDim mta_XmlSql(ll_RowCount - 1)
    Call mo_Db.First(lc_Cursor)
    ll_Idx = 0
    While Not mo_Db.EOF(lc_Cursor)
      mta_XmlSql(ll_Idx).ATS_Id = mo_Db.GetFields(lc_Cursor, "ATS_Id")
      mta_XmlSql(ll_Idx).Request = mo_Db.GetFields(lc_Cursor, "ATS_Sql")
      mta_XmlSql(ll_Idx).ATS_Type = mo_Db.GetFields(lc_Cursor, "ATS_Type")
      mta_XmlSql(ll_Idx).ATS_Node = mo_Db.GetFields(lc_Cursor, "ATS_Node")
      mta_XmlSql(ll_Idx).ATS_IsSubNode = StrComp(mo_Db.GetFields(lc_Cursor, "ATS_IsSubNode"), "X", vbTextCompare) = 0
      mta_XmlSql(ll_Idx).ATS_IsMaster = StrComp(mo_Db.GetFields(lc_Cursor, "ATS_IsMaster"), "X", vbTextCompare) = 0
      mta_XmlSql(ll_Idx).ATS_ImportName = mo_Db.GetFields(lc_Cursor, "ATS_ImportName")
      mta_XmlSql(ll_Idx).ATS_Profile = mo_Db.GetFields(lc_Cursor, "ATS_Profile")
      mta_XmlSql(ll_Idx).ATS_Version = mo_Db.GetFields(lc_Cursor, "ATS_Version")
      
      ls_Request = Replace(mta_XmlSql(ll_Idx).Request, "$Key$", mo_Tools.SQLStr(as_Key), , , vbTextCompare)
      mta_XmlSql(ll_Idx).Cursor = mo_Tools.OpenSQLSafe(ao_Db, ls_Request)
      Call mo_Db.Next(lc_Cursor)
      ll_Idx = ll_Idx + 1
    Wend
  Else
    Err.Raise ArmErr.SQLBadRowExpectedCount, "Distinct", "No SQL Data for XML export found."
  End If
  Call mo_Db.Close(lc_Cursor)
  Exit Sub
errorHandler:
  Call errorHandler("InitSqlData")
End Sub

Private Sub CloseSqlData(ByVal ao_Db As Object)
On Error GoTo errorHandler

Dim ll_Idx As Long

  For ll_Idx = 0 To UBound(mta_XmlSql)
    Call ao_Db.Close(mta_XmlSql(ll_Idx).Cursor)
  Next
  ReDim mta_XmlSql(-1 To -1)
  Exit Sub
errorHandler:
  Call errorHandler("CloseSqlData")
End Sub

Private Function GetXmlSql(ByVal al_ATS_Id As Long) As TXmlSql
On Error GoTo errorHandler

Dim ll_Idx As Long
  
  For ll_Idx = 0 To UBound(mta_XmlSql)
    If al_ATS_Id = mta_XmlSql(ll_Idx).ATS_Id Then
      GetXmlSql = mta_XmlSql(ll_Idx)
      Exit Function
    End If
  Next
  Exit Function
errorHandler:
  Call errorHandler("GetXmlSql")
End Function

Private Function GetXmlMasterSql() As TXmlSql
On Error GoTo errorHandler

Dim ll_Idx As Long
  
  For ll_Idx = 0 To UBound(mta_XmlSql)
    If mta_XmlSql(ll_Idx).ATS_IsMaster Then
      GetXmlMasterSql = mta_XmlSql(ll_Idx)
      Exit Function
    End If
  Next
  Exit Function
errorHandler:
  Call errorHandler("GetXmlMasterSql")
End Function

Private Function Bae_FormatXMLDateTime(ByVal ad_Value As Date) As String
On Error GoTo errorHandler
  
  Bae_FormatXMLDateTime = Format(ad_Value, "mm\/dd\/yyyy hh:mm:ss")
  Exit Function
errorHandler:
  Call errorHandler("Bae_FormatXMLDateTime")
End Function

Private Function SAP_FormatXMLDateTime(ByVal ad_Value As Date) As String
On Error GoTo errorHandler
  
  If ad_Value = 0 Then
    SAP_FormatXMLDateTime = ""
  Else
    SAP_FormatXMLDateTime = Format(ad_Value, "yyyymmdd")
  End If
  Exit Function
errorHandler:
  Call errorHandler("SAP_FormatXMLDateTime")
End Function

Private Function BAE_FormatXMLFloat(ByVal ad_Value As Double, ByVal al_Precision As Long) As String
On Error GoTo errorHandler

  If al_Precision = 0 Then
    BAE_FormatXMLFloat = Format(Round(ad_Value, al_Precision), "0")
  Else
    BAE_FormatXMLFloat = Replace(Format(Round(ad_Value, al_Precision), "0." & String(al_Precision, "0")), ".", ",", , , vbTextCompare)
  End If
  Exit Function
errorHandler:
  Call errorHandler("BAE_FormatXMLFloat")
End Function

Private Function SAP_FormatXMLFloat(ByVal ad_Value As Double, ByVal al_Precision As Long) As String
On Error GoTo errorHandler

  If al_Precision = 0 Then
    SAP_FormatXMLFloat = Format(Round(ad_Value, al_Precision), "0")
  Else
    SAP_FormatXMLFloat = Replace(Format(Round(ad_Value, al_Precision), "0." & String(al_Precision, "0")), ",", ".", , , vbTextCompare)
  End If
  Exit Function
errorHandler:
  Call errorHandler("SAP_FormatXMLFloat")
End Function

Private Function BAE_FormatXMLInt(ByVal al_Value As Long) As String
On Error GoTo errorHandler
  
  BAE_FormatXMLInt = CStr(al_Value)
  Exit Function
errorHandler:
  Call errorHandler("BAE_FormatXMLInt")
End Function

Private Function SAP_FormatXMLInt(ByVal al_Value As Long) As String
On Error GoTo errorHandler
  
  SAP_FormatXMLInt = CStr(al_Value)
  Exit Function
errorHandler:
  Call errorHandler("SAP_FormatXMLInt")
End Function

Private Function AppendElement(ByRef ao_Document As MSXML2.DOMDocument, ByRef ao_parentNode As MSXML2.IXMLDOMNode, ByVal as_Name As String, ByVal as_Value As String) As MSXML2.IXMLDOMNode
On Error GoTo errorHandler
    
   Set AppendElement = Nothing
    
#If LIVE = 1 Then
    Dim lo_newNode As Object
#Else
    Dim lo_newNode As MSXML2.IXMLDOMElement
#End If
    Set lo_newNode = ao_Document.createElement(as_Name)
    
    lo_newNode.Text = as_Value
    If ao_parentNode Is Nothing Then
      Set AppendElement = ao_Document.appendChild(lo_newNode)
    Else
      Set AppendElement = ao_parentNode.appendChild(lo_newNode)
    End If
    Exit Function
errorHandler:
    Call errorHandler("AppendElement")
End Function

Public Sub Bae_ImportArticleAll()
On Error GoTo errorHandler

Dim lc_Cursor As Long
Dim ls_Req As String
Dim ll_RowIdTran As Long
Dim ls_Result As String
Dim le_Status As Long

  ls_Req = "exec DPC_BaeurerPrd_lst $PRD_Id$,$PMaster_Status$,$SBox_Status$"
  ls_Req = Replace(ls_Req, "$PRD_Id$", "NULL", , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$PMaster_Status$", mo_Tools.SqlInt(eDPCBaeurerExportStatus.esExported), , vbTextCompare)
  ls_Req = Replace(ls_Req, "$SBox_Status$", "NULL", , , vbTextCompare)
  lc_Cursor = mo_Tools.OpenSQLSafe(mo_Db, ls_Req)
  While Not mo_Db.EOF(lc_Cursor)
    ll_RowIdTran = mo_Db.GetFields(lc_Cursor, "PMaster_Rowidtran")
    ls_Result = Bae_CheckArticleExportResult(ll_RowIdTran)
    
    le_Status = eDPCBaeurerExportStatus.esNone
    If StrComp(ls_Result, ROWIDTRANSTATUS_ERROR, vbTextCompare) = 0 Then
      le_Status = eDPCBaeurerExportStatus.esExportFailed
    ElseIf StrComp(ls_Result, ROWIDTRANSTATUS_ERROR, vbTextCompare) = 0 Then
      le_Status = eDPCBaeurerExportStatus.esExportOK
    End If
    
    If le_Status <> eDPCBaeurerExportStatus.esNone Then
      ls_Req = "UPDATE DPC_PrdBaeurer SET "
      ls_Req = ls_Req & "PMaster_Status=$PMaster_Status$,"
      ls_Req = ls_Req & "PMaster_Date=getdate(),"
      ls_Req = ls_Req & "Z_Last_Upd_User=$Z_Last_Upd_User$,"
      ls_Req = ls_Req & "Z_Last_Upd=getdate(),"
      ls_Req = ls_Req & "WHERE PRD_Id=$PRD_Id$"
      ls_Req = Replace(ls_Req, "$PRD_Id$", "NULL", , , vbTextCompare)
      ls_Req = Replace(ls_Req, "$PMaster_Status$", mo_Tools.SqlInt(le_Status), , vbTextCompare)
      Call mo_Tools.ExecuteSQLSafe(mo_Db, ls_Req, 1)
    End If
    Call mo_Db.Next(lc_Cursor)
  Wend
  Call mo_Db.Close(lc_Cursor)
  Exit Sub
errorHandler:
  Call errorHandler("Bae_ImportArticleAll")
End Sub

Public Sub Bae_ExportArticleAll()
On Error GoTo errorHandler

Dim lc_Cursor As Long
Dim ls_Req As String
Dim ll_RowIdTran As Long

  ls_Req = "exec DPC_BaeurerPrd_lst $PRD_Id$,$PMaster_Status$,$SBox_Status$"
  ls_Req = Replace(ls_Req, "$PRD_Id$", "NULL", , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$PMaster_Status$", mo_Tools.SqlInt(eDPCBaeurerExportStatus.esReadyToExport), , vbTextCompare)
  ls_Req = Replace(ls_Req, "$SBox_Status$", "NULL", , , vbTextCompare)
  lc_Cursor = mo_Tools.OpenSQLSafe(mo_Db, ls_Req)
  While Not mo_Db.EOF(lc_Cursor)
    ll_RowIdTran = Bae_ExportArticle(mo_Db.GetFields(mo_Db, "PRD_Id"))
    
    ls_Req = "UPDATE DPC_PrdBaeurer SET "
    ls_Req = ls_Req & "PMaster_Status=$PMaster_Status$,"
    ls_Req = ls_Req & "PMaster_Date=getdate(),"
    ls_Req = ls_Req & "PMaster_Rowidtran=$Rowidtran$,"
    ls_Req = ls_Req & "Z_Last_Upd_User=$Z_Last_Upd_User$,"
    ls_Req = ls_Req & "Z_Last_Upd=getdate(),"
    ls_Req = ls_Req & "WHERE PRD_Id=$PRD_Id$"
    ls_Req = Replace(ls_Req, "$PRD_Id$", "NULL", , , vbTextCompare)
    ls_Req = Replace(ls_Req, "$PMaster_Status$", mo_Tools.SqlInt(eDPCBaeurerExportStatus.esExported), , vbTextCompare)
    ls_Req = Replace(ls_Req, "$Rowidtran$", mo_Tools.SqlInt(ll_RowIdTran), , vbTextCompare)
    Call mo_Tools.ExecuteSQLSafe(mo_Db, ls_Req, 1)
    Call mo_Db.Next(lc_Cursor)
  Wend
  Call mo_Db.Close(lc_Cursor)
  Exit Sub
errorHandler:
  Call errorHandler("Bae_ExportArticleAll")
End Sub

Public Function Bae_ExportBOMMaterial(ByVal as_PRD_Id As String) As Boolean
On Error GoTo errorHandler

Dim lo_DPC_Product As DPC_Product
Dim lo_BOM As DPC_BOM

  Bae_ExportBOMMaterial = False
  Set lo_DPC_Product = New DPC_Product
  Set lo_DPC_Product.Tools = mo_Tools
  Set lo_DPC_Product.ArmDb = mo_Db
  lo_DPC_Product.U_Code = ml_U_Code
  lo_DPC_Product.CT_Code = ms_CT_Code
  lo_DPC_Product.CURR_Code = "EUR"
  lo_DPC_Product.ValidityDate = ValidityDate
  lo_DPC_Product.Language_Code = ms_Language_Code
  Call lo_DPC_Product.Load_A_COM
  Call lo_DPC_Product.Load(as_PRD_Id)
  Call lo_DPC_Product.LoadBOM
  For Each lo_BOM In lo_DPC_Product.BOMs
    If (StrComp(lo_BOM.BOM_IdentNr, DPC_BOM_NEW_IDENTNR, vbTextCompare) = 0) And (lo_BOM.BOM_IdentNrTmp <> "") Then
      If lo_BOM.BOM_Categ = eDPCBOMMaterial.bcCoil Then
        If Bae_ExportCoil(lo_DPC_Product, lo_BOM) Then
          lo_DPC_Product.COI_Code = lo_BOM.BOM_IdentNr
          Call lo_DPC_Product.UpdatePrdRectPanel
          Call lo_DPC_Product.UpdateBOMExport(lo_BOM)
        Else
          Exit Function
        End If
      ElseIf lo_BOM.BOM_Categ = eDPCBOMMaterial.bcInlay Then
        If Bae_ExportInlay(lo_DPC_Product, lo_BOM) Then
          Call lo_DPC_Product.UpdateBOMExport(lo_BOM)
        Else
          Exit Function
        End If
      Else
        Exit Function
      End If
    End If
  Next
  Call lo_DPC_Product.Unload_A_COM
  Set lo_DPC_Product = Nothing
  Bae_ExportBOMMaterial = True
  Exit Function
errorHandler:
  Call errorHandler("Bae_ExportBOMMaterial")
End Function


Public Function Bae_ExportCoil(ByVal ao_DPC_Product As DPC_Product, ByVal ao_BOM As DPC_BOM) As Boolean
On Error GoTo errorHandler

Dim lo_XmlDocCoil As Object
Dim ll_RowIdTran As Long
Dim lc_Cursor As Long
Dim ll_VersionCoil As Long
Dim ls_Req As String
Dim ls_ThickPrefix As String
Dim ls_IdentPrefix As String
Dim ls_IdentNr As String
Dim ls_IdentNrTmp As String
Dim le_RawMaterial As eDPCBOMMaterial
Dim ls_Material As String
Dim ls_MaterialName As String
Dim lo_CustomData As Dictionary

  Bae_ExportCoil = False
  
  ls_IdentNr = ""
  ls_IdentNrTmp = ao_BOM.BOM_IdentNrTmp
  ls_IdentPrefix = Left(ao_BOM.BOM_IdentNrTmp, 2)
  
  le_RawMaterial = eDPCBOMMaterial.bcCoil
  ls_Material = ao_DPC_Product.RPL_MatTyp
  ls_MaterialName = "Spaltband " & mo_Tools.DblToScreen(ao_DPC_Product.RPL_CoilW) & " x " & mo_Tools.DblToScreen(ao_DPC_Product.RPL_Thick)
  
  ls_Req = "exec DPC_Bae_Material_sel $IdentNr$,$BMN_Type$,$BMN_Prefix$,$BMN_Mat$,$BMN_Length$,$BMN_Width$,$BMN_Height$,$BMN_Thick$"
  ls_Req = Replace(ls_Req, "$IdentNr$", "NULL", , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$BMN_Type$", mo_Tools.SqlInt(le_RawMaterial), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$BMN_Prefix$", "NULL", , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$BMN_Mat$", mo_Tools.SQLStr(ls_Material), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$BMN_Length$", "NULL", , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$BMN_Width$", mo_Tools.SqlDbl(ao_DPC_Product.RPL_CoilW), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$BMN_Height$", "NULL", , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$BMN_Thick$", mo_Tools.SqlDbl(ao_DPC_Product.RPL_Thick), , , vbTextCompare)
  lc_Cursor = mo_Tools.OpenSQLSafe(mo_Db, ls_Req)
  If mo_Db.RowCount(lc_Cursor) = 1 Then
    ls_IdentNr = mo_Tools.SelectValue(mo_Db, ls_Req, "IdentNr")
    ls_MaterialName = mo_Tools.SelectValue(mo_Db, ls_Req, "BMN_Name")
    ls_Material = mo_Tools.SelectValue(mo_Db, ls_Req, "BMN_Mat")
  End If
  Call mo_Db.Close(lc_Cursor)
  
  If ls_IdentNr <> "" Then
    ao_BOM.BOM_IdentNr = ls_IdentNr
    ao_BOM.BOM_Name = ls_MaterialName
    ao_BOM.BOM_Material = ls_Material
    Bae_ExportCoil = True
    Exit Function
  End If
  
  If Not mo_Tools.ReconnectSafe(mo_DbBaeurer, ms_BaeurerServer, ms_BaeurerDatabase, ms_BaeurerLoginName, ms_BaeurerPassword, ms_BaeurerSource) Then
    Exit Function
  End If
  
'  ls_req = "SELECT TOP 1 g000.IdentNr "
'  ls_req = ls_req & "FROM g000 "
'  ls_req = ls_req & "LEFT JOIN g040 ON (g000.fi_nr = g040.fi_nr AND g000.identnr = g040.identnr ) "
'  ls_req = ls_req & "LEFT JOIN g0402 ON (g000.fi_nr = g0402.fi_nr AND g000.identnr = g0402.identnr and g0402.lang_ext ='de_de') "
'  ls_req = ls_req & "LEFT JOIN g711 as g711Width ON (g000.objektid = g711Width.objektid and g711Width.kritnr = 12) "
'  ls_req = ls_req & "LEFT JOIN g711 as g711Thick ON (g000.objektid = g711Thick.objektid and g711Thick.kritnr = 17) "
'  ls_req = ls_req & "LEFT JOIN g711 as g711SpecWeight ON (g000.objektid = g711SpecWeight.objektid and g711SpecWeight.kritnr = 20) "
'  ls_req = ls_req & "LEFT JOIN g711 as g711Waste ON (g000.objektid = g711Waste.objektid and g711Waste.kritnr = 54) "
'  ls_req = ls_req & "LEFT JOIN g020 ON (g000.identnr = g020.identnr) "
'  ls_req = ls_req & "LEFT JOIN g711 as g711StdCoil ON (g000.objektid = g711StdCoil.objektid and g711StdCoil.kritnr = 1181) "
'  ls_req = ls_req & "LEFT JOIN g023 ON (g000.fi_nr = g023.fi_nr AND g000.identnr = g023.identnr) "
'  ls_req = ls_req & "LEFT JOIN g030 on (g000.identnr = g030.identnr AND g000.fi_nr = g030.fi_nr) "
'  ls_req = ls_req & "WHERE "
'  ls_req = ls_req & "(g000.identnr LIKE $MAT_Pefx$) AND "
'  ls_req = ls_req & "(g0402.werkstoff = $MAT_Werk$) AND "
'  ls_req = ls_req & "(g040.ts = $ts$) AND "
'  ls_req = ls_req & "(g020.lgnr = $lgnr$) "
'
'  ls_req = Replace(ls_req, "$MAT_Pefx$", mo_Tools.SQLStr(as_IdentPrefix & "%"), , , vbTextCompare)
'  ls_req = Replace(ls_req, "$ts$", mo_Tools.SQLStr(1), , , vbTextCompare)
'  ls_req = Replace(ls_req, "$lgnr$", mo_Tools.SqlInt(0), , , vbTextCompare)
'  ls_req = Replace(ls_req, "$MAT_Werk$", mo_Tools.SQLStr(as_Material), , , vbTextCompare)
'
'
'  lc_Cursor = mo_Tools.OpenSQLSafe(mo_DbBaeurer, ls_req)
'  ls_Key = mo_DbBaeurer.GetFields(lc_Cursor, 0)
'  Call mo_DbBaeurer.Close(lc_Cursor)
  
  ls_Req = "SELECT MAX(g000.identnr) "
  ls_Req = ls_Req & "FROM g000 "
  ls_Req = ls_Req & "WHERE "
  ls_Req = ls_Req & "(g000.identnr LIKE $MAT_Pefx$) AND (LEN(g000.identnr) = $lenght$)"
  
'  ls_req = "SELECT MAX(g000.identnr) as IdentNr "
'  ls_req = ls_req & "FROM g000 "
'  ls_req = ls_req & "LEFT JOIN g040 ON (g000.fi_nr = g040.fi_nr AND g000.identnr = g040.identnr ) "
'  ls_req = ls_req & "LEFT JOIN g0402 ON (g000.fi_nr = g0402.fi_nr AND g000.identnr = g0402.identnr and g0402.lang_ext ='de_de') "
'  ls_req = ls_req & "LEFT JOIN g711 as g711Width ON (g000.objektid = g711Width.objektid and g711Width.kritnr = 12) "
'  ls_req = ls_req & "LEFT JOIN g711 as g711Thick ON (g000.objektid = g711Thick.objektid and g711Thick.kritnr = 17) "
'  ls_req = ls_req & "LEFT JOIN g711 as g711SpecWeight ON (g000.objektid = g711SpecWeight.objektid and g711SpecWeight.kritnr = 20) "
'  ls_req = ls_req & "LEFT JOIN g711 as g711Waste ON (g000.objektid = g711Waste.objektid and g711Waste.kritnr = 54) "
'  ls_req = ls_req & "LEFT JOIN g020 ON (g000.identnr = g020.identnr) "
'  ls_req = ls_req & "LEFT JOIN g711 as g711StdCoil ON (g000.objektid = g711StdCoil.objektid and g711StdCoil.kritnr = 1181) "
'  ls_req = ls_req & "LEFT JOIN g023 ON (g000.fi_nr = g023.fi_nr AND g000.identnr = g023.identnr) "
'  ls_req = ls_req & "LEFT JOIN g030 on (g000.identnr = g030.identnr AND g000.fi_nr = g030.fi_nr) "
'  ls_req = ls_req & "WHERE "
'  ls_req = ls_req & "((g000.identnr LIKE $MAT_Pefx$) AND (LEN(g000.identnr) = $lenght$)) AND "
'  ls_req = ls_req & "(g0402.werkstoff = $MAT_Werk$ OR $MAT_Werk$ IS NULL) AND "
'  ls_req = ls_req & "(g040.ts = $ts$) AND "
'  ls_req = ls_req & "(g020.lgnr = $lgnr$) "
  
  
  ls_ThickPrefix = Trim(Str(ao_DPC_Product.RPL_Thick))
  If Left(ls_ThickPrefix, 1) = "." Then ls_ThickPrefix = "0" & ls_ThickPrefix
  ls_ThickPrefix = Replace(ls_ThickPrefix, ".", "")
  
  ls_Req = Replace(ls_Req, "$MAT_Pefx$", mo_Tools.SQLStr(ls_IdentPrefix & ls_ThickPrefix & "%"), , , vbTextCompare)
  'ls_req = Replace(ls_req, "$ts$", mo_Tools.SQLStr(1), , , vbTextCompare)
  'ls_req = Replace(ls_req, "$lgnr$", mo_Tools.SqlInt(0), , , vbTextCompare)
  'ls_req = Replace(ls_req, "$MAT_Werk$", "NULL", , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$lenght$", mo_Tools.SqlInt(Len(ls_IdentPrefix & ls_ThickPrefix) + 4), , , vbTextCompare)
  
  ls_IdentNr = mo_Tools.SelectValue(mo_DbBaeurer, ls_Req)
  
  Do
    If ls_IdentNr = "" Then
      ls_IdentNr = ls_IdentPrefix & ls_ThickPrefix & "0001"
    Else
      If right(ls_IdentNr, 4) = "9999" Then
        Call MsgBox("Counter IdentNr for coil prefix: " & ls_IdentPrefix & ls_ThickPrefix & " overflow")
        Exit Function
      Else
        ls_IdentNr = ls_IdentPrefix & ls_ThickPrefix & (right("0000" & Val(right(ls_IdentNr, 4)) + 1, 4))
      End If
    End If
    'check if we recently did not use this identnr for another coil, need to create new identr by incrementing
    ls_Req = "exec DPC_Bae_Material_sel $IdentNr$, $BMN_Type$, $BMN_Prefix$, $BMN_Mat$, $BMN_Length$, $BMN_Width$, $BMN_Height$, $BMN_Thick$"
    ls_Req = Replace(ls_Req, "$IdentNr$", mo_Tools.SQLStr(ls_IdentNr), , , vbTextCompare)
    ls_Req = Replace(ls_Req, "$BMN_Type$", mo_Tools.SqlInt(eDPCBOMMaterial.bcCoil), , , vbTextCompare)
    ls_Req = Replace(ls_Req, "$BMN_Prefix$", "NULL", , , vbTextCompare)
    ls_Req = Replace(ls_Req, "$BMN_Mat$", "NULL", , , vbTextCompare)
    ls_Req = Replace(ls_Req, "$BMN_Length$", "NULL", , , vbTextCompare)
    ls_Req = Replace(ls_Req, "$BMN_Width$", "NULL", , , vbTextCompare)
    ls_Req = Replace(ls_Req, "$BMN_Height$", "NULL", , , vbTextCompare)
    ls_Req = Replace(ls_Req, "$BMN_Thick$", "NULL", , , vbTextCompare)
  Loop Until mo_Tools.SelectValue(mo_Db, ls_Req, "IdentNr") = ""
  
  Set lo_CustomData = New Dictionary
  Call lo_CustomData.Add("$identnr$", ls_IdentNr)
  Call lo_CustomData.Add("$ben$", ls_MaterialName)
  Call lo_CustomData.Add("$werkstoff$", ls_Material)
  Call lo_CustomData.Add("$breiteb$", ao_DPC_Product.RPL_CoilW)
  Call lo_CustomData.Add("$matdicke$", ao_DPC_Product.RPL_Thick)
  Call lo_CustomData.Add("$stlidentnr$", ls_IdentNr)
  Call lo_CustomData.Add("$aplidentnr$", ls_IdentNr)
  Call lo_CustomData.Add("$vpreis$", ao_BOM.BOM_Cost)
  Call lo_CustomData.Add("$orpreis$", ao_BOM.BOM_Cost)
  Call lo_CustomData.Add("$invpreis$", ao_BOM.BOM_Cost)
  Call lo_CustomData.Add("$datvon$", ao_BOM.BOM_DatVon)
  Call lo_CustomData.Add("$menge_ab$", ao_BOM.BOM_Menge_Ab)
  Set lo_XmlDocCoil = Bae_CreateXMLDocument(mo_DbBaeurer, eDPCXmlExportType.etBae_Material, ls_IdentNrTmp, ll_VersionCoil, lo_CustomData)
  
#If TEST = 0 Then
  'Call SaveXMLDocument(lo_XmlDocCoil, "PMASTER")
  'Exit Function
#End If
  
  ll_RowIdTran = Bae_ExportPMasterRecord(mo_DbBaeurer, 0, ls_IdentNr, eDPCXmlExportType.etBae_Material, lo_XmlDocCoil, ll_VersionCoil)
  Call Bae_ExportPMasterComplete(mo_DbBaeurer, ll_RowIdTran, ls_IdentNr)
  'insert exported ident nr into our historical table
  ls_Req = "exec DPC_Bae_Material_ins $IdentNr$,$BMN_Name$,$BMN_Type$,$BMN_Prefix$,$BMN_Mat$,$BMN_Length$,$BMN_Width$,$BMN_Height$,$BMN_Thick$, $U_Code$"
  ls_Req = Replace(ls_Req, "$IdentNr$", mo_Tools.SQLStr(ls_IdentNr), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$BMN_Name$", mo_Tools.SQLStr(ls_MaterialName), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$BMN_Type$", mo_Tools.SqlInt(eDPCBOMMaterial.bcCoil), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$BMN_Prefix$", mo_Tools.SQLStr(ls_IdentPrefix), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$BMN_Mat$", mo_Tools.SQLStr(ls_Material), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$BMN_Length$", "0", , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$BMN_Width$", mo_Tools.SqlDbl(ao_DPC_Product.RPL_CoilW), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$BMN_Height$", "0", , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$BMN_Thick$", mo_Tools.SqlDbl(ao_DPC_Product.RPL_Thick), , , vbTextCompare)
  ls_Req = ReplaceCommonPlaceholders(ls_Req)
  Call mo_Tools.ExecuteSQLSafe(mo_Db, ls_Req)
  
  ao_BOM.BOM_IdentNr = ls_IdentNr
  ao_BOM.BOM_Name = ls_MaterialName
  ao_BOM.BOM_Material = ls_Material
  
  Call lo_CustomData.RemoveAll
  Set lo_CustomData = Nothing
  Bae_ExportCoil = True
  Exit Function
errorHandler:
  Call errorHandler("Bae_ExportCoil")
End Function

Public Function Bae_ExportInlay(ByVal ao_DPC_Product As DPC_Product, ByVal ao_BOM As DPC_BOM) As Boolean
On Error GoTo errorHandler

Dim lo_XmlDocInlay As Object
Dim ll_RowIdTran As Long
Dim lc_Cursor As Long
Dim ll_VersionInlay As Long
Dim ls_Req As String
Dim ls_IdentNr As String
Dim ls_IdentPrefix As String
Dim ls_IdentNrTmp As String
Dim le_RawMaterial As eDPCBOMMaterial
Dim ls_Material As String
Dim ls_MaterialName As String
Dim lo_CustomData As Dictionary
Dim ls_UoM_PCS As String

  Bae_ExportInlay = False
  
  ls_IdentNr = ""
  ls_IdentNrTmp = ao_BOM.BOM_IdentNrTmp
  ls_IdentPrefix = "3EX"
  
  le_RawMaterial = eDPCBOMMaterial.bcInlay
  ls_MaterialName = "Akustikvlieszuschnitt " & mo_Tools.DblToScreen(ao_BOM.BOM_CutLength, 1) & "x" & mo_Tools.DblToScreen(ao_BOM.BOM_CutWidth, 1) & " mm"
  ls_Material = ao_BOM.BOM_Material
  
  ls_Req = "exec DPC_Bae_Material_sel $IdentNr$,$BMN_Type$,$BMN_Prefix$,$BMN_Mat$,$BMN_Length$,$BMN_Width$,$BMN_Height$,$BMN_Thick$"
  ls_Req = Replace(ls_Req, "$IdentNr$", "NULL", , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$BMN_Type$", mo_Tools.SqlInt(eDPCBOMMaterial.bcInlay), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$BMN_Prefix$", mo_Tools.SQLStr(ls_IdentPrefix), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$BMN_Mat$", mo_Tools.SQLStr(ls_IdentNrTmp), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$BMN_Length$", mo_Tools.SqlDbl(ao_BOM.BOM_CutLength), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$BMN_Width$", mo_Tools.SqlDbl(ao_BOM.BOM_CutWidth), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$BMN_Height$", "NULL", , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$BMN_Thick$", "NULL", , , vbTextCompare)
  lc_Cursor = mo_Tools.OpenSQLSafe(mo_Db, ls_Req)
  If mo_Db.RowCount(lc_Cursor) = 1 Then
    ls_IdentNr = mo_Tools.SelectValue(mo_Db, ls_Req, "IdentNr")
    ls_MaterialName = mo_Tools.SelectValue(mo_Db, ls_Req, "BMN_Name")
    ls_Material = mo_Tools.SelectValue(mo_Db, ls_Req, "BMN_Mat")
  End If
  Call mo_Db.Close(lc_Cursor)

  If ls_IdentNr <> "" Then
    ao_BOM.BOM_IdentNr = ls_IdentNr
    ao_BOM.BOM_Name = ls_MaterialName
    ao_BOM.BOM_Material = ls_Material
    Bae_ExportInlay = True
    Exit Function
  End If
  
  
  ls_Req = "SELECT MAX(g000.identnr) "
  ls_Req = ls_Req & "FROM g000 "
  ls_Req = ls_Req & "WHERE "
  ls_Req = ls_Req & "(g000.identnr LIKE $MAT_Pefx$) AND (LEN(g000.identnr) = $lenght$)"
  
  ls_Req = Replace(ls_Req, "$MAT_Pefx$", mo_Tools.SQLStr(ls_IdentPrefix & "%"), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$lenght$", mo_Tools.SqlInt(Len(ls_IdentPrefix) + 4), , , vbTextCompare)
  
  ls_IdentNr = mo_Tools.SelectValue(mo_DbBaeurer, ls_Req)
  
  Do
    If ls_IdentNr = "" Then
      ls_IdentNr = ls_IdentPrefix & "0001"
    Else
      If right(ls_IdentNr, 4) = "9999" Then
        Call MsgBox("Counter IdentNr for inlay prefix: " & ls_IdentPrefix & " overflow")
        Exit Function
      Else
        ls_IdentNr = ls_IdentPrefix & (right("0000" & Val(right(ls_IdentNr, 4)) + 1, 4))
      End If
    End If
    'check if we recently did not use this identnr for another coil, need to create new identr by incrementing
    ls_Req = "exec DPC_Bae_Material_sel $IdentNr$, $BMN_Type$, $BMN_Prefix$, $BMN_Mat$, $BMN_Length$, $BMN_Width$, $BMN_Height$, $BMN_Thick$"
    ls_Req = Replace(ls_Req, "$IdentNr$", mo_Tools.SQLStr(ls_IdentNr), , , vbTextCompare)
    ls_Req = Replace(ls_Req, "$BMN_Type$", mo_Tools.SqlInt(eDPCBOMMaterial.bcInlay), , , vbTextCompare)
    ls_Req = Replace(ls_Req, "$BMN_Prefix$", "NULL", , , vbTextCompare)
    ls_Req = Replace(ls_Req, "$BMN_Mat$", "NULL", , , vbTextCompare)
    ls_Req = Replace(ls_Req, "$BMN_Length$", "NULL", , , vbTextCompare)
    ls_Req = Replace(ls_Req, "$BMN_Width$", "NULL", , , vbTextCompare)
    ls_Req = Replace(ls_Req, "$BMN_Height$", "NULL", , , vbTextCompare)
    ls_Req = Replace(ls_Req, "$BMN_Thick$", "NULL", , , vbTextCompare)
  Loop Until mo_Tools.SelectValue(mo_Db, ls_Req, "IdentNr") = ""
  
  
  Set lo_CustomData = New Dictionary
  ls_UoM_PCS = mo_Tools.ConvertCodeToBaeurer(mo_Db, eDPCCodeConversionBaeurer.ccUnitOfMeasure, DPC_UOM_PCS)
  Call lo_CustomData.Add("$identnr$", ls_IdentNr)
  Call lo_CustomData.Add("$ben$", ls_MaterialName)
  Call lo_CustomData.Add("$werkstoff$", ls_Material)
  Call lo_CustomData.Add("$laengea$", ao_BOM.BOM_CutLength)
  Call lo_CustomData.Add("$breiteb$", ao_BOM.BOM_CutWidth)
  Call lo_CustomData.Add("$me$", ls_UoM_PCS)
  Call lo_CustomData.Add("$mes$", ls_UoM_PCS)
  Call lo_CustomData.Add("$stlidentnr$", ls_IdentNr)
  Call lo_CustomData.Add("$aplidentnr$", ls_IdentNr)
  Call lo_CustomData.Add("$qm$", (ao_BOM.BOM_CutLength * ao_BOM.BOM_CutWidth) / 1000000)
  Call lo_CustomData.Add("$vpreis$", ao_BOM.BOM_Cost)
  Call lo_CustomData.Add("$orpreis$", ao_BOM.BOM_Cost)
  Call lo_CustomData.Add("$invpreis$", ao_BOM.BOM_Cost)
  Call lo_CustomData.Add("$datvon$", ao_BOM.BOM_DatVon)
  Call lo_CustomData.Add("$menge_ab$", ao_BOM.BOM_Menge_Ab)
  
  Set lo_XmlDocInlay = Bae_CreateXMLDocument(mo_DbBaeurer, eDPCXmlExportType.etBae_Material, ls_IdentNrTmp, ll_VersionInlay, lo_CustomData)
  
#If TEST = 0 Then
  'Call SaveXMLDocument(lo_XmlDocInlay, "PMASTER")
  'Exit Function
#End If
  
  ll_RowIdTran = Bae_ExportPMasterRecord(mo_DbBaeurer, 0, ls_IdentNr, eDPCXmlExportType.etBae_Material, lo_XmlDocInlay, ll_VersionInlay)
  Call Bae_ExportPMasterComplete(mo_DbBaeurer, ll_RowIdTran, ls_IdentNr)
  'insert exported ident nr into our historical table
  ls_Req = "exec DPC_Bae_Material_ins $IdentNr$,$BMN_Name$,$BMN_Type$,$BMN_Prefix$,$BMN_Mat$,$BMN_Length$,$BMN_Width$,$BMN_Height$,$BMN_Thick$, $U_Code$"
  ls_Req = Replace(ls_Req, "$IdentNr$", mo_Tools.SQLStr(ls_IdentNr), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$BMN_Name$", mo_Tools.SQLStr(ls_MaterialName), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$BMN_Type$", mo_Tools.SqlInt(eDPCBOMMaterial.bcInlay), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$BMN_Prefix$", mo_Tools.SQLStr(ls_IdentPrefix), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$BMN_Mat$", mo_Tools.SQLStr(ls_IdentNrTmp), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$BMN_Length$", mo_Tools.SqlDbl(ao_BOM.BOM_CutLength), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$BMN_Width$", mo_Tools.SqlDbl(ao_BOM.BOM_CutWidth), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$BMN_Height$", "0", , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$BMN_Thick$", "0", , , vbTextCompare)
  ls_Req = ReplaceCommonPlaceholders(ls_Req)
  Call mo_Tools.ExecuteSQLSafe(mo_Db, ls_Req)
  
  ao_BOM.BOM_IdentNr = ls_IdentNr
  ao_BOM.BOM_Name = ls_MaterialName
  ao_BOM.BOM_Material = ls_Material
  
  Call lo_CustomData.RemoveAll
  Set lo_CustomData = Nothing
  
  Bae_ExportInlay = True
  Exit Function
errorHandler:
  Call errorHandler("Bae_ExportInlay")
End Function

Public Function Bae_ExportArticle(ByVal as_PRD_Id As String) As Long
On Error GoTo errorHandler

Dim lo_XmlDocPMaster As Object
Dim lo_XmlDocBOM As Object
Dim lo_XmlDocBOR As Object
Dim ll_RowIdTran As Long
Dim ls_PRD_Code As String
Dim ls_Request As String
Dim lc_Cursor As Long
Dim ll_VersionPMaster As Long
Dim ll_VersionBOM As Long
Dim ll_VersionBOR As Long

  If Not mo_Tools.ReconnectSafe(mo_DbBaeurer, ms_BaeurerServer, ms_BaeurerDatabase, ms_BaeurerLoginName, ms_BaeurerPassword, ms_BaeurerSource) Then
    Exit Function
  End If
  
  If Not Bae_ExportBOMMaterial(as_PRD_Id) Then
    Exit Function
  End If
  
  Set lo_XmlDocPMaster = Bae_CreateXMLDocument(mo_Db, eDPCXmlExportType.etBae_ArticleMaster, as_PRD_Id, ll_VersionPMaster, Nothing)
  Set lo_XmlDocBOM = Bae_CreateXMLDocument(mo_Db, eDPCXmlExportType.etBae_BOM, as_PRD_Id, ll_VersionBOM, Nothing)
  Set lo_XmlDocBOR = Bae_CreateXMLDocument(mo_Db, eDPCXmlExportType.etBae_BOR, as_PRD_Id, ll_VersionBOR, Nothing)
  
#If TEST = 0 Then
  'Call Bae_SaveXMLDocument(lo_XmlDocPMaster, "PMASTER")
  'Call SaveXMLDocument(lo_XmlDocBOM, "BOM")
  'Call SaveXMLDocument(lo_XmlDocBOR, "BOR")
#End If

  ls_Request = "SELECT PRD_Code FROM DPC_PrdCommon WHERE PRD_Id=$PRD_Id$"
  ls_Request = Replace(ls_Request, "$PRD_Id$", mo_Tools.SQLStr(as_PRD_Id), , , vbTextCompare)
  ls_PRD_Code = mo_Tools.SelectValue(mo_Db, ls_Request)
  
  ll_RowIdTran = Bae_ExportPMasterRecord(mo_DbBaeurer, 0, ls_PRD_Code, eDPCXmlExportType.etBae_ArticleMaster, lo_XmlDocPMaster, ll_VersionPMaster)
  Call Bae_ExportPMasterRecord(mo_DbBaeurer, ll_RowIdTran, ls_PRD_Code, eDPCXmlExportType.etBae_BOM, lo_XmlDocBOM, ll_VersionBOM)
  Call Bae_ExportPMasterRecord(mo_DbBaeurer, ll_RowIdTran, ls_PRD_Code, eDPCXmlExportType.etBae_BOR, lo_XmlDocBOR, ll_VersionBOR)
  Call Bae_ExportPMasterComplete(mo_DbBaeurer, ll_RowIdTran, as_PRD_Id)
  Bae_ExportArticle = ll_RowIdTran
  Exit Function
errorHandler:
  Call errorHandler("Bae_ExportArticle")
End Function

Public Sub Bae_ExportXml(ByVal ll_RowId As Long)
  
  If Not mo_Tools.ReconnectSafe(mo_DbBaeurer, ms_BaeurerServer, ms_BaeurerDatabase, ms_BaeurerLoginName, ms_BaeurerPassword, ms_BaeurerSource) Then
    Exit Sub
  End If
  Call mo_DbBaeurer.BlobToFileSQL("SELECT xmllong from tran_sc where rowid=" & ll_RowId, "c:\xml\test.xml")
End Sub

Private Function Bae_CheckArticleExportResult(ByVal al_RowIdTran As Long) As String
On Error GoTo errorHandler

Dim ls_Req As String
Dim lc_Cursor As Long
Dim lc_FilterError As Long
Dim ll_CountError As Long
Dim lc_FilterOK As Long
Dim ll_CountOK As Long

  Bae_CheckArticleExportResult = ""
  ls_Req = "SELECT status_tran FROM tran_sc WHERE rowidtran=$rowidtran$"
  ls_Req = Replace(ls_Req, "$rowidtran$", mo_Tools.SqlInt(al_RowIdTran), , , vbTextCompare)
  lc_Cursor = mo_Tools.OpenSQLSafe(mo_DbBaeurer, ls_Req)
  If mo_DbBaeurer.RowCount(lc_Cursor) = 3 Then
  
    lc_FilterError = mo_DbBaeurer.Filter(lc_Cursor, "status_tran", "=", ROWIDTRANSTATUS_ERROR, 1)
    ll_CountError = mo_DbBaeurer.RowCount(lc_FilterError)
    Call mo_DbBaeurer.Close(lc_FilterError)
    
    lc_FilterOK = mo_DbBaeurer.Filter(lc_Cursor, "status_tran", "=", ROWIDTRANSTATUS_OK, 1)
    ll_CountOK = mo_DbBaeurer.RowCount(lc_FilterOK)
    Call mo_DbBaeurer.Close(lc_FilterOK)
    
    If ll_CountError > 0 Then
      Bae_CheckArticleExportResult = ROWIDTRANSTATUS_ERROR
    ElseIf ll_CountOK = 3 Then
      Bae_CheckArticleExportResult = ROWIDTRANSTATUS_OK
    End If
  End If
  Call mo_DbBaeurer.Close(lc_Cursor)
  Exit Function
errorHandler:
  Call errorHandler("Bae_CheckArticleExportResult")
End Function

Private Function Bae_CheckCustomerExportResult(ByVal al_RowIdTran As Long) As String
On Error GoTo errorHandler

Dim ls_Req As String
Dim lc_Cursor As Long

  Bae_CheckCustomerExportResult = ""
  ls_Req = "SELECT status_tran FROM tran_cus WHERE rowidtran=$rowidtran$"
  ls_Req = Replace(ls_Req, "$rowidtran$", mo_Tools.SqlInt(al_RowIdTran), , , vbTextCompare)
  lc_Cursor = mo_Tools.OpenSQLSafe(mo_DbBaeurer, ls_Req)
  If mo_DbBaeurer.RowCount(lc_Cursor) = 1 Then
  
    If StrComp(mo_DbBaeurer.GetFields(lc_Cursor, "status_tran"), ROWIDTRANSTATUS_ERROR, vbTextCompare) = 0 Then
      Bae_CheckCustomerExportResult = ROWIDTRANSTATUS_ERROR
    ElseIf StrComp(mo_DbBaeurer.GetFields(lc_Cursor, "status_tran"), ROWIDTRANSTATUS_OK, vbTextCompare) = 0 Then
      Bae_CheckCustomerExportResult = ROWIDTRANSTATUS_OK
    End If
  End If
  Call mo_DbBaeurer.Close(lc_Cursor)
  Exit Function
errorHandler:
  Call errorHandler("Bae_CheckCustomerExportResult")
End Function

Private Function Bae_CreateBaeurerConnection(ByVal ao_Db As Object) As Long
On Error GoTo errorHandler

Dim ll_ConnectId As Long
Dim ls_Req As String

  ls_Req = "INSERT INTO b050 "
  ls_Req = ls_Req & "(connect_id ,logname, tty, datuhr, gruppe, session_id, logname_os, serverapp)"
  ls_Req = ls_Req & " VALUES "
  ls_Req = ls_Req & "($connect_id$ ,$logname$, $tty$, getdate(), $gruppe$, @@SPID, $logname_os$, $serverapp$)"
  
  ls_Req = Replace(ls_Req, "$connect_id$", mo_Tools.SqlInt(DPC_DEFUALT_BAEURER_CONNECTID), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$logname$", mo_Tools.SQLStr(ms_BaeurerLoginName), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$tty$", mo_Tools.SQLStr(ms_PC_Name), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$gruppe$", mo_Tools.SQLStr("badmin"), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$session_id$", mo_Tools.SqlInt(DPC_DEFUALT_BAEURER_CONNECTID), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$logname_os$", mo_Tools.SQLStr(ms_BaeurerLoginName), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$serverapp$", mo_Tools.SQLStr(ms_BaeurerServer), , , vbTextCompare)
  
  Call mo_Tools.ExecuteSQLSafe(ao_Db, ls_Req)
  Bae_CreateBaeurerConnection = DPC_DEFUALT_BAEURER_CONNECTID
  Exit Function
errorHandler:
  Call errorHandler("Bae_CreateBaeurerConnection")
End Function

Private Function Bae_CloseBaeurerConnection(ByVal ao_Db As Object, ByVal al_Connect_Id As Long) As Boolean
On Error GoTo errorHandler

Dim ls_Req As String
  
  ls_Req = "DELETE FROM b050 WHERE connect_id=$connect_id$"
  ls_Req = Replace(ls_Req, "$connect_id$", mo_Tools.SqlInt(al_Connect_Id), , , vbTextCompare)
  Call mo_Tools.ExecuteSQLSafe(ao_Db, ls_Req)
  Exit Function
errorHandler:
  Call errorHandler("Bae_CloseBaeurerConnection")
End Function

Private Function Bae_LockRecord(ByVal ao_Db As Object, ByVal as_Table As String, ByVal av_Key As Variant, as_Screen As String) As Long
On Error GoTo errorHandler

Dim ls_Req As String
Dim ls_Key As String

  Bae_LockRecord = 0
  If IsArray(av_Key) Then
    ls_Key = Join(av_Key, "@")
  Else
    ls_Key = Str(av_Key)
  End If
 
  Call Bae_CloseBaeurerConnection(mo_DbBaeurer, DPC_DEFUALT_BAEURER_CONNECTID)
  ml_BaeurerConnectID = Bae_CreateBaeurerConnection(ao_Db)
  If ml_BaeurerConnectID = 0 Then
    Exit Function
  End If
  
  ls_Req = "SELECT COUNT(*) FROM b030 WHERE schluessel=$schluessel$"
  ls_Req = Replace(ls_Req, "$schluessel$", mo_Tools.SQLStr(ls_Key), , , vbTextCompare)
  If mo_Tools.SelectValue(ao_Db, ls_Req) > 0 Then
    Call Bae_CloseBaeurerConnection(ao_Db, ml_BaeurerConnectID)
    ml_BaeurerConnectID = 0
    Exit Function
  End If

  ls_Req = "INSERT INTO [b030] "
  ls_Req = ls_Req & "([tabelle] ,[fi_nr], [schluessel], [logname], [connect_id], [maske], [datuhr]) "
  ls_Req = ls_Req & " VALUES "
  ls_Req = ls_Req & "($tabelle$ ,$fi_nr$, $schluessel$, $logname$, $connect_id$, $maske$, getdate())"
  
  ls_Req = Replace(ls_Req, "$tabelle$", mo_Tools.SQLStr(as_Table), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$fi_nr$", mo_Tools.SqlInt(ml_BaeurerFi_Nr), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$schluessel$", mo_Tools.SQLStr(ls_Key), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$logname$", mo_Tools.SQLStr(ms_BaeurerSource), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$maske$", mo_Tools.SQLStr(as_Screen), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$connect_id$", mo_Tools.SqlInt(ml_BaeurerConnectID), , , vbTextCompare)
  Call mo_Tools.ExecuteSQLSafe(ao_Db, ls_Req, 1)
  
  Bae_LockRecord = mo_Tools.GetLastIdentity(ao_Db)
  Exit Function
errorHandler:
  'do nothing, lock was not succesfull it will be shown in the message
End Function

Private Sub Bae_UnlockRecord(ByVal ao_Db As Object, ByVal al_RowId As Long)
On Error GoTo errorHandler
  
Dim ls_Request As String
  
  ls_Request = "DELETE FROM [b030] WHERE rowid=$rowid$"
  ls_Request = Replace(ls_Request, "$rowid$", mo_Tools.SqlInt(al_RowId), , , vbTextCompare)
  Call mo_Tools.ExecuteSQLSafe(ao_Db, ls_Request)
  Call Bae_CloseBaeurerConnection(mo_DbBaeurer, ml_BaeurerConnectID)
  Exit Sub
errorHandler:
  Call errorHandler("Bae_UnlockRecord")
End Sub

Private Function CreateNextIdOfferPos(ByVal ao_Collection As Collection)
On Error GoTo errorHandler

Dim ls_OFD_IdParNew As String
Dim lo_Offer As DPC_OfferPos
  
  ls_OFD_IdParNew = mo_Tools.GetNextID(mo_Db, "Cap_OfferDetail")
  For Each lo_Offer In ao_Collection
    If lo_Offer.OFD_Main = eDPCOfferDetailMain.odMain Then
      lo_Offer.OFD_Id = ls_OFD_IdParNew
      lo_Offer.OFD_IdPar = ls_OFD_IdParNew
    Else
      lo_Offer.OFD_Id = mo_Tools.GetNextID(mo_Db, "Cap_OfferDetail")
      lo_Offer.OFD_IdPar = ls_OFD_IdParNew
    End If
  Next
  Exit Function
errorHandler:
  Call errorHandler("CreateNextIdOfferPos")
End Function

Private Function CopyOfferPos(ByVal as_COF_Id As String, ByVal as_OFD_Id As String, ByVal al_SplitNr As Long, ByRef al_OFD_PosSrc As Long) As String
On Error GoTo errorHandler

Dim ls_Req As String
Dim ls_OFD_IdParNew As String
Dim lo_Offer As DPC_OfferPos
Dim lo_Collection As Collection
Dim ls_Request As String
Dim lc_Cursor As Long

  Set lo_Collection = New Collection
  
  ls_Request = "exec Cap_OfferDetail_lst2 $COF_Id$, $Language_Code$, $OFD_Main$, $OFD_IdPar$, $OFD_Valid$, $OFD_Id$"
  ls_Request = Replace(ls_Request, "$COF_Id$", mo_Tools.SQLStr(as_COF_Id), , , vbTextCompare)
  ls_Request = Replace(ls_Request, "$OFD_Main$", "NULL", , , vbTextCompare)
  ls_Request = Replace(ls_Request, "$OFD_IdPar$", mo_Tools.SQLStr(as_OFD_Id), , , vbTextCompare)
  ls_Request = Replace(ls_Request, "$OFD_Valid$", "NULL", , , vbTextCompare)
  ls_Request = Replace(ls_Request, "$OFD_Id$", "NULL", , , vbTextCompare)
  ls_Request = ReplaceCommonPlaceholders(ls_Request)
  lc_Cursor = mo_Tools.OpenSQLSafe(mo_Db, ls_Request)
  While Not mo_Db.EOF(lc_Cursor)
    Set lo_Offer = New DPC_OfferPos
    Set lo_Offer.Tools = mo_Tools
    Call lo_Offer.ReadOfferPos(mo_Db, lc_Cursor)
    Call lo_Collection.Add(lo_Offer)
    Call mo_Db.Next(lc_Cursor)
  Wend
  Call mo_Db.Close(lc_Cursor)
  
  ls_OFD_IdParNew = mo_Tools.GetNextID(mo_Db, "Cap_OfferDetail")
  For Each lo_Offer In lo_Collection
    lo_Offer.OFD_IdPar = ls_OFD_IdParNew
    lo_Offer.OFD_Pos = lo_Offer.OFD_Pos + (al_SplitNr * 10)
    If (lo_Offer.DOF_Id = eDPCOfferDetail.odPosition) Or _
       (lo_Offer.DOF_Id = eDPCOfferDetail.odSubconstPosition) Or _
       (lo_Offer.DOF_Id = eDPCOfferDetail.odManualPosition) Then
      lo_Offer.OFD_Id = ls_OFD_IdParNew
      al_OFD_PosSrc = lo_Offer.OFD_Pos
    Else
      lo_Offer.OFD_Id = mo_Tools.GetNextID(mo_Db, "Cap_OfferDetail")
    End If
    Call lo_Offer.Insert(mo_Db, ml_U_Code)
  Next
  CopyOfferPos = ls_OFD_IdParNew
  Exit Function
errorHandler:
  Call errorHandler("CopyOfferPos")
End Function

Private Sub Bae_UpdateOrderPositionFromPlaningBox(ByVal as_COF_Id As String, ByVal as_OFD_Id As String, ByVal al_OFD_Split As Long, ByVal ac_PlanBoxCursor As Long)
On Error GoTo errorHandler

Dim lo_Product As DPC_Product
Dim lo_Offer As DPC_OfferPos
Dim lo_Cutout As DPC_Cutout
Dim lo_Inlay As DPC_Inlay
Dim ls_PRD_Id As String
Dim ls_Req As String
Dim ll_QtyPCS As Long

  ls_Req = "SELECT PRD_Id FROM Cap_OfferDetail WHERE COF_Id=$COF_Id$ AND OFD_Id=$OFD_Id$"
  ls_Req = Replace(ls_Req, "$COF_Id$", mo_Tools.SQLStr(as_COF_Id), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$OFD_Id$", mo_Tools.SQLStr(as_OFD_Id), , , vbTextCompare)
  ls_PRD_Id = mo_Tools.SelectValue(mo_Db, ls_Req)
  
  If ls_PRD_Id = "" Then
    Err.Raise ArmErr.InvalidArgument, "ls_PRD_Id", "Article ID not found: as_COF_Id=" & as_COF_Id & " as_OFD_Id=" & as_OFD_Id
  End If
  
  Set lo_Product = New DPC_Product
  Set lo_Product.Tools = mo_Tools
  Set lo_Product.ArmDb = mo_Db
  lo_Product.CT_Code = ms_CT_Code
  lo_Product.ValidityDate = ValidityDate
  lo_Product.Language_Code = ms_Language_Code
  lo_Product.COF_Id = as_COF_Id
  lo_Product.U_Code = ml_U_Code
  Call lo_Product.Load_A_COM
  Call lo_Product.InitOffer
  Call lo_Product.Load(ls_PRD_Id)
  Call lo_Product.LoadOffer(as_COF_Id, as_OFD_Id)
    
  ll_QtyPCS = mo_DbBaeurer.GetFields(ac_PlanBoxCursor, "menge_best")
  If lo_Product.PanelQtyPCS <> ll_QtyPCS Then
    For Each lo_Offer In lo_Product.OfferPrice
      If (Not lo_Offer.DOF_IsStp) And (Not lo_Offer.DOF_IsTxt) Then
        Call lo_Offer.SetQty(DPC_UOM_PCS, ll_QtyPCS)
        Call lo_Offer.Update(mo_Db, ml_U_Code)
      End If
    Next
    For Each lo_Cutout In lo_Product.Cutouts
      For Each lo_Offer In lo_Cutout.OfferPrice
        If (Not lo_Offer.DOF_IsStp) And (Not lo_Offer.DOF_IsTxt) Then
          Call lo_Offer.SetQty(DPC_UOM_PCS, ll_QtyPCS)
          Call lo_Offer.Update(mo_Db, ml_U_Code)
        End If
      Next
    Next
    For Each lo_Inlay In lo_Product.Inlays
      For Each lo_Offer In lo_Inlay.OfferPrice
        If (Not lo_Offer.DOF_IsStp) And (Not lo_Offer.DOF_IsTxt) Then
          Call lo_Offer.SetQty(DPC_UOM_PCS, ll_QtyPCS)
          Call lo_Offer.Update(mo_Db, ml_U_Code)
        End If
      Next
    Next
    Call lo_Product.CalcPositionPrice
  End If
    
  Set lo_Offer = lo_Product.GetOfferPos(eDPCOfferDetail.odPosition)
  lo_Offer.OFD_ShpDat = mo_DbBaeurer.GetFields(ac_PlanBoxCursor, "lief_termb")
  lo_Offer.OFD_PlaDat = mo_DbBaeurer.GetFields(ac_PlanBoxCursor, "dataen")
  lo_Offer.OFD_PlaUsr = mo_DbBaeurer.GetFields(ac_PlanBoxCursor, "useraen")
  lo_Offer.OFD_B7Sta = mo_DbBaeurer.GetFields(ac_PlanBoxCursor, "kn_verarb")
  lo_Offer.OFD_Split = al_OFD_Split
  lo_Offer.OFD_InfoB7 = mo_DbBaeurer.GetFields(ac_PlanBoxCursor, "info_b7")
  lo_Offer.OFD_OrdNrB7 = mo_DbBaeurer.GetFields(ac_PlanBoxCursor, "aufnr")
  lo_Offer.OFD_PosB7 = mo_DbBaeurer.GetFields(ac_PlanBoxCursor, "aufpos")
  Call lo_Offer.Update(mo_Db, ml_U_Code)
  Call lo_Product.Unload_A_COM
  Set lo_Product = Nothing
  Exit Sub
errorHandler:
  Call errorHandler("Bae_UpdateOrderPositionFromPlaningBox")
End Sub

Private Sub Bae_UpdatePlaningBoxFromOrderPosition(ByVal as_COF_Code As String, ByVal al_OFD_Pos As Long, ByVal al_OFD_Split As Long, ByVal al_OFD_PosSrc As Long)
On Error GoTo errorHandler

Dim ls_Req As String
  ', kn_verarb=$kn_verarb_new$  - changed, status will be changed after XML export to SAP/B7
  ls_Req = "UPDATE va1101 SET seblpos_q=$aufpos_q_new$, aufpos_q=$aufpos_q_new$ WHERE aufnr_q=$aufnr_q$ AND aufpos_q=$aufpos_q_old$ AND seblpos=$seblpos$ AND fi_nr=$fi_nr$ AND kn_verarb=$kn_verarb_old$"
  ls_Req = Replace(ls_Req, "$aufnr_q$", mo_Tools.SQLStr(as_COF_Code), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$aufpos_q_old$", mo_Tools.SqlInt(al_OFD_Pos), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$aufpos_q_new$", mo_Tools.SqlInt(al_OFD_PosSrc), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$seblpos$", mo_Tools.SqlInt(al_OFD_Split), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$fi_nr$", mo_Tools.SqlInt(ml_BaeurerFi_Nr), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$kn_verarb_old$", mo_Tools.SQLStr(BAE_PLABOX_RequestReadyForCapture), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$kn_verarb_new$", mo_Tools.SQLStr(BAE_PLABOX_RequestAcceptedByCapture), , , vbTextCompare)
  Call mo_Tools.ExecuteSQLSafe(mo_DbBaeurer, ls_Req)
  Exit Sub
errorHandler:
  Call errorHandler("Bae_UpdatePlaningBoxFromOrderPosition")
End Sub

Public Sub Bae_UpdatePlaningBoxStatus(ByVal as_COF_Code As String, ByVal as_kn_verarb_old As String, ByVal as_kn_verarb_new As String)
On Error GoTo errorHandler

Dim ls_Req As String
Dim ll_LockRowId As Long

  If Not mo_Tools.ReconnectSafe(mo_DbBaeurer, ms_BaeurerServer, ms_BaeurerDatabase, ms_BaeurerLoginName, ms_BaeurerPassword, ms_BaeurerSource) Then
    Exit Sub
  End If
  
  ll_LockRowId = Bae_LockRecord(mo_DbBaeurer, "va1101", Array(ml_BaeurerFi_Nr, as_COF_Code), "vva100")
  If ll_LockRowId = 0 Then
    Call mo_Tools.ShowMsg(mo_Db, ms_Language_Code, 666, "#Manufacturing validation in progress")
    Exit Sub
  End If
  
  ls_Req = "UPDATE va1101 SET kn_verarb=$kn_verarb_new$ WHERE aufnr_q=$aufnr_q$ AND fi_nr=$fi_nr$ AND kn_verarb IN ($kn_verarb_old$)"
  ls_Req = Replace(ls_Req, "$aufnr_q$", mo_Tools.SQLStr(as_COF_Code), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$fi_nr$", mo_Tools.SqlInt(ml_BaeurerFi_Nr), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$kn_verarb_old$", mo_Tools.SqlStrIn(as_kn_verarb_old), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$kn_verarb_new$", mo_Tools.SQLStr(as_kn_verarb_new), , , vbTextCompare)
  Call mo_Tools.ExecuteSQLSafe(mo_DbBaeurer, ls_Req)
  
  Call Bae_UnlockRecord(mo_DbBaeurer, ll_LockRowId)
  Call mo_DbBaeurer.Disconnect
  Exit Sub
errorHandler:
  Call mo_Tools.UpdateError(True)
  If ll_LockRowId <> 0 Then
    Call Bae_UnlockRecord(mo_DbBaeurer, ll_LockRowId)
    Call mo_DbBaeurer.Disconnect
  End If
  Call mo_Tools.UpdateError(False)
  Call errorHandler("Bae_UpdatePlaningBoxStatus")
End Sub

Public Function Bae_CheckExistCustPurchOrderNumber(ByVal as_COF_CodeCus As String, ByVal al_Konto As Long) As Boolean
On Error GoTo errorHandler

Dim ls_Req As String
Dim ll_LockRowId As Long

  Bae_CheckExistCustPurchOrderNumber = True
  If Not mo_Tools.ReconnectSafe(mo_DbBaeurer, ms_BaeurerServer, ms_BaeurerDatabase, ms_BaeurerLoginName, ms_BaeurerPassword, ms_BaeurerSource) Then
    Exit Function
  End If
  
  ls_Req = "SELECT best_nr from v100 where konto = $konto$ and vvorgart = '1' and fi_nr = $fi_nr$ and best_nr = $COF_CodeCus$"
  ls_Req = Replace(ls_Req, "$konto$", mo_Tools.SqlInt(al_Konto), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$fi_nr$", mo_Tools.SqlInt(ml_BaeurerFi_Nr), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$COF_CodeCus$", mo_Tools.SQLStr(as_COF_CodeCus), , , vbTextCompare)
  Bae_CheckExistCustPurchOrderNumber = mo_Tools.SelectValue(mo_DbBaeurer, ls_Req) <> ""
  Call mo_DbBaeurer.Disconnect
  Exit Function
errorHandler:
  Call errorHandler("Bae_CheckExistCustPurchOrderNumber")
End Function

Private Function FindOrderPositionLink(ByVal as_COF_Id As String, ByVal al_OFD_Pos As Long, ByVal as_PRD_Code As String, ByVal al_OFD_Split As Long) As String
On Error GoTo errorHandler

Dim ls_Req As String
  
  ls_Req = "SELECT TOP 1 OFD_IdPar FROM Cap_OfferDetail WHERE COF_Id=$COF_Id$ AND OFD_Pos=$OFD_Pos$ AND OFD_Main=$OFD_Main$ AND PRD_Code=$PRD_Code$ AND ISNULL(OFD_Split,0)=$OFD_Split$ AND Drop_Flag=''"
  ls_Req = Replace(ls_Req, "$COF_Id$", mo_Tools.SQLStr(as_COF_Id), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$OFD_Pos$", mo_Tools.SqlInt(al_OFD_Pos), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$OFD_Main$", mo_Tools.SqlInt(eDPCOfferDetailMain.odMain), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$PRD_Code$", mo_Tools.SQLStr(as_PRD_Code), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$OFD_Split$", mo_Tools.SqlInt(al_OFD_Split), , , vbTextCompare)
  FindOrderPositionLink = mo_Tools.SelectValue(mo_Db, ls_Req)
  Exit Function
errorHandler:
  Call errorHandler("FindOrderPositionLink")
End Function

Public Function Bae_AcceptPlanningBox(ByVal as_COF_Id As String, ByVal as_COF_Code As String, ByRef as_ErrMsg As String) As Boolean
On Error GoTo errorHandler

Dim ls_Req As String
Dim lc_PlanBoxCursor As Long
Dim ls_OFD_Id As String, ls_OFD_IdSrc As String
Dim ll_OFD_Pos As Long, ll_OFD_PosSrc As Long
Dim ls_PRD_Code As String, ls_COF_Code As String
Dim ll_OFD_Split As Long
Dim ll_ConnectId As Long
Dim ll_LockRowId As Long
  
  as_ErrMsg = ""
  Bae_AcceptPlanningBox = False
  If Not mo_Tools.ReconnectSafe(mo_DbBaeurer, ms_BaeurerServer, ms_BaeurerDatabase, ms_BaeurerLoginName, ms_BaeurerPassword, ms_BaeurerSource) Then
    Exit Function
  End If
  
  ll_LockRowId = Bae_LockRecord(mo_DbBaeurer, "va1101", Array(ml_BaeurerFi_Nr, as_COF_Code), "vva100")
  If ll_LockRowId = 0 Then
    Call mo_Tools.ShowMsg(mo_Db, ms_Language_Code, 666, "#Manufacturing validation in progress")
    Exit Function
  End If
  
  ls_Req = "SELECT * FROM va1101 WHERE (aufnr_q=$aufnr_q$) AND (fi_nr=$fi_nr$) AND (kn_verarb IN ($kn_verarb$)) ORDER BY aufnr_q, aufpos_q, seblpos"
  ls_Req = Replace(ls_Req, "$aufnr_q$", mo_Tools.SQLStr(as_COF_Code), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$fi_nr$", mo_Tools.SqlInt(ml_BaeurerFi_Nr), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$kn_verarb$", mo_Tools.SqlStrIn(Array(BAE_PLABOX_RequestReadyForCapture, BAE_PLABOX_RequestDeadlineTimeout)), , , vbTextCompare)
  lc_PlanBoxCursor = mo_Tools.OpenSQLSafe(mo_DbBaeurer, ls_Req)
  
  If mo_DbBaeurer.RowCount(lc_PlanBoxCursor) = 0 Then
    Call Bae_UnlockRecord(mo_DbBaeurer, ll_LockRowId)
    Call mo_Db.Close(lc_PlanBoxCursor)
    as_ErrMsg = "No item is approved in planning box"
    Exit Function
  End If
  
  If mo_DbBaeurer.Find(lc_PlanBoxCursor, "kn_verarb", BAE_PLABOX_RequestDeadlineTimeout) >= 0 Then
    Call Bae_UnlockRecord(mo_DbBaeurer, ll_LockRowId)
    Call mo_Db.Close(lc_PlanBoxCursor)
    as_ErrMsg = "Request deadline timeout"
    Exit Function
  Else
  
    Call mo_DbBaeurer.First(lc_PlanBoxCursor)
    While Not mo_DbBaeurer.EOF(lc_PlanBoxCursor)
      ls_COF_Code = mo_DbBaeurer.GetFields(lc_PlanBoxCursor, "aufnr_q")
      ll_OFD_Pos = mo_DbBaeurer.GetFields(lc_PlanBoxCursor, "aufpos_q")
      ll_OFD_PosSrc = mo_DbBaeurer.GetFields(lc_PlanBoxCursor, "seblpos_q")
      ls_PRD_Code = mo_DbBaeurer.GetFields(lc_PlanBoxCursor, "identnr")
      ll_OFD_Split = mo_DbBaeurer.GetFields(lc_PlanBoxCursor, "seblpos")
      ls_OFD_Id = ""
      ' find source order line position - original order line exported to planning box which may or may not be splitted
      ls_OFD_IdSrc = FindOrderPositionLink(as_COF_Id, ll_OFD_Pos, ls_PRD_Code, 0)
      ' update link of capture order line into planning box and change status as it was imported ok by Capture
      Call Bae_UpdatePlaningBoxFromOrderPosition(ls_COF_Code, ll_OFD_Pos, ll_OFD_Split, ll_OFD_PosSrc)
      ' go to next planning box line
      Call mo_DbBaeurer.Next(lc_PlanBoxCursor)
    Wend
    Call mo_DbBaeurer.Close(lc_PlanBoxCursor)
  End If
  Call Bae_UnlockRecord(mo_DbBaeurer, ll_LockRowId)
  Call mo_DbBaeurer.Disconnect
  Bae_AcceptPlanningBox = True
  Exit Function
errorHandler:
  Call mo_Tools.UpdateError(True)
  If ll_LockRowId <> 0 Then
    Call Bae_UnlockRecord(mo_DbBaeurer, ll_LockRowId)
    Call mo_DbBaeurer.Disconnect
  End If
  Call mo_Tools.UpdateError(False)
  Call errorHandler("Bae_AcceptPlanningBox")
End Function

Public Function Bae_ImportSecretBox(ByVal as_COF_Id As String, ByVal as_COF_Code As String, ByRef as_ErrMsg As String) As Boolean
On Error GoTo errorHandler

Dim ls_Req As String
Dim lc_PlanBoxCursor As Long
Dim ls_OFD_Id As String, ls_OFD_IdSrc As String
Dim ll_OFD_Pos As Long, ll_OFD_PosSrc As Long
Dim ls_PRD_Code As String, ls_COF_Code As String
Dim ll_OFD_Split As Long
Dim ll_SplitNr As Long
Dim ll_LockRowId As Long
Dim ls_COF_CodeBae As String

  as_ErrMsg = ""
  Bae_ImportSecretBox = False
  If Not mo_Tools.ReconnectSafe(mo_DbBaeurer, ms_BaeurerServer, ms_BaeurerDatabase, ms_BaeurerLoginName, ms_BaeurerPassword, ms_BaeurerSource) Then
    Exit Function
  End If
  
  ll_LockRowId = Bae_LockRecord(mo_DbBaeurer, "va1101", Array(ml_BaeurerFi_Nr, as_COF_Code), "vva100")
  If ll_LockRowId = 0 Then
    Call mo_Tools.ShowMsg(mo_Db, ms_Language_Code, 666, "#Manufacturing validation in progress")
    Exit Function
  End If
  
  ls_Req = "SELECT * FROM va1101 WHERE (aufnr_q=$aufnr_q$) AND (fi_nr=$fi_nr$) AND (kn_verarb IN ($kn_verarb$)) ORDER BY aufnr_q, aufpos_q, seblpos"
  ls_Req = Replace(ls_Req, "$aufnr_q$", mo_Tools.SQLStr(as_COF_Code), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$fi_nr$", mo_Tools.SqlInt(ml_BaeurerFi_Nr), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$kn_verarb$", mo_Tools.SqlStrIn(Array(BAE_PLABOX_RequestReadyForCapture, BAE_PLABOX_RequestDeadlineTimeout)), , , vbTextCompare)
  lc_PlanBoxCursor = mo_Tools.OpenSQLSafe(mo_DbBaeurer, ls_Req)
  
  If mo_DbBaeurer.RowCount(lc_PlanBoxCursor) = 0 Then
    Call Bae_UnlockRecord(mo_DbBaeurer, ll_LockRowId)
    Call mo_DbBaeurer.Close(lc_PlanBoxCursor)
    as_ErrMsg = "No item is approved in planning box"
    Exit Function
  End If
  
  If mo_DbBaeurer.Find(lc_PlanBoxCursor, "kn_verarb", BAE_PLABOX_RequestDeadlineTimeout) >= 0 Then
    Call Bae_UnlockRecord(mo_DbBaeurer, ll_LockRowId)
    Call mo_DbBaeurer.Close(lc_PlanBoxCursor)
    as_ErrMsg = "Request deadline timeout"
    Exit Function
  Else
    ls_COF_CodeBae = ""
    Call mo_DbBaeurer.First(lc_PlanBoxCursor)
    While Not mo_DbBaeurer.EOF(lc_PlanBoxCursor)
      ls_COF_Code = mo_DbBaeurer.GetFields(lc_PlanBoxCursor, "aufnr_q")
      ll_OFD_Pos = mo_DbBaeurer.GetFields(lc_PlanBoxCursor, "aufpos_q")
      ll_OFD_PosSrc = mo_DbBaeurer.GetFields(lc_PlanBoxCursor, "seblpos_q")
      ls_PRD_Code = mo_DbBaeurer.GetFields(lc_PlanBoxCursor, "identnr")
      ll_OFD_Split = mo_DbBaeurer.GetFields(lc_PlanBoxCursor, "seblpos")
      ls_OFD_Id = ""
      If (ls_COF_CodeBae = "") And (mo_DbBaeurer.GetFields(lc_PlanBoxCursor, "aufnr") <> "") Then
        ls_COF_CodeBae = mo_DbBaeurer.GetFields(lc_PlanBoxCursor, "aufnr")
      End If
      ' find source order line position - original order line exported to planning box which may or may not be splitted
      ls_OFD_IdSrc = FindOrderPositionLink(as_COF_Id, ll_OFD_Pos, ls_PRD_Code, 0)
      If ls_OFD_IdSrc = "" Then
        Call Bae_UnlockRecord(mo_DbBaeurer, ll_LockRowId)
        Call mo_DbBaeurer.Close(lc_PlanBoxCursor)
        ' we did not found line in capture order
        as_ErrMsg = "Order line not found for article: " & ls_PRD_Code & " position: " & ll_OFD_Pos & " block: " & ll_OFD_Split
        Exit Function
      End If
      
      ' calculate real split "position offset" - if line is split, copied line will get new position number with offset to original line position number
      If ll_OFD_Split = 0 Then
        ll_SplitNr = 0
        ls_OFD_Id = ls_OFD_IdSrc
      Else
        ' we have some split, increment position counter (maybe we can user ll_OFD_Split, but is it consistent?)
        ll_SplitNr = ll_SplitNr + 1
        ' in case we try to import the same order from planning box again - line is marked and linked to existing order line
        If ll_OFD_PosSrc > 0 Then
          ls_OFD_Id = FindOrderPositionLink(as_COF_Id, ll_OFD_PosSrc, ls_PRD_Code, ll_OFD_Split)
          ' link exist, but line not found in Capture.. hmm create it again or how error ?
          If (ls_OFD_Id = "") Then
            ls_OFD_Id = CopyOfferPos(as_COF_Id, ls_OFD_IdSrc, ll_SplitNr, ll_OFD_PosSrc)
          End If
        Else
          ' in case we detected split and dont have link in planing box, copy base offer description
          ls_OFD_Id = CopyOfferPos(as_COF_Id, ls_OFD_IdSrc, ll_SplitNr, ll_OFD_PosSrc)
        End If
      End If
      
      If ls_OFD_Id = "" Then
        Call Bae_UnlockRecord(mo_DbBaeurer, ll_LockRowId)
        Call mo_DbBaeurer.Close(lc_PlanBoxCursor)
        as_ErrMsg = "Order line not found for article: " & ls_PRD_Code & " position: " & ll_OFD_Pos & " block: " & ll_OFD_Split
        Exit Function
      End If
      ' update qty, shipment date and other attributes from planning box into capture order line position
      Call Bae_UpdateOrderPositionFromPlaningBox(as_COF_Id, ls_OFD_Id, ll_OFD_Split, lc_PlanBoxCursor)
      ' update link of capture order line into planning box and change status as it was imported ok by Capture
      Call Bae_UpdatePlaningBoxFromOrderPosition(ls_COF_Code, ll_OFD_Pos, ll_OFD_Split, ll_OFD_PosSrc)
      ' go to next planning box line
      Call mo_DbBaeurer.Next(lc_PlanBoxCursor)
    Wend
    Call mo_DbBaeurer.Close(lc_PlanBoxCursor)
  End If
  
  If ls_COF_CodeBae <> "" Then
    ls_Req = "UPDATE Cap_Offer SET COF_CodeBae=$COF_CodeBae$ WHERE COF_Id=$COF_Id$"
    ls_Req = Replace(ls_Req, "$COF_Id$", mo_Tools.SQLStr(as_COF_Id), , , vbTextCompare)
    ls_Req = Replace(ls_Req, "$COF_CodeBae$", mo_Tools.SQLStr(ls_COF_CodeBae), , , vbTextCompare)
    Call mo_Tools.ExecuteSQLSafe(mo_Db, ls_Req)
  End If
  
  Call Bae_UnlockRecord(mo_DbBaeurer, ll_LockRowId)
  Call mo_DbBaeurer.Disconnect
  Bae_ImportSecretBox = True
  Exit Function
errorHandler:
  Call mo_Tools.UpdateError(True)
  If ll_LockRowId <> 0 Then
    Call Bae_UnlockRecord(mo_DbBaeurer, ll_LockRowId)
    Call mo_DbBaeurer.Disconnect
  End If
  Call mo_Tools.UpdateError(False)
  Call errorHandler("Bae_ImportSecretBox")
End Function

Private Sub UpdateOfferStatus(ByVal as_COF_Id As String, ByVal ae_COF_Stat As eOfferStatus)
On Error GoTo errorHandler

Dim ls_Req As String

  ls_Req = "UPDATE Cap_Offer SET COF_Stat=$COF_Stat$, Z_Last_Upd_User=$Z_Last_Upd_User$,Z_Last_Upd=getdate(),iConcurrency=iConcurrency+1 WHERE COF_Id=$COF_Id$"
  ls_Req = Replace(ls_Req, "$COF_Id$", mo_Tools.SQLStr(as_COF_Id), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$COF_Stat$", mo_Tools.SqlInt(ae_COF_Stat), , , vbTextCompare)
  ls_Req = ReplaceCommonPlaceholders(ls_Req)
  Call mo_Tools.ExecuteSQLSafe(mo_Db, ls_Req)
  Exit Sub
errorHandler:
  Call errorHandler("UpdateOfferStatus")
End Sub

Private Sub Bae_UpdateOfferCode(ByVal as_COF_Id As String, ByVal as_COF_CodeBae As String)
On Error GoTo errorHandler

Dim ls_Req As String

  ls_Req = "UPDATE Cap_Offer SET COF_CodeBae=$COF_CodeBae$, Z_Last_Upd_User=$Z_Last_Upd_User$,Z_Last_Upd=getdate(),iConcurrency=iConcurrency+1 WHERE COF_Id=$COF_Id$"
  ls_Req = Replace(ls_Req, "$COF_Id$", mo_Tools.SQLStr(as_COF_Id), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$COF_CodeBae$", mo_Tools.SQLStr(as_COF_CodeBae), , , vbTextCompare)
  ls_Req = ReplaceCommonPlaceholders(ls_Req)
  Call mo_Tools.ExecuteSQLSafe(mo_Db, ls_Req)
  Exit Sub
errorHandler:
  Call errorHandler("UpdateOfferStatus")
End Sub

Private Sub Bae_ClearOfferDetailCodePos(ByVal as_COF_Id As String)
On Error GoTo errorHandler

Dim ls_Req As String

  ls_Req = "UPDATE Cap_OfferDetail SET OFD_OrdNrB7='',OFD_PosB7=0,OFD_InfoB7='',OFD_B7Sta=0,Z_Last_Upd_User=$Z_Last_Upd_User$,Z_Last_Upd=getdate(),iConcurrency=iConcurrency+1 WHERE COF_Id=$COF_Id$"
  ls_Req = Replace(ls_Req, "$COF_Id$", mo_Tools.SQLStr(as_COF_Id), , , vbTextCompare)
  ls_Req = ReplaceCommonPlaceholders(ls_Req)
  Call mo_Tools.ExecuteSQLSafe(mo_Db, ls_Req)
  Exit Sub
errorHandler:
  Call errorHandler("UpdateOfferStatus")
End Sub

Public Function Bae_CheckDeadlinePlanningBox(ByVal as_COF_Id As String, ByVal as_COF_Code As String, ByRef as_ErrMsg As String) As Boolean
On Error GoTo errorHandler

Dim ls_Req As String

   Bae_CheckDeadlinePlanningBox = True
  Exit Function
errorHandler:

  Call errorHandler(" Bae_CheckDeadlinePlanningBox")
End Function

Public Function Bae_ReadSalesOrderResponse(ByVal as_COF_Id As String, ByRef as_ErrMsg As String) As Boolean
On Error GoTo errorHandler

Dim lo_XMLDoc As Object
Dim lo_NodeElem As Object
Dim lo_NodeList As Object
Dim lo_NodeId As Object
Dim ls_Value As String
Dim ls_ValidationXSD As String
Dim ls_FormatterXML As String
Dim ls_Error As String
Dim ls_Req As String
Dim ls_Filename As String

    Bae_ReadSalesOrderResponse = False
    Call ClearLogInterface
    
    If DownloadXMLDocument(as_COF_Id, ls_Filename, as_ErrMsg) = True Then
        Set lo_XMLDoc = CreateObject("MSXML2.DOMDocument")
                
        lo_XMLDoc.async = False
        Call lo_XMLDoc.Load(ms_TempDir & "\" & ls_Filename)
        
        If (lo_XMLDoc.parseError.errorCode <> 0) Then
        
            mo_ILO.ILO_Error = lo_XMLDoc.parseError.reason
            mo_ILO.ILO_Status = eDPCInterfaceStatus.isFailed
        
            Call LogInterface(mo_Db, ml_U_Code)
            
            as_ErrMsg = "Parse Error:" & lo_XMLDoc.parseError.reason
           
        Else
           Set lo_NodeElem = lo_XMLDoc.selectSingleNode("//SUCC_FAIL_IND")
           ls_Value = lo_NodeElem.nodeTypedValue
           If ls_Value = "F" Then
                mo_ILO.ILO_Status = eDPCInterfaceStatus.isFailed
           
           ElseIf ls_Value = "S" Then
           
                mo_ILO.ILO_Status = eDPCInterfaceStatus.isOK
                Bae_ReadSalesOrderResponse = True
           End If
                  
        End If
    Else
        mo_ILO.ILO_Status = eDPCInterfaceStatus.isFailed
    End If
            
    Set lo_NodeElem = Nothing
    Set lo_NodeList = Nothing
    Set lo_XMLDoc = Nothing
    
    Exit Function
errorHandler:
        
    Set lo_NodeElem = Nothing
    Set lo_NodeList = Nothing
    Set lo_XMLDoc = Nothing
    
    Call LogInterface(mo_Db, ml_U_Code)
    
    Call errorHandler("Bae_ReadSalesOrderResponse")
End Function

Public Function Bae_KillSecretBox(ByVal as_COF_Id As String, ByVal as_COF_Code As String, ByRef as_ErrMsg As String) As Boolean
On Error GoTo errorHandler

Dim ls_Req As String
Dim lc_PlanBoxCursor As Long
Dim ll_LockRowId As Long
Dim lc_Status As Long
Dim ls_KN_Verarb_Old As String
Dim ls_KN_Verarb_New As String

  as_ErrMsg = ""
  Bae_KillSecretBox = False
  If Not mo_Tools.ReconnectSafe(mo_DbBaeurer, ms_BaeurerServer, ms_BaeurerDatabase, ms_BaeurerLoginName, ms_BaeurerPassword, ms_BaeurerSource) Then
    Exit Function
  End If
  
  ll_LockRowId = Bae_LockRecord(mo_DbBaeurer, "va1101", Array(ml_BaeurerFi_Nr, as_COF_Code), "vva100")
  If ll_LockRowId = 0 Then
    Call mo_Tools.ShowMsg(mo_Db, ms_Language_Code, 666, "#Manufacturing validation in progress")
    Exit Function
  End If
  
  ls_Req = "SELECT * FROM va1101 WHERE (aufnr_q=$aufnr_q$) AND (fi_nr=$fi_nr$) AND (kn_verarb IN ($kn_verarb$)) ORDER BY aufnr_q, aufpos_q, seblpos"
  ls_Req = Replace(ls_Req, "$aufnr_q$", mo_Tools.SQLStr(as_COF_Code), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$fi_nr$", mo_Tools.SqlInt(ml_BaeurerFi_Nr), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$kn_verarb$", mo_Tools.SqlStrIn(Array(BAE_PLABOX_FromCaptureReady, BAE_PLABOX_RequestReadyForCapture, BAE_PLABOX_RequestInProgress, BAE_PLABOX_RequestDeadlineTimeout)), , , vbTextCompare)
  lc_PlanBoxCursor = mo_Tools.OpenSQLSafe(mo_DbBaeurer, ls_Req)
  
  If mo_DbBaeurer.RowCount(lc_PlanBoxCursor) = 0 Then
    Call Bae_UnlockRecord(mo_DbBaeurer, ll_LockRowId)
    Call mo_DbBaeurer.Close(lc_PlanBoxCursor)
    as_ErrMsg = "No item to kill in planning box"
    Exit Function
  End If
  
  lc_Status = mo_DbBaeurer.Distinct(lc_PlanBoxCursor, "kn_verarb")
  If mo_DbBaeurer.RowCount(lc_Status) > 1 Then
    Call Bae_UnlockRecord(mo_DbBaeurer, ll_LockRowId)
    Call mo_DbBaeurer.Close(lc_Status)
    Call mo_DbBaeurer.Close(lc_PlanBoxCursor)
    as_ErrMsg = "No item to kill in planning box"
    Exit Function
  End If
  ls_KN_Verarb_Old = mo_DbBaeurer.GetFields(lc_Status, "kn_verarb")
  Call mo_DbBaeurer.Close(lc_Status)
  
  If StrComp(ls_KN_Verarb_Old, BAE_PLABOX_FromCaptureReady, vbTextCompare) = 0 Then
    ls_KN_Verarb_New = BAE_PLABOX_RequestConfirmationMarkedDelete
  ElseIf StrComp(ls_KN_Verarb_Old, BAE_PLABOX_RequestReadyForCapture, vbTextCompare) = 0 Then
    ls_KN_Verarb_New = BAE_PLABOX_RequestConfirmationMarkedDelete
  Else
    Call Bae_UnlockRecord(mo_DbBaeurer, ll_LockRowId)
    Call mo_DbBaeurer.Close(lc_PlanBoxCursor)
    as_ErrMsg = "You cannot delete planning box items with status: " & ls_KN_Verarb_Old
    Exit Function
  End If
  
  'Call UpdatePlaningBoxStatus(as_COF_Code, ls_KN_Verarb_Old, ls_KN_Verarb_New)
  ls_Req = "UPDATE va1101 SET kn_verarb=$kn_verarb_new$ WHERE aufnr_q=$aufnr_q$ AND fi_nr=$fi_nr$ AND kn_verarb IN ($kn_verarb_old$)"
  ls_Req = Replace(ls_Req, "$aufnr_q$", mo_Tools.SQLStr(as_COF_Code), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$fi_nr$", mo_Tools.SqlInt(ml_BaeurerFi_Nr), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$kn_verarb_old$", mo_Tools.SqlStrIn(ls_KN_Verarb_Old), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$kn_verarb_new$", mo_Tools.SQLStr(ls_KN_Verarb_New), , , vbTextCompare)
  Call mo_Tools.ExecuteSQLSafe(mo_DbBaeurer, ls_Req)
  
  ls_Req = "UPDATE Cap_Offer SET COF_CodeBae='' WHERE COF_Id=$COF_Id$"
  ls_Req = Replace(ls_Req, "$COF_Id$", mo_Tools.SQLStr(as_COF_Id), , , vbTextCompare)
  Call mo_Tools.ExecuteSQLSafe(mo_Db, ls_Req)
  
  ls_Req = "UPDATE Cap_OfferDetail SET OFD_OrdNrB7='', OFD_PosB7=0, OFD_InfoB7='' WHERE COF_Id=$COF_Id$"
  ls_Req = Replace(ls_Req, "$COF_Id$", mo_Tools.SQLStr(as_COF_Id), , , vbTextCompare)
  Call mo_Tools.ExecuteSQLSafe(mo_Db, ls_Req)
  
  
  Call Bae_UnlockRecord(mo_DbBaeurer, ll_LockRowId)
  Call mo_DbBaeurer.Disconnect
  Bae_KillSecretBox = True
  Exit Function
errorHandler:
  Call mo_Tools.UpdateError(True)
  If ll_LockRowId <> 0 Then
    Call Bae_UnlockRecord(mo_DbBaeurer, ll_LockRowId)
    Call mo_DbBaeurer.Disconnect
  End If
  Call mo_Tools.UpdateError(False)
  Call errorHandler("KillSecretBox")
End Function

Public Function Bae_GetOrderType(ByVal ao_Db As Object, ByVal al_Konto As Long) As Long
On Error GoTo errorHandler

Dim ls_Req As String

  ls_Req = "SELECT auf_art FROM g600 WHERE fi_nr=$fi_nr$ AND satzart=$satzart$ AND konto=$konto$"
  ls_Req = Replace(ls_Req, "$fi_nr$", mo_Tools.SqlInt(ml_BaeurerFi_Nr), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$satzart$", mo_Tools.SqlInt(1), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$konto$", mo_Tools.SqlInt(al_Konto), , , vbTextCompare)
  Bae_GetOrderType = mo_Tools.SelectValue(ao_Db, ls_Req)
  Exit Function
errorHandler:
  Call errorHandler("Bae_GetOrderType")
End Function

Public Function Bae_GetUserAccount(ByVal ao_Db As Object, ByVal al_Konto As Long, ByVal as_Email As String) As Long
On Error GoTo errorHandler

Dim ls_Req As String

'  ls_req = "SELECT sb_schl FROM g915 WHERE fi_nr=$fi_nr$ AND email=$email$"
'  ls_req = Replace(ls_req, "$fi_nr$", mo_Tools.SqlInt(ml_BaeurerFi_Nr), , , vbTextCompare)
'  ls_req = Replace(ls_req, "$email$", mo_Tools.SQLStr(as_Email), , , vbTextCompare)
  ls_Req = "SELECT ansprnr FROM g620 WHERE fi_nr=$fi_nr$ AND satzart=$satzart$ AND konto=$konto$ AND email=$email$"
  ls_Req = Replace(ls_Req, "$fi_nr$", mo_Tools.SqlInt(ml_BaeurerFi_Nr), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$satzart$", mo_Tools.SqlInt(1), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$konto$", mo_Tools.SqlInt(al_Konto), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$email$", mo_Tools.SQLStr(as_Email), , , vbTextCompare)
  Bae_GetUserAccount = mo_Tools.SelectValue(ao_Db, ls_Req)
  Exit Function
errorHandler:
  Call errorHandler("Bae_GetUserAccount")
End Function

Public Sub Bae_InsertProductSecretBox(ByVal ao_Db As Object, ByVal ac_Offer As Long, ByVal ac_OfferPos As Long)
On Error GoTo errorHandler

Dim ls_Req As String
  
  ls_Req = "INSERT INTO [va1101] "
  ls_Req = ls_Req & "([abrmenge], [aendnr], [identnr], [var], [aufnr_q], [aufpos_q], [auf_dat], [best_dat], [datbis], [lief_prio],"
  ls_Req = ls_Req & "[dataen], [datneu], [wunsch_term], [fi_nr], [kn_abruf], [sb_schl_q], [kn_verarb], [useraen], [userneu], [status_menge],"
  ls_Req = ls_Req & "[status_termin], [status_ruestko], [lief_termb], [menge_best], [sb_schl], [datum_frei], [konto], [satzart], [auf_art],"
  ls_Req = ls_Req & "[ben], [mevk], [projekt_id], [vvorgart], [lgnr], [info_b7], [aufnr], [aufpos], [ruestko], [info_txt], [info_b7_k],"
  ls_Req = ls_Req & "[seblpos], [seblpos_q], [kn_rueko], [vers_art], [lb]) "
  ls_Req = ls_Req & "VALUES"
  ls_Req = ls_Req & "($abrmenge$, $aendnr$, $identnr$, $var$, $aufnr_q$, $aufpos_q$, $auf_dat$, $best_dat$, $datbis$, $lief_prio$,"
  ls_Req = ls_Req & "$dataen$, $datneu$, $wunsch_term$, $fi_nr$, $kn_abruf$, $sb_schl_q$, $kn_verarb$, $useraen$, $userneu$, $status_menge$,"
  ls_Req = ls_Req & "$status_termin$, $status_ruestko$, $lief_termb$, $menge_best$, $sb_schl$, $datum_frei$, $konto$, $satzart$, $auf_art$,"
  ls_Req = ls_Req & "$ben$, $mevk$, $projekt_id$, $vvorgart$, $lgnr$, $info_b7$, $aufnr$, $aufpos$, $ruestko$, $info_txt$, $info_b7_k$,"
  ls_Req = ls_Req & "$seblpos$, $seblpos_q$, $kn_rueko$, $vers_art$, $lb$) "

  ls_Req = Replace(ls_Req, "$abrmenge$", mo_Tools.SqlInt(mo_Db.GetFields(ac_OfferPos, "OFD_QtyPCS")), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$aendnr$", mo_Tools.SqlInt(ml_BaeurerFi_Nr), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$identnr$", mo_Tools.SQLStr(mo_Db.GetFields(ac_OfferPos, "PRD_Code")), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$var$", mo_Tools.SQLStr(" "), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$aufnr_q$", mo_Tools.SQLStr(Left(mo_Db.GetFields(ac_Offer, "COF_Code"), 10)), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$aufpos_q$", mo_Tools.SqlInt(mo_Db.GetFields(ac_OfferPos, "OFD_Pos")), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$auf_dat$", mo_Tools.SqlDate(mo_Db.GetFields(ac_Offer, "Z_Creation")), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$best_dat$", mo_Tools.SqlDate(mo_Db.GetFields(ac_Offer, "Z_Creation")), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$datbis$", mo_Tools.SqlDate(mo_Db.GetFields(ac_Offer, "COF_ExDat")), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$lief_prio$", mo_Tools.SQLStr("5"), , , vbTextCompare)
  
  ls_Req = Replace(ls_Req, "$dataen$", "NULL", , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$datneu$", "getdate()", , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$wunsch_term$", mo_Tools.SqlDate(mo_Db.GetFields(ac_OfferPos, "OFD_WshDat")), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$fi_nr$", mo_Tools.SqlInt(ml_BaeurerFi_Nr), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$kn_abruf$", "NULL", , , vbTextCompare)
  'ls_Req = Replace(ls_Req, "$sb_schl_q$", mo_Tools.SqlInt(GetUserAccount(ao_Db, mo_Db.GetFields(ac_Offer, "LEN_BaeKonto"), mo_Db.GetFields(ac_Offer, "Z_CreatorEmail"))), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$sb_schl_q$", mo_Tools.SqlInt(Val(mo_Db.GetFields(ac_Offer, "COF_Bae_Partner"))), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$kn_verarb$", mo_Tools.SQLStr(BAE_PLABOX_FromCaptureReady), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$useraen$", "NULL", , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$userneu$", mo_Tools.SQLStr(mo_Db.GetFields(ac_Offer, "Z_CreatorDesc")), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$status_menge$", "NULL", , , vbTextCompare)
  
  ls_Req = Replace(ls_Req, "$status_termin$", "NULL", , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$status_ruestko$", "NULL", , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$lief_termb$", "NULL", , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$menge_best$", "NULL", , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$sb_schl$", "NULL", , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$datum_frei$", "NULL", , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$konto$", mo_Tools.SqlInt(Val(mo_Db.GetFields(ac_Offer, "LEN_BaeKonto"))), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$satzart$", mo_Tools.SqlInt(ml_BaeurerFi_Nr), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$auf_art$", mo_Tools.SqlInt(Bae_GetOrderType(ao_Db, mo_Db.GetFields(ac_Offer, "LEN_BaeKonto"))), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$ben$", mo_Tools.SQLStr(Left(mo_Db.GetFields(ac_Offer, "SP_Desc"), 40)), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$mevk$", mo_Tools.SQLStr("STK"), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$projekt_id$", mo_Tools.SQLStr(mo_Db.GetFields(ac_Offer, "SP_Capkey")), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$vvorgart$", "NULL", , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$lgnr$", "NULL", , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$info_b7$", "NULL", , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$aufnr$", "NULL", , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$aufpos$", "NULL", , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$ruestko$", "NULL", , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$info_txt$", mo_Tools.SQLStr(mo_Db.GetFields(ac_Offer, "COF_Comm"), 70), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$info_b7_k$", "NULL", , , vbTextCompare)
  
  ls_Req = Replace(ls_Req, "$seblpos$", "NULL", , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$seblpos_q$", mo_Tools.SqlInt(mo_Db.GetFields(ac_OfferPos, "OFD_Pos")), , , vbTextCompare)
  
  ls_Req = Replace(ls_Req, "$kn_rueko$", "NULL", , , vbTextCompare)
  
  ls_Req = Replace(ls_Req, "$vers_art$", mo_Tools.SqlInt(Val(mo_Db.GetFields(ac_Offer, "COF_Bae_DelType"))), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$lb$", mo_Tools.SqlInt(Val(mo_Db.GetFields(ac_Offer, "COF_Bae_DelCond"))), , , vbTextCompare)
  Call mo_Tools.ExecuteSQLSafe(ao_Db, ls_Req, 1)
  Exit Sub
errorHandler:
  Call errorHandler("Bae_InsertProductSecretBox")
End Sub

Public Function Bae_ExportSecretBox(ByVal as_COF_Id As String, ByRef as_ErrMessage As String) As Boolean
On Error GoTo errorHandler

Dim lc_Cursor As Long
Dim ls_Req As String
Dim ll_LockRowId As Long
Dim lc_Offer As Long
Dim lc_OfferPos As Long
Dim ll_CAT_Id As Long
Dim le_DOF_Id As eDPCOfferDetail
Dim le_OFD_Main As eDPCOfferDetailMain
Dim lc_PlanBoxCursor As Long
Dim ls_Status As String
Dim lb_PlanningFinished As Boolean
Dim lb_PlanningNotStarted As Boolean
Dim lb_PlanningTimeout As Boolean

  Bae_ExportSecretBox = False
  as_ErrMessage = ""
  
'  ls_req = "SELECT CCU.CCU_B7Konto FROM Cap_Offer COF INNER JOIN claim_customer CCU ON (COF.CCU_CapKey=CCU.CCU_Capkey) WHERE COF.COF_Id =$COF_Id$"
'  ls_req = Replace(ls_req, "$COF_Id$", mo_Tools.SQLStr(as_COF_Id), , , vbTextCompare)
'  If mo_Tools.SelectValue(mo_Db, ls_req) = 0 Then
'    as_ErrMessage = "#Offer customer was not exported to Baeurer B7"
'    Exit Function
'  End If
  
  
  ls_Req = "SELECT COUNT(*) FROM Cap_OfferDetail OFD INNER JOIN DPC_PrdCommon PRD ON (OFD.PRD_Id=PRD.PRD_Id) WHERE OFD.COF_Id =$COF_Id$ AND OFD.OFD_Main=1 AND OFD.OFD_Valid='X' AND (OFD.DOF_Id IN (1)) AND (OFD.CAT_Id IN (1)) AND PRD.PRD_StaBae<>1 AND OFD.Drop_Flag=''"
  ls_Req = Replace(ls_Req, "$COF_Id$", mo_Tools.SQLStr(as_COF_Id), , , vbTextCompare)
  If mo_Tools.SelectValue(mo_Db, ls_Req) > 0 Then
    as_ErrMessage = "#Not all custom materials inside sales order were successfuly exported to Baeurer B7"
    Exit Function
  End If
  
  If Not mo_Tools.ReconnectSafe(mo_DbBaeurer, ms_BaeurerServer, ms_BaeurerDatabase, ms_BaeurerLoginName, ms_BaeurerPassword, ms_BaeurerSource) Then
    Exit Function
  End If
  
  ls_Req = "exec Cap_Offer_sel $COF_Id$, $Language_Code$"
  ls_Req = Replace(ls_Req, "$COF_Id$", mo_Tools.SQLStr(as_COF_Id), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$Language_Code$", mo_Tools.SQLStr("E"), , , vbTextCompare)
  lc_Offer = mo_Tools.OpenSQLSafe(mo_Db, ls_Req)
  
  ls_Req = "SELECT LEN.LEN_BaeKonto FROM GEN_LegalEntity LEN WHERE LEN.LEN_Id = $LEN_Id$"
  ls_Req = Replace(ls_Req, "$LEN_Id$", mo_Tools.SqlInt(mo_Db.GetFields(lc_Offer, "LEN_Id")), , , vbTextCompare)
  If Trim(mo_Tools.SelectValue(mo_Db, ls_Req)) = "" Then
    Call mo_Db.Close(lc_Offer)
    Call mo_Db.Close(lc_OfferPos)
    as_ErrMessage = "#Internal customer is not defined for selected legal entity"
    Exit Function
  End If
  
  ls_Req = "exec Cap_OfferDetail_lst2 $COF_Id$, $Language_Code$, $OFD_Main$, $OFD_IdPar$, $OFD_Valid$, $OFD_Id$"
  ls_Req = Replace(ls_Req, "$COF_Id$", mo_Tools.SQLStr(as_COF_Id), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$Language_Code$", mo_Tools.SQLStr("E"), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$OFD_Main$", "NULL", , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$OFD_IdPar$", "NULL", , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$OFD_Valid$", "NULL", , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$OFD_Id$", "NULL", , , vbTextCompare)
  lc_OfferPos = mo_Tools.OpenSQLSafe(mo_Db, ls_Req)
  
  ll_LockRowId = Bae_LockRecord(mo_DbBaeurer, "va1101", Array(ml_BaeurerFi_Nr, mo_Db.GetFields(lc_Offer, "COF_Code")), "vva100")
  If ll_LockRowId = 0 Then
    Call mo_Db.Close(lc_Offer)
    Call mo_Db.Close(lc_OfferPos)
    as_ErrMessage = "#Manufacturing validation in progress"
    Exit Function
  End If
  
  lb_PlanningFinished = False
  lb_PlanningNotStarted = False
  lb_PlanningTimeout = False
  ls_Req = "SELECT kn_verarb FROM va1101 WHERE (aufnr_q=$aufnr_q$) AND (fi_nr=$fi_nr$) AND (kn_verarb NOT IN ($kn_verarb$)) ORDER BY aufnr_q, aufpos_q, seblpos"
  ls_Req = Replace(ls_Req, "$aufnr_q$", mo_Tools.SQLStr(mo_Db.GetFields(lc_Offer, "COF_Code")), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$fi_nr$", mo_Tools.SqlInt(ml_BaeurerFi_Nr), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$kn_verarb$", mo_Tools.SqlStrIn(Array(BAE_PLABOX_RequestConfirmationMarkedDelete, BAE_PLABOX_RequestConfirmationDeletedByBaeurer, BAE_PLABOX_RequestTrashed)), , , vbTextCompare)
  lc_PlanBoxCursor = mo_Tools.OpenSQLSafe(mo_DbBaeurer, ls_Req)
  If mo_DbBaeurer.RowCount(lc_PlanBoxCursor) > 0 Then
  
    Call mo_DbBaeurer.First(lc_PlanBoxCursor)
    While Not mo_DbBaeurer.EOF(lc_PlanBoxCursor)
      ls_Status = mo_DbBaeurer.GetFields(lc_PlanBoxCursor, "kn_verarb")
      If ls_Status = BAE_PLABOX_RequestReadyForCapture Then
        lb_PlanningFinished = True
        If lb_PlanningNotStarted Or lb_PlanningTimeout Then
          as_ErrMessage = "#Inconsistent state of planing box - status mixed: " & BAE_PLABOX_RequestReadyForCapture & BAE_PLABOX_FromCaptureReady & BAE_PLABOX_RequestInProgress & BAE_PLABOX_RequestDeadlineTimeout
          Call mo_DbBaeurer.Close(lc_PlanBoxCursor)
          Call mo_Db.Close(lc_Offer)
          Call mo_Db.Close(lc_OfferPos)
          Call Bae_UnlockRecord(mo_DbBaeurer, ll_LockRowId)
          Exit Function
        End If
      ElseIf (ls_Status = BAE_PLABOX_FromCaptureReady) Or _
         (ls_Status = BAE_PLABOX_RequestInProgress) Then
        lb_PlanningNotStarted = True
        If lb_PlanningFinished Or lb_PlanningTimeout Then
          as_ErrMessage = "#Inconsistent state of planing box - status mixed: " & BAE_PLABOX_RequestReadyForCapture & BAE_PLABOX_FromCaptureReady & BAE_PLABOX_RequestInProgress & BAE_PLABOX_RequestDeadlineTimeout
          Call mo_DbBaeurer.Close(lc_PlanBoxCursor)
          Call mo_Db.Close(lc_Offer)
          Call mo_Db.Close(lc_OfferPos)
          Call Bae_UnlockRecord(mo_DbBaeurer, ll_LockRowId)
          Exit Function
        End If
      ElseIf ls_Status = BAE_PLABOX_RequestDeadlineTimeout Then
        lb_PlanningTimeout = True
        If lb_PlanningFinished Or lb_PlanningNotStarted Then
          as_ErrMessage = "#Inconsistent state of planing box - status mixed: " & BAE_PLABOX_RequestReadyForCapture & BAE_PLABOX_FromCaptureReady & BAE_PLABOX_RequestInProgress & BAE_PLABOX_RequestDeadlineTimeout
          Call mo_DbBaeurer.Close(lc_PlanBoxCursor)
          Call mo_Db.Close(lc_Offer)
          Call mo_Db.Close(lc_OfferPos)
          Call Bae_UnlockRecord(mo_DbBaeurer, ll_LockRowId)
          Exit Function
        End If
      Else
        as_ErrMessage = "#Order is locked in the planning box"
        Call mo_DbBaeurer.Close(lc_PlanBoxCursor)
        Call mo_Db.Close(lc_Offer)
        Call mo_Db.Close(lc_OfferPos)
        Call Bae_UnlockRecord(mo_DbBaeurer, ll_LockRowId)
        Exit Function
      End If
      Call mo_DbBaeurer.Next(lc_PlanBoxCursor)
    Wend
  End If
  Call mo_DbBaeurer.Close(lc_PlanBoxCursor)
  
  ls_Req = "UPDATE va1101 SET kn_verarb=$kn_verarb_new$ WHERE aufnr_q=$aufnr_q$ AND fi_nr=$fi_nr$ AND kn_verarb IN ($kn_verarb_old$)"
  ls_Req = Replace(ls_Req, "$aufnr_q$", mo_Tools.SQLStr(mo_Db.GetFields(lc_Offer, "COF_Code")), , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$fi_nr$", mo_Tools.SqlInt(ml_BaeurerFi_Nr), , , vbTextCompare)
  If lb_PlanningFinished Then
    ls_Req = Replace(ls_Req, "$kn_verarb_new$", mo_Tools.SQLStr(BAE_PLABOX_RequestConfirmationMarkedDelete), , , vbTextCompare)
    ls_Req = Replace(ls_Req, "$kn_verarb_old$", mo_Tools.SqlStrIn(Array(BAE_PLABOX_RequestReadyForCapture)), , , vbTextCompare)
    Call mo_Tools.ExecuteSQLSafe(mo_DbBaeurer, ls_Req)
  ElseIf lb_PlanningNotStarted Then
    ls_Req = Replace(ls_Req, "$kn_verarb_new$", mo_Tools.SQLStr(BAE_PLABOX_RequestConfirmationDeletedByBaeurer), , , vbTextCompare)
    ls_Req = Replace(ls_Req, "$kn_verarb_old$", mo_Tools.SqlStrIn(Array(BAE_PLABOX_FromCaptureReady, BAE_PLABOX_RequestInProgress, BAE_PLABOX_RequestAcceptedByCapture)), , , vbTextCompare)
    Call mo_Tools.ExecuteSQLSafe(mo_DbBaeurer, ls_Req)
  ElseIf lb_PlanningTimeout Then
    ls_Req = Replace(ls_Req, "$kn_verarb_new$", mo_Tools.SQLStr(BAE_PLABOX_RequestConfirmationDeletedByBaeurer), , , vbTextCompare)
    ls_Req = Replace(ls_Req, "$kn_verarb_old$", mo_Tools.SqlStrIn(Array(BAE_PLABOX_RequestDeadlineTimeout)), , , vbTextCompare)
    Call mo_Tools.ExecuteSQLSafe(mo_DbBaeurer, ls_Req)
  End If
  
  Call mo_Db.First(lc_OfferPos)
  While Not mo_Db.EOF(lc_OfferPos)
    le_OFD_Main = mo_Db.GetFields(lc_OfferPos, "OFD_Main")
    ll_CAT_Id = mo_Db.GetFields(lc_OfferPos, "CAT_Id")
    le_DOF_Id = mo_Db.GetFields(lc_OfferPos, "DOF_Id")
    If (le_OFD_Main = eDPCOfferDetailMain.odMain) And _
       (le_DOF_Id = eDPCOfferDetail.odPosition) And _
      ((ll_CAT_Id = eDPCCategory.cgMetalCustomRectPanel) Or (ll_CAT_Id = eDPCCategory.cgMetalPanelSKU)) Then
      If mo_Db.GetFields(lc_OfferPos, "OFD_B7Sta") <> 7 Then
        Call Bae_InsertProductSecretBox(mo_DbBaeurer, lc_Offer, lc_OfferPos)
      End If
    End If
    Call mo_Db.Next(lc_OfferPos)
  Wend
  
  Call Bae_UnlockRecord(mo_DbBaeurer, ll_LockRowId)
  Call mo_Db.Close(lc_Offer)
  Call mo_Db.Close(lc_OfferPos)
  Call mo_DbBaeurer.Disconnect
  Bae_ExportSecretBox = True
  Exit Function
errorHandler:
  Call mo_Tools.UpdateError(True)
  If ll_LockRowId <> 0 Then
    Call Bae_UnlockRecord(mo_DbBaeurer, ll_LockRowId)
    Call mo_DbBaeurer.Disconnect
  End If
  Call mo_Tools.UpdateError(False)
  Call errorHandler("Bae_ExportSecretBox")
End Function

'Public Function ExportSecretBox(ByVal ac_Offer As Long, ByVal ac_OfferPos As Long) As Boolean
'On Error GoTo errorHandler
'
'Dim lo_Product As DPC_Product
'Dim ll_LockRowId As Long
'Dim lc_Offer As Long
'Dim lc_OfferPos As Long
'Dim lc_PlanBoxCursor As Long
'Dim ls_Req As String
'Dim ls_Status As String

    
'  ls_Req = "exec Cap_Offer_sel $COF_Id$, $Language_Code$"
'  ls_Req = Replace(ls_Req, "$COF_Id$", mo_Tools.SQLStr(as_COF_Id), , , vbTextCompare)
'  ls_Req = Replace(ls_Req, "$Language_Code$", mo_Tools.SQLStr("E"), , , vbTextCompare)
'  lc_Offer = mo_Tools.OpenSQLSafe(mo_Db, ls_Req)
'
'  ls_Req = "exec Cap_OfferDetail_lst2 $COF_Id$, $Language_Code$, $OFD_Main$, $OFD_IdPar$, $OFD_Valid$, $OFD_Id$"
'  ls_Req = Replace(ls_Req, "$COF_Id$", mo_Tools.SQLStr(as_COF_Id), , , vbTextCompare)
'  ls_Req = Replace(ls_Req, "$Language_Code$", mo_Tools.SQLStr("E"), , , vbTextCompare)
'  ls_Req = Replace(ls_Req, "$OFD_Main$", "NULL", , , vbTextCompare)
'  ls_Req = Replace(ls_Req, "$OFD_IdPar$", "NULL", , , vbTextCompare)
'  ls_Req = Replace(ls_Req, "$OFD_Valid$", "NULL", , , vbTextCompare)
'  ls_Req = Replace(ls_Req, "$OFD_Id$", mo_Tools.SQLStr(as_OFD_Id), , , vbTextCompare)
'  lc_OfferPos = mo_Tools.OpenSQLSafe(mo_Db, ls_Req, 1)
'
'  Set lo_Product = New DPC_Product
'  Set lo_Product.Tools = mo_Tools
'  Set lo_Product.ArmDb = mo_Db
'  lo_Product.U_Code = ml_U_Code
'  lo_Product.CT_Code = ms_CT_Code
'  lo_Product.CURR_Code = "EUR"
'  lo_Product.ValidityDate = ValidityDate
'  lo_Product.Language_Code = "E"
'  lo_Product.COF_Id = as_COF_Id
'  Call lo_Product.Load_A_COM
'  Call lo_Product.InitOffer
'  Call lo_Product.Load(mo_Db.GetFields(lc_OfferPos, "PRD_ID"))
'  Call lo_Product.LoadOffer(as_COF_Id, as_OFD_Id)
  
  'll_LockRowId = LockRecord(mo_DbBaeurer, "va1101", Array(ml_BaeurerFi_Nr, mo_Db.GetFields(lc_Offer, "COF_Code")), "vva100")
'  Call InsertProductSecretBox(mo_DbBaeurer, ac_Offer, ac_OfferPos)
  'Call UnlockRecord(mo_DbBaeurer, ll_LockRowId)
'  Call mo_Db.Close(lc_Offer)
'  Call mo_Db.Close(lc_OfferPos)
'  Call lo_Product.Unload_A_COM
'  Set lo_Product = Nothing
'  ExportSecretBox = True
'  Exit Function
'errorHandler:
'  Call errorHandler("ExportSecretBox")
'End Function

Public Sub Bae_ExportCustomerAll()
On Error GoTo errorHandler

Dim lc_Cursor As Long
Dim ls_Req As String
Dim ll_RowIdTran As Long

  ls_Req = "exec xxx_lst $PRD_Id$,$Cust_Status$"
  ls_Req = Replace(ls_Req, "$PRD_Id$", "NULL", , , vbTextCompare)
  ls_Req = Replace(ls_Req, "$Cust_Status$", mo_Tools.SqlInt(eDPCBaeurerExportStatus.esReadyToExport), , vbTextCompare)
  lc_Cursor = mo_Tools.OpenSQLSafe(mo_Db, ls_Req)
  While Not mo_Db.EOF(lc_Cursor)
    ll_RowIdTran = Bae_ExportArticle(mo_Db.GetFields(mo_Db, "PRD_Id"))
    
    ls_Req = "UPDATE xxxxx SET "
    ls_Req = ls_Req & "PMaster_Status=$PMaster_Status$,"
    ls_Req = ls_Req & "PMaster_Date=getdate(),"
    ls_Req = ls_Req & "PMaster_Rowidtran=$Rowidtran$,"
    ls_Req = ls_Req & "Z_Last_Upd_User=$Z_Last_Upd_User$,"
    ls_Req = ls_Req & "Z_Last_Upd=getdate(),"
    ls_Req = ls_Req & "WHERE PRD_Id=$PRD_Id$"
    ls_Req = Replace(ls_Req, "$PRD_Id$", "NULL", , , vbTextCompare)
    ls_Req = Replace(ls_Req, "$PMaster_Status$", mo_Tools.SqlInt(eDPCBaeurerExportStatus.esExported), , vbTextCompare)
    ls_Req = Replace(ls_Req, "$Rowidtran$", mo_Tools.SqlInt(ll_RowIdTran), , vbTextCompare)
    Call mo_Tools.ExecuteSQLSafe(mo_Db, ls_Req, 1)
    Call mo_Db.Next(lc_Cursor)
  Wend
  Call mo_Db.Close(lc_Cursor)
  Exit Sub
errorHandler:
  Call errorHandler("Bae_ExportCustomerAll")
End Sub

Public Function Bae_ExportCustomer(ByVal as_CCU_Capkey As String) As Boolean
On Error GoTo errorHandler

Dim lo_XmlDocCust As Object
Dim ll_RowIdTran As Long
Dim ll_Konto As Long
Dim ls_Request As String
Dim lc_Cursor As Long
Dim ll_VersionCust As Long

  Bae_ExportCustomer = False
  
  Call ClearLogInterface
  mo_ILO.ILO_Interface = eDPCXmlExportType.etBae_Customer
  mo_ILO.ILO_MasterId = as_CCU_Capkey
  
  If Not mo_Tools.ReconnectSafe(mo_DbBaeurer, ms_BaeurerServer, ms_BaeurerDatabase, ms_BaeurerLoginName, ms_BaeurerPassword, ms_BaeurerSource) Then
    Exit Function
  End If

  
#If TEST = 0 Then
  'Call SaveXMLDocument(lo_XmlDocCust, "CUST")
  'Exit Function
#End If
  
  ls_Request = "SELECT CCU_B7Konto FROM claim_customer WHERE CCU_Capkey=$CCU_Capkey$"
  ls_Request = Replace(ls_Request, "$CCU_Capkey$", mo_Tools.SQLStr(as_CCU_Capkey), , , vbTextCompare)
  ll_Konto = mo_Tools.SelectValue(mo_Db, ls_Request)
  
  If ll_Konto = 0 Then
    
    ls_Request = "SELECT MAX(Konto) + 1 FROM g600 where konto < 99999999 and fi_nr = 1"
    ll_Konto = mo_Tools.SelectValue(mo_DbBaeurer, ls_Request)
    
    ls_Request = "UPDATE claim_customer SET CCU_B7Konto=$CCU_B7Konto$ WHERE CCU_CapKey=$CCU_Capkey$"
    ls_Request = Replace(ls_Request, "$CCU_B7Konto$", mo_Tools.SqlInt(ll_Konto), , , vbTextCompare)
    ls_Request = Replace(ls_Request, "$CCU_Capkey$", mo_Tools.SQLStr(as_CCU_Capkey), , , vbTextCompare)
    Call mo_Tools.ExecuteSQLSafe(mo_Db, ls_Request, 1)
    
    Set lo_XmlDocCust = Bae_CreateXMLDocument(mo_Db, eDPCXmlExportType.etBae_Customer, as_CCU_Capkey, ll_VersionCust, Nothing)
    ll_RowIdTran = Bae_ExportCustomerRecord(mo_DbBaeurer, 0, ll_Konto, eDPCXmlExportType.etBae_Customer, lo_XmlDocCust, ll_VersionCust)
    Call Bae_ExportCustomerComplete(mo_DbBaeurer, ll_RowIdTran, as_CCU_Capkey)
    
    mo_ILO.ILO_Status = eDPCInterfaceStatus.isOK
    
    Bae_ExportCustomer = True
  Else
    mo_ILO.ILO_Error = "Konto <> 0"
    mo_ILO.ILO_Status = eDPCInterfaceStatus.isFailed
  End If
  
  Call LogInterface(mo_Db, ml_U_Code)
    
  Exit Function
errorHandler:
  
  Call LogInterface(mo_Db, ml_U_Code)
    
  Call errorHandler("Bae_ExportCustomer")
End Function

Private Function Bae_ExportPMasterRecord(ByVal ao_Db As Object, ByVal al_RowIdTran As Long, ByVal as_Key As String, ByVal ae_ATR_Type As eDPCXmlExportType, ByRef ao_XMLDoc As MSXML2.DOMDocument, ByVal al_Version As Long) As Long
On Error GoTo errorHandler

Dim ls_Request As String
Dim ls_RequestTran As String
Dim ls_path As String
Dim ll_RowId As Long
Dim lc_Cursor As Long

  Call ClearLogInterface
  mo_ILO.ILO_Interface = ae_ATR_Type
  mo_ILO.ILO_MasterId = as_Key
  
  ls_Request = "INSERT INTO tran_sc " & _
              "(rowidtran,identnr,var,xmldatatype,xmllong,status_tran,msg_text,uebdat,verarbdat,versionsnr,source) " & _
              "VALUES " & _
              "($rowidtran$, $identnr$, $var$, $xmldatatype$, $xmllong$, $status_tran$, $msg_text$, $uebdat$, $verarbdat$, $versionsnr$, $source$)"
              
  ls_RequestTran = "UPDATE tran_sc SET rowidtran=rowid where rowid=$rowid$"
  
  ls_Request = Replace(ls_Request, "$rowidtran$", mo_Tools.SqlInt(al_RowIdTran), , , vbTextCompare)
  ls_Request = Replace(ls_Request, "$status_tran$", mo_Tools.SQLStr(""), , , vbTextCompare)
  ls_Request = Replace(ls_Request, "$msg_text$", mo_Tools.SQLStr(""), , , vbTextCompare)
  ls_Request = Replace(ls_Request, "$uebdat$", "getdate()", , , vbTextCompare)
  ls_Request = Replace(ls_Request, "$verarbdat$", "NULL", , , vbTextCompare)
  ls_Request = Replace(ls_Request, "$versionsnr$", mo_Tools.SqlInt(al_Version), , , vbTextCompare)
  ls_Request = Replace(ls_Request, "$source$", mo_Tools.SQLStr(ms_BaeurerSource), , , vbTextCompare)
  
  ls_Request = Replace(ls_Request, "$identnr$", mo_Tools.SqlStrKey(as_Key), , , vbTextCompare)
  ls_Request = Replace(ls_Request, "$var$", mo_Tools.SQLStr(""), , , vbTextCompare)
  
  Select Case ae_ATR_Type
  Case eDPCXmlExportType.etBae_ArticleMaster
    ls_path = CreateXMLPath("PMASTER", as_Key)
    ls_Request = Replace(ls_Request, "$xmldatatype$", mo_Tools.SQLStr("PMASTER"), , , vbTextCompare)
  Case eDPCXmlExportType.etBae_BOM
    ls_path = CreateXMLPath("BOM", as_Key)
    ls_Request = Replace(ls_Request, "$xmldatatype$", mo_Tools.SQLStr("BOM"), , , vbTextCompare)
  Case eDPCXmlExportType.etBae_BOR
    ls_path = CreateXMLPath("BOR", as_Key)
    ls_Request = Replace(ls_Request, "$xmldatatype$", mo_Tools.SQLStr("BOR"), , , vbTextCompare)
  Case eDPCXmlExportType.etBae_Material
    ls_path = CreateXMLPath("PMASTER", as_Key)
    ls_Request = Replace(ls_Request, "$xmldatatype$", mo_Tools.SQLStr("PMASTER"), , , vbTextCompare)
  Case Else
    mo_ILO.ILO_Error = "Invalid ATR_Type: " & ae_ATR_Type
    Err.Raise ArmErr.InvalidArgument, "ae_ATR_Type", "Invalid ATR_Type: " & ae_ATR_Type
  End Select
  
  ls_Request = Replace(ls_Request, "$xmllong$", mo_Tools.SQLStr(ao_XMLDoc.xml), , , vbTextCompare)
  
  
  Call mo_Tools.ExecuteSQLSafe(ao_Db, ls_Request)
  ll_RowId = mo_Tools.GetLastIdentity(ao_Db)
 
  If al_RowIdTran = 0 Then
    ls_RequestTran = Replace(ls_RequestTran, "$rowid$", mo_Tools.SqlInt(ll_RowId), , , vbTextCompare)
    Call mo_Tools.ExecuteSQLSafe(ao_Db, ls_RequestTran)
  End If
  Bae_ExportPMasterRecord = ll_RowId
  
  mo_ILO.ILO_Status = eDPCInterfaceStatus.isOK
  Call LogInterface(mo_Db, ml_U_Code)
  
  Exit Function
errorHandler:
  
  mo_ILO.ILO_Status = eDPCInterfaceStatus.isFailed
  Call LogInterface(mo_Db, ml_U_Code)
  
  Call errorHandler("Bae_ExportPMasterRecord")
End Function

Private Function Bae_ExportCustomerRecord(ByVal ao_Db As Object, ByVal al_RowIdTran As Long, ByVal al_Konto As Long, ByVal ae_ATR_Type As eDPCXmlExportType, ByRef ao_XMLDoc As MSXML2.DOMDocument, ByVal al_Version As Long) As Long
On Error GoTo errorHandler

Dim ls_Request As String
Dim ls_RequestTran As String
Dim ls_path As String
Dim ll_RowId As Long
Dim lc_Cursor As Long

  ls_Request = "INSERT INTO tran_cus (rowidtran, konto, satzart, xmldatatype, xmllong, status_tran, msg_text, uebdat, verarbdat, versionsnr, source) " & _
              " VALUES " & _
              "($rowidtran$, $konto$, $satzart$, $xmldatatype$, $xmllong$, $status_tran$, $msg_text$, $uebdat$, $verarbdat$, $versionsnr$, $source$)"
  ls_RequestTran = "UPDATE tran_cus SET rowidtran=rowid where rowid=$rowid$"
  
  ls_Request = Replace(ls_Request, "$rowidtran$", mo_Tools.SqlInt(al_RowIdTran), , , vbTextCompare)
  ls_Request = Replace(ls_Request, "$status_tran$", mo_Tools.SQLStr(""), , , vbTextCompare)
  ls_Request = Replace(ls_Request, "$msg_text$", mo_Tools.SQLStr(""), , , vbTextCompare)
  ls_Request = Replace(ls_Request, "$uebdat$", "getdate()", , , vbTextCompare)
  ls_Request = Replace(ls_Request, "$verarbdat$", "NULL", , , vbTextCompare)
  ls_Request = Replace(ls_Request, "$versionsnr$", mo_Tools.SqlInt(al_Version), , , vbTextCompare)
  ls_Request = Replace(ls_Request, "$source$", mo_Tools.SQLStr(ms_BaeurerSource), , , vbTextCompare)
  ls_Request = Replace(ls_Request, "$konto$", mo_Tools.SqlIntKey(al_Konto), , , vbTextCompare)
  ls_Request = Replace(ls_Request, "$satzart$", mo_Tools.SqlInt(1), , , vbTextCompare)
  
  ls_path = CreateXMLPath("CUST", al_Konto)
  
  If ae_ATR_Type = eDPCXmlExportType.etBae_Customer Then
    ls_Request = Replace(ls_Request, "$xmldatatype$", mo_Tools.SQLStr("CUSTOMER"), , , vbTextCompare)
  Else
    Err.Raise ArmErr.InvalidArgument, "ae_ATR_Type", "Invalid ATR_Type: " & ae_ATR_Type
  End If
  
  ls_Request = Replace(ls_Request, "$xmllong$", mo_Tools.SQLStr(ao_XMLDoc.xml), , , vbTextCompare)
  Call ao_XMLDoc.Save(ls_path)
  
'  If Not ao_Db.FileToBlobSQL(ls_Request, ls_Path, 0, 0) Then
'    Err.Raise ArmErr.CompFncFailed, "FileToBlobSQL", ao_Db.LastErrorMessage
'  End If
  
  Call mo_Tools.ExecuteSQLSafe(ao_Db, ls_Request)
  ll_RowId = mo_Tools.GetLastIdentity(ao_Db)
 
  If al_RowIdTran = 0 Then
    ls_RequestTran = Replace(ls_RequestTran, "$rowid$", mo_Tools.SqlInt(ll_RowId), , , vbTextCompare)
    Call mo_Tools.ExecuteSQLSafe(ao_Db, ls_RequestTran)
  End If
  Bae_ExportCustomerRecord = ll_RowId
  Call mo_Shell.Run("""" & ls_path & """")
  Exit Function
errorHandler:
  Call errorHandler("Bae_ExportCustomerRecord")
End Function

Private Function CreateXMLPath(ByVal as_ExportName As String, ByVal as_Key As String) As String
On Error GoTo errorHandler
Dim ls_path As String

  ls_path = mo_Tools.GetAndCreateTempDir(mo_FSO, SCREEN_NAME)
  as_Key = Replace(as_Key, "\", "_", , , vbTextCompare)
  as_Key = Replace(as_Key, "/", "_", , , vbTextCompare)
  as_Key = Replace(as_Key, "$", "_", , , vbTextCompare)
  as_Key = Replace(as_Key, "*", "_", , , vbTextCompare)
  
  CreateXMLPath = ls_path & "\" & as_ExportName & as_Key & ".xml"
  Exit Function
errorHandler:
  Call errorHandler("CreateXMLPath")
End Function

Private Sub Bae_ExportCustomerComplete(ByVal ao_Db As Object, ByVal al_RowIdTran As Long, ByVal as_CCU_Capkey As String)
On Error GoTo errorHandler

  Dim ls_Request As String

  ls_Request = "UPDATE tran_cus SET status_tran=$status_tran$ where rowidtran=$rowidtran$"
  ls_Request = Replace(ls_Request, "$status_tran$", mo_Tools.SQLStr(ROWIDTRANSTATUS_NEW), , , vbTextCompare)
  ls_Request = Replace(ls_Request, "$rowidtran$", mo_Tools.SqlInt(al_RowIdTran), , , vbTextCompare)
  Call mo_Tools.ExecuteSQLSafe(ao_Db, ls_Request)
  Exit Sub
errorHandler:
  Call errorHandler("Bae_ExportCustomerComplete")
End Sub

Private Sub Bae_ExportPMasterComplete(ByVal ao_Db As Object, ByVal al_RowIdTran As Long, ByVal as_PRD_Id As String)
On Error GoTo errorHandler

  Dim ls_Request As String

  ls_Request = "UPDATE tran_sc SET status_tran=$status_tran$ where rowidtran=$rowidtran$"
  ls_Request = Replace(ls_Request, "$status_tran$", mo_Tools.SQLStr(ROWIDTRANSTATUS_NEW), , , vbTextCompare)
  ls_Request = Replace(ls_Request, "$rowidtran$", mo_Tools.SqlInt(al_RowIdTran), , , vbTextCompare)
  Call mo_Tools.ExecuteSQLSafe(ao_Db, ls_Request)
  Exit Sub
errorHandler:
  Call errorHandler("Bae_ExportPMasterComplete")
End Sub

Public Function ConvertCodeFromAMC(ByVal as_CodeConversion As String, ByVal as_CodeOut As String) As String
On Error GoTo ErrHandler

Dim lc_Cursor As Long
Dim ls_Request As String

  ConvertCodeFromAMC = ""
  ls_Request = "SELECT AC_CodeIn "
  ls_Request = ls_Request & "FROM A_CodeTranslator "
  ls_Request = ls_Request & "WHERE "
  ls_Request = ls_Request & "AC_CodeLookup = $AC_CodeLookup$ AND "
  ls_Request = ls_Request & "AC_CodeOut = $AC_CodeOut$"
    
  ls_Request = Replace(ls_Request, "$AC_CodeLookup$", mo_Tools.SQLStr(as_CodeConversion), , , vbTextCompare)
  ls_Request = Replace(ls_Request, "$AC_CodeOut$", mo_Tools.SQLStr(as_CodeOut), , , vbTextCompare)
  
  lc_Cursor = mo_Tools.OpenSQLSafe(mo_Db, ls_Request)
  If mo_Db.RowCount(lc_Cursor) = 1 Then
    ConvertCodeFromAMC = mo_Db.GetFields(lc_Cursor, "AC_CodeIn")
  Else
    Err.Raise ArmErr.InvalidArgument, "as_CodeIn", "Invalid conversion code as_CodeConversion: " & as_CodeConversion & " as_CodeOut: " & as_CodeOut
  End If
  Call mo_Db.Close(lc_Cursor)
  Exit Function
ErrHandler:
  Call mo_Db.Close(lc_Cursor)
  Call errorHandler("ConvertCodeFromAMC")
End Function

Public Function ConvertCodeToAMC(ByVal as_CodeConversion As String, ByVal as_CodeIn As String) As String
On Error GoTo ErrHandler

Dim lc_Cursor As Long
Dim ls_Request As String

  ConvertCodeToAMC = ""
  ls_Request = "SELECT AC_CodeOut "
  ls_Request = ls_Request & "FROM A_CodeTranslator "
  ls_Request = ls_Request & "WHERE "
  ls_Request = ls_Request & "AC_CodeLookup = $AC_CodeLookup$ AND "
  ls_Request = ls_Request & "AC_CodeIn = $AC_CodeIn$"
  
  ls_Request = Replace(ls_Request, "$AC_CodeLookup$", mo_Tools.SQLStr(as_CodeConversion), , , vbTextCompare)
  ls_Request = Replace(ls_Request, "$AC_CodeIn$", mo_Tools.SQLStr(as_CodeIn), , , vbTextCompare)
  
  lc_Cursor = mo_Tools.OpenSQLSafe(mo_Db, ls_Request)
  If mo_Db.RowCount(lc_Cursor) = 1 Then
    ConvertCodeToAMC = mo_Db.GetFields(lc_Cursor, "AC_CodeOut")
  Else
    Err.Raise ArmErr.InvalidArgument, "as_CodeIn", "Invalid conversion code as_CodeConversion: " & as_CodeConversion & " as_CodeIn: " & as_CodeIn
  End If
  Call mo_Db.Close(lc_Cursor)
  Exit Function
ErrHandler:
  Call mo_Db.Close(lc_Cursor)
  Call errorHandler("ConvertCodeToAMC")
End Function

Public Function GetATRValue(ByVal al_CursorXML As Long, ByVal al_CursorMaster As Long, ByVal al_ATR_Name As String) As Variant
On Error GoTo ErrHandler

Dim ls_Value As String
Dim ls_place As String

  GetATRValue = ""
  
  If mo_Db.Find(al_CursorXML, "ATR_Name", al_ATR_Name, 0, 1) < 0 Then
       Err.Raise ArmErr.SQLBadRowExpectedCount, "Distinct", "No SQL Data for XML export found. ATR_B7Name missing:" + al_ATR_Name
  Else
    ls_place = mo_Db.GetFields(al_CursorXML, "ATR_Value")
    If InStr(ls_place, "$") > 0 Then
        GetATRValue = mo_Db.GetFields(al_CursorMaster, Replace(ls_place, "$", ""))
    Else
        GetATRValue = ls_place
    End If
  End If
    
  Exit Function
ErrHandler:
  Call errorHandler("GetATRValue")
End Function

Public Function SplitATRValue(ByVal as_Value As String, ByVal al_DataLength As Long) As String()
On Error GoTo ErrHandler

Dim la_StrValues() As String
Dim ll_Dimension As Integer
Dim ll_Index As Integer
Dim ll_Pos As Integer

    SplitATRValue = la_StrValues
    
    ReDim la_StrValues(0)
    ll_Index = 0

    If Len(as_Value) > al_DataLength Then
      While Len(as_Value) > al_DataLength
      
          ReDim Preserve la_StrValues(UBound(la_StrValues) + 1)
          ll_Pos = InStrRev(as_Value, vbCrLf, al_DataLength)
          If ll_Pos <= 0 Then
              ll_Pos = InStrRev(as_Value, " ", al_DataLength)
              If ll_Pos > 0 Then
                ll_Pos = ll_Pos - 1
              End If
          End If
          If ll_Pos > 0 Then
              la_StrValues(ll_Index) = Left(as_Value, ll_Pos)
              ll_Index = ll_Index + 1
              as_Value = right(as_Value, Len(as_Value) - (ll_Pos + 1))
          Else
              la_StrValues(ll_Index) = Left(as_Value, al_DataLength)
              ll_Index = ll_Index + 1
              as_Value = right(as_Value, Len(as_Value) - al_DataLength)
          End If
      Wend
      If Len(as_Value) > 0 Then
          la_StrValues(ll_Index) = as_Value
      Else
          ReDim Preserve la_StrValues(UBound(la_StrValues) - 1)
      End If
    Else
      ReDim la_StrValues(0)
      la_StrValues(0) = as_Value
    End If
    
    SplitATRValue = la_StrValues
    
  Exit Function
ErrHandler:
  Call errorHandler("SplitATRValue")
End Function

Public Function SAP_MaterialCreate(ByVal as_COF_Id As String, ByVal as_OFD_Id As String, ByRef as_ErrorMsg As String) As Boolean
On Error GoTo errorHandler

Dim ls_Xml As String
Dim ls_Response As String

        SAP_MaterialCreate = False
        
        ls_Xml = SAP_MaterialCreateGetXML(as_COF_Id, as_OFD_Id)
        If (SendRequest(DPC_SAP_MATERIAL_CREATE, "POST", ls_Xml, ls_Response) = True) Then
            
            'ls_Response = "<?xml version=""1.0"" encoding=""UTF-8""?><AMC_BASIC_SAP_BAPI_RESPONSE><SUCC_FAIL_IND>F</SUCC_FAIL_IND><ERRORS><ERROR_GROUP>" & _
            '    "<SEVERITY_TYPE>E</SEVERITY_TYPE><MSG_CLASS>SAP_WRAPPER_FM</MSG_CLASS><MSG_NO>999</MSG_NO><MSG_TEXT>Material already exists and changes are not permitted</MSG_TEXT>" & _
            '    "<MSG_PARM_ROW>0</MSG_PARM_ROW></ERROR_GROUP></ERRORS></AMC_BASIC_SAP_BAPI_RESPONSE>"
            
            If (SAP_ProcessBasicResponse(ls_Response, as_ErrorMsg) = True) Then
                SAP_MaterialCreate = True
            End If
            
            Call LogInterface(mo_Db, ml_U_Code)
        Else
            as_ErrorMsg = ls_Response
        End If
        
  Exit Function
errorHandler:
  
  Call LogInterface(mo_Db, ml_U_Code)
  
  Call errorHandler("SAP_MaterialCreate")
End Function


Public Function SAP_MaterialCreateGetXML(ByVal as_COF_Id As String, ByVal as_OFD_Id As String) As String
On Error GoTo errorHandler

Dim lo_XmlDocCust As Object
Dim lo_SubNode As Object
Dim lo_parentNode As Object
Dim lo_MainNode As Object
Dim lc_CursorMaster As Long
Dim lc_Header As Long
Dim lc_CursorXML As Long
Dim lt_XmlSql As TXmlSql
Dim lt_XmlMaster As TXmlSql
Dim lo_XMLDoc As MSXML2.DOMDocument
Dim ls_Request As String
Dim ls_ATR_Value As String
Dim ls_ATR_DataLength As Long
Dim la_StrValues() As String
Dim ll_Nominator As Long, ll_Denominator As Long
Dim ll_Index As Integer
Dim ls_UOM As String, ll_OFD_PU As Long
Dim ls_OFD_CurrCode, ls_RequiredCurrCode As String
Dim ld_ExRate, ld_Cost As Double

  Call ClearLogInterface
  mo_ILO.ILO_Interface = eDPCXmlExportType.etSAP_MaterialCreate
  
  Set lo_XMLDoc = CreateObject("MSXML2.DOMDocument")
  
  lc_CursorXML = SAP_GetXmlCursor(eDPCXmlExportType.etSAP_MaterialCreate)
    
  Set lo_MainNode = lo_XMLDoc.createProcessingInstruction("xml", "version='1.0' encoding='utf-8'")
  lo_XMLDoc.appendChild lo_MainNode
    
  Set lo_MainNode = AppendElement(lo_XMLDoc, Nothing, "AMC_MATERIAL_ICTP_CREATE", "")
  lo_MainNode.appendChild lo_XMLDoc.createTextNode(vbNewLine + vbTab)
      
  ls_Request = "exec DPC_SAPMaterialCreateHeader_sel $COF_Id$,$OFD_Id$,$Language_Code$"
  ls_Request = Replace(ls_Request, "$COF_Id$", mo_Tools.SQLStr(as_COF_Id), , , vbTextCompare)
  ls_Request = Replace(ls_Request, "$OFD_Id$", mo_Tools.SQLStr(as_OFD_Id), , , vbTextCompare)
  ls_Request = Replace(ls_Request, "$Language_Code$", "'E'", , , vbTextCompare)
  lc_Header = mo_Tools.OpenSQLSafe(mo_Db, ls_Request)
  
  Call SAP_CreateXMLNode("MATERIAL_NO", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "MATERIAL_NO"), lo_XMLDoc, lo_MainNode)
  
  mo_ILO.ILO_MasterId = GetATRValue(lc_CursorXML, lc_Header, "MATERIAL_NO")
  
  ls_UOM = GetATRValue(lc_CursorXML, lc_Header, "BASE_UOM")
  If StrComp(ls_UOM, DPC_UOM_M2, vbTextCompare) = 0 Then
    Call SAP_CreateXMLNode("BASE_UOM_PCS", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "BASE_UOM_PCS"), lo_XMLDoc, lo_MainNode)
  Else
    Call SAP_CreateXMLNode("BASE_UOM", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "BASE_UOM"), lo_XMLDoc, lo_MainNode)
  End If
  Call SAP_CreateXMLNode("NET_WEIGHT", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "NET_WEIGHT"), lo_XMLDoc, lo_MainNode)
  Call SAP_CreateXMLNode("WEIGHT_UOM", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "WEIGHT_UOM"), lo_XMLDoc, lo_MainNode)
  Call SAP_CreateXMLNode("SALES_ORG_CUST_ORD", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "SALES_ORG_CUST_ORD"), lo_XMLDoc, lo_MainNode)
  Call SAP_CreateXMLNode("DIST_CHAN_CUST_ORD", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "DIST_CHAN_CUST_ORD"), lo_XMLDoc, lo_MainNode)
  Call SAP_CreateXMLNode("SALES_ORG_MANUF_LOC", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "SALES_ORG_MANUF_LOC"), lo_XMLDoc, lo_MainNode)
  Call SAP_CreateXMLNode("DIST_CHAN_MANUF_LOC", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "DIST_CHAN_MANUF_LOC"), lo_XMLDoc, lo_MainNode)
  Call SAP_CreateXMLNode("DEL_PLANT_CUST_ORD", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "DEL_PLANT_CUST_ORD"), lo_XMLDoc, lo_MainNode)
  If StrComp(ls_UOM, DPC_UOM_M2, vbTextCompare) = 0 Then
    Call SAP_CreateXMLNode("TRIANG_SO_ICTP_AMT_PCS", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "TRIANG_SO_ICTP_AMT_PCS"), lo_XMLDoc, lo_MainNode)
  Else
    Call SAP_CreateXMLNode("TRIANG_SO_ICTP_AMT", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "TRIANG_SO_ICTP_AMT"), lo_XMLDoc, lo_MainNode)
  End If
  Call SAP_CreateXMLNode("TRIANG_SO_ICTP_CURR", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "TRIANG_SO_ICTP_CURR"), lo_XMLDoc, lo_MainNode)
  Call SAP_CreateXMLNode("TRIANG_SO_ICTP_UNIT", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "TRIANG_SO_ICTP_UNIT"), lo_XMLDoc, lo_MainNode)
  If StrComp(ls_UOM, DPC_UOM_M2, vbTextCompare) = 0 Then
    Call SAP_CreateXMLNode("TRIANG_SO_ICTP_UOM_PCS", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "TRIANG_SO_ICTP_UOM_PCS"), lo_XMLDoc, lo_MainNode)
  Else
    Call SAP_CreateXMLNode("TRIANG_SO_ICTP_UOM", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "TRIANG_SO_ICTP_UOM"), lo_XMLDoc, lo_MainNode)
  End If
    
  'MAT DESCRIPTION
  ls_Request = "exec DPC_SAPMaterialCreateMatDesc_lst $COF_Id$,$OFD_Id$"
  ls_Request = Replace(ls_Request, "$COF_Id$", mo_Tools.SQLStr(as_COF_Id), , , vbTextCompare)
  ls_Request = Replace(ls_Request, "$OFD_Id$", mo_Tools.SQLStr(as_OFD_Id), , , vbTextCompare)
  lc_CursorMaster = mo_Tools.OpenSQLSafe(mo_Db, ls_Request)
    
  If mo_Db.RowCount(lc_CursorMaster) > 0 Then
      Set lo_parentNode = AppendElement(lo_XMLDoc, lo_MainNode, "MATL_DESCRIPTIONS", "")
      
      Call mo_Db.First(lc_CursorMaster)
      
      While Not mo_Db.EOF(lc_CursorMaster)
                          
          ls_ATR_Value = GetATRValue(lc_CursorXML, lc_CursorMaster, "MATL_DESC")
          ls_ATR_DataLength = mo_Db.GetFields(lc_CursorXML, "ATR_DataLength")
                          
          la_StrValues = SplitATRValue(ls_ATR_Value, ls_ATR_DataLength)
          For ll_Index = 0 To UBound(la_StrValues)
            Set lo_SubNode = AppendElement(lo_XMLDoc, lo_parentNode, "MATL_DESC_GROUP", "")
    
            Call SAP_CreateXMLNode("MATL_DESC", lc_CursorXML, la_StrValues(ll_Index), lo_XMLDoc, lo_SubNode)
            Call SAP_CreateXMLNode("MD_LANGU", lc_CursorXML, GetATRValue(lc_CursorXML, lc_CursorMaster, "MD_LANGU"), lo_XMLDoc, lo_SubNode)
          Next
    
          mo_Db.Next (lc_CursorMaster)
      Wend
  End If
  
  mo_Db.Close (lc_CursorMaster)
        
  
  ll_OFD_PU = mo_Db.GetFields(lc_Header, "OFD_PU")

  If (StrComp(ls_UOM, DPC_UOM_M2, vbTextCompare) = 0) Or (StrComp(ls_UOM, DPC_UOM_PCS, vbTextCompare) = 0) Then
    Set lo_parentNode = AppendElement(lo_XMLDoc, lo_MainNode, "ALT_UOMS", "")
    Set lo_SubNode = AppendElement(lo_XMLDoc, lo_parentNode, "ALT_UOM_GROUP", "")
        ll_Nominator = 1000
        ll_Denominator = Round(mo_Db.GetFields(lc_Header, "ModuleSurface") * 1000, 0)
        
        Call SAP_CreateXMLNode("ALT_UOM", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "BASE_UOM_M2"), lo_XMLDoc, lo_SubNode)
        Call SAP_CreateXMLNode("NUMERATOR", lc_CursorXML, ll_Nominator, lo_XMLDoc, lo_SubNode)
        Call SAP_CreateXMLNode("DENOMINATOR", lc_CursorXML, ll_Denominator, lo_XMLDoc, lo_SubNode)
  ElseIf (StrComp(ls_UOM, DPC_UOM_PU, vbTextCompare) = 0) And (ll_OFD_PU > 0) Then
    Set lo_parentNode = AppendElement(lo_XMLDoc, lo_MainNode, "ALT_UOMS", "")
    Set lo_SubNode = AppendElement(lo_XMLDoc, lo_parentNode, "ALT_UOM_GROUP", "")
    ll_Nominator = ll_OFD_PU
    ll_Denominator = 1
    Call SAP_CreateXMLNode("ALT_UOM", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "BASE_UOM_PCS"), lo_XMLDoc, lo_SubNode)
    Call SAP_CreateXMLNode("NUMERATOR", lc_CursorXML, ll_Nominator, lo_XMLDoc, lo_SubNode)
    Call SAP_CreateXMLNode("DENOMINATOR", lc_CursorXML, ll_Denominator, lo_XMLDoc, lo_SubNode)
  End If
  
  'MAT ATTRIBUTES
  ls_Request = "exec DPC_SAPMaterialCreateMatAttr_lst $COF_Id$,$OFD_Id$"
  ls_Request = Replace(ls_Request, "$COF_Id$", mo_Tools.SQLStr(as_COF_Id), , , vbTextCompare)
  ls_Request = Replace(ls_Request, "$OFD_Id$", mo_Tools.SQLStr(as_OFD_Id), , , vbTextCompare)
  lc_CursorMaster = mo_Tools.OpenSQLSafe(mo_Db, ls_Request)
    
  If mo_Db.RowCount(lc_CursorMaster) > 0 Then
      Set lo_parentNode = AppendElement(lo_XMLDoc, lo_MainNode, "MATL_ATTRIBUTES", "")
      
      Call mo_Db.First(lc_CursorMaster)
      
      While Not mo_Db.EOF(lc_CursorMaster)
                    
          ls_ATR_Value = GetATRValue(lc_CursorXML, lc_CursorMaster, "MATL_ATTRIBUTE")
          ls_ATR_DataLength = mo_Db.GetFields(lc_CursorXML, "ATR_DataLength")
                    
          la_StrValues = SplitATRValue(ls_ATR_Value, ls_ATR_DataLength)
          
          For ll_Index = 0 To UBound(la_StrValues)
      
              Set lo_SubNode = AppendElement(lo_XMLDoc, lo_parentNode, "MATL_ATTR_GROUP", "")
          
              Call SAP_CreateXMLNode("MATL_ATTRIBUTE", lc_CursorXML, la_StrValues(ll_Index), lo_XMLDoc, lo_SubNode)
              Call SAP_CreateXMLNode("MA_LANGU", lc_CursorXML, GetATRValue(lc_CursorXML, lc_CursorMaster, "MA_LANGU"), lo_XMLDoc, lo_SubNode)
          Next
    
          mo_Db.Next (lc_CursorMaster)
      Wend
  End If
  
  mo_Db.Close (lc_CursorMaster)
  
  
  'PLANTS
  Set lo_parentNode = AppendElement(lo_XMLDoc, lo_MainNode, "PLANTS", "")
  
  For ll_Index = 1 To 4
    If mo_Db.GetFields(lc_Header, "PLANT_CODE_" & ll_Index) <> "" Or mo_Db.GetFields(lc_Header, "ORIGIN_IND_" & ll_Index) <> "" Or mo_Db.GetFields(lc_Header, "SP_PROC_TYPE_" & ll_Index) <> "" Then
           
        Set lo_SubNode = AppendElement(lo_XMLDoc, lo_parentNode, "PLANT_GROUP", "")
        
        Call SAP_CreateXMLNode("PLANT_CODE", lc_CursorXML, mo_Db.GetFields(lc_Header, "PLANT_CODE_" & ll_Index), lo_XMLDoc, lo_SubNode)
        Call SAP_CreateXMLNode("ORIGIN_IND", lc_CursorXML, mo_Db.GetFields(lc_Header, "ORIGIN_IND_" & ll_Index), lo_XMLDoc, lo_SubNode)
        Call SAP_CreateXMLNode("SP_PROC_TYPE", lc_CursorXML, mo_Db.GetFields(lc_Header, "SP_PROC_TYPE_" & ll_Index), lo_XMLDoc, lo_SubNode)
        Call SAP_CreateXMLNode("COMM_CODE", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "COMM_CODE"), lo_XMLDoc, lo_SubNode)
        Call SAP_CreateXMLNode("COUNTRY_ORI", lc_CursorXML, mo_Db.GetFields(lc_Header, "VEN_CountryOrigin"), lo_XMLDoc, lo_SubNode)
                
        If StrComp(ls_UOM, DPC_UOM_M2, vbTextCompare) = 0 Then
          ld_Cost = GetATRValue(lc_CursorXML, lc_Header, "STD_COST_PCS")
        Else
          ld_Cost = GetATRValue(lc_CursorXML, lc_Header, "STD_COST")
        End If
        
        ls_OFD_CurrCode = mo_Db.GetFields(lc_Header, "CURR_CODE")
        ls_RequiredCurrCode = mo_Db.GetFields(lc_Header, "CURR_CODE_" & ll_Index)
        
        If ls_OFD_CurrCode <> ls_RequiredCurrCode Then
            ld_ExRate = mo_Tools.SelectExchangeRate(mo_Db, ls_OFD_CurrCode, ls_RequiredCurrCode, mo_Db.GetFields(lc_Header, "COF_DocDat"))
            ld_Cost = ld_Cost * ld_ExRate
        End If
                
        If StrComp(ls_UOM, DPC_UOM_M2, vbTextCompare) = 0 Then
          Call SAP_CreateXMLNode("STD_COST_PCS", lc_CursorXML, ld_Cost, lo_XMLDoc, lo_SubNode)
        Else
          Call SAP_CreateXMLNode("STD_COST", lc_CursorXML, ld_Cost, lo_XMLDoc, lo_SubNode)
        End If
                
        Call SAP_CreateXMLNode("COST_UNIT", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "COST_UNIT"), lo_XMLDoc, lo_SubNode)
        
        If StrComp(ls_UOM, DPC_UOM_M2, vbTextCompare) = 0 Then
          Call SAP_CreateXMLNode("STK_TRANS_ICTP_AMT_PCS", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "STK_TRANS_ICTP_AMT_PCS"), lo_XMLDoc, lo_SubNode)
        Else
          Call SAP_CreateXMLNode("STK_TRANS_ICTP_AMT", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "STK_TRANS_ICTP_AMT"), lo_XMLDoc, lo_SubNode)
        End If
        Call SAP_CreateXMLNode("STK_TRANS_ICTP_CURR", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "STK_TRANS_ICTP_CURR"), lo_XMLDoc, lo_SubNode)
        Call SAP_CreateXMLNode("STK_TRANS_ICTP_UNIT", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "STK_TRANS_ICTP_UNIT"), lo_XMLDoc, lo_SubNode)
        If StrComp(ls_UOM, DPC_UOM_M2, vbTextCompare) = 0 Then
          Call SAP_CreateXMLNode("STK_TRANS_ICTP_UOM_PCS", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "STK_TRANS_ICTP_UOM_PCS"), lo_XMLDoc, lo_SubNode)
        Else
          Call SAP_CreateXMLNode("STK_TRANS_ICTP_UOM", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "STK_TRANS_ICTP_UOM"), lo_XMLDoc, lo_SubNode)
        End If
    End If
  Next
  Call mo_Db.Close(lc_Header)
  Call mo_Db.Close(lc_CursorXML)
  
  Set lo_SubNode = Nothing
  Set lo_parentNode = Nothing
  Set lo_MainNode = Nothing
  
#If LIVE = 0 Then
  SAP_MaterialCreateGetXML = SAP_SaveXMLDocument(lo_XMLDoc, "AMC_MaterialCreate", "SAPAMCMaterialCreate", False)
  Exit Function
#Else
  SAP_MaterialCreateGetXML = SAP_SaveXMLDocument(lo_XMLDoc, "AMC_MaterialCreate", "SAPAMCMaterialCreate")
#End If
  
  Exit Function
errorHandler:
  
  If lc_CursorMaster <> 0 Then
    mo_Db.Close (lc_CursorMaster)
  End If
  
  If lc_CursorXML <> 0 Then
    mo_Db.Close (lc_CursorXML)
  End If

  Set lo_SubNode = Nothing
  Set lo_parentNode = Nothing
  Set lo_MainNode = Nothing

  Call LogInterface(mo_Db, ml_U_Code)
  
  Call errorHandler("SAP_MaterialCreateGetXML")
End Function

Public Function SAP_SalesOrderCreate(ByVal as_COF_Id As String, ByVal as_ActionCode As String, ByRef as_ErrorMsg As String) As String
On Error GoTo errorHandler

Dim ls_Xml As String
Dim ls_Response As String
Dim lb_Simulate As Boolean

        SAP_SalesOrderCreate = False
        lb_Simulate = as_ActionCode = "T"
        ls_Xml = SAP_SalesOrderCreateGetXML(as_COF_Id, as_ActionCode)
        
        If (SendRequest(DPC_SAP_SALESORDER_CREATE, "POST", ls_Xml, ls_Response) = True) Then
            
            'ls_Response = "<?xml version=""1.0"" encoding=""UTF-8""?><AMC_SALES_ORD_CREATE_CHG_RESPONSE><SUCC_FAIL_IND>F</SUCC_FAIL_IND><EPC_ORD_NO>00536.A</EPC_ORD_NO>" & _
            '    "<ERRORS><ERROR_GROUP><SEVERITY_TYPE>E</SEVERITY_TYPE><MSG_CLASS>VP</MSG_CLASS><MSG_NO>200</MSG_NO><MSG_TEXT>No customer master record exists for customer 207691</MSG_TEXT>" & _
            '    "<MSG_PARAMETER>SALES_HEADER_IN</MSG_PARAMETER><MSG_PARM_ROW/></ERROR_GROUP></ERRORS></AMC_SALES_ORD_CREATE_CHG_RESPONSE>"
          If (SAP_SalesOrderCreateProcessResponse(ls_Response, as_ErrorMsg, lb_Simulate) = True) Then
              SAP_SalesOrderCreate = True
          End If
          If Not lb_Simulate Then
            Call LogInterface(mo_Db, ml_U_Code)
          End If
        Else
            as_ErrorMsg = ls_Response
        End If
        
  Exit Function
errorHandler:
  
  Call LogInterface(mo_Db, ml_U_Code)
  
  Call errorHandler("SAP_SalesOrderCreate")
End Function

Public Function SAP_SalesOrderCreateGetXML(ByVal as_COF_Id As String, ByVal as_ActionCode As String) As String
On Error GoTo errorHandler

Dim lo_XmlDocCust As Object
'Dim ll_Version As Long
Dim lo_SubNode As Object
Dim lo_SubSubNode As Object
Dim lo_SubSubSubNode As Object
Dim lo_parentNode As Object
Dim lo_MainNode As Object
Dim lc_CursorXML As Long
Dim lc_CursorGroup As Long
Dim lc_Header As Long
Dim lc_Lines As Long
Dim lt_XmlSql As TXmlSql
Dim lt_XmlMaster As TXmlSql
Dim lo_XMLDoc As MSXML2.DOMDocument
Dim ls_Request As String
Dim ls_ATR_Value As String
Dim ls_ATR_DataLength As Long
Dim la_StrValues() As String
Dim ll_Index As Integer
Dim ld_DelDate As Date
Dim ls_UOM As String
Dim le_CAT_Id As eDPCCategory

  Call ClearLogInterface
  mo_ILO.ILO_Interface = eDPCXmlExportType.etSAP_SalesOrderCreate
  mo_ILO.ILO_MasterId = as_COF_Id
  
  Set lo_XMLDoc = CreateObject("MSXML2.DOMDocument")
  
  lc_CursorXML = SAP_GetXmlCursor(eDPCXmlExportType.etSAP_SalesOrderCreate)
    
  Set lo_MainNode = lo_XMLDoc.createProcessingInstruction("xml", "version='1.0' encoding='utf-8'")
  lo_XMLDoc.appendChild lo_MainNode
    
  Set lo_MainNode = AppendElement(lo_XMLDoc, Nothing, "AMC_SALES_ORD_CREATE_SIMU", "")
  lo_MainNode.appendChild lo_XMLDoc.createTextNode(vbNewLine + vbTab)
      
  ls_Request = "exec DPC_SAPSalesOrderCreateHeader_sel $COF_Id$,$Language_Code$"
  ls_Request = Replace(ls_Request, "$COF_Id$", mo_Tools.SQLStr(as_COF_Id), , , vbTextCompare)
  ls_Request = Replace(ls_Request, "$Language_Code$", "'E'", , , vbTextCompare)
  lc_Header = mo_Tools.OpenSQLSafe(mo_Db, ls_Request)
  
  ls_Request = "exec DPC_SAPSalesOrderCreateLines_lst $COF_Id$,'E'"
  ls_Request = Replace(ls_Request, "$COF_Id$", mo_Tools.SQLStr(as_COF_Id), , , vbTextCompare)
  lc_Lines = mo_Tools.OpenSQLSafe(mo_Db, ls_Request)
  ld_DelDate = mo_Db.GetFields(lc_Lines, "OFD_DelDat")
  Do While Not mo_Db.EOF(lc_Lines)
    If ld_DelDate <> mo_Db.GetFields(lc_Lines, "OFD_DelDat") Then
      ld_DelDate = 0
      Exit Do
    End If
    Call mo_Db.Next(lc_Lines)
  Loop
  
  
  Call mo_Db.First(lc_Header)
        
  Call SAP_CreateXMLNode("ACTION_CODE", lc_CursorXML, as_ActionCode, lo_XMLDoc, lo_MainNode)
  Call SAP_CreateXMLNode("SALES_ORG", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "SALES_ORG"), lo_XMLDoc, lo_MainNode)
  Call SAP_CreateXMLNode("DISTR_CHAN", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "DISTR_CHAN"), lo_XMLDoc, lo_MainNode)
  Call SAP_CreateXMLNode("SOLDTO_CUST_NO", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "SOLDTO_CUST_NO"), lo_XMLDoc, lo_MainNode)
  Call SAP_CreateXMLNode("CONTACT_NAME", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "CONTACT_NAME"), lo_XMLDoc, lo_MainNode)
  Call SAP_CreateXMLNode("CUST_PO_NO", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "CUST_PO_NO"), lo_XMLDoc, lo_MainNode)
  Call SAP_CreateXMLNode("CUST_PO_DATE", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "CUST_PO_DATE"), lo_XMLDoc, lo_MainNode)
  Call SAP_CreateXMLNode("PROJ_ID_KEY", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "PROJ_ID_KEY"), lo_XMLDoc, lo_MainNode)
  Call SAP_CreateXMLNode("AMC_PROJ_NO", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "AMC_PROJ_NO"), lo_XMLDoc, lo_MainNode)
  Call SAP_CreateXMLNode("PROJ_ID_DESC", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "PROJ_ID_DESC"), lo_XMLDoc, lo_MainNode)
  Call SAP_CreateXMLNode("EPC_OFFER_NO", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "EPC_OFFER_NO"), lo_XMLDoc, lo_MainNode)
  Call SAP_CreateXMLNode("EPC_OFFER_VERS_NO", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "EPC_OFFER_VERS_NO"), lo_XMLDoc, lo_MainNode)
  Call SAP_CreateXMLNode("EPC_ORD_NO", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "EPC_ORD_NO"), lo_XMLDoc, lo_MainNode)
  Call SAP_CreateXMLNode("EPC_ORD_VERS_NO", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "EPC_ORD_VERS_NO"), lo_XMLDoc, lo_MainNode)
  Call SAP_CreateXMLNode("HDR_REQ_DEL_DATE", lc_CursorXML, ld_DelDate, lo_XMLDoc, lo_MainNode)
  
  'DELIV ADDRESS
  ls_ATR_Value = GetATRValue(lc_CursorXML, lc_Header, "DA_NAME")
  ls_ATR_DataLength = mo_Db.GetFields(lc_CursorXML, "ATR_DataLength")
  
  If Len(ls_ATR_Value) > 0 Then
    Set lo_parentNode = AppendElement(lo_XMLDoc, lo_MainNode, "DELIV_ADDRESS", "")
                
    la_StrValues = SplitATRValue(ls_ATR_Value, ls_ATR_DataLength)
      
    If UBound(la_StrValues) = 0 Then
        Call SAP_CreateXMLNode("DA_NAME", lc_CursorXML, la_StrValues(0), lo_XMLDoc, lo_parentNode)
    
        ls_ATR_Value = GetATRValue(lc_CursorXML, lc_Header, "DA_NAME2")
        ls_ATR_DataLength = mo_Db.GetFields(lc_CursorXML, "ATR_DataLength")
                
        la_StrValues = SplitATRValue(ls_ATR_Value, ls_ATR_DataLength)
        Call SAP_CreateXMLNode("DA_NAME2", lc_CursorXML, la_StrValues(0), lo_XMLDoc, lo_parentNode)
        
        If UBound(la_StrValues) = 1 Then
            Call SAP_CreateXMLNode("DA_NAME3", lc_CursorXML, la_StrValues(0), lo_XMLDoc, lo_parentNode)
        End If
    Else
        Call SAP_CreateXMLNode("DA_NAME", lc_CursorXML, la_StrValues(0), lo_XMLDoc, lo_parentNode)
        Call SAP_CreateXMLNode("DA_NAME2", lc_CursorXML, la_StrValues(1), lo_XMLDoc, lo_parentNode)
    
        ls_ATR_Value = GetATRValue(lc_CursorXML, lc_Header, "DA_NAME2")
        ls_ATR_DataLength = mo_Db.GetFields(lc_CursorXML, "ATR_DataLength")
                
        la_StrValues = SplitATRValue(ls_ATR_Value, ls_ATR_DataLength)
        
        Call SAP_CreateXMLNode("DA_NAME3", lc_CursorXML, la_StrValues(0), lo_XMLDoc, lo_parentNode)
        
        If UBound(la_StrValues) = 1 Then
            Call SAP_CreateXMLNode("DA_NAME4", lc_CursorXML, la_StrValues(0), lo_XMLDoc, lo_parentNode)
        End If
    End If
    
              
    Call SAP_CreateXMLNode("DA_STREET", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "DA_STREET"), lo_XMLDoc, lo_parentNode)
    Call SAP_CreateXMLNode("DA_CITY", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "DA_CITY"), lo_XMLDoc, lo_parentNode)
    Call SAP_CreateXMLNode("DA_REGION", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "DA_REGION"), lo_XMLDoc, lo_parentNode)
    Call SAP_CreateXMLNode("DA_POSTL_CODE", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "DA_POSTL_CODE"), lo_XMLDoc, lo_parentNode)
    Call SAP_CreateXMLNode("DA_COUNTRY", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "DA_COUNTRY"), lo_XMLDoc, lo_parentNode)
  
  End If
  
  'HDR_TEXTS
  If Len(GetATRValue(lc_CursorXML, lc_Header, "TEXT_LINE1")) > 0 Or Len(GetATRValue(lc_CursorXML, lc_Header, "TEXT_LINE2")) > 0 Then
                  
    Set lo_parentNode = AppendElement(lo_XMLDoc, lo_MainNode, "HDR_TEXTS", "")
                  
    ls_ATR_Value = GetATRValue(lc_CursorXML, lc_Header, "TEXT_LINE1")
    ls_ATR_DataLength = mo_Db.GetFields(lc_CursorXML, "ATR_DataLength")
  
    If Len(ls_ATR_Value) > 0 Then
        Set lo_SubNode = AppendElement(lo_XMLDoc, lo_parentNode, "HDR_TEXT_GROUP", "")
                
        Call SAP_CreateXMLNode("TEXT_ID1", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "TEXT_ID1"), lo_XMLDoc, lo_SubNode)
        Call SAP_CreateXMLNode("TEXT_LANGU", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "TEXT_LANGU"), lo_XMLDoc, lo_SubNode)
             
        Set lo_SubSubNode = AppendElement(lo_XMLDoc, lo_SubNode, "TEXT_LINES", "")
                
        la_StrValues = SplitATRValue(ls_ATR_Value, ls_ATR_DataLength)
        
        For ll_Index = 0 To UBound(la_StrValues)
            Call SAP_CreateXMLNode("TEXT_LINE1", lc_CursorXML, la_StrValues(ll_Index), lo_XMLDoc, lo_SubSubNode)
        Next
        
        'Call SAP_CreateXMLNode("TEXT_LINE1", lc_CursorXML, ls_ATR_Value, lo_XMLDoc, lo_SubSubNode)
    End If
    
    ls_ATR_Value = GetATRValue(lc_CursorXML, lc_Header, "TEXT_LINE2")
    ls_ATR_DataLength = mo_Db.GetFields(lc_CursorXML, "ATR_DataLength")
  
    If Len(ls_ATR_Value) > 0 Then
        Set lo_SubNode = AppendElement(lo_XMLDoc, lo_parentNode, "HDR_TEXT_GROUP", "")
                
        Call SAP_CreateXMLNode("TEXT_ID2", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "TEXT_ID2"), lo_XMLDoc, lo_SubNode)
        Call SAP_CreateXMLNode("TEXT_LANGU", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "TEXT_LANGU"), lo_XMLDoc, lo_SubNode)
             
        Set lo_SubSubNode = AppendElement(lo_XMLDoc, lo_SubNode, "TEXT_LINES", "")
                
        la_StrValues = SplitATRValue(ls_ATR_Value, ls_ATR_DataLength)
        
        For ll_Index = 0 To UBound(la_StrValues)
            Call SAP_CreateXMLNode("TEXT_LINE2", lc_CursorXML, la_StrValues(ll_Index), lo_XMLDoc, lo_SubSubNode)
        Next
        
        'Call SAP_CreateXMLNode("TEXT_LINE2", lc_CursorXML, ls_ATR_Value, lo_XMLDoc, lo_SubSubNode)
    End If
  End If
      
  'LINES
  If mo_Db.RowCount(lc_Lines) > 0 Then
      
    Set lo_parentNode = AppendElement(lo_XMLDoc, lo_MainNode, "LINES", "")
      
    Call mo_Db.First(lc_Lines)
    
    While Not mo_Db.EOF(lc_Lines)
      
      ls_UOM = GetATRValue(lc_CursorXML, lc_Lines, "SALES_UOM")
      le_CAT_Id = mo_Db.GetFields(lc_Lines, "CAT_Id")
      
      Set lo_SubNode = AppendElement(lo_XMLDoc, lo_parentNode, "LINE_GROUP", "")
      Call SAP_CreateXMLNode("MATERIAL_NO", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Lines, "MATERIAL_NO"), lo_XMLDoc, lo_SubNode)
      Call SAP_CreateXMLNode("EPC_ORD_LINE_POS", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Lines, "EPC_ORD_LINE_POS"), lo_XMLDoc, lo_SubNode)
      Call SAP_CreateXMLNode("FREE_OF_CHARGE_IND", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Lines, "FREE_OF_CHARGE_IND"), lo_XMLDoc, lo_SubNode)
      Call SAP_CreateXMLNode("MFG_PRE_RESERV_NO", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Lines, "MFG_PRE_RESERV_NO"), lo_XMLDoc, lo_SubNode)
      Call SAP_CreateXMLNode("MFG_PRE_RESERV_LIN_POS", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Lines, "MFG_PRE_RESERV_LIN_POS"), lo_XMLDoc, lo_SubNode)
      Call SAP_CreateXMLNode("CUST_POSITION", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Lines, "CUST_POSITION"), lo_XMLDoc, lo_SubNode)
      If (le_CAT_Id = eDPCCategory.cgMetalCustomRectPanel) And (StrComp(ls_UOM, DPC_UOM_M2, vbTextCompare) = 0) Then
        Call SAP_CreateXMLNode("SALES_QTY_PCS", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Lines, "SALES_QTY_PCS"), lo_XMLDoc, lo_SubNode)
        Call SAP_CreateXMLNode("SALES_UOM_PCS", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Lines, "SALES_UOM_PCS"), lo_XMLDoc, lo_SubNode)
        Call SAP_CreateXMLNode("LINE_PRICE_AMT_PCS", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Lines, "LINE_PRICE_AMT_PCS"), lo_XMLDoc, lo_SubNode)
      Else
        Call SAP_CreateXMLNode("SALES_QTY", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Lines, "SALES_QTY"), lo_XMLDoc, lo_SubNode)
        Call SAP_CreateXMLNode("SALES_UOM", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Lines, "SALES_UOM"), lo_XMLDoc, lo_SubNode)
        Call SAP_CreateXMLNode("LINE_PRICE_AMT", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Lines, "LINE_PRICE_AMT"), lo_XMLDoc, lo_SubNode)
      End If
      
      Call SAP_CreateXMLNode("LINE_PRICE_CURR", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Lines, "LINE_PRICE_CURR"), lo_XMLDoc, lo_SubNode)
      Call SAP_CreateXMLNode("LINE_PRICE_UNIT", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Lines, "LINE_PRICE_UNIT"), lo_XMLDoc, lo_SubNode)
      If (le_CAT_Id = eDPCCategory.cgMetalCustomRectPanel) And (StrComp(ls_UOM, DPC_UOM_M2, vbTextCompare) = 0) Then
        Call SAP_CreateXMLNode("LINE_PRICE_UOM_PCS", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Lines, "LINE_PRICE_UOM_PCS"), lo_XMLDoc, lo_SubNode)
      Else
        Call SAP_CreateXMLNode("LINE_PRICE_UOM", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Lines, "LINE_PRICE_UOM"), lo_XMLDoc, lo_SubNode)
      End If
      Call SAP_CreateXMLNode("SHIPPING_PLANT", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Lines, "SHIPPING_PLANT"), lo_XMLDoc, lo_SubNode)
      Call SAP_CreateXMLNode("ITM_REQ_DEL_DATE", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Lines, "ITM_REQ_DEL_DATE"), lo_XMLDoc, lo_SubNode)

      
      ls_ATR_Value = GetATRValue(lc_CursorXML, lc_Lines, "TEXT_LINE")
      ls_ATR_DataLength = mo_Db.GetFields(lc_CursorXML, "ATR_DataLength")

      If Len(ls_ATR_Value) > 0 Then
        Set lo_SubNode = AppendElement(lo_XMLDoc, lo_SubNode, "ITM_TEXTS", "")
            
        Set lo_SubSubNode = AppendElement(lo_XMLDoc, lo_SubNode, "ITM_TEXT_GROUP", "")
            
        Call SAP_CreateXMLNode("TEXT_ID", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Lines, "TEXT_ID"), lo_XMLDoc, lo_SubSubNode)
        Call SAP_CreateXMLNode("TEXT_LANGU", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Lines, "TEXT_LANGU"), lo_XMLDoc, lo_SubSubNode)
            
        Set lo_SubSubSubNode = AppendElement(lo_XMLDoc, lo_SubSubNode, "TEXT_LINES", "")
                                
        la_StrValues = SplitATRValue(ls_ATR_Value, ls_ATR_DataLength)
        
        For ll_Index = 0 To UBound(la_StrValues)
            Call SAP_CreateXMLNode("TEXT_LINE", lc_CursorXML, la_StrValues(ll_Index), lo_XMLDoc, lo_SubSubSubNode)
        Next
      End If

      mo_Db.Next (lc_Lines)
    Wend
  End If
  
  Call mo_Db.Close(lc_Lines)
  Call mo_Db.Close(lc_Header)
 
  Call mo_Db.Close(lc_CursorXML)
  
  Set lo_SubSubNode = Nothing
  Set lo_SubNode = Nothing
  Set lo_parentNode = Nothing
  Set lo_MainNode = Nothing
  
#If LIVE = 0 Then
  SAP_SalesOrderCreateGetXML = SAP_SaveXMLDocument(lo_XMLDoc, "AMC_SalesOrderCreate", "SAPAMCSalesOrderCreate", False)
  Exit Function
#Else
  SAP_SalesOrderCreateGetXML = SAP_SaveXMLDocument(lo_XMLDoc, "AMC_SalesOrderCreate", "SAPAMCSalesOrderCreate")
#End If
  
  Exit Function
errorHandler:
  
  If lc_Lines <> 0 Then
    mo_Db.Close (lc_Lines)
  End If
  
  If lc_CursorXML <> 0 Then
    mo_Db.Close (lc_CursorXML)
  End If

  Set lo_SubSubNode = Nothing
  Set lo_SubNode = Nothing
  Set lo_parentNode = Nothing
  Set lo_MainNode = Nothing

  Call LogInterface(mo_Db, ml_U_Code)
  
  Call errorHandler("SAP_SalesOrderCreateGetXML")
End Function

Public Function Bae_SalesOrderExport(ByVal as_COF_Id As String, ByRef as_ErrorMsg As String) As Boolean
On Error GoTo errorHandler

Dim lc_Cursor As Long
Dim ls_Req As String
Dim le_ZipExport As eDPCBaeurerZipExport
Dim lsa_Zip2Countries() As String
Dim ll_Idx As Long

  Bae_SalesOrderExport = False
  ls_Req = "exec Cap_Offer_sel $COF_Id$, $Language_Code$"
  ls_Req = Replace(ls_Req, "$COF_Id$", mo_Tools.SQLStr(as_COF_Id), , , vbTextCompare)
  ls_Req = ReplaceCommonPlaceholders(ls_Req)
  lc_Cursor = mo_Tools.OpenSQLSafe(mo_Db, ls_Req)
    
  If Bae_CheckExistCustPurchOrderNumber(mo_Db.GetFields(lc_Cursor, "COF_CodeCus"), Val(mo_Db.GetFields(lc_Cursor, "LEN_BaeKonto"))) Then
    as_ErrorMsg = "Current customer purchase order number already exists in B7"
    Call mo_Db.Close(lc_Cursor)
    Exit Function
  End If
  
  le_ZipExport = eDPCBaeurerZipExport.zeZip
  lsa_Zip2Countries = Split(mo_Tools.GetAConfigData("DPC_BAE_ZIP2_SLSORD"), SEP)
  For ll_Idx = 0 To UBound(lsa_Zip2Countries)
    If StrComp(mo_Db.GetFields(lc_Cursor, "SP_CT_Code"), lsa_Zip2Countries(ll_Idx), vbTextCompare) = 0 Then
      le_ZipExport = eDPCBaeurerZipExport.zeZip2
      Exit For
    End If
  Next
  
  Call mo_Db.Close(lc_Cursor)
  Bae_SalesOrderExport = Bae_SalesOrderCreate(as_COF_Id, "A", le_ZipExport, as_ErrorMsg)
  Exit Function
errorHandler:
  Call errorHandler("Bae_SalesOrderExport")
End Function

Public Function Bae_SalesOrderKill(ByVal as_COF_Id As String, ByRef as_ErrorMsg As String) As Boolean
On Error GoTo errorHandler

Dim lc_Cursor As Long
Dim ls_Req As String
Dim le_ZipExport As eDPCBaeurerZipExport
Dim lsa_Zip2Countries() As String
Dim ll_Idx As Long

  Bae_SalesOrderKill = False
  ls_Req = "exec Cap_Offer_sel $COF_Id$, $Language_Code$"
  ls_Req = Replace(ls_Req, "$COF_Id$", mo_Tools.SQLStr(as_COF_Id), , , vbTextCompare)
  ls_Req = ReplaceCommonPlaceholders(ls_Req)
  lc_Cursor = mo_Tools.OpenSQLSafe(mo_Db, ls_Req)
  
  le_ZipExport = eDPCBaeurerZipExport.zeZip
  lsa_Zip2Countries = Split(mo_Tools.GetAConfigData("DPC_BAE_ZIP2_SLSORD"), SEP)
  For ll_Idx = 0 To UBound(lsa_Zip2Countries)
    If StrComp(mo_Db.GetFields(lc_Cursor, "SP_CT_Code"), lsa_Zip2Countries(ll_Idx), vbTextCompare) = 0 Then
      le_ZipExport = eDPCBaeurerZipExport.zeZip2
      Exit For
    End If
  Next
  
  Call mo_Db.Close(lc_Cursor)
  If Bae_SalesOrderCreate(as_COF_Id, "K", le_ZipExport, as_ErrorMsg) Then
    Call Bae_UpdateOfferCode(as_COF_Id, "")
    Call Bae_ClearOfferDetailCodePos(as_COF_Id)
    Bae_SalesOrderKill = True
  End If
  Exit Function
errorHandler:
  Call errorHandler("Bae_SalesOrderKill")
End Function

Private Function Bae_SalesOrderCreate(ByVal as_COF_Id As String, ByVal as_ActionCode As String, ByVal ae_ZipExport As eDPCBaeurerZipExport, ByRef as_ErrorMsg As String) As String
On Error GoTo errorHandler

Dim ls_Xml As String
Dim ls_Response As String
Dim ls_Filename As String

  Bae_SalesOrderCreate = False
  
  ls_Filename = Bae_SalesOrderCreateGetXML(as_COF_Id, as_ActionCode, ae_ZipExport)
  
  Bae_SalesOrderCreate = TransferXMLDocument(ls_Filename, as_ErrorMsg)
  
  'If (SendRequest(DPC_SAP_SALESORDER_CREATE, "POST", ls_Xml, ls_Response) = True) Then
      
      'ls_Response = "<?xml version=""1.0"" encoding=""UTF-8""?><AMC_SALES_ORD_CREATE_CHG_RElSPONSE><SUCC_FAIL_IND>F</SUCC_FAIL_IND><EPC_ORD_NO>00536.A</EPC_ORD_NO>" & _
      '    "<ERRORS><ERROR_GROUP><SEVERITY_TYPE>E</SEVERITY_TYPE><MSG_CLASS>VP</MSG_CLASS><MSG_NO>200</MSG_NO><MSG_TEXT>No customer master record exists for customer 207691</MSG_TEXT>" & _
      '    "<MSG_PARAMETER>SALES_HEADER_IN</MSG_PARAMETER><MSG_PARM_ROW/></ERROR_GROUP></ERRORS></AMC_SALES_ORD_CREATE_CHG_RESPONSE>"
     
      'If (SalesOrderCreateProcessResponse(ls_Response, as_ErrorMsg) = True) Then
      '    SalesOrderCreate = True
      'End If
      
      'Call mo_Tools.LogInterface(mo_Db, ml_U_Code, Me)
      
  'Else
      'as_ErrorMsg = ls_Response
  'End If
  Exit Function
errorHandler:
  
  Call LogInterface(mo_Db, ml_U_Code)
  
  Call errorHandler("Bae_SalesOrderCreate")
End Function

Public Function Bae_SalesOrderCreateGetXML(ByVal as_COF_Id As String, ByVal as_ActionCode As String, ByVal ae_ZipExport As eDPCBaeurerZipExport) As String
On Error GoTo errorHandler

Dim lo_XmlDocCust As Object
'Dim ll_Version As Long
Dim lo_SubNode As Object
Dim lo_SubSubNode As Object
Dim lo_SubSubSubNode As Object
Dim lo_parentNode As Object
Dim lo_MainNode As Object
Dim lc_CursorXML As Long
Dim lc_CursorGroup As Long
Dim lc_Header As Long
Dim lc_Lines As Long
Dim lt_XmlSql As TXmlSql
Dim lt_XmlMaster As TXmlSql
Dim lo_XMLDoc As MSXML2.DOMDocument
Dim ls_Request As String
Dim ls_ATR_Value As String
Dim ll_ATR_DataLength As Long
Dim la_StrValues() As String
Dim ll_Index As Integer
Dim ld_DelDate As Date
Dim ls_UOM As String
Dim le_CAT_Id As eDPCCategory
Dim ll_Count As Long
Dim ls_Filename As String

  Call ClearLogInterface
  mo_ILO.ILO_Interface = eDPCXmlExportType.etBae_SalesOrderCreate
  mo_ILO.ILO_MasterId = as_COF_Id
  
  Set lo_XMLDoc = CreateObject("MSXML2.DOMDocument")
  
  lc_CursorXML = Bae_GetXmlCursor(eDPCXmlExportType.etBae_SalesOrderCreate)
  Set lo_MainNode = lo_XMLDoc.createProcessingInstruction("xml", "version='1.0' encoding='utf-8'")
  lo_XMLDoc.appendChild lo_MainNode
    
    
  Set lo_MainNode = AppendElement(lo_XMLDoc, Nothing, "AMC_SO_DEMAND_CREATE_CHANGE", "")
  lo_MainNode.appendChild lo_XMLDoc.createTextNode(vbNewLine + vbTab)
      
  ls_Request = "exec DPC_BaeSalesOrderCreateHeader_sel $COF_Id$,$Language_Code$,$ZipExport$"
  ls_Request = Replace(ls_Request, "$COF_Id$", mo_Tools.SQLStr(as_COF_Id), , , vbTextCompare)
  ls_Request = Replace(ls_Request, "$ZipExport$", mo_Tools.SqlInt(ae_ZipExport), , , vbTextCompare)
  ls_Request = Replace(ls_Request, "$Language_Code$", "'E'", , , vbTextCompare)
  lc_Header = mo_Tools.OpenSQLSafe(mo_Db, ls_Request)
  
  ls_Request = "exec DPC_BaeSalesOrderCreateLines_lst $COF_Id$,'E'"
  ls_Request = Replace(ls_Request, "$COF_Id$", mo_Tools.SQLStr(as_COF_Id), , , vbTextCompare)
  lc_Lines = mo_Tools.OpenSQLSafe(mo_Db, ls_Request)
  ld_DelDate = mo_Db.GetFields(lc_Lines, "OFD_DelDat")
  Do While Not mo_Db.EOF(lc_Lines)
    If ld_DelDate <> mo_Db.GetFields(lc_Lines, "OFD_DelDat") Then
      ld_DelDate = 0
      Exit Do
    End If
    Call mo_Db.Next(lc_Lines)
  Loop
  
  
  Call mo_Db.First(lc_Header)
        
  'Call SAP_CreateXMLNode("ACTION_CODE",mo_Db, lc_CursorXML, as_ActionCode, lo_XMLDoc, lo_MainNode)
  Call SAP_CreateXMLNode("COMP_CODE", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "COMP_CODE"), lo_XMLDoc, lo_MainNode)
  Call SAP_CreateXMLNode("EPC_ORD_NO", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "EPC_ORD_NO"), lo_XMLDoc, lo_MainNode)
  Call SAP_CreateXMLNode("SALES_ORG", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "SALES_ORG"), lo_XMLDoc, lo_MainNode)
  Call SAP_CreateXMLNode("DISTR_CHAN", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "DISTR_CHAN"), lo_XMLDoc, lo_MainNode)
  Call SAP_CreateXMLNode("SOLDTO_CUST_NO", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "SOLDTO_CUST_NO"), lo_XMLDoc, lo_MainNode)
  Call SAP_CreateXMLNode("CLIENT_ID", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "CLIENT_ID"), lo_XMLDoc, lo_MainNode)
  Call SAP_CreateXMLNode("CONTACT_NAME", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "CONTACT_NAME"), lo_XMLDoc, lo_MainNode)
  Call SAP_CreateXMLNode("CUST_PO_NO", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "CUST_PO_NO"), lo_XMLDoc, lo_MainNode)
  Call SAP_CreateXMLNode("CUST_PO_DATE", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "CUST_PO_DATE"), lo_XMLDoc, lo_MainNode)
  Call SAP_CreateXMLNode("PROJ_ID_KEY", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "PROJ_ID_KEY"), lo_XMLDoc, lo_MainNode)
  Call SAP_CreateXMLNode("AMC_PROJ_NO", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "AMC_PROJ_NO"), lo_XMLDoc, lo_MainNode)
  Call SAP_CreateXMLNode("PROJ_ID_DESC", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "PROJ_ID_DESC"), lo_XMLDoc, lo_MainNode)
  Call SAP_CreateXMLNode("EPC_OFFER_NO", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "EPC_OFFER_NO"), lo_XMLDoc, lo_MainNode)
  Call SAP_CreateXMLNode("EPC_OFFER_VERS_NO", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "EPC_OFFER_VERS_NO"), lo_XMLDoc, lo_MainNode)
  'Call SAP_CreateXMLNode("EPC_ORD_VERS_NO", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "EPC_ORD_VERS_NO"), lo_XMLDoc, lo_MainNode)
  Call SAP_CreateXMLNode("HDR_REQ_DEL_DATE", lc_CursorXML, ld_DelDate, lo_XMLDoc, lo_MainNode)
  Call SAP_CreateXMLNode("VERP_ART", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "VERP_ART"), lo_XMLDoc, lo_MainNode)
  
  'customer - sales project address
  ls_ATR_Value = GetATRValue(lc_CursorXML, lc_Header, "CA_NAME")
  ll_ATR_DataLength = mo_Db.GetFields(lc_CursorXML, "ATR_DataLength")
  la_StrValues = SplitATRValue(ls_ATR_Value, ll_ATR_DataLength)
    
  If UBound(la_StrValues) = 0 Then
      Call SAP_CreateXMLNode("CA_NAME", lc_CursorXML, la_StrValues(0), lo_XMLDoc, lo_MainNode)
  
      ls_ATR_Value = GetATRValue(lc_CursorXML, lc_Header, "CA_NAME2")
      ll_ATR_DataLength = mo_Db.GetFields(lc_CursorXML, "ATR_DataLength")
              
      la_StrValues = SplitATRValue(ls_ATR_Value, ll_ATR_DataLength)
      Call SAP_CreateXMLNode("CA_NAME2", lc_CursorXML, la_StrValues(0), lo_XMLDoc, lo_MainNode)
      
      If UBound(la_StrValues) = 1 Then
          Call SAP_CreateXMLNode("CA_NAME3", lc_CursorXML, la_StrValues(1), lo_XMLDoc, lo_MainNode)
      End If
  Else
      Call SAP_CreateXMLNode("CA_NAME", lc_CursorXML, la_StrValues(0), lo_XMLDoc, lo_MainNode)
      Call SAP_CreateXMLNode("CA_NAME2", lc_CursorXML, la_StrValues(1), lo_XMLDoc, lo_MainNode)
  
      ls_ATR_Value = GetATRValue(lc_CursorXML, lc_Header, "CA_NAME2")
      ll_ATR_DataLength = mo_Db.GetFields(lc_CursorXML, "ATR_DataLength")
              
      la_StrValues = SplitATRValue(ls_ATR_Value, ll_ATR_DataLength)
      
      Call SAP_CreateXMLNode("CA_NAME3", lc_CursorXML, la_StrValues(0), lo_XMLDoc, lo_MainNode)
      
      If UBound(la_StrValues) = 1 Then
          Call SAP_CreateXMLNode("CA_NAME4", lc_CursorXML, la_StrValues(1), lo_XMLDoc, lo_MainNode)
      End If
  End If
  Call SAP_CreateXMLNode("CA_STREET", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "CA_STREET"), lo_XMLDoc, lo_MainNode)
  Call SAP_CreateXMLNode("CA_CITY", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "CA_CITY"), lo_XMLDoc, lo_MainNode)
  'Call SAP_CreateXMLNode("CA_REGION", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "CA_REGION"), lo_XMLDoc, lo_MainNode)
  Call SAP_CreateXMLNode("CA_POSTL_CODE", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "CA_POSTL_CODE"), lo_XMLDoc, lo_MainNode)
  Call SAP_CreateXMLNode("CA_COUNTRY", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "CA_COUNTRY"), lo_XMLDoc, lo_MainNode)
  
  'DELIV ADDRESS
  ls_ATR_Value = GetATRValue(lc_CursorXML, lc_Header, "DA_NAME")
  ll_ATR_DataLength = mo_Db.GetFields(lc_CursorXML, "ATR_DataLength")
  
  If Len(ls_ATR_Value) > 0 Then
    'Set lo_parentNode = AppendElement(lo_XMLDoc, lo_MainNode, "DELIV_ADDRESS", "")
                
    la_StrValues = SplitATRValue(ls_ATR_Value, ll_ATR_DataLength)
      
    If UBound(la_StrValues) = 0 Then
        Call SAP_CreateXMLNode("DA_NAME", lc_CursorXML, la_StrValues(0), lo_XMLDoc, lo_MainNode)
    
        ls_ATR_Value = GetATRValue(lc_CursorXML, lc_Header, "DA_NAME2")
        ll_ATR_DataLength = mo_Db.GetFields(lc_CursorXML, "ATR_DataLength")
                
        la_StrValues = SplitATRValue(ls_ATR_Value, ll_ATR_DataLength)
        Call SAP_CreateXMLNode("DA_NAME2", lc_CursorXML, la_StrValues(0), lo_XMLDoc, lo_MainNode)
        
        If UBound(la_StrValues) = 1 Then
            Call SAP_CreateXMLNode("DA_NAME3", lc_CursorXML, la_StrValues(1), lo_XMLDoc, lo_MainNode)
        End If
    Else
        Call SAP_CreateXMLNode("DA_NAME", lc_CursorXML, la_StrValues(0), lo_XMLDoc, lo_MainNode)
        Call SAP_CreateXMLNode("DA_NAME2", lc_CursorXML, la_StrValues(1), lo_XMLDoc, lo_MainNode)
    
        ls_ATR_Value = GetATRValue(lc_CursorXML, lc_Header, "DA_NAME2")
        ll_ATR_DataLength = mo_Db.GetFields(lc_CursorXML, "ATR_DataLength")
                
        la_StrValues = SplitATRValue(ls_ATR_Value, ll_ATR_DataLength)
        
        Call SAP_CreateXMLNode("DA_NAME3", lc_CursorXML, la_StrValues(0), lo_XMLDoc, lo_MainNode)
        
        If UBound(la_StrValues) = 1 Then
            Call SAP_CreateXMLNode("DA_NAME4", lc_CursorXML, la_StrValues(1), lo_XMLDoc, lo_MainNode)
        End If
    End If
    
              
    Call SAP_CreateXMLNode("DA_STREET", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "DA_STREET"), lo_XMLDoc, lo_MainNode)
    Call SAP_CreateXMLNode("DA_CITY", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "DA_CITY"), lo_XMLDoc, lo_MainNode)
    'Call SAP_CreateXMLNode("DA_REGION", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "DA_REGION"), lo_XMLDoc, lo_MainNode)
    Call SAP_CreateXMLNode("DA_POSTL_CODE", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "DA_POSTL_CODE"), lo_XMLDoc, lo_MainNode)
    Call SAP_CreateXMLNode("DA_COUNTRY", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "DA_COUNTRY"), lo_XMLDoc, lo_MainNode)
  
  End If
  
  'HDR_TEXTS
  If Len(GetATRValue(lc_CursorXML, lc_Header, "TEXT_LINE1")) > 0 Or Len(GetATRValue(lc_CursorXML, lc_Header, "TEXT_LINE2")) > 0 Then
                  
    'Set lo_parentNode = AppendElement(lo_XMLDoc, lo_MainNode, "HDR_TEXTS", "")
                  
    ls_ATR_Value = GetATRValue(lc_CursorXML, lc_Header, "TEXT_LINE1")
    ll_ATR_DataLength = mo_Db.GetFields(lc_CursorXML, "ATR_DataLength")
  
    If (Len(ls_ATR_Value) > 0) And (ll_ATR_DataLength > 0) Then
        'Set lo_SubNode = AppendElement(lo_XMLDoc, lo_parentNode, "HDR_TEXT_GROUP", "")
                
        Call SAP_CreateXMLNode("TEXT_ID1", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "TEXT_ID1"), lo_XMLDoc, lo_MainNode)
        'Call SAP_CreateXMLNode("TEXT_LANGU", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "TEXT_LANGU"), lo_XMLDoc, lo_MainNode)
             
        'Set lo_SubSubNode = AppendElement(lo_XMLDoc, lo_SubNode, "TEXT_LINES", "")
                
        la_StrValues = SplitATRValue(ls_ATR_Value, ll_ATR_DataLength)
        
        ll_Count = UBound(la_StrValues)
        If ll_Count > 2 Then ll_Count = 2
        For ll_Index = 0 To ll_Count
            Call AppendElement(lo_XMLDoc, lo_MainNode, "TEXT_LINE" & (ll_Index + 1), la_StrValues(ll_Index))
            'Call SAP_CreateXMLNode("TEXT_LINE1", lc_CursorXML, la_StrValues(ll_Index), lo_XMLDoc, lo_SubSubNode)
        Next
        
        'Call SAP_CreateXMLNode("TEXT_LINE1", lc_CursorXML, ls_ATR_Value, lo_XMLDoc, lo_SubSubNode)
    End If
    
    ls_ATR_Value = GetATRValue(lc_CursorXML, lc_Header, "TEXT_LINE2")
    ll_ATR_DataLength = mo_Db.GetFields(lc_CursorXML, "ATR_DataLength")
  
    If (Len(ls_ATR_Value) > 0) And (ll_ATR_DataLength > 0) Then
        'Set lo_SubNode = AppendElement(lo_XMLDoc, lo_parentNode, "HDR_TEXT_GROUP", "")
                
        Call SAP_CreateXMLNode("TEXT_ID2", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "TEXT_ID2"), lo_XMLDoc, lo_MainNode)
        'Call SAP_CreateXMLNode("TEXT_LANGU", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Header, "TEXT_LANGU"), lo_XMLDoc, lo_MainNode)
             
        'Set lo_SubSubNode = AppendElement(lo_XMLDoc, lo_SubNode, "TEXT_LINES", "")
                
        la_StrValues = SplitATRValue(ls_ATR_Value, ll_ATR_DataLength)
        
        ll_Count = UBound(la_StrValues)
        If ll_Count > 2 Then ll_Count = 2
        For ll_Index = 0 To ll_Count
            Call AppendElement(lo_XMLDoc, lo_MainNode, "TEXT_LINE" & (ll_Index + 1), la_StrValues(ll_Index))
            'Call SAP_CreateXMLNode("TEXT_LINE2", lc_CursorXML, la_StrValues(ll_Index), lo_XMLDoc, lo_SubSubNode)
        Next
        
        'Call SAP_CreateXMLNode("TEXT_LINE2", lc_CursorXML, ls_ATR_Value, lo_XMLDoc, lo_SubSubNode)
    End If
  End If
      
  'LINES
  If mo_Db.RowCount(lc_Lines) > 0 Then
      
    Set lo_parentNode = AppendElement(lo_XMLDoc, lo_MainNode, "LINES", "")
      
    Call mo_Db.First(lc_Lines)
    
    While Not mo_Db.EOF(lc_Lines)
      
      ls_UOM = GetATRValue(lc_CursorXML, lc_Lines, "SALES_UOM")
      le_CAT_Id = mo_Db.GetFields(lc_Lines, "CAT_Id")
      
      Set lo_SubNode = AppendElement(lo_XMLDoc, lo_parentNode, "LINE_GROUP", "")
      
      
      Call SAP_CreateXMLNode("LINE_ACTION_CODE", lc_CursorXML, as_ActionCode, lo_XMLDoc, lo_SubNode)
      
      Call SAP_CreateXMLNode("MATERIAL_NO", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Lines, "MATERIAL_NO"), lo_XMLDoc, lo_SubNode)
      Call SAP_CreateXMLNode("EPC_ORD_LINE_POS", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Lines, "EPC_ORD_LINE_POS"), lo_XMLDoc, lo_SubNode)
      Call SAP_CreateXMLNode("FREE_OF_CHARGE_IND", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Lines, "FREE_OF_CHARGE_IND"), lo_XMLDoc, lo_SubNode)
      Call SAP_CreateXMLNode("MFG_PRE_RESERV_NO", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Lines, "MFG_PRE_RESERV_NO"), lo_XMLDoc, lo_SubNode)
      Call SAP_CreateXMLNode("MFG_PRE_RESERV_LIN_POS", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Lines, "MFG_PRE_RESERV_LIN_POS"), lo_XMLDoc, lo_SubNode)
      Call SAP_CreateXMLNode("CUST_POSITION", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Lines, "CUST_POSITION"), lo_XMLDoc, lo_SubNode)
      If (le_CAT_Id = eDPCCategory.cgMetalCustomRectPanel) And (StrComp(ls_UOM, DPC_UOM_M2, vbTextCompare) = 0) Then
        Call SAP_CreateXMLNode("SALES_QTY_PCS", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Lines, "SALES_QTY_PCS"), lo_XMLDoc, lo_SubNode)
        Call SAP_CreateXMLNode("SALES_UOM_PCS", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Lines, "SALES_UOM_PCS"), lo_XMLDoc, lo_SubNode)
        Call SAP_CreateXMLNode("LINE_PRICE_AMT_PCS", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Lines, "LINE_PRICE_AMT_PCS"), lo_XMLDoc, lo_SubNode)
      Else
        Call SAP_CreateXMLNode("SALES_QTY", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Lines, "SALES_QTY") * 1000, lo_XMLDoc, lo_SubNode)
        Call SAP_CreateXMLNode("SALES_UOM", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Lines, "SALES_UOM"), lo_XMLDoc, lo_SubNode)
        Call SAP_CreateXMLNode("LINE_PRICE_AMT", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Lines, "LINE_PRICE_AMT"), lo_XMLDoc, lo_SubNode)
      End If
      
      Call SAP_CreateXMLNode("LINE_PRICE_CURR", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Lines, "LINE_PRICE_CURR"), lo_XMLDoc, lo_SubNode)
      Call SAP_CreateXMLNode("LINE_PRICE_UNIT", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Lines, "LINE_PRICE_UNIT"), lo_XMLDoc, lo_SubNode)
      If (le_CAT_Id = eDPCCategory.cgMetalCustomRectPanel) And (StrComp(ls_UOM, DPC_UOM_M2, vbTextCompare) = 0) Then
        Call SAP_CreateXMLNode("LINE_PRICE_UOM_PCS", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Lines, "LINE_PRICE_UOM_PCS"), lo_XMLDoc, lo_SubNode)
      Else
        Call SAP_CreateXMLNode("LINE_PRICE_UOM", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Lines, "LINE_PRICE_UOM"), lo_XMLDoc, lo_SubNode)
      End If
      Call SAP_CreateXMLNode("SHIPPING_PLANT", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Lines, "SHIPPING_PLANT"), lo_XMLDoc, lo_SubNode)
      Call SAP_CreateXMLNode("ITM_REQ_DEL_DATE", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Lines, "ITM_REQ_DEL_DATE"), lo_XMLDoc, lo_SubNode)

      
      ls_ATR_Value = GetATRValue(lc_CursorXML, lc_Lines, "TEXT_LINE")
      ll_ATR_DataLength = mo_Db.GetFields(lc_CursorXML, "ATR_DataLength")

      If (Len(ls_ATR_Value) > 0) And (ll_ATR_DataLength > 0) Then
        'Set lo_SubNode = AppendElement(lo_XMLDoc, lo_SubNode, "ITM_TEXTS", "")
            
        'Set lo_SubSubNode = AppendElement(lo_XMLDoc, lo_SubNode, "ITM_TEXT_GROUP", "")
            
        Call SAP_CreateXMLNode("TEXT_ID", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Lines, "TEXT_ID"), lo_XMLDoc, lo_SubNode)
        'Call SAP_CreateXMLNode("TEXT_LANGU", lc_CursorXML, GetATRValue(lc_CursorXML, lc_Lines, "TEXT_LANGU"), lo_XMLDoc, lo_SubNode)
            
        'Set lo_SubSubSubNode = AppendElement(lo_XMLDoc, lo_SubSubNode, "TEXT_LINES", "")
                                
        la_StrValues = SplitATRValue(ls_ATR_Value, ll_ATR_DataLength)
        ll_Count = UBound(la_StrValues)
        If ll_Count > 2 Then ll_Count = 2
        
        For ll_Index = 0 To ll_Count
            Call AppendElement(lo_XMLDoc, lo_SubNode, "TEXT_LINE" & (ll_Index + 1), la_StrValues(ll_Index))
            'Call SAP_CreateXMLNode("TEXT_LINE", lc_CursorXML, la_StrValues(ll_Index), lo_XMLDoc, lo_SubSubSubNode)
        Next
      End If

      mo_Db.Next (lc_Lines)
    Wend
  End If
  
  ls_Filename = mo_Db.GetFields(lc_Lines, "OFD_OrdNrB7") & "_" & Format(Now, "yyyymmdd_hhmmss")
  
  Call mo_Db.Close(lc_Lines)
  Call mo_Db.Close(lc_Header)
 
  Call mo_Db.Close(lc_CursorXML)
  
  Set lo_SubSubNode = Nothing
  Set lo_SubNode = Nothing
  Set lo_parentNode = Nothing
  Set lo_MainNode = Nothing
  
  Bae_SalesOrderCreateGetXML = Bae_SaveXMLDocument(lo_XMLDoc, ls_Filename)
'
'#If LIVE = 0 Then
'  SalesOrderCreateGetXML_v2 = SaveXMLDocument(lo_XMLDoc, "AMC_SalesOrderCreate", "SAPAMCSalesOrderCreate", False, True)
'  Exit Function
'#Else
'  SalesOrderCreateGetXML_v2 = SaveXMLDocument(lo_XMLDoc, "AMC_SalesOrderCreate", "SAPAMCSalesOrderCreate")
'#End If
  
  Exit Function
errorHandler:
  
  If lc_Lines <> 0 Then
    mo_Db.Close (lc_Lines)
  End If
  
  If lc_CursorXML <> 0 Then
    mo_Db.Close (lc_CursorXML)
  End If

  Set lo_SubSubNode = Nothing
  Set lo_SubNode = Nothing
  Set lo_parentNode = Nothing
  Set lo_MainNode = Nothing

  Call LogInterface(mo_Db, ml_U_Code)
  
  Call errorHandler("Bae_SalesOrderCreateGetXML")
End Function

Public Function SAP_SalesOrderCreateProcessResponse(ByVal as_Response As String, ByRef as_ErrorMsg As String, ByVal ab_Simulate As Boolean) As Boolean
On Error GoTo errorHandler

Dim lo_XMLDoc As Object
Dim lo_NodeElem As Object
Dim lo_NodeList As Object
Dim lo_NodeId As Object
Dim ls_Value As String
Dim ls_COF_Code As String
Dim ls_SAP_Code As String
Dim ll_Cursor As Long
Dim lb_InTransaction As Boolean
Dim ll_COF_Id As String
Dim ll_iConcurrency As Long
Dim ls_OFD_Pos() As String
Dim ls_OFD_PosSAP() As String
Dim ls_Request As String
Dim ll_Index As Integer
Dim ls_ValidationXSD As String
Dim ls_FormatterXML As String
Dim ls_Error As String

    SAP_SalesOrderCreateProcessResponse = False
    
    Call LoadXMLFiles("SAPAMCSalesOrderChangeResponse", ls_ValidationXSD, ls_FormatterXML)
      
    Call ValidateXMLFile(as_Response, "", ls_ValidationXSD, True)

    Set lo_XMLDoc = CreateObject("MSXML2.DOMDocument")
    
    lo_XMLDoc.async = False
    Call lo_XMLDoc.loadXML(as_Response)
    
    If (lo_XMLDoc.parseError.errorCode <> 0) Then
    
        mo_ILO.ILO_Error = lo_XMLDoc.parseError.reason
        mo_ILO.ILO_Status = eDPCInterfaceStatus.isFailed
        
        Err.Raise ArmErr.CompFncFailed, "Parse Error:", lo_XMLDoc.parseError.reason
       
    Else
       Set lo_NodeElem = lo_XMLDoc.selectSingleNode("//SUCC_FAIL_IND")
       ls_Value = lo_NodeElem.nodeTypedValue
       If ls_Value = "S" Then
                   
            If Not ab_Simulate Then
              ls_COF_Code = lo_XMLDoc.selectSingleNode("//EPC_ORD_NO").nodeTypedValue
              ls_SAP_Code = lo_XMLDoc.selectSingleNode("//SAP_ORD_NO").nodeTypedValue
              
              Set lo_NodeList = lo_XMLDoc.selectNodes("//LINE_GROUP")
      
              If lo_NodeList.length > 0 Then
                  
                  ReDim ls_OFD_Pos(lo_NodeList.length - 1)
                  ReDim ls_OFD_PosSAP(lo_NodeList.length - 1)
                  ll_Index = 0
                  
                  For Each lo_NodeElem In lo_NodeList
                      ls_OFD_Pos(ll_Index) = lo_NodeElem.selectSingleNode("EPC_ORD_LINE_POS").nodeTypedValue
                      ls_OFD_PosSAP(ll_Index) = lo_NodeElem.selectSingleNode("SAP_ORD_LINE_POS").nodeTypedValue
                      ll_Index = ll_Index + 1
                  Next
                              
                  ls_Request = "exec CAP_Offer_sel2 $COF_Code$,'E'"
                  ls_Request = Replace(ls_Request, "$COF_Code$", mo_Tools.SQLStr(ls_COF_Code), , , vbTextCompare)
                  ll_Cursor = mo_Tools.OpenSQLSafe(mo_Db, ls_Request, 1)
                  
                  ll_COF_Id = mo_Db.GetFields(ll_Cursor, "COF_Id")
                  ll_iConcurrency = mo_Db.GetFields(ll_Cursor, "iConcurrency")
                              
                  Call mo_Db.Close(ll_Cursor)
                  
                  Call mo_Tools.BeginTran(mo_Db, ml_U_Code, SCREEN_NAME, "CAP_Offer_SAPResponse")
                  lb_InTransaction = True
                  
                  ls_Request = "exec CAP_Offer_SAPResponse_upd $COF_Code$,$COF_CodeSAP$,$COF_SAPStat$,$iConcurrency$,$Z_Last_Upd_User$"
                  ls_Request = Replace(ls_Request, "$COF_Code$", mo_Tools.SQLStr(ls_COF_Code), , , vbTextCompare)
                  ls_Request = Replace(ls_Request, "$COF_CodeSAP$", mo_Tools.SQLStr(ls_SAP_Code), , , vbTextCompare)
                  ls_Request = Replace(ls_Request, "$COF_SAPStat$", 1, , , vbTextCompare)
                  ls_Request = Replace(ls_Request, "$iConcurrency$", ll_iConcurrency, , , vbTextCompare)
                  ls_Request = Replace(ls_Request, "$Z_Last_Upd_User$", ml_U_Code, , , vbTextCompare)
                  Call mo_Tools.ExecuteSQLSafe(mo_Db, ls_Request, 1)
                  
                  For ll_Index = 0 To lo_NodeList.length - 1
                  
                      ls_Request = "exec CAP_OfferDetail_SAPResponse_upd $COF_Id$,$OFD_Pos$,$OFD_PosSAP$,$Z_Last_Upd_User$"
                      ls_Request = Replace(ls_Request, "$COF_Id$", mo_Tools.SQLStr(ll_COF_Id), , , vbTextCompare)
                      ls_Request = Replace(ls_Request, "$OFD_Pos$", mo_Tools.SQLStr(ls_OFD_Pos(ll_Index)), , , vbTextCompare)
                      ls_Request = Replace(ls_Request, "$OFD_PosSAP$", mo_Tools.SQLStr(ls_OFD_PosSAP(ll_Index)), , , vbTextCompare)
                      ls_Request = Replace(ls_Request, "$Z_Last_Upd_User$", ml_U_Code, , , vbTextCompare)
                      Call mo_Tools.ExecuteSQLSafe(mo_Db, ls_Request, 1)
                  
                  Next
                              
                  Call mo_Tools.CommitTran(mo_Db, ml_U_Code, SCREEN_NAME, "CAP_Offer_SAPResponse")
                  lb_InTransaction = False
                  
              End If
            End If
            SAP_SalesOrderCreateProcessResponse = True
     
            mo_ILO.ILO_Status = eDPCInterfaceStatus.isOK
       Else
            mo_ILO.ILO_Status = eDPCInterfaceStatus.isFailed
       End If
       
       'read error, warrning, info messages
       Set lo_NodeList = lo_XMLDoc.selectNodes("//ERROR_GROUP")
            
       For Each lo_NodeElem In lo_NodeList
            as_ErrorMsg = as_ErrorMsg & lo_NodeElem.selectSingleNode("MSG_TEXT").nodeTypedValue & vbNewLine
       Next
                      
       mo_ILO.ILO_Error = as_ErrorMsg
    End If
    
    Set lo_NodeElem = Nothing
    Set lo_NodeList = Nothing
    Set lo_XMLDoc = Nothing
        
  Exit Function
errorHandler:
    
    If lb_InTransaction Then
        Call mo_Tools.RollbackTran(mo_Db, ml_U_Code, SCREEN_NAME, "CAP_Offer_SAPResponse")
    End If

    If ll_Cursor <> 0 Then
        Call mo_Db.Close(ll_Cursor)
    End If
    
    Set lo_NodeElem = Nothing
    Set lo_NodeList = Nothing
    Set lo_XMLDoc = Nothing
    
  Call LogInterface(mo_Db, ml_U_Code)
  
  Call errorHandler("SAP_SalesOrderCreateProcessResponse")
End Function

Public Function SAP_ProcessBasicResponse(ByVal as_Response As String, ByRef as_ErrorMsg As String) As Boolean
On Error GoTo errorHandler

Dim lo_XMLDoc As Object
Dim lo_NodeElem As Object
Dim lo_NodeList As Object
Dim lo_NodeId As Object
Dim ls_Value As String
Dim ls_ValidationXSD As String
Dim ls_FormatterXML As String
Dim ls_Error As String

    SAP_ProcessBasicResponse = False
    
    Call LoadXMLFiles("SAPAMCBasicResponse", ls_ValidationXSD, ls_FormatterXML)
      
    Call ValidateXMLFile(as_Response, "", ls_ValidationXSD, True)

    Set lo_XMLDoc = CreateObject("MSXML2.DOMDocument")
    
    lo_XMLDoc.async = False
    Call lo_XMLDoc.loadXML(as_Response)
    
    If (lo_XMLDoc.parseError.errorCode <> 0) Then
    
        mo_ILO.ILO_Error = lo_XMLDoc.parseError.reason
        mo_ILO.ILO_Status = eDPCInterfaceStatus.isFailed
    
        Err.Raise ArmErr.CompFncFailed, "Parse Error:", lo_XMLDoc.parseError.reason
       
    Else
       Set lo_NodeElem = lo_XMLDoc.selectSingleNode("//SUCC_FAIL_IND")
       ls_Value = lo_NodeElem.nodeTypedValue
       If ls_Value = "F" Then
       
            mo_ILO.ILO_Status = eDPCInterfaceStatus.isFailed
            SAP_ProcessBasicResponse = False
       
       ElseIf ls_Value = "S" Then
       
            mo_ILO.ILO_Status = eDPCInterfaceStatus.isOK
            SAP_ProcessBasicResponse = True
       End If
              
    End If
    
    'read error, warrning, info messages
    Set lo_NodeList = lo_XMLDoc.selectNodes("//ERROR_GROUP")
        
    For Each lo_NodeElem In lo_NodeList
        as_ErrorMsg = as_ErrorMsg & lo_NodeElem.selectSingleNode("MSG_TEXT").nodeTypedValue & vbNewLine
    Next
    
    mo_ILO.ILO_Error = as_ErrorMsg
    
    Set lo_NodeElem = Nothing
    Set lo_NodeList = Nothing
    Set lo_XMLDoc = Nothing
    
  Exit Function
errorHandler:
        
    Set lo_NodeElem = Nothing
    Set lo_NodeList = Nothing
    Set lo_XMLDoc = Nothing
    
  Call LogInterface(mo_Db, ml_U_Code)
  
  Call errorHandler("SAP_ProcessBasicResponse")
End Function

Public Function SAP_SalesOrderLineCancelAddReplace(ByVal as_COF_Id As String, ByRef as_ErrorMsg As String) As String
On Error GoTo errorHandler

Dim ls_Xml As String
Dim ls_Response As String

        SAP_SalesOrderLineCancelAddReplace = False
        
        ls_Xml = SAP_SalesOrderLineCancelAddReplaceGetXML(as_COF_Id)
        
        If (SendRequest(DPC_SAP_SALESORDER_CHANGE, "POST", ls_Xml, ls_Response) = True) Then
                       
            If (SAP_SalesOrderCreateProcessResponse(ls_Response, as_ErrorMsg, False) = True) Then
                SAP_SalesOrderLineCancelAddReplace = True
            End If
            
            Call LogInterface(mo_Db, ml_U_Code)
        Else
            as_ErrorMsg = ls_Response
        End If
        
  Exit Function
errorHandler:
  
  Call LogInterface(mo_Db, ml_U_Code)

  Call errorHandler("SAP_SalesOrderLineCancelAddReplace")
End Function

Public Function SAP_SalesOrderLineCancelAddReplaceGetXML(ByVal as_COF_Id As String) As String
On Error GoTo errorHandler

Dim lo_XmlDocCust As Object
'Dim ll_Version As Long
Dim lo_SubNode1 As Object, lo_SubNode2 As Object, lo_SubNode3 As Object, lo_SubNode4 As Object, lo_SubNode5 As Object
Dim lo_parentNode As Object, lo_SubNode As Object
Dim lo_MainNode As Object
Dim lc_CursorMaster As Long
Dim lc_CursorXML As Long
Dim lc_CursorGroup As Long
Dim lt_XmlSql As TXmlSql
Dim lt_XmlMaster As TXmlSql
Dim lo_XMLDoc As MSXML2.DOMDocument
Dim ls_Request As String
Dim ls_ATR_Value As String
Dim ls_ATR_DataLength As Long
Dim la_StrValues() As String
Dim ll_Index As Integer
Dim ls_UOM As String
Dim le_CAT_Id As eDPCCategory

On Error GoTo errorHandler
  
  Call ClearLogInterface
  mo_ILO.ILO_Interface = eDPCXmlExportType.etSAP_SalesOrderLineCancelAddReplace
  mo_ILO.ILO_MasterId = as_COF_Id
  
  Set lo_XMLDoc = CreateObject("MSXML2.DOMDocument")
  
  lc_CursorXML = SAP_GetXmlCursor(eDPCXmlExportType.etSAP_SalesOrderLineCancelAddReplace)
    
  Set lo_MainNode = lo_XMLDoc.createProcessingInstruction("xml", "version='1.0' encoding='utf-8'")
  lo_XMLDoc.appendChild lo_MainNode
    
  Set lo_MainNode = AppendElement(lo_XMLDoc, Nothing, "AMC_SALES_ORD_LINE_CANCEL_ADD_REPLACE", "")
  lo_MainNode.appendChild lo_XMLDoc.createTextNode(vbNewLine + vbTab)
      
  ls_Request = "exec DPC_SAPSalesOrderLineChangeHeader_sel $COF_Id$,$Language_Code$"
  ls_Request = Replace(ls_Request, "$COF_Id$", mo_Tools.SQLStr(as_COF_Id), , , vbTextCompare)
  ls_Request = Replace(ls_Request, "$Language_Code$", "'E'", , , vbTextCompare)
  lc_CursorMaster = mo_Tools.OpenSQLSafe(mo_Db, ls_Request)
  
  Call mo_Db.First(lc_CursorMaster)
        
  Call SAP_CreateXMLNode("SAP_ORD_NO", lc_CursorXML, GetATRValue(lc_CursorXML, lc_CursorMaster, "SAP_ORD_NO"), lo_XMLDoc, lo_MainNode)
  Call SAP_CreateXMLNode("EPC_ORD_NO", lc_CursorXML, GetATRValue(lc_CursorXML, lc_CursorMaster, "EPC_ORD_NO"), lo_XMLDoc, lo_MainNode)
                
  mo_Db.Close (lc_CursorMaster)

  'LINES
  ls_Request = "exec DPC_SAPSalesOrderLineChangeLines_lst $COF_Id$,'E'"
  ls_Request = Replace(ls_Request, "$COF_Id$", mo_Tools.SQLStr(as_COF_Id), , , vbTextCompare)
  lc_CursorMaster = mo_Tools.OpenSQLSafe(mo_Db, ls_Request)
    
  If mo_Db.RowCount(lc_CursorMaster) > 0 Then
      
      Set lo_parentNode = AppendElement(lo_XMLDoc, lo_MainNode, "LINES", "")
      
      Call mo_Db.First(lc_CursorMaster)
      
      While Not mo_Db.EOF(lc_CursorMaster)
                
          ls_UOM = GetATRValue(lc_CursorXML, lc_CursorMaster, "SALES_UOM")
          le_CAT_Id = mo_Db.GetFields(lc_CursorMaster, "CAT_Id")
          
          If (mo_Db.GetFields(lc_CursorMaster, "OFD_SAPAct") = "D") Or (mo_Db.GetFields(lc_CursorMaster, "OFD_SAPAct") = "K") Then
              'DELETE GROUPS
            Set lo_SubNode = AppendElement(lo_XMLDoc, lo_parentNode, "LINE_GROUP", "")
                  
            Call SAP_CreateXMLNode("ACTION_CODE", lc_CursorXML, GetATRValue(lc_CursorXML, lc_CursorMaster, "ACTION_CODE"), lo_XMLDoc, lo_SubNode)
            Call SAP_CreateXMLNode("SAP_CANC_ORD_LINE_POS", lc_CursorXML, GetATRValue(lc_CursorXML, lc_CursorMaster, "SAP_CANC_ORD_LINE_POS"), lo_XMLDoc, lo_SubNode)
          
          ElseIf mo_Db.GetFields(lc_CursorMaster, "OFD_SAPAct") = "A" Then
            'ADD GROUPS
            Set lo_SubNode = AppendElement(lo_XMLDoc, lo_parentNode, "LINE_GROUP", "")
                    
            Call SAP_CreateXMLNode("ACTION_CODE", lc_CursorXML, GetATRValue(lc_CursorXML, lc_CursorMaster, "ACTION_CODE"), lo_XMLDoc, lo_SubNode)
                
            Set lo_SubNode2 = AppendElement(lo_XMLDoc, lo_SubNode, "LINE_DETAIL_GROUP", "")
                
            Call SAP_CreateXMLNode("MATERIAL_NO", lc_CursorXML, GetATRValue(lc_CursorXML, lc_CursorMaster, "MATERIAL_NO"), lo_XMLDoc, lo_SubNode2)
            Call SAP_CreateXMLNode("EPC_ORD_LINE_POS", lc_CursorXML, GetATRValue(lc_CursorXML, lc_CursorMaster, "EPC_ORD_LINE_POS"), lo_XMLDoc, lo_SubNode2)
            Call SAP_CreateXMLNode("FREE_OF_CHARGE_IND", lc_CursorXML, GetATRValue(lc_CursorXML, lc_CursorMaster, "FREE_OF_CHARGE_IND"), lo_XMLDoc, lo_SubNode2)
            Call SAP_CreateXMLNode("MFG_PRE_RESERV_NO", lc_CursorXML, GetATRValue(lc_CursorXML, lc_CursorMaster, "MFG_PRE_RESERV_NO"), lo_XMLDoc, lo_SubNode2)
            Call SAP_CreateXMLNode("MFG_PRE_RESERV_LIN_POS", lc_CursorXML, GetATRValue(lc_CursorXML, lc_CursorMaster, "MFG_PRE_RESERV_LIN_POS"), lo_XMLDoc, lo_SubNode2)
            Call SAP_CreateXMLNode("CUST_POSITION", lc_CursorXML, GetATRValue(lc_CursorXML, lc_CursorMaster, "CUST_POSITION"), lo_XMLDoc, lo_SubNode2)
            If (le_CAT_Id = eDPCCategory.cgMetalCustomRectPanel) And (StrComp(ls_UOM, DPC_UOM_M2, vbTextCompare) = 0) Then
              Call SAP_CreateXMLNode("SALES_QTY_PCS", lc_CursorXML, GetATRValue(lc_CursorXML, lc_CursorMaster, "SALES_QTY_PCS"), lo_XMLDoc, lo_SubNode2)
              Call SAP_CreateXMLNode("SALES_UOM_PCS", lc_CursorXML, GetATRValue(lc_CursorXML, lc_CursorMaster, "SALES_UOM_PCS"), lo_XMLDoc, lo_SubNode2)
            Else
              Call SAP_CreateXMLNode("SALES_QTY", lc_CursorXML, GetATRValue(lc_CursorXML, lc_CursorMaster, "SALES_QTY"), lo_XMLDoc, lo_SubNode2)
              Call SAP_CreateXMLNode("SALES_UOM", lc_CursorXML, GetATRValue(lc_CursorXML, lc_CursorMaster, "SALES_UOM"), lo_XMLDoc, lo_SubNode2)
            End If
            If (le_CAT_Id = eDPCCategory.cgMetalCustomRectPanel) And (StrComp(ls_UOM, DPC_UOM_M2, vbTextCompare) = 0) Then
              Call SAP_CreateXMLNode("LINE_PRICE_AMT_PCS", lc_CursorXML, GetATRValue(lc_CursorXML, lc_CursorMaster, "LINE_PRICE_AMT_PCS"), lo_XMLDoc, lo_SubNode2)
            Else
              Call SAP_CreateXMLNode("LINE_PRICE_AMT", lc_CursorXML, GetATRValue(lc_CursorXML, lc_CursorMaster, "LINE_PRICE_AMT"), lo_XMLDoc, lo_SubNode2)
            End If
            Call SAP_CreateXMLNode("LINE_PRICE_CURR", lc_CursorXML, GetATRValue(lc_CursorXML, lc_CursorMaster, "LINE_PRICE_CURR"), lo_XMLDoc, lo_SubNode2)
            Call SAP_CreateXMLNode("LINE_PRICE_UNIT", lc_CursorXML, GetATRValue(lc_CursorXML, lc_CursorMaster, "LINE_PRICE_UNIT"), lo_XMLDoc, lo_SubNode2)
            If (le_CAT_Id = eDPCCategory.cgMetalCustomRectPanel) And (StrComp(ls_UOM, DPC_UOM_M2, vbTextCompare) = 0) Then
              Call SAP_CreateXMLNode("LINE_PRICE_UOM_PCS", lc_CursorXML, GetATRValue(lc_CursorXML, lc_CursorMaster, "LINE_PRICE_UOM_PCS"), lo_XMLDoc, lo_SubNode2)
            Else
              Call SAP_CreateXMLNode("LINE_PRICE_UOM", lc_CursorXML, GetATRValue(lc_CursorXML, lc_CursorMaster, "LINE_PRICE_UOM"), lo_XMLDoc, lo_SubNode2)
            End If
            Call SAP_CreateXMLNode("SHIPPING_PLANT", lc_CursorXML, GetATRValue(lc_CursorXML, lc_CursorMaster, "SHIPPING_PLANT"), lo_XMLDoc, lo_SubNode2)
            Call SAP_CreateXMLNode("ITM_REQ_DEL_DATE", lc_CursorXML, GetATRValue(lc_CursorXML, lc_CursorMaster, "ITM_REQ_DEL_DATE"), lo_XMLDoc, lo_SubNode2)
          
            ls_ATR_Value = GetATRValue(lc_CursorXML, lc_CursorMaster, "TEXT_LINE")
            
            If Len(ls_ATR_Value) > 0 Then
                Set lo_SubNode3 = AppendElement(lo_XMLDoc, lo_SubNode2, "ITM_TEXTS", "")
                    
                Set lo_SubNode4 = AppendElement(lo_XMLDoc, lo_SubNode3, "ITM_TEXT_GROUP", "")
                
                Call SAP_CreateXMLNode("TEXT_ID", lc_CursorXML, GetATRValue(lc_CursorXML, lc_CursorMaster, "TEXT_ID"), lo_XMLDoc, lo_SubNode4)
                Call SAP_CreateXMLNode("TEXT_LANGU", lc_CursorXML, GetATRValue(lc_CursorXML, lc_CursorMaster, "TEXT_LANGU"), lo_XMLDoc, lo_SubNode4)
            
                Set lo_SubNode5 = AppendElement(lo_XMLDoc, lo_SubNode4, "TEXT_LINES", "")
              
                ls_ATR_DataLength = mo_Db.GetFields(lc_CursorXML, "ATR_DataLength")
                
                la_StrValues = SplitATRValue(ls_ATR_Value, ls_ATR_DataLength)
                
                For ll_Index = 0 To UBound(la_StrValues)
                    Call SAP_CreateXMLNode("TEXT_LINE", lc_CursorXML, la_StrValues(ll_Index), lo_XMLDoc, lo_SubNode5)
                Next
            End If
    
          ElseIf mo_Db.GetFields(lc_CursorMaster, "OFD_SAPAct") = "R" Then
  'REPLACE GROUPS
            Set lo_SubNode = AppendElement(lo_XMLDoc, lo_parentNode, "LINE_GROUP", "")
                    
            Call SAP_CreateXMLNode("ACTION_CODE", lc_CursorXML, GetATRValue(lc_CursorXML, lc_CursorMaster, "ACTION_CODE"), lo_XMLDoc, lo_SubNode)
            Call SAP_CreateXMLNode("SAP_CANC_ORD_LINE_POS", lc_CursorXML, GetATRValue(lc_CursorXML, lc_CursorMaster, "SAP_CANC_ORD_LINE_POS"), lo_XMLDoc, lo_SubNode)
                
            Set lo_SubNode2 = AppendElement(lo_XMLDoc, lo_SubNode, "LINE_DETAIL_GROUP", "")
                
            Call SAP_CreateXMLNode("MATERIAL_NO", lc_CursorXML, GetATRValue(lc_CursorXML, lc_CursorMaster, "MATERIAL_NO"), lo_XMLDoc, lo_SubNode2)
            Call SAP_CreateXMLNode("EPC_ORD_LINE_POS", lc_CursorXML, GetATRValue(lc_CursorXML, lc_CursorMaster, "EPC_ORD_LINE_POS"), lo_XMLDoc, lo_SubNode2)
            Call SAP_CreateXMLNode("FREE_OF_CHARGE_IND", lc_CursorXML, GetATRValue(lc_CursorXML, lc_CursorMaster, "FREE_OF_CHARGE_IND"), lo_XMLDoc, lo_SubNode2)
            Call SAP_CreateXMLNode("MFG_PRE_RESERV_NO", lc_CursorXML, GetATRValue(lc_CursorXML, lc_CursorMaster, "MFG_PRE_RESERV_NO"), lo_XMLDoc, lo_SubNode2)
            Call SAP_CreateXMLNode("MFG_PRE_RESERV_LIN_POS", lc_CursorXML, GetATRValue(lc_CursorXML, lc_CursorMaster, "MFG_PRE_RESERV_LIN_POS"), lo_XMLDoc, lo_SubNode2)
            Call SAP_CreateXMLNode("CUST_POSITION", lc_CursorXML, GetATRValue(lc_CursorXML, lc_CursorMaster, "CUST_POSITION"), lo_XMLDoc, lo_SubNode2)
            If (le_CAT_Id = eDPCCategory.cgMetalCustomRectPanel) And (StrComp(ls_UOM, DPC_UOM_M2, vbTextCompare) = 0) Then
              Call SAP_CreateXMLNode("SALES_QTY_PCS", lc_CursorXML, GetATRValue(lc_CursorXML, lc_CursorMaster, "SALES_QTY_PCS"), lo_XMLDoc, lo_SubNode2)
              Call SAP_CreateXMLNode("SALES_UOM_PCS", lc_CursorXML, GetATRValue(lc_CursorXML, lc_CursorMaster, "SALES_UOM_PCS"), lo_XMLDoc, lo_SubNode2)
            Else
              Call SAP_CreateXMLNode("SALES_QTY", lc_CursorXML, GetATRValue(lc_CursorXML, lc_CursorMaster, "SALES_QTY"), lo_XMLDoc, lo_SubNode2)
              Call SAP_CreateXMLNode("SALES_UOM", lc_CursorXML, GetATRValue(lc_CursorXML, lc_CursorMaster, "SALES_UOM"), lo_XMLDoc, lo_SubNode2)
            End If
            If (le_CAT_Id = eDPCCategory.cgMetalCustomRectPanel) And (StrComp(ls_UOM, DPC_UOM_M2, vbTextCompare) = 0) Then
              Call SAP_CreateXMLNode("LINE_PRICE_AMT_PCS", lc_CursorXML, GetATRValue(lc_CursorXML, lc_CursorMaster, "LINE_PRICE_AMT_PCS"), lo_XMLDoc, lo_SubNode2)
            Else
              Call SAP_CreateXMLNode("LINE_PRICE_AMT", lc_CursorXML, GetATRValue(lc_CursorXML, lc_CursorMaster, "LINE_PRICE_AMT"), lo_XMLDoc, lo_SubNode2)
            End If
            Call SAP_CreateXMLNode("LINE_PRICE_CURR", lc_CursorXML, GetATRValue(lc_CursorXML, lc_CursorMaster, "LINE_PRICE_CURR"), lo_XMLDoc, lo_SubNode2)
            Call SAP_CreateXMLNode("LINE_PRICE_UNIT", lc_CursorXML, GetATRValue(lc_CursorXML, lc_CursorMaster, "LINE_PRICE_UNIT"), lo_XMLDoc, lo_SubNode2)
            If (le_CAT_Id = eDPCCategory.cgMetalCustomRectPanel) And (StrComp(ls_UOM, DPC_UOM_M2, vbTextCompare) = 0) Then
              Call SAP_CreateXMLNode("LINE_PRICE_UOM_PCS", lc_CursorXML, GetATRValue(lc_CursorXML, lc_CursorMaster, "LINE_PRICE_UOM_PCS"), lo_XMLDoc, lo_SubNode2)
            Else
              Call SAP_CreateXMLNode("LINE_PRICE_UOM", lc_CursorXML, GetATRValue(lc_CursorXML, lc_CursorMaster, "LINE_PRICE_UOM"), lo_XMLDoc, lo_SubNode2)
            End If
            Call SAP_CreateXMLNode("SHIPPING_PLANT", lc_CursorXML, GetATRValue(lc_CursorXML, lc_CursorMaster, "SHIPPING_PLANT"), lo_XMLDoc, lo_SubNode2)
            Call SAP_CreateXMLNode("ITM_REQ_DEL_DATE", lc_CursorXML, GetATRValue(lc_CursorXML, lc_CursorMaster, "ITM_REQ_DEL_DATE"), lo_XMLDoc, lo_SubNode2)
          
            ls_ATR_Value = GetATRValue(lc_CursorXML, lc_CursorMaster, "TEXT_LINE")
            ls_ATR_DataLength = mo_Db.GetFields(lc_CursorXML, "ATR_DataLength")
            
            If Len(ls_ATR_Value) > 0 Then
              Set lo_SubNode3 = AppendElement(lo_XMLDoc, lo_SubNode2, "ITM_TEXTS", "")
            
              Set lo_SubNode4 = AppendElement(lo_XMLDoc, lo_SubNode3, "ITM_TEXT_GROUP", "")
              
              Call SAP_CreateXMLNode("TEXT_ID", lc_CursorXML, GetATRValue(lc_CursorXML, lc_CursorMaster, "TEXT_ID"), lo_XMLDoc, lo_SubNode4)
              Call SAP_CreateXMLNode("TEXT_LANGU", lc_CursorXML, GetATRValue(lc_CursorXML, lc_CursorMaster, "TEXT_LANGU"), lo_XMLDoc, lo_SubNode4)
              
              Set lo_SubNode5 = AppendElement(lo_XMLDoc, lo_SubNode4, "TEXT_LINES", "")
                                    
              la_StrValues = SplitATRValue(ls_ATR_Value, ls_ATR_DataLength)
                  
              For ll_Index = 0 To UBound(la_StrValues)
                  Call SAP_CreateXMLNode("TEXT_LINE", lc_CursorXML, la_StrValues(ll_Index), lo_XMLDoc, lo_SubNode5)
              Next
            End If
            
          End If
        
          Call mo_Db.Next(lc_CursorMaster)
          
      Wend
   End If
          
  mo_Db.Close (lc_CursorMaster)
  
  mo_Db.Close (lc_CursorXML)
  
  Set lo_SubNode2 = Nothing
  Set lo_SubNode = Nothing
  Set lo_parentNode = Nothing
  Set lo_MainNode = Nothing
  
#If LIVE = 0 Then
  SAP_SalesOrderLineCancelAddReplaceGetXML = SAP_SaveXMLDocument(lo_XMLDoc, "AMC_SalesOrderLineCancelAddReplace", "SAPAMCSalesOrderChange", False)
  Exit Function
#Else
  SAP_SalesOrderLineCancelAddReplaceGetXML = SAP_SaveXMLDocument(lo_XMLDoc, "AMC_SalesOrderLineCancelAddReplace", "SAPAMCSalesOrderChange")
  
#End If
  
  Exit Function
errorHandler:
  
  If lc_CursorMaster <> 0 Then
    mo_Db.Close (lc_CursorMaster)
  End If
  
  If lc_CursorXML <> 0 Then
    mo_Db.Close (lc_CursorXML)
  End If

  Set lo_SubNode2 = Nothing
  Set lo_SubNode = Nothing
  Set lo_parentNode = Nothing
  Set lo_MainNode = Nothing

  Call LogInterface(mo_Db, ml_U_Code)

  Call errorHandler("SAP_SalesOrderLineCancelAddReplaceGetXML")
End Function

Public Function SendRequest(ByVal as_RestAddress As String, ByVal as_Type As String, ByVal as_XML As String, ByRef as_Response As String) As Boolean
On Error GoTo errorHandler

#If LIVE = 1 Then
'    Dim mo_Sys As Object
    Dim mo_XMLHttp As Object
#Else
'    Dim mo_Sys As ARMSYSCOMLib.ArmSYS
    Dim mo_XMLHttp As Object
#End If
    
    Dim ld_RequestTime As Date
    Dim lb_SendOk As Boolean
    
    ld_RequestTime = Now()
    SendRequest = False
    lb_SendOk = False
    
    mo_ILO.ILO_XMLSent = as_XML
    
    Set mo_XMLHttp = CreateObject("MSXML2.ServerXMLHTTP")
    
    Call mo_XMLHttp.setTimeouts(40000, 40000, 40000, 40000)
    
    'since the server i am communicating with is using a self signed certificate authority
    ' I have to ignore all ssl errors.
    'XMLHTTP.setOption 2, 13056
    
    ' I set the friendlyname of my certificate just in case i have tried with and without
    'XMLHTTP.setOption 3, "myrealfriendlynameofcrt"
    
    If as_Type = "GET" Then
        
        mo_ILO.ILO_Connection = "http://lccas050.americas.armstrong.com:6010/" & as_RestAddress & "?AwiApiKey=vfls9eviwzyEbgIudODJfBlQef0JCXULQ+FfuaZHZf4=&SourceSystem=Capture&SchemaVersion=1.0&ClientIdentifier=FooBar"
        Call mo_XMLHttp.Open("GET", "http://lccas050.americas.armstrong.com:6010/" & as_RestAddress & "?AwiApiKey=vfls9eviwzyEbgIudODJfBlQef0JCXULQ+FfuaZHZf4=&SourceSystem=Capture&SchemaVersion=1.0&ClientIdentifier=FooBar", False)
        
        On Error Resume Next
        Call mo_XMLHttp.send
            
    ElseIf as_Type = "POST" Then
    
        mo_ILO.ILO_Connection = "http://lccas050.americas.armstrong.com:6010/" & as_RestAddress
        Call mo_XMLHttp.Open("POST", "http://lccas050.americas.armstrong.com:6010/" & as_RestAddress, False)
        
        mo_XMLHttp.setRequestHeader "Content-type", "application/xml"
        mo_XMLHttp.setRequestHeader "x-awi-ApiKey", "vfls9eviwzyEbgIudODJfBlQef0JCXULQ+FfuaZHZf4="
        mo_XMLHttp.setRequestHeader "x-awi-SourceSystem", "Capture"
        mo_XMLHttp.setRequestHeader "x-awi-SchemaVersion", "1.0"
        
        On Error Resume Next
        With mo_XMLHttp
         .send (as_XML)
        End With
    End If
    
    If Err.Number <> 0 Then
        as_Response = "Send error occured: " & Err.Description
        mo_ILO.ILO_Error = Err.Description
        mo_ILO.ILO_Status = eDPCInterfaceStatus.isFailed
        Call LogInterface(mo_Db, ml_U_Code)
    Else
        lb_SendOk = True
    End If
    
    On Error GoTo errorHandler
    
    mo_ILO.ILO_Performance = DateDiff("s", ld_RequestTime, Now())
    
    If lb_SendOk = True Then
        If mo_XMLHttp.Status < 200 Or mo_XMLHttp.Status > 202 Then
            as_Response = "Error occured : " & mo_XMLHttp.Status & " - " & mo_XMLHttp.statusText
            mo_ILO.ILO_Error = as_Response
            mo_ILO.ILO_Status = eDPCInterfaceStatus.isFailed
            Call LogInterface(mo_Db, ml_U_Code)
        Else
            as_Response = mo_XMLHttp.responseText
            mo_ILO.ILO_XMLResponse = as_Response
            mo_ILO.ILO_RespMsg = as_Response
            SendRequest = True
        End If
    End If
    
    Set mo_XMLHttp = Nothing
    
    Exit Function
  
errorHandler:
  Call LogInterface(mo_Db, ml_U_Code)
  Call errorHandler("SendRequest")
End Function

Public Function TransferXMLDocument(ByVal as_SrcFileName As String, ByRef as_ErrorMsg As String) As Boolean
On Error GoTo errorHandler

#If LIVE = 1 Then
    Dim lo_FTP As Object
    Set lo_FTP = CreateObject("ArmSysCOM.ArmFTP")
#Else
    Dim lo_FTP As ARMSYSCOMLib.ArmFTP
    Set lo_FTP = New ARMSYSCOMLib.ArmFTP
#End If

Dim ls_Error As String
Dim ls_FTPServerIP As String, ls_FTPServerLogin As String, ls_FTPServerPswd As String, ls_FTPServerPath As String
Dim ls_Bae_FTPConn() As String
Dim ls_Filename As String
    
    TransferXMLDocument = False
    
    ls_Bae_FTPConn = Split(mo_Tools.GetAConfigData("DPC_BAE_FTP_SLSORD"), SEP1)
    
    ls_FTPServerIP = ls_Bae_FTPConn(0)
    ls_FTPServerLogin = ls_Bae_FTPConn(1)
    ls_FTPServerPswd = ls_Bae_FTPConn(2)
    ls_FTPServerPath = ls_Bae_FTPConn(3)
    ls_Error = ""
    
    ls_Filename = right(as_SrcFileName, Len(as_SrcFileName) - InStrRev(as_SrcFileName, "\"))
    If OpenFTP(lo_FTP, ls_FTPServerIP, ls_FTPServerLogin, ls_FTPServerPswd, ls_Error) Then

        ' upload file to FTP server
        If UploadFile(lo_FTP, as_SrcFileName, ls_FTPServerPath & ls_Filename, ls_Error) = True Then
            TransferXMLDocument = True
        End If
        
        Call lo_FTP.LogoffServer
    
    End If
          
    Set lo_FTP = Nothing
    
    as_ErrorMsg = ls_Error
    
    Exit Function
errorHandler:
  Call errorHandler("TransferXMLDocument")
End Function

Public Function DownloadXMLDocument(ByVal as_COF_Id As String, ByRef as_FileName As String, ByRef as_ErrorMsg As String) As Boolean
On Error GoTo errorHandler

#If LIVE = 1 Then
    Dim lo_FTP As Object
    Set lo_FTP = CreateObject("ArmSysCOM.ArmFTP")
#Else
    Dim lo_FTP As ARMSYSCOMLib.ArmFTP
    Set lo_FTP = New ARMSYSCOMLib.ArmFTP
#End If

Dim ls_Error As String
Dim ls_FTPServerIP As String, ls_FTPServerLogin As String, ls_FTPServerPswd As String, ls_FTPServerOutPath As String
Dim ls_Bae_FTPConn() As String
Dim ls_Request As String
Dim lc_Lines As Long
Dim ls_Filename, ls_Name As String
Dim ll_i, ll_Success As Long

    DownloadXMLDocument = False
    
    ls_Request = "exec DPC_BaeSalesOrderCreateLines_lst $COF_Id$,'E'"
    ls_Request = Replace(ls_Request, "$COF_Id$", mo_Tools.SQLStr(as_COF_Id), , , vbTextCompare)
    lc_Lines = mo_Tools.OpenSQLSafe(mo_Db, ls_Request)
  
    If Len(mo_Db.GetFields(lc_Lines, "OFD_OrdNrB7")) <= 0 Then
        Call mo_Db.Close(lc_Lines)
        as_ErrorMsg = "XML Download failed, OFD_OrdNrB7 empty for COF_Id: " & as_COF_Id
        Exit Function
    End If
    
    ls_Filename = mo_Db.GetFields(lc_Lines, "OFD_OrdNrB7") & "-"
    
    Call mo_Db.Close(lc_Lines)
    
    ls_Bae_FTPConn = Split(mo_Tools.GetAConfigData("DPC_BAE_FTP_SLSORD"), SEP1)
    
    ls_FTPServerIP = ls_Bae_FTPConn(0)
    ls_FTPServerLogin = ls_Bae_FTPConn(1)
    ls_FTPServerPswd = ls_Bae_FTPConn(2)
    ls_FTPServerOutPath = ls_Bae_FTPConn(4)
    ls_Error = ""
    
    If OpenFTP(lo_FTP, ls_FTPServerIP, ls_FTPServerLogin, ls_FTPServerPswd, ls_Error) Then

         If Not lo_FTP.List(ls_FTPServerOutPath & ls_Filename & "*", FTP_PASIVE) Then
             Call lo_FTP.LogoffServer
             Set lo_FTP = Nothing
             as_ErrorMsg = "FTP command List " & ls_FTPServerOutPath & "\" & ls_Filename & "*" & " failed."
             Exit Function
         End If
         
         ls_Filename = ""
         
         For ll_i = 0 To lo_FTP.ListCount - 1
             ls_Name = lo_FTP.ListFileName(ll_i)

             If lo_FTP.ListFileSize(ll_i) > 0 And ls_Name > ls_Filename Then
                ls_Filename = ls_Name
             End If
         Next
    
        If Len(ls_Filename) > 0 Then
            ' download file from FTP server
            If DownloadFile(lo_FTP, ls_FTPServerOutPath & ls_Filename, ms_TempDir & "\" & ls_Filename, ls_Error) = True Then
                as_FileName = ls_Filename
                
                'delete files from ftp
                For ll_i = 0 To lo_FTP.ListCount - 1
                     Call lo_FTP.DeleteFile(lo_FTP.ListFileName(ll_i), ll_Success)
                Next
         
                DownloadXMLDocument = True
            End If
        End If
        
        Call lo_FTP.LogoffServer
    
    End If
    
    Set lo_FTP = Nothing
    
    as_ErrorMsg = ls_Error
    
    Exit Function
errorHandler:
  If lc_Lines <> 0 Then
    Call mo_Db.Close(lc_Lines)
  End If
  
  Call errorHandler("DownloadXMLDocument")
End Function

' ************************************************************************************
' ******************************* FTP FUNCTIONS **************************************
' ************************************************************************************
#If LIVE = 1 Then
Private Function OpenFTP(ByRef ao_FTP As Object, ByVal as_IP As String, as_Login As String, as_Password As String, ByRef as_ErrorMsg As String) As Boolean
#Else
Private Function OpenFTP(ByRef ao_FTP As ARMSYSCOMLib.ArmFTP, ByVal as_IP As String, as_Login As String, as_Password As String, ByRef as_ErrorMsg As String) As Boolean
#End If
On Error GoTo ErrHandler
    OpenFTP = False
    
    If Not ao_FTP.LogOnToServer(as_IP, , as_Login, as_Password) Then
        as_ErrorMsg = "Cannot connect to FTP Server: " & as_IP
        Exit Function
    End If
        
    Dim ll_i As Long
    ll_i = InStr(1, as_Login, "/")
    If ll_i <> 0 Then
        ms_FTPRoot = right(as_Login, Len(as_Login) - ll_i) & "\"
    Else
        ms_FTPRoot = ""
    End If

    OpenFTP = True
    Exit Function
ErrHandler:
    Call errorHandler("OpenFTP()")
End Function

#If LIVE = 1 Then
Private Function UploadFile(ByVal ao_FTP As Object, ByVal as_FileName As String, ByVal as_UploadedFile As String, ByRef as_ErrorMsg As String) As Boolean
#Else
Private Function UploadFile(ByVal ao_FTP As ARMSYSCOMLib.ArmFTP, ByVal as_FileName As String, ByVal as_UploadedFile As String, ByRef as_ErrorMsg As String) As Boolean
#End If
On Error GoTo ErrHandler
    Dim ll_BytesTransfered As Long
    Dim ll_BytesTotal As Long
    Dim ll_Result As Long
    
    UploadFile = False
           
    If Not ao_FTP.UploadFileAsynch(as_FileName, as_UploadedFile, FTP_PASIVE) Then
        as_ErrorMsg = "FTP file upload failed. File name:\\" & as_FileName
        Exit Function
    Else
        ' set global value
        ms_copyFile = as_FileName
        ' this consume most of the time of file upload
        While ao_FTP.AsynchOperationProgress(ll_BytesTransfered, ll_BytesTotal, ll_Result) And Not mb_copyAbort
            'll_Result = DoEvents()
            DoEvents
            'Debug.Print ll_BytesTransfered & " : " & ll_BytesTotal & " Result: " & ll_Result
        Wend
        Debug.Print ll_BytesTransfered & " : " & ll_BytesTotal & " Result: " & ll_Result
        
        If ll_BytesTransfered = ll_BytesTotal And Not mb_copyAbort And ll_Result <> 0 Then
                        
            ms_copyFile = ""
        Else
            ' transfer interrupted for some reason
            If mb_copyAbort Then
                ' stop download
                Call ao_FTP.AbortAsynch
                
                as_ErrorMsg = "FTP file upload aborted. File name:\\" & as_FileName
                Exit Function
            Else
                ' other FTP transfer abort
                
                as_ErrorMsg = "FTP file upload interupted. File name:\\" & as_FileName
                Exit Function
            End If
        End If
    End If
    
    UploadFile = True
    Exit Function
ErrHandler:
    Call errorHandler("UploadFile()")
End Function

#If LIVE = 1 Then
Private Function DownloadFile(ByVal ao_FTP As Object, ByVal as_FileName As String, ByVal as_DownloadedFile As String, ByRef as_ErrorMsg As String) As Boolean
#Else
Private Function DownloadFile(ByVal ao_FTP As ARMSYSCOMLib.ArmFTP, ByVal as_FileName As String, ByVal as_DownloadedFile As String, ByRef as_ErrorMsg As String) As Boolean
#End If
On Error GoTo ErrHandler
    Dim ll_BytesTransfered As Long
    Dim ll_BytesTotal As Long
    Dim ll_Result As Long
    
    DownloadFile = False
    
    If Not ao_FTP.DownloadFileAsynch(as_DownloadedFile, as_FileName, FTP_PASIVE) Then
        as_ErrorMsg = "FTP file download failed. File name:\\" & as_FileName
        Exit Function
    Else
        ' set global value
        ms_copyFile = as_DownloadedFile
        ' this consume most of thloade time of file upload
        While ao_FTP.AsynchOperationProgress(ll_BytesTransfered, ll_BytesTotal, ll_Result) And Not mb_copyAbort
            'll_Result = DoEvents()
            DoEvents
            'Debug.Print ll_BytesTransfered & " : " & ll_BytesTotal & " Result: " & ll_Result
        Wend
        'Debug.Print ll_BytesTransfered & " : " & ll_BytesTotal & " Result: " & ll_Result
        
        If ll_BytesTransfered = ll_BytesTotal And Not mb_copyAbort And ll_Result <> 0 Then
                        
            ms_copyFile = ""
        Else
            ' transfer interrupted for some reason
            If mb_copyAbort Then
                ' stop download
                Call ao_FTP.AbortAsynch
                
                as_ErrorMsg = "FTP file download aborted. File name:\\" & as_FileName
                Exit Function
            Else
                ' other FTP transfer abort
                
                as_ErrorMsg = "FTP file download interupted. File name:\\" & as_FileName
                Exit Function
            End If
        End If
    End If
    
    DownloadFile = True
    Exit Function
ErrHandler:
    Call errorHandler("DownloadFile()")
End Function

#If LIVE = 1 Then
Public Function LogInterface(ByVal ao_Db As Object, ByVal al_U_Code As Long) As Boolean
#Else
Public Function LogInterface(ByVal ao_Db As ARMSYSCOMLib.ArmDb, ByVal al_U_Code As Long) As Boolean
#End If

Dim ll_errNumber As Long
Dim ls_ErrSource As String
Dim ls_errDescription As String
Dim ls_LogMessage As String
Dim ls_ILO_Error

  ll_errNumber = Err.Number
  ls_ErrSource = Err.Source
  ls_errDescription = Err.Description
  
  If Err.Number > 0 Then
    ls_ILO_Error = mo_ILO.ILO_Error + Err.Description
  Else
    ls_ILO_Error = mo_ILO.ILO_Error
  End If
  
On Error GoTo errorHandler

Const SQL_LOG_INS = "exec DPC_LogInterface_ins $ILO_Interface$,$ILO_MasterId$,$ILO_Status$,$ILO_RespMsg$,$ILO_Error$,$ILO_Connection$,$ILO_XMLSent$,$ILO_DateSent$,$ILO_XMLResponse$,$ILO_Performance$,$U_Code$"

Dim ls_Request As String

    LogInterface = False
        
    ls_Request = Replace(SQL_LOG_INS, "$ILO_Interface$", mo_Tools.SqlInt(mo_ILO.ILO_Interface), , , vbTextCompare)
    ls_Request = Replace(ls_Request, "$ILO_MasterId$", mo_Tools.SQLStr(mo_ILO.ILO_MasterId), , , vbTextCompare)
    ls_Request = Replace(ls_Request, "$ILO_Status$", mo_Tools.SqlInt(mo_ILO.ILO_Status), , , vbTextCompare)
    ls_Request = Replace(ls_Request, "$ILO_RespMsg$", mo_Tools.SQLStr(mo_ILO.ILO_RespMsg), , , vbTextCompare)
    ls_Request = Replace(ls_Request, "$ILO_Error$", mo_Tools.SQLStr(ls_ILO_Error), , , vbTextCompare)
    ls_Request = Replace(ls_Request, "$ILO_Connection$", mo_Tools.SQLStr(mo_ILO.ILO_Connection), , , vbTextCompare)
    ls_Request = Replace(ls_Request, "$ILO_XMLSent$", mo_Tools.SQLStr(mo_ILO.ILO_XMLSent), , , vbTextCompare)
    ls_Request = Replace(ls_Request, "$ILO_DateSent$", mo_Tools.SqlDate(mo_ILO.ILO_DateSent), , , vbTextCompare)
    ls_Request = Replace(ls_Request, "$ILO_XMLResponse$", mo_Tools.SQLStr(mo_ILO.ILO_XMLResponse), , , vbTextCompare)
    ls_Request = Replace(ls_Request, "$ILO_Performance$", mo_Tools.SqlDbl(mo_ILO.ILO_Performance), , , vbTextCompare)
    ls_Request = Replace(ls_Request, "$U_Code$", mo_Tools.SqlInt(al_U_Code), , , vbTextCompare)

    Call mo_Tools.ExecuteSQLSafe(ao_Db, ls_Request)
    
    LogInterface = True
    
    Err.Number = ll_errNumber
    Err.Source = ls_ErrSource
    Err.Description = ls_errDescription
    
    Exit Function
  
errorHandler:
    
  Call errorHandler("LogInterface")
End Function

Public Function ClearLogInterface() As Boolean
On Error GoTo errorHandler

    ClearLogInterface = False
            
    mo_ILO.ILO_Interface = 0
    mo_ILO.ILO_MasterId = ""
    mo_ILO.ILO_Status = eDPCInterfaceStatus.isNone
    mo_ILO.ILO_RespMsg = ""
    mo_ILO.ILO_Error = ""
    mo_ILO.ILO_Connection = ""
    mo_ILO.ILO_XMLSent = ""
    mo_ILO.ILO_DateSent = Now()
    mo_ILO.ILO_XMLResponse = ""
    mo_ILO.ILO_Performance = 0
        
    ClearLogInterface = True
    
    Exit Function
  
errorHandler:
    
  Call errorHandler("ClearLogInterface")
End Function

Private Function ReplaceCommonPlaceholders(ByVal as_Request As String) As String
On Error GoTo ErrHandler

  as_Request = Replace(as_Request, "$Z_Creator$", mo_Tools.SqlInt(ml_U_Code), , , vbTextCompare)
  as_Request = Replace(as_Request, "$U_Code$", mo_Tools.SqlInt(ml_U_Code), , , vbTextCompare)
  as_Request = Replace(as_Request, "$Z_Last_Upd_User$", mo_Tools.SqlInt(ml_U_Code), , , vbTextCompare)
  as_Request = Replace(as_Request, "$Language_Code$", mo_Tools.SQLStr(ms_Language_Code), , , vbTextCompare)
  ReplaceCommonPlaceholders = as_Request
  Exit Function
ErrHandler:
  Call errorHandler("ReplaceCommonPlaceholders")
End Function

' Standard error handler
Private Sub errorHandler(ByVal as_Fct As String)
  
    Call Err.Raise(Err.Number, as_Fct & SEP1 & Err.Source, Err.Description)
End Sub



