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.Persistent.BaseImpl
Imports DevExpress.ExpressApp.SystemModule
Imports DevExpress.ExpressApp.CloneObject
Imports DevExpress.Xpo
Imports DevExpress.Xpo.DB
Imports DevExpress.ExpressApp.Utils
Imports System.Reflection
Imports System.IO

Public Class CustomersVC
    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 Sub New()
        MyBase.New()
        'This call is required by the Component Designer.
        InitializeComponent()
        RegisterActions(components)
    End Sub
#Region "Overrides"
    Protected Overrides Sub OnActivated()
        MyBase.OnActivated()

        Frame.GetController(Of CustomersVC).aCustomersSetToCustomers.Active.SetItemValue("", False)

        If View.Id = "CustomersNG_ListView" Or View.Id = "CustomersNG_LookupListView" Then
            Dim _CustomersNG As CustomersNG

            _CustomersNG = TryCast(View.ObjectSpace, Xpo.XPObjectSpace).Session.FindObject(Of CustomersNG)(1, CriteriaOperator.Parse("Oid=Oid"))

            If _CustomersNG Is Nothing Then
                Frame.GetController(Of DevExpress.ExpressApp.SystemModule.NewObjectViewController)().Active.SetItemValue("", True)
            Else
                Frame.GetController(Of DevExpress.ExpressApp.SystemModule.NewObjectViewController)().Active.SetItemValue("", False)
            End If
        End If
        If View.Id = "Customers_CRM_Opportunities_ListView" Then
            Frame.GetController(Of NewObjectViewController)().Active.SetItemValue("", False)
            'Frame.GetController(Of LinkDialogController)().Active.SetItemValue("", False)
            Frame.GetController(Of LinkUnlinkController)().Active.SetItemValue("", False)
            Frame.GetController(Of CloneObjectViewController)().Active.SetItemValue("", False)
        End If
        If View.Id = "CustomersNGCollection_DetailView" Then
            Frame.GetController(Of NewObjectViewController)().Active.SetItemValue("", False)
            Frame.GetController(Of CloneObjectViewController)().Active.SetItemValue("", False)
            Frame.GetController(Of LinkUnlinkController)().Active.SetItemValue("", False)
        End If
        If View.Id = "Customers_CustomersBankAccounts_ListView" Then
            Frame.GetController(Of CloneObjectViewController).Active.SetItemValue("", False)
            Frame.GetController(Of LinkDialogController).Active.SetItemValue("", False)
            Frame.GetController(Of LinkUnlinkController).Active.SetItemValue("", False)
        End If
        If View.Id = "CustomersFrom_CustomersBankAccounts_ListView" Then
            Frame.GetController(Of CloneObjectViewController).Active.SetItemValue("", False)
            Frame.GetController(Of LinkDialogController).Active.SetItemValue("", False)
            Frame.GetController(Of LinkUnlinkController).Active.SetItemValue("", False)
        End If
        If View.Id = "Customers_DetailView" Then
            Frame.GetController(Of CloneObjectViewController).Active.SetItemValue("", False)
            AddHandler Frame.GetController(Of DeleteObjectsViewController).DeleteAction.Executing, AddressOf Customers_DetailView_DeleteAction_Executing
            AddHandler Frame.GetController(Of ModificationsController).SaveAction.Executing, AddressOf Customers_DetailView_Save_Executing
            AddHandler Frame.GetController(Of ModificationsController).SaveAndCloseAction.Executing, AddressOf Customers_DetailView_Save_Executing
            AddHandler Frame.GetController(Of ModificationsController).SaveAndNewAction.Executing, AddressOf Customers_DetailView_Save_Executing
        End If
        If View.Id = "Customers_LookupListView" Then
            'Frame.GetController(Of NewObjectViewController)().Active.SetItemValue("", False)
            Frame.GetController(Of CloneObjectViewController)().Active.SetItemValue("", False)
        End If
        If View.Id = "CustomersFileAttachment_ListView" Then
            Frame.GetController(Of DevExpress.ExpressApp.SystemModule.DeleteObjectsViewController).Active.SetItemValue("", False)
        End If
        If View.Id = "Customers_CustomersFileAttachment_ListView" Then
            Frame.GetController(Of DevExpress.ExpressApp.SystemModule.DeleteObjectsViewController).Active.SetItemValue("", False)
        End If
        If View.Id = "Customers_Customers_BusinessDirectory_ListView" Then
            Frame.GetController(Of LinkUnlinkController)().Active.SetItemValue("", False)
            Frame.GetController(Of CloneObjectViewController)().Active.SetItemValue("", False)
        End If

        If View.Id = "Customers_ListView_Deleted" Then
            Frame.GetController(Of CustomersVC).aCreateOpportunityFromCustomers.Active.SetItemValue("", False)
            Frame.GetController(Of CustomersVC).aCustomersToCustomersOrder.Active.SetItemValue("", False)
            Frame.GetController(Of CustomersVC).aPCICheck_Customers.Active.SetItemValue("", False)
            Frame.GetController(Of CustomersVC).aCustomers_CreateBusinessDirectory.Active.SetItemValue("", False)
            Frame.GetController(Of CustomersVC).aMergeCustomers.Active.SetItemValue("", False)

            Frame.GetController(Of CloneObject.CloneObjectViewController).Active.SetItemValue("", False)
            Frame.GetController(Of DeleteObjectsViewController).Active.SetItemValue("", False)
            If TryCast(View, ListView) IsNot Nothing Then
                If TryCast(View, ListView).CollectionSource IsNot Nothing Then
                    If TryCast(View, ListView).CollectionSource.Collection IsNot Nothing Then
                        If TryCast(TryCast(View, ListView).CollectionSource.Collection, ProxyCollection) IsNot Nothing Then
                            If TryCast(TryCast(View, ListView).CollectionSource.Collection, ProxyCollection).OriginalCollection IsNot Nothing Then
                                If TryCast(TryCast(TryCast(View, ListView).CollectionSource.Collection, ProxyCollection).OriginalCollection, XPCollection) IsNot Nothing Then
                                    TryCast(TryCast(TryCast(View, ListView).CollectionSource.Collection, ProxyCollection).OriginalCollection, XPCollection).SelectDeleted = True
                                End If
                            End If
                        End If
                    End If
                End If
            End If
        End If

    End Sub
    Protected Overrides Sub OnDeactivated()
        MyBase.OnDeactivated()
        If View.Id = "CustomersNG_ListView" Or View.Id = "CustomersNG_LookupListView" Then
            Dim _CustomersNG As CustomersNG

            _CustomersNG = TryCast(View.ObjectSpace, Xpo.XPObjectSpace).Session.FindObject(Of CustomersNG)(1, CriteriaOperator.Parse("Oid=Oid"))

            If _CustomersNG Is Nothing Then
                Frame.GetController(Of DevExpress.ExpressApp.SystemModule.NewObjectViewController)().Active.SetItemValue("", False)
            Else
                Frame.GetController(Of DevExpress.ExpressApp.SystemModule.NewObjectViewController)().Active.SetItemValue("", True)
            End If
        End If
        If View.Id = "Customers_CRM_Opportunities_ListView" Then
            Frame.GetController(Of NewObjectViewController)().Active.SetItemValue("", True)
            'Frame.GetController(Of LinkDialogController)().Active.SetItemValue("", False)
            Frame.GetController(Of LinkUnlinkController)().Active.SetItemValue("", True)
            Frame.GetController(Of CloneObjectViewController)().Active.SetItemValue("", True)
        End If
        If View.Id = "CustomersNGCollection_Deatilview" Then
            Frame.GetController(Of NewObjectViewController)().Active.SetItemValue("", True)
            Frame.GetController(Of CloneObjectViewController)().Active.SetItemValue("", True)
            Frame.GetController(Of LinkUnlinkController)().Active.SetItemValue("", True)
        End If
        If View.Id = "Customers_CustomersBankAccounts_ListView" Then
            Frame.GetController(Of CloneObjectViewController).Active.SetItemValue("", True)
            Frame.GetController(Of LinkDialogController).Active.SetItemValue("", True)
            Frame.GetController(Of LinkUnlinkController).Active.SetItemValue("", True)
        End If
        If View.Id = "CustomersFrom_CustomersBankAccounts_ListView" Then
            Frame.GetController(Of CloneObjectViewController).Active.SetItemValue("", True)
            Frame.GetController(Of LinkDialogController).Active.SetItemValue("", True)
            Frame.GetController(Of LinkUnlinkController).Active.SetItemValue("", True)
        End If
        If View.Id = "Customers_DetailView" Then
            Frame.GetController(Of CloneObjectViewController).Active.SetItemValue("", True)
        End If
        If View.Id = "Customers_LookupListView" Then
            'Frame.GetController(Of NewObjectViewController)().Active.SetItemValue("", True)
            Frame.GetController(Of CloneObjectViewController)().Active.SetItemValue("", True)
        End If
        If View.Id = "CustomersFileAttachment_ListView" Then
            Frame.GetController(Of DeleteObjectsViewController).Active.SetItemValue("", True)
        End If
        If View.Id = "Customers_CustomersFileAttachment_ListView" Then
            Frame.GetController(Of DeleteObjectsViewController).Active.SetItemValue("", True)
        End If
        If View.Id = "Customers_Customers_BusinessDirectory_ListView" Then
            Frame.GetController(Of LinkUnlinkController)().Active.SetItemValue("", True)
            Frame.GetController(Of CloneObjectViewController)().Active.SetItemValue("", True)
        End If
        If View.Id = "Customers_ListView_Deleted" Then
            Frame.GetController(Of CustomersVC).aCreateOpportunityFromCustomers.Active.SetItemValue("", True)
            Frame.GetController(Of CustomersVC).aCustomersToCustomersOrder.Active.SetItemValue("", True)
            Frame.GetController(Of CustomersVC).aPCICheck_Customers.Active.SetItemValue("", True)
            Frame.GetController(Of CustomersVC).aCustomers_CreateBusinessDirectory.Active.SetItemValue("", True)

            Frame.GetController(Of CloneObject.CloneObjectViewController).Active.SetItemValue("", True)
            Frame.GetController(Of DeleteObjectsViewController).Active.SetItemValue("", True)
            Frame.GetController(Of CustomersVC).aMergeCustomers.Active.SetItemValue("", True)
        End If
    End Sub
