Imports System
Imports System.ComponentModel

Imports DevExpress.Xpo
Imports DevExpress.Data.Filtering

Imports DevExpress.ExpressApp
Imports DevExpress.Persistent.Base
Imports DevExpress.Persistent.BaseImpl
Imports DevExpress.Persistent.Validation
Imports DevExpress.ExpressApp.ConditionalAppearance

Imports System.Linq
Imports System.Linq.Expressions

'-- Kimenő árajánlatok --

'<EditorStateRule("Disable properties when IsEditable=False", "*", ViewType.DetailView, "IsEditable = False", EditorState.Disabled)> _

<Appearance("Disable properties when IsEditable=False", TargetItems:="*", Criteria:="IsEditable = False", Enabled:=False, Context:="DetailView")> _
<Appearance("Hide OfferLOSTReasons when eOfferOutState <> 2", AppearanceItemType.ViewItem, "OfferOutState <> 2", TargetItems:="OfferLOSTReason", visibility:=Editors.ViewItemVisibility.Hide)> _
<Appearance("Hide OfferLOSTReasonDescription when OfferLOSTReason <> 7", AppearanceItemType.ViewItem, "OfferLOSTReason <> 7", TargetItems:="OfferLOSTReasonDescription", visibility:=Editors.ViewItemVisibility.Hide)> _
<Appearance("Hide Installation when row_RowType = Product", AppearanceItemType.ViewItem, "row_RowType = 0", TargetItems:="row_VAT;row_Description;row_Installation;row_ShortName;row_Units", visibility:=Editors.ViewItemVisibility.Hide)> _
<Appearance("Hide Product when row_RowType = Installation", AppearanceItemType.ViewItem, "row_RowType = 2", TargetItems:="row_VAT;row_Products;row_Units;row_Description;row_ShortName", visibility:=Editors.ViewItemVisibility.Hide)> _
<Appearance("Hide some properties when RowType = Other", AppearanceItemType.ViewItem, "row_RowType = 1", TargetItems:="row_Installation;row_Products", visibility:=Editors.ViewItemVisibility.Hide)> _
<Appearance("Disable row action when IsEditable=False", AppearanceItemType.LayoutItem, "!IsEditable", TargetItems:="@OfferOutHeader_AC", visibility:=Editors.ViewItemVisibility.Hide)> _
<Appearance("Disable DocumentNumber, DocumentOutNumber", AppearanceItemType.ViewItem, "1=1", TargetItems:="DocumentNumber;DocumentOutNumber", Enabled:=False)> _
<Appearance("Hide CloneObject-OfferOut", AppearanceItemType.Action, "IsEditable = False", TargetItems:="CloneObject", enabled:=False)> _
<Appearance("Disable OpeneObject-OfferOut", AppearanceItemType.Action, "IsEditable = False", TargetItems:="OpenObject", Enabled:=False)> _
<Appearance("Disable Delete-OfferOut", AppearanceItemType.Action, "IsEditable = False", TargetItems:="Delete", Enabled:=False)> _
<Appearance("Disable ShowAllContexts-OfferOut", AppearanceItemType.Action, "IsEditable = False", TargetItems:="ShowAllContexts", Enabled:=False)> _
<Appearance("Hide _row_ListPriceDEV-OfferOut if CurrencyName is HUF", AppearanceItemType.ViewItem, "CurrencyName.ShortName='HUF'", TargetItems:="row_ListPriceDEV", visibility:=Editors.ViewItemVisibility.Hide)> _
<Appearance("Hide _row_ListPriceHUF-OfferOut if CurrencyName is not HUF", AppearanceItemType.ViewItem, "CurrencyName.ShortName<>'HUF'", TargetItems:="row_ListPriceHUF", visibility:=Editors.ViewItemVisibility.Hide)> _
<Appearance("Hide tab page Item3 if header is incomplete-OfferOut", AppearanceItemType.LayoutItem, "IsNull(CustomersFrom)=True Or IsNull(Contact)=True Or IsNull(Customers)=True Or IsNull(CurrencyName)=True Or IsNull(OfferOutParameters)=True Or IsNull(PaymentOption)=True", TargetItems:="Item3", visibility:=Editors.ViewItemVisibility.Hide)> _
<Appearance("Disable OfferOutHeader-Contact", AppearanceItemType.ViewItem, "IsNull(Contact)=False", TargetItems:="Contact", Enabled:=False)> _
<Appearance("Disable OfferOutHeader-Customers", AppearanceItemType.ViewItem, "IsNull(Customers)=False", TargetItems:="Customers", Enabled:=False)> _
<Appearance("Disable OfferOutHeader-CustomersFrom", AppearanceItemType.ViewItem, "IsNull(CustomersFrom)=False", TargetItems:="CustomersFrom", Enabled:=False)> _
<Appearance("Disable aOffersOutFinal", AppearanceItemType.Action, "IsEditable = False", TargetItems:="aOffersOutFinal", Enabled:=False)> _
<Appearance("Hide row_ info when IsEditable=False OffersIn", AppearanceItemType.ViewItem, "IsEditable=False", TargetItems:="row_RowType, row_Products; row_Installation;" _
    & "row_ShortName; row_Description; row_QTT; row_Units;  row_VAT; row_ListPriceHUF; row_ListPriceDEV; row_DiscountPercent; row_RowGroup1; row_RowGroup2", visibility:=Editors.ViewItemVisibility.Hide)> _
