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.Persistent.Base.General
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Linq
Imports System.Linq.Expressions
Imports DevExpress.ExpressApp.ConditionalAppearance
Imports System.Drawing
Imports DevExpress.ExpressApp.Utils

'<EditorStateRule("Hide currency rate VAT", "CurrencyRateVAT", EditorState.Hidden, "(CurrencyName.ShortName = 'HUF') or PartnerType=0", ViewType.DetailView)> _
'<EditorStateRule("Hide row_AmountHUF when Currency is not HUF", "row_AmountHUF", EditorState.Hidden, "CurrencyName.ShortName <> 'HUF'", ViewType.DetailView)> _
'<EditorStateRule("Hide IsRegistry", "IsRegistry;DocumentFile", EditorState.Hidden, "(PartnerType = 0)", ViewType.DetailView)> _
'<EditorStateRule("Hide DocumentFile when IsRegistry=False", "DocumentFile;CustomerBankAccounts", EditorState.Hidden, "(IsRegistry=False)", ViewType.DetailView)> _
'<EditorStateRule("GLAccounts date properties hide when PaymentOption.PayMode Is InCash", "DateExecution;DatePayment;row_DateVAT", ViewType.DetailView, "(PaymentOption.PayMode = 0)", EditorState.Disabled)> _

'-- Vevő szállító
<Appearance("Hide currency rate VAT", TargetItems:="CurrencyRateVAT", Criteria:="(CurrencyName.ShortName = 'HUF') or PartnerType=0", Visibility:=Editors.ViewItemVisibility.Hide, Context:="DetailView")> _
<Appearance("Hide row_AmountHUF when Currency is not HUF", TargetItems:="row_AmountHUF", Criteria:="CurrencyName.ShortName <> 'HUF'", Visibility:=Editors.ViewItemVisibility.Hide, Context:="DetailView")> _
<Appearance("Hide IsRegistry", TargetItems:="IsRegistry;DocumentFile", Criteria:="(PartnerType = 0)", Visibility:=Editors.ViewItemVisibility.Hide, Context:="DetailView")> _
<Appearance("Hide DocumentFile when IsRegistry=False", TargetItems:="DocumentFile;CustomerBankAccounts", Criteria:="(IsRegistry=False)", Visibility:=Editors.ViewItemVisibility.Hide, Context:="DetailView")> _
<Appearance("GLAccounts date properties hide when PaymentOption.PayMode Is InCash", TargetItems:="DateExecution;DatePayment;row_DateVAT", Criteria:="(PaymentOption.PayMode = 0)", Enabled:=False, Context:="DetailView")> _
<Appearance("Hide row_ info when IsEditable=False", AppearanceItemType.ViewItem, "IsEditable=False", TargetItems:="row_ChartOfAccounts", visibility:=Editors.ViewItemVisibility.Hide)> _
<Appearance("Disable if ImportedRegistryHeader is not null", AppearanceItemType.ViewItem, "isnull(ImportedRegistryHeader)=False", _
             TargetItems:="Customers;DateExecution;DocumentNumber;CurrencyName;RegistryNumber;DateCreated;DatePayment;PaymentOption;PartnerType;CustomerBankAccounts;DateVAT", Enabled:=False)> _
<Appearance("Disable row action if ImportedRegistryHeader is not null", AppearanceItemType.Action, "isnull(ImportedRegistryHeader)=False and IsRegistry=False", _
             TargetItems:="aToTableD_GLAccounts;aToTable_GLAccounts;aBackToRowEdit_GLAccounts", visibility:=Editors.ViewItemVisibility.Hide)> _
