Imports System
Imports System.ComponentModel

Imports DevExpress.Xpo
Imports DevExpress.Data.Filtering

Imports DevExpress.ExpressApp.ConditionalAppearance
Imports DevExpress.ExpressApp
Imports DevExpress.Persistent.Base
Imports DevExpress.Persistent.BaseImpl
Imports DevExpress.Persistent.Validation
Imports System.Linq
Imports System.Linq.Expressions

'-- Bejövő megrendelés ---------------------------------------------------------------------------------------------------

'<EditorStateRule("OrderInHeader.Customers.DisableEditor", "Customers", ViewType.DetailView, "IsNull(Contacts) = False", EditorState.Disabled)> _
'<EditorStateRule("Disable all properties when IsEditable = False", "OrderInParameters;CustomersFrom;Customers;DocumentNumber;Contacts;DateCreated;DateExecution;ObjectCreated;IsEditable;IsStorno", ViewType.DetailView, "IsEditable = False", EditorState.Disabled)> _
'<EditorStateRuleAttribute("Disable OrderInParameters when is not empty in OrderIn", "OrderInParameters", ViewType.DetailView, "IsNull(OrderInParameters) = False", EditorState.Disabled)> _
'<EditorStateRuleAttribute("Disable Customers when is not empty in OrderIn", "Customers", ViewType.DetailView, "IsNull(Customers) = False", EditorState.Disabled)> _
'<EditorStateRuleAttribute("Disable CustomresFrom when is not empty in CustomresFrom", "CustomersFrom", ViewType.DetailView, "IsNull(CustomersFrom) = False", EditorState.Disabled)> _
'<EditorStateRuleAttribute("Disable CRM_Opportunities when is not empty in CRM_Opportunities", "CRM_Opportunities", ViewType.DetailView, "IsNull(CRM_Opportunities) = False", EditorState.Disabled)> _
'<EditorStateRuleAttribute("Disable Contacts when is not empty in Contacts", "Contacts", ViewType.DetailView, "IsNull(Contacts) = False", EditorState.Disabled)> _
'<EditorStateRuleAttribute("Disable CRM_Opportunities when IsEditable=False", "CRM_Opportunities", ViewType.DetailView, " IsEditable=False", EditorState.Disabled)> _

'<Appearance("Hide Item2", AppearanceItemType.LayoutItem, "IsNull(DocumentNumber) Or IsNull(OrderInParameters) Or (IsNull(CustomersFrom) Or IsNull(Customers))", TargetItems:="Item2", visibility:=Editors.ViewItemVisibility.Hide)> _
'<Appearance("Hide Item4", AppearanceItemType.LayoutItem, "IsNull(DocumentNumber) Or IsNull(OrderInParameters) Or (IsNull(CustomersFrom) Or IsNull(Customers))", TargetItems:="Item4", visibility:=Editors.ViewItemVisibility.Hide)> _

<DefaultClassOptions()>
<NavigationItem("BusinessTransactions")>
<Appearance("OrderInHeader.Customers.DisableEditor", TargetItems:="Customers", Criteria:="IsNull(Contacts) = False", Enabled:=False, Context:="DetailView")>
<Appearance("Disable all properties when IsEditable = False", TargetItems:="OrderInParameters;CustomersFrom;Customers;DocumentNumber;Contacts;DateCreated;DateExecution;ObjectCreated;IsEditable;IsStorno", Criteria:="IsEditable = False", Enabled:=False, Context:="DetailView")>
<Appearance("Disable Customers when is not empty in OrderIn", TargetItems:="Customers", Criteria:="IsNull(DocumentNumber) = False", Enabled:=False, Context:="DetailView")>
<Appearance("Disable CustomresFrom when is not empty in CustomresFrom", TargetItems:="CustomersFrom", Criteria:="IsNull(CustomersFrom) = False", Enabled:=False, Context:="DetailView")>
<Appearance("Disable CRM_Opportunities when is not empty in CRM_Opportunities", TargetItems:="CRM_Opportunities", Criteria:="IsNull(CRM_Opportunities) = False", Enabled:=False, Context:="DetailView")>
<Appearance("Disable CRM_Opportunities when IsEditable=False", TargetItems:="CRM_Opportunities", Criteria:="IsEditable=False", Enabled:=False, Context:="DetailView")>
<Appearance("Hide Tab_OrderInRows", AppearanceItemType.LayoutItem, "IsNull(DocumentNumber) Or IsNull(OrderInParameters) Or (IsNull(CustomersFrom) Or IsNull(Customers))", TargetItems:="Tab_OrderInRows", Visibility:=Editors.ViewItemVisibility.Hide)>
<Appearance("Hide Tab_OrderInAcknoledgement", AppearanceItemType.LayoutItem, "IsNull(DocumentNumber) Or IsNull(OrderInParameters) Or (IsNull(CustomersFrom) Or IsNull(Customers))", TargetItems:="Tab_OrderInAcknoledgement", Visibility:=Editors.ViewItemVisibility.Hide)>
<Appearance("Hide Tab_DeliveryNoteOutRows", AppearanceItemType.LayoutItem, "IsNull(DocumentNumber) Or IsNull(OrderInParameters) Or (IsNull(CustomersFrom) Or IsNull(Customers))", TargetItems:="Tab_DeliveryNoteOutRows", Visibility:=Editors.ViewItemVisibility.Hide)>
<Appearance("Hide AddRows and RemoveRows", AppearanceItemType.Action, "IsNull(OrderInParameters) Or (IsNull(CustomersFrom) Or IsNull(Customers))", TargetItems:="aToTable_OrderIn;aToTableD_OrderIn;aToTable_OrderInOther;aToTableD_OrderInOther", Visibility:=Editors.ViewItemVisibility.Hide)>
<Appearance("Hide AddRows and RemoveRows when IsEditable=False", AppearanceItemType.Action, "IsEditable=False", TargetItems:="aToTable_OrderIn;aToTableD_OrderIn;aToTable_OrderInOther;aToTableD_OrderInOther", Visibility:=Editors.ViewItemVisibility.Hide)>
<Appearance("Hide row_Products and row_QTT when IsEditable=False", AppearanceItemType.ViewItem, "IsEditable=False", TargetItems:="row_o_DiscountPercent;row_o_ListPriceDEV;row_o_ListPriceHUF;row_o_VAT;row_o_Units;row_o_QTT;row_o_Description;row_o_ShortName;row_Products;row_QTT", Visibility:=Editors.ViewItemVisibility.Hide)>
<Appearance("Hide DEV properties when CurrencyName = HUF", AppearanceItemType.ViewItem, "OrderInParameters.CurrencyName.ShortName = 'HUF'", TargetItems:="row_o_ListPriceDEV", Visibility:=Editors.ViewItemVisibility.Hide)>
<Appearance("Hide HUF properties when CurrencyName != HUF", AppearanceItemType.ViewItem, "OrderInParameters.CurrencyName.ShortName != 'HUF'", TargetItems:="row_o_ListPriceHUF", Visibility:=Editors.ViewItemVisibility.Hide)>
<Appearance("Hide row_ info when IsEditable=False OrderIn", AppearanceItemType.ViewItem, "IsEditable=False", TargetItems:="row_Products; row_QTT; row_o_ShortName;" _
    & "row_o_Description; row_o_QTT; row_o_Units; row_o_VAT; row_o_ListPriceHUF; row_o_ListPriceDEV; row_o_DiscountPercent", Visibility:=Editors.ViewItemVisibility.Hide)>
