Imports System
Imports System.ComponentModel
Imports System.Collections.Generic
Imports System.Diagnostics
Imports System.Text

Imports DevExpress.ExpressApp
Imports DevExpress.ExpressApp.Actions
Imports DevExpress.Persistent.Base
Imports DevExpress.Data.Filtering
Imports DevExpress.Xpo
Imports DevExpress.ExpressApp.SystemModule
Imports DevExpress.ExpressApp.CloneObject
Imports System.Linq
Imports System.Linq.Expressions
Imports DevExpress.Persistent.Validation
Imports DevExpress.Persistent.BaseImpl
Imports DevExpress.ExpressApp.ConditionalAppearance
Imports DevExpress.ExpressApp.Editors
Imports DevExpress.Xpo.DB

Public Class GLCardVC
    Inherits DevExpress.ExpressApp.ViewController
    Protected selection As ArrayList
    Protected noselect As Boolean = False
    Public Event InitWork(ByVal _Minimum As Long, ByVal _Step As Long, ByVal _Maximum As Long)
    Public Event DoWork()
    Public Event FinalWork
    Private appearanceController As AppearanceController
    Public Sub New()
        MyBase.New()

        selection = New ArrayList
        'This call is required by the Component Designer.
        InitializeComponent()
        RegisterActions(components)

    End Sub
    Protected Overrides Sub OnActivated()
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _User As User
        If _ocur IsNot Nothing Then
            _User = _ocur.GetObjectByKey(Of User)(_ocur.GetKeyValue(SecuritySystem.CurrentUser))
        End If

        'appearanceController = Frame.GetController(Of AppearanceController)()
        'If appearanceController IsNot Nothing Then
        '    AddHandler appearanceController.CustomApplyAppearance, AddressOf appearanceController_CustomApplyAppearance
        '    AddHandler appearanceController.AppearanceApplied, AddressOf appearanceController_AppearanceApplied
        'End If

        MyBase.OnActivated()
        AddHandler View.SelectionChanged, AddressOf view_SelectionChanged
        If View.Id Like "GLCardsHeader_GLCardsRows_ListView" Then
            Frame.GetController(Of LinkUnlinkController)().Active.SetItemValue("", False)
            Frame.GetController(Of NewObjectViewController)().Active.SetItemValue("", False)
            Frame.GetController(Of DeleteObjectsViewController)().Active.SetItemValue("", False)
            Frame.GetController(Of CloneObjectViewController)().Active.SetItemValue("", False)
            Frame.GetController(Of ModificationsController)().Active.SetItemValue("", False)
            Frame.GetController(Of ListViewProcessCurrentObjectController).Active.SetItemValue("", False)
        End If

        If View.Id = "GLCardsHeader_DetailView" Then
            Dim _GLCardsHeader As GLCardsHeader = TryCast(View.SelectedObjects(0), GLCardsHeader)

            If _GLCardsHeader.UserCreated IsNot Nothing Then
                If Not _GLCardsHeader.UserCreated.Equals(_User) Then
                    Frame.GetController(Of ModificationsController).SaveAction.Active.SetItemValue("", False)
                    Frame.GetController(Of ModificationsController).SaveAndCloseAction.Active.SetItemValue("", False)
                    Frame.GetController(Of ModificationsController).SaveAndNewAction.Active.SetItemValue("", False)
                    Frame.GetController(Of DeleteObjectsViewController).Active.SetItemValue("", False)
                    Frame.GetController(Of CloneObjectViewController).Active.SetItemValue("", False)
                    Frame.GetController(Of GLCardVC).aGLCardsQuery.Active.SetItemValue("", False)
                End If
            End If
        End If

        If View.Id = "GLCardsHeader_ListView" Then
            Frame.GetController(Of DeleteObjectsViewController).DeleteAction.TargetObjectsCriteria = "UserCreated.Oid='" & _User.Oid.ToString & "' or 'SysAdmin'='" & SecuritySystem.CurrentUserName & "'"
            Frame.GetController(Of DeleteObjectsViewController).DeleteAction.TargetObjectsCriteriaMode = TargetObjectsCriteriaMode.TrueForAll
        End If
    End Sub
    Protected Overrides Sub OnDeactivated()
        MyBase.OnDeactivated()

        If appearanceController IsNot Nothing Then
            RemoveHandler appearanceController.CustomApplyAppearance, AddressOf appearanceController_CustomApplyAppearance
            RemoveHandler appearanceController.AppearanceApplied, AddressOf appearanceController_AppearanceApplied
        End If

        If View.Id = "GLCardsHeader_DetailView" Then
            Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
            Dim _GLCardsHeader As GLCardsHeader = TryCast(View.SelectedObjects(0), GLCardsHeader)
            Dim _User As User
            If _ocur IsNot Nothing Then
                _User = _ocur.GetObjectByKey(Of User)(_ocur.GetKeyValue(SecuritySystem.CurrentUser))
            End If

            If _GLCardsHeader.UserCreated IsNot Nothing Then
                If Not _GLCardsHeader.UserCreated.Equals(_User) Then
                    Frame.GetController(Of ModificationsController).SaveAction.Active.SetItemValue("", True)
                    Frame.GetController(Of ModificationsController).SaveAndCloseAction.Active.SetItemValue("", True)
                    Frame.GetController(Of ModificationsController).SaveAndNewAction.Active.SetItemValue("", True)
                    Frame.GetController(Of DeleteObjectsViewController).Active.SetItemValue("", True)
                    Frame.GetController(Of CloneObjectViewController).Active.SetItemValue("", True)
                    Frame.GetController(Of GLCardVC).aGLCardsQuery.Active.SetItemValue("", True)
                End If
            End If
        End If
    End Sub

    Private Sub view_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim _GLCardsRows As GLCardsRows
        If View Is Nothing Then Exit Sub

        If View.Id Like "GLCardsHeader_GLCardsRows_ListView" And noselect = False Then
            selection.Clear()
            For Each _GLCardsRows In View.SelectedObjects
                selection.Add(_GLCardsRows)
            Next
        End If

    End Sub

    Private Sub aGLCardsQuery_Execute(ByVal sender As System.Object, ByVal e As DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs) Handles aGLCardsQuery.Execute
        'Frame.GetController(Of ModificationsController).SaveAction.DoExecute()

        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _uow As UnitOfWork = New UnitOfWork(_ocur.Session.DataLayer)
        Dim _COP As String
        Dim _GLCardsHeader As GLCardsHeader = _uow.GetObjectByKey(Of GLCardsHeader)(TryCast(View.SelectedObjects(0), GLCardsHeader).Oid)
        Dim I As Long = 0
        Dim _DebitAmountHUF As Double
        Dim _CreditAmountHUF As Double
        Dim _DebitAmountDEV As Double
        Dim _CreditAmountDEV As Double
        Dim _DateFromCurrentYear As Date



        Dim _GLCardsRows_Collection As New XPCollection(_uow, GetType(GLCardsRows), _
        CriteriaOperator.Parse("GLCardsHeader=?", _GLCardsHeader))
        _uow.Delete(_GLCardsRows_Collection)

        Dim _GLCardsRows As GLCardsRows
        _COP = "GLHeader.CustomersFrom=? and (GLHeader.DateExecution >=? and GLHeader.DateExecution<=?) "
        _COP += " and (AmountHUF<>0) and GLHeader.IsEditable=False"

        If _GLCardsHeader.IsClose = False Then
            _COP += " and (DebitChartOfAccounts.AccountNumber !='492' and CreditChartOfAccounts.AccountNumber != '492')"
        End If
        If _GLCardsHeader.IsOpen = False Then
            _COP += " and (DebitChartOfAccounts.AccountNumber !='491' and CreditChartOfAccounts.AccountNumber != '491')"
        End If

        _COP += " and (DebitChartOfAccounts.AccountNumber = ? or CreditChartOfAccounts.AccountNumber = ?)"

        Dim _GLRows_Collection As New XPCollection(_uow, GetType(GLRows), _
        CriteriaOperator.Parse(_COP, _GLCardsHeader.CustomersFrom, _GLCardsHeader.DateFrom, DateAdd(DateInterval.Minute, 1439, _GLCardsHeader.DateTo.Date), _GLCardsHeader.ChartOfAccount.AccountNumber, _GLCardsHeader.ChartOfAccount.AccountNumber))
        Dim _GLRows As GLRows

        _GLRows_Collection.Sorting.Clear()
        _GLRows_Collection.Sorting.Add(New SortProperty("GetDate(GLHeader.DateExecution)", DB.SortingDirection.Ascending))
        _GLRows_Collection.Sorting.Add(New SortProperty("InAmountHUF", DB.SortingDirection.Descending))
        _GLRows_Collection.Sorting.Add(New SortProperty("OutAmountHUF", DB.SortingDirection.Ascending))
        _GLRows_Collection.Sorting.Add(New SortProperty("GLHeader.DocumentNumber", DB.SortingDirection.Ascending))

        Dim _BallanceRulliringHUF As Double = 0
        Dim _BallanceRulliringDEV As Double = 0
        Dim _RowIndex As Long = 0

        '-- Ide kény egy nyitó sor ..............................................................................
        _DateFromCurrentYear = CDate(Year(_GLCardsHeader.DateFrom) & "/01/01")
        Dim _GLRows_xpquery = New XPQuery(Of GLRows)(_ocur.Session)

        _DebitAmountHUF = 0
        _DebitAmountDEV = 0
        Dim query = From _glr In _GLRows_xpquery
                    Where _glr.DebitChartOfAccounts.AccountNumber = _GLCardsHeader.ChartOfAccount.AccountNumber And _
                          _glr.GLHeader.IsEditable = False And _
                          _glr.GLHeader.DateExecution.Date >= _DateFromCurrentYear And
                          _glr.GLHeader.DateExecution.Date < _GLCardsHeader.DateFrom.Date And
                          _glr.GLHeader IsNot Nothing And _
                          _glr.GLHeader.CustomersFrom.Oid = _GLCardsHeader.CustomersFrom.Oid _
        Group _glr By _glr.DebitChartOfAccounts.AccountNumber Into g = Group _
        Select New With {Key .AmountHUF = g.Sum(Function(inv) (inv.AmountHUF)), _
                         Key .AmountDEV = g.Sum(Function(inv) (inv.AmountDEV))}
        For Each item In query
            _DebitAmountHUF += item.AmountHUF
            _DebitAmountDEV += item.AmountDEV
        Next
        '2.
        _CreditAmountHUF = 0
        _CreditAmountDEV = 0
        query = From _glr In _GLRows_xpquery
                    Where _glr.CreditChartOfAccounts.AccountNumber = _GLCardsHeader.ChartOfAccount.AccountNumber And _
                          _glr.GLHeader.IsEditable = False And _
                          _glr.GLHeader.DateExecution.Date >= _DateFromCurrentYear.Date And
                          _glr.GLHeader.DateExecution.Date < _GLCardsHeader.DateFrom.Date And
                          _glr.GLHeader.CustomersFrom.Oid = _GLCardsHeader.CustomersFrom.Oid _
        Group _glr By _glr.CreditChartOfAccounts.AccountNumber Into g = Group _
        Select New With {Key .AmountHUF = g.Sum(Function(inv) (inv.AmountHUF)), _
                         Key .AmountDEV = g.Sum(Function(inv) (inv.AmountDEV))}

        For Each item In query
            _CreditAmountHUF += item.AmountHUF
            _CreditAmountDEV += item.AmountDEV
        Next
        _GLCardsRows = New GLCardsRows(_uow)
        _GLCardsRows.GLCardsHeader = _GLCardsHeader
        _GLCardsRows.CustomersForm = _GLCardsHeader.CustomersFrom
        _GLCardsRows.ShortNameFrom = _GLCardsHeader.ChartOfAccount.Name
        _GLCardsRows.ShortNameTo = "NYITÓ"
        _BallanceRulliringHUF += _DebitAmountHUF - _CreditAmountHUF
        _BallanceRulliringDEV += _DebitAmountDEV - _CreditAmountDEV
        If _DebitAmountHUF > _CreditAmountHUF Then
            _GLCardsRows.DebitAmountHUF = _DebitAmountHUF - _CreditAmountHUF
        Else
            _GLCardsRows.CreditAmountHUF = _CreditAmountHUF - _DebitAmountHUF
        End If
        If _DebitAmountDEV > _CreditAmountDEV Then
            _GLCardsRows.DebitAmountDEV = _DebitAmountDEV - _CreditAmountDEV
        Else
            _GLCardsRows.CreditAmountDEV = _CreditAmountDEV - _DebitAmountDEV
        End If
        _GLCardsRows.BallanceRulliringHUF = _BallanceRulliringHUF
        _GLCardsRows.BallanceRulliringDEV = _BallanceRulliringDEV
        _RowIndex += 1
        _GLCardsRows.RowIndex = _RowIndex
        _GLCardsRows.Note_Rows = "Nyitó : " & _DateFromCurrentYear.ToString & " - " & _GLCardsHeader.DateFrom.ToString
        _GLCardsRows.Save()
        '// Ha van erre a nyitó dátumra adott pénzeszköt fk. számlára LiquidAssetsrate akkor az lesz anyitó DEV !

        '........................................................................................................
        RaiseEvent InitWork(1, 1, _GLRows_Collection.Count)
        For Each _GLRows In _GLRows_Collection
            I += 1
            RaiseEvent DoWork()

            If _GLRows.DebitChartOfAccounts.AccountNumber = _GLCardsHeader.ChartOfAccount.AccountNumber Then
                _GLCardsRows = New GLCardsRows(_uow)
                _GLCardsRows.GLCardsHeader = _GLCardsHeader
                _GLCardsRows.CustomersForm = _GLCardsHeader.CustomersFrom
                _GLCardsRows.ShortNameFrom = _GLCardsHeader.ChartOfAccount.Name
                _GLCardsRows.ShortNameTo = _GLRows.CreditChartOfAccounts.Name
                _GLCardsRows.DebitAmountHUF = _GLRows.AmountHUF
                _GLCardsRows.DebitAmountDEV = _GLRows.AmountDEV
                If _GLRows.AmountDEV = 0 Then
                    _GLCardsRows.CurrencyRate = 1.0
                Else
                    _GLCardsRows.CurrencyRate = Math.Round(_GLRows.AmountHUF / _GLRows.AmountDEV, 4, MidpointRounding.AwayFromZero)
                End If
                _GLCardsRows.Customers = _GLRows.Customer
                _GLCardsRows.ConnectionInfo = _GLRows.ConnectInfo
                _GLCardsRows.DateExecution = _GLRows.GLHeader.DateExecution
                _BallanceRulliringHUF += _GLRows.AmountHUF
                _BallanceRulliringDEV += _GLRows.AmountDEV
                _GLCardsRows.BallanceRulliringHUF = _BallanceRulliringHUF
                _GLCardsRows.BallanceRulliringDEV = _BallanceRulliringDEV
                _GLCardsRows.DocumentNumber = _GLRows.GLHeader.DocumentNumber

                _GLCardsRows.Controlling = _GLRows.Controlling
                _GLCardsRows.UniqueObjects = _GLRows.UniqueObjects
                _GLCardsRows.JobNumberObjects = _GLRows.JobNumberObjects
                _GLCardsRows.CostHolder = _GLRows.CostHolder
                _GLCardsRows.CostPlace = _GLRows.CostPlace

                _RowIndex += 1
                _GLCardsRows.RowIndex = _RowIndex
                _GLCardsRows.Note_Rows = _GLRows.NoteRows
                _GLCardsRows.GLRows = _GLRows
                _GLCardsRows.Save()
            ElseIf _GLRows.CreditChartOfAccounts.AccountNumber = _GLCardsHeader.ChartOfAccount.AccountNumber Then
                _GLCardsRows = New GLCardsRows(_uow)
                _GLCardsRows.GLCardsHeader = _GLCardsHeader
                _GLCardsRows.CustomersForm = _GLCardsHeader.CustomersFrom
                _GLCardsRows.ShortNameFrom = _GLCardsHeader.ChartOfAccount.Name
                _GLCardsRows.ShortNameTo = _GLRows.DebitChartOfAccounts.Name
                _GLCardsRows.CreditAmountHUF = _GLRows.AmountHUF
                _GLCardsRows.CreditAmountDEV = _GLRows.AmountDEV
                If _GLRows.AmountDEV = 0 Then
                    _GLCardsRows.CurrencyRate = 1.0
                Else
                    _GLCardsRows.CurrencyRate = Math.Round(_GLRows.AmountHUF / _GLRows.AmountDEV, 4, MidpointRounding.AwayFromZero)
                End If
                _GLCardsRows.Customers = _GLRows.Customer
                _GLCardsRows.ConnectionInfo = _GLRows.ConnectInfo
                _GLCardsRows.DateExecution = _GLRows.GLHeader.DateExecution
                _BallanceRulliringHUF -= _GLRows.AmountHUF
                _BallanceRulliringDEV -= _GLRows.AmountDEV
                _GLCardsRows.BallanceRulliringHUF = _BallanceRulliringHUF
                _GLCardsRows.BallanceRulliringDEV = _BallanceRulliringDEV
                _GLCardsRows.DocumentNumber = _GLRows.GLHeader.DocumentNumber

                _GLCardsRows.Controlling = _GLRows.Controlling
                _GLCardsRows.UniqueObjects = _GLRows.UniqueObjects
                _GLCardsRows.JobNumberObjects = _GLRows.JobNumberObjects
                _GLCardsRows.CostHolder = _GLRows.CostHolder
                _GLCardsRows.CostPlace = _GLRows.CostPlace

                _RowIndex += 1
                _GLCardsRows.RowIndex = _RowIndex
                _GLCardsRows.Note_Rows = _GLRows.NoteRows
                _GLCardsRows.GLRows = _GLRows
                _GLCardsRows.Save()
                If I Mod 100 = 0 Then _uow.CommitChanges()
            End If
        Next
        _uow.CommitTransaction()

        _GLCardsHeader.CreateGLRowsStatictics(_uow, _GLCardsHeader.DateFrom, _GLCardsHeader.DateTo, _GLCardsHeader.CustomersFrom, _GLCardsHeader.Oid)

        RaiseEvent FinalWork
        If Frame.GetController(Of RefreshController).RefreshAction.Enabled Then
            Frame.GetController(Of RefreshController).RefreshAction.DoExecute()
        End If
    End Sub
    Private Sub aGLCardsPrint_Execute(sender As System.Object, e As DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs) Handles aGLCardsPrint.Execute
        '-- Ez egy beégetés !!
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _ReportData As ReportData
        Dim _GLCardsHeader As GLCardsHeader = TryCast(View.SelectedObjects(0), GLCardsHeader)

        If _GLCardsHeader IsNot Nothing Then
            _ReportData = _ocur.FindObject(Of ReportData)(CriteriaOperator.Parse("Name=?", "Főkönyvi karton"))

            If _ReportData IsNot Nothing Then
                Frame.GetController(Of Reports.ReportServiceController).ShowPreview(_ReportData, CriteriaOperator.Parse("GLCardsHeader=?", _GLCardsHeader), True)
            Else
                Throw New UserFriendlyException("Nincs beállítva a Főkönyvi karton nyomtatvány !")
            End If
        End If
    End Sub
    Private Sub aViewAttachments_Cards_Execute(sender As System.Object, e As DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs) Handles aViewAttachments_Cards.Execute
        Dim _GLCardsRows As GLCardsRows = TryCast(View.SelectedObjects(0), GLCardsRows)
        Dim _CustomersFrom As CustomersFrom = _GLCardsRows.CustomersForm
        Dim _Customers As Customers = _GLCardsRows.Customers
        Dim _DocumentNumber As String = _GLCardsRows.ConnectionInfo

        ViewAttachments.ViewAttachments(View.ObjectSpace, Frame, _CustomersFrom, _Customers, _DocumentNumber, "")

    End Sub
    Private Sub aViewRegistry_Cards_Execute(sender As System.Object, e As DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs) Handles aViewRegistry_Cards.Execute
        Dim _GLCardsRows As GLCardsRows = TryCast(View.SelectedObjects(0), GLCardsRows)
        Dim _CustomersFrom As CustomersFrom = _GLCardsRows.CustomersForm
        Dim _Customers As Customers = _GLCardsRows.Customers
        Dim _DocumentNumber As String = _GLCardsRows.ConnectionInfo
        ViewRegistry.ViewRegistry(View.ObjectSpace, Application, e, _CustomersFrom, _Customers, _DocumentNumber)
    End Sub
    Private Sub aGLCardsChangeParam_CustomizePopupWindowParams(sender As Object, e As DevExpress.ExpressApp.Actions.CustomizePopupWindowParamsEventArgs) Handles aGLCardsChangeParam.CustomizePopupWindowParams
        Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
        Dim _GLRowsCheck As GLRowsCheck = _onew.CreateObject(Of GLRowsCheck)()
        Dim _GLCardsRows As GLCardsRows = TryCast(View.SelectedObjects(0), GLCardsRows)

        If _GLCardsRows IsNot Nothing Then
            _GLRowsCheck.ChartOfAccountsYear = _onew.FindObject(Of ChartOfAccountsYear)(CriteriaOperator.Parse("AccountYear=?", _GLCardsRows.GLRows.GLHeader.DateExecution.Year))
        Else
            _GLRowsCheck.ChartOfAccountsYear = _onew.FindObject(Of ChartOfAccountsYear)(CriteriaOperator.Parse("AccountYear=?", GetSQLTime(_onew.Session).Year))
        End If

        e.View = Application.CreateDetailView(_onew, "GLRowsCheck_DetailView", False, _GLRowsCheck)
    End Sub
    Private Sub aGLCardsChangeParam_Execute(sender As System.Object, e As DevExpress.ExpressApp.Actions.PopupWindowShowActionExecuteEventArgs) Handles aGLCardsChangeParam.Execute
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _GLRowsCheck As GLRowsCheck = TryCast(e.PopupWindow.View.SelectedObjects(0), GLRowsCheck)
        Dim _GLRows As GLRows
        Dim _GLCardsRows As GLCardsRows
        Dim I As Long = 0
        Dim _Controlling As Controlling
        Dim _JobNumberObjects As JobNumberObjects
        Dim _CostHolder As CostHolder
        Dim _CostPlace As CostPlace
        Dim _UniqueObjects As UniqueObjects
        Dim _DebitChartOfAccounts As ChartOfAccounts
        Dim _CreditChartOfAccounts As ChartOfAccounts

        If _GLRowsCheck.Controlling IsNot Nothing Then
            _Controlling = _ocur.FindObject(Of Controlling)(CriteriaOperator.Parse("Oid=?", _GLRowsCheck.Controlling.Oid), True)
            If _Controlling.Children.Count > 0 Then
                Throw New Exception(String.Format("Nem gyermekobjektum. <<{0}>> Csak gyermekobjektum választható ki !", _Controlling.Name))
                Exit Sub
            End If
        Else
            _Controlling = Nothing
        End If
        If _GLRowsCheck.JobNumberObjects IsNot Nothing Then
            _JobNumberObjects = _ocur.FindObject(Of JobNumberObjects)(CriteriaOperator.Parse("Oid=?", _GLRowsCheck.JobNumberObjects.Oid), True)
        Else
            _JobNumberObjects = Nothing
        End If
        If _GLRowsCheck.CostHolder IsNot Nothing Then
            _CostHolder = _ocur.FindObject(Of CostHolder)(CriteriaOperator.Parse("Oid=?", _GLRowsCheck.CostHolder.Oid), True)
        Else
            _CostHolder = Nothing
        End If
        If _GLRowsCheck.CostPlace IsNot Nothing Then
            _CostPlace = _ocur.FindObject(Of CostPlace)(CriteriaOperator.Parse("Oid=?", _GLRowsCheck.CostPlace.Oid), True)
        Else
            _CostPlace = Nothing
        End If
        If _GLRowsCheck.UniqueObjects IsNot Nothing Then
            _UniqueObjects = _ocur.FindObject(Of UniqueObjects)(CriteriaOperator.Parse("Oid=?", _GLRowsCheck.UniqueObjects.Oid), True)
        Else
            _UniqueObjects = Nothing
        End If
        If _GLRowsCheck.DebitChartOfAccounts IsNot Nothing Then
            _DebitChartOfAccounts = _ocur.FindObject(Of ChartOfAccounts)(CriteriaOperator.Parse("Oid=?", _GLRowsCheck.DebitChartOfAccounts.Oid), True)
        Else
            _DebitChartOfAccounts = Nothing
        End If
        If _GLRowsCheck.CreditChartOfAccounts IsNot Nothing Then
            _CreditChartOfAccounts = _ocur.FindObject(Of ChartOfAccounts)(CriteriaOperator.Parse("Oid=?", _GLRowsCheck.CreditChartOfAccounts.Oid), True)
        Else
            _CreditChartOfAccounts = Nothing
        End If

        If _DebitChartOfAccounts IsNot Nothing And _CreditChartOfAccounts IsNot Nothing Then
            If _DebitChartOfAccounts.Oid = _CreditChartOfAccounts.Oid Then
                Throw New Exception("*A tartozik és a követel számlaszám NEM lehet azonos !")
                Exit Sub
            End If
        End If

        RaiseEvent InitWork(1, 1, View.SelectedObjects.Count)
        For Each _GLCardsRows In View.SelectedObjects
            I += 1
            RaiseEvent DoWork()
            _GLRows = _GLCardsRows.GLRows
            If _GLRows IsNot Nothing Then
                If _Controlling IsNot Nothing Then _GLRows.Controlling = _Controlling
                If _JobNumberObjects IsNot Nothing Then _GLRows.JobNumberObjects = _JobNumberObjects
                If _CostHolder IsNot Nothing Then _GLRows.CostHolder = _CostHolder
                If _CostPlace IsNot Nothing Then _GLRows.CostPlace = _CostPlace
                If _UniqueObjects IsNot Nothing Then _GLRows.UniqueObjects = _UniqueObjects
                If _DebitChartOfAccounts IsNot Nothing Then _GLRows.DebitChartOfAccounts = _DebitChartOfAccounts
                If _CreditChartOfAccounts IsNot Nothing Then _GLRows.CreditChartOfAccounts = _CreditChartOfAccounts
                _GLRows.Save()
            End If
            If I Mod 100 = 0 Then _ocur.CommitChanges()
        Next
        _ocur.CommitChanges()
        RaiseEvent FinalWork

        Dim nestedFrame As NestedFrame = TryCast(Frame, NestedFrame)
        If nestedFrame IsNot Nothing Then
            Dim parentView As View = nestedFrame.View
            parentView.ObjectSpace.Refresh()
        End If

    End Sub
    Private Sub aGLCardsDivideRows_CustomizePopupWindowParams(sender As Object, e As DevExpress.ExpressApp.Actions.CustomizePopupWindowParamsEventArgs) Handles aGLCardsDivideRows.CustomizePopupWindowParams
        Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
        Dim _GLRowsDivideH As GLRowsDivideH = _onew.CreateObject(Of GLRowsDivideH)()
        Dim _GLCardsRows As GLCardsRows = TryCast(View.SelectedObjects(0), GLCardsRows)

        If _GLCardsRows.GLRows IsNot Nothing Then
            If _GLCardsRows.GLRows.PartnerType = ePartnerType.ePayabels Or _GLCardsRows.GLRows.PartnerType = ePartnerType.eReceivables Then
                _GLRowsDivideH.GLRows_Oid = _GLCardsRows.GLRows.Oid
                _GLRowsDivideH.row_Customers = _onew.GetObject(_GLCardsRows.GLRows.Customer)
                _GLRowsDivideH.row_PartnerType = _GLCardsRows.GLRows.PartnerType
                e.View = Application.CreateDetailView(_onew, "GLRowsDivideH_DetailView_ConnectionDivide", False, _GLRowsDivideH)
            Else
                _GLRowsDivideH.GLRows_Oid = _GLCardsRows.GLRows.Oid
                e.View = Application.CreateDetailView(_onew, "GLRowsDivideH_DetailView", False, _GLRowsDivideH)
            End If
        End If
    End Sub
    Private Sub aGLCardsDivideRows_Execute(sender As System.Object, e As DevExpress.ExpressApp.Actions.PopupWindowShowActionExecuteEventArgs) Handles aGLCardsDivideRows.Execute
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _GLRowsDivideH As GLRowsDivideH = TryCast(e.PopupWindow.View.SelectedObjects(0), GLRowsDivideH)
        Dim _GLCardsRows As GLCardsRows = TryCast(View.SelectedObjects(0), GLCardsRows)
        Dim _GLRows As GLRows = _GLCardsRows.GLRows

        If _GLRows IsNot Nothing Then
            _GLRows.DivideRows(_ocur, _GLRows, _GLRowsDivideH, True)
            _GLCardsRows.IsDivided = True
            _GLCardsRows.Save()
            _ocur.CommitChanges()
        End If
    End Sub
    Private Sub aGLCardsMakeConnection_CustomizePopupWindowParams(sender As Object, e As DevExpress.ExpressApp.Actions.CustomizePopupWindowParamsEventArgs) Handles aGLCardsMakeConnection.CustomizePopupWindowParams
        '-- POPUP ----------------------------------------------------------------------------------------------------------------

        Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
        Dim _PartnerConnectionInfoCleanUp_PopupWindow As PartnerConnectionInfoCleanUp_PopupWindow
        Dim _GLCardRows As GLCardsRows = TryCast(View.SelectedObjects(0), GLCardsRows)

        _PartnerConnectionInfoCleanUp_PopupWindow = _onew.FindObject(Of PartnerConnectionInfoCleanUp_PopupWindow)(CriteriaOperator.Parse("Oid=Oid"), True)
        If _PartnerConnectionInfoCleanUp_PopupWindow Is Nothing Then
            _PartnerConnectionInfoCleanUp_PopupWindow = _onew.CreateObject(Of PartnerConnectionInfoCleanUp_PopupWindow)()
        End If

        _PartnerConnectionInfoCleanUp_PopupWindow.ConnectInfo = _GLCardRows.ConnectionInfo
        _PartnerConnectionInfoCleanUp_PopupWindow.Save()
        _onew.CommitChanges()

        noselect = True

        e.View = Application.CreateDetailView(_onew, _PartnerConnectionInfoCleanUp_PopupWindow, True)
    End Sub
    Private Sub aGLCardsMakeConnection_Execute(sender As System.Object, e As DevExpress.ExpressApp.Actions.PopupWindowShowActionExecuteEventArgs) Handles aGLCardsMakeConnection.Execute
        '-- Ez a kijelölt sorokat összepontozza ---------------------------------------------------------------------------------
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _GLCardsRows As GLCardsRows
        Dim _PartnerConnectionInfoCleanUp_PopupWindow As PartnerConnectionInfoCleanUp_PopupWindow = TryCast(e.PopupWindow.View.SelectedObjects(0), PartnerConnectionInfoCleanUp_PopupWindow)

        For Each _GLCardsRows In selection
            Select Case _GLCardsRows.GLRows.GLHeader.GLDocumentType
                Case eGLDocumentType.eGLBank, eGLDocumentType.eGLCassa, eGLDocumentType.eGLCompensation, eGLDocumentType.eGLMixed
                    If _GLCardsRows.GLRows IsNot Nothing Then
                        _GLCardsRows.GLRows.ConnectInfo = _PartnerConnectionInfoCleanUp_PopupWindow.ConnectInfo
                        _GLCardsRows.GLRows.Save()
                        _GLCardsRows.ConnectionInfo = _PartnerConnectionInfoCleanUp_PopupWindow.ConnectInfo
                        _GLCardsRows.Save()
                    End If
            End Select
        Next
        _ocur.CommitChanges()
        View.Refresh()
        noselect = False
    End Sub
    Private Sub aGLCardsOpenDocument_Execute(sender As System.Object, e As DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs) Handles aGLCardsOpenDocument.Execute
        '-- Karton sorához tartozó eredeti dokumentum megnyitása
        Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _GLCardsRows As GLCardsRows = TryCast(View.SelectedObjects(0), GLCardsRows)
        If _GLCardsRows IsNot Nothing Then
            e.ShowViewParameters.CreatedView = Application.CreateDetailView(_onew, _onew.GetObject(_GLCardsRows.GLRows.GLHeader))
        End If

    End Sub

    Protected Overridable Sub CustomizeDisabledEditorsAppearance(ByVal e As ApplyAppearanceEventArgs)
    End Sub
    Private Sub appearanceController_AppearanceApplied(ByVal sender As Object, ByVal e As ApplyAppearanceEventArgs)
        If e.AppearanceObject.Enabled = False Then
            CustomizeDisabledEditorsAppearance(e)
        End If
    End Sub
    Private Sub appearanceController_CustomApplyAppearance(ByVal sender As Object, ByVal e As ApplyAppearanceEventArgs)
        Dim _GLCardsRows As GLCardsRows = TryCast(e.ContextObjects(0), GLCardsRows)
        If e.ItemType = "Action" Then Exit Sub
        'If _GLCardsRows IsNot Nothing Then
        '    If _GLCardsRows.IsDivided = True Then
        '        CType(e.Item, IAppearanceFormat).FontStyle = Drawing.FontStyle.Bold
        '        CType(e.Item, IAppearanceFormat).FontColor = Drawing.Color.Red
        '        e.Handled = True
        '    End If
        'End If
    End Sub

    Private Sub aViewPCIDetail_GLCard_Execute(sender As System.Object, e As DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs) Handles aViewPCIDetail_GLCard.Execute
        Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _GLCardsRows As GLCardsRows = TryCast(View.SelectedObjects(0), GLCardsRows)

        ViewPDCI.ViewPDCIDetail(_onew, Application, e, _GLCardsRows.GLRows.GLHeader.CustomersFrom, _
                          _GLCardsRows.GLRows.Customer, _GLCardsRows.GLRows.PartnerType, _
                          _GLCardsRows.GLRows.ConnectInfo)
    End Sub

    Private Sub aPCICheckDetail_GLCard_Execute(sender As System.Object, e As DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs) Handles aPCICheckDetail_GLCard.Execute
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _uow As New UnitOfWork(_ocur.Session.DataLayer)
        Dim _GLCardsRows As GLCardsRows

        RaiseEvent InitWork(1, 1, View.SelectedObjects.Count)
        For Each _GLCardsRows In View.SelectedObjects
            RaiseEvent DoWork()
            GLFunctions.ReconfigurePCI(_uow, _GLCardsRows.GLRows.GLHeader.CustomersFrom, _GLCardsRows.GLRows.Customer, _GLCardsRows.GLRows.PartnerType, _GLCardsRows.GLRows.ConnectInfo)

        Next
        RaiseEvent FinalWork
    End Sub

    Private Sub aGLCardsQueryPCI_Execute(sender As Object, e As SimpleActionExecuteEventArgs) Handles aGLCardsQueryPCI.Execute
        Dim _GLCardsHeader As GLCardsHeader = TryCast(View.SelectedObjects(0), GLCardsHeader)
        Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
        Dim _uow As New UnitOfWork(_onew.Session.DataLayer)
        Dim _uow_2 As New UnitOfWork(_onew.Session.DataLayer)

        Dim _GLCardsRowsPCI As GLCardsRowsPCI

        If _GLCardsHeader Is Nothing Then Exit Sub

        _GLCardsHeader = _uow.GetObjectByKey(Of GLCardsHeader)(_GLCardsHeader.Oid)

        _uow.Delete(_GLCardsHeader.GLCardsRowsPCI)
        _uow.CommitChanges()

        Dim _GLCardsRows_xpquery = New XPQuery(Of GLCardsRows)(_uow)

        Dim query = From _GLCardsRows In _GLCardsRows_xpquery
                    Where _GLCardsRows.GLCardsHeader.Oid = _GLCardsHeader.Oid
        Group _GLCardsRows By _GLCardsRows.GLRows.Customer, _GLCardsRows.GLRows.PartnerType, _GLCardsRows.GLRows.ConnectInfo Into g = Group _
        Select New With {Key .Customers = Customer,
                         Key .PartnerType = PartnerType,
                         Key .ConnectInfo = ConnectInfo,
                         Key .DebitAmountHUF = g.Sum(Function(inv) (inv.DebitAmountHUF)), _
                         Key .CreditAmountHUF = g.Sum(Function(inv) (inv.CreditAmountHUF))}

        RaiseEvent InitWork(1, 1, query.Count)
        For Each item In query
            RaiseEvent DoWork()
            _GLCardsRowsPCI = New GLCardsRowsPCI(_uow)
            _GLCardsRowsPCI.GLCardsHeader = _GLCardsHeader
            _GLCardsRowsPCI.Customers = item.Customers
            _GLCardsRowsPCI.PartnerType = item.PartnerType
            _GLCardsRowsPCI.ConnectInfo = item.ConnectInfo
            _GLCardsRowsPCI.BallanceHUF_Card_Debit = Math.Round(item.DebitAmountHUF, 0, MidpointRounding.AwayFromZero)
            _GLCardsRowsPCI.BallanceHUF_Card_Credit = Math.Round(item.CreditAmountHUF, 0, MidpointRounding.AwayFromZero)
            If item.PartnerType = ePartnerType.ePayabels Then
                _GLCardsRowsPCI.BallanceHUF_Card = Math.Round(item.CreditAmountHUF, 0, MidpointRounding.AwayFromZero) - Math.Round(item.DebitAmountHUF, 0, MidpointRounding.AwayFromZero)
            Else
                _GLCardsRowsPCI.BallanceHUF_Card = Math.Round(item.DebitAmountHUF, 0, MidpointRounding.AwayFromZero) - Math.Round(item.CreditAmountHUF, 0, MidpointRounding.AwayFromZero)
            End If

            '// Folyószámlában rákeresés !!!
            _GLCardsRowsPCI.BallanceHUF_PCI = Me.GetPCIBallance(_uow_2, _GLCardsHeader.CustomersFrom, item.Customers, item.PartnerType, item.ConnectInfo, _GLCardsHeader.DateTo)
            _GLCardsRowsPCI.DifferentHUF = Math.Round(_GLCardsRowsPCI.BallanceHUF_Card - _GLCardsRowsPCI.BallanceHUF_PCI, 0, MidpointRounding.AwayFromZero)

            _uow.CommitChanges()
        Next
        RaiseEvent FinalWork
        If Frame.GetController(Of RefreshController).RefreshAction.Enabled Then
            Frame.GetController(Of RefreshController).RefreshAction.DoExecute()
        End If
    End Sub
    Private Function GetPCIBallance(_uow As UnitOfWork, _CustomersFrom As CustomersFrom, _Customers As Customers, _PartnerType As ePartnerType, _ConnectInfo As String, _DateClose As Date) As Double
        Dim _SQL As String = ""

        Dim _SelectStatementResultRow As SelectStatementResultRow
        Dim _SelectedData As DevExpress.Xpo.DB.SelectedData = Nothing

        Dim _GetPCIBallance As Double = 0

        If _Customers Is Nothing Then Exit Function
        If _CustomersFrom Is Nothing Then Exit Function

        Select Case GLOBAL_SQLType
            Case eSQLType.MySQL, eSQLType.MSSQL
                _SQL = " SELECT SUM(t1.BallanceHUF)"

                _SQL += " FROM PCIDetail t1"

                _SQL += " WHERE t1.PartnerType=" & _PartnerType
                _SQL += String.Format(" AND t1.CustomersFrom='{0}'", _CustomersFrom.Oid)
                _SQL += String.Format(" AND t1.Customers='{0}'", _Customers.Oid)
                _SQL += String.Format(" AND t1.ConnectInfo='{0}'", _ConnectInfo)
                _SQL += String.Format(" AND t1.DateExecution<'{0}-{1}-{2}'", _DateClose.AddDays(1).Year, _DateClose.AddDays(1).Month, _DateClose.AddDays(1).Day)

            Case eSQLType.PostgreSQL

        End Select

        _SelectedData = _uow.ExecuteQuery(_SQL)
        If _SelectedData.ResultSet.Length > 0 Then
            For Each _SelectStatementResultRow In _SelectedData.ResultSet(0).Rows
                _GetPCIBallance = _SelectStatementResultRow.Values(0)
            Next
        End If

        Return Math.Round(_GetPCIBallance, 0, MidpointRounding.AwayFromZero)

    End Function

    Private Sub aViewPCIDGroup_GLCrads_Execute(sender As Object, e As SimpleActionExecuteEventArgs) Handles aViewPCIDGroup_GLCrads.Execute
        Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _GLCardsRowsPCI As GLCardsRowsPCI = TryCast(View.SelectedObjects(0), GLCardsRowsPCI)

        ViewPDCI.ViewPDCIDetail(_onew, Application, e, _GLCardsRowsPCI.GLCardsHeader.CustomersFrom, _
                          _GLCardsRowsPCI.Customers, _GLCardsRowsPCI.PartnerType, _
                          _GLCardsRowsPCI.ConnectInfo)
    End Sub

    Private Sub aViewPCIDGroup_GLDetails_GLCards_Execute(sender As Object, e As SimpleActionExecuteEventArgs) Handles aViewPCIDGroup_GLDetails_GLCards.Execute
        Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _GLCardsRowsPCI As GLCardsRowsPCI = TryCast(View.SelectedObjects(0), GLCardsRowsPCI)

        ViewPDCI.ViewGLDetails(_onew, Application, e, _GLCardsRowsPCI.GLCardsHeader.CustomersFrom, _
                          _GLCardsRowsPCI.Customers, _GLCardsRowsPCI.PartnerType, _
                          _GLCardsRowsPCI.ConnectInfo)
    End Sub

    Private Sub aViewAttachments_GLCards_Execute(sender As Object, e As SimpleActionExecuteEventArgs) Handles aViewAttachments_GLCards.Execute
        Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _GLCardsRowsPCI As GLCardsRowsPCI = TryCast(View.SelectedObjects(0), GLCardsRowsPCI)

        ViewAttachments.ViewAttachments(_ocur, Frame, _GLCardsRowsPCI.GLCardsHeader.CustomersFrom, _
                                             _GLCardsRowsPCI.Customers, _GLCardsRowsPCI.ConnectInfo, _
                                             "")
    End Sub

    Private Sub aPCICheckDetail_GLCardsRowsPCI_Execute(sender As Object, e As SimpleActionExecuteEventArgs) Handles aPCICheckDetail_GLCardsRowsPCI.Execute
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _uow As New UnitOfWork(_ocur.Session.DataLayer)
        Dim _GLCardsRowsPCI As GLCardsRowsPCI = TryCast(View.SelectedObjects(0), GLCardsRowsPCI)

        RaiseEvent InitWork(1, 1, View.SelectedObjects.Count)
        For Each _GLCardsRowsPCI In View.SelectedObjects
            RaiseEvent DoWork()
            GLFunctions.ReconfigurePCI(_uow, _GLCardsRowsPCI.GLCardsHeader.CustomersFrom, _GLCardsRowsPCI.Customers, _GLCardsRowsPCI.PartnerType, _GLCardsRowsPCI.ConnectInfo)

        Next
        RaiseEvent FinalWork
    End Sub

    Private Sub aGLCardsQueryABRQuery_Execute(sender As Object, e As SimpleActionExecuteEventArgs) Handles aGLCardsQueryABRQuery.Execute
        Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
        Dim _uow As New UnitOfWork(_onew.Session.DataLayer)
        Dim _GLCardsHeader As GLCardsHeader = _uow.GetObjectByKey(Of GLCardsHeader)(TryCast(View.SelectedObjects(0), GLCardsHeader).Oid)
        Dim _GLAccounts As GLAccounts = Nothing
        Dim _ABRQueryRowsDetail As ABRQueryRowsDetail = Nothing
        Dim _ABRQueryRows As ABRQueryRows = Nothing
        Dim _BallanceHUF As Double = 0
        Dim _DiffDay As Long = 0
        Dim i As Long = 0

        _uow.Delete(_GLCardsHeader.ABRQueryRowsDetail)
        _uow.Delete(_GLCardsHeader.ABRQueryRows)

        Dim _GLCardsRows_xpquery = New XPQuery(Of GLCardsRows)(_uow)

        Dim query = From _GLCardsRows In _GLCardsRows_xpquery
                    Where _GLCardsRows.GLCardsHeader.Oid = _GLCardsHeader.Oid
        Group _GLCardsRows By _GLCardsRows.GLRows.Customer, _GLCardsRows.GLRows.PartnerType, _GLCardsRows.GLRows.ConnectInfo Into g = Group _
        Select New With {Key .Customers = Customer,
                         Key .PartnerType = PartnerType,
                         Key .ConnectInfo = ConnectInfo,
                         Key .DebitAmountHUF = g.Sum(Function(inv) (inv.DebitAmountHUF)), _
                         Key .CreditAmountHUF = g.Sum(Function(inv) (inv.CreditAmountHUF))}
        RaiseEvent InitWork(1, 1, query.Count)
        For Each item In query
            RaiseEvent DoWork()

            If item.PartnerType = ePartnerType.ePayabels Then
                _BallanceHUF = Math.Round(item.CreditAmountHUF, 0, MidpointRounding.AwayFromZero) - Math.Round(item.DebitAmountHUF, 0, MidpointRounding.AwayFromZero)
            Else
                _BallanceHUF = Math.Round(item.DebitAmountHUF, 0, MidpointRounding.AwayFromZero) - Math.Round(item.CreditAmountHUF, 0, MidpointRounding.AwayFromZero)
            End If

            If _BallanceHUF <> 0 Then
                _ABRQueryRowsDetail = New ABRQueryRowsDetail(_uow)
                _ABRQueryRowsDetail.GLCardsHeader = _GLCardsHeader
                _ABRQueryRowsDetail.BallanceHUF = _BallanceHUF
                _ABRQueryRowsDetail.CustomersFrom = _GLCardsHeader.CustomersFrom
                _ABRQueryRowsDetail.Customers = item.Customers
                _ABRQueryRowsDetail.PartnerType = item.PartnerType
                _ABRQueryRowsDetail.ConnectInfo = item.ConnectInfo

                _GLAccounts = _uow.FindObject(Of GLAccounts)(CriteriaOperator.Parse("CustomersFrom=? and Customers=? and PartnerType=? and ConnectInfo=?", _GLCardsHeader.CustomersFrom, item.Customers, item.PartnerType, item.ConnectInfo))
                If _GLAccounts Is Nothing Then
                    '// Nyitott P.Ü. teljesítés !!!
                    _ABRQueryRowsDetail.D00_OpenLiquidHUF = _BallanceHUF
                Else
                    _ABRQueryRowsDetail.AmountHUF = _GLAccounts.AmountHUFBrutto
                    _ABRQueryRowsDetail.DateExecution = _GLAccounts.DateExecution
                    _ABRQueryRowsDetail.DatePayment = _GLAccounts.DatePayment

                    If _GLCardsHeader.DateTo.Date <= GetSQLTime(_onew.Session).Date Then
                        _DiffDay = DateDiff(DateInterval.Day, _GLAccounts.DatePayment.Date, _GLCardsHeader.DateTo.Date)
                    Else
                        _DiffDay = DateDiff(DateInterval.Day, _GLAccounts.DatePayment.Date, GetSQLTime(_uow).Date)
                    End If

                    _ABRQueryRowsDetail.DelayedDay = _DiffDay
                    Select Case _DiffDay
                        Case Is <= 0
                            _ABRQueryRowsDetail.D01_NotExpiredHUF = _BallanceHUF
                        Case 1 To 15
                            _ABRQueryRowsDetail.D02_001_015HUF = _BallanceHUF
                        Case 16 To 30
                            _ABRQueryRowsDetail.D03_016_030HUF = _BallanceHUF
                        Case 31 To 60
                            _ABRQueryRowsDetail.D04_031_060HUF = _BallanceHUF
                        Case 61 To 90
                            _ABRQueryRowsDetail.D05_061_090HUF = _BallanceHUF
                        Case 91 To 150
                            _ABRQueryRowsDetail.D06_091_150HUF = _BallanceHUF
                        Case 151 To 365
                            _ABRQueryRowsDetail.D07_151_365HUF = _BallanceHUF
                        Case Is > 365
                            _ABRQueryRowsDetail.D08_OverOneYearHUF = _BallanceHUF
                    End Select
                End If
            End If
        Next
        _uow.CommitChanges()
        RaiseEvent FinalWork

        i = 0
        Dim PCI2 As New XPQuery(Of ABRQueryRowsDetail)(_uow)
        Dim query2 = From _PCI2 In PCI2
                    Where _PCI2.GLCardsHeader Is _GLCardsHeader
                    Group _PCI2 By
                          _PCI2.CustomersFrom, _
                          _PCI2.Customers, _
                          _PCI2.PartnerType, _
                          _PCI2.CurrencyName_Account Into g = Group
                   Order By CustomersFrom, Customers, PartnerType, CurrencyName_Account
                   Select New With {Key .CustomersFrom = CustomersFrom, _
                             Key .Customers = Customers, _
                             Key .PartnerType = PartnerType,
                             Key .CurrencyName_Account = CurrencyName_Account,
                             Key .BallanceDEV = g.Sum(Function(inv) inv.BallanceDEV),
                             Key .BallanceHUF = g.Sum(Function(inv) inv.BallanceHUF),
                             Key .D00_OpenLiquidDEV = g.Sum(Function(inv) inv.D00_OpenLiquidDEV),
                             Key .D00_OpenLiquidHUF = g.Sum(Function(inv) inv.D00_OpenLiquidHUF),
                             Key .D02_001_015DEV = g.Sum(Function(inv) inv.D02_001_015DEV),
                             Key .D02_001_015HUF = g.Sum(Function(inv) inv.D02_001_015HUF),
                             Key .D03_016_030DEV = g.Sum(Function(inv) inv.D03_016_030DEV),
                             Key .D03_016_030HUF = g.Sum(Function(inv) inv.D03_016_030HUF),
                             Key .D04_031_060DEV = g.Sum(Function(inv) inv.D04_031_060DEV),
                             Key .D04_031_060HUF = g.Sum(Function(inv) inv.D04_031_060HUF),
                             Key .D05_061_090DEV = g.Sum(Function(inv) inv.D05_061_090DEV),
                             Key .D05_061_090HUF = g.Sum(Function(inv) inv.D05_061_090HUF),
                             Key .D06_091_150DEV = g.Sum(Function(inv) inv.D06_091_150DEV),
                             Key .D06_091_150HUF = g.Sum(Function(inv) inv.D06_091_150HUF),
                             Key .D07_151_365DEV = g.Sum(Function(inv) inv.D07_151_365DEV),
                             Key .D07_151_365HUF = g.Sum(Function(inv) inv.D07_151_365HUF),
                             Key .D01_NotExpiredHUF = g.Sum(Function(inv) inv.D01_NotExpiredHUF),
                             Key .D01_NotExpiredDEV = g.Sum(Function(inv) inv.D01_NotExpiredDEV),
                             Key .D08_OverOneYearHUF = g.Sum(Function(inv) inv.D08_OverOneYearHUF),
                             Key .D08_OverOneYearDEV = g.Sum(Function(inv) inv.D08_OverOneYearDEV)}
        RaiseEvent InitWork(1, 1, query2.Count)

        For Each item In query2
            i += 1
            RaiseEvent DoWork()
            _ABRQueryRows = New ABRQueryRows(_uow)
            _ABRQueryRows.GLCardsHeader = _GLCardsHeader
            _ABRQueryRows.BallanceHUF = item.BallanceHUF
            _ABRQueryRows.CurrencyName_Account = item.CurrencyName_Account
            _ABRQueryRows.Customers = item.Customers
            _ABRQueryRows.CustomersFrom = item.CustomersFrom
            _ABRQueryRows.PartnerType = item.PartnerType

            _ABRQueryRows.D00_OpenLiquidHUF = item.D00_OpenLiquidHUF
            _ABRQueryRows.D01_NotExpiredHUF = item.D01_NotExpiredHUF
            _ABRQueryRows.D02_001_015HUF = item.D02_001_015HUF
            _ABRQueryRows.D03_016_030HUF = item.D03_016_030HUF
            _ABRQueryRows.D04_031_060HUF = item.D04_031_060HUF
            _ABRQueryRows.D05_061_090HUF = item.D05_061_090HUF
            _ABRQueryRows.D06_091_150HUF = item.D06_091_150HUF
            _ABRQueryRows.D07_151_365HUF = item.D07_151_365HUF
            _ABRQueryRows.D08_OverOneYearHUF = item.D08_OverOneYearHUF
        Next
        _uow.CommitChanges()
        RaiseEvent FinalWork

    End Sub

    Private Sub aGenerateOpenClosePCIRecord_GLCards_CustomizePopupWindowParams(sender As Object, e As CustomizePopupWindowParamsEventArgs) Handles aGenerateOpenClosePCIRecord_GLCards.CustomizePopupWindowParams
        Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
        Dim _GLAccountsOpenClosePCIPopup As GLAccountsOpenClosePCIPopup = _onew.CreateObject(Of GLAccountsOpenClosePCIPopup)()

        e.View = Application.CreateDetailView(_onew, "GLAccountsOpenClosePCIPopup_DetailView", True, _GLAccountsOpenClosePCIPopup)
    End Sub

    Private Sub aGenerateOpenClosePCIRecord_GLCards_Execute(sender As Object, e As PopupWindowShowActionExecuteEventArgs) Handles aGenerateOpenClosePCIRecord_GLCards.Execute
        Dim _GLAccountsOpenClosePCIPopup As GLAccountsOpenClosePCIPopup = TryCast(e.PopupWindow.View.SelectedObjects(0), GLAccountsOpenClosePCIPopup)
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _uow As New UnitOfWork(_ocur.Session.DataLayer)
        Dim _GLCardsRowsPCI As GLCardsRowsPCI

        RaiseEvent InitWork(1, 1, View.SelectedObjects.Count)

        For Each _GLCardsRowsPCI In View.SelectedObjects
            RaiseEvent DoWork()
            Frame.GetController(Of GLAccountsVC).MakeOpenClosePCI(_uow, _GLCardsRowsPCI.GLCardsHeader.CustomersFrom, _GLCardsRowsPCI.Customers, _GLCardsRowsPCI.PartnerType, _GLCardsRowsPCI.ConnectInfo, _GLAccountsOpenClosePCIPopup.YearClose, _GLAccountsOpenClosePCIPopup.GLRowsTypeSelect)
        Next
        RaiseEvent FinalWork
    End Sub

    Private Sub aGenerateOpenClosePCIRecord_Storno_GLCards_CustomizePopupWindowParams(sender As Object, e As CustomizePopupWindowParamsEventArgs) Handles aGenerateOpenClosePCIRecord_Storno_GLCards.CustomizePopupWindowParams
        Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
        Dim _GLAccountsOpenClosePCIPopup As GLAccountsOpenClosePCIPopup = _onew.CreateObject(Of GLAccountsOpenClosePCIPopup)()

        e.View = Application.CreateDetailView(_onew, "GLAccountsOpenClosePCIPopup_DetailView", True, _GLAccountsOpenClosePCIPopup)
    End Sub

    Private Sub aGenerateOpenClosePCIRecord_Storno_GLCards_Execute(sender As Object, e As PopupWindowShowActionExecuteEventArgs) Handles aGenerateOpenClosePCIRecord_Storno_GLCards.Execute
        Dim _GLAccountsOpenClosePCIPopup As GLAccountsOpenClosePCIPopup = TryCast(e.PopupWindow.View.SelectedObjects(0), GLAccountsOpenClosePCIPopup)
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _uow As New UnitOfWork(_ocur.Session.DataLayer)
        Dim _GLCardsRowsPCI As GLCardsRowsPCI

        RaiseEvent InitWork(1, 1, View.SelectedObjects.Count)

        For Each _GLCardsRowsPCI In View.SelectedObjects
            RaiseEvent DoWork()
            Frame.GetController(Of GLAccountsVC).RemoveOpenClosePCI(_uow, _GLCardsRowsPCI.GLCardsHeader.CustomersFrom, _GLCardsRowsPCI.Customers, _GLCardsRowsPCI.PartnerType, _GLCardsRowsPCI.ConnectInfo, _GLAccountsOpenClosePCIPopup.YearClose)
        Next
        RaiseEvent FinalWork
    End Sub
End Class