<Appearance("Disable ObjectCreated OfferOutHeader", AppearanceItemType.ViewItem, "1=1", TargetItems:="ObjectCreated", Enabled:=False)> _
<Appearance("Disable UserCreated OfferOutHeader", AppearanceItemType.ViewItem, "1=1", TargetItems:="UserCreated", Enabled:=False)> _
<DefaultClassOptions()> _
<NavigationItem("BusinessTransactions")> _
<DefaultProperty("DocumentNumber")> _
Public Class OfferOutHeader
    Inherits BaseObject
    Private _OfferOutParameters As OfferOutParameters 'Árajánlat paramétere, ami a sorszámot és egyéb tul. meghat.
    Private _OfferOutState As eOfferOutState 'Ajánlat státusz, hol tart jelenleg
    Private _OfferLOSTReason As eOfferOutLOSTReason 'Ha nem fogadták el, miért ?
    Private _OfferLOSTReasonDescription As String ' Ha nem fogadták el és eOther akkor szövegesen beírni !
    Private _DocumentNumber As String 'Árajánlat száma (generálódik)
    Private _DocumentOutNumber As String 'Árajánlat változati szám
    Private _CustomersFrom As CustomersFrom 'Saját cég
    Private _Customers As Customers 'Partner, akire az árajánlat szól (ez nem kötelező, de a contactból  ismerje fel !)
    Private _Contact As Contacts 'Kapcsolat, akire az árajánlat szól (ez a fő !!! kötelező)
    Private _DateCreated As Date 'Kiállítás dátuma
    Private _DateExecution As Date 'Teljesítés dátuma
    Private _DatePayment As Date 'Fiz. hat
    Private _DateDue As Date 'Érvényesség dátuma
    Private _Description As String 'Leírás (fejlécen)
    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 _CurrencyName As CurrencyName 'Deviza
    Private _SumPriceHUF As Double = 0 'Árajánlat összesített értéke HUF
    Private _SumPriceDEV As Double = 0 'Árajánlat összesített értéke DEV
    Private _ObjectCreated As Date 'Maga az objektum mikor készült el
    Private _UserCreated As User 'Ki csinálta az ajánlatot
    Private _IsEditable As Boolean = True 'Szerkeszthető vagy végleges ajánlat
    Private _IsStorno As Boolean = False 'Stornírozott ajánlat
    Private _DocumentBody As String 'RichText dokumentum test
    Private _ExcelProperty As String 'Excel !!!
    Private _ExcelFile As FileData
    Private _PDF_Original As FileData
    Private _WorkflowSystemSteps As WorkflowSystemSteps
    Private _MasterBusinessDirectory As BusinessDirectory

    '--- Sorok rögzítéséhez nonpersistent propertyk
    Private _row_RowType As eRowType 'Sor tipus
    Private _row_Products As Products 'Termék
    Private _row_Installation As Installation 'Gyártmány
    Private _row_ShortName As String 'Megnevezés
    Private _row_Description As String 'Leírás
    Private _row_QTT As Double 'Mennyiség
    Private _row_Units As Units 'Mennyiségi egység
    Private _row_VAT As VAT 'ÁFA kód
    Private _row_ListPriceHUF As Double 'Termék listaára HUF
    Private _row_ListPriceDEV As Double 'Termék listaára DEV
    Private _row_DiscountPercent As Double 'Termék ár kedvezmény %-ban
    Private _row_RowGroup1 As String 'Csoportosító sor1
    Private _row_RowGroup2 As String 'Csoportosító sor2
    '--- CRM miatt ----------------------------------------------
    Private _CRM_Opportunities As CRM_Opportunities
    Private _OtherCostPercent As Double 'egyéb sorokra vonatkozó általánios bekrülési %

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

        Me.DateExecution = GetSQLTime(Session)
        Me.DateCreated = GetSQLTime(Session)
        Me.CurrencyName = Session.FindObject(Of CurrencyName)(CriteriaOperator.Parse("ShortName = 'HUF'"))
        Me.row_VAT = Session.FindObject(Of VAT)(CriteriaOperator.Parse("DefaultForBusinnes='True'"))
        Me.row_Units = Session.FindObject(Of Units)(CriteriaOperator.Parse("DefaultForBusinnes='True'"))
    End Sub
    Protected Overrides Sub OnSaving()
        MyBase.OnSaving()
        If String.IsNullOrEmpty(DocumentNumber) Then
            DocumentNumber = Me.OfferOutParameters.NumberGenerator.GetNewNumber(Me.OfferOutParameters.NumberGenerator)
        End If
        If Session.IsNewObject(Me) Then
            ObjectCreated = GetSQLTime(Session)
            UserCreated = Session.GetObjectByKey(Of User)(Session.GetKeyValue(SecuritySystem.CurrentUser))
            If Me.OfferOutParameters IsNot Nothing Then
                If Me.OfferOutParameters.MasterBusinessDirectory IsNot Nothing Then
                    Dim _BusinessDirectory As New BusinessDirectory(Session)
                    _BusinessDirectory.ShortName = DocumentNumber
                    _BusinessDirectory.BusinessDirectory_Parent = Me.OfferOutParameters.MasterBusinessDirectory
                    _BusinessDirectory.IsDashBoard = False
                    _BusinessDirectory.Save()
                End If
            End If
        End If
    End Sub
    Function CalculatePriceNettoHUF() As Double
        Dim _i As Integer = 0 ' segédváltozó, hogy ha nincs a megadott intervallumokban a mennyiség akkor a normál listaárral térünk vissza

        For Each _PricingFix As PricingFix In Me.Customers.Pricing.PricingFix '1. Fix árat megnézni
            If _PricingFix.Products Is row_Products Then
                Return _PricingFix.PriceNetto
            End If
        Next
        For Each _PricingFixStaged As PricingFixStaged In Me.Customers.Pricing.PricingFixStaged '2. Fix lépcsõs árat megnézni
            If _PricingFixStaged.Products Is Me.row_Products Then
                If Me.row_QTT >= _PricingFixStaged.VolumeFrom And Me.row_QTT <= _PricingFixStaged.VolumeTo Then
                    Return _PricingFixStaged.PriceNetto
                Else
                    _i = _i + 1
                End If
                If _i >= Me.Customers.Pricing.PricingFixStaged.Count Then ' Amennyiben a megadott intervallumokon kívül van a megadott mennyiség, akkor normál listaár
                    Return Me.row_Products.ListPriceOutHUF
                End If
            End If
        Next
        For Each _PricingProductsGroups As PricingProductsGroups In Me.Customers.Pricing.PricingProductsGroups '3. Termékcsoport árat megnézni
            If _PricingProductsGroups.ProductsGroups Is Me.row_Products.ProductGroups Then ' Ha a levélelemnek meg van adva a kedvezmény
                Me.row_DiscountPercent = _PricingProductsGroups.DiscountPercent
                Return Me.row_Products.ListPriceOutHUF - ((_PricingProductsGroups.DiscountPercent / 100) * Me.row_Products.ListPriceOutHUF)
            Else
                Me.row_DiscountPercent = _PricingProductsGroups.DiscountPercent
                Return RecurziveProductsGroupsHUF(Me.row_Products, _PricingProductsGroups, Me.row_Products.ProductGroups) ' A levélelemnek nincs megadva a kedvezmény akkor rekurzív bejárás
            End If
        Next
    End Function
    Function CalculatePriceNettoDEV() As Double
        Dim _i As Integer = 0 ' segédváltozó, hogy ha nincs a megadott intervallumokban a mennyiség akkor a normál listaárral térünk vissza

        For Each _PricingFix As PricingFix In Me.Customers.Pricing.PricingFix '1. Fix árat megnézni
            If _PricingFix.Products Is row_Products Then
                Return _PricingFix.PriceNetto
            End If
        Next
        For Each _PricingFixStaged As PricingFixStaged In Me.Customers.Pricing.PricingFixStaged '2. Fix lépcsõs árat megnézni
            If _PricingFixStaged.Products Is Me.row_Products Then
                If Me.row_QTT >= _PricingFixStaged.VolumeFrom And Me.row_QTT <= _PricingFixStaged.VolumeTo Then
                    Return _PricingFixStaged.PriceNetto
                Else
                    _i = _i + 1
                End If
                If _i >= Me.Customers.Pricing.PricingFixStaged.Count Then ' Amennyiben a megadott intervallumokon kívül van a megadott mennyiség, akkor normál listaár
                    Return Me.row_Products.ListPriceOutDEV
                End If
            End If
        Next
        For Each _PricingProductsGroups As PricingProductsGroups In Me.Customers.Pricing.PricingProductsGroups '3. Termékcsoport árat megnézni
            If _PricingProductsGroups.ProductsGroups Is Me.row_Products.ProductGroups Then ' Ha a levélelemnek meg van adva a kedvezmény
                Return Me.row_Products.ListPriceOutDEV - ((_PricingProductsGroups.DiscountPercent / 100) * Me.row_Products.ListPriceOutDEV)
                Me.row_DiscountPercent = _PricingProductsGroups.DiscountPercent
            Else
                Return RecurziveProductsGroupsDEV(Me.row_Products, _PricingProductsGroups, Me.row_Products.ProductGroups) ' A levélelemnek nincs megadva a kedvezmény akkor rekurzív bejárás
                Me.row_DiscountPercent = _PricingProductsGroups.DiscountPercent
            End If
        Next
    End Function
    Function RecurziveProductsGroupsHUF(ByVal _p_Products As Products, ByVal _p_PricingProductsGroups As PricingProductsGroups, ByVal _p_ProductsGroups As ProductsGroups) As Double
        'A treelist bejárása rekurzívan, mindaddig amíg van szülő, és keressük van e termékcsoport kedvezmény, ha van visszatérünk vele, ha nincs akkor az eredeti listaárral térünk vissza
        If _p_ProductsGroups.Parent IsNot Nothing Then
            If _p_ProductsGroups.Parent Is _p_PricingProductsGroups.ProductsGroups Then
                Return _p_Products.ListPriceOutHUF - ((_p_PricingProductsGroups.DiscountPercent / 100) * _p_Products.ListPriceOutHUF) ' Visszatérés a levélelemhez legközelebbi termékcsoport kedvezményes árral.
            End If
            RecurziveProductsGroupsHUF(_p_Products, _p_PricingProductsGroups, _p_ProductsGroups.Parent) ' Rekurzív hívás, hogy minden elemen keressen
        End If
        Return _p_Products.ListPriceOutHUF ' Visszatérés az eredeti listaárral
    End Function
    Function RecurziveProductsGroupsDEV(ByVal _p_Products As Products, ByVal _p_PricingProductsGroups As PricingProductsGroups, ByVal _p_ProductsGroups As ProductsGroups) As Double
        'A treelist bejárása rekurzívan, mindaddig amíg van szülő, és keressük van e termékcsoport kedvezmény, ha van visszatérünk vele, ha nincs akkor az eredeti listaárral térünk vissza
        If _p_ProductsGroups.Parent IsNot Nothing Then
            If _p_ProductsGroups.Parent Is _p_PricingProductsGroups.ProductsGroups Then
                Return _p_Products.ListPriceOutDEV - ((_p_PricingProductsGroups.DiscountPercent / 100) * _p_Products.ListPriceOutDEV) ' Visszatérés a levélelemhez legközelebbi termékcsoport kedvezményes árral.
            End If
            RecurziveProductsGroupsDEV(_p_Products, _p_PricingProductsGroups, _p_ProductsGroups.Parent) ' Rekurzív hívás, hogy minden elemen keressen
        End If
        Return _p_Products.ListPriceOutDEV ' Visszatérés az eredeti listaárral
    End Function

    <ImmediatePostData(True), DataSourceCriteria("CustomersFrom = '@This.CustomersFrom'")>
    <RuleRequiredField("OfferOutHeader.OfferOutParameters", DefaultContexts.Save)>
    Property OfferOutParameters As OfferOutParameters
        Get
            Return _OfferOutParameters
        End Get
        Set(ByVal value As OfferOutParameters)
            SetPropertyValue("OfferOutParameters", _OfferOutParameters, value)
        End Set
    End Property
    <ImmediatePostData()>
    Property OfferOutState As eOfferOutState
        Get
            Return _OfferOutState
        End Get
        Set(ByVal value As eOfferOutState)
            SetPropertyValue("OfferOutState", _OfferOutState, value)
            If Session.IsObjectsLoading = False And Session.IsObjectsSaving = False Then
                Select Case OfferOutState
                    Case eOfferOutState.eClosedWON
                        OfferLOSTReason = eOfferOutLOSTReason.eNotSet
                    Case eOfferOutState.eInProgress
                        OfferLOSTReason = eOfferOutLOSTReason.eNotSet
                    Case eOfferOutState.eInThinkingOf
                        OfferLOSTReason = eOfferOutLOSTReason.eNotSet
                End Select
            End If
        End Set
    End Property
    <ImmediatePostData()>
    <RuleValueComparison("OfferOutHeader.OfferLostReason", DevExpress.Persistent.Validation.DefaultContexts.Save,
        DevExpress.Persistent.Validation.ValueComparisonType.NotEquals, eOfferOutLOSTReason.eNotSet, TargetCriteria:="OfferOutState = 2")>
    Property OfferLOSTReason As eOfferOutLOSTReason
        Get
            Return _OfferLOSTReason
        End Get
        Set(ByVal value As eOfferOutLOSTReason)
            SetPropertyValue("OfferLOSTReason", _OfferLOSTReason, value)
            If Session.IsObjectsLoading = False And Session.IsObjectsSaving = False Then
                Select Case OfferLOSTReason
                    Case eOfferOutLOSTReason.eNotSet
                        OfferLOSTReasonDescription = ""
                    Case eOfferOutLOSTReason.eTooExpensive
                        OfferLOSTReasonDescription = ""
                    Case eOfferOutLOSTReason.eTooLate
                        OfferLOSTReasonDescription = ""
                    Case eOfferOutLOSTReason.eChooseConcurrency
                        OfferLOSTReasonDescription = ""
                    Case eOfferOutLOSTReason.eQualityProblem
                        OfferLOSTReasonDescription = ""
                    Case eOfferOutLOSTReason.eNoAnswer
                        OfferLOSTReasonDescription = ""
                    Case eOfferOutLOSTReason.eWINOther
                        OfferLOSTReasonDescription = ""
                End Select
            End If
        End Set
    End Property
    <RuleRequiredField("OfferOutHeader.OfferLostReasonDescription", DefaultContexts.Save, TargetCriteria:="OfferLOSTReason = 7")>
    <ImmediatePostData()>
    <Size(-1)>
    Property OfferLOSTReasonDescription As String
        Get
            Return _OfferLOSTReasonDescription
        End Get
        Set(ByVal value As String)
            SetPropertyValue("OfferLOSTReasonDescription", _OfferLOSTReasonDescription, value)
        End Set
    End Property
    Property DocumentNumber As String
        Get
            Return _DocumentNumber
        End Get
        Set(ByVal value As String)
            SetPropertyValue("DocumentNumber", _DocumentNumber, value)
        End Set
    End Property
    Property DocumentOutNumber As String
        Get
            Return _DocumentOutNumber
        End Get
        Set(ByVal value As String)
            SetPropertyValue("DocumentOutNumber", _DocumentOutNumber, value)
        End Set
    End Property
    <RuleRequiredField("OfferOutHeader.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
    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
    <ImmediatePostData(True), DataSourceProperty("Customers.Contacts", DataSourcePropertyIsNullMode.SelectAll)>
    <RuleRequiredField("OfferOutHeader.Contact", DefaultContexts.Save)>
    Property Contact As Contacts
        Get
            Return _Contact
        End Get
        Set(ByVal value As Contacts)
            SetPropertyValue("Contact", _Contact, value)
            If Session.IsObjectsLoading = False And Session.IsObjectsSaving = False And value IsNot Nothing Then
                Me.Customers = Me.Contact.Customers
            End If
        End Set
    End Property
    Property DateCreated As Date
        Get
            Return _DateCreated
        End Get
        Set(ByVal value As Date)
            SetPropertyValue("DateCreated", _DateCreated, value)
        End Set
    End Property
    Property DateExecution As Date
        Get
            Return _DateExecution
        End Get
        Set(ByVal value As Date)
            SetPropertyValue("DateExecution", _DateExecution, value)
        End Set
    End Property
    Property DatePayment As Date
        Get
            Return _DatePayment
        End Get
        Set(ByVal value As Date)
            SetPropertyValue("DatePayment", _DatePayment, value)
        End Set
    End Property
    <RuleRequiredField("OfferOutHeader-DateDue", DefaultContexts.Save)>
    Property DateDue As Date
        Get
            Return _DateDue
        End Get
        Set(ByVal value As Date)
            SetPropertyValue("DateDue", _DateDue, value)
        End Set
    End Property

    <Size(-1)>
    Property Description As String
        Get
            Return _Description
        End Get
        Set(ByVal value As String)
            SetPropertyValue("Description", _Description, value)
        End Set
    End Property
    <RuleRequiredField("OfferOutHeader.PaymentOption", DefaultContexts.Save)>
    Property PaymentOption As PaymentOption
        Get
            Return _PaymentOption
        End Get
        Set(ByVal value As PaymentOption)
            SetPropertyValue("PaymentOption", _PaymentOption, value)
            If Session.IsObjectsLoading = False And Session.IsObjectsSaving = False Then
                Me.DatePayment = Me.DateExecution.AddDays(Me.PaymentOption.PayDay)
            End If
        End Set
    End Property
    Property ShipmentOption As ShipmentOption
        Get
            Return _ShipmentOption
        End Get
        Set(ByVal 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
    <RuleRequiredField("OfferOutHeader.CurrencyName", DefaultContexts.Save)>
    Property CurrencyName As CurrencyName
        Get
            Return _CurrencyName
        End Get
        Set(ByVal value As CurrencyName)
            SetPropertyValue("CurrencyName", _CurrencyName, 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
    <Size(-1)>
    Property DocumentBody As String
        Get
            Return _DocumentBody
        End Get
        Set(value As String)
            SetPropertyValue("DocumentBody", _DocumentBody, value)
        End Set
    End Property
    <Size(-1)>
    Property ExcelProperty As String
        Get
            Return _ExcelProperty
        End Get
        Set(value As String)
            SetPropertyValue("ExcelProperty", _ExcelProperty, value)
        End Set
    End Property
    Property ExcelFile As FileData
        Get
            Return _ExcelFile
        End Get
        Set(value As FileData)
            SetPropertyValue("ExcelFile", _ExcelFile, value)
        End Set
    End Property
    Property PDF_Original As FileData
        Get
            Return _PDF_Original
        End Get
        Set(value As FileData)
            SetPropertyValue("PDF_Original", _PDF_Original, value)
        End Set
    End Property
    <ImmediatePostData(True), DataSourceCriteria("WorkflowSystem='@This.OfferOutParameters.WorkflowSystem'")>
    Property WorkflowSystemSteps As WorkflowSystemSteps
        Get
            Return _WorkflowSystemSteps
        End Get
        Set(value As WorkflowSystemSteps)
            SetPropertyValue("WorkflowSystemSteps", _WorkflowSystemSteps, value)
        End Set
    End Property

    <Persistent("SumPriceHUF")> _
    ReadOnly Property SumPriceHUF As Double
        Get
            '// Át kell nézni, mert nem jó !
            If Session.IsObjectsLoading = False And Session.IsObjectsSaving = False Then
                _SumPriceHUF = 0
                For Each detail As OfferOutRows In OfferOutRows
                    _SumPriceHUF += detail.SumPriceHUF
                Next
                Return _SumPriceHUF
            End If
        End Get
    End Property
    <Persistent("SumPriceDEV")> _
    ReadOnly Property SumPriceDEV As Double
        Get
            '// Át kell nézni, mert nem jó !
            If Session.IsObjectsLoading = False And Session.IsObjectsSaving = False Then
                _SumPriceDEV = 0
                For Each detail As OfferOutRows In Me.OfferOutRows
                    _SumPriceDEV += detail.SumPriceDEV
                Next
                Return _SumPriceDEV
            End If
        End Get
    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
    <VisibleInListView(False)> _
    <Association("OfferOutHeader", GetType(OfferOutRows))> _
    Public ReadOnly Property OfferOutRows() As XPCollection(Of OfferOutRows)
        Get
            Return GetCollection(Of OfferOutRows)("OfferOutRows")
        End Get
    End Property
    <VisibleInListView(False)> _
    <Association("OfferOutCostRows", GetType(OfferOutCostRows))> _
    Public ReadOnly Property OfferOutCostRows() As XPCollection
        Get
            Return GetCollection("OfferOutCostRows")
        End Get
    End Property
    <VisibleInListView(False)> _
    <Association("OfferOutHeader-OfferOutVATRows", GetType(OfferOutVATRows))> _
    Public ReadOnly Property OfferOutVATRows() As XPCollection
        Get
            Return GetCollection("OfferOutVATRows")
        End Get
    End Property
    Public ReadOnly Property OfferInHeader As XPCollection(Of OfferInHeader)
        Get
            Dim _OfferInHeader_Collection As New XPCollection(Of OfferInHeader)(Session, CriteriaOperator.Parse("1=2"))
            Dim _OfferOutHeaderInHeader_Collection As New XPCollection(Of OfferOutHeaderInHeader)(Session, CriteriaOperator.Parse("OfferOutHeader=?", Me))

            For Each _OfferOutHeaderInHeader As OfferOutHeaderInHeader In _OfferOutHeaderInHeader_Collection
                _OfferInHeader_Collection.Add(_OfferOutHeaderInHeader.OfferInHeader)
            Next

            Return _OfferInHeader_Collection
        End Get
    End Property

    '--Nonpersistent propertyk
    <NonPersistent()> _
    <ImmediatePostData()> _
    <VisibleInListView(False)> _
    Property row_RowType As eRowType
        Get
            Return _row_RowType
        End Get
        Set(value As eRowType)
            SetPropertyValue("row_RowType", _row_RowType, value)
            If Session.IsObjectsLoading = False And Session.IsObjectsSaving = False And Me.row_RowType = eRowType.IsOther Then
                Me.row_Units = Session.FindObject(Of Units)(CriteriaOperator.Parse("ShortName='DB'"))

                Dim _DefaultVAT As VAT = Nothing
                Dim _VAT_Collection As New XPCollection(Of VAT)(Session)

                For Each _VAT As VAT In _VAT_Collection
                    If _VAT.DefaultForBusinnes = True Then
                        _DefaultVAT = _VAT
                        Exit For
                    End If
                Next

                If _DefaultVAT IsNot Nothing Then
                    Me.row_VAT = _DefaultVAT
                End If
            End If
        End Set
    End Property
    <NonPersistent()> _
    <ImmediatePostData()> _
    <RuleRequiredField("OfferOutHeader.row_Products", "aTotable_OfferOut", TargetCriteria:="row_RowType = 0")> _
    <VisibleInListView(False)> _
    Property row_Products As Products
        Get
            Return _row_Products
        End Get
        Set(ByVal value As Products)
            SetPropertyValue("row_Products", _row_Products, value)

            If Session.IsObjectsLoading = False And Session.IsObjectsSaving = False And value IsNot Nothing Then
                If Me.Customers.Pricing IsNot Nothing And Me.OfferOutParameters.OfferOutMainType = eOfferOutMainType.eFromProducts And Me.row_QTT > 0 Then
                    If Me.CurrencyName.ShortName = "HUF" Then ' Ha a Deviza HUF
                        Me.row_ListPriceHUF = CalculatePriceNettoHUF()
                    Else ' Ha a deviza nem HUF
                        Me.row_ListPriceDEV = CalculatePriceNettoDEV() ' A kedvezményt tartalmazó listaár DEV-ben
                    End If
                End If
                If Me.Customers.Pricing Is Nothing Then
                    If Me.CurrencyName.ShortName = "HUF" Then ' Ha nincs árkalkuláció akkor a normál listaáron lesz a termék
                        Me.row_ListPriceHUF = Me.row_Products.ListPriceOutHUF
                    End If
                    If Me.CurrencyName.ShortName <> "HUF" Then
                        Me.row_ListPriceDEV = Me.row_Products.ListPriceOutDEV
                    End If
                End If
            End If

        End Set
    End Property
    <NonPersistent()> _
    <ImmediatePostData()> _
    <RuleRequiredField("OfferOutHeader.row_Installation", "aTotable_OfferOut", TargetCriteria:="row_RowType = 2")> _
    <VisibleInListView(False)> _
    Property row_Installation As Installation
        Get
            Return _row_Installation
        End Get
        Set(ByVal value As Installation)
            SetPropertyValue("row_Installation", _row_Installation, value)
        End Set
    End Property
    <NonPersistent()> _
    <ImmediatePostData()> _
    <RuleRequiredField("OfferOutHeader.row_ShortName", "aTotable_OfferOut", TargetCriteria:="row_RowType = 1")> _
    <VisibleInListView(False)> _
    Property row_ShortName As String
        Get
            Return _row_ShortName
        End Get
        Set(value As String)
            SetPropertyValue("row_ShortName", _row_ShortName, value)
        End Set
    End Property
    <NonPersistent()> _
    <ImmediatePostData()> _
    <RuleRequiredField("OfferOutHeader.row_Description", "aTotable_OfferOut", TargetCriteria:="row_RowType = 1")> _
    <VisibleInListView(False)> _
    Property row_Description As String
        Get
            Return _row_Description
        End Get
        Set(value As String)
            SetPropertyValue("row_Description", _row_Description, value)
        End Set
    End Property
    <NonPersistent()> _
    <ImmediatePostData()> _
    <RuleRange("OfferOutHeader._row_QTT", "aTotable_OfferOut", 0.001, 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)

            If Session.IsObjectsLoading = False And Session.IsObjectsSaving = False And value > 0 Then
                If Me.Customers.Pricing IsNot Nothing And Me.OfferOutParameters.OfferOutMainType = eOfferOutMainType.eFromProducts And Me.row_Products IsNot Nothing Then
                    If Me.CurrencyName.ShortName = "HUF" Then ' Ha a Deviza HUF
                        Me.row_ListPriceHUF = CalculatePriceNettoHUF()
                    Else ' Ha a deviza nem HUF
                        Me.row_ListPriceDEV = CalculatePriceNettoDEV() ' A kedvezményt tartalmazó listaár DEV-ben
                    End If
                End If
                If Me.Customers.Pricing Is Nothing Then
                    If Me.row_ListPriceHUF = 0 And Me.CurrencyName.ShortName = "HUF" Then ' Ha nincs árkalkuláció akkor a normál listaáron lesz a termék
                        Me.row_ListPriceHUF = Me.row_Products.ListPriceOutHUF
                    End If
                    If Me.row_ListPriceDEV = 0 And Me.CurrencyName.ShortName <> "HUF" Then
                        Me.row_ListPriceDEV = Me.row_Products.ListPriceOutDEV
                    End If
                End If
            End If

        End Set
    End Property
    <NonPersistent()> _
    <ImmediatePostData()> _
    <RuleRequiredField("OfferOutHeader.row_Units", "aTotable_OfferOut", TargetCriteria:="row_RowType = 1")> _
    <VisibleInListView(False)> _
    Property row_Units As Units
        Get
            Return _row_Units
        End Get
        Set(value As Units)
            SetPropertyValue("row_Units", _row_Units, value)
        End Set
    End Property
    <NonPersistent()> _
    <RuleRequiredField("OfferOutHeader-row_VAT", "aToTable_OfferOut")> _
    <VisibleInListView(False)> _
    Property row_VAT As VAT
        Get
            Return _row_VAT
        End Get
        Set(value As VAT)
            SetPropertyValue("row_VAT", _row_VAT, value)
        End Set
    End Property
    <NonPersistent()> _
    <RuleRange("OfferOutHeader-row_ListPriceHUF", "aToTable_OfferOut", 0.0001, Double.MaxValue, TargetCriteria:="CurrencyName.ShortName='HUF'")> _
    <VisibleInListView(False)> _
    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()> _
      <RuleRange("OfferOutHeader-row_ListPriceDEV", "aToTable_OfferOut", 0.0001, Double.MaxValue, TargetCriteria:="CurrencyName.ShortName!='HUF'")> _
      <VisibleInListView(False)> _
    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
    <NonPersistent()> _
    <RuleRange("OfferOutHeader-row_DiscountPercent", "aToTable_OfferOut", 0, 99)> _
    <VisibleInListView(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()> _
    <VisibleInListView(False)> _
    Property row_RowGroup1 As String
        Get
            Return _row_RowGroup1
        End Get
        Set(value As String)
            SetPropertyValue("RowGroup1", _row_RowGroup1, value)
        End Set
    End Property
    <NonPersistent()> _
    <VisibleInListView(False)> _
    Property row_RowGroup2 As String
        Get
            Return _row_RowGroup2
        End Get
        Set(value As String)
            SetPropertyValue("RowGroup2", _row_RowGroup2, value)
        End Set
    End Property
    '-- CRM miatt
    <Association("OfferOutHeader-CRM_Opportunities", 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
    Property OtherCostPercent As Double
        Get
            Return _OtherCostPercent
        End Get
        Set(value As Double)
            SetPropertyValue("OtherCostPercent", _OtherCostPercent, value)
        End Set
    End Property
    Property MasterBusinessDirectory As BusinessDirectory
        Get
            Return _MasterBusinessDirectory
        End Get
        Set(value As BusinessDirectory)
            SetPropertyValue("MasterBusinessDirectory", _MasterBusinessDirectory, value)
        End Set
    End Property
    <VisibleInListView(False), VisibleInLookupListView(False)> _
    Public ReadOnly Property OfferOutHeader_BusinessDirectory As XPCollection(Of BusinessDirectory)
        Get
            Dim _BusinessDirectory_Collection As New XPCollection(Of BusinessDirectory)(Session, CriteriaOperator.Parse("1=2"))

            If MasterBusinessDirectory IsNot Nothing Then
                If MasterBusinessDirectory.Children.Count > 0 Then
                    _BusinessDirectory_Collection.Add(MasterBusinessDirectory)
                    RecursiveBusinessDirectory(_BusinessDirectory_Collection, MasterBusinessDirectory.NestedBusinessDirectory)
                Else
                    _BusinessDirectory_Collection.Add(MasterBusinessDirectory)
                End If
            End If
            Return _BusinessDirectory_Collection
        End Get
    End Property

#Region "Other subs"
    Private Sub RecursiveBusinessDirectory(_BusinessDirectoryList As XPCollection(Of BusinessDirectory), _NestedBusinessDirectory As XPCollection(Of BusinessDirectory))
        For Each _BusinessDirectory As BusinessDirectory In _NestedBusinessDirectory
            If _BusinessDirectory.Children.Count > 0 Then
                _BusinessDirectoryList.Add(_BusinessDirectory)
                RecursiveBusinessDirectory(_BusinessDirectoryList, _BusinessDirectory.NestedBusinessDirectory)
            Else
                _BusinessDirectoryList.Add(_BusinessDirectory)
            End If
        Next
    End Sub
#End Region
    Sub RecalculateOfferOut(ByVal _OfferOutHeader As OfferOutHeader, ByVal _ocur As Xpo.XPObjectSpace)
        '-- A rutin újragenerálja a pénzügyi sorokat
        Dim _OfferOutVATRows As OfferOutVATRows
        Dim i As Long = 1
        Dim j As Long = 1
        Dim _Exists As Boolean = False

        Session.Delete(_OfferOutHeader.OfferOutVATRows)
        Dim OfferRows = New XPQuery(Of OfferOutRows)(_ocur.Session)
        Dim query = From OfferRow In OfferRows Where OfferRow.OfferOutHeader.Oid = _OfferOutHeader.Oid _
            Group OfferRow By OfferRow.VAT Into g = Group _
            Select New With {Key .VAT = VAT, _
                             Key .AmountNettoHUF = g.Sum(Function(inv) (inv.FinalPriceHUF) * inv.QTT), _
                             Key .AmountNettoDEV = g.Sum(Function(inv) (inv.FinalPriceDEV) * inv.QTT), _
                             Key .S2 = g.Sum(Function(inv) inv.FinalPriceDEV), _
                             Key .M1 = g.Max(Function(inv) inv.DiscountPriceHUF * inv.QTT)}
        '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
            _OfferOutVATRows = _ocur.CreateObject(Of OfferOutVATRows)()
            _OfferOutVATRows.OfferOutHeader = _OfferOutHeader
            _OfferOutVATRows.VAT = item.VAT
            _OfferOutVATRows.AmountNettoHUF = Math.Round(item.AmountNettoHUF, 0, MidpointRounding.AwayFromZero)
            _OfferOutVATRows.AmountVATHUF = 0
            If item.VAT IsNot Nothing Then
                _OfferOutVATRows.AmountVATHUF = Math.Round(item.VAT.KeyValue * _OfferOutVATRows.AmountNettoHUF, 0, MidpointRounding.AwayFromZero)
            End If
            _OfferOutVATRows.AmountBruttoHUF = _OfferOutVATRows.AmountNettoHUF + _OfferOutVATRows.AmountVATHUF

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

            _OfferOutVATRows.Save()
            _OfferOutHeader.OfferOutVATRows.Add(_OfferOutVATRows)
        Next

        _OfferOutHeader.Save()
    End Sub
End Class