<Appearance("Hide aGenerateStorageOutFromOrderIn when IsEditable=False", AppearanceItemType.Action, "IsEditable=False", TargetItems:="aGenerateStorageOutFromOrderIn", Visibility:=Editors.ViewItemVisibility.Hide)>
<Appearance("Hide aGenerateStorageOutFromOrderInFIFO when IsEditable=False", AppearanceItemType.Action, "IsEditable=False", TargetItems:="aGenerateStorageOutFromOrderInFIFO", Visibility:=Editors.ViewItemVisibility.Hide)>
<Appearance("Hide aGenerateStorageOutFromOrderInBack when IsEditable=False", AppearanceItemType.Action, "IsEditable=False", TargetItems:="aGenerateStorageOutFromOrderInBack", Visibility:=Editors.ViewItemVisibility.Hide)>
<Appearance("Hide aProductFinder when IsEditable=False", AppearanceItemType.Action, "IsEditable=False", TargetItems:="aProductFinder", Visibility:=Editors.ViewItemVisibility.Hide)>
<Appearance("Hide aGenerateOrderOutTempFromOrderIn when IsEditable=False", AppearanceItemType.Action, "IsEditable=False", TargetItems:="aGenerateOrderOutTempFromOrderIn", Visibility:=Editors.ViewItemVisibility.Hide)>
<Appearance("Disable ObjectCreated OrderInHeader", AppearanceItemType.ViewItem, "1=1", TargetItems:="ObjectCreated", Enabled:=False)>
<Appearance("Disable UserCreated OrderInHeader", AppearanceItemType.ViewItem, "1=1", TargetItems:="UserCreated", Enabled:=False)>
<Appearance("Hide row_APCSheetByProducts", AppearanceItemType.ViewItem, "OrderInParameters.IsAPCSheet<>True", TargetItems:="row_APCSheetByProducts", Visibility:=Editors.ViewItemVisibility.Hide)>
<Appearance("OrderInHeader - Disable OfferOutHeader all times", AppearanceItemType.ViewItem, "1=1", TargetItems:="OfferOutHeader", Enabled:=False)>
<DefaultProperty("DocumentNumber")>
Public Class OrderInHeader
    Inherits BaseObject
    Private _OrderInParameters As OrderInParameters 'Bejövő megrendelés paraméterei
    Private _OfferOutHeader As OfferOutHeader 'Kimenő árajánlat kapcsolata
    Private _CustomersFrom As CustomersFrom 'Saját cég
    Private _Customers As Customers 'Ügyfél
    Private _CustomersRefNumber As String 'partner megrendelési referencia száma
    Private _DocumentNumber As String 'Sorszám
    Private _Contacts As Contacts 'Kapcsolat
    Private _DateCreated As Date 'Létrehozás dátuma
    Private _DateExecution As Date 'Végrehajtás dátuma
    Private _ObjectCreated As Date 'Az objektum létrejöttének időpontja
    Private _UserCreated As User
    Private _IsEditable As Boolean = True 'Végleges e? 
    Private _IsStorno As Boolean = False 'Stornó e? 
    Private _TotalBruttoHUF As Double = 0 'Teljes összeg bruttó HUF
    Private _TotalBruttoDEV As Double = 0 ' Teljes összeg bruttó DEV
    Private _PaymentOption As PaymentOption 'Fizetési opció
    Private _ShipmentOption As ShipmentOption 'Szállítási opció
    Private _QualityOption As QualityOption 'Minőségi opció

    Private _PermissionAllowed As Boolean 'Engedélyzve, vagy sem.
    Private _WorkflowSystemSteps As WorkflowSystemSteps 'Folyamatlépések

    '-- CRM miatt
    Private _CRM_Opportunities As CRM_Opportunities
    '-- Non persistent
    Private _row_Products As ProductSelect 'Termék, ami meg lett rendelve
    Private _row_QTT As Double 'Termék rendelt mennyisége
    Private _row_DiscountPercent As Double 'Kedvezmény %-ban !
    Private _row_APCSheetByProducts As APCSheetByProducts 'Termeltetési szerződés
    Private _row_ListPriceHUF As Double 'Értékesítési listaár
    Private _row_ListPriceDEV As Double 'Értékesítési listaár DEVIZA

    '-- Non persistent for other rows
    Private _row_o_APCSheetByProducts As APCSheetByProducts 'Termeltetési szerződés
    Private _row_o_CustomsTariffs As CustomsTariffs 'SZJ szám
    Private _row_o_ShortName As String 'Megnevezés
    Private _row_o_Description As String 'Leírás
    Private _row_o_QTT As Double 'Mennyiség
    Private _row_o_Units As Units 'Mennyiségi egység
    Private _row_o_VAT As VAT 'ÁFA kód
    Private _row_o_ListPriceHUF As Double 'Termék listaára HUF
    Private _row_o_ListPriceDEV As Double 'Termék listaára DEV
    Private _row_o_DiscountPercent As Double 'Termék ár kedvezmény %-ban

    Public Sub New(ByVal session As Session)
        MyBase.New(session)
    End Sub
    Public Overrides Sub AfterConstruction()
        MyBase.AfterConstruction()

        DateCreated = GetSQLTime(Session)
        DateExecution = GetSQLTime(Session)
        ObjectCreated = GetSQLTime(Session)
        Me.row_o_VAT = Session.FindObject(Of VAT)(CriteriaOperator.Parse("DefaultForBusinnes=True"))
        Me.row_o_Units = Session.FindObject(Of Units)(CriteriaOperator.Parse("DefaultForBusinnes=True"))
    End Sub
    Protected Overrides Sub OnSaving()
        MyBase.OnSaving()
        If IsDeleted = False Then
            If Session.IsNewObject(Me) Then
                ObjectCreated = GetSQLTime(Session)
                UserCreated = Session.GetObjectByKey(Of User)(Session.GetKeyValue(SecuritySystem.CurrentUser))
            End If
            If String.IsNullOrEmpty(DocumentNumber) Then
                DocumentNumber = OrderInParameters.NumberGenerator.GetNewNumber(OrderInParameters.NumberGenerator)
            End If

            RecalculateHeaderTotalBrutto()

            If Me.OrderInParameters IsNot Nothing Then
                If Me.ShipmentOption Is Nothing And Me.OrderInParameters.ShipmentOption IsNot Nothing Then
                    Me.ShipmentOption = Me.OrderInParameters.ShipmentOption
                End If
                If Me.QualityOption Is Nothing And Me.OrderInParameters.QualityOption IsNot Nothing Then
                    Me.QualityOption = Me.OrderInParameters.QualityOption
                End If
            End If
        End If
    End Sub
    <ImmediatePostData(True), DataSourceCriteria("CustomersFrom='@This.CustomersFrom'")>
    Property OfferOutHeader As OfferOutHeader
        Get
            Return _OfferOutHeader
        End Get
        Set(value As OfferOutHeader)
            SetPropertyValue("OfferOutHeader", _OfferOutHeader, value)
        End Set
    End Property

    <RuleRequiredField("ROrderInHeader.OrderInParameters", DefaultContexts.Save)>
    <ImmediatePostData(True), DataSourceCriteria("CustomersFrom = '@This.CustomersFrom'")>
    Property OrderInParameters() As OrderInParameters
        Get
            Return _OrderInParameters
        End Get
        Set(ByVal value As OrderInParameters)
            SetPropertyValue("OrderInParameters", _OrderInParameters, value)
        End Set
    End Property
    <RuleRequiredField("OrderInHeader.CustomersFrom", DefaultContexts.Save)>
    Property CustomersFrom() As CustomersFrom
        Get
            Return _CustomersFrom
        End Get
        Set(ByVal value As CustomersFrom)
            SetPropertyValue("CustomersFrom", _CustomersFrom, value)
        End Set
    End Property
    <RuleRequiredField("OrderInHeader.Customers", DefaultContexts.Save)>
    <ImmediatePostData>
    Property Customers() As Customers
        Get
            Return _Customers
        End Get
        Set(ByVal value As Customers)
            SetPropertyValue("Customers", _Customers, value)
            If Not Session.IsObjectsSaving And Not Session.IsObjectsLoading Then
                If value IsNot Nothing Then
                    If value.PaymentOption IsNot Nothing And Me.PaymentOption Is Nothing Then
                        Me.PaymentOption = value.PaymentOption
                    End If
                    If value.ShipmentOption IsNot Nothing And Me.ShipmentOption Is Nothing Then
                        Me.ShipmentOption = value.ShipmentOption
                    End If
                    If value.QualityOption IsNot Nothing And Me.QualityOption Is Nothing Then
                        Me.QualityOption = value.QualityOption
                    End If
                End If
            End If
        End Set
    End Property
    Property CustomersRefNumber As String
        Get
            Return _CustomersRefNumber
        End Get
        Set(value As String)
            SetPropertyValue("CustomersRefNumber", _CustomersRefNumber, value)
        End Set
    End Property
    <NonCloneable()>
    Property DocumentNumber() As String
        Get
            Return _DocumentNumber
        End Get
        Set(ByVal value As String)
            SetPropertyValue("DocumentNumber", _DocumentNumber, value)
        End Set
    End Property
    <RuleRequiredField("OrderInHeader.Contacts", DefaultContexts.Save)>
    <ImmediatePostData(True), DataSourceProperty("Customers.Contacts", DataSourcePropertyIsNullMode.CustomCriteria, "Oid=Oid")>
    Property Contacts() As Contacts
        Get
            Return _Contacts
        End Get
        Set(ByVal value As Contacts)
            SetPropertyValue("Contacts", _Contacts, value)
        End Set
    End Property
    <NonCloneable()>
    Property DateCreated() As Date
        Get
            Return _DateCreated
        End Get
        Set(ByVal value As Date)
            SetPropertyValue("DateCreated", _DateCreated, value)
        End Set
    End Property
    <NonCloneable()>
    Property DateExecution() As Date
        Get
            Return _DateExecution
        End Get
        Set(ByVal value As Date)
            SetPropertyValue("DateExecution", _DateExecution, value)
        End Set
    End Property
    <NonCloneable()>
    Property ObjectCreated() As Date
        Get
            Return _ObjectCreated
        End Get
        Set(ByVal value As Date)
            SetPropertyValue("ObjectCreated", _ObjectCreated, value)
        End Set
    End Property
    <NonCloneable()>
    Property UserCreated As User
        Get
            Return _UserCreated
        End Get
        Set(value As User)
            SetPropertyValue("UserCreated", _UserCreated, value)
        End Set
    End Property
    Property IsEditable() As Boolean
        Get
            Return _IsEditable
        End Get
        Set(ByVal value As Boolean)
            SetPropertyValue("IsEditable", _IsEditable, value)
        End Set
    End Property
    Property IsStorno() As Boolean
        Get
            Return _IsStorno
        End Get
        Set(ByVal value As Boolean)
            SetPropertyValue("IsStorno", _IsStorno, value)
        End Set
    End Property
    Property TotalBruttoHUF As Double
        Get
            Return _TotalBruttoHUF
        End Get
        Set(ByVal value As Double)
            SetPropertyValue("TotalBruttoHUF", _TotalBruttoHUF, value)
        End Set
    End Property
    Property TotalBruttoDEV As Double
        Get
            Return _TotalBruttoDEV
        End Get
        Set(ByVal value As Double)
            SetPropertyValue("TotalBruttoDEV", _TotalBruttoDEV, value)
        End Set
    End Property
    Property PaymentOption As PaymentOption
        Get
            Return _PaymentOption
        End Get
        Set(value As PaymentOption)
            SetPropertyValue("PaymentOption", _PaymentOption, value)
        End Set
    End Property
    Property ShipmentOption As ShipmentOption
        Get
            Return _ShipmentOption
        End Get
        Set(value As ShipmentOption)
            SetPropertyValue("ShipmentOption", _ShipmentOption, value)
        End Set
    End Property
    Property QualityOption() As QualityOption
        Get
            Return _QualityOption
        End Get
        Set(ByVal value As QualityOption)
            SetPropertyValue("QualityOption", _QualityOption, value)
        End Set
    End Property

    Property PermissionAllowed As Boolean
        Get
            Return _PermissionAllowed
        End Get
        Set(value As Boolean)
            SetPropertyValue("PermissionAllowed", _PermissionAllowed, value)
        End Set
    End Property
    <ImmediatePostData(True), DataSourceCriteria("WorkflowSystem.CustomersFrom = '@This.OrderInParameters.WorkflowSystem'")>
    Property WorkflowSystemSteps As WorkflowSystemSteps
        Get
            Return _WorkflowSystemSteps
        End Get
        Set(value As WorkflowSystemSteps)
            SetPropertyValue("WorkflowSystemSteps", _WorkflowSystemSteps, value)
        End Set
    End Property
    '-- CRM miatt
    <Association("CRM_Opportunities-OrderInHeader", GetType(CRM_Opportunities))>
    Property CRM_Opportunities As CRM_Opportunities
        Get
            Return _CRM_Opportunities
        End Get
        Set(ByVal value As CRM_Opportunities)
            SetPropertyValue("CRM_Opportunities", _CRM_Opportunities, value)
        End Set
    End Property
    '-- Non persistent
    <NonPersistent()>
    <RuleRequiredField("OrderInHeader-row_Products", "aToTable_OrderIn")>
    <VisibleInListView(False)>
    Property row_Products As ProductSelect
        Get
            Return _row_Products
        End Get
        Set(ByVal value As ProductSelect)
            SetPropertyValue("row_Products", _row_Products, value)
        End Set
    End Property
    <NonPersistent()>
    <RuleRange("OrderInHeader-row_QTT", "aToTable_OrderIn", 0.0001, Double.MaxValue)>
    <VisibleInListView(False)>
    Property row_QTT As Double
        Get
            Return _row_QTT
        End Get
        Set(ByVal value As Double)
            SetPropertyValue("row_QTT", _row_QTT, value)
        End Set
    End Property
    <NonPersistent, VisibleInListView(False), VisibleInLookupListView(False)>
    Property row_DiscountPercent As Double
        Get
            Return _row_DiscountPercent
        End Get
        Set(value As Double)
            SetPropertyValue("row_DiscountPercent", _row_DiscountPercent, value)
        End Set
    End Property
    <NonPersistent>
    <RuleRequiredField("OrderInHeader-row_APCSheetByProducts", "aToTable_OrderIn", TargetCriteria:="OrderInParameters.IsAPCSheet=True")>
    <ImmediatePostData(True), DataSourceCriteria("APCSheetHeader.Customers='@This.Customers' and APCSheetHeader.CustomersFrom='@This.CustomersFrom'")>
    Property row_APCSheetByProducts As APCSheetByProducts
        Get
            Return _row_APCSheetByProducts
        End Get
        Set(value As APCSheetByProducts)
            SetPropertyValue("row_APCSheetByProducts", _row_APCSheetByProducts, value)
        End Set
    End Property
    <NonPersistent>
    Property row_ListPriceHUF As Double
        Get
            Return _row_ListPriceHUF
        End Get
        Set(value As Double)
            SetPropertyValue("row_ListPriceHUF", _row_ListPriceHUF, value)
        End Set
    End Property
    <NonPersistent>
    Property row_ListPriceDEV As Double
        Get
            Return _row_ListPriceDEV
        End Get
        Set(value As Double)
            SetPropertyValue("row_ListPriceDEV", _row_ListPriceDEV, value)
        End Set
    End Property
    '-- Non persistent for other rows
    <NonPersistent>
    <RuleRequiredField("OrderInHeader-row_o_APCSheetByProducts", "aToTable_OrderInOther_Context", TargetCriteria:="OrderInParameters.IsAPCSheet=True")>
    <ImmediatePostData(True), DataSourceCriteria("APCSheetHeader.Customers='@This.Customers' and APCSheetHeader.CustomersFrom='@This.CustomersFrom'")>
    Property row_o_APCSheetByProducts As APCSheetByProducts
        Get
            Return _row_o_APCSheetByProducts
        End Get
        Set(value As APCSheetByProducts)
            SetPropertyValue("row_o_APCSheetByProducts", _row_o_APCSheetByProducts, value)
        End Set
    End Property
    <NonPersistent()>
    <RuleRequiredField("OrderInHeader-row_o_CustomsTariffs", "aToTable_OrderInOther_Context")>
    <VisibleInListView(False)>
    Property row_o_CustomsTariffs As CustomsTariffs
        Get
            Return _row_o_CustomsTariffs
        End Get
        Set(value As CustomsTariffs)
            SetPropertyValue("row_o_CustomsTariffs", _row_o_CustomsTariffs, value)
        End Set
    End Property
    <NonPersistent()>
    <RuleRequiredField("OrderInHeader-row_o_ShortName", "aToTable_OrderInOther_Context")>
    <VisibleInListView(False)>
    Property row_o_ShortName As String
        Get
            Return _row_o_ShortName
        End Get
        Set(value As String)
            SetPropertyValue("row_o_ShortName", _row_o_ShortName, value)
        End Set
    End Property
    <NonPersistent()>
    <RuleRequiredField("OrderInHeader-row_o_Description", "aToTable_OrderInOther_Context")>
    <VisibleInListView(False)>
    Property row_o_Description As String
        Get
            Return _row_o_Description
        End Get
        Set(value As String)
            SetPropertyValue("row_o_Description", _row_o_Description, value)
        End Set
    End Property
    <NonPersistent()>
    <RuleValueComparison("OrderInHeader-row_o_QTT", "aToTable_OrderInOther_Context", ValueComparisonType.NotEquals, 0)>
    <VisibleInListView(False)>
    Property row_o_QTT As Double
        Get
            Return _row_o_QTT
        End Get
        Set(value As Double)
            SetPropertyValue("row_o_QTT", _row_o_QTT, value)
        End Set
    End Property
    <NonPersistent()>
    <RuleRequiredField("OrderInHeader-row_o_Units", "aToTable_OrderInOther_Context")>
    <VisibleInListView(False)>
    Property row_o_Units As Units
        Get
            Return _row_o_Units
        End Get
        Set(value As Units)
            SetPropertyValue("row_o_Units", _row_o_Units, value)
        End Set
    End Property
    <NonPersistent()>
    <RuleRequiredField("OrderInHeader-row_o_VAT", "aToTable_OrderInOther_Context")>
    <VisibleInListView(False)>
    Property row_o_VAT As VAT
        Get
            Return _row_o_VAT
        End Get
        Set(value As VAT)
            SetPropertyValue("row_o_VAT", _row_o_VAT, value)
        End Set
    End Property
    <NonPersistent()>
    <RuleRange("OrderInHeader-row_o_ListPriceHUF", "aToTable_OrderInOther_Context", 0.0001, Double.MaxValue, TargetCriteria:="OrderInParameters.CurrencyName.ShortName = 'HUF'")>
    <VisibleInListView(False)>
    Property row_o_ListPriceHUF As Double
        Get
            Return _row_o_ListPriceHUF
        End Get
        Set(value As Double)
            SetPropertyValue("row_o_ListPriceHUF", _row_o_ListPriceHUF, value)
        End Set
    End Property
    <NonPersistent()>
    <RuleRange("OrderInHeader-row_o_ListPriceDEV", "aToTable_OrderInOther_Context", 0.0001, Double.MaxValue, TargetCriteria:="OrderInParameters.CurrencyName.ShortName != 'HUF'")>
    <VisibleInListView(False)>
    Property row_o_ListPriceDEV As Double
        Get
            Return _row_o_ListPriceDEV
        End Get
        Set(value As Double)
            SetPropertyValue("row_o_ListPriceDEV", _row_o_ListPriceDEV, value)
        End Set
    End Property
    <NonPersistent()>
    <RuleRange("OrderInHeader-row_o_DiscountPercent", "aToTable_OrderInOther_Context", 0, 99)>
    <VisibleInListView(False)>
    Property row_o_DiscountPercent As Double
        Get
            Return _row_o_DiscountPercent
        End Get
        Set(value As Double)
            SetPropertyValue("row_o_DiscountPercent", _row_o_DiscountPercent, value)
        End Set
    End Property

    '-- XPCollections
    <VisibleInListView(False)>
    <Association("OrderInHeader-OrderInHeaderVAT", GetType(OrderInHeaderVAT))>
    ReadOnly Property OrderInHeaderVAT As XPCollection(Of OrderInHeaderVAT)
        Get
            Return GetCollection(Of OrderInHeaderVAT)("OrderInHeaderVAT")
        End Get
    End Property
    <VisibleInListView(False)>
    <Association("OrderInHeader-OrderInAcknowledgementHeader", GetType(OrderInAcknowledgementHeader))>
    ReadOnly Property OrderInAcknowledgementHeader As XPCollection(Of OrderInAcknowledgementHeader)
        Get
            Return GetCollection(Of OrderInAcknowledgementHeader)("OrderInAcknowledgementHeader")
        End Get
    End Property
    <VisibleInListView(False)>
    ReadOnly Property OrderInTo As XPCollection(Of OrderInTo)
        Get
            Return New XPCollection(Of OrderInTo)(Session, CriteriaOperator.Parse("OrderInRows.OrderInHeader.Oid=?", Me.Oid))
        End Get
    End Property
    <VisibleInListView(False)>
    <Association("OrderInHeader", GetType(OrderInRows))>
    ReadOnly Property OrderInRows() As XPCollection
        Get
            Return GetCollection("OrderInRows")
        End Get
    End Property
    <VisibleInListView(False)>
    <Association("OrderInHeader-OrderInRowsOther", GetType(OrderInRowsOther))>
    ReadOnly Property OrderInRowsOther As XPCollection(Of OrderInRowsOther)
        Get
            Return GetCollection(Of OrderInRowsOther)("OrderInRowsOther")
        End Get
    End Property
    <VisibleInDetailView(False), VisibleInListView(False), VisibleInLookupListView(False)>
    ReadOnly Property DeliveryNoteOutRows As XPCollection(Of DeliveryNoteOutRows)
        Get
            Return New XPCollection(Of DeliveryNoteOutRows)(Session, CriteriaOperator.Parse("StorageOutRowsInRows.StorageOutRows.OrderInRows.OrderInHeader=?", Me))
        End Get
    End Property
    <VisibleInListView(False), VisibleInLookupListView(False)>
    ReadOnly Property InvoiceRows As XPCollection(Of InvoiceRows)
        Get
            Return New XPCollection(Of InvoiceRows)(Session, CriteriaOperator.Parse("(OrderInRows.OrderInHeader=? or OrderInRowsOther.OrderInHeader=?) and IsNull(InvoiceHeader.GCRecord)=True and IsNull(InvoiceHeader)=False", Me, Me))
        End Get
    End Property
    <VisibleInListView(False), VisibleInLookupListView(False)>
    ReadOnly Property InvoiceAdvance As XPCollection(Of InvoiceHeader)
        Get
            Dim _Criteria As String = ""
            _Criteria = " IsEditable=False and DocumentNumber !='' and "
            _Criteria += " InvoiceType.InvoiceTypeBase In ('eEarnestofTender','eAdvancePayment') and "
            _Criteria += " Customers=? and CustomersFrom=? and IsNull(GCRecord)=True and "
            _Criteria += " TotalBruttoHUF > TotalAdvancedBruttoHUF "

            Return New XPCollection(Of InvoiceHeader)(Session, CriteriaOperator.Parse(_Criteria, Customers, Me.CustomersFrom))
        End Get
    End Property
    <VisibleInListView(False), VisibleInLookupListView(False)>
    ReadOnly Property StorageOutRowsInRows As XPCollection(Of StorageOutRowsInRows)
        Get
            Return New XPCollection(Of StorageOutRowsInRows)(Session, CriteriaOperator.Parse("StorageOutRows.OrderInRows.OrderInHeader=? and StorageOutRows.QTT<>0", Me))
        End Get
    End Property
    <VisibleInListView(False), VisibleInLookupListView(False)>
    ReadOnly Property StorageMoveEvents As XPCollection(Of StorageMoveEvents)
        Get
            Return New XPCollection(Of StorageMoveEvents)(Session, CriteriaOperator.Parse("StorageOutRows.OrderInRows.OrderInHeader=?", Me))
        End Get
    End Property
    <Association("OrderInheader-OrderInheaderFileAttachment", GetType(OrderInHeaderFileAttachment)), VisibleInListView(False), VisibleInLookupListView(False)>
    ReadOnly Property OrderInHeaderFileAttachment As XPCollection(Of OrderInHeaderFileAttachment)
        Get
            Return GetCollection(Of OrderInHeaderFileAttachment)("OrderInHeaderFileAttachment")
        End Get
    End Property
    <VisibleInListView(False), VisibleInLookupListView(False)>
    ReadOnly Property PCIDetail As XPCollection(Of PCIDetail)
        Get
            '// Partnerhez tartozó nyitott pénzügyi teljesítések előleghez !
            Dim _PCIDetail_Collection_Return As New XPCollection(Of PCIDetail)(Session, CriteriaOperator.Parse("1=2"))
            Dim _PCIGroup_Collection As XPCollection(Of PCIGroup)
            If Me.OrderInParameters IsNot Nothing Then
                If Me.OrderInParameters.CurrencyName_Invoice.ShortName = "HUF" Then
                    _PCIGroup_Collection = New XPCollection(Of PCIGroup)(Session,
                                                CriteriaOperator.Parse(" CustomersFrom=? and Customers=? " +
                                                                       " and PartnerType=0 and CurrencyName=?" +
                                                                       " and BallanceHUF<0",
                                                Me.CustomersFrom, Me.Customers, Me.OrderInParameters.CurrencyName_Invoice))
                Else
                    _PCIGroup_Collection = New XPCollection(Of PCIGroup)(Session,
                                            CriteriaOperator.Parse(" CustomersFrom=? and Customers=? " +
                                                                   " and PartnerType=0 and CurrencyName=?" +
                                                                   " and BallanceDEV<0",
                                            Me.CustomersFrom, Me.Customers, Me.OrderInParameters.CurrencyName_Invoice))
                End If
                Dim _PCIGroup As PCIGroup
                Dim _PCIDetail As PCIDetail
                For Each _PCIGroup In _PCIGroup_Collection
                    Dim _PCIDetail_Collection As New XPCollection(Of PCIDetail)(Session, CriteriaOperator.Parse("PCIGroup=?", _PCIGroup))
                    For Each _PCIDetail In _PCIDetail_Collection
                        Select Case _PCIDetail.MainType
                            Case "03-Cassa", "02-Bank"
                                _PCIDetail_Collection_Return.Add(_PCIDetail)
                        End Select

                    Next
                Next
            End If
            Return _PCIDetail_Collection_Return
        End Get
    End Property
    Sub RecalculateOrder(ByVal _OrderInHeader As OrderInHeader, ByVal _ocur As Xpo.XPObjectSpace)
        '-- A rutin újragenerálja a pénzügyi sorokat
        Dim _OrderInHeaderVAT As OrderInHeaderVAT

        Dim i As Long = 1
        Dim j As Long = 1
        Dim _Exists As Boolean = False

        _ocur.Delete(_OrderInHeader.OrderInHeaderVAT)
        Dim orderinrows = New XPQuery(Of OrderInRows)(_ocur.Session)
        Dim query = From orderinrow In orderinrows Where orderinrow.OrderInHeader.Oid = _OrderInHeader.Oid
                    Group orderinrow By orderinrow.Products.VAT Into g = Group
                    Select New With {Key .VAT = VAT,
                             Key .AmountNettoHUF = g.Sum(Function(inv) (inv.ListPriceHUF - inv.DiscountPriceHUF) * inv.QTT),
                             Key .AmountNettoDEV = g.Sum(Function(inv) (inv.ListPriceDEV - inv.DiscountPriceDEV) * inv.QTT),
                             Key .S2 = g.Sum(Function(inv) inv.ListPriceDEV),
                             Key .M1 = g.Max(Function(inv) inv.DiscountPriceHUF * inv.QTT)}
        For Each item In query
            _OrderInHeaderVAT = _ocur.CreateObject(Of OrderInHeaderVAT)()
            _OrderInHeaderVAT.OrderInHeader = _OrderInHeader
            _OrderInHeaderVAT.AmountNettoHUF = Math.Round(item.AmountNettoHUF, 0, MidpointRounding.AwayFromZero)
            _OrderInHeaderVAT.AmountVATHUF = 0
            _OrderInHeaderVAT.VAT = item.VAT
            If item.VAT IsNot Nothing Then
                _OrderInHeaderVAT.AmountVATHUF = Math.Round(item.VAT.KeyValue * _OrderInHeaderVAT.AmountNettoHUF, 0, MidpointRounding.AwayFromZero)
            End If
            _OrderInHeaderVAT.AmountBruttoHUF = _OrderInHeaderVAT.AmountNettoHUF + _OrderInHeaderVAT.AmountVATHUF

            _OrderInHeaderVAT.AmountNettoDEV = Math.Round(item.AmountNettoDEV, 2, MidpointRounding.AwayFromZero)
            _OrderInHeaderVAT.AmountVATDEV = 0
            If item.VAT IsNot Nothing Then
                _OrderInHeaderVAT.AmountVATDEV = Math.Round(item.VAT.KeyValue * _OrderInHeaderVAT.AmountNettoDEV, 2, MidpointRounding.AwayFromZero)
            End If
            _OrderInHeaderVAT.AmountBruttoDEV = _OrderInHeaderVAT.AmountNettoDEV + _OrderInHeaderVAT.AmountVATDEV

            _OrderInHeaderVAT.Save()
            _OrderInHeader.OrderInHeaderVAT.Add(_OrderInHeaderVAT)
        Next

        Dim orderinrowsother = New XPQuery(Of OrderInRowsOther)(_ocur.Session)
        Dim query1 = From orderinrowo In orderinrowsother Where orderinrowo.OrderInHeader.Oid = _OrderInHeader.Oid
                     Group orderinrowo By orderinrowo.VAT Into g = Group
                     Select New With {Key .VAT = VAT,
                             Key .AmountNettoHUF = g.Sum(Function(inv) (inv.ListPriceHUF - inv.DiscountPriceHUF) * inv.QTT),
                             Key .AmountNettoDEV = g.Sum(Function(inv) (inv.ListPriceDEV - inv.DiscountPriceDEV) * inv.QTT),
                             Key .S2 = g.Sum(Function(inv) inv.ListPriceDEV),
                             Key .M1 = g.Max(Function(inv) inv.DiscountPriceHUF * inv.QTT)}
        For Each item In query1
            _OrderInHeaderVAT = _ocur.CreateObject(Of OrderInHeaderVAT)()
            _OrderInHeaderVAT.OrderInHeader = _OrderInHeader
            _OrderInHeaderVAT.AmountNettoHUF = Math.Round(item.AmountNettoHUF, 0, MidpointRounding.AwayFromZero)
            _OrderInHeaderVAT.AmountVATHUF = 0
            _OrderInHeaderVAT.VAT = item.VAT
            If item.VAT IsNot Nothing Then
                _OrderInHeaderVAT.AmountVATHUF = Math.Round(item.VAT.KeyValue * _OrderInHeaderVAT.AmountNettoHUF, 0, MidpointRounding.AwayFromZero)
            End If
            _OrderInHeaderVAT.AmountBruttoHUF = _OrderInHeaderVAT.AmountNettoHUF + _OrderInHeaderVAT.AmountVATHUF

            _OrderInHeaderVAT.AmountNettoDEV = Math.Round(item.AmountNettoDEV, 2, MidpointRounding.AwayFromZero)
            _OrderInHeaderVAT.AmountVATDEV = 0
            If item.VAT IsNot Nothing Then
                _OrderInHeaderVAT.AmountVATDEV = Math.Round(item.VAT.KeyValue * _OrderInHeaderVAT.AmountNettoDEV, 2, MidpointRounding.AwayFromZero)
            End If
            _OrderInHeaderVAT.AmountBruttoDEV = _OrderInHeaderVAT.AmountNettoDEV + _OrderInHeaderVAT.AmountVATDEV

            _OrderInHeaderVAT.Save()
            _OrderInHeader.OrderInHeaderVAT.Add(_OrderInHeaderVAT)
        Next


        Dim _TotalBruttoDEV As Double = 0
        Dim _TotalBruttoHUF As Double = 0

        For Each _OrderInHeaderVAT In _OrderInHeader.OrderInHeaderVAT
            _TotalBruttoHUF += _OrderInHeaderVAT.AmountBruttoHUF
            _TotalBruttoDEV += _OrderInHeaderVAT.AmountBruttoDEV
        Next
        _OrderInHeader.TotalBruttoHUF = _TotalBruttoHUF
        _OrderInHeader.TotalBruttoDEV = _TotalBruttoDEV
        _OrderInHeader.Save()
    End Sub
    Function SubjectToApproval(_OrderInHeader As OrderInHeader, _ocur As Xpo.XPObjectSpace) As Boolean
        Dim _Approval As Boolean = False
        If _OrderInHeader.OrderInParameters.NeedPermission Then                                                 'V-REND-0009-13
            Dim _PermissionDay As Long = _OrderInHeader.OrderInParameters.NeedPersmissionPaymentDay
            If _OrderInHeader.PaymentOption IsNot Nothing Then
                If _PaymentOption.PayMode <> ePayMode.InCash Then
                    If _PaymentOption.PayDay > _PermissionDay Then _Approval = True

                    If Not _Approval Then
                        Dim _VolumeByCustomersHUF As Double = _OrderInHeader.OrderInParameters.NeedPermissionVolumeByCustomersHUF
                        Dim _CustomersHUF As Double = 0

                        Dim _OrderInHeader_Collection As New XPCollection(Of OrderInHeader)(_ocur.Session, CriteriaOperator.Parse("Customers.Oid=? AND IsEditable=True", _OrderInHeader.Customers.Oid))

                        For Each _OrderInHeaderAct As OrderInHeader In _OrderInHeader_Collection
                            _OrderInHeaderAct.RecalculateOrder(_OrderInHeader, _ocur)
                            _CustomersHUF += _OrderInHeader.TotalBruttoHUF
                        Next

                        If _CustomersHUF > _VolumeByCustomersHUF Then _Approval = True
                    End If
                End If
            End If
        End If

        Return _Approval
    End Function

    Public Sub RecalculateHeaderTotalBrutto()
        Dim _OrderInRows As OrderInRows
        Dim _VAT_DefaultForExternalEUNoVAT As VAT = Session.FindObject(Of VAT)(CriteriaOperator.Parse("DefaultForExternalEUNoVAT=True"))
        Dim _VAT_DefaultForBusinnes As VAT = Session.FindObject(Of VAT)(CriteriaOperator.Parse("DefaultForBusinnes=True"))
        Dim _VAT_DefaultForExternalOther As VAT = Session.FindObject(Of VAT)(CriteriaOperator.Parse("DefaultForExternalOther=True"))
        Dim _VAT_DefaultForInversVAT As VAT = Session.FindObject(Of VAT)(CriteriaOperator.Parse("DefaultForInversVAT=True"))

        TotalBruttoDEV = 0
        TotalBruttoHUF = 0

        For Each _OrderInRows In Me.OrderInRows

            If Me.OrderInParameters IsNot Nothing Then
                Select Case Me.OrderInParameters.ExportMode
                    Case eExportMode.eExternalEUNoVAT
                        _OrderInRows.VAT = _VAT_DefaultForExternalEUNoVAT
                    Case eExportMode.eExternalEUwithVAT
                        _OrderInRows.VAT = _OrderInRows.Products.VAT
                    Case eExportMode.eExternalOther
                        _OrderInRows.VAT = _VAT_DefaultForExternalOther
                    Case eExportMode.eInternalwithVAT
                        _OrderInRows.VAT = _OrderInRows.Products.VAT
                    Case eExportMode.eInversVAT
                        _OrderInRows.VAT = _VAT_DefaultForInversVAT
                End Select
                _OrderInRows.RecalculateRows()
                _OrderInRows.Save()
            End If

            If _OrderInRows.APCSheetByProducts IsNot Nothing Then
                _OrderInRows.RecalculateRows()
                _OrderInRows.Save()
            End If
            TotalBruttoDEV += _OrderInRows.SumPriceBruttoDEV
            TotalBruttoHUF += _OrderInRows.SumPriceBruttoHUF
        Next
        Dim _OrderInRowsOther As OrderInRowsOther
        For Each _OrderInRowsOther In Me.OrderInRowsOther

            If Me.OrderInParameters IsNot Nothing Then
                Select Case Me.OrderInParameters.ExportMode
                    Case eExportMode.eExternalEUNoVAT
                        _OrderInRowsOther.VAT = _VAT_DefaultForExternalEUNoVAT
                    Case eExportMode.eExternalEUwithVAT
                        _OrderInRowsOther.VAT = _VAT_DefaultForBusinnes
                    Case eExportMode.eExternalOther
                        _OrderInRowsOther.VAT = _VAT_DefaultForExternalOther
                    Case eExportMode.eInversVAT
                        _OrderInRowsOther.VAT = _VAT_DefaultForInversVAT
                End Select
                _OrderInRowsOther.RecalculateRows()
                _OrderInRowsOther.Save()
            End If
            TotalBruttoDEV += _OrderInRowsOther.SumPriceBruttoDEV
            TotalBruttoHUF += _OrderInRowsOther.SumPriceBruttoHUF
        Next
    End Sub

End Class
