

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.Xpo
Imports DevExpress.Data.Filtering
Imports DevExpress.ExpressApp.SystemModule
Imports System.Linq
Imports DevExpress.ExpressApp.Editors
Imports DevExpress.Persistent.BaseImpl
Imports DevExpress.ExpressApp.Utils

Public Class AssetsPCIVC
    Inherits DevExpress.ExpressApp.ViewController
    Public Event InitWork(ByVal _Minimum As Long, ByVal _Step As Long, ByVal _Maximum As Long)
    Public Event DoWork()
    Public Event FinalWork
    Public selection As ArrayList
    Private _ActiveForm As Boolean
    Public Sub New()
        MyBase.New()
        InitializeComponent()
        RegisterActions(components)
        selection = New ArrayList
    End Sub
    Protected Overrides Sub OnActivated()
        MyBase.OnActivated()

        Frame.GetController(Of AssetsPCIVC).aPrintAssetsHandling.Active.SetItemValue("", False)
        Frame.GetController(Of AssetsPCIVC).aPrintAssetsHandling2.Active.SetItemValue("", False)
        Frame.GetController(Of AssetsPCIVC).aPrintAssetsHandling3.Active.SetItemValue("", False)
        Frame.GetController(Of AssetsPCIVC).aCreateLateCharges.Active.SetItemValue("", False)
        Frame.GetController(Of AssetsPCIVC).aCountLateCharges.Active.SetItemValue("", False)
        Frame.GetController(Of AssetsPCIVC).aNoAssetsHandling.Active.SetItemValue("", False)
        Frame.GetController(Of AssetsPCIVC).aViewLateCharges.Active.SetItemValue("", False)

        If View.Id Like "AssetsPCIHeader_AssetsPCIRows_ListView*" Then
            Frame.GetController(Of DevExpress.ExpressApp.SystemModule.ModificationsController).Active.SetItemValue("", False)
            Frame.GetController(Of DevExpress.ExpressApp.SystemModule.DeleteObjectsViewController).Active.SetItemValue("", False)
            Frame.GetController(Of DevExpress.ExpressApp.SystemModule.LinkUnlinkController)().Active.SetItemValue("", False)
            Frame.GetController(Of DevExpress.ExpressApp.CloneObject.CloneObjectViewController)().Active.SetItemValue("", False)
            Frame.GetController(Of DevExpress.ExpressApp.SystemModule.NewObjectViewController).Active.SetItemValue("", False)
            Frame.GetController(Of ListViewProcessCurrentObjectController).Active.SetItemValue("", False)
            Frame.GetController(Of AssetsPCIVC).aViewLateCharges.Active.SetItemValue("", True)
        End If
        If View.Id = "PCIGroup_ListView_DelayedPay" Then
            Frame.GetController(Of AssetsPCIVC).aCreateLateCharges.Active.SetItemValue("", True)
            Frame.GetController(Of AssetsPCIVC).aViewLateCharges.Active.SetItemValue("", True)
        End If
        If View.Id = "AssetsHandling_ListView_Active" Then
            Frame.GetController(Of DevExpress.ExpressApp.SystemModule.ModificationsController).Active.SetItemValue("", False)
            If TryCast(SecuritySystem.CurrentUser, User).UserName <> "SysAdmin" Then Frame.GetController(Of DevExpress.ExpressApp.SystemModule.DeleteObjectsViewController).Active.SetItemValue("", False)
            Frame.GetController(Of DevExpress.ExpressApp.SystemModule.LinkUnlinkController)().Active.SetItemValue("", False)
            Frame.GetController(Of DevExpress.ExpressApp.CloneObject.CloneObjectViewController)().Active.SetItemValue("", False)
            Frame.GetController(Of DevExpress.ExpressApp.SystemModule.NewObjectViewController).Active.SetItemValue("", False)

            Frame.GetController(Of AssetsPCIVC).aPrintAssetsHandling.Active.SetItemValue("", True)
            Frame.GetController(Of AssetsPCIVC).aPrintAssetsHandling2.Active.SetItemValue("", True)
            Frame.GetController(Of AssetsPCIVC).aPrintAssetsHandling3.Active.SetItemValue("", True)
            Frame.GetController(Of AssetsPCIVC).aCreateLateCharges.Active.SetItemValue("", True)
            Frame.GetController(Of AssetsPCIVC).aCreateLateCharges.Enabled.SetItemValue("", True)
            Frame.GetController(Of AssetsPCIVC).aCountLateCharges.Active.SetItemValue("", True)
            Frame.GetController(Of AssetsPCIVC).aNoAssetsHandling.Active.SetItemValue("", True)

            AddHandler View.SelectionChanged, AddressOf view_SelectionChanged
        End If
        If View.Id = "AssetsHandling_ListView_All" Then
            Frame.GetController(Of DevExpress.ExpressApp.SystemModule.ModificationsController).Active.SetItemValue("", False)
            If TryCast(SecuritySystem.CurrentUser, User).UserName <> "SysAdmin" Then Frame.GetController(Of DevExpress.ExpressApp.SystemModule.DeleteObjectsViewController).Active.SetItemValue("", False)
            Frame.GetController(Of DevExpress.ExpressApp.SystemModule.LinkUnlinkController)().Active.SetItemValue("", False)
            Frame.GetController(Of DevExpress.ExpressApp.CloneObject.CloneObjectViewController)().Active.SetItemValue("", False)
            Frame.GetController(Of DevExpress.ExpressApp.SystemModule.NewObjectViewController).Active.SetItemValue("", False)

            Frame.GetController(Of AssetsPCIVC).aPrintAssetsHandling.Active.SetItemValue("", True)
            Frame.GetController(Of AssetsPCIVC).aPrintAssetsHandling2.Active.SetItemValue("", True)
            Frame.GetController(Of AssetsPCIVC).aPrintAssetsHandling3.Active.SetItemValue("", True)
            Frame.GetController(Of AssetsPCIVC).aCreateLateCharges.Active.SetItemValue("", True)
            Frame.GetController(Of AssetsPCIVC).aCreateLateCharges.Enabled.SetItemValue("", False)
            Frame.GetController(Of AssetsPCIVC).aCountLateCharges.Active.SetItemValue("", True)
            Frame.GetController(Of AssetsPCIVC).aNoAssetsHandling.Active.SetItemValue("", True)

            AddHandler View.SelectionChanged, AddressOf view_SelectionChanged
        End If

    End Sub
    Protected Overrides Sub OnDeactivated()
        MyBase.OnDeactivated()
        Frame.GetController(Of DevExpress.ExpressApp.Validation.PersistenceValidationController).Active.SetItemValue("", True)
        Frame.GetController(Of DevExpress.ExpressApp.CloneObject.CloneObjectViewController)().Active.SetItemValue("", True)
        Frame.GetController(Of AssetsPCIVC).aPrintAssetsHandling.Active.SetItemValue("", False)
        Frame.GetController(Of AssetsPCIVC).aPrintAssetsHandling2.Active.SetItemValue("", False)
        Frame.GetController(Of AssetsPCIVC).aPrintAssetsHandling3.Active.SetItemValue("", False)
        Frame.GetController(Of AssetsPCIVC).aCreateLateCharges.Active.SetItemValue("", False)

        If View.Id Like "AssetsPCIHeader_AssetsPCIRows_ListView*" Then
            Frame.GetController(Of DevExpress.ExpressApp.SystemModule.ModificationsController).Active.SetItemValue("", True)
            Frame.GetController(Of DevExpress.ExpressApp.SystemModule.DeleteObjectsViewController).Active.SetItemValue("", True)
            Frame.GetController(Of DevExpress.ExpressApp.SystemModule.LinkUnlinkController)().Active.SetItemValue("", True)
            Frame.GetController(Of DevExpress.ExpressApp.CloneObject.CloneObjectViewController)().Active.SetItemValue("", True)
            Frame.GetController(Of DevExpress.ExpressApp.SystemModule.NewObjectViewController).Active.SetItemValue("", True)
            Frame.GetController(Of ListViewProcessCurrentObjectController).Active.SetItemValue("", True)
        End If

        If View.Id = "AssetsHandling_ListView_Active" Then
            Frame.GetController(Of DevExpress.ExpressApp.SystemModule.ModificationsController).Active.SetItemValue("", True)
            Frame.GetController(Of DevExpress.ExpressApp.SystemModule.DeleteObjectsViewController).Active.SetItemValue("", True)
            Frame.GetController(Of DevExpress.ExpressApp.SystemModule.LinkUnlinkController)().Active.SetItemValue("", True)
            Frame.GetController(Of DevExpress.ExpressApp.CloneObject.CloneObjectViewController)().Active.SetItemValue("", True)
            Frame.GetController(Of DevExpress.ExpressApp.SystemModule.NewObjectViewController).Active.SetItemValue("", True)

            RemoveHandler View.SelectionChanged, AddressOf view_SelectionChanged
        End If

        If View.Id = "AssetsHandling_ListView_All" Then
            Frame.GetController(Of DevExpress.ExpressApp.SystemModule.ModificationsController).Active.SetItemValue("", True)
            Frame.GetController(Of DevExpress.ExpressApp.SystemModule.DeleteObjectsViewController).Active.SetItemValue("", True)
            Frame.GetController(Of DevExpress.ExpressApp.SystemModule.LinkUnlinkController)().Active.SetItemValue("", True)
            Frame.GetController(Of DevExpress.ExpressApp.CloneObject.CloneObjectViewController)().Active.SetItemValue("", True)
            Frame.GetController(Of DevExpress.ExpressApp.SystemModule.NewObjectViewController).Active.SetItemValue("", True)

            RemoveHandler View.SelectionChanged, AddressOf view_SelectionChanged
        End If

    End Sub
    Private Sub view_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim _AssetsHandling As AssetsHandling = Nothing

        If View.SelectedObjects.Count > 0 Then
            _AssetsHandling = TryCast(View.SelectedObjects(0), AssetsHandling)
        Else
            Frame.GetController(Of AssetsPCIVC).aPrintAssetsHandling.Enabled.SetItemValue("", False)
            Frame.GetController(Of AssetsPCIVC).aPrintAssetsHandling2.Enabled.SetItemValue("", False)
            Frame.GetController(Of AssetsPCIVC).aPrintAssetsHandling3.Enabled.SetItemValue("", False)
        End If

        If _AssetsHandling IsNot Nothing Then
            If _AssetsHandling.IsActive = True Then
                If _AssetsHandling.QueueIndex = 0 Then
                    Frame.GetController(Of AssetsPCIVC).aPrintAssetsHandling.Enabled.SetItemValue("", True)
                    Frame.GetController(Of AssetsPCIVC).aPrintAssetsHandling2.Enabled.SetItemValue("", False)
                    Frame.GetController(Of AssetsPCIVC).aPrintAssetsHandling3.Enabled.SetItemValue("", False)
                End If
                If _AssetsHandling.QueueIndex = 1 Then
                    Frame.GetController(Of AssetsPCIVC).aPrintAssetsHandling.Enabled.SetItemValue("", False)
                    Frame.GetController(Of AssetsPCIVC).aPrintAssetsHandling2.Enabled.SetItemValue("", True)
                    Frame.GetController(Of AssetsPCIVC).aPrintAssetsHandling3.Enabled.SetItemValue("", False)
                End If
                If _AssetsHandling.QueueIndex = 2 Then
                    Frame.GetController(Of AssetsPCIVC).aPrintAssetsHandling.Enabled.SetItemValue("", False)
                    Frame.GetController(Of AssetsPCIVC).aPrintAssetsHandling2.Enabled.SetItemValue("", False)
                    Frame.GetController(Of AssetsPCIVC).aPrintAssetsHandling3.Enabled.SetItemValue("", True)
                End If
            Else
                Frame.GetController(Of AssetsPCIVC).aPrintAssetsHandling.Enabled.SetItemValue("", False)
                Frame.GetController(Of AssetsPCIVC).aPrintAssetsHandling2.Enabled.SetItemValue("", False)
                Frame.GetController(Of AssetsPCIVC).aPrintAssetsHandling3.Enabled.SetItemValue("", False)
            End If
        End If
    End Sub
    Private Sub aPrintAssetsHandling_Execute(sender As System.Object, e As DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs) Handles aPrintAssetsHandling.Execute
        '-- Ez egy beégetés !!
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _ReportData As ReportData
        Dim _AssetsHandlingParameter As AssetsHandlingParameter
        Dim _AssetsHandling As AssetsHandling = TryCast(View.SelectedObjects(0), AssetsHandling)

        If _AssetsHandling Is Nothing Then Exit Sub
        _AssetsHandlingParameter = _ocur.FindObject(Of AssetsHandlingParameter)(CriteriaOperator.Parse("CustomersFrom=?", _AssetsHandling.CustomersFrom))
        If _AssetsHandlingParameter IsNot Nothing Then
            _ReportData = _AssetsHandlingParameter.ReportData
            If _ReportData IsNot Nothing Then
                Frame.GetController(Of Reports.ReportServiceController).ShowPreview(_ReportData, CriteriaOperator.Parse("QueueIndex=0 and IsActive=True and NoAssetsHandling=False and CustomersFrom=?", _AssetsHandling.CustomersFrom), True)
            Else
                Throw New UserFriendlyException("Nincs beállítva a fizetési felszólítási nyomtatvány.")
            End If
        End If
    End Sub
    Private Sub aPrintAssetsHandling2_Execute(sender As System.Object, e As DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs) Handles aPrintAssetsHandling2.Execute
        '-- Ez egy beégetés !!
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _ReportData As ReportData
        Dim _AssetsHandlingParameter As AssetsHandlingParameter
        Dim _AssetsHandling As AssetsHandling = TryCast(View.SelectedObjects(0), AssetsHandling)

        If _AssetsHandling Is Nothing Then Exit Sub
        _AssetsHandlingParameter = _ocur.FindObject(Of AssetsHandlingParameter)(CriteriaOperator.Parse("CustomersFrom=?", _AssetsHandling.CustomersFrom))
        If _AssetsHandlingParameter IsNot Nothing Then
            _ReportData = _AssetsHandlingParameter.ReportData2
            If _ReportData IsNot Nothing Then
                Frame.GetController(Of Reports.ReportServiceController).ShowPreview(_ReportData, CriteriaOperator.Parse("QueueIndex=1 and IsActive=True and NoAssetsHandling=False and CustomersFrom=?", _AssetsHandling.CustomersFrom), True)
            Else
                Throw New UserFriendlyException("Nincs beállítva a fizetési felszólítási nyomtatvány.")
            End If
        End If
    End Sub
    Private Sub aPrintAssetsHandling3_Execute(sender As Object, e As SimpleActionExecuteEventArgs) Handles aPrintAssetsHandling3.Execute
        '-- Ez egy beégetés !!
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _ReportData As ReportData
        Dim _AssetsHandlingParameter As AssetsHandlingParameter
        Dim _AssetsHandling As AssetsHandling = TryCast(View.SelectedObjects(0), AssetsHandling)

        If _AssetsHandling Is Nothing Then Exit Sub
        _AssetsHandlingParameter = _ocur.FindObject(Of AssetsHandlingParameter)(CriteriaOperator.Parse("CustomersFrom=?", _AssetsHandling.CustomersFrom))
        If _AssetsHandlingParameter IsNot Nothing Then
            _ReportData = _AssetsHandlingParameter.ReportData3
            If _ReportData IsNot Nothing Then
                Frame.GetController(Of Reports.ReportServiceController).ShowPreview(_ReportData, CriteriaOperator.Parse("QueueIndex=2 and IsActive=True and NoAssetsHandling=False and CustomersFrom=?", _AssetsHandling.CustomersFrom), True)
            Else
                Throw New UserFriendlyException("Nincs beállítva a fizetési felszólítási nyomtatvány.")
            End If
        End If
    End Sub

    Private Sub aGenerateAssetsReport_Execute(sender As System.Object, e As DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs) Handles aGenerateAssetsReport.Execute
        '-- Az adott záródátumra vonatkozó partner connection infot adja meg
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _uow As UnitOfWork = New UnitOfWork(_ocur.Session.DataLayer)

        Dim _AssetsPCIRows As AssetsPCIRows

        Dim _AssetsPCIHeader As AssetsPCIHeader = _uow.GetObjectByKey(Of AssetsPCIHeader) _
            (TryCast(View.SelectedObjects(0), AssetsPCIHeader).Oid)

        If _AssetsPCIHeader Is Nothing Then Exit Sub

        _AssetsPCIHeader.Save()


        Dim _AssetsPCIRows_Collection As New XPCollection(Of AssetsPCIRows) _
            (_uow, CriteriaOperator.Parse("AssetsPCIHeader=?", _AssetsPCIHeader))
        _uow.Delete(_AssetsPCIRows_Collection)
        _uow.CommitChanges()
        Try
            '-- Lekérdezés, adott teljesítési dátumig történő lekérdezés LINQ paranccsal
            '_PCI.Customers.IsAssetsHandling = True And
            Dim _AssetsPCICustomersFrom_XPQuery As New XPQuery(Of AssetsPCICustomersFrom)(_uow)
            Dim cquery = From _AssetsPCICustomersFrom_LINQ In _AssetsPCICustomersFrom_XPQuery
                         Where _AssetsPCICustomersFrom_LINQ.AssetsPCIHeader.Oid = _AssetsPCIHeader.Oid
                         Select _AssetsPCICustomersFrom_LINQ.CustomersFrom.Oid


            Dim PCI As New XPQuery(Of PCIDetail)(_uow, True)
            Dim query = From _PCI In PCI
            Where _PCI.DateExecution.Date <= _AssetsPCIHeader.DateClose.Date And
                  _PCI.Customers IsNot Nothing And
                  String.IsNullOrEmpty(_PCI.ConnectInfo) = False And
                  _PCI.PartnerType = ePartnerType.eReceivables And
                  _PCI.Customers.IsAssetsHandling = True And
                  cquery.Contains(_PCI.CustomersFrom.Oid) And
                 _PCI.DatePayment_Account.Date <= _AssetsPCIHeader.DateClose.Date And
                  String.IsNullOrEmpty(_PCI.DateExecution_Account) = False
                                  Group _PCI By _PCI.CustomersFrom, _
                              _PCI.Customers, _
                              _PCI.PartnerType, _
                              _PCI.CurrencyName_Account, _
                              _PCI.ConnectInfo Into g = Group _
                Select New With {Key .CustomersFrom = CustomersFrom, _
                                 Key .Customers = Customers, _
                                 Key .PartnerType = PartnerType, _
                                 Key .ConnectInfo = ConnectInfo, _
                                 Key .CurrencyName_Account = CurrencyName_Account,
                                 Key .BallanceHUF = g.Sum(Function(inv) inv.BallanceHUF), _
                                 Key .BallanceDEV = g.Sum(Function(inv) inv.BallanceDEV), _
                                 Key .AmountHUF_Account = g.Sum(Function(inv) inv.AmountHUF_Account), _
                                 Key .AmountDEV_Account = g.Sum(Function(inv) inv.AmountDEV_Account), _
                                 Key .DatePayment = g.Max(Function(inv) inv.DatePayment_Account), _
                                 Key .DelayedDay = g.Max(Function(inv) inv.DelayedDay), _
                                 Key .DateExecution = g.Max(Function(inv) inv.DateExecution), _
                                 Key .DateCreated = g.Max(Function(inv) inv.DateCreated)}


            RaiseEvent InitWork(1, 1, query.Count)
            For Each item In query
                If item.CurrencyName_Account IsNot Nothing Then
                    If Math.Round(item.BallanceHUF, 0, MidpointRounding.AwayFromZero) > 0 And item.CurrencyName_Account.ShortName = "HUF" Then
                        If _AssetsPCIHeader.QueryCustomersFrom = True Then
                            _AssetsPCIRows = New AssetsPCIRows(_uow)
                            _AssetsPCIRows.AssetsPCIHeader = _AssetsPCIHeader
                            _AssetsPCIRows.CustomersFrom = item.CustomersFrom
                            _AssetsPCIRows.Customers = item.Customers
                            _AssetsPCIRows.DateExecution = item.DateExecution
                            _AssetsPCIRows.DateCreated = item.DateCreated
                            _AssetsPCIRows.DatePayment = item.DatePayment
                            _AssetsPCIRows.BallanceDEV = item.BallanceDEV
                            _AssetsPCIRows.BallanceHUF = item.BallanceHUF
                            _AssetsPCIRows.ConnectInfo = item.ConnectInfo
                            _AssetsPCIRows.CurrencyName = item.CurrencyName_Account
                            _AssetsPCIRows.DatePayment = item.DatePayment
                            _AssetsPCIRows.DelayedDay = item.DelayedDay
                            _AssetsPCIRows.PartnerType = item.PartnerType
                            _AssetsPCIRows.AmountDEV_Account = item.AmountDEV_Account
                            _AssetsPCIRows.AmountHUF_Account = item.AmountHUF_Account
                        Else
                            If TryCast(item.Customers, CustomersFrom) Is Nothing Then
                                _AssetsPCIRows = New AssetsPCIRows(_uow)
                                _AssetsPCIRows.AssetsPCIHeader = _AssetsPCIHeader
                                _AssetsPCIRows.CustomersFrom = item.CustomersFrom
                                _AssetsPCIRows.Customers = item.Customers
                                _AssetsPCIRows.DateExecution = item.DateExecution
                                _AssetsPCIRows.DateCreated = item.DateCreated
                                _AssetsPCIRows.DatePayment = item.DatePayment
                                _AssetsPCIRows.BallanceDEV = item.BallanceDEV
                                _AssetsPCIRows.BallanceHUF = item.BallanceHUF
                                _AssetsPCIRows.ConnectInfo = item.ConnectInfo
                                _AssetsPCIRows.CurrencyName = item.CurrencyName_Account
                                _AssetsPCIRows.DatePayment = item.DatePayment
                                _AssetsPCIRows.DelayedDay = item.DelayedDay
                                _AssetsPCIRows.PartnerType = item.PartnerType
                                _AssetsPCIRows.AmountDEV_Account = item.AmountDEV_Account
                                _AssetsPCIRows.AmountHUF_Account = item.AmountHUF_Account
                            End If

                        End If
                    End If
                    If Math.Round(item.BallanceDEV, 2, MidpointRounding.AwayFromZero) > 0 And item.CurrencyName_Account.ShortName <> "HUF" Then
                        If TryCast(item.Customers, CustomersFrom) Is Nothing Then
                            _AssetsPCIRows = New AssetsPCIRows(_uow)
                            _AssetsPCIRows.AssetsPCIHeader = _AssetsPCIHeader
                            _AssetsPCIRows.CustomersFrom = item.CustomersFrom
                            _AssetsPCIRows.Customers = item.Customers
                            _AssetsPCIRows.DateExecution = item.DateExecution
                            _AssetsPCIRows.DateCreated = item.DateCreated
                            _AssetsPCIRows.DatePayment = item.DatePayment
                            _AssetsPCIRows.BallanceDEV = item.BallanceDEV
                            _AssetsPCIRows.BallanceHUF = item.BallanceHUF
                            _AssetsPCIRows.ConnectInfo = item.ConnectInfo
                            _AssetsPCIRows.CurrencyName = item.CurrencyName_Account
                            _AssetsPCIRows.DatePayment = item.DatePayment
                            _AssetsPCIRows.DelayedDay = item.DelayedDay
                            _AssetsPCIRows.PartnerType = item.PartnerType
                            _AssetsPCIRows.AmountDEV_Account = item.AmountDEV_Account
                            _AssetsPCIRows.AmountHUF_Account = item.AmountHUF_Account
                        Else
                            If TryCast(item.Customers, CustomersFrom) IsNot Nothing Then
                                _AssetsPCIRows = New AssetsPCIRows(_uow)
                                _AssetsPCIRows.AssetsPCIHeader = _AssetsPCIHeader
                                _AssetsPCIRows.CustomersFrom = item.CustomersFrom
                                _AssetsPCIRows.Customers = item.Customers
                                _AssetsPCIRows.DateExecution = item.DateExecution
                                _AssetsPCIRows.DateCreated = item.DateCreated
                                _AssetsPCIRows.DatePayment = item.DatePayment
                                _AssetsPCIRows.BallanceDEV = item.BallanceDEV
                                _AssetsPCIRows.BallanceHUF = item.BallanceHUF
                                _AssetsPCIRows.ConnectInfo = item.ConnectInfo
                                _AssetsPCIRows.CurrencyName = item.CurrencyName_Account
                                _AssetsPCIRows.DatePayment = item.DatePayment
                                _AssetsPCIRows.DelayedDay = item.DelayedDay
                                _AssetsPCIRows.PartnerType = item.PartnerType
                                _AssetsPCIRows.AmountDEV_Account = item.AmountDEV_Account
                                _AssetsPCIRows.AmountHUF_Account = item.AmountHUF_Account
                            End If
                        End If
                    End If
                End If
                RaiseEvent DoWork()
            Next
            _uow.CommitChanges()
            RaiseEvent FinalWork
        Catch ex As Exception
            RaiseEvent FinalWork
            MsgBox(ex.Message)
        End Try

        If Frame.GetController(Of RefreshController).RefreshAction.Enabled Then
            Frame.GetController(Of RefreshController).RefreshAction.DoExecute()
        End If
    End Sub
    Private Sub aViewAttachments_AssetsHandling_Execute(sender As System.Object, e As DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs) Handles aViewAttachments_AssetsHandling.Execute
        Dim _AssetsPCIRows As AssetsPCIRows
        Dim _CustomersFrom As CustomersFrom
        Dim _Customers As Customers
        Dim _DocumentNumber As String

        If View.SelectedObjects.Count > 0 Then
            _AssetsPCIRows = TryCast(View.SelectedObjects(0), AssetsPCIRows)
            _CustomersFrom = _AssetsPCIRows.CustomersFrom
            _Customers = _AssetsPCIRows.Customers
            _DocumentNumber = _AssetsPCIRows.ConnectInfo

            ViewAttachments.ViewAttachments(View.ObjectSpace, Frame, _CustomersFrom, _Customers, _DocumentNumber, "")
        Else
            Throw New UserFriendlyException("Nincs kiválasztott elem.")
        End If
    End Sub
    Private Sub aCreateAssetsHandling_Execute(sender As System.Object, e As DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs) Handles aCreateAssetsHandling.Execute

        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _uow As New UnitOfWork(_ocur.Session.DataLayer)
        Dim _AssetsPCIHeader As AssetsPCIHeader = TryCast(View.SelectedObjects(0), AssetsPCIHeader)
        Dim _AssetsPCIRows_ListEditor As ListPropertyEditor = TryCast(View, DetailView).FindItem("AssetsPCIRows")

        Dim _AssetsPCIRows As AssetsPCIRows

        Dim _AssetsHandling As AssetsHandling
        Dim _AssetsHandling_Last As AssetsHandling
        Dim _AssetsHandling_Last_Collection As XPCollection(Of AssetsHandling)
        Dim _AssetsHandlingParameter As AssetsHandlingParameter
        Dim _InvoiceHeader As InvoiceHeader
        Dim I As Long = 0
        Dim _QueueIndex As Long = 1
        Dim _SysDate As Date = GetSQLTime(_ocur.Session).Date

        Dim _Customers As Customers
        Dim _CustomersFrom As CustomersFrom

        'Dim _AssetsHandling_IsActiveCollection As New XPCollection(Of AssetsHandling)(_uow, CriteriaOperator.Parse("CustomersFrom.Oid=? And IsActive=True ", _AssetsPCIHeader.CustomersFrom.Oid))
        '
        'RaiseEvent InitWork(1, 1, _AssetsHandling_IsActiveCollection.Count)
        'For Each _AssetsHandling In _AssetsHandling_IsActiveCollection
        '    I += 1
        '    _AssetsHandling.IsActive = False
        '    RaiseEvent DoWork()
        '    If I Mod 1000 = 0 Then _uow.CommitChanges()
        'Next
        '_uow.CommitChanges()
        'RaiseEvent FinalWork

        RaiseEvent InitWork(1, 1, _AssetsPCIRows_ListEditor.ListView.CollectionSource.List.Count)
        For Each _AssetsPCIRows In _AssetsPCIRows_ListEditor.ListView.CollectionSource.List
            I += 1
            _QueueIndex = 0

            _Customers = _uow.GetObjectByKey(Of Customers)(_AssetsPCIRows.Customers.Oid)
            _CustomersFrom = _uow.GetObjectByKey(Of CustomersFrom)(_AssetsPCIRows.CustomersFrom.Oid)

            _AssetsHandling_Last_Collection = New XPCollection(Of AssetsHandling)(_uow, CriteriaOperator.Parse("Customers=? And CustomersFrom=? And DocumentNumber=?", _
                                                                                                               _Customers, _CustomersFrom, _AssetsPCIRows.ConnectInfo))

            _AssetsHandling_Last_Collection.Sorting().Add(New SortProperty("QueueIndex", DB.SortingDirection.Descending))
            '_QueueIndex = _AssetsHandling_Last_Collection(0).QueueIndex + 1

            For Each _AssetsHandling_Last In _AssetsHandling_Last_Collection
                _QueueIndex = _AssetsHandling_Last.QueueIndex
                Exit For
            Next

            _AssetsHandlingParameter = _uow.FindObject(Of AssetsHandlingParameter)(CriteriaOperator.Parse("CustomersFrom=?", _CustomersFrom))

            RaiseEvent DoWork()
            If _AssetsHandlingParameter IsNot Nothing Then



                If (_QueueIndex = 0 And _SysDate >= _AssetsPCIRows.DatePayment.Date.AddDays(_AssetsHandlingParameter.TolerationDay1)) Or _
                   (_QueueIndex = 1 And _SysDate >= _AssetsPCIRows.DatePayment.Date.AddDays(_AssetsHandlingParameter.TolerationDay2)) Then

                    For Each _AssetsHandling_Last In _AssetsHandling_Last_Collection
                        _AssetsHandling_Last.IsActive = False 'Az előző rekordok nem lehetnek aktívak.
                    Next

                    _AssetsHandling = New AssetsHandling(_uow)

                    _AssetsHandling.QueueIndex = _QueueIndex

                    _AssetsHandling.AmountDEV_Account = _AssetsPCIRows.AmountDEV_Account
                    _AssetsHandling.AmountHUF_Account = _AssetsPCIRows.AmountHUF_Account
                    _AssetsHandling.BalanceDEV = _AssetsPCIRows.BallanceDEV
                    _AssetsHandling.BalanceHUF = _AssetsPCIRows.BallanceHUF
                    _AssetsHandling.CustomersFrom = _CustomersFrom
                    _AssetsHandling.Customers = _Customers
                    _AssetsHandling.DateClose = _AssetsPCIRows.AssetsPCIHeader.DateClose
                    _AssetsHandling.DatePayment = _AssetsPCIRows.DatePayment
                    _AssetsHandling.DateExecution = _AssetsPCIHeader.DateExecution
                    _AssetsHandling.DocumentNumber = _AssetsPCIRows.ConnectInfo
                    _AssetsHandling.DateCreated = _AssetsPCIRows.DateCreated
                    _AssetsHandling.IsActive = True
                    If _AssetsPCIRows.Customers.IsAssetsHandling Then
                    Else
                        _AssetsHandling.NoAssetsHandling = True
                    End If
                    _InvoiceHeader = _uow.FindObject(Of InvoiceHeader)(CriteriaOperator.Parse("CustomersFrom=? and Customers=? and DocumentNumber=?", _CustomersFrom, _Customers, _AssetsHandling.DocumentNumber))
                    _AssetsHandling.InvoiceHeader = _InvoiceHeader
                    If _AssetsHandling.InvoiceHeader IsNot Nothing Then
                        If _AssetsHandling.InvoiceHeader.AssetsHandlingStatus IsNot Nothing Then
                            If _AssetsHandling.InvoiceHeader.AssetsHandlingStatus.QueueIndex > 0 Then
                                _AssetsHandling.QueueIndex = _AssetsHandling.InvoiceHeader.AssetsHandlingStatus.QueueIndex
                            End If
                        End If
                    End If
                End If
            End If
            If I Mod 1000 = 0 Then _uow.CommitChanges()
        Next
        _uow.CommitChanges()
        RaiseEvent FinalWork
        If Frame.GetController(Of RefreshController).RefreshAction.Enabled Then
            Frame.GetController(Of RefreshController).RefreshAction.DoExecute()
        End If
    End Sub
    Private Sub aViewLateCharges_CustomizePopupWindowParams(sender As Object, e As DevExpress.ExpressApp.Actions.CustomizePopupWindowParamsEventArgs) Handles aViewLateCharges.CustomizePopupWindowParams
        Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _CS As New CollectionSource(_onew, GetType(LateCharges))
        If View.Id = "PCIGroup_ListView_DelayedPay" Then
            Dim _PCIGroup As PCIGroup
            Dim _InvoiceHeader As InvoiceHeader
            _PCIGroup = TryCast(View.SelectedObjects(0), PCIGroup)
            If _PCIGroup IsNot Nothing Then
                _invoiceheader = _PCIGroup.InvoiceHeader
                If _InvoiceHeader IsNot Nothing Then

                    CreateLateCharges(_ocur.Session, _InvoiceHeader, Now, True, True)

                    _ocur.CommitChanges()

                    _CS.BeginUpdateCriteria()
                    _CS.Criteria.Clear()
                    _CS.Criteria("First") = CriteriaOperator.Parse("InvoiceHeader.Oid=?", _InvoiceHeader.Oid)
                    _CS.EndUpdateCriteria()

                    _CS.Sorting.Clear()
                    _CS.Sorting.Add(New SortProperty("DateExecution", DB.SortingDirection.Descending))

                    e.View = Application.CreateListView("LateCharges_ListView_Info", _CS, False)
                End If
            End If
        Else
            If View.SelectedObjects.Count > 0 Then
                Dim _AssetsPCIRows As AssetsPCIRows = TryCast(View.SelectedObjects(0), AssetsPCIRows)
                Dim _CustomersFrom As CustomersFrom = _AssetsPCIRows.CustomersFrom
                Dim _Customers As Customers = _AssetsPCIRows.Customers
                Dim _DocumentNumber As String = _AssetsPCIRows.ConnectInfo
                Dim _DateClose As Date = _AssetsPCIRows.AssetsPCIHeader.DateClose

                Dim _InvoiceHeader As InvoiceHeader = _ocur.FindObject(Of InvoiceHeader)(CriteriaOperator.Parse("CustomersFrom=? and Customers=? and DocumentNumber=?",
                                                                                                                  _CustomersFrom, _Customers, _DocumentNumber))

                If _InvoiceHeader IsNot Nothing Then

                    CreateLateCharges(_ocur.Session, _InvoiceHeader, _DateClose, True, True)

                    _ocur.CommitChanges()

                    _CS.BeginUpdateCriteria()
                    _CS.Criteria.Clear()
                    _CS.Criteria("First") = CriteriaOperator.Parse("InvoiceHeader.Oid=?", _InvoiceHeader.Oid)
                    _CS.EndUpdateCriteria()

                    _CS.Sorting.Clear()
                    _CS.Sorting.Add(New SortProperty("DateExecution", DB.SortingDirection.Descending))

                    e.View = Application.CreateListView("LateCharges_ListView_Info", _CS, False)
                End If
            Else
                Throw New UserFriendlyException("Nincs kiválasztott elem.")
            End If
        End If
        

    End Sub
    Private Sub aViewLateCharges_Execute(sender As System.Object, e As DevExpress.ExpressApp.Actions.PopupWindowShowActionExecuteEventArgs) Handles aViewLateCharges.Execute
    End Sub
    Sub CreateLateCharges(_Session As Session, _pInvoiceHeader As InvoiceHeader, _pDateClose As Date, Optional _WithTransaction As Boolean = False, Optional _StatusBar As Boolean = False)
        Dim _uow As New UnitOfWork(_Session.DataLayer)
        Dim _EmptyDate As Date = New Date
        Dim _InvoiceHeader As InvoiceHeader = _uow.GetObjectByKey(Of InvoiceHeader)(_pInvoiceHeader.Oid)
        Dim _MaxCount As Long = Math.Abs(DateDiff(DateInterval.Day, _InvoiceHeader.DatePayment.Date, _pDateClose))
        Dim _I As Long = 0
        Dim _TotalBruttoPayedBefore As Double = 0
        Dim _MoneyRate As MoneyRate = Nothing
        Dim _MoneyRate_Collection As New XPCollection(Of MoneyRate)(_uow) 'Alapkamat rekordok összegyűjtése
        _MoneyRate_Collection.Sorting.Add(New SortProperty("DateFrom", DB.SortingDirection.Ascending))
        Dim _LateChargesCountMode As LateChargesCountMode = Nothing
        Dim _LateCharges As LateCharges = Nothing
        Dim _LateCharges_Collection As New XPCollection(Of LateCharges)(_uow, CriteriaOperator.Parse("InvoiceHeader=?", _InvoiceHeader.Oid))
        _uow.Delete(_LateCharges_Collection)

        'Az összes a lejáratot megelőző fizetéssel a kollekciót növelni kell
        Dim _PCID_Before As PCIDetail = Nothing
        Dim _PCID_Before_Collection As New XPCollection(Of PCIDetail) _
            (_uow, CriteriaOperator.Parse("CustomersFrom=? and Customers=? and PartnerType=0 and ConnectInfo=? and MainType <>'01-Account' and MainType<>'06-Latecharge' and GetDate(DateExecution)<=?", _
                                          _InvoiceHeader.CustomersFrom, _InvoiceHeader.Customers, _InvoiceHeader.DocumentNumber, _InvoiceHeader.DatePayment.Date))
        For Each _PCID_Before In _PCID_Before_Collection
            _TotalBruttoPayedBefore += _PCID_Before.BallanceHUF
        Next

        For _I = 0 To _MaxCount
            _LateCharges = New LateCharges(_uow)
            _LateCharges.InvoiceHeader = _InvoiceHeader
            _LateCharges.DateExecution = DateAdd(DateInterval.Day, _I, _InvoiceHeader.DatePayment.Date)
            If _I = 0 Then
                _LateCharges.DebitHUF = _InvoiceHeader.TotalBruttoHUF + _TotalBruttoPayedBefore
            Else
                '// Napi késedelmi kamat kikeresése ------------
                'Először a szerződésben keressük, mi a késedelemi kamat.
                If _InvoiceHeader.Customers.LateChargesCountMode IsNot Nothing Then
                    _LateChargesCountMode = _InvoiceHeader.Customers.LateChargesCountMode
                End If

                'Másodszor a szerződésben keressük, mi a késedelemi kamat. Ez akkor felülbírálja a szerződés adatait.
                If _InvoiceHeader.LateChargesCountMode IsNot Nothing Then
                    _LateChargesCountMode = _InvoiceHeader.LateChargesCountMode
                End If

                For Each _MoneyRate In _MoneyRate_Collection ' A MoneyRate objektum egy példányának úgy kell tartalmaznia az aktuális kamatot, hogy az érvényesség első és utolsó napja szerepeljen benne.
                    If _LateCharges.DateExecution.Date >= _MoneyRate.DateFrom.Date And (_MoneyRate.DateTo.Date = _EmptyDate.Date Or _LateCharges.DateExecution.Date <= _MoneyRate.DateTo.Date) Then
                        Exit For
                    End If
                    _MoneyRate = Nothing
                Next

                If _LateChargesCountMode IsNot Nothing Then
                    If _LateChargesCountMode.LCCountMode = eLCCountMode.eFix Then 'Ha fix értéket tartalmaz a kamatszámítás-rekord, akkor azt vesszük figyelembe.
                        _LateCharges.CurrentLateChargesPercent = _LateChargesCountMode.LCValue / 100
                    Else
                        If _MoneyRate IsNot Nothing Then 'Ellenkező esetben a kamattáblázatból kikeresett értéket használjuk, a és szorozzuk a kamatszámítás-rekord értékével.
                            _LateCharges.CurrentLateChargesPercent = (_MoneyRate.KeyValue / 100) * _LateChargesCountMode.LCValue
                        End If
                    End If
                Else
                    If _MoneyRate IsNot Nothing Then
                        _LateCharges.CurrentLateChargesPercent = (_MoneyRate.KeyValue / 100) * 2
                    End If
                End If

                If _MoneyRate Is Nothing Then 'Ha nem sikerült beazonosítani a késedelmi kamat mértékét.
                    _LateCharges.CurrentLateChargesPercent = 0
                End If

                '//---------------------------------------------
            End If
            _LateCharges_Collection.Add(_LateCharges)
        Next

        

        _LateCharges_Collection.Sorting.Add(New SortProperty("GetDate(DateExecution)", DB.SortingDirection.Ascending))

        Dim _PCID As PCIDetail = Nothing
        Dim _PCID_Collection As New XPCollection(Of PCIDetail) _
            (_uow, CriteriaOperator.Parse("CustomersFrom=? and Customers=? and PartnerType=0 and ConnectInfo=? and MainType <>'01-Account' and MainType<>'06-Latecharge' and GetDate(DateExecution)>?", _
                                          _InvoiceHeader.CustomersFrom, _InvoiceHeader.Customers, _InvoiceHeader.DocumentNumber, _InvoiceHeader.DatePayment.Date))
        _PCID_Collection.Sorting.Add(New SortProperty("GetDate(DateExecution)", DB.SortingDirection.Ascending))

        For Each _PCID In _PCID_Collection
            For Each _LateCharges In _LateCharges_Collection
                If _LateCharges.DateExecution.Date = _PCID.DateExecution.Date Then
                    If _PCID.BallanceHUF > 0 Then
                        _LateCharges.DebitHUF = _PCID.BallanceHUF
                    Else
                        _LateCharges.CreditHUF = _PCID.BallanceHUF
                    End If

                    Exit For
                End If
            Next
        Next
        '// TŐKE változása -------------------------------------------------------------------------------------------------------------
        _I = 0
        Dim _CapitalBalanceHUF As Double = 0
        Dim _LateChargesBalanceHUF As Double = 0
        Dim _LateChargesHUF As Double = 0
        For Each _LateCharges In _LateCharges_Collection
            If _I = 0 Then
                _LateCharges.CapitalBalanceHUF = _LateCharges.DebitHUF + _LateCharges.CreditHUF
                _CapitalBalanceHUF = _LateCharges.CapitalBalanceHUF
            Else
                If _LateCharges.CreditHUF <> 0 Then
                    _CapitalBalanceHUF += _LateCharges.CreditHUF
                End If

                _LateCharges.CapitalBalanceHUF = _CapitalBalanceHUF
            End If
            _I += 1
        Next

        '// Kamat számítása ------------------------------------------------------------------------------------------------------------------------
        _I = 0
        For Each _LateCharges In _LateCharges_Collection
            If _I = 0 Then
          
            Else
                _LateChargesHUF = ((_LateCharges.CapitalBalanceHUF * _LateCharges.CurrentLateChargesPercent) / 365)
                _LateChargesBalanceHUF += _LateChargesHUF
                _LateCharges.LateChargesBalanceHUF = _LateChargesBalanceHUF
                _LateCharges.DebitHUF = _LateChargesHUF
            End If
            _I += 1
        Next

        If _WithTransaction Then
            _uow.CommitChanges()
        End If



    End Sub
    Sub CreateLateCharges_BAD(_Session As Session, _pInvoiceHeader As InvoiceHeader, _pDateClose As Date, Optional _WithTransaction As Boolean = False, Optional _StatusBar As Boolean = False)
        Dim _uow As New UnitOfWork(_Session.DataLayer)

        Dim _LateCharges As LateCharges = Nothing
        Dim _Previous_LateCharges As LateCharges = Nothing
        'Dim _Deletable_LateCharge As LateCharges
        Dim _EmptyDate As Date = New Date
        If _pInvoiceHeader Is Nothing Then Exit Sub
        Dim _InvoiceHeader As InvoiceHeader = _uow.GetObjectByKey(Of InvoiceHeader)(_pInvoiceHeader.Oid)

        Dim _LateCharges_Collection As New XPCollection(Of LateCharges)(_uow, CriteriaOperator.Parse("InvoiceHeader=?", _InvoiceHeader.Oid))

        '-- A pénzügyi teljesítések kollekciója
        Dim _PCID As PCIDetail
        Dim _PCID_Collection As New XPCollection(Of PCIDetail) _
            (_uow, CriteriaOperator.Parse("CustomersFrom=? and Customers=? and PartnerType=0 and ConnectInfo=? and MainType <>'01-Account'", _
                                          _InvoiceHeader.CustomersFrom, _InvoiceHeader.Customers, _InvoiceHeader.DocumentNumber))
        _PCID_Collection.Sorting.Add(New SortProperty("GetDate(DateExecution)", DB.SortingDirection.Ascending))
        Dim _AssetsHandling_Collection As New XPCollection(Of AssetsHandling)(_uow, CriteriaOperator.Parse("InvoiceHeader=?", _InvoiceHeader))

        If _pDateClose.Date > GetSQLTime(_Session).Date Then
            _pDateClose = GetSQLTime(_Session).Date
        End If

        Dim _AssetsHandlingParameter As AssetsHandlingParameter = _uow.FindObject(Of AssetsHandlingParameter)(CriteriaOperator.Parse("CustomersFrom=?", _InvoiceHeader.CustomersFrom))

        'Eddigi késedelmi kamatrekordok összegyűjtése.
        'If _LateCharges_Collection IsNot Nothing Then
        '    _LateCharges_Collection.Sorting.Add(New SortProperty("DateExecution", DB.SortingDirection.Descending))
        '    If _LateCharges_Collection.Count > 0 Then
        '        _Previous_LateCharges = New LateCharges(_uow)
        '        _Deletable_LateCharge = _Previous_LateCharges 'Ezt a végén törölni fogjuk.
        '        _Previous_LateCharges = _LateCharges_Collection(0)
        '    End If
        'End If

        If _LateCharges_Collection IsNot Nothing Then 'Kitöröljük az előzményeket.
            _uow.Delete(_LateCharges_Collection)
        End If

        If _Previous_LateCharges Is Nothing Then 'Ha nincsenek előzmények, akkor tiszta lappal indulunk.
            _Previous_LateCharges = New LateCharges(_uow)
            _Previous_LateCharges.InvoiceHeader = _InvoiceHeader
            _Previous_LateCharges.DateExecution = _InvoiceHeader.DatePayment.Date
            _Previous_LateCharges.CapitalBalanceHUF = _InvoiceHeader.TotalBruttoHUF
            _Previous_LateCharges.CapitalBalanceDEV = _InvoiceHeader.TotalBruttoDEV
            _Previous_LateCharges.LateChargesBalanceHUF = 0
            _Previous_LateCharges.LateChargesBalanceDEV = 0
            _Previous_LateCharges.CostBalanceHUF = 0
            _Previous_LateCharges.CostBalanceHUF = 0
            _Previous_LateCharges.DebitHUF = _InvoiceHeader.TotalBruttoHUF
            _Previous_LateCharges.DebitDEV = _InvoiceHeader.TotalBruttoDEV
            _Previous_LateCharges.CreditHUF = 0
            _Previous_LateCharges.CreditDEV = 0
            _Previous_LateCharges.CostNote = ""
            _Previous_LateCharges.CurrentLateChargesPercent = 0

            '_Deletable_LateCharge = _Previous_LateCharges 'Ezt a végén törölni fogjuk?
        End If


        Dim _MoneyRate As MoneyRate = Nothing
        Dim _LateChargesCountMode As LateChargesCountMode = Nothing
        Dim _MoneyRate_Collection As New XPCollection(Of MoneyRate)(_uow) 'Alapkamat rekordok összegyűjtése

        If _MoneyRate_Collection IsNot Nothing Then
            _MoneyRate_Collection.Sorting.Add(New SortProperty("DateFrom", DB.SortingDirection.Ascending))
        End If

        If _StatusBar Then
            RaiseEvent InitWork(1, 1, DateDiff(DateInterval.Day, _Previous_LateCharges.DateExecution, _pDateClose.Date))
        End If

        Do While _Previous_LateCharges.DateExecution.Date < _pDateClose.Date 'A Számla fizetési határidjétől vagy az utolsó késedelmi kamatsortól indulunk, és a záródátumig haladunk.
            If _StatusBar Then
                RaiseEvent DoWork()
            End If

            'Először a szerződésben keressük, mi a késedelemi kamat.
            If _InvoiceHeader.Customers.LateChargesCountMode IsNot Nothing Then
                _LateChargesCountMode = _InvoiceHeader.Customers.LateChargesCountMode
            End If

            'Másodszor a szerződésben keressük, mi a késedelemi kamat. Ez akkor felülbírálja a szerződés adatait.
            If _InvoiceHeader.LateChargesCountMode IsNot Nothing Then
                _LateChargesCountMode = _InvoiceHeader.LateChargesCountMode
            End If

            ''Ha nem találtunk idáig bejegyzést, akkor az aktuális alapkamat kétszerese lesz.
            'If _LateChargesCountMode Is Nothing Then 'Ez így nem lesz jó, ezt nem szeretnénk létrehozni!
            '    _LateChargesCountMode = New LateChargesCountMode(_uow)
            '    _LateChargesCountMode.LCCountMode = eLCCountMode.eFix
            '    _LateChargesCountMode.LCValue = 2
            'End If
            '_LateChargesCountMode.dispose() 'Ez most miért nem?

            _LateCharges = New LateCharges(_uow)
            _LateCharges.InvoiceHeader = _Previous_LateCharges.InvoiceHeader
            _LateCharges.DateExecution = DateAdd(DateInterval.Day, 1, _Previous_LateCharges.DateExecution.Date) 'Naponta egy rekord.

            For Each _MoneyRate In _MoneyRate_Collection ' A MoneyRate objektum egy példányának úgy kell tartalmaznia az aktuális kamatot, hogy az érvényesség első és utolsó napja szerepeljen benne.
                If _LateCharges.DateExecution.Date >= _MoneyRate.DateFrom.Date And (_MoneyRate.DateTo.Date = _EmptyDate.Date Or _LateCharges.DateExecution.Date <= _MoneyRate.DateTo.Date) Then
                    Exit For
                End If
                _MoneyRate = Nothing
            Next

            If _LateChargesCountMode IsNot Nothing Then
                If _LateChargesCountMode.LCCountMode = eLCCountMode.eFix Then 'Ha fix értéket tartalmaz a kamatszámítás-rekord, akkor azt vesszük figyelembe.
                    _LateCharges.CurrentLateChargesPercent = _LateChargesCountMode.LCValue / 100
                Else
                    If _MoneyRate IsNot Nothing Then 'Ellenkező esetben a kamattáblázatból kikeresett értéket használjuk, a és szorozzuk a kamatszámítás-rekord értékével.
                        _LateCharges.CurrentLateChargesPercent = (_MoneyRate.KeyValue / 100) * _LateChargesCountMode.LCValue
                    End If
                End If
            Else
                If _MoneyRate IsNot Nothing Then
                    _LateCharges.CurrentLateChargesPercent = (_MoneyRate.KeyValue / 100) * 2
                End If
            End If

            If _MoneyRate Is Nothing Then 'Ha nem sikerült beazonosítani a késedelmi kamat mértékét.
                _LateCharges.CurrentLateChargesPercent = 0
            End If

            _LateCharges.CapitalBalanceHUF = _Previous_LateCharges.CapitalBalanceHUF
            _LateCharges.CapitalBalanceDEV = _Previous_LateCharges.CapitalBalanceDEV
            _LateCharges.DebitHUF = ((_LateCharges.CapitalBalanceHUF * _LateCharges.CurrentLateChargesPercent) / 365)
            _LateCharges.DebitDEV = ((_LateCharges.CapitalBalanceDEV * _LateCharges.CurrentLateChargesPercent) / 365) 'Ez így jó? 365 nappal számolunk?
            _LateCharges.LateChargesBalanceHUF = _Previous_LateCharges.LateChargesBalanceHUF + _LateCharges.DebitHUF
            _LateCharges.LateChargesBalanceDEV = _Previous_LateCharges.LateChargesBalanceDEV + _LateCharges.DebitDEV
            _LateCharges.CostBalanceHUF = _Previous_LateCharges.CostBalanceHUF
            _LateCharges.CostBalanceDEV = _Previous_LateCharges.CostBalanceDEV
            _LateCharges.CreditHUF = 0
            _LateCharges.CreditDEV = 0
            _LateCharges.CostNote = ""

            If _AssetsHandlingParameter IsNot Nothing Then
                For Each _AssetsHandling In _AssetsHandling_Collection
                    If _AssetsHandling.DateExecution.Date = _LateCharges.DateExecution.Date Then
                        Select Case _AssetsHandling.QueueIndex
                            Case 0
                                _LateCharges.CostBalanceHUF = _LateCharges.CostBalanceHUF + _AssetsHandlingParameter.Cost1HUF
                            Case 1
                                _LateCharges.CostBalanceHUF = _LateCharges.CostBalanceHUF + _AssetsHandlingParameter.Cost2HUF
                        End Select

                    End If
                Next
            End If

            For Each _PCID In _PCID_Collection

                If _PCID.DateExecution.Date = _LateCharges.DateExecution.Date Then

                    If _PCID.BallanceDEV <> 0 Then                                                                      'Ha van devizás befolyt összeg,

                        _LateCharges.LateChargesBalanceDEV = _LateCharges.LateChargesBalanceDEV + _PCID.BallanceDEV     'akkor letudjuk belőle a kamatot.
                        If _LateCharges.LateChargesBalanceDEV < 0 Then                                                  'Ha nagyobb volt az befolyt összeg, mint a késedelmi kamat,
                            _PCID.BallanceDEV = _LateCharges.LateChargesBalanceDEV                                      'akkor a maradék összeget megtartjuk,
                            _LateCharges.LateChargesBalanceDEV = 0                                                      'a késedelmi kamat összegét pedig nullára állítjuk.
                        End If

                        If _PCID.BallanceDEV < 0 Then                                                                   'Ha még mindig maradt pénz,
                            _LateCharges.CapitalBalanceDEV = _LateCharges.CapitalBalanceDEV + _PCID.BallanceDEV         'levonjuk a tőke részből.
                            If _LateCharges.CapitalBalanceDEV < 0 Then                                                  'Ha nagyobb volt az összeg a tőkénél is, akkor nullára állítjuk be a tőkét.
                                _LateCharges.CapitalBalanceDEV = 0
                            End If
                        End If

                    End If

                    If _PCID.BallanceHUF <> 0 Then 'A devizás esetre ugyan ezt kell alkalmazni tesztelés után!

                        If _PCID.BallanceHUF < 0 Then
                            _LateCharges.CostBalanceHUF = _LateCharges.CostBalanceHUF + _PCID.BallanceHUF
                            If _LateCharges.CostBalanceHUF < 0 Then
                                _PCID.BallanceHUF = _LateCharges.CostBalanceHUF
                                _LateCharges.CostBalanceHUF = 0
                            Else
                                _PCID.BallanceHUF = 0
                            End If
                        End If

                        If _PCID.BallanceHUF < 0 Then
                            _LateCharges.LateChargesBalanceHUF = _LateCharges.LateChargesBalanceHUF + _PCID.BallanceHUF
                            If _LateCharges.LateChargesBalanceHUF < 0 Then
                                _PCID.BallanceHUF = _LateCharges.LateChargesBalanceHUF
                                _LateCharges.LateChargesBalanceHUF = 0
                            Else
                                _PCID.BallanceHUF = 0
                            End If
                        End If

                        If _PCID.BallanceHUF < 0 Then
                            _LateCharges.CapitalBalanceHUF = _LateCharges.CapitalBalanceHUF + _PCID.BallanceHUF
                            If _LateCharges.CapitalBalanceHUF < 0 Then
                                _LateCharges.CapitalBalanceHUF = 0
                            End If
                        End If

                    End If

                End If
            Next

            If _Previous_LateCharges.LateChargesBalanceDEV + _LateCharges.DebitDEV > _LateCharges.LateChargesBalanceDEV Then
                _LateCharges.CreditDEV = (_LateCharges.LateChargesBalanceDEV - _Previous_LateCharges.LateChargesBalanceDEV) + (_LateCharges.DebitDEV * -1)
            End If
            If _Previous_LateCharges.CapitalBalanceDEV > _LateCharges.CapitalBalanceDEV Then
                _LateCharges.CreditDEV = _LateCharges.CreditDEV + (_LateCharges.CapitalBalanceDEV - _Previous_LateCharges.CapitalBalanceDEV)
            End If

            If _Previous_LateCharges.LateChargesBalanceHUF + _LateCharges.DebitHUF > _LateCharges.LateChargesBalanceHUF Then
                _LateCharges.CreditHUF = (_LateCharges.LateChargesBalanceHUF - _Previous_LateCharges.LateChargesBalanceHUF) + (_LateCharges.DebitHUF * -1)
            End If
            If _Previous_LateCharges.CapitalBalanceHUF > _LateCharges.CapitalBalanceHUF Then
                _LateCharges.CreditHUF = _LateCharges.CreditHUF + (_LateCharges.CapitalBalanceHUF - _Previous_LateCharges.CapitalBalanceHUF)
            End If

            _Previous_LateCharges = _LateCharges
        Loop
        'If _Deletable_LateCharge IsNot Nothing Then
        '    _Deletable_LateCharge.Delete() 'Erre nincs szükség.
        'End If
        If _StatusBar Then
            RaiseEvent FinalWork
        End If
        If _WithTransaction Then
            _uow.CommitChanges()
        End If

    End Sub
    Private Sub aCreateLateCharges_Execute(sender As System.Object, e As DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs) Handles aCreateLateCharges.Execute
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)

        If View.Id = "PCIGroup_ListView_DelayedPay" Then
            Dim _InvoiceHeader As InvoiceHeader
            Dim _PCIGroup As PCIGroup
            Dim _uow As New UnitOfWork(_ocur.Session.DataLayer)
            Frame.GetController(Of DevExpress.ExpressApp.Validation.PersistenceValidationController).Active.SetItemValue("", False)
            RaiseEvent InitWork(1, 1, TryCast(View, ListView).CollectionSource.List.Count)
            For Each _PCIGroup In TryCast(View, ListView).CollectionSource.List
                RaiseEvent DoWork()
                If _PCIGroup.InvoiceHeader IsNot Nothing Then
                    _InvoiceHeader = _uow.GetObjectByKey(Of InvoiceHeader)(_PCIGroup.InvoiceHeader.Oid)

                    CreateLateCharges(_uow, _InvoiceHeader, Now, True)
                    Dim _LateCharges_Collection As New XPCollection(Of LateCharges)(_uow, _
                                                                   CriteriaOperator.Parse("InvoiceHeader=?", _InvoiceHeader))
                    _LateCharges_Collection.Sorting.Add(New SortProperty("DateExecution", DB.SortingDirection.Descending))
                    For Each _LateCharges In _LateCharges_Collection
                        _InvoiceHeader.LateChargesBalanceHUF = Math.Round(_LateCharges.LateChargesBalanceHUF, 0, MidpointRounding.AwayFromZero)
                        _uow.CommitChanges()
                        Exit For
                    Next
                End If
            Next
            _uow.CommitChanges()
            RaiseEvent FinalWork
            Frame.GetController(Of DevExpress.ExpressApp.Validation.PersistenceValidationController).Active.SetItemValue("", True)
        Else
            Dim _AssetsHandling As AssetsHandling
            Dim _AssetsHandling_Collection As New XPCollection(Of AssetsHandling)(_ocur.Session, CriteriaOperator.Parse("NoAssetsHandling = False and IsActive=True"))
            Dim _LateCharges As LateCharges



            RaiseEvent InitWork(1, 1, _AssetsHandling_Collection.Count)
            For Each _AssetsHandling In _AssetsHandling_Collection
                RaiseEvent DoWork()
                _AssetsHandling.LateChargesBalanceHUF = 0

                _ocur.CommitChanges()
                If _AssetsHandling.NoAssetsHandling = False Then 'And _AssetsHandling.QueueIndex = 1 Then
                    CreateLateCharges(_ocur.Session, _AssetsHandling.InvoiceHeader, _AssetsHandling.DateClose, True)
                End If
                Dim _LateCharges_Collection As New XPCollection(Of LateCharges)(_ocur.Session, _
                                                                CriteriaOperator.Parse("InvoiceHeader=?", _AssetsHandling.InvoiceHeader))
                _LateCharges_Collection.Sorting.Add(New SortProperty("DateExecution", DB.SortingDirection.Descending))
                For Each _LateCharges In _LateCharges_Collection
                    _AssetsHandling.LateChargesBalanceHUF = Math.Round(_LateCharges.LateChargesBalanceHUF, 0, MidpointRounding.AwayFromZero)
                    _ocur.CommitChanges()
                    Exit For
                Next
            Next
            _ocur.CommitChanges()
            RaiseEvent FinalWork
        End If
        


    End Sub
    Private Sub aNoAssetsHandling_Execute(sender As Object, e As DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs) Handles aNoAssetsHandling.Execute
        Dim _uow As New UnitOfWork(TryCast(View.ObjectSpace, Xpo.XPObjectSpace).Session.DataLayer)

        Dim _AssetsHandling As AssetsHandling

        If View.SelectedObjects.Count > 0 Then
            RaiseEvent InitWork(1, 1, View.SelectedObjects.Count)
            For Each _AssetsHandling In View.SelectedObjects
                RaiseEvent DoWork()
                If _AssetsHandling.NoAssetsHandling Then
                    _AssetsHandling.NoAssetsHandling = False
                Else
                    _AssetsHandling.NoAssetsHandling = True
                End If
            Next
            RaiseEvent FinalWork
            _uow.CommitChanges()
        Else
            Throw New UserFriendlyException("Nincs kiválasztott elem.")
        End If
    End Sub
    Private Sub aCountLateCharges_Execute(sender As Object, e As DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs) Handles aCountLateCharges.Execute
        Dim _uow As New UnitOfWork(TryCast(View.ObjectSpace, Xpo.XPObjectSpace).Session.DataLayer)

        If View.SelectedObjects.Count > 0 Then
            RaiseEvent InitWork(1, 1, View.SelectedObjects.Count)
            For Each _AssetsHandling In View.SelectedObjects
                RaiseEvent DoWork()
                _AssetsHandling.CountLateCharges = Not _AssetsHandling.CountLateCharges
            Next
            RaiseEvent FinalWork
            _uow.CommitChanges()
        Else
            Throw New UserFriendlyException("Nincs kiválasztott elem.")
        End If
    End Sub
    Private Sub aViewCustomerPaymentBehaviour_Execute(sender As System.Object, e As DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs) Handles aViewCPBAssetsPCIRows_ListView.Execute
        Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
        Dim _AssetsHandlingCPB As AssetsHandlingCPB
        Dim _AssetsPCIRows As AssetsPCIRows = TryCast(View.SelectedObjects(0), AssetsPCIRows)

        If _AssetsPCIRows IsNot Nothing Then
            _AssetsHandlingCPB = _onew.CreateObject(Of AssetsHandlingCPB)()
            _AssetsHandlingCPB.Customers = _onew.GetObject(_AssetsPCIRows.Customers)
            e.ShowViewParameters.CreatedView = Application.CreateDetailView(_onew, "AssetsHandlingCPB_DetailView", True, _AssetsHandlingCPB)
        End If

    End Sub
    Private Sub aViewCPBAssetsHandling_ListView_Execute(sender As System.Object, e As DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs) Handles aViewCPBAssetsHandling_ListView.Execute
        Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
        Dim _AssetsHandlingCPB As AssetsHandlingCPB
        Dim _AssetsHandling As AssetsHandling = TryCast(View.SelectedObjects(0), AssetsHandling)

        If _AssetsHandling IsNot Nothing Then
            _AssetsHandlingCPB = _onew.CreateObject(Of AssetsHandlingCPB)()
            _AssetsHandlingCPB.Customers = _onew.GetObject(_AssetsHandling.Customers)
            e.ShowViewParameters.CreatedView = Application.CreateDetailView(_onew, "AssetsHandlingCPB_DetailView", True, _AssetsHandlingCPB)
        End If

    End Sub
    Private Sub aViewPCIDW_AssetsPCIRows_Execute(sender As System.Object, e As DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs) Handles aViewPCIDW_AssetsPCIRows.Execute
        Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _AssetsPCIRows As AssetsPCIRows = TryCast(View.SelectedObjects(0), AssetsPCIRows)

        If _AssetsPCIRows IsNot Nothing Then
            ViewPDCI.ViewPDCIDetail(_onew, Application, e, _AssetsPCIRows.CustomersFrom, _AssetsPCIRows.Customers, _AssetsPCIRows.PartnerType, _AssetsPCIRows.ConnectInfo)
        End If
    End Sub
    Private Sub aPCIGenerate_AssetsHandling_Execute(sender As System.Object, e As DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs) Handles aPCIGenerate_AssetsHandling.Execute
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _uow As New UnitOfWork(_ocur.Session.DataLayer)

        Dim _AssetsPCIRows As AssetsPCIRows

        RaiseEvent InitWork(1, 1, View.SelectedObjects.Count)
        For Each _AssetsPCIRows In View.SelectedObjects
            RaiseEvent DoWork()
            GLFunctions.ReconfigurePCI(_uow, _AssetsPCIRows.CustomersFrom, _AssetsPCIRows.Customers, ePartnerType.eReceivables, _AssetsPCIRows.ConnectInfo)
        Next
        RaiseEvent FinalWork

    End Sub
    Private Sub aAssetsHandling_CreateSendEmailQueue_Execute(sender As Object, e As SimpleActionExecuteEventArgs) Handles aAssetsHandling_CreateSendEmailQueue.Execute
        Try
            _ActiveForm = False
            Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)

            Dim _AssetsHandling_Collection As CollectionSource = TryCast(View, ListView).CollectionSource
            Dim _AssetsHandlingParameter_Collection As New XPCollection(Of AssetsHandlingParameter)(_ocur.Session)
            Dim _BalanceHUF As Double = 0
            If _AssetsHandlingParameter_Collection.Count > 0 Then
                If _AssetsHandlingParameter_Collection(0).EMailSendQueueParameters Is Nothing Then Throw New Exception("*Nincs beállítva E-mail csomag paraméter!")
                If _AssetsHandlingParameter_Collection(0).ReportData Is Nothing Then Throw New Exception("*Nincs beállítva nyomtatvány a kintlévőség kezelés paraméterben!")
            Else
                Throw New Exception("*Nincs beállítva kintlévőség kezelés paraméter!")
            End If

            _AssetsHandling_Collection.BeginUpdateCriteria()
            _AssetsHandling_Collection.Criteria.Clear()
            _AssetsHandling_Collection.Criteria("First") = CriteriaOperator.Parse("QueueIndex=0 AND NoAssetsHandling<>True AND IsActive=True")
            _AssetsHandling_Collection.EndUpdateCriteria()

            _AssetsHandling_Collection.Sorting.Clear()
            _AssetsHandling_Collection.Sorting.Add(New SortProperty("Customers", DB.SortingDirection.Descending))

            Dim _EMailSendQueueHeader As New EMailSendQueueHeader(_ocur.Session)
            _EMailSendQueueHeader.EmailSendQueueParameters = _AssetsHandlingParameter_Collection(0).EMailSendQueueParameters
            _EMailSendQueueHeader.ShortName = "Kinnlévőség kezelés automatikius e-mail"
            _ocur.CommitChanges()

            RaiseEvent InitWork(1, 1, TryCast(_AssetsHandling_Collection.List, IList).Count)
            _ActiveForm = True
            Dim _ActCustomersOid As String = "" '= TryCast(TryCast(_AssetsHandling_Collection.List, IList)(0), AssetsHandling).Oid.ToString
            Dim _ActCustomersFromOid As String = ""
            For _ik As Long = 0 To TryCast(_AssetsHandling_Collection.List, IList).Count - 1
                Dim _AssetsHandling As AssetsHandling = TryCast(TryCast(_AssetsHandling_Collection.List, IList)(_ik), AssetsHandling)

                Dim _AssetsHandlingStatus As AssetsHandlingStatus = _ocur.FindObject(Of AssetsHandlingStatus)(CriteriaOperator.Parse("QueueIndex=1"))
                If _AssetsHandling.InvoiceHeader IsNot Nothing Then
                    _AssetsHandling.InvoiceHeader.AssetsHandlingStatus = _AssetsHandlingStatus
                End If

                If _AssetsHandling.Customers.Oid.ToString <> _ActCustomersOid Or _AssetsHandling.CustomersFrom.Oid.ToString <> _ActCustomersFromOid Then
                    Dim _ReportData As ReportData = _AssetsHandlingParameter_Collection(0).ReportData
                    Dim _XafReport As Reports.XafReport = _ReportData.LoadReport(_ocur)
                    Dim _FilterString As String = String.Format("QueueIndex=0 and IsActive=True and NoAssetsHandling=False and Customers.Oid='{0}' and CustomersFrom.Oid = '{1}'", _
                                                                _AssetsHandling.Customers.Oid.ToString, _AssetsHandling.CustomersFrom.Oid.ToString)
                    _XafReport.FilterString = _FilterString
                    Dim _FileName As String = System.IO.Path.GetTempPath & _AssetsHandling.Customers.FullName + ".pdf"
                    Dim _StreamFile As New System.IO.FileStream(_FileName, System.IO.FileMode.Create)

                    _XafReport.ExportToPdf(_StreamFile)
                    _StreamFile.Close()



                    If System.IO.File.Exists(_FileName) Then
                        Dim _EMailSendQueueRows As New EMailSendQueueRows(_ocur.Session)
                        _EMailSendQueueRows.EMailSendQueueHeader = _EMailSendQueueHeader
                        Dim _Contacts As Contacts = _ocur.FindObject(Of Contacts)(CriteriaOperator.Parse("Customers=? AND IsAssetsHandlingResponsible=True", _AssetsHandling.Customers))
                        If _Contacts IsNot Nothing Then
                            _EMailSendQueueRows.EMailTo = _Contacts.Email
                        Else
                            _EMailSendQueueRows.EMailTo = _AssetsHandling.Customers.Email
                        End If

                        _EMailSendQueueRows.EMailFrom = _EMailSendQueueHeader.EmailSendQueueParameters.EMailFrom

                        _EMailSendQueueRows.Subject = _EMailSendQueueHeader.EmailSendQueueParameters.Subject

                        _BalanceHUF = 0
                        For _BB As Long = 0 To TryCast(_AssetsHandling_Collection.List, IList).Count - 1
                            Dim _AssetsHandling2 As AssetsHandling = TryCast(TryCast(_AssetsHandling_Collection.List, IList)(_BB), AssetsHandling)
                            If _AssetsHandling2.Customers.Oid = _AssetsHandling.Customers.Oid And _AssetsHandling2.CustomersFrom.Oid = _AssetsHandling.CustomersFrom.Oid Then
                                _BalanceHUF += _AssetsHandling2.BalanceHUF
                            End If
                        Next

                        _EMailSendQueueRows.HTMLBody = String.Format(_EMailSendQueueHeader.EmailSendQueueParameters.HTMLBody, _AssetsHandling.Customers.FullName, _EMailSendQueueHeader.ObjectCreated, _BalanceHUF)
                        _BalanceHUF = 0

                        _EMailSendQueueRows.FileAttachments1 = New FileData(_ocur.Session)
                        _EMailSendQueueRows.FileAttachments1.FileName = System.IO.Path.GetFileName(_FileName)

                        _StreamFile = New System.IO.FileStream(_FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read)
                        Dim _StreamReader As New System.IO.StreamReader(_StreamFile)
                        _StreamFile.Seek(0, System.IO.SeekOrigin.Begin)

                        _EMailSendQueueRows.FileAttachments1.LoadFromStream(_EMailSendQueueRows.FileAttachments1.FileName, _StreamFile)
                        _StreamReader.Close()
                        _StreamFile.Close()

                        System.IO.File.Delete(_FileName)
                        _AssetsHandling.EMailSendQueueRows = _EMailSendQueueRows

                        RaiseEvent DoWork()
                    End If
                Else
                    _AssetsHandling.EMailSendQueueRows = _EMailSendQueueHeader.EMailSendQueueRows(_EMailSendQueueHeader.EMailSendQueueRows.Count - 1)
                    RaiseEvent DoWork()
                End If
                _ActCustomersOid = _AssetsHandling.Customers.Oid.ToString
                _ActCustomersFromOid = _AssetsHandling.CustomersFrom.Oid.ToString
                _AssetsHandling.QueueIndex = 1

            Next
            _ocur.CommitChanges()

            Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
            e.ShowViewParameters.CreatedView = Application.CreateDetailView(_onew, "EMailSendQueueHeader_DetailView", False, _onew.GetObject(_EMailSendQueueHeader))
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, String.Format(CaptionHelper.GetLocalizedText("Exceptions\SISBusinessExceptions", "MsgBoxCheckItAgain")))
        Finally
            If _ActiveForm Then RaiseEvent FinalWork
        End Try
    End Sub

    Private Sub aAssetsHandling_RemoveSendEmailQueue_Execute(sender As Object, e As SimpleActionExecuteEventArgs) Handles aAssetsHandling_RemoveSendEmailQueue.Execute
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _AssetsHandling As AssetsHandling
        Dim _AssetsHandling_Collection As XPCollection(Of AssetsHandling)
        Dim _AssetsHandling2 As AssetsHandling
        For Each _AssetsHandling In View.SelectedObjects
            If _AssetsHandling.EMailSendQueueRows IsNot Nothing Then
                _AssetsHandling_Collection = New XPCollection(Of AssetsHandling)(_ocur.Session, _
                                                             CriteriaOperator.Parse("EMailSendQueueRows=?", _
                                                            _AssetsHandling.EMailSendQueueRows))
                _AssetsHandling.EMailSendQueueRows.Delete()
                For Each _AssetsHandling2 In _AssetsHandling_Collection
                    _AssetsHandling2.EMailSendQueueRows = Nothing
                    _AssetsHandling2.QueueIndex = 0
                    Dim _AssetsHandlingStatus As AssetsHandlingStatus = _ocur.FindObject(Of AssetsHandlingStatus)(CriteriaOperator.Parse("QueueIndex=0"))
                    If _AssetsHandling2.InvoiceHeader IsNot Nothing Then
                        _AssetsHandling2.InvoiceHeader.AssetsHandlingStatus = _AssetsHandlingStatus
                    End If
                Next
            End If
        Next

        _ocur.CommitChanges()
    End Sub

    Private Sub aAssetsHandling_GroupChange_CustomizePopupWindowParams(sender As Object, e As CustomizePopupWindowParamsEventArgs) Handles aAssetsHandling_GroupChange.CustomizePopupWindowParams
        Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
        Dim _AssetsHandlingGroupChange As AssetsHandlingGroupChange = _onew.CreateObject(Of AssetsHandlingGroupChange)()
        _AssetsHandlingGroupChange.QueueIndex = 0
        e.View = Application.CreateDetailView(_onew, "AssetsHandlingGroupChange_DetailView", False, _AssetsHandlingGroupChange)
    End Sub

    Private Sub aAssetsHandling_GroupChange_Execute(sender As Object, e As PopupWindowShowActionExecuteEventArgs) Handles aAssetsHandling_GroupChange.Execute
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _AssetsHandling As AssetsHandling
        Dim _AssetsHandlingGroupChange As AssetsHandlingGroupChange = TryCast(e.PopupWindow.View.SelectedObjects(0), AssetsHandlingGroupChange)
        RaiseEvent InitWork(1, 1, View.SelectedObjects.Count)

        Frame.GetController(Of Validation.PersistenceValidationController).Active.SetItemValue("", False)
        For Each _AssetsHandling In View.SelectedObjects
            RaiseEvent DoWork()
            If _AssetsHandlingGroupChange.IsQueueIndex Then
                _AssetsHandling.QueueIndex = _AssetsHandlingGroupChange.QueueIndex
                If _AssetsHandling.InvoiceHeader IsNot Nothing Then
                    _AssetsHandling.InvoiceHeader.AssetsHandlingStatus = _ocur.GetObject(_AssetsHandlingGroupChange.AssetsHandlingStatus)
                End If
            End If

            If _AssetsHandlingGroupChange.IsAssetsHandling_Note_Customers Then _AssetsHandling.Customers.AssetsHandling_Note = _AssetsHandlingGroupChange.AssetsHandling_Note_Customers
            If _AssetsHandlingGroupChange.IsAssetsHandling_Note_Invoice Then _AssetsHandling.InvoiceHeader.AssetsHandling_Note = _AssetsHandlingGroupChange.AssetsHandling_Note_Invoice
            If _AssetsHandlingGroupChange.AktivModifies Then _AssetsHandling.IsActive = _AssetsHandlingGroupChange.IsActive
            If _AssetsHandlingGroupChange.NoAssetsHandlingModifies Then _AssetsHandling.NoAssetsHandling = _AssetsHandlingGroupChange.NoAssetsHandling
            If _AssetsHandlingGroupChange.IsAssetsHandling_InvoiceHeader_Modifies Then _AssetsHandling.InvoiceHeader.IsAssetsHandling = _AssetsHandlingGroupChange.IsAssetsHandling_InvoiceHeader
            If _AssetsHandlingGroupChange.NoAssetsHandlingModifies Then _AssetsHandling.Customers.IsAssetsHandling = _AssetsHandlingGroupChange.NoAssetsHandling
            If _AssetsHandlingGroupChange.AktivModifies Then _AssetsHandling.IsActive = _AssetsHandlingGroupChange.IsActive

            If _AssetsHandlingGroupChange.IsLateChargeModifies Then _AssetsHandling.InvoiceHeader.IsLateCharge = _AssetsHandlingGroupChange.IsLateCharge

        Next
        RaiseEvent FinalWork
        _ocur.CommitChanges()
        Frame.GetController(Of Validation.PersistenceValidationController).Active.SetItemValue("", True)
    End Sub

    Private Sub aViewLateCharges_AssetsHandling_CustomizePopupWindowParams(sender As Object, e As CustomizePopupWindowParamsEventArgs) Handles aViewLateCharges_AssetsHandling.CustomizePopupWindowParams
        Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)

        If View.SelectedObjects.Count > 0 Then
            Dim _AssetsHandling As AssetsHandling = TryCast(View.SelectedObjects(0), AssetsHandling)
            Dim _CustomersFrom As CustomersFrom = _AssetsHandling.CustomersFrom
            Dim _Customers As Customers = _AssetsHandling.Customers
            Dim _DocumentNumber As String = _AssetsHandling.DocumentNumber
            Dim _DateClose As Date = _AssetsHandling.DateClose
            Dim _CS As New CollectionSource(_onew, GetType(LateCharges))
            Dim _InvoiceHeader As InvoiceHeader = _ocur.FindObject(Of InvoiceHeader) _
                                                  (CriteriaOperator.Parse("CustomersFrom=? and Customers=? and DocumentNumber=?", _
                                                                          _CustomersFrom, _Customers, _DocumentNumber))

            If _InvoiceHeader IsNot Nothing Then

                CreateLateCharges(_ocur.Session, _InvoiceHeader, _DateClose, True, True)

                _ocur.CommitChanges()

                _CS.BeginUpdateCriteria()
                _CS.Criteria.Clear()
                _CS.Criteria("First") = CriteriaOperator.Parse("InvoiceHeader.Oid=?", _InvoiceHeader.Oid)
                _CS.EndUpdateCriteria()

                _CS.Sorting.Clear()
                _CS.Sorting.Add(New SortProperty("DateExecution", DB.SortingDirection.Descending))

                e.View = Application.CreateListView("LateCharges_ListView_Info", _CS, False)
            End If
        Else
            Throw New UserFriendlyException("Nincs kiválasztott elem.")
        End If
    End Sub

    Private Sub aViewLateCharges_AssetsHandling_Execute(sender As Object, e As PopupWindowShowActionExecuteEventArgs) Handles aViewLateCharges_AssetsHandling.Execute

    End Sub

    Private Sub aSelectCustomersFromAssetsHandlingPCI_CustomizePopupWindowParams(sender As Object, e As CustomizePopupWindowParamsEventArgs) Handles aSelectCustomersFromAssetsHandlingPCI.CustomizePopupWindowParams
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace


        Dim _CS As New CollectionSource(_onew, GetType(CustomersFrom))

        '_CS.BeginUpdateCriteria()
        '_CS.Criteria.Clear()
        '_CS.Criteria("First") = ""
        '_CS.EndUpdateCriteria()

        e.View = Application.CreateListView("CustomersFrom_ListView_Select", _CS, False)
    End Sub

    Private Sub aSelectCustomersFromAssetsHandlingPCI_Execute(sender As Object, e As PopupWindowShowActionExecuteEventArgs) Handles aSelectCustomersFromAssetsHandlingPCI.Execute
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _uow As New UnitOfWork(_ocur.Session.DataLayer)
        Dim _Customersfrom As CustomersFrom
        Dim _AssetsPCIHeader As AssetsPCIHeader = TryCast(TryCast(View, ListView).CollectionSource, PropertyCollectionSource).MasterObject
        Dim _AssetsPCICustomersFrom As AssetsPCICustomersFrom

        If _AssetsPCIHeader Is Nothing Then Exit Sub

        If e.PopupWindow.View.SelectedObjects.Count > 0 Then

            For Each _Customersfrom In e.PopupWindow.View.SelectedObjects
                _AssetsPCICustomersFrom = New AssetsPCICustomersFrom(_uow)
                _AssetsPCICustomersFrom.AssetsPCIHeader = _uow.GetObjectByKey(Of AssetsPCIHeader)(_AssetsPCIHeader.Oid)
                _AssetsPCICustomersFrom.CustomersFrom = _uow.GetObjectByKey(Of CustomersFrom)(_Customersfrom.Oid)
            Next
            _uow.CommitChanges()
        End If

        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 aCreateLateChargesDocument_CustomizePopupWindowParams(sender As Object, e As CustomizePopupWindowParamsEventArgs) Handles aCreateLateChargesDocument.CustomizePopupWindowParams
        Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
        Dim _LateChargesPopup As LateChargesPopup = _onew.CreateObject(Of LateChargesPopup)()

        e.View = Application.CreateDetailView(_onew, "LateChargesPopup_DetailView", True, _LateChargesPopup)
    End Sub

    Private Sub aCreateLateChargesDocument_Execute(sender As Object, e As PopupWindowShowActionExecuteEventArgs) Handles aCreateLateChargesDocument.Execute
        Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
        Dim _LateChargesPopup As LateChargesPopup = TryCast(e.PopupWindow.View.SelectedObjects(0), LateChargesPopup)
        Dim _PCIGroup As PCIGroup
        Dim _GLMixed As GLMixed
        Dim _GLRows As GLRows
        Dim _GLMixedNG As GLMixedNG
        Dim _uow As New UnitOfWork(_onew.Session.DataLayer)
        RaiseEvent InitWork(1, 1, View.SelectedObjects.Count)

        For Each _PCIGroup In View.SelectedObjects
            RaiseEvent DoWork()
            _PCIGroup = _onew.GetObject(_PCIGroup)

            If _PCIGroup.InvoiceHeader IsNot Nothing And _PCIGroup.InvoiceHeader.AssetsHandling_GLMixed Is Nothing Then
                If _PCIGroup.InvoiceHeader.LateChargesBalanceHUF > 0 And _PCIGroup.InvoiceHeader.IsLateCharge Then
                    _GLMixedNG = _onew.FindObject(Of GLMixedNG)(CriteriaOperator.Parse("CustomersFrom.Oid=?", _PCIGroup.CustomersFrom.Oid))
                    If _GLMixedNG IsNot Nothing Then
                        _GLMixed = _onew.CreateObject(Of GLMixed)()

                        _GLMixed.CustomersFrom = _PCIGroup.CustomersFrom
                        _GLMixed.CurrencyName = _onew.FindObject(Of CurrencyName)(CriteriaOperator.Parse("ShortName='HUF'"))
                        _GLMixed.DocumentNumber = _GLMixedNG.NumberGenerator_LateCharges.GetNewNumber(_GLMixedNG.NumberGenerator_LateCharges)
                        _GLMixed.DateCreated = _LateChargesPopup.DateCreated
                        _GLMixed.DateExecution = _LateChargesPopup.DateCreated
                        _GLMixed.DatePayment = _LateChargesPopup.DateCreated
                        _GLMixed.CurrencyRate = 1
                        _GLMixed.ImportedInvoice = _PCIGroup.InvoiceHeader
                        _GLMixed.GLDocumentType = eGLDocumentType.eLateCharge

                        _GLRows = _onew.CreateObject(Of GLRows)()
                        _GLRows.GLHeader = TryCast(_GLMixed, GLHeader)
                        _GLRows.PartnerType = ePartnerType.eReceivables
                        _GLRows.ConnectInfo = _PCIGroup.ConnectInfo
                        _GLRows.Customer = _PCIGroup.Customers
                        _GLRows.AmountHUF = _PCIGroup.InvoiceHeader.LateChargesBalanceHUF
                        _GLRows.OutAmountHUF = _PCIGroup.InvoiceHeader.LateChargesBalanceHUF
                        _GLRows.CreditChartOfAccounts = _GLMixedNG.CreditControlling_LateCharges.GetChartOfAccounts(_LateChargesPopup.DateCreated.Year, False)
                        _GLRows.DebitChartOfAccounts = _GLMixedNG.DebitControlling_LateCharges.GetChartOfAccounts(_LateChargesPopup.DateCreated.Year, False)

                        _PCIGroup.InvoiceHeader.AssetsHandling_GLMixed = _GLMixed
                        _onew.CommitChanges()

                        GLFunctions.ReconfigurePCI(_uow, _PCIGroup.CustomersFrom, _PCIGroup.Customers, ePartnerType.eReceivables, _PCIGroup.ConnectInfo)

                    End If
                End If
            End If
        Next

        RaiseEvent FinalWork

    End Sub

    Private Sub aRemoveLateChargesDocument_Execute(sender As Object, e As SimpleActionExecuteEventArgs) Handles aRemoveLateChargesDocument.Execute
        Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
        Dim _PCIGroup As PCIGroup
        Dim _uow As New UnitOfWork(_onew.Session.DataLayer)

        RaiseEvent InitWork(1, 1, View.SelectedObjects.Count)
        For Each _PCIGroup In View.SelectedObjects
            RaiseEvent DoWork()

            _PCIGroup = _onew.GetObject(_PCIGroup)


            If _PCIGroup.InvoiceHeader.AssetsHandling_GLMixed IsNot Nothing Then
                
                _onew.Delete(_PCIGroup.InvoiceHeader.AssetsHandling_GLMixed.GLRows)
                _onew.Delete(_PCIGroup.InvoiceHeader.AssetsHandling_GLMixed)
                _PCIGroup.InvoiceHeader.AssetsHandling_GLMixed = Nothing
                _onew.CommitChanges()

                GLFunctions.ReconfigurePCI(_uow, _PCIGroup.CustomersFrom, _PCIGroup.Customers, ePartnerType.eReceivables, _PCIGroup.ConnectInfo)
            End If
        Next

        RaiseEvent FinalWork
    End Sub

    Private Sub aPrintLateChargesDocument_Execute(sender As Object, e As SimpleActionExecuteEventArgs) Handles aPrintLateChargesDocument.Execute

        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _ReportData As ReportData
        Dim _AssetsHandlingParameter As AssetsHandlingParameter
        Dim _PCIGroup As PCIGroup = TryCast(View.SelectedObjects(0), PCIGroup)

        _AssetsHandlingParameter = _ocur.FindObject(Of AssetsHandlingParameter)(CriteriaOperator.Parse("CustomersFrom=?", _PCIGroup.CustomersFrom))

        If _AssetsHandlingParameter IsNot Nothing Then
            _ReportData = _AssetsHandlingParameter.ReportData_LateChargesDocument
            If _ReportData IsNot Nothing Then

                Frame.GetController(Of Reports.ReportServiceController).ShowPreview(_ReportData, CriteriaOperator.Parse("GLHeader.GLDocumentType='eLateCharge' and GLHeader.ImportedInvoice.IsLateCharge=True"), True)
            Else
                Throw New UserFriendlyException("Nincs beállítva a késedelmi kamatlevél nyomtatvány !")
            End If
        End If
    End Sub
End Class