<Appearance("Hide aGetRegistryNumber_GLAccounts", AppearanceItemType.Action, "IsRegistry=False or isnull(RegistryNumber)=False", TargetItems:="aGetRegistryNumber_GLAccounts", visibility:=Editors.ViewItemVisibility.Hide)> _
<RuleCriteria("Rulecriteria GLAccounts-row_ChartOfAccounts", "aToTable_GLAccounts_Contexts", "row_ChartOfAccounts.Children.Count=0", "Csak gyermek objektum választható ki!", SkipNullOrEmptyValues:=False)> _
<DefaultClassOptions()> _
<NavigationItem("FinancialTransactions")> _
<DefaultProperty("DisplayName")> _
Public Class GLAccounts
    Inherits GLHeader
    Private _PartnerType As ePartnerType
    Private _ChartOfAccounts As ChartOfAccounts
    Private _PaymentOption As PaymentOption
    Private _CurrencyRateVAT As Double
    Private _AmountHUFBrutto As Double
    Private _AmountDEVBrutto As Double
    Private _Customers As Customers
    Private _CustomerBankAccounts As CustomerBankAccounts
    Private _HeaderInfo As String
    Private _DocumentFile As FileData
    Private _IsRegistry As Boolean = False 'Ha szállítói bizonylat, van-e iktatás
    Private _ConnectInfo As String
    Private _IsControlling_InCash As Boolean 'Készpénzes rögzítés esetén csináljon-e 
    Private _Controlling_InCash As Controlling 'Készpénz esetén GLAccounts rögzítéskor a kifizetés mire menjen (automatikus sor beszúrás) !
    Private _GLMixed_InCash As GLMixed 'A pénzügyi teljesítés vegyes bizonylata, ami ehhez kapcsolódik
    Private _VATAvowalType As eVATAvowalType 'ÁFA bevallás módja
    Public Sub New(ByVal session As Session)
        MyBase.New(session)
    End Sub
    Protected Overrides Sub OnSaving()
        MyBase.OnSaving()
        If Me.RegistryNumber IsNot Nothing Then
            Dim _RegistryHeader As RegistryHeader = Session.FindObject(Of RegistryHeader)(1, CriteriaOperator.Parse("RegistryNumber=?", Me.RegistryNumber))
            If _RegistryHeader IsNot Nothing Then
                _RegistryHeader.F_IsImported = True
                _RegistryHeader.Save()
            End If
        End If
        If IsDeleted = False Then
            Dim _GLRows As GLRows
            For Each _GLRows In Me.GLRows
                _GLRows.ConnectInfo = Me.row_ConnectInfo
            Next
            Me.ConnectInfo = Me.row_ConnectInfo
        End If
    End Sub
    Public Overrides Sub AfterConstruction()
        MyBase.AfterConstruction()
        If Session.IsNewObject(Me) Then Me.GLDocumentType = eGLDocumentType.eGLAccount
        IsRegistry = False
        HeaderInfo = ""
        IsControlling_InCash = False
        VATAvowalType = eVATAvowalType.eGeneral
        PaymentOption = Session.FindObject(Of PaymentOption)(CriteriaOperator.Parse("PayMode='InTransfer' and DefaultForBusinnes=True"))

    End Sub

    <RuleRequiredField("GLAccounts.PartnerType", "aFinal_GLAccount_Context")> _
    <ImmediatePostData(True)> _
    Property PartnerType() As ePartnerType
        Get
            Return _PartnerType
        End Get
        Set(ByVal value As ePartnerType)
            SetPropertyValue("PartnerType", _PartnerType, value)
        End Set
    End Property
    <NonPersistent()>
    <ImmediatePostData(True), DataSourceCriteria("AccountYear=GetYear('@This.DateExecution')")>
    <RuleRequiredField("GLAccounts.row_Customer.ToTable", "aToTable_GLAccounts_Contexts")>
    <VisibleInListView(False)>
    Property row_ChartOfAccounts() As ChartOfAccounts
        Get
            Return _ChartOfAccounts
        End Get
        Set(ByVal value As ChartOfAccounts)
            SetPropertyValue("ChartOfAccounts", _ChartOfAccounts, value)
        End Set
    End Property
    <ImmediatePostData(True)>
    <RuleRequiredField("GLAccounts.PaymentOption", "aFinal_GLAccount_Context")>
    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
                If Not Me.DateCreated = Nothing Then
                    If value IsNot Nothing Then
                        If value.PayMode = ePayMode.InCash Then
                            Me.DatePayment = Me.DateCreated
                            Me.DateExecution = Me.DateCreated
                            Me.row_DateVAT = Me.DateCreated
                        Else
                            Me.DatePayment = Me.DateCreated.AddDays(value.PayDay)
                        End If
                    End If
                End If
                If value IsNot Nothing Then
                    If value.PayMode = ePayMode.InCash Then
                        IsControlling_InCash = value.IsControlling_InCash
                        If IsControlling_InCash = True Then
                            If value.Controlling_InCash IsNot Nothing Then
                                Controlling_InCash = value.Controlling_InCash
                            End If
                        End If
                    End If
                End If
            End If
        End Set
    End Property
    <RuleRange("GLAcconuts.CurrencyRateVAT_RangeRule", "aFinal_GLAccount_Context", 1.01, 99999999999999999, TargetCriteria:="CurrencyName.ShortName != 'HUF'")>
    Property CurrencyRateVAT() As Double
        Get
            Return _CurrencyRateVAT
        End Get
        Set(ByVal value As Double)
            SetPropertyValue("CurrencyRateVAT", _CurrencyRateVAT, value)
        End Set
    End Property
    Property AmountHUFBrutto() As Double
        Get
            Return _AmountHUFBrutto
        End Get
        Set(ByVal value As Double)
            SetPropertyValue("AmountHUFBrutto", _AmountHUFBrutto, value)
        End Set
    End Property
    Property AmountDEVBrutto() As Double
        Get
            Return _AmountDEVBrutto
        End Get
        Set(ByVal value As Double)
            SetPropertyValue("AmountDEVBrutto", _AmountDEVBrutto, value)
        End Set
    End Property
    <ImmediatePostData(True)>
    <RuleRequiredField("GLAccounts-Customers", DefaultContexts.Save)>
    Property Customers As Customers
        Get
            Return _Customers
        End Get
        Set(ByVal value As Customers)
            SetPropertyValue("Customers", _Customers, value)
            If Session.IsObjectsLoading = False And Session.IsObjectsSaving = False Then
                row_Customer = value
            End If
        End Set
    End Property
    Property HeaderInfo As String
        Get
            Return _HeaderInfo
        End Get
        Set(ByVal value As String)
            SetPropertyValue("HeaderInfo", _HeaderInfo, value)
        End Set
    End Property
    <ImmediatePostData(True)>
    Property IsRegistry As Boolean
        Get
            Return _IsRegistry
        End Get
        Set(ByVal value As Boolean)
            SetPropertyValue("IsRegistry", _IsRegistry, value)
            If Session.IsObjectsLoading = False And Session.IsObjectsSaving = False Then
                Me.IsRegistryGLAccounts = value
            End If
        End Set
    End Property
    <RuleRequiredField("GLAccounts-DocumentFile", "GLAccounts_Context", TargetCriteria:="IsRegistry=True and PartnerType=1")>
    <NonCloneable()>
    <Aggregated()>
    <ExpandObjectMembers(ExpandObjectMembers.Never)>
    Property DocumentFile As FileData
        Get
            Return _DocumentFile
        End Get
        Set(ByVal value As FileData)
            SetPropertyValue("DocumentFile", _DocumentFile, value)
        End Set
    End Property
    <ImmediatePostData(True), DataSourceCriteria("Customers='@This.Customers'")>
    <RuleRequiredField("GLAccounts-CustomerBankAccounts", DefaultContexts.Save, _
        TargetCriteria:="PartnerType=1 and PaymentOption.PayMode=1 and IsRegistry=True and PaymentOption.PayMode<>0")> _
    Property CustomerBankAccounts As CustomerBankAccounts
        Get
            Return _CustomerBankAccounts
        End Get
        Set(ByVal value As CustomerBankAccounts)
            SetPropertyValue("CustomerBankAccounts", _CustomerBankAccounts, value)
        End Set
    End Property
    <VisibleInDetailView(False)> _
    ReadOnly Property Image1 As Image
        Get
            If PartnerType = ePartnerType.eReceivables Then
                If ImportedInvoice IsNot Nothing Then
                    Return ImageLoader.Instance.GetImageInfo("row_delete").Image
                Else
                    Return ImageLoader.Instance.GetImageInfo("edit").Image

                End If
            End If
            If PartnerType = ePartnerType.ePayabels Then
                If IsRegistry Then
                    Return ImageLoader.Instance.GetImageInfo("edit").Image
                ElseIf ImportedRegistryHeader IsNot Nothing Then
                    Return ImageLoader.Instance.GetImageInfo("row_delete").Image
                Else
                    Return ImageLoader.Instance.GetImageInfo("edit").Image
                End If
            End If

        End Get
    End Property
    Property ConnectInfo As String
        Get
            Return _ConnectInfo
        End Get
        Set(ByVal value As String)
            SetPropertyValue("ConnectInfo", _ConnectInfo, value)
            If Session.IsObjectsLoading = False And Session.IsObjectsSaving = False Then
                Me.row_ConnectInfo = value
            End If
        End Set
    End Property
    Property Controlling_InCash As Controlling
        Get
            Return _Controlling_InCash
        End Get
        Set(value As Controlling)
            SetPropertyValue("Controlling_InCash", _Controlling_InCash, value)
        End Set
    End Property
    Property IsControlling_InCash As Boolean
        Get
            Return _IsControlling_InCash
        End Get
        Set(value As Boolean)
            SetPropertyValue("IsControlling_InCash", _IsControlling_InCash, value)
        End Set
    End Property
    Property GLMixed_InCash As GLMixed
        Get
            Return _GLMixed_InCash
        End Get
        Set(value As GLMixed)
            SetPropertyValue("GLMixed_InCash", _GLMixed_InCash, value)
        End Set
    End Property
    Property VATAvowalType As eVATAvowalType
        Get
            Return _VATAvowalType
        End Get
        Set(value As eVATAvowalType)
            SetPropertyValue("VATAvowalType", _VATAvowalType, value)
        End Set
    End Property


    ReadOnly Property DisplayName As String
        Get
            If Me.Customers IsNot Nothing Then
                If Me.CurrencyName IsNot Nothing Then
                    Return String.Format("{0} {1} {2}", Me.CurrencyName.ShortName, Me.DocumentNumber, Me.Customers.FullName)
                Else
                    Return String.Format("{0}", Me.DocumentNumber)
                End If
            Else
                Return String.Format("{0}", Me.DocumentNumber)
            End If
        End Get
    End Property
    Public Overrides Property DocumentNumber As String
        Get
            Return MyBase.DocumentNumber
        End Get
        Set(ByVal value As String)
            MyBase.DocumentNumber = value
            If Session.IsObjectsSaving = False And Session.IsObjectsSaving = False Then
                If ConnectInfo <> value Then
                    ConnectInfo = value
                End If
            End If
        End Set
    End Property

    Public Overrides Property row_Controlling As Controlling
        Get
            Return MyBase.row_Controlling
        End Get
        Set(value As Controlling)
            MyBase.row_Controlling = value
            If Session.IsObjectsSaving = False And Session.IsObjectsSaving = False Then
                If value IsNot Nothing Then
                    row_ChartOfAccounts = value.GetChartOfAccounts(Me.DateExecution.Year, False)
                End If
            End If
        End Set
    End Property
    Sub RecalculateTotal(Optional ByVal WithCurrencyRate As Boolean = False)
        Dim _GLRows As GLRows

        AmountHUFBrutto = 0
        AmountDEVBrutto = 0
        For Each _GLRows In Me.GLRows
            If _PartnerType = ePartnerType.eReceivables Then
                If _GLRows.DebitChartOfAccounts Is _Customers.CustomersGLParameters.GetChartOfAccounts(_GLRows.GLHeader.DateExecution.Year, eVATMode.eOut) Or _GLRows.CreditChartOfAccounts Is _
                    _Customers.CustomersGLParameters.GetChartOfAccounts(_GLRows.GLHeader.DateExecution.Year, eVATMode.eOut) Then
                    AmountHUFBrutto += _GLRows.AmountHUF
                    AmountDEVBrutto += _GLRows.AmountDEV
                End If
            Else
                If _GLRows.DebitChartOfAccounts Is _Customers.CustomersGLParameters.GetChartOfAccounts(_GLRows.GLHeader.DateExecution.Year, eVATMode.eIn) Or _
                    _GLRows.CreditChartOfAccounts Is _Customers.CustomersGLParameters.GetChartOfAccounts(_GLRows.GLHeader.DateExecution.Year, eVATMode.eIn) Then
                    AmountHUFBrutto += _GLRows.AmountHUF
                    AmountDEVBrutto += _GLRows.AmountDEV
                End If
            End If
        Next

        If WithCurrencyRate Then
            If Me.CurrencyName IsNot Nothing Then
                If Me.CurrencyName.ShortName <> "HUF" Then
                    If AmountDEVBrutto <> 0 Then
                        Me.CurrencyRate = Math.Round(AmountHUFBrutto / AmountDEVBrutto, 4, MidpointRounding.AwayFromZero)
                    End If
                End If
            End If
        End If
    End Sub

    Function ReturnTotal()
        Dim _GLRows As GLRows
        Dim _Total As Double
        For Each _GLRows In Me.GLRows
            _Total = _Total + _GLRows.AmountHUF + _GLRows.AmountDEV
        Next
        Return _Total
    End Function
    Function CreateRegistry(ByVal _ocur As Xpo.XPObjectSpace, ByVal _RegistryHeader As RegistryHeader) As RegistryHeader
        Dim _RegistryType As RegistryType
        Dim _RegistryBankTransfer As RegistryBankTransfer
        Dim _RegistryBankTransfer_Collection As XPCollection(Of RegistryBankTransfer)
        Dim _WorkflowSystemSteps As WorkflowSystemSteps
        If Me.CustomersFrom Is Nothing Then
            Return Nothing
            Exit Function
        End If

        If Me.PartnerType = ePartnerType.ePayabels Then
            If Me.IsRegistry Then
                If _RegistryHeader Is Nothing Then
                    _RegistryType = _ocur.FindObject(Of RegistryType)(CriteriaOperator.Parse("CustomersFrom.Oid=? and RegistryMainType=0 and RegistryGLAccount=True", Me.CustomersFrom.Oid))
                    If _RegistryType IsNot Nothing Then
                        _RegistryHeader = _ocur.CreateObject(Of RegistryHeader)()
                        _RegistryHeader.CustomersFrom = CustomersFrom
                        _RegistryHeader.Customers = Me.Customers
                        _RegistryHeader.RegistryType = _RegistryType
                        For Each _WorkflowSystemSteps In _RegistryType.WorkflowSystem.WorkflowSystemSteps
                            If _WorkflowSystemSteps.IsLastStep Then
                                _RegistryHeader.CurrentWorkflowSystemSteps = _WorkflowSystemSteps
                            End If
                        Next
                    Else
                        _ocur.Rollback()
                        Return Nothing
                        Exit Function
                    End If
                Else
                    _RegistryBankTransfer_Collection = New XPCollection(Of RegistryBankTransfer)(_ocur.Session, CriteriaOperator.Parse("RegistryHeader.Oid=?", _RegistryHeader.Oid))
                    _ocur.Delete(_RegistryBankTransfer_Collection)
                End If

                _RegistryHeader.CustomersFrom = CustomersFrom
                _RegistryHeader.Customers = Me.Customers

                _RegistryHeader.F_CurrencyName = Me.CurrencyName
                _RegistryHeader.F_CurrencyRate = Me.CurrencyRate
                _RegistryHeader.F_DateCreated = Me.DateCreated
                _RegistryHeader.F_DateExecution = Me.DateExecution
                _RegistryHeader.F_DatePayment = Me.DatePayment
                _RegistryHeader.F_DateVAT = Me.DateExecution
                _RegistryHeader.F_PayMode = Me.PaymentOption.PayMode
                _RegistryHeader.F_AmountBruttoDEV = Me.AmountDEVBrutto
                _RegistryHeader.F_AmountBruttoHUF = Me.AmountHUFBrutto
                _RegistryHeader.F_CustomerBankAccounts = Me.CustomerBankAccounts
                _RegistryHeader.F_ReadyforBookEntry = True
                _RegistryHeader.DocumentFile = Me.DocumentFile
                _RegistryHeader.DateCreated = GetSQLTime(Session)
                _RegistryHeader.DeliveryType = eDeliveryType.eOther
                _RegistryHeader.DocumentNumber = Me.DocumentNumber
                _RegistryHeader.IsEditable = False



                If Me.PaymentOption.PayMode = ePayMode.InTransfer Or Me.PaymentOption.PayMode = ePayMode.InContinuous Then
                    _RegistryBankTransfer = New RegistryBankTransfer(Session)
                    _RegistryBankTransfer.DatePayment = Me.DatePayment
                    _RegistryBankTransfer.RegistryHeader = _RegistryHeader
                    _RegistryBankTransfer.AmountDEV = Me.AmountDEVBrutto
                    _RegistryBankTransfer.AmountHUF = Me.AmountHUFBrutto

                End If

                Return _RegistryHeader
            End If
        End If
    End Function

End Class

