Imports System.Xml
Imports System.Configuration
Imports DevExpress.Xpo
Imports SISBusiness.Module
Imports DevExpress.Data.Filtering
Imports System.Collections.Specialized

Public Module GetGLAccounts
    Public Sub GLAccountImport(_XML As XmlDocument, _errorLogFile As String)
        Dim _StartTime As DateTime = Now

        GetCustomers.CustomerImport(_XML, "JsonXML/params/ugyfel", _errorLogFile)

        Dim _decimalSeparator As String = Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator
        Dim _groupSeparator As String = Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberGroupSeparator
        Dim _uow As UnitOfWork
        Dim _Session As New Session
        Dim _Customers As Customers
        _Session.ConnectionString = ConfigurationManager.ConnectionStrings.Item("ConnectionString").ConnectionString
        _Session.Connect()
        If _Session.IsConnected Then



            _uow = New UnitOfWork(_Session.DataLayer)
            _uow.Dictionary.GetDataStoreSchema(GetType(GLAccounts).Assembly)
            InitAuditTrail(_uow)

            Dim _GLAccounts As GLAccounts = _uow.FindObject(Of GLAccounts) _
                                            (CriteriaOperator.Parse("PartnerType=0 and CustomersFrom=? and Customers.CustomerNumber=? and DocumentNumber=?", _
                                                                    ConfigurationManager.AppSettings("CustomersFrom").ToString, _XML.SelectSingleNode("JsonXML/params/ugyfelszam").InnerText.ToString, _
                                                                    _XML.SelectSingleNode("JsonXML/params/szamlasorszam").InnerText.ToString))
            Dim _GLRows As GLRows
            Dim _BruttoHUF As Double = 0, _BruttoDEV As Double = 0
            Dim _VATHUF As Double = 0, _VATDEV As Double = 0
            Dim _NettoHUF As Double = 0, _NettoDEV As Double = 0
            Dim _GUID As Guid = Guid.NewGuid
            Dim _NV_Controlling As NameValueCollection = ConfigurationManager.GetSection("Services_Controlling")
            Dim _NV_CostHolder As NameValueCollection = ConfigurationManager.GetSection("Services_CostHolder")
            Dim _NV_VAT As NameValueCollection = ConfigurationManager.GetSection("Services_VAT")

            If _GLAccounts Is Nothing Then


                _Customers = _uow.FindObject(Of Customers)(CriteriaOperator.Parse("CustomerNumber=?", _XML.SelectSingleNode("JsonXML/params/ugyfelszam").InnerText.ToString))

                If _Customers Is Nothing Then
                    WriteErrorLog("Nincs ügyfél rögzítve ! -> " + _XML.SelectSingleNode("JsonXML/params/ügyfelszam").InnerText.ToString, _errorLogFile)
                    Exit Sub
                End If


                _GLAccounts = New GLAccounts(_uow)
                _GLAccounts.IsEditable = True
                _GLAccounts.IsStorno = False
                _GLAccounts.PartnerType = ePartnerType.eReceivables
                _GLAccounts.Customers = _Customers
                _GLAccounts.CustomersFrom = _uow.FindObject(Of CustomersFrom)(CriteriaOperator.Parse("Oid=?", ConfigurationManager.AppSettings("CustomersFrom").ToString))
                _GLAccounts.ConnectInfo = _XML.SelectSingleNode("JsonXML/params/szamlasorszam").InnerText.ToString
                _GLAccounts.DocumentNumber = _XML.SelectSingleNode("JsonXML/params/szamlasorszam").InnerText.ToString
                _GLAccounts.DateCreated = _XML.SelectSingleNode("JsonXML/params/kiallitas").InnerText.ToString
                _GLAccounts.DateExecution = _XML.SelectSingleNode("JsonXML/params/teljesites").InnerText.ToString
                _GLAccounts.DatePayment = _XML.SelectSingleNode("JsonXML/params/hatarido").InnerText.ToString
                _GLAccounts.NoteHeader = _XML.SelectSingleNode("JsonXML/params/megjegyzes").InnerText.ToString
                _GLAccounts.CurrencyName = _uow.FindObject(Of CurrencyName)(CriteriaOperator.Parse("ShortName='HUF'"))
                _GLAccounts.PaymentOption = _uow.FindObject(Of PaymentOption)(CriteriaOperator.Parse("ShortName='ÁTUTALÁS'"))



                Dim _XmlNodeList As XmlNodeList = _XML.SelectNodes("JsonXML/params/szamlasorok")
                For Each _XmlNode As XmlNode In _XmlNodeList
                    If _XmlNode.HasChildNodes Then
                        For Each _XmlNode_szamlasorok As XmlNode In _XmlNode.ChildNodes


                            _GLAccounts.row_Controlling = _uow.FindObject(Of Controlling)(CriteriaOperator.Parse("Oid=?", _NV_Controlling(_XmlNode_szamlasorok.SelectSingleNode("szolgaltatas/szolgaltatascsoport/id").InnerText)))
                            _GLAccounts.row_CostHolder = _uow.FindObject(Of CostHolder)(CriteriaOperator.Parse("Oid=?", _NV_CostHolder(_XmlNode_szamlasorok.SelectSingleNode("szolgaltatas/szolgaltatascsoport/id").InnerText)))
                            _GLAccounts.row_VAT = _uow.FindObject(Of VAT)(CriteriaOperator.Parse("Oid=?", _NV_VAT(_XmlNode_szamlasorok.SelectSingleNode("afanev").InnerText)))

                            _GLAccounts.row_ChartOfAccounts = _GLAccounts.row_Controlling.GetChartOfAccounts(_GLAccounts.DateExecution.Year, False)

                            _GLAccounts.row_AmountDEV = 0
                            _GLAccounts.row_AmountHUF = CDbl(Replace(_XmlNode_szamlasorok.SelectSingleNode("nettoar").InnerText, ".", _decimalSeparator))

                            _GLAccounts.row_DateVAT = _GLAccounts.DateExecution


                            _GLAccounts.row_NoteRows = _XmlNode_szamlasorok.SelectSingleNode("megnevezes").InnerText + vbNewLine + _XmlNode_szamlasorok.SelectSingleNode("megjegyzes").InnerText
                            _GLAccounts.row_UniqueObjects = Nothing
                            _GLAccounts.row_JobNumberObjects = Nothing
                            _GLAccounts.row_CostPlace = Nothing

                            _GLAccounts.row_ConnectInfo = _GLAccounts.ConnectInfo

                            If _GLAccounts.PartnerType = ePartnerType.eReceivables Then
                                _GLAccounts.PartnerType = ePartnerType.eReceivables
                                _GLAccounts.row_CreditChartOfAccounts = _GLAccounts.row_ChartOfAccounts
                                _GLAccounts.row_DebitChartOfAccounts = _GLAccounts.Customers.CustomersGLParameters.GetChartOfAccounts(_GLAccounts.DateExecution.Year, eVATMode.eOut)
                            Else
                                _GLAccounts.PartnerType = ePartnerType.ePayabels
                                _GLAccounts.row_CreditChartOfAccounts = _GLAccounts.Customers.CustomersGLParameters.GetChartOfAccounts(_GLAccounts.DateExecution.Year, eVATMode.eIn)
                                _GLAccounts.row_DebitChartOfAccounts = _GLAccounts.row_ChartOfAccounts
                            End If


                            _BruttoHUF = _GLAccounts.row_AmountHUF
                            If _GLAccounts.row_VAT IsNot Nothing Then
                                If _GLAccounts.row_VAT.InversState = True Then
                                    _VATHUF = Math.Round(_BruttoHUF * _GLAccounts.row_VAT.InversKeyValue, 0, MidpointRounding.AwayFromZero)
                                    _NettoHUF = _BruttoHUF
                                    _BruttoHUF = _NettoHUF + _VATHUF
                                Else
                                    _VATHUF = Math.Round(_BruttoHUF / (1 + _GLAccounts.row_VAT.KeyValue) * _GLAccounts.row_VAT.KeyValue, 0, MidpointRounding.AwayFromZero)
                                    _NettoHUF = _BruttoHUF - _VATHUF
                                End If
                            Else
                                _VATHUF = 0
                                _NettoHUF = _BruttoHUF - _VATHUF
                            End If

                            ' -- ÁFA vizsgálata --------------------------------------------------------------------------------------------
                            ' -- Létrehoz egy sort a nettó összegre ------------------------------------------------------------------------------------------

                            _GLRows = New GLRows(_uow)
                            _GLRows.PartnerType = _GLAccounts.PartnerType
                            If _GLRows.PartnerType = ePartnerType.eReceivables Then
                                _GLRows.DebitAmountHUF = _NettoHUF
                                _GLRows.DebitAmountDEV = _NettoDEV
                            Else
                                _GLRows.CreditAmountHUF = _NettoHUF
                                _GLRows.CreditAmountDEV = _NettoDEV
                            End If
                            _GLRows.AddGLRows(_GLAccounts, _GLAccounts.row_DebitChartOfAccounts, _GLAccounts.row_CreditChartOfAccounts, _
                                              _NettoDEV, _NettoHUF, Nothing, _
                                              _GLAccounts.Customers, _GLAccounts.row_DateVAT, _GLAccounts.row_VAT, _
                                              _GLAccounts.row_NoteRows, _GLAccounts.row_UniqueObjects, _
                                              _GLAccounts.row_Controlling, _GLAccounts.row_JobNumberObjects, _GLAccounts.row_CostPlace, _
                                              _GLAccounts.row_CostHolder, _GLAccounts.row_ConnectInfo, eGLRowsTypeVAT.eNettoRow, _GUID, _
                                              eTransactionType.eNotSet, eCashType.ePartner, _GLAccounts.PartnerType)
                        Next
                    End If
                Next

                '-- ÁFA összesítés egy, egy sorban !
                Dim _XmlNodeList_afaosszesites As XmlNodeList = _XML.SelectNodes("JsonXML/params/afaosszesitesek")
                For Each _XmlNode As XmlNode In _XmlNodeList_afaosszesites
                    If _XmlNode.HasChildNodes Then
                        For Each _XmlNode_afaosszesites As XmlNode In _XmlNode.ChildNodes
                            _VATHUF = CDbl(Replace(_XmlNode_afaosszesites.SelectSingleNode("afa").InnerText, ".", _decimalSeparator))
                            _GLAccounts.row_VAT = _uow.FindObject(Of VAT)(CriteriaOperator.Parse("Oid=?", _NV_VAT(_XmlNode_afaosszesites.SelectSingleNode("afakulcs").InnerText)))

                            _GLAccounts.row_CreditChartOfAccounts = _GLAccounts.row_VAT.GetChartOfAccounts(_GLAccounts.DateExecution.Year, eVATMode.eOut)
                            _GLAccounts.row_DebitChartOfAccounts = _GLAccounts.Customers.CustomersGLParameters.GetChartOfAccounts(_GLAccounts.DateExecution.Year, eVATMode.eOut)
                            _GLRows = New GLRows(_uow)
                            _GLRows.PartnerType = _GLAccounts.PartnerType
                            If _GLRows.PartnerType = ePartnerType.eReceivables Then
                                _GLRows.DebitAmountHUF = _VATHUF
                                _GLRows.DebitAmountDEV = _VATDEV
                            Else
                                _GLRows.CreditAmountHUF = _VATHUF
                                _GLRows.CreditAmountDEV = _VATDEV
                            End If
                            _GLRows.AddGLRows(_GLAccounts, _GLAccounts.row_DebitChartOfAccounts, _GLAccounts.row_CreditChartOfAccounts, _
                                              _VATDEV, _VATHUF, _GLAccounts.row_LiquidAssets, _
                                              _GLAccounts.Customers, _GLAccounts.row_DateVAT, _GLAccounts.row_VAT, _GLAccounts.row_NoteRows, _
                                              _GLAccounts.row_UniqueObjects, _GLAccounts.row_Controlling, _GLAccounts.row_JobNumberObjects, _
                                              _GLAccounts.row_CostPlace, _GLAccounts.row_CostHolder, _GLAccounts.row_ConnectInfo, _
                                              eGLRowsTypeVAT.eVATRow, Nothing, eTransactionType.eNotSet, eCashType.ePartner, _GLAccounts.PartnerType)
                        Next
                    End If
                Next
                '// Számla véglegesítése 
                _GLAccounts.IsEditable = False
                For Each _GLRows In _GLAccounts.GLRows
                    _GLRows.ConnectInfo = _GLAccounts.row_ConnectInfo
                    _GLRows.DateVAT = _GLAccounts.row_DateVAT
                    If _GLRows.GLHeader.CurrencyName.ShortName <> "HUF" Then
                        If _GLAccounts.PartnerType = ePartnerType.ePayabels Then
                            If _GLRows.GLRowsTypeVAT <> eGLRowsTypeVAT.eVATRow Then
                                _GLRows.AmountHUF = Math.Round(Math.Round(_GLAccounts.CurrencyRate, 2, MidpointRounding.AwayFromZero) * Math.Round(_GLRows.AmountDEV, 2, MidpointRounding.AwayFromZero), 0, MidpointRounding.AwayFromZero)
                            End If
                            If _GLRows.GLRowsTypeVAT = eGLRowsTypeVAT.eVATRow Then
                                _GLRows.AmountHUF = Math.Round(Math.Round(_GLAccounts.CurrencyRateVAT, 2, MidpointRounding.AwayFromZero) * Math.Round(_GLRows.AmountDEV, 2, MidpointRounding.AwayFromZero), 0, MidpointRounding.AwayFromZero)
                            End If
                        Else
                            _GLRows.AmountHUF = Math.Round(Math.Round(_GLAccounts.CurrencyRate, 2, MidpointRounding.AwayFromZero) * Math.Round(_GLRows.AmountDEV, 2, MidpointRounding.AwayFromZero), 0, MidpointRounding.AwayFromZero)
                        End If
                    End If
                Next
                _GLAccounts.RecalculateTotal()
            End If
            _uow.CommitChanges()
            SaveAuditTrail(_uow)
            GLFunctions.ReconfigurePCI(_uow, _GLAccounts.CustomersFrom, _GLAccounts.Customers, _GLAccounts.PartnerType, _GLAccounts.ConnectInfo)
            _uow.CommitChanges()
            Dim _EndTime As DateTime = Now
            Dim _ActTime As TimeSpan = _EndTime.Subtract(_StartTime)
            WriteStatisticFile(String.Format("Current time: {0}, Record: [Customer: {1}, GLAccounts: {2}]", _ActTime.ToString, _Customers.Oid_DH, _GLAccounts.DocumentNumber), Environment.CurrentDirectory + "Statistic.txt")
        End If
        If _Session.IsConnected Then _Session.Disconnect()
    End Sub
End Module