#End Region
    Private Sub aCreateOpportunityFromCustomers_Execute(sender As System.Object, e As DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs) Handles aCreateOpportunityFromCustomers.Execute
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _Customers As Customers = TryCast(View.SelectedObjects(0), Customers)
        Dim _CRM_Leads As CRM_Leads
        Dim _CRM_Opportunities As CRM_Opportunities
        Dim _User As User = _ocur.GetObjectByKey(Of User)(_ocur.GetKeyValue(SecuritySystem.CurrentUser))
        Dim _HRPerson As HRPerson = _ocur.FindObject(Of HRPerson)(CriteriaOperator.Parse("User=?", _User))
        Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
        Dim _CRM_FirstMeet As CRM_FirstMeet = _ocur.FindObject(Of CRM_FirstMeet)(CriteriaOperator.Parse("DefaultforBusiness=True"))
        Dim _CustomersGLParameters As CustomersGLParameters = _ocur.FindObject(Of CustomersGLParameters)(CriteriaOperator.Parse("DefaultforBusiness=True"))

        If _Customers.CustomersGLParameters Is Nothing Then
            _Customers.CustomersGLParameters = _CustomersGLParameters
        End If

        If _Customers.CRM_Leads Is Nothing Then
            _CRM_Leads = _ocur.CreateObject(Of CRM_Leads)()
            _CRM_Leads.LeadStatus = eLeadStatus.Qualified
            _CRM_Leads.Customers = _ocur.GetObject(_Customers)
            _CRM_Leads.CompanyName = _Customers.FullName
            _CRM_Leads.Topic = _Customers.FullName
            _CRM_Leads.EMail = "-"
            _CRM_Leads.MobilePhone = "-"
            _CRM_Leads.LastName = "-"
            _CRM_Leads.FirstName = "-"
            _CRM_Leads.CRM_FirstMeet = _CRM_FirstMeet

            _Customers.CRM_Leads = _CRM_Leads
        End If

        _CRM_Opportunities = _ocur.CreateObject(Of CRM_Opportunities)()
        _CRM_Opportunities.Customers = _Customers
        _CRM_Opportunities.CRM_Leads = _Customers.CRM_Leads
        _CRM_Opportunities.HRPerson = _HRPerson
        _CRM_Opportunities.CRM_Opportunities_Probability = _ocur.FindObject(Of CRM_Opportunities_Probability)(CriteriaOperator.Parse("Probability<=30 and Probability>0"))

        _ocur.CommitChanges()

        e.ShowViewParameters.CreatedView = Application.CreateDetailView(_onew, "CRM_Opportunities_DetailView", True, _onew.GetObject(_CRM_Opportunities))


    End Sub
    Private Sub Customers_DetailView_Save_Executing(sender As Object, e As CancelEventArgs)
        '// Ha elmentünk egy partnert, akkor a Name és a FullName legyen u.a.
    End Sub
    Private Sub Customers_DetailView_DeleteAction_Executing(sender As Object, e As CancelEventArgs)
        '//Csak olyan partnert lehessen törölni, amihez nincs semmi még !

    End Sub
    Private Sub aRecreateCustomersOrderDocuments_Execute(sender As System.Object, e As DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs) Handles aRecreateCustomersOrderDocuments.Execute
        Frame.GetController(Of Validation.PersistenceValidationController).Active.SetItemValue("", False)

        Try
            If View.SelectedObjects.Count = 0 Then Throw New Exception("*Nincs kiválasztva egyetlen sor sem!")
            Dim _ocur As Xpo.XPObjectSpace = View.ObjectSpace
            Dim _CustomersOrderDocuments_BASE = _ocur.FindObject(Of CustomersOrderDocuments)(CriteriaOperator.Parse("1=1"))

            If _CustomersOrderDocuments_BASE Is Nothing Then Throw New Exception("*A csoportos beállítás előtt legalább egy rendelési dokumentumot létre kell hozni!")

            Dim _NumberGenerator_BASE As NumberGenerator = _CustomersOrderDocuments_BASE.NumberGenerator

            Dim _CurrencyName_Collection As xpcollection = _ocur.CreateCollection(GetType(CurrencyName), CriteriaOperator.Parse("1=1"))
            RaiseEvent InitWork(1, 1, View.SelectedObjects.Count)
            For Each _CustomersOrder As CustomersOrder In View.SelectedObjects
                RaiseEvent DoWork()
                If _CustomersOrder.CustomersOrderDocuments.Count <> _CurrencyName_Collection.Count Then
                    For Each _CurrencyName As CurrencyName In _CurrencyName_Collection

                        Dim _CustomersOrderDocuments As CustomersOrderDocuments = _ocur.FindObject(Of CustomersOrderDocuments)(CriteriaOperator.Parse("CurrencyName.ShortName=? AND CustomersOrder=?", _
                                                                                                                                                      _CurrencyName.ShortName, _CustomersOrder))
                        If _CustomersOrderDocuments Is Nothing Then
                            Dim _NumberGenerator_NEW As NumberGenerator = _ocur.CreateObject(Of NumberGenerator)()

                            _NumberGenerator_NEW.NumberGeneratorGroups = _NumberGenerator_BASE.NumberGeneratorGroups
                            _NumberGenerator_NEW.PrefixString = _NumberGenerator_BASE.PrefixString
                            _NumberGenerator_NEW.PrefixTag = "-"
                            _NumberGenerator_NEW.SuffixString = _CurrencyName.ShortName
                            _NumberGenerator_NEW.SuffixTag = "-"
                            _NumberGenerator_NEW.SerialNumberPlace = _NumberGenerator_BASE.SerialNumberPlace
                            _NumberGenerator_NEW.SerialNumberDigit = _NumberGenerator_BASE.SerialNumberDigit
                            _NumberGenerator_NEW.YearFormat = eYearFormat.YearTwoDigit
                            _NumberGenerator_NEW.NewNumberPerYear = _NumberGenerator_BASE.NewNumberPerYear
                            _NumberGenerator_NEW.ShortName = "Szállítói rendelések sorszámai: " & _CustomersOrder.DisplayName & ", " & _CurrencyName.ShortName
                            _NumberGenerator_NEW.MonthAfterYear = _NumberGenerator_BASE.MonthAfterYear

                            Dim _CustomersOrderDocuments_NEW As CustomersOrderDocuments = _ocur.CreateObject(Of CustomersOrderDocuments)()

                            _CustomersOrderDocuments_NEW.CurrencyName = _CurrencyName
                            _CustomersOrderDocuments_NEW.CustomersOrder = _CustomersOrder
                            _CustomersOrderDocuments_NEW.NumberGenerator = _NumberGenerator_NEW
                            _CustomersOrderDocuments_NEW.OrderOutMainType = eOrderOutMainType.eFromProducts

                            _CustomersOrder.CustomersOrderDocuments.Add(_CustomersOrderDocuments_NEW)


                            Dim _OrderOutHeader_Collection As xpcollection = _ocur.CreateCollection(GetType(OrderOutHeader), CriteriaOperator.Parse("CustomersOrder=? AND CurrencyName.ShortName=?", _
                                                                                                                                                    _CustomersOrder, _CurrencyName.ShortName))
                            If _OrderOutHeader_Collection.Count Then
                                For Each _OrderOutHeader As OrderOutHeader In _OrderOutHeader_Collection
                                    _OrderOutHeader.CustomersOrderDocuments = _CustomersOrderDocuments_NEW
                                Next
                            End If
                        End If
                    Next
                    _ocur.CommitChanges()
                End If
            Next
            RaiseEvent FinalWork
            Frame.GetController(Of Validation.PersistenceValidationController).Active.SetItemValue("", True)
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub
    Private Sub aCustomersFileAttachment_ChangeGroup_CustomizePopupWindowParams(sender As Object, e As DevExpress.ExpressApp.Actions.CustomizePopupWindowParamsEventArgs) Handles aCustomersFileAttachment_ChangeGroup.CustomizePopupWindowParams
        Try
            Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
            Dim _ChangeFileAttachment_PopUp As ChangeFileAttachment_PopUp = _onew.CreateObject(Of ChangeFileAttachment_PopUp)()

            e.View = Application.CreateDetailView(_onew, "ChangeFileAttachment_PopUp_DetailView", True, _ChangeFileAttachment_PopUp)
            e.View.Tag = e.Action.Id
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly, "Hiba")
        End Try
    End Sub
    Private Sub aCustomersFileAttachment_ChangeGroup_Execute(sender As System.Object, e As DevExpress.ExpressApp.Actions.PopupWindowShowActionExecuteEventArgs) Handles aCustomersFileAttachment_ChangeGroup.Execute
        Try
            Dim _ocur As Xpo.XPObjectSpace = View.ObjectSpace
            Dim _ChangeFileAttachment_PopUp As ChangeFileAttachment_PopUp = TryCast(e.PopupWindow.View.SelectedObjects(0), ChangeFileAttachment_PopUp)
            For Each _CustomersFileAttachment As CustomersFileAttachment In View.SelectedObjects
                If _ChangeFileAttachment_PopUp.ChangeStatus = True Then
                    _CustomersFileAttachment.Status = _ChangeFileAttachment_PopUp.Status
                End If
                If _ChangeFileAttachment_PopUp.ChangeRowGroup1 = True Then
                    _CustomersFileAttachment.RowGroup1 = _ChangeFileAttachment_PopUp.RowGroup1
                End If
                If _ChangeFileAttachment_PopUp.ChangeRowGroup2 = True Then
                    _CustomersFileAttachment.RowGroup2 = _ChangeFileAttachment_PopUp.RowGroup2
                End If
            Next
            _ocur.CommitChanges()
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly, "Hiba")
        End Try
    End Sub

    Private Sub aMergeCustomers_CustomizePopupWindowParams(sender As Object, e As CustomizePopupWindowParamsEventArgs) Handles aMergeCustomers.CustomizePopupWindowParams
        Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
        Dim _CustomersMergePopup As CustomersMergePopup = _onew.CreateObject(Of CustomersMergePopup)()
        Dim _Customers As Customers
        _CustomersMergePopup.CustomersMain = _onew.GetObject(TryCast(View.SelectedObjects(0), Customers))
        _CustomersMergePopup.Customers = New XPCollection(Of Customers)(_onew.Session, CriteriaOperator.Parse("1=2"))
        For Each _Customers In View.SelectedObjects
            If _Customers Is View.SelectedObjects(0) Then
            Else
                _CustomersMergePopup.Customers.Add(_onew.GetObject(_Customers))
            End If
        Next
        e.View = Application.CreateDetailView(_onew, "CustomersMergePopup_DetailView", True, _CustomersMergePopup)

    End Sub

    Private Sub aMergeCustomers_Execute(sender As Object, e As PopupWindowShowActionExecuteEventArgs) Handles aMergeCustomers.Execute
        Try
            Frame.GetController(Of Validation.PersistenceValidationController).Active.SetItemValue("", False)
            Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
            Dim _CustomersMergePopup As CustomersMergePopup = e.PopupWindow.View.SelectedObjects(0)
            Dim _Object As Object

            For Each _Customers As Customers In _CustomersMergePopup.Customers
                For Each _Object In _onew.Session.CollectReferencingObjects(_onew.GetObjectByKey(Of Customers)(_Customers.Oid))
                    Try
                        'Debug.Print(_Object)
                        For Each _PropertyInfo As PropertyInfo In _Object.GetType.GetProperties
                            If _PropertyInfo.PropertyType.Name = "Customers" Then
                                '_Object.setvalue(_PropertyInfo.Name) = _onew.GetObjectByKey(Of Customers)(_CustomersMergePopup.CustomersMain.Oid)
                                _PropertyInfo.SetValue(_Object, _onew.GetObjectByKey(Of Customers)(_CustomersMergePopup.CustomersMain.Oid), Nothing)
                            End If
                        Next

                    Catch ex As Exception
                        Throw New Exception(ex.Message)
                    End Try
                Next
            Next
            _onew.CommitChanges()
        Catch ex As Exception
            MsgBox(ex.Message)
        Finally
            Frame.GetController(Of Validation.PersistenceValidationController).Active.SetItemValue("", True)
        End Try

    End Sub

    Private Sub aGetCustomersQuota_Execute(sender As Object, e As SimpleActionExecuteEventArgs) Handles aGetCustomersQuota.Execute
        '// Forgalmak számolása a Quoták alapján
    End Sub

    Private Sub aCustomersFileAttachmentRemove_Execute(sender As Object, e As SimpleActionExecuteEventArgs) Handles aCustomersFileAttachmentRemove.Execute
        Try
            Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
            Dim _ListView As ListView = TryCast(View, ListView)
            Dim _PropertyCollectionSource As PropertyCollectionSource = TryCast(_ListView.CollectionSource, PropertyCollectionSource)

            Dim _Customers As Customers = TryCast(_PropertyCollectionSource.MasterObject, Customers)
            Dim _CustomersOrderPriority As CustomersOrderPriority = TryCast(_PropertyCollectionSource.MasterObject, CustomersOrderPriority)

            For Each _CustomersFileAttachment As CustomersFileAttachment In e.SelectedObjects
                If _Customers IsNot Nothing Then
                    _Customers.CustomersFileAttachment.Remove(_CustomersFileAttachment)
                End If
                If _CustomersOrderPriority IsNot Nothing Then
                    _CustomersOrderPriority.CustomersOrder.CustomersFileAttachment.Remove(_CustomersFileAttachment)
                End If
            Next
            _ocur.CommitChanges()

        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, String.Format(CaptionHelper.GetLocalizedText("Exceptions\SISBusinessExceptions", "MsgBoxCheckItAgain")))
        End Try
    End Sub
    Private Sub aCustomers_Open_Execute(sender As Object, e As SimpleActionExecuteEventArgs) Handles aCustomers_Open.Execute
        Try
            Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
            Dim _Customers As Customers = _onew.GetObject(TryCast(View.SelectedObjects(0), Customers))
            If _Customers Is Nothing Then Throw New Exception("*Nem lehet azonosítani a partnert!")

            e.ShowViewParameters.CreatedView = Application.CreateDetailView(_onew, "Customers_DetailView", True, _Customers)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, String.Format(CaptionHelper.GetLocalizedText("Exceptions\SISBusinessExceptions", "MsgBoxCheckItAgain")))
        End Try
    End Sub

    Private Sub aPCICheck_Customers_Execute(sender As Object, e As SimpleActionExecuteEventArgs) Handles aPCICheck_Customers.Execute
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _uow As New UnitOfWork(_ocur.Session.DataLayer)

        Dim _Customers As Customers
        Dim _CustomersFrom As CustomersFrom
        Dim _CustomersFrom_Collection As New XPCollection(Of CustomersFrom)(_uow)

        For Each _Customers In View.SelectedObjects
            _Customers = _uow.GetObjectByKey(Of Customers)(_Customers.Oid)

            For Each _CustomersFrom In _CustomersFrom_Collection
                Select Case GLOBAL_SQLType
                    Case eSQLType.PostgreSQL
                        _uow.ExecuteNonQuery("delete from ""PCIDetail"" where ""Customers""='" & _
                                 _Customers.Oid.ToString & "' and ""CustomersFrom""='" & _
                                 _CustomersFrom.Oid.ToString & "'")
                        _uow.CommitChanges()
                        _uow.ExecuteNonQuery("update ""InvoiceHeader"" set ""PCIGroup""=NULL where ""PCIGroup"" not in (select ""PCIGroup"" from ""PCIDetail"")")
                        _uow.ExecuteNonQuery("delete from ""PCIGroup"" where ""Oid"" not in (select ""PCIGroup"" from ""PCIDetail"")")
                        _uow.CommitChanges()
                    Case Else
                        _uow.ExecuteNonQuery("delete from PCIDetail where Customers='" & _
                                 _Customers.Oid.ToString & "' and CustomersFrom='" & _
                                 _CustomersFrom.Oid.ToString & "'")
                        _uow.CommitChanges()
                        _uow.ExecuteNonQuery("update InvoiceHeader set PCIGroup=NULL where PCIGroup not in (select PCIGroup from PCIDetail)")
                        _uow.ExecuteNonQuery("delete from PCIGroup where Oid not in (select PCIGroup from PCIDetail)")
                        _uow.CommitChanges()
                End Select

                Dim _GLAccounts_Collection As New XPCollection(Of GLAccounts)(PersistentCriteriaEvaluationBehavior.InTransaction, _
                _uow, CriteriaOperator.Parse("IsDeleted=False and CustomersFrom.Oid=? and Customers.Oid=? and IsEditable=False", _
                                            _CustomersFrom.Oid, _Customers.Oid))
                RaiseEvent InitWork(1, 1, _GLAccounts_Collection.Count)
                For Each _GLAccounts In _GLAccounts_Collection
                    RaiseEvent DoWork()
                    If _GLAccounts IsNot Nothing Then
                        GLFunctions.ReconfigurePCI(_uow, _GLAccounts.CustomersFrom, _GLAccounts.Customers, _GLAccounts.PartnerType, _GLAccounts.ConnectInfo)
                    End If
                Next
                RaiseEvent FinalWork
                Dim _InvoiceHeader_Collection As New XPCollection(Of InvoiceHeader)(PersistentCriteriaEvaluationBehavior.InTransaction, _
                    _uow, CriteriaOperator.Parse("IsDeleted=False and isnull(DocumentNumber)=False and CustomersFrom.Oid=? and Customers.Oid=? and IsEditable=False and isnull(GLAccounts)=True", _
                                                _CustomersFrom.Oid, _Customers.Oid))
                RaiseEvent InitWork(1, 1, _InvoiceHeader_Collection.Count)
                For Each _InvoiceHeader In _InvoiceHeader_Collection
                    RaiseEvent DoWork()
                    If _InvoiceHeader IsNot Nothing Then
                        GLFunctions.ReconfigurePCI(_uow, _InvoiceHeader.CustomersFrom, _InvoiceHeader.Customers, 0, _InvoiceHeader.ConnectInfo)
                    End If
                Next
                RaiseEvent FinalWork
                Dim _RegistryHeader_Collection As New XPCollection(Of RegistryHeader)(PersistentCriteriaEvaluationBehavior.InTransaction, _
                    _uow, CriteriaOperator.Parse("IsStorno=False and IsDeleted=False and RegistryAcceptState=0 and RegistryType.RegistryMainType =0 and CustomersFrom.Oid=? and Customers.Oid=? and IsEditable=False and isnull(F_GLAccounts)=True", _
                                                _CustomersFrom.Oid, _Customers.Oid))

                RaiseEvent InitWork(1, 1, _RegistryHeader_Collection.Count)
                For Each _RegistryHeader In _RegistryHeader_Collection
                    RaiseEvent DoWork()
                    If _RegistryHeader IsNot Nothing Then
                        GLFunctions.ReconfigurePCI(_uow, _RegistryHeader.CustomersFrom, _RegistryHeader.Customers, 1, _RegistryHeader.F_ConnectInfo)
                    End If
                Next
                RaiseEvent FinalWork

                Dim _GLRows_Collection As New XPCollection(Of GLRows)(PersistentCriteriaEvaluationBehavior.InTransaction, _
                _uow, CriteriaOperator.Parse("GLHeader.IsDeleted=False and GLHeader.CustomersFrom.Oid=? and Customer.Oid=? and PartnerType in (0,1) and  GLHeader.GLDocumentType in (0,2,3,4,5)", _
                                            _CustomersFrom.Oid, _Customers.Oid))

                RaiseEvent InitWork(1, 1, _GLRows_Collection.Count)
                For Each _GLRows In _GLRows_Collection
                    RaiseEvent DoWork()
                    If _GLRows IsNot Nothing Then
                        GLFunctions.ReconfigurePCI(_uow, _GLRows.GLHeader.CustomersFrom, _GLRows.Customer, _GLRows.PartnerType, _GLRows.ConnectInfo)
                    End If
                Next
                RaiseEvent FinalWork
            Next
        Next
    End Sub

    Private Sub aCustomersSetToCustomers_CustomizePopupWindowParams(sender As Object, e As CustomizePopupWindowParamsEventArgs) Handles aCustomersSetToCustomers.CustomizePopupWindowParams
        Try
            Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
            Dim _CS As New CollectionSource(_onew, GetType(Customers))

            e.View = Application.CreateListView("Customers_ListView_Select", _CS, False)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, String.Format(CaptionHelper.GetLocalizedText("Exceptions\SISBusinessExceptions", "MsgBoxCheckItAgain")))
        End Try
    End Sub
    Private Sub aCustomersSetToCustomers_Execute(sender As Object, e As PopupWindowShowActionExecuteEventArgs) Handles aCustomersSetToCustomers.Execute
        Try
            Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace



        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, String.Format(CaptionHelper.GetLocalizedText("Exceptions\SISBusinessExceptions", "MsgBoxCheckItAgain")))
        End Try
    End Sub
    Private Sub aCustomersSetSupplierMarkInfo_CustomizePopupWindowParams(sender As Object, e As CustomizePopupWindowParamsEventArgs) Handles aCustomersSetSupplierMarkInfo.CustomizePopupWindowParams
        Try
            Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
            Dim _CS As New CollectionSource(_onew, GetType(Customers))

            _CS.BeginUpdateCriteria()
            _CS.Criteria.Add("Criteria", CriteriaOperator.Parse("IsNull(SupplierMark, '')<>''"))
            _CS.EndUpdateCriteria()

            e.View = Application.CreateListView("Customers_ListView_Select", _CS, False)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, String.Format(CaptionHelper.GetLocalizedText("Exceptions\SISBusinessExceptions", "MsgBoxCheckItAgain")))
        End Try
    End Sub
    Private Sub aCustomersSetSupplierMarkInfo_Execute(sender As Object, e As PopupWindowShowActionExecuteEventArgs) Handles aCustomersSetSupplierMarkInfo.Execute
        Try
            Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
            Dim _MarkInfo As String = ""
            RaiseEvent InitWork(1, 1, View.SelectedObjects.Count)
            For Each _CustomersOnPopUp As Customers In e.PopupWindow.View.SelectedObjects
                _CustomersOnPopUp = _ocur.GetObject(_CustomersOnPopUp)
                _MarkInfo += _CustomersOnPopUp.SupplierMark + ", "
            Next

            _MarkInfo = _MarkInfo.Remove(_MarkInfo.Length - 2, 2)

            For Each _CustomersOnBaseView As Customers In View.SelectedObjects
                _CustomersOnBaseView.SupplierMarkInfo = _MarkInfo
                RaiseEvent DoWork()
            Next
            _ocur.CommitChanges()
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, String.Format(CaptionHelper.GetLocalizedText("Exceptions\SISBusinessExceptions", "MsgBoxCheckItAgain")))
        Finally
            RaiseEvent FinalWork
        End Try
    End Sub
    Private Sub aCustomersDeleteSupplierMarkInfo_Execute(sender As Object, e As SimpleActionExecuteEventArgs) Handles aCustomersDeleteSupplierMarkInfo.Execute
        Try
            Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
            RaiseEvent InitWork(1, 1, View.SelectedObjects.Count)

            For Each _Customers As Customers In View.SelectedObjects
                _Customers.SupplierMarkInfo = Nothing
                RaiseEvent DoWork()
            Next

            _ocur.CommitChanges()
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, String.Format(CaptionHelper.GetLocalizedText("Exceptions\SISBusinessExceptions", "MsgBoxCheckItAgain")))
        Finally
            RaiseEvent FinalWork
        End Try
    End Sub

    Private Sub aCustomersToContacts_Execute(sender As Object, e As SimpleActionExecuteEventArgs) Handles aCustomersToContacts.Execute
        Try
            Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
            Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
            Dim _Customers As Customers = TryCast(TryCast(TryCast(View, ListView).CollectionSource, PropertyCollectionSource).MasterObject, Customers)
            If _Customers Is Nothing Then Throw New Exception("*Váratlan hiba történt, a folyamat megszakadt!")

            Dim _Contacts As New Contacts(_onew.Session)
            With _Contacts
                .Customers = _onew.GetObject(_Customers)
                .MotherName = _Customers.MotherName
                If _Customers.BirthAddress IsNot Nothing Then
                    If _Customers.BirthAddress.City IsNot Nothing Then .BirthPlace = _Customers.BirthAddress.City
                End If

                .TAJNumber = _Customers.TAJNumber
                .Birthday = _Customers.BirthDate
                .Address1 = _onew.GetObject(_Customers.Address1)
                .Address2 = _onew.GetObject(_Customers.Address2)

            End With

            e.ShowViewParameters.CreatedView = Application.CreateDetailView(_onew, "Contacts_DetailView", True, _Contacts)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, String.Format(CaptionHelper.GetLocalizedText("Exceptions\SISBusinessExceptions", "MsgBoxCheckItAgain")))
        End Try
    End Sub

    Private Sub aCustomersToCustomersOrder_Execute(sender As Object, e As SimpleActionExecuteEventArgs) Handles aCustomersToCustomersOrder.Execute
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _SelectedData As DevExpress.Xpo.DB.SelectedData = Nothing
        Dim _SQL As String = ""
        Dim _Customers As Customers
        Dim _SelectStatementResultRow As SelectStatementResultRow
        Dim _Exists As Boolean = False
        Dim _ObjectType As Long = 0
        For Each _Customers In View.SelectedObjects
            Select Case GLOBAL_SQLType
                Case eSQLType.MSSQL, eSQLType.PostgreSQL
                    _SQL = "select ""Oid"" from ""CustomersOrder"" where ""Oid""='" & _Customers.Oid.ToString & "'"
                Case eSQLType.MySQL
                    _SQL = "select Oid from CustomersOrder where Oid='" & _Customers.Oid.ToString & "'"
            End Select

            _SelectedData = _ocur.Session.ExecuteQuery(_SQL)
            If _SelectedData.ResultSet.Length > 0 Then
                For Each _SelectStatementResultRow In _SelectedData.ResultSet(0).Rows
                    _Exists = True
                Next
            End If

            If _Exists = False Then
                Select Case GLOBAL_SQLType
                    Case eSQLType.MSSQL, eSQLType.PostgreSQL
                        _SQL = "select ""Oid"" from ""XPObjectType"" where ""TypeName""='SISBusiness.Module.CustomersOrder'"
                    Case eSQLType.MySQL
                        _SQL = "select Oid from XPObjectType where TypeName='SISBusiness.Module.CustomersOrder'"
                End Select
                _SelectedData = _ocur.Session.ExecuteQuery(_SQL)
                If _SelectedData.ResultSet.Length > 0 Then
                    For Each _SelectStatementResultRow In _SelectedData.ResultSet(0).Rows
                        _ObjectType = _SelectStatementResultRow.Values(0)
                    Next
                End If
                Select Case GLOBAL_SQLType
                    Case eSQLType.MSSQL, eSQLType.PostgreSQL
                        _SQL = "insert ""CustomersOrder"" (""Oid"") values ('" & _Customers.Oid.ToString & "')"
                    Case eSQLType.MySQL
                        _SQL = "insert CustomersOrder (Oid) values ('" & _Customers.Oid.ToString & "')"
                End Select
                _ocur.Session.ExecuteNonQuery(_SQL)
                Select Case GLOBAL_SQLType
                    Case eSQLType.MSSQL, eSQLType.PostgreSQL
                        _SQL = "Update ""Party"" set ""ObjectType""=" & _ObjectType & " where ""Oid""='" & _Customers.Oid.ToString & "'"
                    Case eSQLType.MySQL
                        _SQL = "Update Party set ObjectType=" & _ObjectType & " where Oid='" & _Customers.Oid.ToString & "'"
                End Select
                _ocur.Session.ExecuteNonQuery(_SQL)
                _ocur.CommitChanges()
                Frame.GetController(Of RefreshController).RefreshAction.DoExecute()
            End If
        Next


    End Sub
    Private Sub aCustomers_ChangeCustomers_CustomizePopupWindowParams(sender As Object, e As CustomizePopupWindowParamsEventArgs) Handles aCustomers_ChangeCustomers.CustomizePopupWindowParams
        Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
        Dim _Customers_Change_PopUP As New Customers_Change_PopUP(_onew.Session)

        e.View = Application.CreateDetailView(_onew, "Customers_Change_PopUP_DetailView", True, _Customers_Change_PopUP)
    End Sub
    Private Sub aCustomers_ChangeCustomers_Execute(sender As Object, e As PopupWindowShowActionExecuteEventArgs) Handles aCustomers_ChangeCustomers.Execute
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _Customers_Change_PopUP As Customers_Change_PopUP = _ocur.GetObject(e.PopupWindow.View.SelectedObjects(0))

        RaiseEvent InitWork(1, 1, View.SelectedObjects.Count)
        For Each _Customers As Customers In View.SelectedObjects
            If _Customers_Change_PopUP.Change_Country1 Then
                If _Customers.Address1 IsNot Nothing Then
                    _Customers.Address1.Country = _ocur.GetObject(_Customers_Change_PopUP.Country1)
                End If
            End If
            If _Customers_Change_PopUP.Change_Country2 Then
                If _Customers.Address2 IsNot Nothing Then
                    _Customers.Address2.Country = _ocur.GetObject(_Customers_Change_PopUP.Country2)
                End If
            End If
            If _Customers_Change_PopUP.Change_CreditlineDay Then
                _Customers.CreditlineDay = _Customers_Change_PopUP.CreditlineDay
            End If
            If _Customers_Change_PopUP.Change_CustomersGLParameters Then
                _Customers.CustomersGLParameters = _ocur.GetObject(_Customers_Change_PopUP.CustomersGLParameters)
            End If
            If _Customers_Change_PopUP.Change_IsAssetsHandling Then
                _Customers.IsAssetsHandling = _ocur.GetObject(_Customers_Change_PopUP.IsAssetsHandling)
            End If
            If _Customers_Change_PopUP.Change_LateChargesCountMode Then
                _Customers.LateChargesCountMode = _ocur.GetObject(_Customers_Change_PopUP.LateChargesCountMode)
            End If
            If _Customers_Change_PopUP.Change_PaymentOption Then
                _Customers.PaymentOption = _ocur.GetObject(_Customers_Change_PopUP.PaymentOption)
            End If
            If _Customers_Change_PopUP.Change_Pricing Then
                _Customers.Pricing = _ocur.GetObject(_Customers_Change_PopUP.Pricing)
            End If
            If _Customers_Change_PopUP.Change_PricingIn Then
                _Customers.PricingIn = _ocur.GetObject(_Customers_Change_PopUP.PricingIn)
            End If
            If _Customers_Change_PopUP.Change_Profile Then
                _Customers.Profile = _Customers_Change_PopUP.Profile
            End If
            If _Customers_Change_PopUP.Change_QualityOption Then
                _Customers.QualityOption = _ocur.GetObject(_Customers_Change_PopUP.QualityOption)
            End If
            If _Customers_Change_PopUP.Change_ShipmentOption Then
                _Customers.ShipmentOption = _ocur.GetObject(_Customers_Change_PopUP.ShipmentOption)
            End If
            RaiseEvent DoWork()
        Next
        _ocur.CommitChanges()
        RaiseEvent FinalWork
    End Sub
    Private Sub aCustomers_CreateBusinessDirectory_Execute(sender As Object, e As SimpleActionExecuteEventArgs) Handles aCustomers_CreateBusinessDirectory.Execute
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _Customers As Customers = TryCast(View.SelectedObjects(0), Customers)

        If _Customers.MasterBusinessDirectory Is Nothing Then
            Dim _CustomersBaseBusinessDirectory As BusinessDirectory = _ocur.FindObject(Of BusinessDirectory)(DevExpress.Data.Filtering.CriteriaOperator.Parse("ShortName='Ügyfelek' AND IsNull(BusinessDirectory_Parent)=True"))

            If _CustomersBaseBusinessDirectory Is Nothing Then
                _CustomersBaseBusinessDirectory = New BusinessDirectory(_ocur.Session)
                With _CustomersBaseBusinessDirectory
                    .ShortName = "Ügyfelek"
                    .BusinessDirectory_Parent = Nothing
                End With
            End If

            Dim _CustomersBusinessDirectory As New BusinessDirectory(_ocur.Session)
            With _CustomersBusinessDirectory
                .ShortName = String.Format("{0}  {1} {2}", _Customers.FullName, _Customers.Address1.City, _Customers.CustomerNumber)
                .BusinessDirectory_Parent = _CustomersBaseBusinessDirectory
            End With
            _CustomersBusinessDirectory.Save()
            _Customers.MasterBusinessDirectory = _CustomersBusinessDirectory
            _ocur.CommitChanges()
        End If
    End Sub

    Private Sub aViewPCIDetail_Customers_Execute(sender As Object, e As SimpleActionExecuteEventArgs) Handles aViewPCIDetail_Customers.Execute
        Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
        Dim _Customers As Customers = _onew.GetObject(TryCast(View.SelectedObjects(0), Customers))

        Dim _PCIDetail_CollectionSource As New CollectionSource(_onew, GetType(PCIDetail))

        _PCIDetail_CollectionSource.BeginUpdateCriteria()
        _PCIDetail_CollectionSource.Criteria("Customers") = CriteriaOperator.Parse("Customers=?", _Customers)
        _PCIDetail_CollectionSource.EndUpdateCriteria()

        e.ShowViewParameters.CreatedView = Application.CreateListView("PCIDetail_ListView_Customers", _PCIDetail_CollectionSource, False)


    End Sub

    Private Sub aCustomers_OpenDHUrl_Execute(sender As Object, e As SimpleActionExecuteEventArgs) Handles aCustomers_OpenDHUrl.Execute
        Dim _Customers As Customers = TryCast(View.SelectedObjects(0), Customers)
        If _Customers IsNot Nothing Then
            Dim _ExternalBrowserPath As String = Nothing
            If TryCast(Application.Model.Options, IModelOptionsExtender) IsNot Nothing Then
                If File.Exists(TryCast(Application.Model.Options, IModelOptionsExtender).ExternalBrowserPath) Then
                    _ExternalBrowserPath = TryCast(Application.Model.Options, IModelOptionsExtender).ExternalBrowserPath
                End If
            End If

            Dim _Process As New System.Diagnostics.Process

            With _Process.StartInfo
                .FileName = _ExternalBrowserPath
                .Arguments = " url """ + _Customers.Url_DH + """"
            End With

            _Process.Start()
        End If
    End Sub
End Class
