Files
SIG/Compras/Compras.aspx.vb
2023-01-04 18:47:01 -07:00

20574 lines
1.1 MiB
Raw Blame History

Option Explicit On
Option Strict On
Imports System.Data
Imports System.Xml
Imports System.Diagnostics
Imports System.Globalization
Imports System.IO
Imports System.Threading.Tasks
Imports Newtonsoft.Json
Imports Extensiones
Imports System.Activities.Expressions
Imports iText.Barcodes.Dmcode
Partial Class Compras_Compras
Inherits ClsPaginas
#Region "Propiedades"
'Local
Private Property RequiereEvaluacion() As Boolean
Get
Return If(IsNothing(ViewState("RequiereEvaluacion")), False, CBool(ViewState("RequiereEvaluacion")))
End Get
Set
ViewState("RequiereEvaluacion") = Value
End Set
End Property
Private Property EstaAsociadoACajaChica() As Boolean
Get
Return If(IsNothing(ViewState("EstaAsociadoACajaChica")), False, CBool(ViewState("EstaAsociadoACajaChica")))
End Get
Set
ViewState("EstaAsociadoACajaChica") = Value
End Set
End Property
Private Property EstaAsociadoAPersonal() As Boolean
Get
Return If(IsNothing(ViewState("EstaAsociadoAPersonal")), False, CBool(ViewState("EstaAsociadoAPersonal")))
End Get
Set
ViewState("EstaAsociadoAPersonal") = Value
End Set
End Property
Private Property CveUsuarioEvaluador() As Integer
Get
Return If(IsNothing(ViewState("CveUsuarioEvaluador")), -1, CInt(ViewState("CveUsuarioEvaluador")))
End Get
Set
ViewState("CveUsuarioEvaluador") = Value
End Set
End Property
Private Property TmpDT As DataTable
Get
Return CType(ViewState("TmpDT"), DataTable)
End Get
Set(value As DataTable)
ViewState("TmpDT") = value
End Set
End Property
Private Property TmpDTOriginal As DataTable
Get
Return CType(ViewState("TmpDTOriginal"), DataTable)
End Get
Set(value As DataTable)
ViewState("TmpDTOriginal") = value
End Set
End Property
Private Property TmpCXP As DataTable
Get
Return CType(ViewState("TmpCXP"), DataTable)
End Get
Set(value As DataTable)
ViewState("TmpCXP") = value
End Set
End Property
'Private Property PSDTRemplazo As DataTable
' Get
' Return CType(ViewState("PSDTRemplazo"), DataTable)
' End Get
' Set(value As DataTable)
' ViewState("PSDTRemplazo") = value
' End Set
'End Property
Private Property DtCheques As DataTable
Get
Return CType(ViewState("DtCheques"), DataTable)
End Get
Set(value As DataTable)
ViewState("DtCheques") = value
End Set
End Property
Private Property Modalidad As String
Get
Return ViewState("Modalidad").ToString
End Get
Set(value As String)
ViewState("Modalidad") = value
End Set
End Property
Public Property IdVale As List(Of Integer)
Get
IdVale = DirectCast(ViewState("IdVale"), List(Of Integer))
End Get
Set(ByVal value As List(Of Integer))
ViewState("IdVale") = value
End Set
End Property
Public Property ListaDocumentos As List(Of String)
Get
ListaDocumentos = DirectCast(ViewState("ListaDocumentos"), List(Of String))
End Get
Set(ByVal value As List(Of String))
ViewState("ListaDocumentos") = value
End Set
End Property
Public Property TieneAnticiposXML As Boolean
Get
TieneAnticiposXML = DirectCast(ViewState("TieneAnticiposXML"), Boolean)
End Get
Set(ByVal value As Boolean)
ViewState("TieneAnticiposXML") = value
End Set
End Property
Private Property DTOCTemp As DataTable
Get
Return CType(ViewState("DTOCTemp"), DataTable)
End Get
Set(value As DataTable)
ViewState("DTOCTemp") = value
End Set
End Property
Private Property DTOCGV As DataTable
Get
Return CType(ViewState("DTOCGV"), DataTable)
End Get
Set(value As DataTable)
ViewState("DTOCGV") = value
End Set
End Property
Private Property DtConsignaciones As DataTable
Get
Return CType(ViewState("DtConsignaciones"), DataTable)
End Get
Set(value As DataTable)
ViewState("DtConsignaciones") = value
End Set
End Property
'Private Property DtCuentas As DataTable
' Get
' Return CType(ViewState("DtCuentas"), DataTable)
' End Get
' Set(value As DataTable)
' ViewState("DtCuentas") = value
' End Set
'End Property
'Private Property CargoFactura As Boolean
' Get
' Return CType(ViewState("CargoFactura"), Boolean)
' End Get
' Set(value As Boolean)
' ViewState("CargoFactura") = value
' End Set
'End Property
Private Property tDTAcarreos As DataTable
Get
Return If(IsNothing(ViewState("tDTAcarreos")), Nothing, CType(ViewState("tDTAcarreos"), DataTable))
End Get
Set(value As DataTable)
ViewState("tDTAcarreos") = value
End Set
End Property
Private Property DtDeudores As DataTable
Get
Return CType(ViewState("DtDeudores"), DataTable)
End Get
Set(value As DataTable)
ViewState("DtDeudores") = value
End Set
End Property
Private Property DtDeudoresDetalle As DataTable
Get
Return CType(ViewState("DtDeudoresDetalle"), DataTable)
End Get
Set(value As DataTable)
ViewState("DtDeudoresDetalle") = value
End Set
End Property
Private Property DtAcreedores As DataTable
Get
Return CType(ViewState("DtAcreedores"), DataTable)
End Get
Set(value As DataTable)
ViewState("DtAcreedores") = value
End Set
End Property
Private Property DTUM As DataTable
Get
Return CType(ViewState("DTUM"), DataTable)
End Get
Set(value As DataTable)
ViewState("DTUM") = value
End Set
End Property
Private Property TmpDTTiposAF As DataTable
Get
Return CType(ViewState("TmpDTTiposAF"), DataTable)
End Get
Set(value As DataTable)
ViewState("TmpDTTiposAF") = value
End Set
End Property
Private Property DtFacturas As DataTable
Get
Return CType(ViewState("DtFacturas"), DataTable)
End Get
Set(value As DataTable)
ViewState("DtFacturas") = value
End Set
End Property
Private Property DtServicios As DataTable
Get
Return CType(ViewState("DtServicios"), DataTable)
End Get
Set(value As DataTable)
ViewState("DtServicios") = value
End Set
End Property
Private ReadOnly Property CveProveedor As Integer
Get
Return ViewState("CveProveedor").ToString.ToEntero
End Get
End Property
Private ReadOnly Property CveTipoProveedor As Integer
Get
Return ViewState("CveTipoProveedor").ToString.ToEntero
End Get
End Property
Private ReadOnly Property CtaProveedor As Integer
Get
Return ViewState("CtaProveedor").ToString.ToEntero
End Get
End Property
Private ReadOnly Property CtaProveedorDeudores As Integer
Get
Return ViewState("CtaProveedorDeudores").ToString.ToEntero
End Get
End Property
Private ReadOnly Property CtaProveedorAcreedores As Integer
Get
Return ViewState("CtaProveedorAcreedores").ToString.ToEntero
End Get
End Property
Private ReadOnly Property CtaProveedorAnticipos As Integer
Get
Return ViewState("CtaProveedorAnticipos").ToString.ToEntero
End Get
End Property
Private ReadOnly Property CtaProveedorAnticiposExtranjera As Integer
Get
Return ViewState("CtaProveedorAnticiposExtranjera").ToString.ToEntero
End Get
End Property
Private ReadOnly Property CtaProveedorAnticiposComplementaria As Integer
Get
Return ViewState("CtaProveedorAnticiposComplementaria").ToString.ToEntero
End Get
End Property
Private ReadOnly Property CtaProveedorRetIVA As Integer
Get
Return ViewState("CtaProveedorRetIVA").ToString.ToEntero
End Get
End Property
Private ReadOnly Property CtaProveedorRetISR As Integer
Get
Return ViewState("CtaProveedorRetISR").ToString.ToEntero
End Get
End Property
Private ReadOnly Property CtaProveedorExtranjera As Integer
Get
Return ViewState("CtaProveedorExtranjera").ToString.ToEntero
End Get
End Property
Private ReadOnly Property CtaProveedorComplementaria As Integer
Get
Return ViewState("CtaProveedorComplementaria").ToString.ToEntero
End Get
End Property
Private ReadOnly Property NombreProveedor As String
Get
Return ViewState("NombreProveedor").ToString
End Get
End Property
Private Property IdPoliza As Integer
Get
Return ViewState("IdPoliza").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("IdPoliza") = value
End Set
End Property
Private Property CveOrdenCorte As Integer
Get
Return ViewState("CveOrdenCorte").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("CveOrdenCorte") = value
End Set
End Property
Private Property CvePrePoliza As Integer
Get
Return ViewState("CvePrePoliza").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("CvePrePoliza") = value
End Set
End Property
Private ReadOnly Property CveCompra As Integer
Get
Return ViewState("CveCompra").ToString.ToEntero
End Get
End Property
Private ReadOnly Property CveFactura As Integer
Get
Return ViewState("CveFactura").ToString.ToEntero
End Get
End Property
Private Property CveMovimientoAlmacen As Integer
Get
Return ViewState("CveMovimientoAlmacen").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("CveMovimientoAlmacen") = value
End Set
End Property
Private Property CveConsignacion As Integer
Get
Return ViewState("CveConsignacion").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("CveConsignacion") = value
End Set
End Property
Private Property PermisoEdicionManual As Boolean
Get
Return CType(ViewState("PermisoEdicionManual"), Boolean)
End Get
Set(value As Boolean)
ViewState("PermisoEdicionManual") = value
End Set
End Property
Private Property NuevaValidacionXML As Integer
Get
Return ViewState("NuevaValidacionXML").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("NuevaValidacionXML") = value
End Set
End Property
Private Property IdCuentaBancaria As Integer
Get
Return ViewState("IdCuentaBancaria").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("IdCuentaBancaria") = value
End Set
End Property
Private Property IdCuentaBancariaComplementaria As Integer
Get
Return ViewState("IdCuentaBancariaComplementaria").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("IdCuentaBancariaComplementaria") = value
End Set
End Property
Private Property IvaAcumulado As Double
Get
Return ViewState("IvaAcumulado").ToString.ToDouble
End Get
Set(value As Double)
ViewState("IvaAcumulado") = value
End Set
End Property
Private Property EsContado As Boolean
Get
Return CType(ViewState("EsContado"), Boolean)
End Get
Set(value As Boolean)
ViewState("EsContado") = value
End Set
End Property
'Private ReadOnly Property CompraFolio As String
' Get
' Return ViewState("CompraFolio").ToString
' End Get
'End Property
'Private ReadOnly Property FolioFiscal As String
' Get
' Return ViewState("FolioFiscal").ToString
' End Get
'End Property
'Private ReadOnly Property IdCtaContProveedores As Integer
' Get
' Return ViewState("IdCtaContProveedores").ToString.ToEntero
' End Get
'End Property
'Private ReadOnly Property IdCtaContAnticipos As Integer
' Get
' Return ViewState("IdCtaContAnticipos").ToString.ToEntero
' End Get
'End Property
'Private ReadOnly Property IdCtaContRetIVA As Integer
' Get
' Return ViewState("IdCtaContRetIVA").ToString.ToEntero
' End Get
'End Property
'Private ReadOnly Property IdCtaContRetISR As Integer
' Get
' Return ViewState("IdCtaContRetISR").ToString.ToEntero
' End Get
'End Property
'Private ReadOnly Property IVAPS As Double
' Get
' Return ViewState("IVAPS").ToString.ToDouble
' End Get
'End Property
'Private ReadOnly Property RetIVA As Double
' Get
' Return ViewState("RetIVA").ToString.ToDouble
' End Get
'End Property
'Private ReadOnly Property RetISR As Double
' Get
' Return ViewState("RetISR").ToString.ToDouble
' End Get
'End Property
'Private ReadOnly Property IEPSPS As Double
' Get
' Return ViewState("IEPSPS").ToString.ToDouble
' End Get
'End Property
'Private ReadOnly Property IEPSPSIVA As Double
' Get
' Return ViewState("IEPSPSIVA").ToString.ToDouble
' End Get
'End Property
Private Property TotalGeneral As Double
Get
Return ViewState("TotalGeneral").ToString.ToDouble
End Get
Set(value As Double)
ViewState("TotalGeneral") = value
End Set
End Property
Private Property CompraSaldo As Double
Get
Return ViewState("CompraSaldo").ToString.ToDouble
End Get
Set(value As Double)
ViewState("CompraSaldo") = value
End Set
End Property
Private Property Saldo As Double
Get
Return ViewState("Saldo").ToString.ToDouble
End Get
Set(value As Double)
ViewState("Saldo") = value
End Set
End Property
Private Property CveMoneda As Integer
Get
Return ViewState("CveMoneda").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("CveMoneda") = value
End Set
End Property
Private Property CveAlmacenConsignacion As Integer
Get
Return ViewState("CveAlmacenConsignacion").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("CveAlmacenConsignacion") = value
End Set
End Property
Private Property DtFuncionarios As DataTable
Get
Return CType(ViewState("DtFuncionarios"), DataTable)
End Get
Set(value As DataTable)
ViewState("DtFuncionarios") = value
End Set
End Property
Private Property DtDatosDetalle As DataTable
Get
Return CType(ViewState("DtDatosDetalle"), DataTable)
End Get
Set(value As DataTable)
ViewState("DtDatosDetalle") = value
End Set
End Property
Private Property CvePSSerieLote As Integer
Get
Return CType(ViewState("CvePSSerieLote"), Integer)
End Get
Set(value As Integer)
ViewState("CvePSSerieLote") = value
End Set
End Property
Private Property CveUMSerieLote As Integer
Get
Return CType(ViewState("CveUMSerieLote"), Integer)
End Get
Set(value As Integer)
ViewState("CveUMSerieLote") = value
End Set
End Property
Private Property PUSerieLote As Decimal
Get
Return CType(ViewState("PUSerieLote"), Decimal)
End Get
Set(value As Decimal)
ViewState("PUSerieLote") = value
End Set
End Property
Private Property TotAcarreos As Double
Get
Return CType(ViewState("TotAcarreos"), Double)
End Get
Set(value As Double)
ViewState("TotAcarreos") = value
End Set
End Property
<Serializable>
Public Class Anticipos
Public Property TipoMovto As String
Public Property CveIE As Integer
Public Property Importe As Decimal
Public Property ImporteComision As Decimal
Public Property TCCompra As Decimal
Public Property CvePersonal As Integer
Public Property CveCompra As Integer
Public Property CvePrePoliza As Integer
End Class
Private Property ArrAnticipos As ArrayList
Get
Return CType(ViewState("ArrAnticipos"), ArrayList)
End Get
Set(value As ArrayList)
ViewState("ArrAnticipos") = value
End Set
End Property
Private Property ArrIE As ArrayList
Get
Return CType(ViewState("ArrIE"), ArrayList)
End Get
Set(value As ArrayList)
ViewState("ArrIE") = value
End Set
End Property
Private Property ArrIEFuncionariosEmpleados As ArrayList
Get
Return CType(ViewState("ArrIEFuncionariosEmpleados"), ArrayList)
End Get
Set(value As ArrayList)
ViewState("ArrIEFuncionariosEmpleados") = value
End Set
End Property
'Inventarios
Private Property DtInv As DataTable
Get
Return CType(ViewState("DtInv"), DataTable)
End Get
Set(value As DataTable)
ViewState("DtInv") = value
End Set
End Property
Private Property DtAC As DataTable
Get
DtAC = DirectCast(ViewState("DtAC"), DataTable)
End Get
Set(ByVal value As DataTable)
ViewState("DtAC") = value
End Set
End Property
'Caja Chica, Funcionario/Empleado
Private ReadOnly Property CveCajaChica As Integer
Get
Return ViewState("CveCajaChica").ToString.ToEntero
End Get
End Property
Private ReadOnly Property CvePersonal As Integer
Get
Return ViewState("CvePersonal").ToString.ToEntero
End Get
End Property
Private Property OCsVinculadas As String
Get
Return ViewState("OCsVinculadas").ToString
End Get
Set(value As String)
ViewState("OCsVinculadas") = value
End Set
End Property
Private Property DdlOC As DropDownList
Get
Return CType(ViewState("OCsVinculadas"), DropDownList)
End Get
Set(value As DropDownList)
ViewState("OCsVinculadas") = value
End Set
End Property
Private Property TieneOC As Boolean
Get
Return CType(ViewState("TieneOC"), Boolean)
End Get
Set(value As Boolean)
ViewState("TieneOC") = value
End Set
End Property
Private Property OCVinculada As Boolean
Get
Return CType(ViewState("OCVinculada"), Boolean)
End Get
Set(value As Boolean)
ViewState("OCVinculada") = value
End Set
End Property
Private Property CierrePeriodo As Boolean
Get
Return CType(ViewState("CierrePeriodo"), Boolean)
End Get
Set(value As Boolean)
ViewState("CierrePeriodo") = value
End Set
End Property
Private Property NCDevolucion As Boolean
Get
Return CType(ViewState("NCDevolucion"), Boolean)
End Get
Set(value As Boolean)
ViewState("NCDevolucion") = value
End Set
End Property
Private Property CompraCargada As Boolean
Get
Return CType(ViewState("CompraCargada"), Boolean)
End Get
Set(value As Boolean)
ViewState("CompraCargada") = value
End Set
End Property
Private Property ModalidadUMAlias As Integer
Get
Return ViewState("EjercicioAC").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("EjercicioAC") = value
End Set
End Property
Private Property CveConceptoContableAlmacen As Integer
Get
Return ViewState("CveConceptoContableAlmacen").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("CveConceptoContableAlmacen") = value
End Set
End Property
Private Property EsNoDeducible As Boolean
Get
Return CType(ViewState("EsNoDeducible"), Boolean)
End Get
Set(value As Boolean)
ViewState("EsNoDeducible") = value
End Set
End Property
#End Region
#Region "PROPIEDADES - AC NEW"
Private Property DtPresupuestos As DataTable
Get
Return CType(ViewState("DtPresupuestos"), DataTable)
End Get
Set(value As DataTable)
ViewState("DtPresupuestos") = value
End Set
End Property
Private Property EjercicioAC As Integer
Get
Return ViewState("EjercicioAC").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("EjercicioAC") = value
End Set
End Property
#End Region
#Region " PROPIEDADES REFACTURACION "
Private Property DtRefacturacion As DataTable
Get
Return CType(ViewState("DtRefacturacion"), DataTable)
End Get
Set(value As DataTable)
ViewState("DtRefacturacion") = value
End Set
End Property
Private Property CveCompraRefacturacion As Integer
Get
If ViewState("CveCompraRefacturacion") Is Nothing Then
ViewState("CveCompraRefacturacion") = -1
End If
Return ViewState("CveCompraRefacturacion").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("CveCompraRefacturacion") = value
End Set
End Property
Private Property EmpresaPrueba As Boolean
Get
Return CBool(ViewState("EmpresaPrueba"))
End Get
Set(value As Boolean)
ViewState("EmpresaPrueba") = value
End Set
End Property
Private Property StringProrrateo As String
Get
Return ViewState("StringProrrateo").ToString
End Get
Set(value As String)
ViewState("StringProrrateo") = value
End Set
End Property
Private Property ClavesBorradas As ArrayList
Get
Return CType(ViewState("ClavesBorradas"), ArrayList)
End Get
Set(value As ArrayList)
ViewState("ClavesBorradas") = value
End Set
End Property
#End Region
#Region " PROPIEDADES OC "
Private Property TipoCambioOC As Decimal
Get
Return ViewState("TipoCambioOC").ToString.ToDecimal
End Get
Set(value As Decimal)
ViewState("TipoCambioOC") = value
End Set
End Property
Private Property PopUpOC As Boolean
Get
Return CBool(ViewState("PopUpOC"))
End Get
Set(value As Boolean)
ViewState("PopUpOC") = value
End Set
End Property
Private Property CompraEstaVinculadaOC As Boolean
Get
Return CBool(ViewState("CompraEstaVinculadaOC"))
End Get
Set(value As Boolean)
ViewState("CompraEstaVinculadaOC") = value
End Set
End Property
#End Region
#Region "PROPIEDADES ALMACEN" 'Charlie
Private Property TotalAlmacen As Decimal
Get
Return ViewState("TotalAlmacen").ToString.ToDecimal
End Get
Set(value As Decimal)
ViewState("TotalAlmacen") = value
End Set
End Property
Private Property TotalFlete As Decimal
Get
Return ViewState("TotalFlete").ToString.ToDecimal
End Get
Set(value As Decimal)
ViewState("TotalFlete") = value
End Set
End Property
#End Region
#Region "Propiedades"
'CFDi
Private Property Serie As String
Private Property Folio As String
Private Property Fecha As String
Private Property SubTotal As Decimal
Private Property Total As Decimal = 0
Private Property Descuentos As Decimal = 0
Private Property Amortizaciones As Decimal = 0
Private Property EmisorRFC As String
Private Property ReceptorRFC As String
Private Property TrasladoIVA As Decimal = 0
Private Property RetencionIVA As Decimal = 0
Private Property RetencionISR As Decimal = 0
Private Property TrasladoIEPS As Decimal = 0
Private Property TFDUUID As String = ""
Private Property Moneda As String = ""
Private Property TipoComprobante As String = ""
Private Property MetodoPago As String = ""
Private Property CveMetodoPago As Integer
Get
Return ViewState("CveMetodoPago").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("CveMetodoPago") = value
End Set
End Property
Private Property TipoCambio As Decimal
Get
Return ViewState("TipoCambio").ToString.ToDecimal
End Get
Set(value As Decimal)
ViewState("TipoCambio") = value
End Set
End Property
'Private Property TipoCambio As Double = 0
Private Property OtrosImpuestos As Decimal = 0
Private Property OtrosImpuestosRetenciones As Decimal = 0
Private Property TotalRetenciones As Decimal = 0
Private Property SumaTotalRetenciones As Decimal = 0
Private Property TotalTraslados As Decimal = 0
Private Property SumaTotalTraslados As Decimal = 0
Private Property SubTotalConceptos As Decimal = 0
Private Property Redondeo As Decimal = 0
Private Property IEPSGasto As Boolean = False
Private Property OtrosImpuestosGasto As Boolean = False
Private Property Version As String
Get
Return ViewState("Version").ToString
End Get
Set(value As String)
ViewState("Version") = value
End Set
End Property
Private Property Index As Integer
Get
Return ViewState("Index").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("Index") = value
End Set
End Property
Private Property Con As Integer
Get
Return ViewState("Con").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("Con") = value
End Set
End Property
Private Property IvaTotalGv As Double
Get
Return DirectCast(ViewState("IvaTotalGv"), Double)
End Get
Set(value As Double)
ViewState("IvaTotalGv") = value
End Set
End Property
Private Property SerieVieja As String
Get
Return DirectCast(ViewState("SerieVieja"), String)
End Get
Set(value As String)
ViewState("SerieVieja") = value
End Set
End Property
Private Property EstatusAlmacen As Integer
Get
Return ViewState("EstatusAlmacen").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("EstatusAlmacen") = value
End Set
End Property
Private Property DtTemporalGuardados As DataTable
Get
Return CType(ViewState("DtTemporalGuardados"), DataTable)
End Get
Set(value As DataTable)
ViewState("DtTemporalGuardados") = value
End Set
End Property
Private Property RFCProv As String
Get
Return IfNull(ViewState("RFCProv"), "").ToString
End Get
Set(value As String)
ViewState("RFCProv") = value
End Set
End Property
Private Property CveImportacion As Integer
Get
Return IfNull(ViewState("CveImportacion"), -1).ToString.ToEntero
End Get
Set(value As Integer)
ViewState("CveImportacion") = value
End Set
End Property
Private Property CveFlete As Integer
Get
Return IfNull(ViewState("CveFlete"), -1).ToString.ToEntero
End Get
Set(value As Integer)
ViewState("CveFlete") = value
End Set
End Property
Private Property FleteImportacionOpcion As Integer
Get
Return IfNull(ViewState("FleteImportacionOpcion"), -1).ToString.ToEntero
End Get
Set(value As Integer)
ViewState("FleteImportacionOpcion") = value
End Set
End Property
Private Property DTClasificacionesComprobaciones As DataTable
Get
If ViewState("DTClasificacionesComprobaciones") Is Nothing Then
Return New DataTable
Else
Return DirectCast(ViewState("DTClasificacionesComprobaciones"), DataTable)
End If
End Get
Set(value As DataTable)
ViewState("DTClasificacionesComprobaciones") = value
End Set
End Property
#End Region
#Region " PROPIEDADES DE TOTALES "
Private Property SubTotalOriginal As Double
Get
Return ViewState("SubTotalOriginal").ToString.ToDouble
End Get
Set(value As Double)
ViewState("SubTotalOriginal") = value
End Set
End Property
Private Property SubTotal2Original As Double
Get
Return ViewState("SubTotal2Original").ToString.ToDouble
End Get
Set(value As Double)
ViewState("SubTotal2Original") = value
End Set
End Property
Private Property SubTotalRefacturacion As Decimal
Get
If ViewState("SubTotalRefacturacion") Is Nothing Then
ViewState("SubTotalRefacturacion") = 0.0D
End If
Return ViewState("SubTotalRefacturacion").ToString.ToDecimal
End Get
Set(value As Decimal)
ViewState("SubTotalRefacturacion") = value
End Set
End Property
Private Property IVAOriginal As Double
Get
If ViewState("IVAOriginal") Is Nothing Then
Return 0
Else
Return ViewState("IVAOriginal").ToString.ToDouble
End If
End Get
Set(value As Double)
ViewState("IVAOriginal") = value
End Set
End Property
Private Property RetIVAOriginal As Double
Get
Return ViewState("RetIVAOriginal").ToString.ToDouble
End Get
Set(value As Double)
ViewState("RetIVAOriginal") = value
End Set
End Property
Private Property RetISROriginal As Double
Get
Return ViewState("RetISROriginal").ToString.ToDouble
End Get
Set(value As Double)
ViewState("RetISROriginal") = value
End Set
End Property
Private Property TotalOriginal As Double
Get
If ViewState("TotalOriginal") Is Nothing Then
Return 0
Else
Return ViewState("TotalOriginal").ToString.ToDouble
End If
End Get
Set(value As Double)
ViewState("TotalOriginal") = value
End Set
End Property
Private Property ActualizaTotales As Boolean
Get
Return CBool(ViewState("ActualizaTotales"))
End Get
Set(value As Boolean)
ViewState("ActualizaTotales") = value
End Set
End Property
#End Region
Dim DTConceptos As DataTable
Private Property EmpresasOC As List(Of Integer)
Get
EmpresasOC = DirectCast(ViewState("EmpresasOC"), List(Of Integer))
End Get
Set(ByVal value As List(Of Integer))
ViewState("EmpresasOC") = value
End Set
End Property
Private Property DtPendientesAlmacen As DataTable
Get
DtPendientesAlmacen = DirectCast(ViewState("DtPendientesAlmacen"), DataTable)
End Get
Set(ByVal value As DataTable)
ViewState("DtPendientesAlmacen") = value
End Set
End Property
Private Property CveTipoConcepto As Integer
Get
Return ViewState("CveTipoConcepto").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("CveTipoConcepto") = value
End Set
End Property
Private Property CveRetISRConceptoOriginal As Integer
Get
If ViewState("CveRetISRConceptoOriginal") Is Nothing Then
ViewState("CveRetISRConceptoOriginal") = -1
End If
Return ViewState("CveRetISRConceptoOriginal").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("CveRetISRConceptoOriginal") = value
End Set
End Property
Private Property CveRetIVAConceptoOriginal As Integer
Get
If ViewState("CveRetIVAConceptoOriginal") Is Nothing Then
ViewState("CveRetIVAConceptoOriginal") = -1
End If
Return ViewState("CveRetIVAConceptoOriginal").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("CveRetIVAConceptoOriginal") = value
End Set
End Property
Public Property FechaCompraOriginal As Date
Get
Return ViewState("FechaCompraOriginal").ToString.ToDate
End Get
Set(value As Date)
ViewState("FechaCompraOriginal") = value
End Set
End Property
Private Property UUIDSList As List(Of String)
Get
If ViewState("UUIDSList") Is Nothing Then
Return New List(Of String)
Else
Return DirectCast(ViewState("UUIDSList"), List(Of String))
End If
End Get
Set(value As List(Of String))
ViewState("UUIDSList") = value
End Set
End Property
Private Property NumeroReembolsoOriginal As String
Get
If ViewState("NumeroReembolsoOriginal") Is Nothing Then
ViewState("NumeroReembolsoOriginal") = ""
End If
Return ViewState("NumeroReembolsoOriginal").ToString
End Get
Set(value As String)
ViewState("NumeroReembolsoOriginal") = value
End Set
End Property
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
'ImgBtnBuscarOC.Attributes.Add("data-toggle", "tooltip")
'ImgBtnBuscarOC.Attributes.Add("data-placement", "top")
CargaDatosAgregarPS()
TieneAnticiposXML = False
Modalidad = ""
Version = "4.0"
CveMetodoPago = -1
RFCProv = ""
CargaDdlTipoGasto()
CreaTmpAcarreos()
EsContado = False
CierrePeriodo = False
NCDevolucion = False
CompraCargada = False
Saldo = 0
SubTotalOriginal = 0
CveConceptoContableAlmacen = 0
EsNoDeducible = False
CveTipoConcepto = 1
'******** Prorrateo ********************************************
If UsuarioActual.Empresa.Funcionalidad(117) <> "" Then
btnProrateo.Visible = True
End If
If UsuarioActual.Empresa.Funcionalidad(303) <> "" Then
btnProrateo2.Visible = True
End If
'****************************************************************
'If UsuarioActual.CveEmpresa = 72 Then
' LiRecepcion.Visible = True
' DdlRecepcion.SelectedValue = "2"
'End If
TipoCambio = 1
IvaAcumulado = 0
TotalAlmacen = 0
TotalFlete = 0
CveOrdenCorte = -1
'VALIDACION DE XML
NuevaValidacionXML = IfNull(Request("NuevaValidacionXML"), 0).ToString.ToEntero
IdVale = New List(Of Integer)
ListaDocumentos = New List(Of String)
'If UsuarioActual.Empresa.Funcionalidad(207) = "1" Then 'Esquema nuevo PrePolizas
If Not UsuarioActual.Empresa.UsaAC Then
EmpresaPrueba = True
TotalGeneral = 0
CompraSaldo = 0
ViewState("CvePersonal") = -1
IdCuentaBancaria = 0
End If
IdCuentaBancariaComplementaria = 0
'If UsuarioActual.TienePermisoProceso(259) Then
DivEsNoDeducible.Visible = True
'End If
If UsuarioActual.Empresa.Funcionalidad(125) = "1" Then 'Seleccionar a quien se abona la Prepoliza
'ddlCargoPrePoliza.Visible = True
'lblProveedor.Visible = False
End If
If isAlmacenistaGluyas() Then
GvInv.Columns(10).Visible = True
'Dim productos As New ClsProductosServicios
'If productos.GetPS(-1, -1, UsuarioActual.CveEmpresa) Then
' PSDTRemplazo = productos.DtResultados.FiltraParametros("PendienteEnOC=1", "PS")
'End If
'productos.Dispose()
End If
PermisoEdicionManual = False
CveMovimientoAlmacen = 0
SetValues()
ArrAnticipos = New ArrayList()
ArrIE = New ArrayList()
ArrIEFuncionariosEmpleados = New ArrayList()
ClavesBorradas = New ArrayList()
TxtFecha.Text = Now.ToShortDateString
TxtFechaEjecucion.Text = Now.ToShortDateString
ViewState("CveFactura") = "0"
ViewState("IdPoliza") = "0"
ViewState("CveCompra") = -1
ViewState("EjercicioAC") = -1
ViewState("CveTipoProveedor") = -1
CveCompraRefacturacion = -1
ModalidadUMAlias = -1
CvePrePoliza = -1
TabActivosFijos.Enabled = UsuarioActual.Empresa.UsaAF
TieneOC = False
CveMoneda = -1
ImgAnticiposPendientes.Attributes.Add("OnClick", "MuestraAnticipos();")
'ImgCerrar.Attributes.Add("OnClick", "$('#DivAnticipos').hide(200);")
'BtnCancelar.Attributes.Add("OnClick", "$('#DivAddEq').hide();")
' ImageButton1.Attributes.Add("OnClick", "$('#DivAlmacen').hide();")
ImgClose.Attributes.Add("OnClick", "$('#DivAlmacen').hide();")
ImgAdd.Attributes.Add("OnClick", "$('#DivAlmacen').hide();")
'LbTotalPorDevengar.Attributes.Add("OnInnerTextChanged", "TotalDevendar();")
'Mensaje temporalca
RBLPago.Visible = True
If UsuarioActual.Empresa.UsaAC Then RBLPago.Items.RemoveAt(2) 'Elimina Reembolso cuando es AC
If UsuarioActual.Empresa.UsaAC Then
TrReembolso.Visible = True
GvPS.Columns(1).Visible = True
TxtFecha.Attributes.Add("onblur", "CambiaFecha();")
End If
TxtOC.Attributes.Add("onkeypress", "fncBuscaOC(event);")
If UsuarioActual.CveEmpresa = 66 And UsuarioActual.TienePermisoProceso(96) Then
ChkProgramarPago.Visible = True
End If
'CARGA PERSONAL
'Dim ObjPersonal As New ClsRH
'ObjPersonal.GetPersonal(-1, UsuarioActual.CveEmpresa)
Dim dtpersonal As DataTable = GlobalDTRHPersonal(UsuarioActual.CveEmpresa)
DdlPersonal.DataSource = dtpersonal 'ObjPersonal.DtResultados
DdlPersonalReembolso.DataSource = dtpersonal.FiltraParametros("CveEstatusPersonal = 1")
'ObjPersonal.Dispose()
DdlPersonal.DataBind()
DdlPersonalReembolso.DataBind()
If UsuarioActual.Empresa.Funcionalidad(590).ToString.ToEntero = 1 Then
DVCultivosCuadro.Visible = True
DdlSubProyecto.AutoPostBack = True
GlobalDTCultivosCuadro(UsuarioActual.CveEmpresa) = Nothing
Dim extrafiltro = "Estatus=1 AND "
If Request("CveCompra") IsNot Nothing AndAlso IsNumeric(Request("CveCompra")) AndAlso Request("CveCompra").ToEntero > 0 Then
extrafiltro = ""
End If
DdlCultivosCuadro.DataSource = GlobalDTCultivosCuadro(UsuarioActual.CveEmpresa).FiltraParametros($"{extrafiltro} CveSubProyecto = {DdlSubProyecto.SelectedValue}", "TemporadaCuadro")
DdlCultivosCuadro.DataBind()
DdlCultivosCuadro.Items.Insert(0, New ListItem("Seleccione uno", "-1"))
End If
'Carga Proveedor
If Request("CveProveedor") IsNot Nothing AndAlso IsNumeric(Request("CveProveedor")) AndAlso Request("CveProveedor").ToEntero > 0 Then
ViewState("CveProveedor") = Request("CveProveedor")
HdnCveProveedor.Value = Request("CveProveedor")
CargaProveedor(CveProveedor, "-1")
GvInv.Visible = True
ElseIf Request("CveFactura") IsNot Nothing AndAlso IsNumeric(Request("CveFactura")) AndAlso Request("CveFactura").ToEntero > 0 Then
ViewState("CveFactura") = Request("CveFactura").ToEntero
Dim RFC As String = CargaFactura(CveFactura)
'If Not VerificarProductosSATPS() Then
' Exit Sub
'End If
If RFC.Trim <> String.Empty Then
DdlProveedor.Visible = False
HplProveedor.Visible = True
GvInv.Visible = True
CargaProveedor(-1, RFC)
If Not DdlTipoComprobante.SelectedValue.Contiene("NC", "DEV") Then
If UsuarioActual.Empresa.Funcionalidad(128) = "1" And Not UsuarioActual.TienePermisoProceso(213) Then
If TmpDT.MAX("CvePS").ToEntero > 0 Then
'BtnGuardar.Enabled = False
RegistraScript("$('#ImgBtnBuscarOC').click()")
End If
End If
End If
If DdlTipoComprobante.SelectedValue = "NC" Then
paneldevolucion.Visible = True
Pnlalmaceninventarios.Visible = False
cargaddldevoluciones(CveProveedor, TxtSubTotal2.Text.ToDouble)
InicializaAplicaNCFact()
DivReembolso.Visible = False
RBLPago.Items(2).Enabled = False
End If
If DdlTipoComprobante.SelectedValue = "DEV" Then
InicializaAplicaNCFact()
End If
If UsuarioActual.Empresa.UsaAC Then
CambiaEjercicioAC()
End If
If UsuarioActual.Empresa.Funcionalidad(123) <> "" And Not UsuarioActual.TienePermisoProceso(156) Then
If Not ValidaCierrePeriodo() Then
Alert("El periodo de la compra actual ya se encuentra cerrado. No podra registrar la compra.", TipoMensaje.MsgAdvertencia)
BtnGuardar.Visible = False
TxtOC.Enabled = False
ImgBtnBuscarOC.Enabled = False
CierrePeriodo = True
DivRestriccionAdvertencia.Visible = True
LtRestriccionAdvertencia.Text = "El periodo de la compra actual ya se encuentra cerrado."
End If
End If
Dim HayDifIEPS As Boolean = False
For Each Gvr As GridViewRow In GvPS.Rows
If Gvr.DataKey("CvePS").ToEntero > 0 AndAlso Gvr.DataKey("IEPSPSPorcentaje").ToDouble > 0 Then
If GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=Gvr.DataKey("CvePS").ToEntero).Rows.Count > 0 Then
Dim DrPS As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=Gvr.DataKey("CvePS").ToEntero).Rows(0)
If DrPS IsNot Nothing Then
If DrPS("IEPSPorcentaje").ToString.ToDouble <> Gvr.DataKey("IEPSPSPorcentaje").ToDouble Then
HayDifIEPS = True
End If
End If
End If
End If
Next
If HayDifIEPS Then Alert("El porcentaje de IEPS del producto no coincide con el especificado.", TipoMensaje.MsgAdvertencia)
If UsuarioActual.Empresa.Funcionalidad(562).ToEntero > 0 Then CargaGastosServicios(UsuarioActual.Empresa.Funcionalidad(562).ToEntero)
End If
ElseIf Request("CveCompra") IsNot Nothing AndAlso IsNumeric(Request("CveCompra")) AndAlso Request("CveCompra").ToEntero > 0 Then
ViewState("CveCompra") = Request("CveCompra")
CargaCompra()
BtnGuardar.Enabled = False
'TdIVA.Visible = True
'DdlIVA.Enabled = False
CargaGvBitacora()
InventarioMov()
HabilitaNCInv()
DivConsignaciones.Visible = False
' 2018/05/25 - Muestra Boton Agregar Guia
LnkAgregarGuia.Visible = True
UpLnkPaqueteriaGuias.Update()
DivEsNoDeducible.Visible = True
DivActualizarVincular.Visible = True
DVModalAnticipoFechaEjecucion.Visible = True
Else
ViewState("CveProveedor") = -1
HdnCveProveedor.Value = "-1"
DdlProveedor.Items.Insert(0, New ListItem("Seleccione el Proveedor", "-1"))
GvInv.Visible = True
'TdIVA.Visible = True
'cuando es nuevo
TxtSubTotal2.Attributes.Add("onkeyup", "ActIVA();")
TxtIVA.Attributes.Add("onkeyup", "ActTotal();")
If UsuarioActual.Empresa.UsaAC Then ChkACGeneral.Checked = False ' codigo que se usa para que al agregar una compra manual, al cambiar el filtro del presupuestos afecte a lo capturado
If UsuarioActual.Empresa.UsaAC Then
CambiaEjercicioAC()
End If
UpConsignaciones.Update()
UpINV.Update()
'DdlIVA.Visible = True ' cuando es compra manual
If UsuarioActual.CveEmpresa = 126 Then
CargaOrdenCorte()
LnkAddOtrosGastos.Visible = True
UpnTools.Update()
End If
LnkAgregarGuia.Visible = False
UpLnkPaqueteriaGuias.Update()
End If
If Not CveCompra > 0 Then
LIContratos.Visible = True
End If
'SI ES UNA COMPRA NUEVA SE PONE EL TOTAL, SI NO EL SALDO
LblSaldoFactura.Text = If(CveCompra > 0, Saldo.FormatoNumero, TxtTotal.Text.FormatoNumero)
'cuando es factura con amortizacion, el importe a descontar es el saldo que se debe de aplicar para la amortizacion
If ListaDocumentos IsNot Nothing AndAlso ListaDocumentos.Count > 0 Then
LblSaldoFactura.Text = TmpDT.SUMD("Descuento").ToString
End If
If UsuarioActual.CveEmpresa = 126 And CveCompra > 0 Then
LnkExportaGv.Visible = True
End If
'Condiciones de la Compra
Dim dt As DataTable = GlobalDTBancosCuentas(UsuarioActual.CveUsuario, CveEmpresa:=UsuarioActual.CveEmpresa)
dt = dt.FiltraParametros(String.Format("CveTipoCuenta = 1"))
DdlCajaChica.DataSource = dt
DdlCajaChica.DataBind()
DdlCuentaCajaChicaReembolso.DataSource = dt
DdlCuentaCajaChicaReembolso.DataBind()
ViewState("CveCajaChica") = -1
ViewState("CvePersonal") = -1
CargaTipoTransaccion()
CargaCuentas()
'If CveFactura > 0 AndAlso UsuarioActual.Empresa.UsaAC Then
' CompruebaAgregar()
'End If
'VALIDA REQUIERE CENTRO COSTOS
If UsuarioActual.Empresa.RequiereCentroCostos Then
'RFVSubProyecto.Enabled = True
End If
'VALIDA Usuario TIPO REMESA
If UsuarioActual.TienePermisoProceso(108) Then
RBLPago.Enabled = False
'VALIDA FECHAPAGO PARA USUARIO TIPO REMESA
If UsuarioActual.TienePermisoProceso(109) Then
TxtFechaPago.Enabled = False
End If
End If
'Valida Proceso 115 para ALMACENISTA
If UsuarioActual.TienePermisoProceso(115) Then
TxtFechaPago.Enabled = False
ChkAplicaNotaCredito.Enabled = False
RBLPago.Enabled = False
BtnGuardar.Enabled = False
BtnGuardar.ToolTip = "Obliga a seleccionar una Orden de compra para su registro."
End If
'Valida Proceso 119 para ROL Administrador de obra - Bloquea Contado
If UsuarioActual.TienePermisoProceso(119) Then
RBLPago.Items(1).Enabled = False
End If
'VALIDA REFACTURACION
ValidaRefacturacion()
If UsuarioActual.TienePermisoProceso(118) Then
RBLPago.Enabled = True
RBLPago.Items(1).Enabled = False
End If
'Cargamos los Fletes
ValidaFletesServicios()
If CveCompra > 0 Then
CargaFletesAgregados()
End If
InicializaOC()
'Valida si el IVA del XML es está bien calculado
ValidaIVA()
If UsuarioActual.TienePermisoProceso(196) Then
BtnRegenerarPrePolizaAlmacen.Visible = True
UpFacturar.Update()
End If
If CompraCargada AndAlso Request("ADRegenerarPPD") IsNot Nothing AndAlso IsNumeric(Request("ADRegenerarPPD")) AndAlso Request("ADRegenerarPPD").ToEntero = 15062017 Then
RegeneraPrePoliza()
End If
CargaFletes()
If UsuarioActual.Empresa.CvePlataforma = 2 Then
TabActivosFijos.Visible = False
VerRefacturacion.Visible = False
'liServicios.Visible = False
DivConsignaciones.Visible = False
End If
CargarCentrosDeCosto(DdlAsignarProyecto, DdlAsignaSubProyecto, LitHProyecto, LblSubProyectoHeader)
CargarCentrosDeCosto(DdlProyecto, Nothing, Nothing, Nothing)
divproyecto.Visible = DdlProyecto.Visible
CargaGvPersonal()
CargaDdlPersonal()
InicializaDevolucionAlmacen()
HabilitaEdicionManualAgregar()
InicializaActualizarTC()
LtlTareaNueva.Text = String.Format("<a class=""caption-subject bold font-green"" onclick=""OpenModalNewTareaUserControl(1,-1,{{CveCompra:{0}}});""> <i class=""fa fa-plus""'></i> Tarea</a>", CveCompra)
'Valida si tienes permisos para devolucion automatica y si cumple con las condiciones para mostrarlo
If UsuarioActual.TienePermisoProceso(315) And GvInvMov.Rows.Count > 0 Then
divDevAuto.Visible = True
End If
If UsuarioActual.CveEmpresa.Contiene(13, 83) Then
GVAnticipos.Columns(6).Visible = True
DVAntComiciones.Visible = True
End If
If DdlTipoComprobante.SelectedValue = "NC" Then
NCSeleccionFacturasRelacionadas(UUIDSList)
End If
End If
'SE OCUPAN AFUERA DEL POSTBACK ??
cargaddlVinculacionServcios()
If UsuarioActual.TienePermisoProceso(117) Then
HplAddClasificacion.Visible = False
ImgClasificacion.Visible = False
End If
'If CargoFactura Then
' 'If UsuarioActual.Empresa.Funcionalidad(128) = "1" Then
' ' If TmpDT.MAX("CvePS").ToEntero > 0 Then
' ' BtnGuardar.Enabled = False
' ' RegistraScript($"AbrirVentana('/OC/PopUpBuscarReq.aspx?V=VOCCOMP&P={CveProveedor}&Masterimpoup=true',1000,600,'S'); return false;")
' ' End If
' 'End If
'End If
'RegistraScript("ScrollVentanaAddProducto();")
If UsuarioActual.Empresa.Funcionalidad(558) = "1" Then
divImportacion.Visible = True
chkImportacion.Attributes.Add("onclick", "ChkImportacion(this);")
End If
MostrarOcultarColumnaIEPS()
End Sub
#Region "C A R G A S"
Private Sub MostrarOcultarColumnaIEPS()
If TxtIEPS.Text.ToDecimal <> 0 And TmpDT.SUM("IEPSPS") <> 0 Then
GvPS.Columns(9).Visible = True
TD_Gvps_IEPS.Visible = True
Else
GvPS.Columns(9).Visible = False
TD_Gvps_IEPS.Visible = False
End If
UpPS.Update()
End Sub
Private Sub CargaOrdenCorte()
Dim ObjCGame As New ClsCGame()
If ObjCGame.GetOrdenCorte(UsuarioActual.CveEmpresa) Then
DdlOrdenCorte.DataSource = ObjCGame.DtResultados.FiltraParametros("Disponible = 1")
DdlOrdenCorte.Items.Insert(0, New ListItem("No vincular", "-1"))
End If
ObjCGame.Dispose()
DdlOrdenCorte.DataBind()
UpOtrosGastos.Update()
End Sub
Private Sub CargaDdlTipoGasto()
DdlTipoGasto.DataSource = GlobalDTTiposGastos(UsuarioActual.CveEmpresa)
DdlTipoGasto.DataBind()
DdlTipoGastoAsignar.DataSource = GlobalDTTiposGastos(UsuarioActual.CveEmpresa)
DdlTipoGastoAsignar.DataBind()
UpParametros.Update()
If UsuarioActual.CveRol = 1 OrElse UsuarioActual.CveEmpresa = 119 Then
ChkAliasFlexible.Visible = True
End If
End Sub
Private Sub CargaGvAcarreos(tCveProveedor As Integer)
Dim ObjAcar As New ClsAcarreos
If ObjAcar.GetPreEstimacion(tCveProveedor, UsuarioActual.CveEmpresa, -1) Then
GvAcarreo.DataSource = ObjAcar.DtResultados
If ObjAcar.DtResultados.Rows.Count > 0 Then
LnkAcarreo.Visible = True
End If
End If
ObjAcar.Dispose()
UpAddAcarreo.Update()
GvAcarreo.DataBind()
End Sub
Private Sub ValidaIVA()
If (Version <> "3.3" And Version <> "4.0") And CveCompra <= 0 Then
Dim ImporteIVAXML As Double = (TxtSubTotal.Text.Trim.ToDouble - TxtDescuento.Text.Trim.ToDouble - TxtIEPS.Text.Trim.ToDouble) * 0.16
If Math.Abs(TxtIVA.Text.Trim.ToDouble - ImporteIVAXML) >= 1 Then
Alert("El <b>IVA</b> del <b>CFDi</b> no tiene un comportamiento normal, por favor verifique que sea correcto. <br /><br /> <b>NOTA:</b> Esta advertencia no aplica en casos de conceptos(alimentos, combustibles o servicios de comunicación) exentos de IVA o causantes de IEPS.", TipoMensaje.MsgAdvertencia)
End If
End If
End Sub
Private Function isAlmacenistaGluyas() As Boolean
'Return (UsuarioActual.CveRol = 1052 And UsuarioActual.CveEmpresa = 66)
Return False
End Function
Private Function CargaFactura(CveFactura As Integer) As String
Dim ObjeFacturas As New ClsCompras
Dim RFC As String = ""
If ObjeFacturas.GetFacturas(CveFactura, "-1", Now.AddYears(-4), Now, "-1", "-1", -1, -1, -1, -1, "-1", UsuarioActual.CveEmpresa) AndAlso ObjeFacturas.DtResultados.Rows.Count > 0 Then
Dim dr As DataRow = ObjeFacturas.DtResultados.Rows(0) ' no toma la cero, porque es el totalizador
Dim XMLDoc As New XmlDocument
Dim Archivo As String = String.Format("{0}Compras\{1}\{2}", UsuarioActual.Empresa.Ruta, dr("RFCDe"), dr("XML"))
If IO.File.Exists(Archivo) Then
Dim Validada As Boolean = True
Dim EnListadoEFOS As Boolean = False
If Not UsuarioActual.Empresa.Funcionalidad(529) = "1" Then
'verificacion doble, si no la han cancelado, ya tiene una validaci[on para que llegue aqui
Dim SWatch As New Stopwatch
SWatch.Start()
Dim ts As New TimeSpan
Dim Valida As New ClsValidaCFDi(dr("UUID").ToString(), dr("RFCDe").ToString, dr("RFCPara").ToString(), dr("Total").ToString.ToDecimal)
SWatch.Stop()
Dim SegundosRespuesta As Double = SWatch.ElapsedMilliseconds / 1000
SegundosRespuesta = SegundosRespuesta.ToEntero
If SWatch.ElapsedMilliseconds >= 5000 Then
Alert($"Los servicios de validacion del SAT presentan lentitud en la respuesta [{ SegundosRespuesta } s].", TipoMensaje.ToastError, "", 0)
End If
If UsuarioActual.CveEmpresa < 2 Then
Valida.EsValida = 1
End If
EnListadoEFOS = Valida.EnListaEFOS
If EnListadoEFOS Then
Alert("El emisor de la factura se encuentra dentro del listado de EFOS.", TipoMensaje.MsgAdvertencia)
End If
If Valida.EsValida > 0 Then
If Valida.EsValida = 2 Then
Validada = False
If ObjeFacturas.UpdateEstatus(Valida.EsValida, CveFactura, UsuarioActual.CveEmpresa) Then
End If
Alert("La factura está cancelada ante el SAT.", TipoMensaje.MsgError)
Else ' cuando es valor =1, es vigente
Validada = True
'solicitud de activacion de facturas
'If UsuarioActual.CveEmpresa = 66 Then Alert("Se deshabilitado la validación ante el SAT.<br/> Pero el Sistema validación del SAT esta funcionando. ")
End If
Else
'no se pudo validar, pero ya tuvo la primera vuelta de validacion
Validada = True
End If
'Valida.Dispose()
Else
Alert("Los servicios de validacion de facturas del SAT, no están activados.", TipoMensaje.ToastError, "", 0)
End If
UpPSS.Update()
If Validada And Not EnListadoEFOS Then
Try
XMLDoc.LoadXml(File.ReadAllText(Archivo).Replace("&lt;br&gt;", "").Replace("&lt;", "").Replace("o;?", ""))
Catch ex As Exception
Try
Dim oReader = New StreamReader(Archivo, Encoding.GetEncoding("ISO-8859-1"))
XMLDoc.Load(oReader)
oReader.Dispose()
Catch ex2 As Exception
GuardaLog("Error al intentar leer el XML del SAT. Error:" & ex2.ToString())
End Try
End Try
CreaDTConceptos()
CargaComprobanteXML(XMLDoc)
If NuevaValidacionXML = 1 Or (Version = "3.3" Or Version = "4.0") Then
Dim Xml As String
Dim nodo As XmlNode = XMLDoc.DocumentElement
Dim Version = ValorXML(nodo, "version")
Dim Prefijo As String = If(XMLDoc.DocumentElement.Prefix = "", "cfd", XMLDoc.DocumentElement.Prefix)
Dim cfdVer As String = ""
Dim namespaces As New XmlNamespaceManager(XMLDoc.NameTable)
If Version = "3.2" Then
Prefijo = "cfd"
cfdVer = "http://www.sat.gob.mx/cfd/2"
ElseIf Version = "3.3" Then
cfdVer = "http://www.sat.gob.mx/cfd/3"
Else ' se considera que es la version 4.0
cfdVer = "http://www.sat.gob.mx/cfd/4"
End If
'If Prefijo.ToLower <> "cfdi" Then cfdVer = "http://www.sat.gob.mx/cfd/2"
namespaces.AddNamespace(Prefijo, cfdVer)
namespaces.AddNamespace("tfd", "http://www.sat.gob.mx/TimbreFiscalDigital")
namespaces.AddNamespace("implocal", "http://www.sat.gob.mx/implocal")
namespaces.AddNamespace("registrofiscal", "http://www.sat.gob.mx/registrofiscal")
Dim nodeconceptos As XmlNode = XMLDoc.SelectSingleNode(String.Format("//{0}:Conceptos", Prefijo), namespaces)
Xml = Replace(nodeconceptos.OuterXml, "<cfdi:", "<")
Xml = Xml.Replace("</cfdi:", "</")
Xml = Xml.Replace("xmlns:cfdi=""http://www.sat.gob.mx/cfd/3""", "")
Xml = Xml.Replace("xmlns:cfdi=""http://www.sat.gob.mx/cfd/4""", "")
Xml = Xml.Replace("&quot;", "") 'comillas
Xml = System.Web.HttpUtility.HtmlDecode(Xml.ToString)
Xml = Xml.Replace(Chr(13), "") 'salto de linea
Xml = Xml.Replace(Chr(10), "")
Xml = Xml.Replace("<br />", "") 'salto de linea html
Xml = Xml.Replace("&lt;br&gt;", "")
Xml = Xml.Replace("&lt;", "")
Xml = Xml.Replace("&", "") 'adicional, si hay otros
If ObjeFacturas.GetFacturasComparacionXML(Version, Xml, UsuarioActual.CveEmpresa) Then
TmpDT = ObjeFacturas.DtResultados
TmpDT.Columns.Add("CveSATPSActualizado")
SubTotalConceptos = TmpDT.SUMD("Total").RoundSQL
If Not TmpDT.Columns.Contains("Amortizacion") Then
TmpDT.Columns.Add("Amortizacion", GetType(Decimal))
End If
AddPS2(False)
'VALIDA QUE EL XML SI VIENE CON EL CODIGO SAT 01010101
Dim ProductosCodigoSATNoPermitidos As New StringBuilder("")
For Each drr As DataRow In TmpDT.FiltraParametros("ClaveProdServ = '01010101'").Rows
ProductosCodigoSATNoPermitidos.AppendFormat("{0}</br>", drr("PS"))
Next
If ProductosCodigoSATNoPermitidos.ToString.Length > 0 Then
Dim mensajeAdvertencia As String = String.Format("El comprobante contiene productos con código SAT '01010101', revise los productos:</br></br>{0}", ProductosCodigoSATNoPermitidos.ToString)
Alert(mensajeAdvertencia, TipoMensaje.MsgAdvertencia)
End If
End If
Else
CargaConceptosXML(XMLDoc)
End If
Select Case TipoComprobante
Case "ingreso" : DdlTipoComprobante.SelectedValue = "Fac" : DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("NC")) : DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("DEV"))
Case "egreso" : DdlTipoComprobante.SelectedValue = "NC" : DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Fac")) : DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Ant")) : ChkAplicaNotaCredito.Enabled = False
Case "I"
DdlTipoComprobante.SelectedValue = "Fac"
DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("NC"))
DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("DEV"))
DdlTipoCompra.Items.Remove(DdlTipoCompra.Items.FindByValue("6"))
DdlTipoCompra.Items.Remove(DdlTipoCompra.Items.FindByValue("11"))
Case "E"
DdlTipoComprobante.SelectedValue = "NC"
DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Fac"))
DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Ant"))
ChkAplicaNotaCredito.Enabled = False
DdlTipoCompra.Items.Clear()
DdlTipoCompra.Items.Add(New ListItem("Seleccione", "-1"))
DdlTipoCompra.Items.Add(New ListItem("NC Con Productos", "6"))
DdlTipoCompra.Items.Add(New ListItem("Apoyo Logístico", "9"))
DdlTipoCompra.Items.Add(New ListItem("NC Por Devolución", "11"))
Case "T"
DdlTipoCompra.Items.Clear()
DdlTipoCompra.Items.Add(New ListItem("Apoyo Logístico", "9"))
DdlTipoComprobante.SelectedValue = "Fac"
DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("NC"))
DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("DEV"))
End Select
'DIV ALIAS
CargaPSAlias()
RFC = dr("RFCDe").ToString
RFCProv = RFC
TxtFecha.Text = dr("FechaFactura").ToString.ToDate.ToShortDateString
TxtSerie.Text = dr("Serie").ToString
TxtFolio.Text = dr("Folio").ToString
DdlValidadaSAT.SelectedValue = If(dr("FueValidado").ToString.Contiene("Si", "1"), "Si", "No")
DdlValidadaSAT.Enabled = False
LblTipoFact.Text = dr("TipoFactura").ToString
SerieVieja = dr("Serie").ToString
LblMetodoPago.Text = MetodoPago
Dim SubTotal2, IVA, IEPS As Decimal
IVA = TrasladoIVA
If Not UsuarioActual.TienePermisoProceso(130) Then
TxtFolio.Enabled = False
TxtSerie.Enabled = False
End If
'DdlTipoComprobante.Enabled = False
'PERMISO PARA MODIFICACIÓN DE FECHA AUN CON FACTURA
TxtFecha.Enabled = UsuarioActual.TienePermisoProceso(216)
ImgFecha.Enabled = UsuarioActual.TienePermisoProceso(216)
CEFecha.Enabled = UsuarioActual.TienePermisoProceso(216)
TxtSubTotal.Enabled = False
TxtDescuento.Enabled = False
TxtSubTotal2.Enabled = False
TxtIVA.Enabled = False
TxtTotal.Enabled = False
DdlProveedor.Enabled = False
If TxtFolio.Text.Trim = "" Then TxtFolio.Enabled = True : TxtSerie.Enabled = True
If UsuarioActual.TienePermisoProceso(112) Then
PermisoEdicionManual = True
TxtSubTotal.Enabled = True
TxtDescuento.Enabled = True
TxtSubTotal2.Enabled = True
TxtIVA.Enabled = True
TxtTotal.Enabled = True
End If
If UsuarioActual.Empresa.Funcionalidad(118) = "1" AndAlso DdlTipoComprobante.SelectedValue = "Fac" Then
VerVales.Visible = True
End If
If TieneAnticiposXML Then 'si tiene anticipos, limpia los descuentos
'LblAmortizacion.Text = ImporteAnticipo.FormatoNumero
TxtDescuento.Text = "0.00"
LblAmortizacion.Text = Descuentos.FormatoNumero
'limpia los descuentos
For Each drr As DataRow In TmpDT.Rows
'drr("Total") = drr("Total").ToString.ToDecimal + drr("Descuento").ToString.ToDecimal
drr("Amortizacion") = drr("Descuento") 'pasamos el importe de descuento a amortizacion
drr("Descuento") = 0.00
Next
Amortizaciones = Descuentos
Descuentos = 0
End If
Dim Msg As String = ""
If Version = "3.3" Or Version = "4.0" Then
If Not TmpDT.Columns.Contains("Amortizacion") Then
TmpDT.Columns.Add("Amortizacion", GetType(Decimal))
End If
TmpDT.AcceptChanges()
ValidacionesTotalesXml()
Else
'PRUEBA
'http://rm/Compras/Compras.aspx?CveFactura=122518 Emp: 48
'tTotal = Math.Round(SubTotal2 + IVA - RetencionIVA - RetencionISR + IEPS + OtrosImpuestos, 2)
HdnCompraSaldo.Value = Total.ToString
CompraSaldo = Total
Dim AjustaUltimoConcepto = False
'AGREGA IEPS COMO CONCEPTO
If TrasladoIEPS > 0 And UsuarioActual.Empresa.Funcionalidad(112).ToString.ToEntero > 0 Then
AgregarConceptoIEPS(TrasladoIEPS, UsuarioActual.Empresa.Funcionalidad(112).ToString.ToEntero)
' TrasladoIEPS = 0
End If
'AGREGA IEPS COMO IMPORTE GENERAL
'If TrasladoIEPS > 0 And Not UsuarioActual.Empresa.Funcionalidad(112).ToString.ToEntero > 0 Then
' IEPS = TrasladoIEPS
'End If
'en otro impuesto lo esta registrando en ajuste en automatico
If OtrosImpuestos > 0 Then
AjustaUltimoConcepto = True
End If
If RFC = "CFE370814QI0" Then ' RFC de CFE, se hace un ajuste por diferencia para sacar el DAP
'OtrosImpuestos = Total - (SubTotal2 + IVA)
'este importe lo vamos a meter al gasto
'AjustaImporteUltimoConcepto(OtrosImpuestos)
OtrosImpuestos = 1
AjustaUltimoConcepto = True
'SubTotal2 = SubTotal
End If
Dim SubTotalReal As Decimal = 0
SubTotalReal = Math.Round(Total + RetencionISR + RetencionIVA - IVA + Descuentos - TrasladoIEPS, 2) ' NO se incluye otros impuestos para ajustar esa cifra
Dim DiferenciaTotales As Decimal = SubTotalReal - Math.Round(SubTotalConceptos, 2)
If DiferenciaTotales <> 0 Then
'Verificamos IEPS y Otros Impuestos
'restricccion general, que si el subtotal de los conceptos no cuadra con Total + RetISR + RetIVA - IVA <> SubTotalConeptos, ajuste al final
If TrasladoIEPS > 0 OrElse OtrosImpuestos > 0 OrElse Math.Abs(DiferenciaTotales) < 1 Then
'Condicion necesaria cuando hay IVA pero no hay diferencia
If DiferenciaTotales <> 0 Then
If DiferenciaTotales < 50 OrElse AjustaUltimoConcepto = True Then
Dim IA As Decimal = Total + RetencionISR + RetencionIVA - IVA - SubTotalConceptos - TrasladoIEPS + Descuentos
AjustaImporteUltimoConcepto(IA, True)
ElseIf DiferenciaTotales > 50 Then
PnlAjusteProductos.Visible = True
Dim Porcentaje As Double = Math.Round((SubTotalConceptos - SubTotalReal) / SubTotalConceptos * 100, 2)
TxtAjustePorcentaje.Text = Porcentaje.FormatoNumero
Msg &= String.Format("La Factura presenta anomalias en los importes mostrados, estas anomalias impiden que se editen las partidas. Por favor realice el ajuste correspondiente <br>")
ImgBtnBuscarOC.Visible = False : TxtOC.Enabled = False
'Ocultamos la opcion de Editar y Eliminar hasta que se arreglen las anomalias
For Each Row As GridViewRow In GvPS.Rows
Row.FCLinkButton("imgE").Visible = False
Row.FCLinkButton("imgD").Visible = False
Next
End If
End If
TrasladoIEPS = 0 : OtrosImpuestos = 0 : SubTotal2 = SubTotal
Else
PnlAjusteProductos.Visible = True
Dim Porcentaje As Double = If(SubTotalConceptos > 0, Math.Round((SubTotalConceptos - SubTotalReal) / SubTotalConceptos * 100, 2), 0)
TxtAjustePorcentaje.Text = Porcentaje.FormatoNumero
Msg &= String.Format("La Factura presenta anomalias en los importes mostrados, estas anomalias impiden que se editen las partidas. Por favor realice el ajuste correspondiente <br>")
ImgBtnBuscarOC.Visible = False : TxtOC.Enabled = False
'Ocultamos la opcion de Editar y Eliminar hasta que se arreglen las anomalias
For Each Row As GridViewRow In GvPS.Rows
Row.FCLinkButton("imgE").Visible = False
Row.FCLinkButton("imgD").Visible = False
Next
End If
End If
'Si no hay diferencias pero tenemos descuento, se ofrece la opcion para ajustar el gasto
If Descuentos > 0 Then
'[IPP] PARCHE: Factura TELMEX para APH 12/ENERO/2018
If CveFactura = 286290 Then
Else
PnlAjusteProductos.Visible = True
Dim Porcentaje As Double = Math.Round((Descuentos) / (SubTotalConceptos) * 100, 4)
TxtAjustePorcentaje.Text = Porcentaje.FormatoNumero(4)
Msg &= String.Format("La Factura presenta anomalias en los importes mostrados, estas anomalias impiden que se editen las partidas. Por favor realice el ajuste correspondiente <br>")
ImgBtnBuscarOC.Visible = False : TxtOC.Enabled = False
'Ocultamos la opcion de Editar y Eliminar hasta que se arreglen las anomalias
For Each Row As GridViewRow In GvPS.Rows
Row.FCLinkButton("imgE").Visible = False
Row.FCLinkButton("imgD").Visible = False
Next
End If
End If
SubTotal2 = SubTotalReal - Descuentos
If Descuentos > 0 Then
TrDescuento.Visible = True
End If
If Msg <> "" Then
Alert(Msg, TipoMensaje.MsgAdvertencia)
BtnGuardar.Enabled = False
End If
'AJUSTAMOS SUBTOTAL EN CASO DE SER DIFERENTE AL SUBTOTAL2 DEL XML (TOTAL - IVA)
If SubTotal2 <> SubTotal Then
SubTotal = SubTotalConceptos
End If
TxtSubTotal.Text = SubTotal.FormatoNumero
TxtDescuento.Text = Descuentos.FormatoNumero
TxtSubTotal2.Text = SubTotal2.FormatoNumero
TxtIVA.Text = IVA.FormatoNumero
TxtTotal.Text = Total.ToString.FormatoNumero
HfTotalCompra.Value = Total.ToString
CompraSaldo = Total
CalculaTotalPorDevengar()
TxtDocumentoImporteFE.Text = Total.ToString
RVDocumentoImporte.MaximumValue = Math.Round(Total, 2).ToString
RVDocumentoImporteFE.MaximumValue = RVDocumentoImporte.MaximumValue
RVDocumentoImporteCaja.MaximumValue = RVDocumentoImporte.MaximumValue
TxtDocumentoImporte.Text = Total.FormatoNumero
TxtDocumentoImporteCaja.Text = Total.FormatoNumero
TxtRetIVA.Text = RetencionIVA.FormatoNumero
TxtRetISR.Text = RetencionISR.FormatoNumero
TxtIEPS.Text = IEPS.FormatoNumero
If IEPS > 0 Then TrIEPS.Visible = True
If RetencionIVA > 0 Then TrRetIVA.Visible = True
If RetencionISR > 0 Then TrRetISR.Visible = True
TxtOtrosImpuestos.Text = OtrosImpuestos.FormatoNumero
If OtrosImpuestos > 0 Then TrOtrosImpuestos.Visible = True
HFDiferenciaCompra.Value = TxtTotal.Text
LblRetIVA.Text = (If(SubTotal2 > 0, (RetencionIVA / SubTotal2), 0) * 100).FormatoNumero(3) + "%"
LblRetISR.Text = (If(SubTotal2 > 0, (RetencionISR / SubTotal2), 0) * 100).FormatoNumero(3)
'ASIGNA VALORES ORIGINALES PARA GUARDAR
AsignaValoresOriginales(SubTotal, SubTotal2, IVA, RetencionIVA, RetencionISR, Total)
End If
TxtFechaPago.Text = (TxtFecha.Text.ToDate.AddDays(LblDiasCredito.Text.ToEntero)).ToShortDateString
Dim drMon As DataRow = GlobalDTMonedas.FiltroPrimero(String.Format(" (Abreviatura LIKE '%{0}%' OR Moneda LIKE '%{0}%' )", Moneda))
If drMon IsNot Nothing Then
DdlMoneda.SelectedValue = drMon("CveMoneda").ToString
Else
'sino busco en la tabla de alias
drMon = GlobalDTMonedasAlias.FiltroPrimero(String.Format("MonedaAlias LIKE '%{0}%' ", Moneda))
If drMon IsNot Nothing Then
DdlMoneda.SelectedValue = drMon("CveMoneda").ToString
Else
LblMoneda.Text = Moneda
LblMoneda.ForeColor = Drawing.Color.Red
End If
End If
If DdlMoneda.SelectedValue.ToEntero > 1 Then
If TipoCambio <= 10 Then
TipoCambio = GlobalTipoCambio(TxtFecha.Text.ToDate).ToDecimal
End If
TxtFecha.Attributes.Remove("onblur")
If UsuarioActual.Empresa.UsaAC Then
TxtFecha.Attributes.Add("onblur", "CambiaFecha();CambiaFechaTC();")
Else
TxtFecha.Attributes.Add("onblur", "CambiaFechaTC();")
End If
End If
If TipoCambio > 0 And DdlMoneda.SelectedValue.ToEntero > 1 Then LblTC.Text = String.Format("TC: {0}", TipoCambio.ToString("N4"))
'DF - 10-04-17
If UsuarioActual.TienePermisoProceso(187) Then
TxtSerie.Enabled = True
End If
If LblMetodoPago.Text = "" AndAlso TipoComprobante <> "T" Then
Alert("El xml no contiene la etiqueta 'método de pago', favor de verificar la emisión con el proveedor.", TipoMensaje.MsgAdvertencia)
BtnGuardar.Visible = False
End If
End If
Else
Alert("No se Encontró la Factura", TipoMensaje.MsgAdvertencia)
BtnGuardar.Visible = False
End If
'GvPS.DataSource = 'DTConceptos
'GvPS.DataBind()
End If
ObjeFacturas.Dispose()
If RFC <> "" Then
Dim ObjSAT As New ClsSAT
If ObjSAT.GetListado69B(2, UsuarioActual.CveEmpresa, RFC) Then
If ObjSAT.DtResultados.Rows.Count > 0 Then
Dim Estatus As String = ObjSAT.DtResultados.Rows(0)("Situacion").ToString
BtnGuardar.Enabled = False
UpParametros.Update()
Alert($"El RFC del proveedor se encuentra en estado <b>{Estatus}</b> en el Listado EFOS (69B) del SAT", TipoMensaje.MsgAdvertencia)
System.Threading.Thread.Sleep(5)
End If
End If
ObjSAT.Dispose()
End If
Return RFC
End Function
Private Sub CargaRetIVAConcepto(Optional Cambio As Boolean = False, Optional DIOTCveTipoOperacion As Integer = -1)
If TrRetIVA.Visible Then
TdRetIVAConcepto.Visible = True
End If
If Cambio Then
DdlRetIVAConcepto.Items.Clear()
If RFCProv.Length = 13 Then ' personal fisica
If DIOTCveTipoOperacion = 1 Then '03 - Prestación de Servicios Profesionales
DdlRetIVAConcepto.Items.Insert(0, New ListItem("Honorarios/Serv. Prof.", "1"))
End If
If DIOTCveTipoOperacion = 2 Then ' 06 - Arrendamiento de inmuebles
DdlRetIVAConcepto.Items.Add(New ListItem("Arrendamiento", "4"))
End If
If DIOTCveTipoOperacion.Contiene(0, 3) Then ' 85 - Otros
DdlRetIVAConcepto.Items.Insert(0, New ListItem("Honorarios/Serv. Prof.", "1"))
DdlRetIVAConcepto.Items.Add(New ListItem("Arrendamiento", "4"))
DdlRetIVAConcepto.Items.Insert(0, New ListItem("Fletes P.F.", "2"))
DdlRetIVAConcepto.Items.Add(New ListItem("Resico", "5"))
DdlRetIVAConcepto.Items.Add(New ListItem("General", "6"))
End If
ElseIf RFCProv.Length = 12 Then ' persona moral
If DIOTCveTipoOperacion = 1 Then '03 - Prestación de Servicios Profesionales
DdlRetIVAConcepto.Items.Insert(0, New ListItem("Honorarios/Serv. Prof.", "1"))
End If
If DIOTCveTipoOperacion = 2 Then ' 06 - Arrendamiento de inmuebles
DdlRetIVAConcepto.Items.Add(New ListItem("Arrendamiento", "4"))
End If
If DIOTCveTipoOperacion.Contiene(0, 3) Then ' 85 - Otros
DdlRetIVAConcepto.Items.Insert(0, New ListItem("Honorarios/Serv. Prof.", "1"))
DdlRetIVAConcepto.Items.Add(New ListItem("Arrendamiento", "4"))
DdlRetIVAConcepto.Items.Insert(0, New ListItem("Fletes P.M.", "3"))
DdlRetIVAConcepto.Items.Add(New ListItem("Resico", "5"))
DdlRetIVAConcepto.Items.Add(New ListItem("General.", "6"))
End If
End If
End If
UpPS.Update()
End Sub
Private Sub CargaRetISRConcepto(Optional Cambio As Boolean = False, Optional DIOTCveTipoOperacion As Integer = -1)
If TrRetISR.Visible Then
TdRetISRConcepto.Visible = True
End If
If Cambio Then
DdlRetISRConcepto.Items.Clear()
If DIOTCveTipoOperacion = 1 Then '03 - Prestación de Servicios Profesionales
DdlRetISRConcepto.Items.Insert(0, New ListItem("Honorarios", "1"))
DdlRetISRConcepto.Items.Insert(1, New ListItem("Resico", "3"))
End If
If DIOTCveTipoOperacion = 2 Then ' 06 - Arrendamiento de inmuebles
DdlRetISRConcepto.Items.Insert(0, New ListItem("Arrendamiento", "2"))
DdlRetISRConcepto.Items.Insert(1, New ListItem("Resico", "3"))
End If
If DIOTCveTipoOperacion.Contiene(0, 3) Then ' 85 - Otros
DdlRetISRConcepto.Items.Insert(0, New ListItem("Honorarios", "1"))
DdlRetISRConcepto.Items.Insert(1, New ListItem("Arrendamiento", "2"))
DdlRetISRConcepto.Items.Insert(1, New ListItem("Resico", "3"))
End If
End If
UpPS.Update()
End Sub
Private Sub ValidacionesTotalesXml()
If Not TmpDT.Columns.Contains("Amortizacion") Then
TmpDT.Columns.Add("Amortizacion", GetType(Decimal))
End If
Dim Msg As String = ""
Dim SubtotalTemp = TmpDT.SUM("Total") + Math.Round(TmpDT.SUM("Descuento") + Math.Round(TmpDT.SUM("Amortizacion")), 2)
Dim DescuentosTemp = TmpDT.SUM("Descuento")
Dim Subtotal2Temp = TmpDT.SUM("Total")
Dim IVATemp = TmpDT.SUM("IVA")
Dim IEPSTemp = TmpDT.SUM("IEPSPS")
Dim RetIVATemp = TmpDT.SUM("RetIVA")
Dim RetISRTemp = TmpDT.SUM("RetISR")
Dim TotalTemp As Decimal = (Subtotal2Temp - RetIVATemp - RetISRTemp + Math.Round(IVATemp, 6) + IEPSTemp + OtrosImpuestos - OtrosImpuestosRetenciones).ToDecimal
If Math.Abs(Math.Round(DescuentosTemp, 6) - Math.Round(Descuentos, 6)) > 0.01 Then
Msg &= String.Format("- Los descuentos del detalle no coinciden con el descuento general <br>")
End If
If Math.Abs(Math.Round(IVATemp, 6) - Math.Round(TrasladoIVA, 6)) > 0.01 Then
Msg &= String.Format("- Los IVAS del detalle no coinciden con el IVA general <br>")
End If
If Math.Abs(Math.Round(IEPSTemp, 6) - Math.Round(TrasladoIEPS, 6)) > 0.01 Then
Msg &= String.Format("- Los IEPS del detalle no coinciden con el IEPS general <br>")
End If
If Math.Abs(Math.Round(RetIVATemp, 6) - Math.Round(RetencionIVA, 6)) > 0.01 Then
Msg &= String.Format("- Los RetIVA del detalle no coinciden con el RetIVA general <br>")
End If
If Math.Abs(Math.Round(RetISRTemp, 6) - Math.Round(RetencionISR, 6)) > 0.01 Then
Msg &= String.Format("- Las RetISR del detalle no coinciden con el RetIVA general <br>")
End If
If Math.Abs(Math.Round(TotalTemp, 2) - Math.Round(Total, 2)) > 0.01 Then
Msg &= String.Format("- El total generado por los detalles no coincide con el total general <br> ({0}-{1})", Math.Round(TotalTemp, 2), Math.Round(Total, 2))
End If
If Msg <> "" Then
Alert($"<b>El comprobante XML presenta las siguientes inconsistencias:</b> <br><br> {Msg}", TipoMensaje.MsgAdvertencia)
Tab.ActiveTabIndex = 0
''''BLOQUEA ACCIONES''''
BtnGuardar.Enabled = False
'BLOQUEA OC
TxtOC.Enabled = False
ImgBtnBuscarOC.Visible = False
Else
'[IPP] IGUALAMOS VALORES PARA RESPETAR LOS DEL XML EN CASO DE DIF DE 0.01
DescuentosTemp = Descuentos
IVATemp = TrasladoIVA
TotalTemp = Total
RetIVATemp = RetencionIVA
RetISRTemp = RetencionISR
IEPSTemp = TrasladoIEPS
End If
If TrasladoIEPS > 0 Or OtrosImpuestos > 0 Then
If OtrosImpuestos > 0 Then
RegistraScript("$('#ModalIEPS').modal({ backdrop: 'static', keyboard: false },'show');")
Else
RegistraScript("$('#ModalIEPS').modal('show');")
BtnCancelarotrosImpuestos.Visible = True
End If
If TrasladoIEPS > 0 Then
ChkIEPS.Visible = True
ChkIEPS.Checked = True
DdlConceptoIEPS.Visible = True
CargaProductos(DdlConceptoIEPS, If(UsuarioActual.Empresa.Funcionalidad(112).ToString.ToEntero > 0, UsuarioActual.Empresa.Funcionalidad(112).ToString.ToEntero, -1))
LbImporte.Text = "$" + TrasladoIEPS.ToString
End If
If OtrosImpuestos > 0 Then
ChkOtrosI.Visible = True
ChkOtrosI.Checked = True
DdlConceptoOI.Visible = True
CargaProductos(DdlConceptoOI, If(UsuarioActual.Empresa.Funcionalidad(305).ToString.ToEntero > 0, UsuarioActual.Empresa.Funcionalidad(305).ToString.ToEntero, -1))
LbImporte2.Text = "$" + OtrosImpuestos.ToString
End If
End If
Dim MostrarRetIva6 As Boolean = False
TxtSubTotal.Text = SubtotalTemp.FormatoNumero
TxtDescuento.Text = DescuentosTemp.FormatoNumero
TxtSubTotal2.Text = Subtotal2Temp.FormatoNumero
TxtIVA.Text = IVATemp.FormatoNumero
TxtTotal.Text = TotalTemp.FormatoNumero
TxtRetIVA.Text = RetIVATemp.FormatoNumero
TxtRetISR.Text = RetISRTemp.FormatoNumero
TxtIEPS.Text = IEPSTemp.FormatoNumero
TrDescuento.Visible = DescuentosTemp > 0
TrIEPS.Visible = IEPSTemp > 0
TrRetIVA.Visible = RetIVATemp > 0
TrRetISR.Visible = RetISRTemp > 0
TxtSubTotal.Enabled = False
TxtDescuento.Enabled = False
TxtSubTotal2.Enabled = False
TxtIVA.Enabled = False
TxtTotal.Enabled = False
TxtRetIVA.Enabled = False
TxtRetISR.Enabled = False
TxtIEPS.Enabled = False
HfTotalCompra.Value = TotalTemp.ToString
CompraSaldo = TotalTemp
CalculaTotalPorDevengar()
TxtDocumentoImporteFE.Text = TotalTemp.ToString
RVDocumentoImporte.MaximumValue = Math.Round(TotalTemp, 2).ToString
RVDocumentoImporteFE.MaximumValue = RVDocumentoImporte.MaximumValue
RVDocumentoImporteCaja.MaximumValue = RVDocumentoImporte.MaximumValue
TxtDocumentoImporte.Text = TotalTemp.FormatoNumero
TxtDocumentoImporteCaja.Text = TotalTemp.FormatoNumero
TxtOtrosImpuestos.Text = OtrosImpuestos.FormatoNumero
If OtrosImpuestos > 0 Then TrOtrosImpuestos.Visible = True
If OtrosImpuestosRetenciones > 0 Then TrOtrosImpuestos.Visible = True : TxtOtrosImpuestos.Text = (-OtrosImpuestosRetenciones).FormatoNumero
HFDiferenciaCompra.Value = TxtTotal.Text
HdnCompraSaldo.Value = TotalTemp.ToString
CompraSaldo = TotalTemp
LblRetIVA.Text = (If(Subtotal2Temp > 0, (RetIVATemp / Subtotal2Temp), 0) * 100).FormatoNumero(3) + "%"
LblRetISR.Text = (If(Subtotal2Temp > 0, (RetISRTemp / Subtotal2Temp), 0) * 100).FormatoNumero(3)
'ASIGNA VALORES ORIGINALES PARA GUARDAR
AsignaValoresOriginales(SubtotalTemp, Subtotal2Temp, IVATemp, RetIVATemp, RetISRTemp, Total)
'If UsuarioActual.Empresa.Funcionalidad(577).ToString = "1" Then
' If RetencionIVA = 0 And IVAOriginal > 0 Then
' For Each dRow As DataRow In TmpDT.Rows
' If dRow("CveTipoPS").ToString.ToEntero = 1 Then
' 'comentado para reubicar el boton
' 'tdIVA6.Visible = True
' Exit For
' End If
' Next
' End If
'End If
End Sub
''' <summary>
''' Método que convierte el IEPS en un concepto para no ajustar totales
''' </summary>
Private Sub AgregarConceptoIEPS(IEPS As Decimal, CvePS1 As Integer)
Dim SubTotalR As Decimal = TmpDT.SUM("Total").ToString.ToDecimal
Dim PSS As DataTable = GlobalDTPS(UsuarioActual.CveEmpresa).FiltraParametros(String.Format("CvePS = {0} ", CvePS1), "PS")
Dim PSS2 As DataTable = TmpDT.FiltraParametros(String.Format("CvePS = {0} ", CvePS1), "PS")
If PSS.Rows.Count > 0 Or PSS2.Rows.Count > 0 Then
Dim CveUM As Integer = 0
Dim UM As String = ""
Dim CveClasificacion As Integer = 0
Dim Clasificacion As String = ""
Dim CvePS As Integer = 0
Dim PS As String = ""
Dim CveTipoPS As Integer = 0
If PSS.Rows.Count > 0 Then
CveUM = PSS.Rows(0)("CveUM").ToString.ToEntero
UM = PSS.Rows(0)("UnidadMedida").ToString
CveClasificacion = PSS.Rows(0)("CveClasificacion").ToString.ToEntero
Clasificacion = PSS.Rows(0)("Clasificacion").ToString
CvePS = PSS.Rows(0)("CvePS").ToString.ToEntero
PS = PSS.Rows(0)("PS").ToString
CveTipoPS = PSS.Rows(0)("CveTipoPS").ToString.ToEntero
End If
Dim Cantidad As Decimal = 1
Dim CveSubProyectoContrato As String = "-1"
Dim CveProyecto As String = "-1"
Dim SubProyecto As String = "SE"
Dim Proyecto As String = "SE"
Dim Obs As String = ""
Dim PU As Decimal = IEPS
Dim Total As Decimal = Cantidad * PU
Dim IVA As Decimal = 0
Dim Descuento As Decimal = 0
If PSS2.Rows.Count > 0 Then
CveUM = PSS2.Rows(0)("CveUM").ToString.ToEntero
UM = PSS2.Rows(0)("UM").ToString
CveClasificacion = PSS2.Rows(0)("CveClasificacion").ToString.ToEntero
Clasificacion = PSS2.Rows(0)("Clasificacion").ToString
CvePS = PSS2.Rows(0)("CvePS").ToString.ToEntero
PS = PSS2.Rows(0)("PS").ToString
CveTipoPS = PSS2.Rows(0)("CveTipoPS").ToString.ToEntero
CveSubProyectoContrato = PSS2.Rows(0)("CveSubProyecto").ToString
CveProyecto = PSS2.Rows(0)("CveProyecto").ToString
SubProyecto = PSS2.Rows(0)("SubProyecto").ToString
Proyecto = PSS2.Rows(0)("Proyecto").ToString
Obs = PSS2.Rows(0)("Obs").ToString
Dim CveTipoGasto As Integer = PSS2.Rows(0)("CveTipoGasto").ToString.ToEntero
Dim TipoGasto As String = PSS2.Rows(0)("TipoGasto").ToString
AddPS(Cantidad, CveUM, UM, CveClasificacion, Clasificacion, CvePS, PS, CveTipoPS, CveSubProyectoContrato, SubProyecto, Proyecto, CveProyecto, Obs, PU, Total, IVA, 0, 0, 0, 0, Descuento, TCalculaTotales:=False, CveTipoGasto:=CveTipoGasto, TipoGasto:=TipoGasto)
AddPS2()
Else
AddPS(Cantidad, CveUM, UM, CveClasificacion, Clasificacion, CvePS, PS, CveTipoPS, CveSubProyectoContrato, SubProyecto, Proyecto, CveProyecto, Obs, PU, Total, IVA, 0, 0, 0, 0, Descuento, TCalculaTotales:=False)
AddPS2()
End If
End If
Dim SubTotalIEPS = TmpDT.SUM("Total").ToString.ToDecimal
SubTotal = Math.Round(SubTotalIEPS, 2)
SubTotalConceptos = Math.Round(SubTotalIEPS, 2)
'If SubTotalR <> SubTotalIEPS Then
' Dim IA As Decimal = SubTotalR - SubTotalIEPS
' AjustaImporteUltimoConcepto(IA)
'End If
PSS.Dispose()
End Sub
Private Sub CargaCompra()
Dim ObjCompra As New ClsCompras()
Dim ObjOC As New ClsOC()
If ObjCompra.GetCompras(CveCompra, "-1", "-1", -1, -1, UsuarioActual.CveEmpresa) Then
If ObjCompra.DtResultados IsNot Nothing AndAlso ObjCompra.DtResultados.Rows.Count > 0 Then
CompraCargada = True
'data-toggle="tooltip" data-placement="left" title="Agregar Escolaridad ."
If ObjCompra.DtResultados.Rows(0)("FolioREQ").ToString <> "" Then
lblOCLabel.Attributes.Add("data-toggle", "tooltip")
lblOCLabel.Attributes.Add("data-placement", "top")
lblOCLabel.Attributes.Add("title", "REQ: " & ObjCompra.DtResultados.Rows(0)("FolioREQ").ToString)
End If
'CargaProveedor
Dim dr As DataRow = ObjCompra.DtResultados.Rows(0)
Saldo = dr("Saldo").ToString.ToDecimal
RBLPago.Visible = False
Dim CveProveedor As Integer = dr("CveProveedor").ToString.ToEntero
HdnCveProveedor.Value = CveProveedor.ToString
ViewState("CveProveedor") = CveProveedor
ImgBtnBuscarOC.OnClientClick = String.Format("AbrirVentana('/OC/PopUpBuscarReq.aspx?V=VOCCOMP&P={0}&T={1}&Masterimpoup=true',1000,600,'S'); return false;", CveProveedor, DdlTipoComprobante.SelectedValue)
Dim ObjBancos As New ClsBancos()
If ObjBancos.GetCreditosCompra(CveCompra) And ObjBancos.DtResultados.Rows.Count > 0 Then
GvCreditosRelacionados.DataSource = ObjBancos.DtResultados
GvCreditosRelacionados.Visible = True
GvCreditosRelacionados.DataBind()
romCreditosTabla.Visible = True
GvCreditos.Visible = False
GvCreditosRelacionados.Visible = True
PnlContadoCreditos.Visible = True
Else
GvCreditosRelacionados.DataSource = Nothing
GvCreditosRelacionados.Visible = False
GvCreditosRelacionados.DataBind()
End If
UpGvCreditos.Update()
LblImporteCreditos.Visible = True
ObjBancos.Dispose()
'RegistraScript("CargaProveedor(""" & CveProveedor & """);")
'CargaEncabezado
'ViewState("FolioFiscal") = ObjCompra.DtResultados.Rows(0)("FolioFiscal").ToString
TxtSerie.Text = dr("Serie").ToString
TxtFolio.Text = dr("Folio").ToString
TxtFolioSecundario.Text = dr("FolioSecundario").ToString
TxtFecha.Text = dr("Fecha").ToString.ToDate.ToShortDateString
FechaCompraOriginal = dr("Fecha").ToString.ToDate
TxtDescripcion.Text = dr("Descripcion").ToString
CvePrePoliza = dr("CvePrePoliza").ToString.ToEntero
EstatusAlmacen = dr("EstatusAlmacen").ToString.ToEntero
DdlTipoCompra.SelectedValueExist(dr("CveTipoCompra"))
CveTipoConcepto = dr("CveTipoConcepto").ToString.ToEntero
ChkEsNoDeducible.Checked = Boolean.Parse(dr("NoDeducible").ToString)
'Select Case dr("PorcentajeIVA").ToString.ToDouble
' Case 0
' DdlIVA.SelectedValue = "1"
' Case 0.16
' DdlIVA.SelectedValue = "1.16"
' Case 0.08
' DdlIVA.SelectedValue = "1.08"
'End Select
'If dr("PorcentajeIVA").ToString.ToDouble = 0 Then DdlIVA.SelectedValue = "1" Else DdlIVA.SelectedValue = "1.16"
LblMetodoPago.Text = dr("MetodoPagoSAT").ToString
If UsuarioActual.Empresa.UsaAC Then
CambiaEjercicioAC(False)
End If
If GlobalDTProveedorSucursales(CveProveedor, UsuarioActual.CveEmpresa).Rows.Count > 0 Then
RowProveedorSucursal.Visible = True
DdlProveedorSucursal.Items.Clear()
DdlProveedorSucursal.DataSource = GlobalDTProveedorSucursales(CveProveedor, UsuarioActual.CveEmpresa)
DdlProveedorSucursal.DataBind()
DdlProveedorSucursal.Items.Insert(0, New ListItem("Matriz", "0"))
DdlProveedorSucursal.SelectedValueExist(dr("CveProveedorSucursal").ToString.ToEntero)
End If
''SE AJUSTO EL SUBTOTAL POR LA COMPRA # 52433 DE LA EMPRESA 48 PARA QUE CUADREN LOS TOTALES CUANDO VIENE CON DESCUENTOS
'TxtSubTotal.Text = (dr("SubTotal").ToString.ToDouble + dr("Descuentos").ToString.ToDouble).FormatoNumero(2)
TxtSubTotal.Text = (dr("SubTotal").ToString.ToDouble).FormatoNumero
'TxtSubTotal2.Text = (dr("SubTotal").ToString.ToDouble).FormatoNumero
TxtSubTotal2.Text = (dr("SubTotal").ToString.ToDouble - dr("Descuentos").ToString.ToDouble).FormatoNumero(2)
TxtDescuento.Text = dr("Descuentos").ToString.FormatoNumero(2)
LblAmortizacion.Text = dr("Amortizacion").ToString.FormatoNumero(2)
TxtIVA.Text = dr("IVA").ToString.FormatoNumero(2)
TxtRetIVA.Text = dr("RetIVA").ToString.FormatoNumero(2)
TxtRetISR.Text = dr("RetISR").ToString.FormatoNumero(2)
TxtIEPS.Text = dr("IEPS").ToString.FormatoNumero(2)
If dr("IEPS").ToString.ToDouble > 0 Then TrIEPS.Visible = True
If dr("RetIVA").ToString.ToDouble > 0 Then TrRetIVA.Visible = True
If dr("RetISR").ToString.ToDouble > 0 Then TrRetISR.Visible = True
If Math.Abs(dr("Redondeo").ToString.ToDouble) > 0 Then TrRedondeo.Visible = True
TxtRedondeo.Text = dr("Redondeo").ToString.FormatoNumero(2)
TxtOtrosImpuestos.Text = dr("OtrosImpuestos").ToString.FormatoNumero(2)
If dr("OtrosImpuestos").ToString.ToDouble > 0 Then TrOtrosImpuestos.Visible = True
TxtTotal.Text = dr("Total").ToString.FormatoNumero(2)
HfTotalCompra.Value = TxtTotal.Text
CompraSaldo = TxtTotal.Text.ToDouble
TipoCambio = dr("TipoCambio").ToString.ToDecimal
Dim TipoCambioOriginal = dr("TipoCambioOriginal").ToString.ToDouble
If TipoCambio > 1 Then LblTC.Text = String.Format("TC: {0}", TipoCambio.ToString("N4"))
If TipoCambio <> TipoCambioOriginal Then LblTCO.Text = String.Format("<br/>TC Original: {0}", TipoCambioOriginal.ToString("N4"))
AsignaValoresOriginales(TxtSubTotal.Text.ToDouble, TxtSubTotal2.Text.ToDouble, TxtIVA.Text.ToDouble, TxtRetIVA.Text.ToDouble, TxtRetISR.Text.ToDouble, TxtTotal.Text.ToDouble)
CalculaTotalPorDevengar()
TxtDocumentoImporteFE.Text = dr("Total").ToString
RVDocumentoImporte.MaximumValue = dr("Total").ToString.FormatoNumero(2)
RVDocumentoImporteFE.MaximumValue = RVDocumentoImporte.MaximumValue
RVDocumentoImporteCaja.MaximumValue = RVDocumentoImporte.MaximumValue
HFDiferenciaCompra.Value = TxtTotal.Text
TotalGeneral = dr("Total").ToString.ToDouble
CveMoneda = dr("CveMoneda").ToString.ToEntero
DdlValidadaSAT.SelectedValue = "Si"
TxtObsFact.Text = dr("Observaciones").ToString
LblUsuarioCaptura.Text = dr("Usuario").ToString
LitFechCaptura.Text = dr("FechaIng").ToString.ToDate.ToShortDateString
LitFechCaptura.ToolTip = dr("FechaIng").ToString
LblRetIVA.Text = Math.Round((dr("RetIVA").ToString.ToDouble / TxtSubTotal2.Text.ToDouble) * 100, 4).FormatoNumero(3) + "%"
LblRetISR.Text = Math.Round((dr("RetISR").ToString.ToDouble / TxtSubTotal2.Text.ToDouble) * 100, 4).FormatoNumero(3)
If dr("TipoFactura").ToString <> "CFDi" Then LblTipoFact.Text = dr("TipoFactura").ToString : divTipoFactura.Visible = True
ViewState("CveFactura") = dr("CveFactura").ToString.ToEntero
ViewState("IdPoliza") = dr("IdPoliza").ToString.ToEntero
DdlMoneda.SelectedValue = dr("CveMoneda").ToString
'primero se asigna la moneda, para que dentro del proveedor carge los anticipos solo de esa moneda
DdlProveedor.Visible = False
HplProveedor.Visible = True
CargaProveedor(CveProveedor, "-1")
DdlRetIVAConcepto.SelectedValueExist(dr("CveRetIVAConcepto").ToString)
DdlRetISRConcepto.SelectedValueExist(dr("CveRetISRConcepto").ToString)
CveRetIVAConceptoOriginal = If(dr("CveRetIVAConcepto").ToString.ToEntero > 0, dr("CveRetIVAConcepto").ToString.ToEntero, -1)
CveRetISRConceptoOriginal = If(dr("CveRetISRConcepto").ToString.ToEntero > 0, dr("CveRetISRConcepto").ToString.ToEntero, -1)
If dr("CveTipoConcepto").ToString.ToEntero = 1 Then LblProveedor.Text = "Proveedor:" Else LblProveedor.Text = "Acreedor:"
HdnCveEstatusFactura.Value = dr("CveEstatusFactura").ToString
LblCompraEstatus.Text = dr("EstatusFactura").ToString
If dr("CveEstatusFactura").ToString = "2" Then ChkProgramarPago.Checked = True
TrRembolsoUpdate.Visible = True
TrRembolsoNumero.Visible = True
Dim DtPersonal = GlobalDTRHPersonal(UsuarioActual.CveEmpresa).FiltraParametros("", "NombreCompleto")
DdlRembolsoPersonal.DataSource = DtPersonal
DdlRembolsoPersonal.Items.Insert(0, New ListItem("Sin Seleccionar", "-1"))
DdlRembolsoPersonal.DataBind()
If dr("CvePersonal").ToString.ToEntero > 0 Then
DdlRembolsoPersonal.SelectedValueExist(dr("CvePersonal").ToString)
TxtRembolsoNumero.Text = dr("NumeroReembolso").ToString
RblRembolso.SelectedValuesIfExist("1")
TrRembolsoPersonal.Visible = True
End If
Dim DtCajaChica As DataTable = GlobalDTBancosCuentas(UsuarioActual.CveUsuario, CveEmpresa:=UsuarioActual.CveEmpresa)
DtCajaChica = DtCajaChica.FiltraParametros(String.Format("CveTipoCuenta = 1"))
DdlRembolsoCajaChica.DataSource = DtCajaChica
DdlRembolsoCajaChica.Items.Insert(0, New ListItem("Sin Seleccionar", "-1"))
DdlRembolsoCajaChica.DataBind()
If dr("CveCajaChica").ToString.ToEntero > 0 Then
DdlRembolsoCajaChica.SelectedValueExist(dr("CveCajaChica").ToString)
TxtRembolsoNumero.Text = dr("NumeroReembolso").ToString
RblRembolso.SelectedValuesIfExist("2")
TrRembolsoCajaChica.Visible = True
End If
If dr("CvePersonal").ToString.ToEntero > 0 Or dr("CveCajaChica").ToString.ToEntero > 0 Then
NumeroReembolsoOriginal = dr("NumeroReembolso").ToString
End If
VisualizaEstatusCompraSaldo(dr("TipoDocto").ToString, dr("Saldo").ToString.ToDecimal, dr("Total").ToString.ToDecimal)
If dr("IdPoliza").ToString.ToEntero > 0 Then
HplCompraContabilizada.Text = "Si"
HplCompraContabilizada.NavigateUrl = String.Format("/Contabilidad/RegPoliza.aspx?IdPoliza={0}", dr("IdPoliza"))
LblCompraEstatus.ForeColor = Drawing.Color.Navy
trContabilizada.Visible = True
If UsuarioActual.TienePermisoProceso(107) Then BtnDescontabilizar.Visible = True
Else
BtnDescontabilizar.Visible = False
HplCompraContabilizada.Text = "No"
trContabilizada.Visible = True
If UsuarioActual.Empresa.UsaAC Then
LBContabilizarAC.Visible = True
End If
End If
UPPDescontablizar.Update()
TxtFechaPago.Text = dr("FechaVencimiento").ToString.ToDate.ToShortDateString
RowBitacora.Visible = True
CargaEventoBitacora()
'ImgAddObs.Attributes.Add("onclick", "javascript: PosicionaObjeto(this.id,'DivEventoBitacora',null,-250,-250); $('#DivEventoBitacora').show(1000); ")
ImgAddObs.Visible = True
ChkAplicaNotaCredito.Checked = CBool(dr("AplicaNotaCredito").ToString)
'RBLPago.Enabled = False
'If dr("CveIE").ToString.ToEntero > 0 Then
' RBLPago.SelectedValue = "2"
' 'cargo los datos del pago
' 'PnlPago.Visible = True
' 'PnlChkFuncionariosEmpleados.Visible = True
' Dim ObjIE As New ClsBancos()
' If ObjIE.GetBancosIE(dr("CveIE").ToString.ToEntero, UsuarioActual.CveEmpresa) Then
' If ObjIE.DtResultados.Rows.Count > 0 Then
' DdlTipoTransaccion.SelectedValue = ObjIE.CveTipoTransaccion.ToString
' DdlCuenta.SelectedValue = ObjIE.CveCuenta.ToString
' TxtDocumentoFolio.Text = ObjIE.Folio
' TxtDocumentoImporte.Text = ObjIE.Importe.FormatoNumero
' TxtDocumentoObservaciones.Text = ObjIE.Observaciones
' End If
' End If
' ObjIE.Dispose()
'End If
CompraSaldo = TotalGeneral - LblAmortizacion.Text.ToDouble
If EmpresaPrueba Then
CompraSaldo = dr("Saldo").ToString.ToDouble
End If
If CompraSaldo > dr("Saldo").ToString.ToDouble Then
CompraSaldo = dr("Saldo").ToString.ToDouble
End If
HdnCompraSaldo.Value = CompraSaldo.ToString
If CompraSaldo > 0 And UsuarioActual.TienePermisoProceso(100) Then
HLPagar.Visible = True
HLPagar.NavigateUrl = $"/Bancos/PopIECompras.aspx?CveCompra={CveCompra}&TB_iframe=true&height=520&width=700"
End If
If dr("CveFactura").ToString.ToEntero > 0 Then
ImgDownXML.Visible = True : ImgDownXML.NavigateUrl = String.Format("/Compras/PopUpVerFactura.aspx?P={0}", Encripta(String.Format("OP=Fact&EXT=xml&CveFactura={0}&RFC={1}", dr("CveFactura"), dr("RFC").ToString.Replace("&", "%26%"))))
ImgDownPDF.Visible = True : ImgDownPDF.NavigateUrl = String.Format("/Compras/PopUpVerFactura.aspx?P={0}", Encripta(String.Format("OP=Fact&EXT=pdf&CveFactura={0}&RFC={1}", dr("CveFactura"), dr("RFC").ToString.Replace("&", "%26%"))))
End If
TxtRembolsoNumero.Enabled = If(IdPoliza > 0, False, True)
'CargaDetalle
If ObjCompra.GetCompraDetalle(CveCompra) Then
TmpDT = ObjCompra.DtResultados
TmpDTOriginal = ObjCompra.DtResultados.Copy
TmpDT.Columns.Add("CveClasificacionActualizar", GetType(Integer))
'TmpDT.Columns.Add("CveEq", GetType(Integer))
TmpDT.Columns.Add("CveAlmacen", GetType(Integer))
'TmpDT.Columns.Add("CvePersonal", GetType(Integer))
TmpDT.Columns.Add("IdCuentaComprometido", GetType(Integer))
TmpDT.Columns.Add("IdCuentaPorEjercer", GetType(Integer))
TmpDT.Columns.Add("IdCuentaDevengado", GetType(Integer))
TmpDT.Columns.Add("IdCuentaMatriz", GetType(Integer))
TmpDT.Columns.Add("PSDescripcion", GetType(String))
TmpDT.Columns.Add("ProductoOC", GetType(String))
TmpDT.Columns.Add("CantidadF", GetType(Double))
'Consignaciones
TmpDT.Columns.Add("CveAlmacenConsignacion", GetType(Integer))
TmpDT.Columns.Add("NoConsignacion", GetType(Integer))
TmpDT.Columns.Add("CveConsignacion", GetType(Integer))
TmpDT.Columns.Add("HdnPS", GetType(String))
TmpDT.Columns.Add("HdnCvePS", GetType(String))
TmpDT.Columns.Add("HdnClasificacion", GetType(String))
TmpDT.Columns.Add("HdnCveClasificacion", GetType(String))
TmpDT.Columns.Add("HdnCveAlmacen", GetType(String))
'INVENTARIO SERIE/LOTE
TmpDT.Columns.Add("CveMetodoInventario", GetType(Integer))
'Fletes y Servicios
'TmpDT.Columns.Add("AplicaCostoIndirecto", GetType(Integer)) 'Ya traemos el estatus flete
TmpDT.Columns.Add("CostoIndirectoAlmacen", GetType(Decimal))
TmpDT.Columns.Add("EntregaDirecta", GetType(Integer))
TmpDT.Columns.Add("CveContrato", GetType(Integer))
TmpDT.Columns.Add("DifPSSat", GetType(Integer))
If Not TmpDT.Columns.Contains("CveContratoDetalle") Then
TmpDT.Columns.Add("CveContratoDetalle", GetType(Integer))
End If
If Not TmpDT.Columns.Contains("CveCultivoCuadroDetalle") Then
TmpDT.Columns.Add("CveCultivoCuadroDetalle", GetType(Integer))
End If
If Not TmpDT.Columns.Contains("CveSATPSActualizado") Then
TmpDT.Columns.Add("CveSATPSActualizado", GetType(Integer))
End If
If Not TmpDT.Columns.Contains("ImporteSinImpuestos") Then
TmpDT.Columns.Add("ImporteSinImpuestos", GetType(Decimal))
End If
GvPS.DataSource = TmpDT
GvPS.DataBind()
If UsuarioActual.Empresa.UsaAC Then
CargaHidendsAC()
End If
CalculaTotales(True)
If UsuarioActual.Empresa.UsaInventarios Then
DtInv = TmpDT.FiltraParametros(String.Format("CveTipoPS = 2")).Copy
If dr("Inventario").ToString = "1" Then
CveMovimientoAlmacen = dr("CveMovimiento").ToString.ToEntero
Dim Inv As New ClsInventarios
If Inv.GetMovimientosDetalle(dr("CveMovimiento").ToString.ToEntero, UsuarioActual.CveEmpresa) Then
'Dim TempParametros = Encripta(String.Format("OP=Alm&CveMovimiento={0}", dr("CveMovimiento")))
'ImgImprimirAlmacen.NavigateUrl = String.Format("/Compras/PopUpVerFactura.aspx?P={0}", TempParametros)
ImgImprimirAlmacen.Visible = True
ImgImprimirAlmacen.NavigateUrl = String.Format("/Inventarios/EntradasSalidas.aspx?CveMovimiento={0}", dr("CveMovimiento"))
Dim drt As DataRow
'actualizo el almacen
For Each dri As DataRow In DtInv.Rows
drt = Inv.DtResultados.FiltroPrimero(String.Format("CvePS = {0} AND Cantidad = {1}", dri("CvePS"), dri("Cantidad")))
If drt IsNot Nothing Then
Dim TmpDr As DataRow = TmpDT.Select($"Consec = {dri("Consec").ToString.ToEntero}")(0) 'Charlie
TmpDr("CveAlmacen") = drt("CveAlmacen") 'Charlie
dri("CveAlmacen") = drt("CveAlmacen")
End If
Next
End If
'Proceso Super Tramposo de Charlie
If Inv.GetMovimientosDetalle(dr("CveMovimiento").ToString.ToEntero, UsuarioActual.CveEmpresa, CveCompra:=-123) Then
Dim drt As DataRow
For Each dri As DataRow In DtInv.Rows
drt = Inv.DtResultados.FiltroPrimero(String.Format("CvePS = {0} AND Cantidad = {1}", dri("CvePS"), dri("Cantidad")))
If drt IsNot Nothing Then
Dim TmpDr As DataRow = TmpDT.Select($"Consec = {dri("Consec").ToString.ToEntero}")(0)
TmpDr("CveAlmacen") = drt("CveAlmacen")
End If
Next
End If
Inv.Dispose()
End If
CargaGvInv()
'Ocultamos "Recibir Aqui"
GvInv.Columns(6).Visible = False
GvInv.Columns(7).Visible = False
End If
End If
DdlTipoComprobante.Enabled = False
DdlTipoComprobante.SelectedValue = dr("TipoDocto").ToString
If dr("TipoDocto").ToString.Contiene("Fac", "Ant") Then
ChkAplicaNotaCredito.Enabled = True
ImgAnticiposPendientes.Visible = True
Else
ImgAnticiposPendientes.Visible = False
ChkAplicaNotaCredito.Enabled = False
End If
HlProveedor.HRef = ""
TxtCodigo.ReadOnly = True
'IPP Usuario Sistema No Bloquea, se cambió al proceso
If UsuarioActual.TienePermisoProceso(79) Then
TxtCantidad.Enabled = True
TxtPrecio.Enabled = True
Else
TxtCantidad.Enabled = False
TxtPrecio.Enabled = False
End If
DdlPS.Enabled = False
TxtObsPS.Enabled = False
'ImgAmort.Attributes.Clear()
LbAgregar.Enabled = False
TxtSerie.Enabled = False
TxtFolio.Enabled = False
TxtFecha.Enabled = False
ImgFecha.Enabled = False
CEFecha.Enabled = False
If UsuarioActual.TienePermisoProceso(342) Then
TxtFecha.Enabled = True
ImgFecha.Enabled = True
CEFecha.Enabled = True
LnkActualziarFechadecompra.Visible = True
End If
DdlProveedor.Enabled = False
DdlProveedorSucursal.Enabled = False
DdlEstatus.Enabled = False
DdlMoneda.Enabled = False
DdlRetIVAConcepto.Enabled = False
DdlRetISRConcepto.Enabled = False
If UsuarioActual.TienePermisoProceso(79) Then
BtnActualizar.Visible = True
DdlProveedorSucursal.Enabled = True
DdlPS.Enabled = True
TxtObsPS.Enabled = True
LbAgregar.Enabled = True
LnkUpdateFechaPago.Visible = True
If DdlRetIVAConcepto.SelectedValue.ToEntero > 0 Then
DdlRetIVAConcepto.Enabled = True
End If
If DdlRetISRConcepto.SelectedValue.ToEntero > 0 Then
DdlRetISRConcepto.Enabled = True
End If
End If
BtnGuardar.Visible = False
BtnGuardar.Enabled = False
UpPSS.Update()
'GvLeyendasFiscales.Enabled = False
TxtSubTotal.ReadOnly = True
TxtIVA.ReadOnly = True
TxtRetIVA.ReadOnly = True
TxtRetISR.ReadOnly = True
TxtIEPS.ReadOnly = True
TxtOtrosImpuestos.ReadOnly = True
TxtTotal.ReadOnly = True
'CargaLeyendasFiscales
ViewState("CompraFolio") = TxtFolio.Text.Trim
Dim dtnc As DataTable = Nothing
If dr("TipoDocto").ToString = "Fac" Then
'carga as notas de credito vinculadas
If ObjCompra.GetComprasNotasCredito(CveCompra, -1) Then
dtnc = ObjCompra.DtResultados
End If
ElseIf dr("TipoDocto").ToString.Contiene("NC", "DEV", "Ant") Then
If dr("TipoDocto").ToString = "NC" Then
DivReembolso.Visible = False
RBLPago.Items(2).Enabled = False
End If
If ObjCompra.GetComprasNotasCredito(-1, CveCompra) Then
dtnc = ObjCompra.DtResultados
GvAnticiposSel.Caption = "<table width='100%'><tr><td style='text-align:center'>Compras Aplicadas</td></tr></table>"
End If
End If
'VINCULACIÓN OC - NUEVA DICIEMBRE 2015
If dr("OCVinculada").ToString() <> "" Then
Dim DtOCs As New DataTable
Dim OCS = "", CveOCS = ""
DtOCs.Columns.Add("FolioOC", GetType(Integer))
DtOCs.Columns.Add("CveOrdenCompra", GetType(Integer))
For Each drt As DataRow In TmpDT.Rows
If drt("FolioOC").ToString <> "" Then
Dim DrOC = DtOCs.NewRow
DrOC("FolioOC") = drt("FolioOC").ToString
DrOC("CveOrdenCompra") = drt("CveOrdenCompra").ToString
DtOCs.Rows.Add(DrOC)
End If
Next
DtOCs = DtOCs.FiltraParametros("", "", {"FolioOC", "CveOrdenCompra"})
DtOCs.Columns.Add("Fecha", GetType(Date))
DtOCs.Columns.Add("Descripcion", GetType(String))
If DtOCs.Rows.Count > 0 Then
For Each drt As DataRow In DtOCs.Rows
If ObjOC.GetOrdenesCompraRep("OC", -1, -1, -1, -1, MinFecha, MaxFecha, drt("CveOrdenCompra").ToString.ToEntero, CveProveedor, -1, -1, -1, UsuarioActual.CveEmpresa, -1) Then
If ObjOC.DtResultados.Rows.Count = 1 Then
OCS += If(OCS <> "", String.Format(",{0}", drt("FolioOC").ToString), drt("FolioOC").ToString)
CveOCS += If(CveOCS <> "", String.Format(",{0}", drt("CveOrdenCompra").ToString), drt("CveOrdenCompra").ToString)
drt("Fecha") = ObjOC.DtResultados.FiltroPrimeroValor("FechaIng")
drt("Descripcion") = ObjOC.DtResultados.FiltroPrimeroValor("Descripcion")
End If
End If
Next
End If
TxtOC.Text = OCS
TieneOC = True
If DtOCs.Rows.Count > 1 Then
HLOCsVinculadas.Visible = True
GvOCsVinculadas.DataSource = DtOCs
GvOCsVinculadas.DataBind()
UpOCsVinculadas.Update()
ElseIf DtOCs.Rows.Count = 1 Then
HLOCsVinculadas.Visible = True
HLOCsVinculadas.Attributes.Remove("data-toggle")
HLOCsVinculadas.Attributes.Remove("data-target")
HLOCsVinculadas.Attributes.Add("data-toggle", "tooltip")
HLOCsVinculadas.NavigateUrl = $"/OC/OC.aspx?OC={DtOCs.FiltroPrimeroValor("CveOrdenCompra")}"
HLOCsVinculadas.Target = "_blank"
End If
End If
'BLOQUEA OC
TxtOC.Enabled = False
ImgBtnBuscarOC.Visible = False
Tab.ActiveTabIndex = 0
GvAnticiposSel.DataSource = dtnc
GvAnticiposSel.DataBind()
'' VALIDA ELIMINAR COMPRA, QUE NO TENGA PAGOS CONCILIADOS
If (UsuarioActual.TienePermisoProceso(77) OrElse UsuarioActual.TienePermisoProceso(135)) AndAlso dr("NumPagosConciliados").ToString.ToEntero = 0 Then ' Eliminar compra
'SIN VINCULACIÓN
If UsuarioActual.TienePermisoProceso(135) Then
If TxtOC.Text = "" AndAlso IdPoliza < 1 AndAlso CveMovimientoAlmacen < 1 AndAlso LblUsuarioCaptura.Text = UsuarioActual.Usuario AndAlso TmpDT.MAX("CveActivoFijo").ToEntero < 1 AndAlso Not ChkProgramarPago.Checked AndAlso CompraSaldo = TxtTotal.Text.ToDouble Then
BtnEliminarCompra.Visible = True
End If
End If
'ELIMINAR A FUERZAS
If UsuarioActual.TienePermisoProceso(77) Then
If Not (IdPoliza > 0) Then
BtnEliminarCompra.Visible = True
End If
End If
Dim StrInventario As String = ""
If dr("Inventario").ToString = "1" Then
StrInventario = "los <b>Movimientos de Inventario</b> relacionados"
End If
If UsuarioActual.Empresa.UsaAC Then
BtnEliminarCompra.Attributes.Add("data-original-title", String.Format("¿Está seguro que desea eliminar la Compra, {0} y la <b>Poliza Asociada</b>?", StrInventario))
Else
BtnEliminarCompra.Attributes.Add("data-original-title", String.Format("¿Está seguro que desea eliminar la Compra y {0}?", StrInventario))
End If
End If
'VALIDA CANCELAR COMPRA - AC
ValidaCancelarCompra()
'CUANDO ESTA CANCELADA
If dr("CveEstatusFactura").ToString = "-2" Then
BtnEliminarCompra.Visible = False
BtnActualizar.Visible = False
BtnGuardar.Visible = False
BtnCancelarCompra.Visible = False
LblCompraEstatus.Text = "CANCELADA"
LblCompraEstatus.Font.Bold = True
LblCompraEstatus.Font.Size = 12
LblCompraEstatus.ForeColor = Drawing.Color.DarkRed
'HplIr.Visible = False
BtnDescontabilizar.Visible = False
BtnEliminarPolizaMultiple.Visible = False
'LIGA POLIZA CANCELACIÓN
'HplPolizaCancelación.NavigateUrl = String.Format("/Contabilidad/RegPoliza.aspx?IdPoliza={0}", dr("IdPoliza"))
End If
'CUANDO FUE REFACTURADA
If dr("CompraRefacturada").ToString.ToEntero > 0 Then
BtnEliminarCompra.Visible = False
BtnActualizar.Visible = False
BtnGuardar.Visible = False
BtnCancelarCompra.Visible = False
End If
'TIENE AMORTIZACIÓN
If GvAnticiposSel.Rows.Count > 0 Then
If Not DdlTipoComprobante.SelectedValue.Contiene("NC", "DEV") Then
BtnCancelarCompra.Visible = False
BtnEliminarCompra.Visible = False
End If
End If
'Tiene Importacion
If UsuarioActual.Empresa.Funcionalidad(558) = "1" Then
If dr("EsImportacion").ToString = "True" Then
chkImportacion.Checked = True
Else
chkImportacion.Checked = False
End If
End If
CargaComplementosPago()
Else
Alert("La compra solicitada no se encontró. Por favor rectifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia)
End If
Else
Alert("Ocurrió un error al cargar la compra. Por favor vuelta a intentar o comuniquese con Sistemas.", TipoMensaje.MsgError)
End If
ObjCompra.Dispose()
ObjOC.Dispose()
End Sub
Private Sub VisualizaEstatusCompraSaldo(TipoDocto As String, Saldo As Decimal, Total As Decimal)
If TipoDocto.Contiene("Fac", "Ant") Then
If HdnCveEstatusFactura.Value.ToEntero = 6 Then
LblCompraEstatus.Text = "Vinculada a Crédito"
LblCompraEstatus.Font.Bold = True
LblCompraEstatus.Font.Size = 12
LblCompraEstatus.ForeColor = Drawing.Color.Navy
BtnAceptarAnticipos.Visible = False
trImporte.Visible = False
HplImporte.Visible = False
HplImporte.Text = ""
HplImporte.NavigateUrl = ""
Else
If Saldo <= 0 Then
LblCompraEstatus.Text = "PAGADA"
LblCompraEstatus.Font.Bold = True
LblCompraEstatus.Font.Size = 12
LblCompraEstatus.ForeColor = Drawing.Color.Navy
BtnAceptarAnticipos.Visible = False
trImporte.Visible = True
HplImporte.Visible = True
HplImporte.Text = String.Format("$ {0}", Total.FormatoNumero())
HplImporte.NavigateUrl = String.Format("/Contabilidad/PopUpAuxiliar.aspx?Tipo=CxPProveedor&CveProveedor={0}&CveCompra={1}&TB_iframe=true&height=700&width=920", CveProveedor, CveCompra)
Else
If Saldo < Total Then
LblCompraEstatus.Text = "ABONADA"
LblCompraEstatus.Font.Bold = True
End If
LblCompraEstatus.ForeColor = Drawing.Color.Navy
trSaldo.Visible = True
HplSaldoAuxiliar.Text = String.Format("$ {0}", Saldo.FormatoNumero())
HplSaldoAuxiliar.NavigateUrl = String.Format("/Contabilidad/PopUpAuxiliar.aspx?Tipo=CxPProveedor&CveProveedor={0}&CveCompra={1}&TB_iframe=true&height=700&width=920", CveProveedor, CveCompra)
End If
End If
UpEstatus.Update()
Else
If CveCompra > 0 Then
LblCompraEstatus.Font.Bold = True
LblCompraEstatus.ForeColor = Drawing.Color.Navy
trSaldo.Visible = True
HplSaldoAuxiliar.Text = String.Format("$ {0}", Saldo.FormatoNumero())
HplSaldoAuxiliar.NavigateUrl = String.Format("/Contabilidad/PopUpAuxiliar.aspx?Tipo=CxPProveedor&CveProveedor={0}&CveCompra={1}&TB_iframe=true&height=700&width=920", CveProveedor, CveCompra)
End If
End If
End Sub
Private Sub CargaMonedas()
DdlMoneda.DataSource = GlobalDTMonedas
DdlMoneda.DataBind()
End Sub
Private Sub CargarAlmacen()
'ddlAlmacen.DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1).FiltraParametros("CveTipoAlmacen IN (1,2)") 'solo muestra tipo material y herramientas
'ddlAlmacen.DataBind()
Dim DtAlmacenes = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1).FiltraParametros("CveTipoAlmacen IN (1,2,7,14,19)")
If DdlTipoCompra.SelectedValue = "10" Then
ddlAlmacenAdd.DataSource = DtAlmacenes.FiltraParametros("Modalidad = 0")
DdlAlmacenDevolucion.DataSource = DtAlmacenes.FiltraParametros("Modalidad = 0")
Else
ddlAlmacenAdd.DataSource = DtAlmacenes
DdlAlmacenDevolucion.DataSource = DtAlmacenes
End If
ddlAlmacenAdd.DataBind()
DdlAlmacenDevolucion.DataBind()
DdlAlmacenDevolucion.Items.Insert(0, New ListItem("Seleccione", "-1"))
End Sub
Protected Sub CargaFuncionariosEmpleados()
'Cargar los FUncionarios Empleados que tengan saldo
Dim objGastosXComprobar As New ClsMovimientos
Dim dtFE As New DataTable
If objGastosXComprobar.GetEgresosSinComprobarPersonal(UsuarioActual.CveEmpresa) Then
'TRATAR DE HACERLO CON c
dtFE.Columns.Add("CvePersonal", GetType(Integer))
dtFE.Columns.Add("NombreCompleto", GetType(String))
dtFE.Columns.Add("Saldo", GetType(Double))
'dtFE.Columns.Add("CveIE", GetType(Integer))
DtFuncionarios = objGastosXComprobar.DtResultados.FiltraParametros("CvePersonal > 0 ") 'objGastosXComprobar.DtResultados.FiltraParametros("CvePersonal > 0 AND Saldo > 0 ") ' saco los egresos sin comprobar de funcionarios y empleados
For Each Row As DataRow In objGastosXComprobar.DtResultados.FiltraParametros("CvePersonal > 0 ", "NombreCompleto").Rows ' saco los totalizadores
Dim RowFE As DataRow = Nothing
RowFE = dtFE.NewRow()
RowFE("CvePersonal") = Row("CvePersonal").ToString.ToEntero
RowFE("NombreCompleto") = String.Format("{0} - ${1}", Row("NombreCompleto").ToString.Trim, Row("Saldo").ToString.FormatoNumero(2))
RowFE("Saldo") = Row("Saldo").ToString.ToDouble
dtFE.Rows.Add(RowFE)
Next
' DtFuncionarios = dtFE
'For Each Row As DataRow In objGastosXComprobar.DtResultados.FiltraParametros("CvePersonal > 0 AND FechaDocumento IS NOT NULL").Rows
' ArrIE.Add(New Anticipos With {.CveIE = Row("CveIE").ToString.ToEntero, .Importe = Row("Saldo").ToString.ToDouble, .CvePersonal = Row("CvePersonal").ToString.ToEntero})
'Next
End If
objGastosXComprobar.Dispose()
DdlFuncionarioEmpleado.DataSource = dtFE.FiltraParametros("", "NombreCompleto")
DdlFuncionarioEmpleado.DataBind()
DdlFuncionarioEmpleado.Items.Insert(0, New ListItem("Seleccione Funcionario Empleado", "-1"))
'UPCondicionesPago.Update()
UpContado.Update()
End Sub
Protected Sub CargaDeudores()
'Cargar los FUncionarios Empleados que tengan saldo
Dim Deudores As New ClsMovimientos
If RBLTipoDeudor.SelectedValue.ToEntero = 1 Then
If Deudores.GetDeudoresSaldos(-1, UsuarioActual.CveEmpresa) Then
DtDeudores = Deudores.DtResultados.FiltraParametros("CveProveedor > 0")
DdlDeudor.DataSource = DtDeudores
DdlDeudor.DataBind()
DdlDeudor.Items.Insert(0, New ListItem("Seleccione Deudor", "-1"))
UpContado.Update()
End If
Else
If Deudores.GetDeudoresComisionesSaldos(UsuarioActual.CveEmpresa) Then
DtDeudores = Deudores.DtResultados.FiltraParametros("CveProveedor > 0")
DdlDeudor.DataSource = DtDeudores
DdlDeudor.DataBind()
DdlDeudor.Items.Insert(0, New ListItem("Seleccione Deudor", "-1"))
UpContado.Update()
End If
End If
Deudores.Dispose()
End Sub
Private Sub CreaTmpAcarreos()
tDTAcarreos = New DataTable
tDTAcarreos.Columns.Add("CvePreEstimacion", GetType(Integer))
tDTAcarreos.Columns.Add("Importe", GetType(Double))
End Sub
Protected Sub CargaAcreedores()
Dim ObjMov As New ClsMovimientos
If ObjMov.GetAcreedoresSaldos(-1, UsuarioActual.CveEmpresa) Then
DtAcreedores = ObjMov.DtResultados.FiltraParametros("CveProveedor > 0")
DdlAcreedor.DataSource = DtAcreedores
DdlAcreedor.DataBind()
DdlAcreedor.Items.Insert(0, New ListItem("Seleccione Acreedor", "-1"))
UpContado.Update()
End If
ObjMov.Dispose()
End Sub
Private Sub CargaCreditos()
Dim Cred As New ClsBancos
Dim Dt As DataTable = Nothing
Dim DtD As DataTable = Nothing
If Cred.GetCreditos(-1, -1, -1, -1, -1, UsuarioActual.CveEmpresa) Then
Dt = Cred.DtResultados.FiltraParametros("CveCredito > 0 AND CveTipoCredito IN (4,5)")
If Dt.Rows.Count > 0 AndAlso Cred.GetCreditosDetalle(Dt.Rows(0)("CveCredito").ToString.ToEntero, -1) Then
DtD = Cred.DtResultados.FiltraParametros("Estatus = 2 AND CveIE IS NOT NULL")
End If
End If
Cred.Dispose()
If DdlTipoCredito.SelectedValue.ToEntero = 1 Then
Dt = Dt.FiltraParametros("CveCompraFactura IS NULL")
End If
DdlCredito.DataSource = Dt.FiltraParametros("", DistinctColumns:={"CveCredito", "ReferenciaImporte"})
DdlCredito.DataBind()
DdlCredito.Items.Insert(0, New ListItem("Seleccione", "-1"))
DdlCreditoDetalle.DataSource = DtD
DdlCreditoDetalle.DataBind()
DdlCreditoDetalle.Items.Insert(0, New ListItem("Seleccione", "-1"))
End Sub
Private Sub CargaCreditosDetalle(CveCredito As Integer)
Dim Cred As New ClsBancos
Dim DtD As DataTable = Nothing
If Cred.GetCreditosDetalle(CveCredito, -1) Then
DtD = Cred.DtResultados.FiltraParametros("Estatus = 2")
End If
Cred.Dispose()
DdlCreditoDetalle.DataSource = DtD
DdlCreditoDetalle.DataBind()
DdlCreditoDetalle.Items.Insert(0, New ListItem("Seleccione", "-1"))
End Sub
Private Sub CargaProveedor(CveProveedor As Integer, RFC As String, Optional RecargaCombo As Boolean = True)
Dim ObjProveedor As New ClsCompProveedores()
If ObjProveedor.GetProveedores(ClsCompProveedores.TipoConsulta.ParaUsoEnEmpresa, CveProveedor, "-1", "-1", "-1", "-1", RFC, "-1", "-1", -1, UsuarioActual.CveEmpresa) Then
If ObjProveedor.DtResultados.Rows.Count > 0 Then
If RecargaCombo Then DdlProveedor.DataSource = ObjProveedor.DtResultados : DdlProveedor.DataBind()
ChkConsignacion.Enabled = True
'MONEDA PREFERENTE
If CveCompra <= 0 Then
If CveFactura <= 0 Then
DdlMoneda.SelectedValueExist(ObjProveedor.CveMonedaPreferente)
End If
CambiaMoneda(False)
End If
ViewState("CveProveedor") = ObjProveedor.CveProveedor
ViewState("CveTipoProveedor") = ObjProveedor.CveTipoProveedor
If ObjProveedor.CveTipoProveedor = 1 Then LblProveedor.Text = "Proveedor:" Else LblProveedor.Text = "Acreedor:"
CveTipoConcepto = ObjProveedor.CveTipoProveedor
'Conta ContPAQ
ViewState("CtaProveedor") = ObjProveedor.IdCtaContProveedores
ViewState("CtaProveedorAnticipos") = ObjProveedor.IdCtaContAnticipos
ViewState("CtaProveedorAnticiposExtranjera") = ObjProveedor.IdCtaContAnticiposExtranjera
ViewState("CtaProveedorAnticiposComplementaria") = ObjProveedor.IdCtaContAnticiposComplementaria
ViewState("CtaProveedorDeudores") = ObjProveedor.IdCtaContDeudor
ViewState("CtaProveedorAcreedores") = ObjProveedor.IdCtaContAcreedor
ViewState("CtaProveedorRetISR") = ObjProveedor.IdCtaContRetISR
ViewState("CtaProveedorRetIVA") = ObjProveedor.IdCtaContRetIVA
ViewState("CtaProveedorExtranjera") = ObjProveedor.IdCtaContProveedoresExtranjera
ViewState("CtaProveedorComplementaria") = ObjProveedor.IdCtaContProveedoresComplementaria
ViewState("IdCtaContDocsXPagar") = ObjProveedor.IdCtaContDocsXPagar
ViewState("NombreProveedor") = ObjProveedor.RazonSocial
HdnCveProveedor.Value = ObjProveedor.CveProveedor.ToString
If ObjProveedor.EditarFolioDuplicado Then
TxtFolio.Enabled = True
TxtSerie.Enabled = True
End If
TxtCodigo.Text = ObjProveedor.Codigo
LblRFC.Text = String.Format("<a class=""Texto"" href=""/Compras/Proveedores.aspx?CveProveedor={0}"">{1}</a>", Me.CveProveedor, ObjProveedor.RFC)
HplProveedor.Text = ObjProveedor.NombreComercial : HplProveedor.NavigateUrl = String.Format("/Compras/Proveedores.aspx?CveProveedor={0}", Me.CveProveedor)
DdlProveedor.SelectedValue = ObjProveedor.CveProveedor.ToString
LblDiasCredito.Text = ObjProveedor.PlazoPago.ToString
LblLimiteCredito.Text = ObjProveedor.LimiteCredito.FormatoNumero
LblCreditoDisponible.Text = ObjProveedor.LimiteCredito.FormatoNumero
If Not CveCompra > 0 Then '[IPP] SI YA ESTA REGISTRADA LOS VALORES SE CARGAN EN EL CARGACOMPRA()
'DF 11-04-17
Dim dtprovsuc As DataTable = GlobalDTProveedorSucursales(ObjProveedor.CveProveedor, UsuarioActual.CveEmpresa)
If dtprovsuc IsNot Nothing AndAlso dtprovsuc.Rows.Count > 0 Then
RowProveedorSucursal.Visible = True
DdlProveedorSucursal.Items.Clear()
DdlProveedorSucursal.DataSource = dtprovsuc
DdlProveedorSucursal.DataBind()
DdlProveedorSucursal.Items.Insert(0, New ListItem("Seleccione", "-1"))
DdlProveedorSucursal.Items.Insert(0, New ListItem("Matriz", "0"))
'si tiene una serie cargada, sugiere la sucursal
If TxtSerie.Text.Trim <> "" Then
DdlProveedorSucursal.SelectedValueExist(dtprovsuc.FiltroPrimeroValor("CveProveedorSucursal", $"Serie LIKE '%{TxtSerie.Text.Trim}%'").ToString())
End If
Else
RowProveedorSucursal.Visible = False
DdlProveedorSucursal.Items.Clear()
DdlProveedorSucursal.Items.Insert(0, New ListItem("N/A", "-1"))
DdlProveedorSucursal.DataBind()
End If
End If
If CveCompra <= 0 AndAlso CveFactura <= 0 Then 'si se está cargando una factura o compra no se carga
'LblRetIVA.Text = ObjProveedor.RetIVA.ToString.FormatoNumero(5)
'LblRetISR.Text = ObjProveedor.RetISR.ToString.FormatoNumero(5)
If ObjProveedor.RFC = "XAXX010101000" Then ' RFC Generico
'cuando se esta dando de alta de nueva la compra, se obtiene el folio siguiente de no deducibles
Dim ObjComp As New ClsCompras
TxtFolio.Text = ObjComp.GetSiguienteFolio(ObjProveedor.CveProveedor, TxtSerie.Text).ToString
ObjComp.Dispose()
End If
End If
ViewState("IVA") = ObjProveedor.IVA
HdnProveedorIVA.Value = ObjProveedor.IVA.ToString
ViewState("IdCtaContProveedores") = ObjProveedor.IdCtaContProveedores
ViewState("IdCtaContAnticipos") = ObjProveedor.IdCtaContAnticipos
ViewState("IdCtaProveedorDeudores") = ObjProveedor.IdCtaContDeudor
ViewState("IdCtaProveedorAcreedores") = ObjProveedor.IdCtaContAcreedor
ViewState("IdCtaContRetIVA") = ObjProveedor.IdCtaContRetIVA
ViewState("IdCtaContRetISR") = ObjProveedor.IdCtaContRetISR
If UsuarioActual.Empresa.Funcionalidad(200) = "1" AndAlso ObjProveedor.IdCtaContProveedores < 1 Then
Alert("El Proveedor seleccionado no tiene cuenta contable asignada.", TipoMensaje.MsgAdvertencia)
End If
ViewState("CveProveedor") = ObjProveedor.CveProveedor
HdnCveProveedor.Value = ObjProveedor.CveProveedor.ToString
TxtFechaPago.Text = (TxtFecha.Text.ToDate.AddDays(LblDiasCredito.Text.ToEntero)).ToShortDateString
RFCProv = ObjProveedor.RFC
CargaRetIVAConcepto(True, ObjProveedor.DIOTCveTipoOperacion)
CargaRetISRConcepto(True, ObjProveedor.DIOTCveTipoOperacion)
If CveFactura > 0 Then
If RetIVAOriginal > 0 Then
Dim CalRetIVAPor As Decimal = (RetIVAOriginal * 1 / SubTotal2Original).RoundAD(6).ToDecimal
If (CalRetIVAPor).RoundSQL(6) = 0.106667 OrElse (CalRetIVAPor).RoundSQL(6) = 0.053333 Then
DdlRetIVAConcepto.SelectedValueExist("1") '10.66 servicios profecionales
End If
If (CalRetIVAPor).RoundSQL(2) = 0.04 Then '4 Fletes
If RFCProv.Length = 13 Then
DdlRetIVAConcepto.SelectedValueExist("2")
Else
DdlRetIVAConcepto.SelectedValueExist("3")
End If
End If
End If
If RetISROriginal > 0 Then
Dim CalRetISRPor As Decimal = (RetISROriginal * 1 / SubTotal2Original).RoundAD(5).ToDecimal
If (CalRetISRPor).RoundSQL(1) = 0.1 Then '10 Servicios profesionales
DdlRetISRConcepto.SelectedValueExist("1")
End If
If (CalRetISRPor).RoundSQL(4) = 0.0125 Then '1.25 Recico regimen simplificado confianza
DdlRetISRConcepto.SelectedValueExist("3")
End If
End If
End If
LbAgregar.Enabled = True
UpPSS.Update()
UpPS.Update()
UpParametros.Update()
UPCondicionesPago.Update()
'si tiene el habiltiado el módulo de Contratos
'checo si tiene estimaciones
'CargaDatosEstimaciones(ObjProveedor.CveProveedor)
ImgBtnBuscarOC.OnClientClick = String.Format("AbrirVentana('/OC/PopUpBuscarReq.aspx?V=VOCCOMP&P={0}&T={1}&Masterimpoup=true',1000,600,'S'); return false;", ObjProveedor.CveProveedor, DdlTipoComprobante.SelectedValue)
CargaAnticipos(ObjProveedor.CveProveedor) : UpAnticipos.Update()
If UsuarioActual.Empresa.UsaAC Then
If (TxtRetIVA.Text.ToDouble > 0 And Not ObjProveedor.IdCtaContRetIVA > 0) Or (TxtRetISR.Text.ToDouble > 0 And Not ObjProveedor.IdCtaContRetISR > 0) Then '
ImgBtnBuscarOC.Visible = False
TxtOC.Enabled = False
BtnGuardar.Visible = False
Alert("El proveedor no tiene registrada cuentas contables de retenciones. Debe asignar las cuentas en el registro del proveedor.", TipoMensaje.MsgAdvertencia)
DivRestriccionAdvertencia.Visible = True
LtRestriccionAdvertencia.Text = "El proveedor no tiene registrada cuentas contables de retenciones."
End If
End If
CargaGvAcarreos(ViewState("CveProveedor").ToString.ToEntero)
If CveProveedor > 0 Then
Dim ObjSAT As New ClsSAT
Dim RFCRequest As String = ObjProveedor.RFC
If ObjSAT.GetListado69B(2, UsuarioActual.CveEmpresa, RFCRequest) Then
If ObjSAT.DtResultados.Rows.Count > 0 Then
Dim Estatus As String = ObjSAT.DtResultados.Rows(0)("Situacion").ToString
BtnGuardar.Enabled = False
UpParametros.Update()
Alert($"El RFC del proveedor se encuentra en estado <b>{Estatus}</b> en el Listado EFOS (69B) del SAT", TipoMensaje.MsgAdvertencia)
System.Threading.Thread.Sleep(5)
End If
End If
ObjSAT.Dispose()
End If
Else
Alert("El Proveedor solicitado no existe, por favor intente de nuevo.", TipoMensaje.MsgAdvertencia)
End If
Else
Alert("Ocurrió un error al consultar el proveedor.", TipoMensaje.MsgError)
End If
If UsuarioActual.Empresa.Funcionalidad(560) = "1" Then
If ObjProveedor.GetProveedoresEvaluacionPediente(Me.CveProveedor, UsuarioActual.CveEmpresa) Then
If ObjProveedor.DtResultados.Rows.Count > 0 Then
Me.RequiereEvaluacion = ObjProveedor.DtResultados.Rows(0)("RequiereEvaluacion").ToString() = "1"
Me.CveUsuarioEvaluador = ObjProveedor.DtResultados.Rows(0)("CveUsuarioEvaluador").ToString().ToEntero()
End If
End If
End If
ObjProveedor.Dispose()
End Sub
Private Sub CargaAnticipos(CveProveedor As Integer, Optional FiltroTipo As String = "-1")
Dim ObjMovtos As New ClsMovimientos()
If ObjMovtos.GetAnticiposProveedor(CveProveedor, -1, CveMoneda:=-1, SelectTop:=-1, TipoDocto:=FiltroTipo) AndAlso ObjMovtos.DtResultados.Rows.Count > 0 Then
Dim CveMoneda As Integer = If(ChkPagarConPesos.Checked, 1, If(ChkPagarConDolares.Checked, 2, DdlMoneda.SelectedValue.ToEntero))
If DdlMoneda.SelectedValue.ToEntero = 1 AndAlso CveCompra > 0 Then DivPagarConDolares.Visible = True Else If CveCompra > 0 Then DivPagarConPesos.Visible = True
GVAnticipos.DataSource = ObjMovtos.DtResultados.FiltraParametros($"Tipo = 'Act' AND CveMoneda = {CveMoneda}")
If ObjMovtos.DtResultados.FiltraParametros("Saldo > 0").Rows.Count > 0 Then
BtnAceptarAnticipos.Enabled = True
If DdlTipoComprobante.SelectedValue = "Fac" Then ImgAnticiposPendientes.Visible = True
End If
Else
GVAnticipos.DataSource = Nothing
End If
ObjMovtos.Dispose()
GVAnticipos.DataBind()
UpAnticipos.Update()
End Sub
Private Sub CargaTiposAF()
ViewState("TmpDTTiposAF") = GlobalDTTipoActivoFijo(UsuarioActual.CveEmpresa)
Dim Row As DataRow = DirectCast(ViewState("TmpDTTiposAF"), DataTable).NewRow()
Row("CveTipoActivoFijo") = -1 : Row("TipoActivoFijo") = "Seleccione"
DirectCast(ViewState("TmpDTTiposAF"), DataTable).Rows.InsertAt(Row, 0)
End Sub
Public Function isWhitFamily() As Boolean
Return UsuarioActual.CveEmpresa = 66
End Function
Private Sub CargaPSAlias()
DdlPSAlias2.setEsWebService(True)
If UsuarioActual.CveEmpresa = 66 Then
DdlPSAlias2.ddlWS.Attributes.Add("data-subfamilia", "-1")
DdlPSAlias2.ddlWS.Attributes.Add("data-fueporxml", "0")
'SOLO CUANDO SEA FACTURA DE INGRESOS
If DdlTipoComprobante.SelectedValue = "Fac" Then
DdlPSAlias2.ddlWS.Attributes.Add("data-pagina", "Compras")
Else
DdlPSAlias2.ddlWS.Attributes.Add("data-pagina", "Compras2")
End If
End If
If Not DdlPSAlias2.UsaWebService AndAlso CType(DdlPSAlias2.DataSource, DataTable) Is Nothing Then
If UsuarioActual.TienePermisoProceso(300) Or UsuarioActual.TienePermisoProceso(301) Then
Dim DTTemp As New DataTable
DTTemp.Columns.Add("CvePS", GetType(Integer))
DTTemp.Columns.Add("PSCodigoClasificacion", GetType(String))
For Each dRow As DataRow In GlobalDTPSSimplificado(UsuarioActual.CveEmpresa).Rows
For Each drowCla As DataRow In DTClasificacionesComprobaciones.Rows
If drowCla("CveClasificacion").ToString.ToEntero = dRow("CveClasificacion").ToString.ToEntero Then
Dim InRow As DataRow = DTTemp.NewRow
InRow("CvePS") = dRow("CvePS").ToString.ToEntero
InRow("PSCodigoClasificacion") = dRow("PSCodigoClasificacion").ToString
DTTemp.Rows.Add(InRow)
End If
Next
Next
DdlPSAlias2.DataSource = DTTemp
DdlPSAlias2.DataBind()
Else
DdlPSAlias2.DataSource = GlobalDTPSSimplificado(UsuarioActual.CveEmpresa)
DdlPSAlias2.DataBind()
End If
End If
End Sub
Private Sub CargarUM(CvePS As Integer, ob As DropDownList)
Dim ObjUM As New ClsProductosServicios()
If ObjUM.GetPSEquivalencias(CvePS, UsuarioActual.CveEmpresa) Then
ViewState("DTUM") = ObjUM.DtResultados
ob.Items.Clear()
ob.DataSource = DTUM
ob.DataBind()
End If
ObjUM.Dispose()
End Sub
Private Sub CargaGridTarjetas()
Dim ObjCreditos As New ClsBancos
ObjCreditos.GetTarjetasCreditos(DdlCuenta.SelectedValue.ToEntero)
DdlTarjeta.Items.Clear()
DdlTarjeta.DataSource = ObjCreditos.DtResultados
DdlTarjeta.DataBind()
DdlTarjeta.Items.Insert(0, New ListItem("Seleccione", "-1"))
ObjCreditos.Dispose()
DivTarjeta.Visible = True
End Sub
Private Sub CargaConceptosXML(XMLDoc As XmlDocument)
Dim i As Integer = 0
Dim Total As Decimal = 0
Dim PU As Decimal = 0
Dim Descuento As Decimal = 0
Dim CveUM As Integer = 0
Dim UMM As String = "No Aplica"
Dim tCvePS As Integer = 0
Dim TipoPS As Integer = 0
Dim tCveClasif As Integer = -1
Dim Clasif As String = "Sin Clasificación"
Dim tPSCodigo As String = "-"
Dim tPSDescripcion As String = "-"
Dim PSS As String = ""
Dim Obs As String = ""
Dim SubTotalTemp = 0.0D
Dim IVA As Decimal = 0
Dim IEPS As Decimal = 0
Dim RetISR As Decimal = 0
Dim RetIVA As Decimal = 0
Dim PorcentajeIVA As Decimal = 0
Dim PorcentajeIEPS As Decimal = 0
Dim PorcentajeRetISR As Decimal = 0
Dim PorcentajeRetIVA As Decimal = 0
Dim DtTemporalGuardados = New DataTable
DtTemporalGuardados.Columns.Add("Contador", GetType(Integer))
DtTemporalGuardados.Columns.Add("Tipo", GetType(Integer))
'GLOBALS
Dim DtUM = GlobalDTUnidadesMedida(UsuarioActual.CveEmpresa).AsEnumerable
Dim DtUMAlias = GlobalDTUnidadesMedidaAlias(UsuarioActual.CveEmpresa).AsEnumerable
Dim DtPS = GlobalDTPS(UsuarioActual.CveEmpresa).AsEnumerable
Dim DtPSAlias = GlobalDTProductosServiciosAlias(UsuarioActual.CveEmpresa).AsEnumerable
Dim namespaces As New XmlNamespaceManager(XMLDoc.NameTable)
Dim nodo As XmlNode = XMLDoc.DocumentElement
Dim VersionCFDI As String = ValorXML(nodo, "version")
Dim Prefijo As String = If(XMLDoc.DocumentElement.Prefix = "", "cfd", XMLDoc.DocumentElement.Prefix)
Dim cfdVer As String = ""
If VersionCFDI = "3.2" Then
Prefijo = "cfd"
cfdVer = "http://www.sat.gob.mx/cfd/2"
ElseIf VersionCFDI = "3.3" Then
cfdVer = "http://www.sat.gob.mx/cfd/3"
Else ' se considera que es la version 4.0
cfdVer = "http://www.sat.gob.mx/cfd/4"
End If
namespaces.AddNamespace(Prefijo, cfdVer)
namespaces.AddNamespace("tfd", "http://www.sat.gob.mx/TimbreFiscalDigital")
namespaces.AddNamespace("implocal", "http://www.sat.gob.mx/implocal")
namespaces.AddNamespace("registrofiscal", "http://www.sat.gob.mx/registrofiscal")
Dim nodeconcepto As XmlNode = XMLDoc.SelectSingleNode(String.Format("//{0}:Conceptos", Prefijo), namespaces)
If nodeconcepto IsNot Nothing AndAlso nodeconcepto.ChildNodes.Count > 0 Then
Dim nodosConceptos As XmlNodeList = nodeconcepto.SelectNodes(String.Format("//{0}:Concepto", Prefijo), namespaces)
For Each node As XmlNode In nodosConceptos
' INICIALIZA VALORES
PU = 0
Descuento = 0
CveUM = 0
UMM = "No Aplica"
tCvePS = 0
TipoPS = 0
tCveClasif = -1
Clasif = "Sin Clasificación"
tPSCodigo = "-"
tPSDescripcion = "-"
PSS = ""
Obs = ""
Total = 0
IVA = 0
IEPS = 0
RetISR = 0
RetIVA = 0
PorcentajeIVA = 0
PorcentajeIEPS = 0
PorcentajeRetISR = 0
PorcentajeRetIVA = 0
'CARGA NODO ACTUAL
' node = XMLDoc.DocumentElement.ChildNodes(2).ChildNodes(i)
'CARGA PU
PU = ValorXML(node, "valorUnitario").ToDecimal
'SI PU >= TOTAL AND CANTIDAD > 0 : PU / CANTIDAD, por si tiene descuento en el importe y el valor unitario es mayor, lo ajusta
If ValorXML(node, "cantidad").ToDecimal > 0 AndAlso ValorXML(node, "valorUnitario").ToDecimal >= (ValorXML(node, "importe").ToDecimal / ValorXML(node, "cantidad").ToDecimal) Then
PU = ValorXML(node, "importe").ToDecimal / ValorXML(node, "cantidad").ToDecimal
End If
If ValorXML(node, "cantidad").ToDecimal > 0 AndAlso ValorXML(node, "valorUnitario").ToDecimal <= 0 And ValorXML(node, "importe").ToDecimal > 0 Then
PU = ValorXML(node, "importe").ToDecimal / ValorXML(node, "cantidad").ToDecimal
End If
'OBTIENE DESCUENTO
If ValorXML(node, "descuento") IsNot Nothing Then Descuento = ValorXML(node, "descuento").Trim.ToDecimal
'OBTIENE TOTAL
If ValorXML(node, "importe") IsNot Nothing Then Total = ValorXML(node, "importe").Trim.ToDecimal
'OBTIENE SUBTOTAL
SubTotalTemp += If(Total > 0, Total, PU * ValorXML(node, "cantidad").ToDecimal)
'OBTIENE UM
If ValorXML(node, "unidad") IsNot Nothing Then UMM = ValorXML(node, "unidad").Trim
'BUSCA UM EN CATALOGO
UMM = UMM.ToUpper.Replace(".", "").Replace(",", "")
Dim fUM = (From u In DtUM
Where String.Compare(u!UnidadMedida.ToString.ToUpper.Trim, UMM, CultureInfo.CurrentCulture, CompareOptions.IgnoreNonSpace) = 0 OrElse
String.Compare(u!Abreviatura.ToString.ToUpper.Trim, UMM, CultureInfo.CurrentCulture, CompareOptions.IgnoreNonSpace) = 0
Select CveUnidadMedida = u!CveUnidadMedida, UnidadMedida = u!UnidadMedida).FirstOrDefault()
If fUM IsNot Nothing AndAlso fUM.CveUnidadMedida.ToString.ToEntero > 0 Then
CveUM = fUM.CveUnidadMedida.ToString.ToEntero
UMM = fUM.UnidadMedida.ToString
Else
'BUSCA UM EN ALIAS
Dim fUMAlias = (From u In DtUMAlias
Where String.Compare(u!UnidadMedidaAlias.ToString.ToUpper.Trim, UMM, CultureInfo.CurrentCulture, CompareOptions.IgnoreNonSpace) = 0
Select u!CveUnidadMedida, u!UnidadMedida).FirstOrDefault()
If fUMAlias IsNot Nothing Then
CveUM = fUMAlias.CveUnidadMedida.ToString.ToEntero
UMM = fUMAlias.UnidadMedida.ToString
End If
End If
'se le puso una condicion de que ignorara los acentos, porque en la bd, marcaria error porque no distingue acentos
'CONCEPTO PRUEBA "TRABAJOS DE CONSTRUCCION", RM/Compras/Compras.aspx?CveFactura=13402&RFC=ECO061206QW7
'' u!PS.ToString.ToUpper.Trim = PSS
'BUSCA PS
PSS = ValorXML(node, "descripcion").ToUpper.Trim.Replace(vbCrLf, " ").Replace(vbLf, " ").Replace("'", "''").Replace(" ", " ").Replace("<22>", "")
If PSS.Length > 844 Then
PSS = PSS.Substring(0, 844) '844,por ser el numero de caracteres aceptados en la columna de la BD
End If
tPSCodigo = PSS
'BUSCA PS EN CATALOGO
Dim fPS = (From u In DtPS
Where String.Compare(u!PS.ToString.ToUpper.Trim, PSS, CultureInfo.CurrentCulture, CompareOptions.IgnoreNonSpace) = 0
Select u!CvePS, u!CveClasificacion, u!Clasificacion, u!CveTipoPS, u!PSCodigo).FirstOrDefault()
If fPS IsNot Nothing Then
PSS = fPS.PSCodigo.ToString
tCvePS = fPS.CvePS.ToString.ToEntero
TipoPS = fPS.CveTipoPS.ToString.ToEntero
tCveClasif = fPS.CveClasificacion.ToString.ToEntero
Clasif = fPS.Clasificacion.ToString
tPSCodigo = fPS.PSCodigo.ToString
Else
'BUSCA PS EN ALIAS
Dim fPSAlias = (From u In DtPSAlias
Where String.Compare(u!PSAlias.ToString.ToUpper.Trim, PSS, CultureInfo.CurrentCulture, CompareOptions.IgnoreNonSpace) = 0
Select u!CvePS, u!PS, u!CveClasificacion, u!Clasificacion, u!CveTipoPS, u!PSCodigo).FirstOrDefault()
If fPSAlias IsNot Nothing Then
Obs = PSS
PSS = fPSAlias.PS.ToString
tCvePS = fPSAlias.CvePS.ToString.ToEntero
TipoPS = fPSAlias.CveTipoPS.ToString.ToEntero
tCveClasif = fPSAlias.CveClasificacion.ToString.ToEntero
Clasif = fPSAlias.Clasificacion.ToString
tPSCodigo = fPSAlias.PSCodigo.ToString
End If
End If
'PARA GLUYAS
If UsuarioActual.CveEmpresa = 66 Then
tPSCodigo = String.Format("{1} - {0}", ValorXML(node, "descripcion").ToUpper.Trim.Replace(vbCrLf, " ").Replace(vbLf, " ").Replace("'", "''"), ValorXML(node, "noIdentificacion").Trim)
End If
'Alert(ValorXML(node, "ClaveProdServ").Trim)
If Version = "3.3" Or Version = "4.0" Then
If node IsNot Nothing AndAlso node.ChildNodes.Count > 0 Then
'OBTENER TRASLADOS POR DETALLES
Dim ContadorTraslado = 0
Dim nodosConceptosTraslado As XmlNodeList = node.SelectNodes(String.Format("//{0}:Impuestos/{0}:Traslados/{0}:Traslado", Prefijo), namespaces)
For Each nodeTraslado As XmlNode In nodosConceptosTraslado
If Not DtTemporalGuardados.FiltraParametros($"Contador = {ContadorTraslado} AND Tipo = 1").Rows.Count > 0 Then
If ValorXML(nodeTraslado, "TasaOCuota").Trim.ToDecimal > 0 And ValorXML(nodeTraslado, "Base").Trim.ToDecimal = Total Then
If ValorXML(nodeTraslado, "Impuesto") = "002" Then
IVA = ValorXML(nodeTraslado, "Importe").Trim.ToDecimal
PorcentajeIVA = ValorXML(nodeTraslado, "TasaOCuota").Trim.ToDecimal
Dim Dr As DataRow
Dr = DtTemporalGuardados.NewRow()
Dr("Contador") = ContadorTraslado
Dr("Tipo") = 1
DtTemporalGuardados.Rows.Add(Dr)
DtTemporalGuardados.AcceptChanges()
If PorcentajeIVA > 0 Then
Exit For
End If
ElseIf ValorXML(nodeTraslado, "Impuesto") = "003" Then
IEPS = ValorXML(nodeTraslado, "Importe").Trim.ToDecimal
PorcentajeIEPS = ValorXML(nodeTraslado, "TasaOCuota").Trim.ToDecimal
Dim Dr As DataRow
Dr = DtTemporalGuardados.NewRow()
Dr("Contador") = ContadorTraslado
Dr("Tipo") = 1
DtTemporalGuardados.Rows.Add(Dr)
DtTemporalGuardados.AcceptChanges()
Exit For
End If
End If
End If
ContadorTraslado += 1
Next
'OBTENER RETENCIONES POR DETALLES
Dim ContadorRetenciones = 0
Dim nodosConceptosRetenciones As XmlNodeList = node.SelectNodes(String.Format("//{0}:Impuestos/{0}:Retenciones/{0}:Retencion", Prefijo), namespaces)
For Each nodeRetencion As XmlNode In nodosConceptosRetenciones
If Not DtTemporalGuardados.FiltraParametros($"Contador = {ContadorRetenciones} AND Tipo = 2").Rows.Count > 0 Then
If ValorXML(nodeRetencion, "TasaOCuota").Trim.ToDecimal > 0 And ValorXML(nodeRetencion, "Base").Trim.ToDecimal = Total Then
If ValorXML(nodeRetencion, "Impuesto".Trim) = "001" Then
RetISR = ValorXML(nodeRetencion, "Importe").Trim.ToDecimal
PorcentajeRetISR = ValorXML(nodeRetencion, "TasaOCuota").Trim.ToDecimal
Dim Dr As DataRow
Dr = DtTemporalGuardados.NewRow()
Dr("Contador") = ContadorRetenciones
Dr("Tipo") = 2
DtTemporalGuardados.Rows.Add(Dr)
DtTemporalGuardados.AcceptChanges()
Exit For
ElseIf ValorXML(nodeRetencion, "Impuesto") = "002" Then
RetIVA = ValorXML(nodeRetencion, "Importe").Trim.ToDecimal
PorcentajeRetIVA = ValorXML(nodeRetencion, "TasaOCuota").Trim.ToDecimal
Dim Dr As DataRow
Dr = DtTemporalGuardados.NewRow()
Dr("Contador") = ContadorRetenciones
Dr("Tipo") = 2
DtTemporalGuardados.Rows.Add(Dr)
DtTemporalGuardados.AcceptChanges()
Exit For
End If
End If
End If
ContadorRetenciones += 1
Next
End If
End If
If Version = "3.2" Then
Try
If node IsNot Nothing AndAlso node.ChildNodes.Count > 0 Then
Dim ContadorTraslado = 0
Dim nodosConceptosTraslado As XmlNodeList = XMLDoc.SelectNodes(String.Format("//{0}:Impuestos/{0}:Traslados/{0}:Traslado", Prefijo), namespaces)
For Each nodeTraslado As XmlNode In nodosConceptosTraslado
If ValorXML(nodeTraslado, "tasa").Trim.ToDecimal > 0 And ValorXML(nodeTraslado, "impuesto").Trim = "IVA" Then
PorcentajeIVA = ValorXML(nodeTraslado, "tasa").Trim.ToDecimal
Alert($"{PorcentajeIVA}")
End If
Next
End If
Catch ex As Exception
End Try
End If
'' AGREGA PS
'AGREGA A TMPDT
AddPS(ValorXML(node, "cantidad").ToDecimal, CveUM, UMM, tCveClasif, Clasif, tCvePS, PSS, TipoPS, "-1", "SE", "SE", "-1", Obs, PU, Total, IVA, RetIVA, RetISR, IEPS, 0, Descuento, PSCodigo:=tPSCodigo, TCalculaTotales:=False, CveSATPS:=ValorXML(node, "ClaveProdServ").ToEntero(), CargaXml:=True, PorcentajeIVA:=PorcentajeIVA, PorcentajeRetIVA:=PorcentajeRetIVA, PorcentajeRetISR:=PorcentajeRetISR, PorcentajeIEPS:=PorcentajeIEPS)
Next
End If
AddPS2(False)
If UsuarioActual.Empresa.UsaAC Then
CompruebaAgregar()
End If
If isAlmacenistaGluyas() Then
BtnGuardar.Visible = False
AlmacenCambiaPS.Visible = True
End If
SubTotalConceptos = Math.Round(SubTotalTemp, 2)
'TmpDT = DtPSTemp.Copy
'DtPSTemp.Dispose()
End Sub
Private Sub CargaClasificacionesComprobaciones()
If UsuarioActual.TienePermisoProceso(300) Or UsuarioActual.TienePermisoProceso(301) Then
Dim ObjClasificaciones As New ClsClasificaciones()
If ObjClasificaciones.GetClasificacionesComprobaciones(UsuarioActual.CveEmpresa) Then
If UsuarioActual.TienePermisoProceso(300) And UsuarioActual.TienePermisoProceso(301) Then
DTClasificacionesComprobaciones = ObjClasificaciones.DtResultados
Else
If UsuarioActual.TienePermisoProceso(300) Then 'TipoComprobacion = 1 Biaticos
DTClasificacionesComprobaciones = ObjClasificaciones.DtResultados.FiltraParametros("TipoComprobacion = 1")
ElseIf UsuarioActual.TienePermisoProceso(301) Then 'TipoComprobacion = 2 Comprobaciones
DTClasificacionesComprobaciones = ObjClasificaciones.DtResultados.FiltraParametros("TipoComprobacion = 2")
End If
End If
End If
ObjClasificaciones.Dispose()
End If
End Sub
#End Region
#Region "Vinculacion De Servcios"
Private Function isAdminObraGluyas() As Boolean
Return (UsuarioActual.CveRol = 1047 And UsuarioActual.CveEmpresa = 66)
End Function
Private Sub cargaddlVinculacionServcios()
If isAdminObraGluyas() Then
TabVinculacionServicios.Visible = True
'Dim productos As New ClsProductosServicios
'If productos.GetPS(-1, -1, UsuarioActual.CveEmpresa) Then
' PSDTRemplazo = productos.DtResultados.FiltraParametros("CveTipoPS=2", "PS")
'End If
'productos.Dispose()
GVVinculacionServicios.DataSource = TmpDT
GVVinculacionServicios.DataBind()
End If
End Sub
Protected Sub GVVinculacionServicios_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GVVinculacionServicios.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim dt As DataTable = Nothing
dt = GlobalDTPS(UsuarioActual.CveEmpresa).FiltraParametros("CveTipoPS=2", "PS")
e.Row.FCDropDownList("Ddlnewps").DataSource = dt 'GlobalDTAlmacen(UsuarioActual.CveEmpresa)
e.Row.FCDropDownList("Ddlnewps").DataBind()
e.Row.FCDropDownList("Ddlnewps").Items.Insert(0, New ListItem("Seleccione", "-1"))
dt.Dispose()
End If
End Sub
#End Region
#Region "BTN'S"
Protected Sub BtnVincularServicios_Click(sender As Object, e As EventArgs) Handles BtnVincularServicios.Click
Dim correcto As Boolean = True
Dim x As Integer = 0
'Dim buid As New StringBuilder
For Each Dr As DataRow In TmpDT.Rows
Dim newps As Integer = GVVinculacionServicios.Rows(x).FCDropDownList("Ddlnewps").SelectedValue.ToEntero
If newps > 0 Then
'buid.Append(String.Format("{0} ---> {1},", Dr("CvePS").ToString, newps))
Dr("CvePS") = newps
'buid.Append(String.Format("{0} ---> {1},</br>", Dr("CvePS").ToString, newps))
Else 'limpio el valor para que no truene en linq mas abajo
correcto = False
Alert("Favor de vincular todos los servicios", TipoMensaje.MsgAdvertencia)
Exit For
End If
x = x + 1
Next
x = 0
For Each Dr As DataRow In GVVinculacionServicios.Rows
Dim newps As Integer = GVVinculacionServicios.Rows(x).FCDropDownList("Ddlnewps").SelectedValue.ToEntero
If newps > 0 Then
'buid.Append(String.Format("{0} ---> {1},", Dr("CvePS").ToString, newps))
Dr("CvePS") = newps
'buid.Append(String.Format("{0} ---> {1},</br>", Dr("CvePS").ToString, newps))
Else 'limpio el valor para que no truene en linq mas abajo
correcto = False
Alert("Favor de vincular todos los servicios", TipoMensaje.MsgAdvertencia)
Exit For
End If
x = x + 1
Next
TmpDT.AcceptChanges()
'Alert(buid.ToString)
If correcto Then
If Not CierrePeriodo Then
BtnGuardar.Visible = True
End If
UpFacturar.Update()
End If
End Sub
Protected Sub BtnCargarProveedores_Click(sender As Object, e As System.EventArgs) Handles BtnCargarProveedores.Click
DdlProveedor.CssClass += " select2me"
DdlProveedor.AutoPostBack = True
DdlProveedor.Items.Clear()
DdlProveedor.DataSource = GlobalDTCompProveedores(UsuarioActual.CveEmpresa)
'Dim ObjProveedor As New ClsCompProveedores
'If ObjProveedor.GetProveedores(ClsCompProveedores.TipoConsulta.ParaUsoEnEmpresa, -1, "-1", "-1", "-1", "-1", "-1", "-1", "-1", UsuarioActual.CveEmpresa) Then
'DdlProveedor.DataSource = ObjProveedor.DtResultados
'End If
DdlProveedor.DataBind()
DdlProveedor.Items.Insert(0, New ListItem("Seleccione el Proveedor", "-1"))
DdlProveedor.Attributes.Remove("onclick")
'RegistraScript("$('#C_DdlProveedor').select2('open');")
End Sub
Protected Sub BtnBuscarProveedor_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnBuscarProveedor.Click
ViewState("CveProveedor") = HdnCveProveedor.Value.ToEntero
CargaProveedor(HdnCveProveedor.Value.ToEntero, "-1")
If DdlPS.SelectedValue IsNot Nothing AndAlso DdlPS.SelectedValue.ToEntero > 0 Then
DdlPS_SelectedIndexChanged(sender, e)
DdlPS.Focus()
Else
TxtCantidad.Focus()
End If
End Sub
Protected Sub BtnGuardar_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnGuardar.Click
'------------------ INICIA VALIDACIONES ------------------
If Not ValidaSeleccionAnticipo() Then
Alert("El proveedor tiene anticipos sin aplicar, favor de especiar uno.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
Dim TotalRealDevolucion As Decimal = 0
Dim EstatusCredito As Integer = 0
Dim CveSubProyecto As Integer = 0
'Credito Multiple
If RBLPago.SelectedValue.ToEntero = 3 Then
If RBLContado.SelectedValue.ToEntero = 6 Or RBLContado.SelectedValue.ToEntero = 2 Then
If Not TxtRembolsoNumero.Text.Length > 0 Then
Alert("Falta especificar un número de reembolso", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
End If
End If
If RBLPago.SelectedValue.ToEntero = 4 Then
Dim DifCreCompra As Decimal = 0
Dim TotalCreditos As Decimal = 0
Dim MensualidadMultipleTotal As Decimal = 0
Dim CveUltimoCreditoDetalleInterno As Integer
For Each GvRow As GridViewRow In GvCreditos.Rows
Dim CapitalMiltiple As Decimal = GvRow.FCTextBox("TxtCapital").Text.ToDecimal
Dim InteresMiltiple As Decimal = GvRow.FCTextBox("TxtInteres").Text.ToDecimal
Dim AmbosMiltiple As Decimal = GvRow.FCTextBox("TxtAmbos").Text.ToDecimal
Dim MensualidadMultiple As Decimal = GvRow.DataKey("Mensualidad").ToDecimal
If CapitalMiltiple > 0 Or InteresMiltiple > 0 Then
TotalCreditos = TotalCreditos + CapitalMiltiple + InteresMiltiple
MensualidadMultipleTotal = MensualidadMultipleTotal + MensualidadMultiple
CveUltimoCreditoDetalleInterno = GvRow.DataKey("CveCreditoDetalle").ToEntero
ElseIf AmbosMiltiple > 0 Then
TotalCreditos = TotalCreditos + AmbosMiltiple
MensualidadMultipleTotal = MensualidadMultipleTotal + MensualidadMultiple
CveUltimoCreditoDetalleInterno = GvRow.DataKey("CveCreditoDetalle").ToEntero
EstatusCredito = GvRow.DataKey("Estatus").ToEntero
End If
Next
If TotalCreditos <> TxtTotal.Text.ToDecimal Then
Alert($"El importe de La factura no concide con el total de los creditos, diferencia: { (TotalCreditos - TxtTotal.Text.ToDecimal).FormatoNumero(2)}", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
End If
''VERIFICA SI LOS PRODUCTOS/SERVICIOS EXISTEN EN EL CATALOGO DEL SAT
'If UsuarioActual.CveEmpresa = 72 Then
' Dim DtNoEncontrados As DataTable = TmpDT.FiltraParametros("ISNULL(CveSATPS,0) = 46920 ")
' If DtNoEncontrados IsNot Nothing AndAlso DtNoEncontrados.Rows.Count > 0 Then
' Dim StrNoEncontrados As New StringBuilder
' StrNoEncontrados.Append("Los siguientes productos no tiene asignado la clave Producto SAT o Unidad Medida SAT<br/><br/>")
' For Each drt As DataRow In DtNoEncontrados.Rows
' StrNoEncontrados.AppendFormat("{0} <br/>", drt("CodigoPS"))
' Next
' Alert(StrNoEncontrados.ToString(), TipoMensaje.MsgAdvertencia)
' DtNoEncontrados.Dispose()
' StrNoEncontrados.Clear()
' Exit Sub
' End If
' DtNoEncontrados.Dispose()
'End If
'Verifica funcionalidad 128 "Require orden de compra para factura de compra"
Dim EsViatico As Boolean = False
If RBLPago.SelectedValue.ToEntero = 3 AndAlso RBLContado.SelectedValue.ToEntero = 2 AndAlso TxtNumeroReembolso.Text.Length > 0 AndAlso DdlPersonalReembolso.SelectedValue.ToEntero > 0 Then
EsViatico = True
End If
If Not DdlTipoComprobante.SelectedValue.Contiene("NC", "DEV") Then
If UsuarioActual.Empresa.Funcionalidad(128) = "1" And Not UsuarioActual.TienePermisoProceso(213) Then
If Not EstaAsociadoACajaChica And Not EstaAsociadoAPersonal And Not EsViatico Then
If Not CompraEstaVinculadaOC Then
Alert("Debe de vincular una orden de compra para registrar la factura")
Exit Sub
End If
End If
End If
End If
'Si se marcó No Deducible en el encabezado mínimo se debe registrar un No Deducible en el Detalle
Dim GuardaNoDeducibles As Boolean = False
If ChkEsNoDeducible.Checked Then
For Each Row As DataRow In TmpDT.Rows
If Row("NoDeducible").ToString().ToUpper().Contiene("TRUE", "1") Then
GuardaNoDeducibles = True
End If
Next
If GuardaNoDeducibles = False Then
Alert("Si la compra es No Deducible, mínimo se debe registrar un producto No Deducible", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
End If
If CierrePeriodo Then
Alert("El periodo de la compra actual ya se encuentra cerrado. No podra registrar la compra.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
''DF - 10/04/2017
'If UsuarioActual.TienePermisoProceso(187) Then
' If TxtSerie.Text <> SerieVieja Then
' Dim dtt As DataTable = GlobalDTProveedorSucursales(CveProveedor, UsuarioActual.CveEmpresa)
' If dtt IsNot Nothing AndAlso dtt.Rows.Count > 0 Then
' Dim SerieNueva As String = dtt.FiltroPrimeroValor("Serie", $"Serie = '{TxtSerie.Text}'").ToString
' If SerieNueva = "" Then
' Alert("La Serie no es válida, por favor revise que se encuentre dentro de la lista de las sucursales del proveedor.", TipoMensaje.MsgAdvertencia)
' Exit Sub
' End If
' End If
' End If
'End If
'Excede el limite de credito
If RBLPago.SelectedValue = "1" AndAlso DdlTipoComprobante.SelectedValue.Contiene("Fac") AndAlso UsuarioActual.Empresa.Funcionalidad(518) = "1" AndAlso Not UsuarioActual.TienePermisoProceso(185) Then
Dim ObjCompras As New ClsCompras
If ObjCompras.ObtenerCreditoRestante(CveProveedor) Then
If ObjCompras.DtResultados.Rows.Count > 0 Then
Dim Saldo As Decimal = ObjCompras.DtResultados(0)("Saldo").ToString.ToDecimal + TxtTotal.Text.ToDecimal
Dim LimiteCredito As Decimal = ObjCompras.DtResultados(0)("LimiteCredito").ToString.ToDecimal
If LimiteCredito > 0 Then
If Saldo / LimiteCredito * 100 > 90 Then
Alert($"Nuestro Limite de Credito con este proveedor supera el 90% </br> Porcentaje Actual: {(Saldo / LimiteCredito * 100).FormatoNumero(2)}%", TipoMensaje.MsgAdvertencia)
End If
End If
Else
ObjCompras.Dispose()
Alert("El proveedor no tiene límite de crédito", TipoMensaje.MsgError)
Exit Sub
End If
Else
ObjCompras.Dispose()
Alert("Ocurrio un error al obtener el limite de credito del Proveedor", TipoMensaje.MsgError)
Exit Sub
End If
ObjCompras.Dispose()
End If
If Not (HFDiferenciaCompra.Value = TxtTotal.Text Or CveFactura < 1 Or CveCompra < 1) Then
Alert("La compra no se puede registrar debido a que los totales no son iguales, verifique sus cambios", TipoMensaje.MsgError)
Exit Sub
End If
'UM EQUIVALENCIAS
For Each gvr As GridViewRow In GvPS.Rows
If gvr.DataKey("CvePS").ToString.ToEntero > 0 Then
If gvr.DataKey("CveUM").ToString.ToEntero = 0 Then
Alert("Existe un error, Unidad de Medida no registrada", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
End If
Next
If ChkConsignacion.Checked Then
For Each gvr As GridViewRow In GvInv.Rows
If gvr.FCDropDownList("DdlVinculaConsignacion").SelectedValue.ToEntero < 0 Then
Alert("Si la compra aplica consignación debe vincular todos los conceptos en Almacén.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
Next
End If
If RowProveedorSucursal.Visible And DdlProveedorSucursal.SelectedValue.ToEntero = -1 Then
Alert("Favor de seleccionar una sucursal del proveedor", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
If UsuarioActual.TienePermisoProceso(121) Then
If DdlTipoComprobante.SelectedValue.Contiene("NC", "DEV") Then
If Not NCDevolucion Then
Alert("Favor de seleccionar un producto en la pestaña de almacen", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
Else
Dim x As Integer = 0
For Each Dr As GridViewRow In GvInv.Rows
If Dr.FCCheckBox("cbInv").Checked Then
x = x + 1
End If
Next
If Not (CveCompraRefacturacion > 0 AndAlso ChkRefacturacionConAlmacen.Checked) Then
If x = 0 AndAlso GvInv.Rows.Count > 0 Then
Alert("Favor de seleccionar un producto en la pestaña de almacen", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
End If
End If
End If
If UsuarioActual.Empresa.Funcionalidad(538).ToEntero = 1 Then
If TmpDT.MIN("CvePS").ToEntero <= 0 Then
Alert("Todos los Productos/Servicios deben estar registrados o aliados a un productos ya registrado.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
End If
If UsuarioActual.Empresa.Funcionalidad(123).ToEntero > 0 And Not UsuarioActual.TienePermisoProceso(156) Then
If Not ValidaCierrePeriodo() Then
Alert("No se puede registar la compra. Se ha cerrado el periodo de la compra actual", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
End If
Dim TotalPorDevengar = Math.Round(TxtTotal.Text.ToDouble, 2)
Dim TotalDetalle = 0.0
Dim RequiereCentroCosto As Boolean = False
'If Not (UsuarioActual.Empresa.Funcionalidad(102) = "") Then
' Dim NotHas117 As Boolean = Not UsuarioActual.TienePermisoProceso(117)
' 'verifica que tenga proyecto y clasificacion
For Each Row As DataRow In TmpDT.Rows
If Row("CveSubProyecto").ToString.ToEntero <= 0 Then
Alert("No se ha completado la asignacion de proyectos en la compra. ", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
CveSubProyecto = Row("CveSubProyecto").ToString.ToEntero
If Row("CveClasificacionActualizar").ToString.ToEntero <= 0 Then 'If NotHas117 AndAlso Row("CveClasificacionActualizar").ToString.ToEntero <= 0 Then
Alert("Hay productos que no tienen clasificación asignada.<br> Favor de asignarle una y darle guardar.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
If UsuarioActual.Empresa.Funcionalidad(527) = "1" Then
If Row("CveTipoGasto").ToString.ToEntero <= 0 Then
Alert("No se ha completado la asignacion de tipos de gasto en la compra.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
End If
Next
'End If
'SI LA CANTIDAD EN SERIE/LOTE NO ES IGUAL A CANTIDAD EN GVPS
'Dim DtDetalles As DataTable
Dim Cantidad As Integer
If GvInv.HeaderRow.FCCheckBox("cbAll").Checked = True Then
For Each Dr As DataRow In DtInv.Rows
If Dr("CveMetodoInventario").ToString.ToEntero = 5 Then
Cantidad = DtDatosDetalle.FiltraParametros(String.Format("CvePS = {0}", Dr("CvePS").ToString)).Rows.Count
If Cantidad < Dr("Cantidad").ToString.ToEntero Then
Alert("No hay productos a los que no se le ha asociado Serie-Lote", TipoMensaje.MsgError)
Exit Sub
End If
End If
Next
End If
If Not HdnCveProveedor.Value <> "-1" Then
Alert("En necesario seleccionar un proveedor, al cual se le va a facturar.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
If Not TmpDT.Rows.Count > 0 Then
Alert("Es necesario agregar al menos un Producto o Servicio a la factura.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
'VALIDA SI LA CLASIFICACIÓN REQUIERE PERSONAL, AF COMPRA O AF INSUMO
Dim ErrorValidacion As Boolean = False
Dim DtTemporal As New DataTable
DtTemporal.Columns.Add("CveClasificacion", GetType(Integer))
For Each Gvr As GridViewRow In GvPS.Rows
Dim Dr As DataRow = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltraParametros($"CveClasificacion = {Gvr.DataKey("CveClasificacion").ToEntero}")(0)
If Dr IsNot Nothing Then
Dim SeValido As Boolean = False
For Each Drt As DataRow In DtTemporal.Rows
If Drt("CveClasificacion").ToString.ToEntero = Dr("CveClasificacion").ToString.ToEntero Then
SeValido = True
Exit For
End If
Next
If Not SeValido Then
If CBool(Dr("RequierePersonal")) Then
For Each GvP As GridViewRow In GvPersonal.Rows
If GvP.DataKey("CveClasificacion").ToEntero = Dr("CveClasificacion").ToString.ToEntero Then
If Not GvP.FCDropDownList("DdlPersonalGv").SelectedValue.ToEntero > 0 Then
ErrorValidacion = True
Alert($"Tiene que seleccionar un personal para esta clasificación: <b>{Dr("Clasificacion").ToString}</b>.", TipoMensaje.MsgAdvertencia)
Exit For
End If
End If
Next
End If
If CBool(Dr("RequiereAFCompra")) Then
For Each GvAFC As GridViewRow In GvAFCompras.Rows
If GvAFC.DataKey("CveClasificacion").ToEntero = Dr("CveClasificacion").ToString.ToEntero Then
If Not GvAFC.FCHiddenField("HdnCveAF").Value.ToEntero > 0 Then
ErrorValidacion = True
Alert($"Tiene que seleccionar un AF compra para esta clasificación: <b>{Dr("Clasificacion").ToString}</b>.", TipoMensaje.MsgAdvertencia)
Exit For
End If
End If
Next
End If
If CBool(Dr("RequiereAFInsumo")) Then
For Each GvAFI As GridViewRow In GvAFInsumos.Rows
If GvAFI.DataKey("CveClasificacion").ToEntero = Dr("CveClasificacion").ToString.ToEntero Then
If Not GvAFI.FCHiddenField("HdnCveAF").Value.ToEntero > 0 Then
ErrorValidacion = True
If Not SeValido Then
Alert($"Tiene que seleccionar un AF insumo para esta clasificación: <b>{Dr("Clasificacion").ToString}</b>.", TipoMensaje.MsgAdvertencia)
End If
Exit For
End If
End If
Next
End If
Dim Drr As DataRow = DtTemporal.NewRow
Drr("CveClasificacion") = Dr("CveClasificacion").ToString.ToEntero
DtTemporal.Rows.Add(Drr)
End If
End If
Next
If ErrorValidacion Then Exit Sub
If UsuarioActual.Empresa.Funcionalidad(545) = "1" Then
Dim dtPSInvalidos As String = ValidarPSContrato(TmpDT.FiltraParametros("", "", {"CveSubProyecto", "CvePS", "Cantidad", "PU"}))
If dtPSInvalidos <> "" Then
Alert(dtPSInvalidos, TipoMensaje.MsgAdvertencia)
Exit Sub
End If
End If
'RECORRO LOS PRODUCTOS O SERVICIOS PARA REGISTRARLOS LOS QUE NO EXISTEN EN EL CATÁLOGO
Dim tCve As Integer
Dim RegeneraPS As Boolean = False
'OBJETOS PROVISIONALES
Dim UM As New ClsUnidadesMedida
Dim PSS As New ClsProductosServicios
Dim Correcto = True
For Each Row As DataRow In TmpDT.Rows
'VALIDACION DE CENTRO DE COSTO
If UsuarioActual.Empresa.RequiereCentroCostos AndAlso Row("CveSubProyecto").ToString.ToEntero <= 0 Then
RequiereCentroCosto = True
UM.Dispose()
PSS.Dispose()
Alert("Falta asignar Proyecto a la compra", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
'REGISTRO LAS UNIDADES DE MEDIDA
If Row("CveUM").ToString.ToEntero = 0 Then
tCve = UM.AddUnidadMedida(Row("UM").ToString, Row("UM").ToString, "", "", "", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1)
If tCve > 0 Then
Row("CveUM") = tCve
Dim rowsToUpdate = TmpDT.AsEnumerable().Where(Function(r) r.Field(Of String)("UM").ToString.ToUpper = Row("UM").ToString.ToUpper AndAlso r!CveUM.ToString.ToEntero = 0)
For Each roww As DataRow In rowsToUpdate
roww.SetField("CveUM", tCve)
Next
Else
Correcto = False
End If
End If
'REGISTRO LOS PRODUCTOS
If Row("CvePS").ToString.ToEntero = 0 Then
'tCve = PSS.AddPS(Row("CveClasificacionActualizar").ToString.ToEntero, -1, Row("CveUM").ToString.ToEntero, "", "", "", Row("PS").ToString, Row("PU").ToString.ToDouble, If(TxtIVA.Text.ToDouble > 0, -1, 0), 0, False, 0, True, False, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, 0)
'If tCve > 0 Then
' RegeneraPS = True
' Row("CvePS") = tCve
' Row("CveClasificacion") = Row("CveClasificacionActualizar").ToString.ToEntero
' 'Row("CveEq") = 1
' TmpDT.AcceptChanges()
' 'busco el mismo PS dentro de la tabla por si está más de una vez y lo actualizo
' Dim rowsToUpdate = TmpDT.AsEnumerable().Where(Function(r) r.Field(Of String)("PS") = Row("PS").ToString AndAlso r!CvePS.ToString.ToEntero = 0)
' For Each roww As DataRow In rowsToUpdate
' roww.SetField("CvePS", tCve)
' roww.SetField("CveClasificacion", Row("CveClasificacionActualizar").ToString.ToEntero)
' 'roww.SetField("CveEq", 1)
' Next
' TmpDT.AcceptChanges()
'Else
' Correcto = False
'End If
Alert("Existen productos sin registrar/Asignar.", TipoMensaje.MsgAdvertencia)
Correcto = False
Else
'UPDATE CLASIFICACION DE PRODUCTO YA REGISTRADO
If Row("CveClasificacionActualizar").ToString.ToEntero > 0 AndAlso Row("CveClasificacion").ToString.ToEntero <= 0 Then
If PSS.UpdateClasificacionPS(Row("CveClasificacionActualizar").ToString.ToEntero, UsuarioActual.CveUsuario, Row("CvePS").ToString.ToEntero) Then
Row("CveClasificacion") = Row("CveClasificacionActualizar").ToString.ToEntero
RegeneraPS = True
Else
Correcto = False
End If
End If
End If
Next
UM.Dispose()
PSS.Dispose()
'VALIDA IMPORTES
If Not ValidaTotalesGuardar() Then
Exit Sub
End If
If Not AjustaCombustibles() Then
Exit Sub
End If
'------------------TERMINA VALIDACIONES------------------
'si hay necesidad de actualizar el globaldtps
If RegeneraPS Then
'Dim Hilo As New System.Threading.Thread(AddressOf GeneraGlobalDT)
'Hilo.Start()
GeneraGlobalDT(Nothing)
End If
Dim CvePlantillaPrePoliza As Integer
If DdlTipoComprobante.SelectedValue.Contiene("NC", "DEV") Then
CvePlantillaPrePoliza = 60
Else
CvePlantillaPrePoliza = 1
End If
Dim tIdContaProveedor As Integer = CtaProveedor
Dim ImporteAnticipo As Decimal = 0
If (ArrAnticipos.Count > 0 And CveCompra > 0) Or (ArrAnticipos.Count > 0 And UsuarioActual.Empresa.UsaAC) Then '-- ESTO SE QUITO - IPP - 04 NOVIMEBRE 2016
CvePlantillaPrePoliza = 52
'cuenta de anticipos
tIdContaProveedor = CtaProveedorAnticipos
For Each Ant As Compras_Compras.Anticipos In ArrAnticipos
ImporteAnticipo += Ant.Importe
Next
If Math.Round(ImporteAnticipo, 2) > TxtTotal.Text.ToDouble Then
Alert("El Importe seleccionado es mayor a la compra", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
End If
If RBLContado.SelectedValue = "2" AndAlso DdlFuncionarioEmpleado.SelectedValue.ToEntero > 0 Then
If EmpresaPrueba Then
If DdlTipoComprobante.SelectedValue.Contiene("NC", "DEV") Then
CvePlantillaPrePoliza = 60
Else
CvePlantillaPrePoliza = 1
End If
Else
CvePlantillaPrePoliza = 9
End If
End If
'If RBLPago.SelectedValue.ToEntero = 4 And UsuarioActual.CveEmpresa.Contiene(1, 7) Then
' CvePlantillaPrePoliza = 69
'End If
TmpDT.AcceptChanges()
If Correcto Then
Dim ObjCompras As New ClsCompras()
Dim ObjConta As New ClsContabilidad(ObjCompras.IniciaTransacSQL())
Dim ObjIE As New ClsBancos(ObjCompras.IniciaTransacSQL)
Dim ObjInventario As New ClsInventarios(ObjCompras.IniciaTransacSQL)
Dim ObjAF As New ClsAF(ObjCompras.IniciaTransacSQL)
Dim ObjOC As New ClsOC(ObjCompras.IniciaTransacSQL)
Dim ObjContratos As New ClsContratos(ObjCompras.IniciaTransacSQL())
Dim ObjProveedores As New ClsCompProveedores(ObjCompras.IniciaTransacSQL())
Dim ObjEventos As New ClsOIEventos(ObjCompras.IniciaTransacSQL())
Dim ObjAcar As New ClsAcarreos(ObjCompras.IniciaTransacSQL())
Dim ObjCGame As New ClsCGame(ObjCompras.IniciaTransacSQL())
Dim ObjProductosServicios As New ClsProductosServicios(ObjCompras.IniciaTransacSQL())
Dim ObjContaAC As ClsContPAQi = Nothing
Dim ErrorMovtosCxP As Boolean = False
Dim ErrorPrepoliza As Boolean = False
Dim ErrorPrepolizaDescuadre As Boolean = False
Dim ErrorMovtosRetIVA As Boolean = False
Dim ErrorMovtosRetISR As Boolean = False
Dim ErrorMovtosEstimaciones As Boolean = False
Dim ErrorMovtosIVA As Boolean = False
Dim ErrorMovtosIE As Boolean = False
Dim ErrorMovInv As Boolean
Dim ErrorMovDev As Boolean = False
Dim ErrorOC = False
Dim TieneError As Boolean = False
Dim ErrorAC As Boolean = False
Dim ErrorAF As Boolean = False
Dim ErrorReembolso As Boolean = False
Dim ErrorBitacora = False
Dim ErrorAddAcarreos As Boolean = False
Dim ErrorCreditosCompra As Boolean = False
Dim ErrorOtrosGastos As Boolean = False
Dim ErrorSATPS As Boolean = False
Dim ErrorACMEnsaje As New StringBuilder
Dim ErrorSaldosInvComp As Boolean = False
Dim CveIE As Integer = -1
Dim CveEstatusFactura As Integer = 1
Dim PolizaFolio As Integer = 0
Dim CvePrePoliza As Integer
Dim ImporteCompra As Decimal = TxtTotal.Text.ToDecimal
Dim MultiplicadorNC = If(DdlTipoComprobante.SelectedValue = "NC", -1, 1)
Dim CveMovimientoInventario As Integer = -1
Dim IVA As Decimal = 1.16D
Dim ListaMovimientosAlmacen As New List(Of Integer)
Dim Devolucion As MMensajeDevolucion = Nothing
Dim ErrorCreditoCapitalIntres As Boolean = False
Dim ErrorCredito As Boolean = False
If ChkProgramarPago.Checked Then
CveEstatusFactura = 2
End If
Dim EntregaDirecta = False
Dim ConceptoPoliza As String = String.Format("{0} - {1}{2} - {3}", NombreProveedor, TxtSerie.Text, TxtFolio.Text, TxtDescripcion.Text.Trim)
Dim EsImportacion As Boolean = chkImportacion.Checked 'funcion para empresas llanteras
'TIPO CAMBIO MANUAL CON COMPRA NUEVA
Dim TipoCambioGuardar As Decimal = 1
If DdlMoneda.SelectedValue.ToEntero > 1 Then
TipoCambioGuardar = If(DivTC.Visible, TxtTC.Text.ToDecimal, LblTC.Text.Substring(3).ToDecimal)
End If
TipoCambio = If(DivTC.Visible, TipoCambioGuardar, TipoCambio)
Try
Dim FolioFijo As Integer = 0
'cheque
If DdlTipoTransaccion.SelectedValue = "1" AndAlso UsuarioActual.CveEmpresa <> 119 Then FolioFijo = TxtFolio.Text.ToEntero
CvePrePoliza = ObjConta.AddPrePolizas("Compras/Registrar", If(EsContado And CvePlantillaPrePoliza = 1, 2, CvePlantillaPrePoliza), ImporteCompra, TxtTotal.Text.ToDouble, DdlMoneda.SelectedValue.ToEntero, TxtFecha.Text.ToDate, ConceptoPoliza, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, FolioFijo:=FolioFijo, ReglaFolioPoliza:=ObjCompras.ObtenerReglaFolio(DdlTipoTransaccion.SelectedValue, DdlTipoTransaccionCaja.SelectedValue, UsuarioActual.CveEmpresa), CveTipoPoliza:=ObjConta.ObtenerTipoPoliza(DdlTipoTransaccion.SelectedValue, DdlTipoTransaccionCaja.SelectedValue, UsuarioActual.CveEmpresa))
If CvePrePoliza > 0 Then
'seria de contado, solo cuando no tenga vinculado ningun anticipo
Dim ImportePago As Decimal = 0
Dim TCPago As Decimal = GlobalTipoCambio(TxtFechaPago.Text.ToDate).ToString.ToDecimal
Dim CveMonedaPago As Integer = DdlMoneda.SelectedValue.ToEntero
If RBLPago.SelectedValue.ToEntero = 2 Then 'Contado
If RBLContado.SelectedValue = "1" Then
ImportePago = TxtDocumentoImporte.Text.Trim.ToDecimal
Dim Dr As DataRow = GlobalDTBancosCuentas(UsuarioActual.CveUsuario, CveEmpresa:=UsuarioActual.CveEmpresa).FiltraParametros($"CveCuenta = {DdlCuenta.SelectedValue}").Rows(0)
If Dr IsNot Nothing Then
CveMonedaPago = Dr("CveMoneda").ToString.ToEntero
End If
If CveMonedaPago = 1 AndAlso DdlMoneda.SelectedValue.ToEntero = 2 Then
ImportePago = (ImportePago * TCPago).RoundSQL
ElseIf CveMonedaPago = 2 AndAlso DdlMoneda.SelectedValue.ToEntero = 1 Then
ImportePago = (ImportePago / TCPago).RoundSQL
ElseIf CveMonedaPago = 1 AndAlso DdlMoneda.SelectedValue.ToEntero = 1 Then
TCPago = 1
End If
'se registra primero el movimiento en bancos para luego vincularlo en la compra
CveIE = ObjIE.AddBancos_IE(DdlCuenta.SelectedValue.ToEntero, DdlTipoTransaccion.SelectedValue.ToEntero, TxtFechaPago.Text.Trim.ToDate, TxtDocumentoFolio.Text.Trim, DdlProveedor.SelectedItem.Text.Trim, ImportePago, CveMonedaPago, TCPago, TxtDocumentoObservaciones.Text.Trim, "", True, True, -1, CvePrePoliza, "", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCuentaTarjeta:=If(DivTarjeta.Visible, DdlTarjeta.SelectedValue.ToEntero, -1))
ElseIf RBLContado.SelectedValue = "6" Then
ImportePago = TxtDocumentoImporteCaja.Text.Trim.ToDecimal
Dim Dr As DataRow = GlobalDTBancosCuentas(UsuarioActual.CveUsuario, CveEmpresa:=UsuarioActual.CveEmpresa).FiltraParametros($"CveCuenta = {DdlCuentaCaja.SelectedValue}").Rows(0)
If Dr IsNot Nothing Then
CveMonedaPago = Dr("CveMoneda").ToString.ToEntero
End If
If CveMonedaPago = 1 AndAlso DdlMoneda.SelectedValue.ToEntero = 2 Then
ImportePago = (ImportePago * TCPago).RoundSQL
ElseIf CveMonedaPago = 2 AndAlso DdlMoneda.SelectedValue.ToEntero = 1 Then
ImportePago = (ImportePago / TCPago).RoundSQL
ElseIf CveMonedaPago = 1 AndAlso DdlMoneda.SelectedValue.ToEntero = 1 Then
TCPago = 1
End If
'se registra primero el movimiento en bancos para luego vincularlo en la compra
CveIE = ObjIE.AddBancos_IE(DdlCuentaCaja.SelectedValue.ToEntero, DdlTipoTransaccionCaja.SelectedValue.ToEntero, TxtFechaPago.Text.Trim.ToDate, TxtDocumentoFolioCaja.Text.Trim, DdlProveedor.SelectedItem.Text.Trim, ImportePago, CveMonedaPago, TCPago, TxtDocumentoObservacionesCaja.Text.Trim, "", True, True, -1, CvePrePoliza, "", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa)
End If
If (RBLContado.SelectedValue = "1" OrElse RBLContado.SelectedValue = "6") AndAlso Not CveIE > 0 Then
ErrorMovtosIE = True
End If
End If
If Not ErrorMovtosIE Then
'REEMBOLSOS NO USA AC
Dim NumeroReembolso = "-1"
If TxtNumeroReembolso IsNot Nothing And RBLPago.SelectedValue = "3" Then
NumeroReembolso = TxtNumeroReembolso.Text
''GUARDA VALORES PARA SESSION
UsuarioActual.Sesion("Comp-NumeroReembolso") = TxtNumeroReembolso.Text
UsuarioActual.Sesion("Comp-CveFYE") = DdlPersonalReembolso.SelectedValue
UsuarioActual.Sesion("Comp-Descripcion") = TxtDescripcion.Text
If NumeroReembolso <> "-1" Then
If CvePersonal <= 0 And CveCajaChica <= 0 Then
ErrorReembolso = True
End If
End If
Else
UsuarioActual.Sesion("Comp-NumeroReembolso") = ""
End If
If Not ErrorReembolso Then
'PORCENTAJE IVA
Dim PorcentajeIVA As Decimal = TmpDT.MAX("IVAPorcentaje").ToDecimal
'If DdlIVA.SelectedValue.ToDouble = 1.16 Then
' PorcentajeIVA = 0.16
'ElseIf DdlIVA.SelectedValue.ToDouble = 1.08 Then
' PorcentajeIVA = 0.08
'End If
'METODO DE PREPOLIZA DE ALMACEN
If UsuarioActual.Empresa.UsaInventarios And Not UsuarioActual.Empresa.Funcionalidad(126) = "1" Then
Dim ImporteAlmacen = TmpDT.SUM(If(ListaDocumentos IsNot Nothing AndAlso ListaDocumentos.Count > 0 AndAlso ArrAnticipos IsNot Nothing AndAlso ArrAnticipos.Count > 0, "ImporteSinImpuestos", "Total"), $"ISNULL(TipoAF,0) <> 2 AND ISNULL(CveAlmacen,0) = 0 AND ISNULL(AplicaCostoIndirecto,0) <> 1 AND CveTipoPS = 2").ToString.ToDecimal
If ImporteAlmacen > 0 Then
If Not DdlTipoComprobante.SelectedValue.Contiene("NC", "DEV", "Ant") Then
If (CveImportacion > 0 Or CveFlete > 0) Then
CveConceptoContableAlmacen = CveConceptoContableAlmacen
Else
CveConceptoContableAlmacen = 205
End If
If OCVinculada AndAlso DdlOCVinculaInv.Visible AndAlso Not (CveImportacion > 0 Or CveFlete > 0) Then
CveConceptoContableAlmacen = DdlOCVinculaInv.SelectedValue.ToEntero
End If
If UsuarioActual.CveEmpresa.Contiene(72, 80, 140, 141, 152) And Not (CveImportacion > 0 Or CveFlete > 0) Then 'se comento, RMF. 2020.08.19, no le hallo sentido
CveConceptoContableAlmacen = 205
End If
Else
CveConceptoContableAlmacen = 225
End If
'Condiciones para los casos de facturas que son en 0 pero que se utiliza el almacen
ElseIf OCVinculada AndAlso Not (CveImportacion > 0 Or CveFlete > 0) AndAlso Not DdlTipoComprobante.SelectedValue.Contiene("NC", "DEV", "Ant") Then
CveConceptoContableAlmacen = DdlOCVinculaInv.SelectedValue.ToEntero
ElseIf (CveImportacion > 0 Or CveFlete > 0) AndAlso Not DdlTipoComprobante.SelectedValue.Contiene("NC", "DEV", "Ant") Then
CveConceptoContableAlmacen = CveConceptoContableAlmacen
ElseIf CveCompraRefacturacion > 0 AndAlso ChkRefacNC.Checked Then ' cuando es refacturacion, tomara del concepto anterior
CveConceptoContableAlmacen = HdnRefacturacionConcepto.Value.ToEntero
End If
End If
If RBLPago.SelectedValue.ToEntero = 4 And EstatusCredito.Contiene(1, 101) Then
CveEstatusFactura = 6
End If
'Compra
Dim CveFactura As Integer = -1
If Request("CveFactura") IsNot Nothing Then
CveFactura = Request("CveFactura").ToString.ToEntero
End If
'si el registro es manual, toma el mismo dato
If CveFactura <= 0 Then TotalOriginal = TxtTotal.Text.ToDecimal
For Each GvRow As GridViewRow In GvPS.Rows
If GvRow.RowType = DataControlRowType.DataRow Then
If GvRow.FCCheckBox("ChkEsNoDeduciblePS").Checked = False Then
EsNoDeducible = False
Exit For
End If
End If
Next
'Compra
If ObjCompras.AddCompra(DdlTipoComprobante.SelectedValue, TxtDescripcion.Text.Trim, TxtSerie.Text.Trim, TxtFolio.Text.Trim, TxtFolioSecundario.Text.Trim, CveProveedor, TxtSubTotal.Text.ToDouble, TxtDescuento.Text.ToDouble,
LblAmortizacion.Text.ToDouble, TxtIVA.Text.ToDouble, TxtRetIVA.Text.ToDouble, TxtRetISR.Text.ToDouble, TxtIEPS.Text.ToDouble, TxtOtrosImpuestos.Text.ToDouble,
TxtRedondeo.Text.ToDouble, TxtTotal.Text.ToDouble, TxtFecha.Text.Trim.ToDate, DdlMoneda.SelectedValue.ToEntero, TipoCambio, TxtFechaPago.Text.Trim.ToDate, ChkAplicaNotaCredito.Checked, TxtObsFact.Text.Trim, CveEstatusFactura,
CvePrePoliza, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, IdPoliza, CveCajaChica:=CveCajaChica, CvePersonal:=CvePersonal, NumeroReembolso:=NumeroReembolso, CveProveedorSucursal:=DdlProveedorSucursal.SelectedValue.ToEntero,
AplicoPromocion:=ChkOCPromocion.Checked, PorcentajeIVA:=PorcentajeIVA, CveMetodoPago:=CveMetodoPago, CveRetIVAConcepto:=If(DdlRetIVAConcepto.Items.Count > 0, DdlRetIVAConcepto.SelectedValue.ToEntero, -1), CveConceptoContableAlmacen:=CveConceptoContableAlmacen,
CveRetISRConcepto:=If(DdlRetISRConcepto.Items.Count > 0, DdlRetISRConcepto.SelectedValue.ToEntero, -1), NoDeducible:=EsNoDeducible, CveTipoCompra:=DdlTipoCompra.SelectedValue.ToEntero, TotalOriginal:=TotalOriginal, CveTipoConcepto:=CveTipoConcepto, EsImportacion:=EsImportacion, CveFactura:=CveFactura) Then
ViewState("CveCompra") = ObjCompras.CveCompra
If ObjCompras.DtResultados.Rows.Count > 0 Then ViewState("CompraFolio") = ObjCompras.DtResultados.Rows(0)("vFolio").ToString
If DdlTipoComprobante.SelectedValue.Contiene("NC", "DEV") Then
Devolucion = guardardevolucion(ObjInventario, ObjCompras.CveCompra, TxtSubTotal2.Text.ToDecimal, TxtFecha.Text.Trim.ToDate)
TotalRealDevolucion = Devolucion.Total
TieneError = Devolucion.TieneError
End If
Dim ErrorDetalles As Boolean = False
' Dim IDPoliza As Integer
Dim IDPolizaComprometido = 0
Dim ErrorComprometido = False
Dim CompraActual As New Compra
CompraActual.CveCompra = ObjCompras.CveCompra
CompraActual.CveTipoConceptoProveedor = CveTipoConcepto
CompraActual.CveProveedor = CveProveedor
CompraActual.CveMoneda = DdlMoneda.SelectedValue.ToEntero
CompraActual.Fecha = TxtFecha.Text.ToDate
CompraActual.SerieFolio = TxtSerie.Text.Trim & "-" & TxtFolio.Text.Trim
CompraActual.ProveedorNombre = HplProveedor.Text
CompraActual.TC = TipoCambio
CompraActual.Total = TxtTotal.Text.ToDecimal
CompraActual.IVA = TxtIVA.Text.ToDecimal
CompraActual.IVADeducible = TxtIVA.Text.ToDecimal
CompraActual.IEPS = TxtIEPS.Text.ToDecimal
CompraActual.RetIVA = TxtRetIVA.Text.ToDecimal
CompraActual.RetISR = TxtRetISR.Text.ToDecimal
CompraActual.CveConceptoRetISR = DdlRetISRConcepto.SelectedValue.ToEntero
CompraActual.CveConceptoRetIVA = DdlRetIVAConcepto.SelectedValue.ToEntero
CompraActual.PorcentajeIVA = PorcentajeIVA
CompraActual.UsuarioActual = UsuarioActual
CompraActual.CveSubProyecto = TmpDT.FiltroPrimeroValor("CveSubProyecto", " CveSubProyecto > 0").ToEntero
CompraActual.IdCtaContableProv = CtaProveedor
CompraActual.IdCtaContableProvComplementaria = CtaProveedorComplementaria
CompraActual.EsImportacion = chkImportacion.Checked
If CveImportacion > 0 Or CveFlete > 0 Then
Select Case CveConceptoContableAlmacen
Case 237
Select Case FleteImportacionOpcion
Case 1
If Not ObjInventario.AddFletesCompras(CveFlete, CveCompra) Then
ErrorOC = True
End If
''actualiza la compra para que no se surta en almacen. sino por el flete o importación
'If Not ObjCompras.UpdateEstatusAlmacen(CveCompra, 2) Then
' ErrorOC = True
'End If
Case 2
If Not ObjInventario.AddFleteDetalle(CveFlete, CveCompra) Then
ErrorOC = True
End If
'actualiza la compra para que no se surta en almacen. sino por el flete o importación
If Not ObjCompras.UpdateEstatusAlmacen(CveCompra, 2, UsuarioActual.CveUsuario) Then
ErrorOC = True
End If
End Select
Case 240
Select Case FleteImportacionOpcion
Case 1
If Not ObjCompras.AddImportacionCompra(CveImportacion, CveCompra) Then
ErrorOC = True
End If
Case 2
If Not ObjCompras.AddImportacionDetalle(CveImportacion, CveCompra) Then
ErrorOC = True
End If
'actualiza la compra para que no se surta en almacen. sino por el flete o importación
If Not ObjCompras.UpdateEstatusAlmacen(CveCompra, 2, UsuarioActual.CveUsuario) Then
ErrorOC = True
End If
End Select
End Select
End If
If UsuarioActual.Empresa.UsaAC AndAlso Not TieneError Then
If TotalPorDevengar <= TxtTotal.Text.ToDouble And TotalPorDevengar > 0 Then
ObjContaAC = New ClsContPAQi(UsuarioActual.Empresa)
ObjContaAC.IniciaTransacSQL()
''POLIZA COMPROMETIDO SOLO SI NO SE VINCULA OC
If HdnVCveOC.Value.ToEntero > 0 Then
' IDPolizaComprometido = ObjContaAC.AddPoliza( 4, "Comprometido", Total, Total, UsuarioActual.CveUsuario, Now)
' If IDPolizaComprometido <= 0 Then
' ErrorComprometido = True
' End If
IDPolizaComprometido = 1
TotalPorDevengar = TotalPorDevengar * 2
Else
TotalPorDevengar = TotalPorDevengar * 3
End If
IdPoliza = ObjContaAC.AddPoliza(3, TxtDescripcion.Text.Trim, TotalPorDevengar, TotalPorDevengar, UsuarioActual.CveUsuario, TxtFecha.Text.ToDate)
'Dim filtro As New StringBuilder
If IdPoliza > 0 Then
PolizaFolio = ObjContaAC.Folio
'Dim RegistroMatriz As DataRow
'Dim CuentaCargo As Integer
Dim CuentaAbono As Integer
Dim Importe As Decimal
'CUENTA PROVEEDOR
If tIdContaProveedor <= 0 Then
'normalmente debe de ser la cuenta 021120000000000000, para el caso de APH, se el cmabio al 2119
If ObjContaAC.GetCuentas(-1, "021190000000000000", -1) Then
Dim drCuenta As DataRow = ObjContaAC.DtResultados.FiltroPrimero("")
If drCuenta IsNot Nothing Then
CuentaAbono = drCuenta("Id").ToString.ToEntero
Dim FolioProveedor = ObjContaAC.GetFolioProveedores("021190000000000000").ToString
ViewState("CtaProveedor") = ObjContaAC.AddCuenta(String.Format("02119{0}000000000", FolioProveedor.PadLeft(4, "0"c)), NombreProveedor, "D", 2, 0, 1, 0, "", 1, CuentaAbono)
ObjProveedores.UpdateProveedorIdCuentaAC(CveProveedor, CtaProveedor)
tIdContaProveedor = CtaProveedor
Else
ErrorAC = True
ErrorACMEnsaje.Append(" - DrCuenta Nula")
End If
Else
ErrorACMEnsaje.Append(" - Error al consultar cuenta 021190000000000000 ")
ErrorAC = True
End If
End If
Dim ConceptoRenglon As String = ""
If Not ErrorAC Then
'INVENTARIOS EN AC
Dim ContadorInventario As Integer = GvInv.Rows.Cast(Of GridViewRow)().Count(Function(gvr) gvr.FCCheckBox("cbInv").Checked)
Dim CtaAlmacen As Integer
If ContadorInventario > 0 Then
Dim drr As DataRow = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimero(String.Format("CveAlmacen = {0}", GvInv.HeaderRow.FCDropDownList("ddlAlmacen").SelectedValue.ToString.ToEntero))
If drr IsNot Nothing Then
CtaAlmacen = drr("IdCtaContable").ToString.ToEntero
End If
End If
Dim tTotalIVA, tTotalGral, tDiferenciaIVA, tIVA, tRetIVA, tRetISR As Decimal
Dim ipresup As Integer = 0
'COMIENZA: PRUEBA AGRUPACION CONCEPTOS
Dim Presup = From gvr As DataRow In TmpDT.Rows.Cast(Of DataRow)()
Group gvr By Grp = New With {
Key .CvePresupuestoEgreso = gvr("CvePresupuestoEgreso").ToString.ToEntero,
Key .CveOrdencompraDetalle = If(gvr("CveOrdencompraDetalle").ToString.ToEntero > 0, 1, -1),
Key .CveActivoFijo = If(gvr("TipoAF").ToString.ToEntero = 2, gvr("CveActivoFijo").ToString.ToEntero, -1)
} Into Group
Select Grp.CvePresupuestoEgreso, Grp.CveActivoFijo, Grp.CveOrdencompraDetalle,
TotalImporte = Group.Sum(Function(r) r("Total").ToString.ToDecimal)
Dim Fecha As Date = TxtFecha.Text.ToDate
'Dim tTotalIVA, tTotalGral, tDiferenciaIVA, tIVA As Double
tTotalIVA = TxtIVA.Text.ToDecimal
tRetIVA = TxtRetIVA.Text.ToDecimal
tRetISR = TxtRetISR.Text.ToDecimal
'tTotalIVA = tTotalIVA - tRetIVA - tRetISR
tTotalGral = TxtTotal.Text.ToDecimal + tRetIVA + tRetISR ' EL TOTAL GENERAL DEBE DE SER EL SUBTOTAL + IVA, NO SE DEBEN DE INCLUIR LAS RETENCIONES, POR ESO SE RESTA
tDiferenciaIVA = tTotalIVA
ipresup = 0
Dim CuentaMatrizAlmacen As Integer
'PresupuestoEgresos
Dim DtPresupuestosTemp As DataTable
Dim IdCuentaComprometido, IdCuentaPorEjercer, IdCuentaDevengado, IdCuentaMatriz As Integer
' Dim DescuentoConIVA As Decimal
Dim tPorIVA As Decimal = tTotalIVA / (tTotalGral - tTotalIVA)
Dim tAjusteTotal As Decimal
For Each grp In Presup
Importe = grp.TotalImporte
TotalDetalle += Importe
ipresup += 1
If Importe > 0 Then
'saco la proporcion de iva que le corresponde
tIVA = Math.Round(Importe * tPorIVA, 2)
tDiferenciaIVA -= tIVA
'identifico si es el ultimo registro, para ver si es necesario un ajuste
If ipresup = Presup.Count Then
If Math.Round(TotalDetalle - tTotalGral, 2) <= 0.01 AndAlso tDiferenciaIVA > 0 Then
tIVA += tDiferenciaIVA
End If
End If
'le sumo el iva al concepto
Importe += tIVA
'codigo Provisional, para cuand tenga descuento, solo tome el subtotal * el iva,RMF
If TxtDescuento.Text.ToDouble > 0 Then
Importe = grp.TotalImporte * 1.16D
End If
tAjusteTotal += Importe
'valido que la sumas de lo detalles no exceda al totalgeneral
If Math.Round(tAjusteTotal, 2) > tTotalGral Then
'le resto la diferencia
Importe -= (tAjusteTotal - tTotalGral)
End If
'Presupuesto Egresos
DtPresupuestosTemp = DtPresupuestos.FiltraParametros(String.Format("CvePresupuestoEgreso = {0}", grp.CvePresupuestoEgreso))
If DtPresupuestosTemp.Rows.Count <> 1 Then
ErrorAC = True
ErrorACMEnsaje.Append(" - DtPresupuestosTemp.Rows.Count <> 1 ")
Exit For
End If
IdCuentaComprometido = DtPresupuestosTemp.Rows(0)("IdCuentaComprometido").ToString.ToEntero
IdCuentaPorEjercer = DtPresupuestosTemp.Rows(0)("IdCuentaPorEjercer").ToString.ToEntero
IdCuentaDevengado = DtPresupuestosTemp.Rows(0)("IdCuentaDevengado").ToString.ToEntero
IdCuentaMatriz = DtPresupuestosTemp.Rows(0)("IdCuentaMatriz").ToString.ToEntero
'COMPROMETIDO DEPENDIENTE SI EXISTE SU POLIZA
If grp.CveOrdencompraDetalle = -1 Then
ConceptoRenglon = String.Format("GC Fact: {0}-{1} {2}", TxtSerie.Text.Trim, TxtFolio.Text.Trim, DdlProveedor.SelectedItem.Text)
If ObjContaAC.AddMovimiento(IdPoliza, IdCuentaComprometido, False, MultiplicadorNC * Importe, "", ConceptoRenglon, 0, Fecha, "") Then
If Not ObjContaAC.AddMovimiento(IdPoliza, IdCuentaPorEjercer, True, MultiplicadorNC * Importe, "", ConceptoRenglon, 0, Fecha, "") Then
ErrorAC = True
ErrorACMEnsaje.Append(" - Error al agregar movimiento contabilidad 1")
Exit For
End If
Else
ErrorACMEnsaje.Append(" - Error al agregar movimiento contabilidad 2")
ErrorAC = True
Exit For
End If
End If
ConceptoRenglon = String.Format("GD Fact:{0}-{1} {2}", TxtSerie.Text.Trim, TxtFolio.Text.Trim, DdlProveedor.SelectedItem.Text)
'DEVENGADO
If ObjContaAC.AddMovimiento(IdPoliza, IdCuentaDevengado, False, MultiplicadorNC * Importe, "", ConceptoRenglon, 0, Fecha, "") Then
If Not ObjContaAC.AddMovimiento(IdPoliza, IdCuentaComprometido, True, MultiplicadorNC * Importe, "", ConceptoRenglon, 0, Fecha, "") Then
ErrorACMEnsaje.Append(" - Error al agregar movimiento contabilidad 3")
ErrorAC = True
Exit For
End If
Else
ErrorACMEnsaje.Append(" - Error al agregar movimiento contabilidad 4")
ErrorAC = True
Exit For
End If
If ContadorInventario > 0 Then
CuentaMatrizAlmacen = CtaAlmacen
ElseIf grp.CveActivoFijo > 0 Then
Dim CtaAF = -1
Dim AF = ""
Dim CuentaInicial = -1
If ObjAF.GetActivosFijos(grp.CveActivoFijo, UsuarioActual.CveEmpresa, "-1", "-1", -1, -1, "-1", -1, -1, -1, -1, -1, "", -1, UsuarioActual.CveEmpresa) Then
CtaAF = ObjAF.Cuenta
AF = ObjAF.Descripcion
CuentaInicial = ObjAF.CuentaInicial
Else
ErrorAC = True
ErrorACMEnsaje.Append(" - Error al obtener activos fijos ")
Exit For
End If
If Not CuentaInicial > 0 Then
CuentaInicial = 1241
End If
'CUENTA AF
If CtaAF <= 0 Then
If ObjContaAC.GetCuentas(-1, String.Format("0{0}0000000000000", CuentaInicial), -1) Then
Dim drCuenta As DataRow = ObjContaAC.DtResultados.FiltroPrimero("")
If drCuenta IsNot Nothing Then
ErrorACMEnsaje.Append(" - Error al obtener cuentas 0{0}0000000000000 drCuenta nula")
CuentaAbono = drCuenta("Id").ToString.ToEntero
Dim FolioAF = ObjContaAC.GetFolioProveedores(String.Format("0{0}0000000000000", CuentaInicial)).ToString
CtaAF = ObjContaAC.AddCuenta(String.Format("0{0}{1}000000000", CuentaInicial, FolioAF.PadLeft(4, "0"c)), AF, "A", 2, 0, 1, 0, "", 1, CuentaAbono)
ObjAF.UpdateActivosFijosCuentaAC(grp.CveActivoFijo, CtaAF, UsuarioActual.CveUsuario)
Else
ErrorACMEnsaje.Append(" - Error al obtener cuentas 0{0}0000000000000 drCuenta nulo")
ErrorAC = True
End If
Else
ErrorACMEnsaje.Append(" - Error al obtener cuentas 0{0}0000000000000")
ErrorAC = True
End If
End If
CuentaMatrizAlmacen = CtaAF
Else
CuentaMatrizAlmacen = IdCuentaMatriz
End If
''AFECTAR MATRIZ EGRESOS
If ObjContaAC.AddMovimiento(IdPoliza, CuentaMatrizAlmacen, False, MultiplicadorNC * Importe, "", ConceptoRenglon, 0, Fecha, "") Then
''VERIFICA SI TIENE DESCUENTO (AMORTIZACION)
'If TxtDescuento.Text.ToDouble > 0 Then
' DescuentoConIVA = TxtDescuento.Text.ToDouble * 1.16
' 'Valida que el descuento con iva cuadre en los totales
' If Math.Abs(DescuentoConIVA - (Importe - TxtTotal.Text.ToDouble)) < 0.02 Then
' DescuentoConIVA = Importe - TxtTotal.Text.ToDouble
' ElseIf DescuentoConIVA <> (Importe - TxtTotal.Text.ToDouble) Then
' ErrorAC = True
' Exit For
' End If
' 'actualizo el idcuenta del presupuesto
' If ObjContaAC.AddMovimiento(123456, IdPoliza, tIdContaProveedor, True, Importe - DescuentoConIVA, "", ConceptoRenglon, 0, Fecha, "") Then
' 'agrego a la cuenta contable anticipos
' If Not ObjContaAC.AddMovimiento(123456, IdPoliza, CtaProveedorAnticipos, True, DescuentoConIVA, "", ConceptoRenglon, 0, Fecha, "") Then
' ErrorAC = True
' Exit For
' End If
' Else
' ErrorAC = True
' Exit For
' End If
'Else
' 'actualizo el idcuenta del presupuesto
' Importe = TxtTotal.Text.ToDouble
' If Not ObjContaAC.AddMovimiento(123456, IdPoliza, tIdContaProveedor, True, If(ArrAnticipos.Count > 0, ImporteAnticipo, Importe), "", ConceptoRenglon, 0, Fecha, "") Then
' ErrorAC = True
' Exit For
' End If
'End If
Else
ErrorACMEnsaje.Append(" - Error AFECTAR MATRIZ EGRESOS ObjContaAC.AddMovimiento")
ErrorAC = True
Exit For
End If
''TERMINA AFECTAR MATRIZ EGRESOS
Else
ErrorACMEnsaje.Append(" - For Each grp In Presup Importe > 0 ")
ErrorAC = True
Exit For
End If
Next
'actualizo el idcuenta del presupuesto
Importe = TxtTotal.Text.ToDecimal
If Not ObjContaAC.AddMovimiento(IdPoliza, tIdContaProveedor, True, MultiplicadorNC * (If(ArrAnticipos.Count > 0, ImporteAnticipo, Importe)), "", ConceptoRenglon, 0, Fecha, "") Then
ErrorACMEnsaje.Append(" - actualizo el idcuenta del presupuesto ObjContaAC.AddMovimiento 3")
ErrorAC = True
End If
'End If
If tRetISR > 0 Then
ConceptoRenglon = String.Format("GD Fact: {0}-{1} {2}", TxtSerie.Text.Trim, TxtFolio.Text.Trim, DdlProveedor.SelectedItem.Text)
If Not ObjContaAC.AddMovimiento(IdPoliza, CtaProveedorRetISR, True, MultiplicadorNC * tRetISR, "", ConceptoRenglon, 0, Fecha, "") Then
ErrorACMEnsaje.Append(" RetISR > 0 ObjContaAC.AddMovimiento")
ErrorAC = True
End If
End If
'TERMINA: PRUEBA AGRUPACION CONCEPTOS
'registrar amortizar anticipos
End If
Else
ErrorACMEnsaje.Append(" - Id Poliza = 0 ")
ErrorAC = True
End If
Else
TieneError = True
ErrorACMEnsaje.Append("- TotalPorDevengar <= TxtTotal.Text.ToDouble And TotalPorDevengar > 0")
ErrorAC = True
End If
End If
If Not ErrorAC AndAlso Not TieneError Then
Dim AutoConta As Boolean = UsuarioActual.Empresa.Funcionalidad(200) = "1"
If UsuarioActual.CveEmpresa = 119 AndAlso (DdlPersonalReembolso.SelectedValue.ToEntero > 0 Or DdlCuentaCajaChicaReembolso.SelectedValue.ToEntero > 0 Or DdlTipoComprobante.SelectedValue = "Ant") Then
AutoConta = False
End If
If (AutoConta Or UsuarioActual.Empresa.UsaAC) And ObjContaAC Is Nothing AndAlso UsuarioActual.Empresa.TipoContabilidad = 2 Then
ObjContaAC = New ClsContPAQi(UsuarioActual.Empresa)
ObjContaAC.IniciaTransacSQL()
End If
''EMPIEZA: INSERTA DETALLES DE LA COMPRA
Dim indiceTR = 0
Dim Cont As Integer = 0
For Each Row As DataRow In TmpDT.Rows
Dim TipoRecepcion As Integer = -1
''INVENTARIOS
If GvInv.Rows.Count > indiceTR Then
If GvInv.Rows(indiceTR).FCCheckBox("cbInv").Checked = True And GvInv.Rows(indiceTR).FCDropDownList("DdlRecibirInv").SelectedValue = "1" Then
TipoRecepcion = 1
ElseIf GvInv.Rows(indiceTR).FCCheckBox("cbInv").Checked = True And GvInv.Rows(indiceTR).FCDropDownList("DdlRecibirInv").SelectedValue = "0" Then
TipoRecepcion = 2
End If
End If
Dim CvePersonal = -1
Dim Referencia = ""
If GvPersonal.Rows.Count > Cont Then
CvePersonal = GvPersonal.Rows(Cont).FCDropDownList("DdlPersonalGv").SelectedValue.ToEntero
Referencia = GvPersonal.Rows(Cont).FCTextBox("TxtReferencia").Text
End If
Cont = Cont + 1
'Si es AF-INSUMO se guarda CveAF en CompraDetalle
Dim CveAF = If(Row("CveActivoFijo").ToString.ToEntero > 0 AndAlso Row("TipoAF").ToString.ToEntero = 1, Row("CveActivoFijo").ToString.ToEntero, -1)
'Si es AF-COMPRA se guarda CveAF en la Columna CveAFCompra
Dim CveAFC = If(Row("CveActivoFijo").ToString.ToEntero > 0 AndAlso Row("TipoAF").ToString.ToEntero = 2, Row("CveActivoFijo").ToString.ToEntero, -1)
'AGREGA COMPRA DETALLE
If Not ObjCompras.AddCompraDetalle(CveCompra, Row("CveUM").ToString.ToEntero, Row("CvePS").ToString.ToEntero, Row("CveSubProyecto").ToString.ToEntero, -1, CveAF,
Row("Cantidad").ToString.ToDecimal, Row("PU").ToString.ToDecimal, Row("IVA").ToString.ToDecimal, Row("Total").ToString.ToDecimal, Row("Descuento").ToString.ToDecimal,
Row("Obs").ToString, Row("CveOrdenCompraDetalle").ToString.ToEntero, TipoRecepcion, Row("CveContrato").ToString.ToEntero, Row("CvePresupuestoEgreso").ToString.ToEntero,
AplicaCostoIndirecto:=Row("AplicaCostoIndirecto").ToString.ToEntero, EstatusAlmacen:=Row("EntregaDirecta").ToString.ToEntero, CvePersonal:=CvePersonal,
CveTipoGasto:=Row("CveTipoGasto").ToString.ToEntero, AF_Medida:=Row("AFMedida").ToString.ToEntero, AF_TipoMantenimiento:=Row("AFTipoMantenimiento").ToString.ToEntero, Referencia:=Referencia, OtrosGastos:=Row("OtrosGastos").ToString.ToDecimal,
RetIVA:=Row("RetIVA").ToString.ToDecimal, RetISR:=Row("RetISR").ToString.ToDecimal, IEPSPS:=Row("IEPSPS").ToString.ToDecimal.RoundSQL, IEPSPSIVA:=Row("IEPSPSIVA").ToString.ToDecimal,
IVAPorcentaje:=Row("IVAPorcentaje").ToString.ToDecimal, RetIVAPorcentaje:=Row("RetIVAPorcentaje").ToString.ToDecimal, RetISRPorcentaje:=Row("RetISRPorcentaje").ToString.ToDecimal,
IEPSPSPorcentaje:=Row("IEPSPSPorcentaje").ToString.ToDecimal, IEPSPSIVAPorcentaje:=Row("IEPSPSIVAPorcentaje").ToString.ToDecimal, NoDeducible:=If((Row("NoDeducible").ToString().ToUpper().Contiene("TRUE", "1")) AndAlso EsNoDeducible, True, False),
CveContratoDetalle:=Row("CveContratoDetalle").ToString.ToEntero, CveCultivoCuadroDetalle:=Row("CveCultivoCuadroDetalle").ToString.ToEntero) Then
ErrorDetalles = True
Exit For
Else
If Row("EntregaDirecta").ToString.ToEntero > 0 Then
EntregaDirecta = True
End If
Dim TmpDr As DataRow = TmpDT.Select($"Consec = {Row("Consec").ToString}")(0)
TmpDr("CveCompraDetalle") = ObjCompras.CveCompraDetalle
' Si no es un movimiento de almacen va a tronar
Try
Dim InvDr As DataRow = DtInv.Select($"Consec = {Row("Consec").ToString}")(0)
InvDr("CveCompraDetalle") = ObjCompras.CveCompraDetalle
Catch ex As Exception
End Try
End If
'Vincula Vales
If IdVale.Count > 0 Then
For Each cve In IdVale
If Not ObjAF.UpdateValeCombustible(cve, CveCompra, -1, "", -1, -1, -1, UsuarioActual.CveEmpresa) Then
ErrorAF = True
Exit For
End If
Next
Else
End If
'AGREGA AF COMPRA - Cuando es Compra se guarda CveCompraDetalle en AF
If Row("TipoAF").ToString.ToEntero = 2 Then
If Not ObjAF.UpdateActivosFijosCompra(Row("CveActivoFijo").ToString.ToEntero, ObjCompras.CveCompraDetalle, Row("TipoAF").ToString.ToEntero, Row("Total").ToString.ToDouble, TxtFecha.Text.Trim.ToDate) Then
ErrorDetalles = True
Exit For
End If
End If
'ACTUALIZAR PRODUCTO/SERVICIO SAT
If Version = "3.3" Or Version = "4.0" Then
If Row("CveSATPSActualizado").ToString().ToEntero() = 1 Then
If Not ObjProductosServicios.UpdateProductosServiciosSAT(Row("CvePS").ToString().ToEntero(), Row("CveSATPS").ToString().ToEntero(), UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa) Then
ErrorSATPS = True
End If
End If
End If
indiceTR += 1
Next
''TERMINA: INSERTA DETALLES DE LA COMPRA
'QUEMA SALDOS DE INV-COMPRA | MERCANCIA RECIBIDA POR ADELANTADO (OC) | PP 176
If OCVinculada And Not DdlTipoComprobante.SelectedValue.Contiene("NC", "DEV", "Ant") And Not UsuarioActual.Empresa.Funcionalidad(126) = "1" Then
For Each Row As DataRow In TmpDT.FiltraParametros("CveTipoPS = 2").Rows
If Not ObjOC.OrdenesCompraDetalleSaldosInvCompraAdd(Row("CveOrdenCompraDetalle").ToString.ToEntero, -1, -1, Row("CveCompraDetalle").ToString.ToEntero, Row("Cantidad").ToString.ToDecimal) Then
ErrorSaldosInvComp = True
Exit For
End If
Next
'verifica si fue vinculada con una OC, y si fue la opción de entrega por adelantado, que si hubo cambios de precios
If DdlOCVinculaInv.SelectedValue.ToEntero.Contiene(176, 205) Then
If Not AjustarPrePolizaVinculacionOC(ObjOC, ObjEventos, ObjInventario, ObjConta, ObjContaAC) Then
ErrorPrepoliza = True
End If
End If
End If
If CvePrePoliza > 0 Then
'INVENTARIOS - ALMACEN
If UsuarioActual.Empresa.UsaInventarios Then 'And UsuarioActual.Empresa.UsaAC = False
''SI ES CON DOLARES VALIDA QUE SE TENGA EL TIPO DE CAMBIO DEL DIA DE LA FACTURA - SI NO, NO HACE NADA, la validación del TC, ya está chk constrains
' If DdlMoneda.SelectedValue.ToEntero = 1 Or (DdlMoneda.SelectedValue.ToEntero > 1 AndAlso GlobalTipoCambio(TxtFecha.Text.ToDate) > 0) Then
''ALMACEN CONSIGNACION
If CveConsignacion > 0 Then
'actualizamos cvecompraconsignacion
For Each gvr As GridViewRow In GvInv.Rows
If gvr.FCCheckBox("cbinv").Checked AndAlso gvr.FCHiddenField("HdnCveConsignacion").Value.ToEntero > 0 Then
If Not ObjInventario.UpdateConsignacionesCompra(CveCompra, gvr.FCHiddenField("HdnCveConsignacion").Value.ToEntero, gvr.FCHiddenField("HdnCveAlmacen").Value.ToEntero, gvr.FCHiddenField("HdnCvePS").Value.ToEntero, gvr.DataKey("Cantidad").ToDouble, UsuarioActual.CveEmpresa) Then
ErrorMovInv = True
Exit For
End If
End If
Next
If Not ErrorMovInv Then
Dim x As Integer = 0
For Each dr As DataRow In DtInv.Rows
If GvInv.Rows(x).FCCheckBox("cbInv").Checked And GvInv.Rows(x).FCTextBox("TbCantidad").Text.ToDouble > 0 Then
Dim TmpDr As DataRow = TmpDT.Select($"Consec = {dr("Consec").ToString.ToEntero}")(0) 'Charlie
TmpDr("CveAlmacen") = GvInv.Rows(x).FCDropDownList("ddlEAlmacen").SelectedValue.ToEntero 'Charlie
dr("CveAlmacen") = GvInv.Rows(x).FCDropDownList("ddlealmacen").SelectedValue.ToEntero
dr("Cantidad") = GvInv.Rows(x).FCTextBox("TbCantidad").Text.ToDouble
Else
Dim TmpDr As DataRow = TmpDT.Select($"Consec = {dr("Consec").ToString.ToEntero}")(0) 'Charlie
TmpDr("CveAlmacen") = 0 'Charlie
dr("CveAlmacen") = 0
End If
x = x + 1
Next
Dim cvemovimientosalida = 0
Dim cvemovimientoentrada = 0
Dim cvemovimientosalidagasto = 0
Dim folio = 0
Dim fecha As Date = TxtFecha.Text.ToDate
Dim indice = 0
Dim importeconcepto As Decimal = 0
Dim listalmacenes = (From cvealmacen In DtInv.AsEnumerable() Where cvealmacen.Field(Of Integer)("cvealmacen") > 0 Select cvealmacen.Field(Of Integer)("cvealmacen")).Distinct().ToList
For Each tcvealmacen As Integer In listalmacenes
If GvInv.Rows(indice).FCDropDownList("ddlrecibirinv").SelectedValue = "1" Then
Continue For
End If
indice += 1
'agregamos la entrada
If Not UsuarioActual.Empresa.UsaAC Then fecha = Now
folio = ObjInventario.GetFolioSiguiente(2, UsuarioActual.CveEmpresa)
cvemovimientoentrada = ObjInventario.AddMovimiento(tcvealmacen, 2, 1, fecha, folio, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCompra, -1, -1, -1, TipoCambio:=If(DdlMoneda.SelectedValue.ToEntero = 1, -1, TipoCambioGuardar), Modulo:="Comp/G4")
If cvemovimientoentrada <= 0 Then
ErrorMovInv = True
Exit For
Else
CveMovimientoInventario = cvemovimientoentrada
ListaMovimientosAlmacen.Add(CveMovimientoInventario)
For Each dr As DataRow In DtInv.Rows
If dr("cvealmacen").ToString.ToEntero = tcvealmacen Then
'hay que restarle descuento
importeconcepto = If(DdlMoneda.SelectedValue.ToEntero = 1, dr("pu").ToString.ToDecimal, dr("pu").ToString.ToDecimal * TipoCambioGuardar) - (If(DdlMoneda.SelectedValue.ToEntero = 1, dr("descuento").ToString.ToDecimal, dr("descuento").ToString.ToDecimal * TipoCambioGuardar) / dr("cantidad").ToString.ToDecimal)
If Not ObjInventario.AddMovimientoDetalle(cvemovimientoentrada, dr("cantidad").ToString.ToDouble, dr("cveum").ToString.ToEntero, dr("cveps").ToString.ToEntero, importeconcepto, -1, PUTC:=If(DdlMoneda.SelectedValue.ToEntero = 1, -1, dr("pu").ToString.ToDecimal), CveCompraDetalle:=dr("CveCompraDetalle").ToString.ToEntero) Then
ErrorMovInv = True
Exit For
End If
End If
Next
End If
'agregamos la salida
folio = ObjInventario.GetFolioSiguiente(3, UsuarioActual.CveEmpresa)
cvemovimientosalidagasto = ObjInventario.AddMovimiento(tcvealmacen, 3, DdlMoneda.SelectedValue.ToEntero, fecha.AddSeconds(1), folio, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCompra, -1, -1, -1, Modulo:="Comp/G3")
If cvemovimientosalidagasto <= 0 Then
ErrorMovInv = True
Exit For
Else
If ObjInventario.GetMovimientosDetalle(cvemovimientoentrada, UsuarioActual.CveEmpresa) Then
For Each dr As DataRow In ObjInventario.DtResultados.Rows
If Not ObjInventario.AddMovimientoDetalle(cvemovimientosalidagasto, dr("cantidad").ToString.ToDouble, dr("cveum").ToString.ToEntero, dr("cveps").ToString.ToEntero, 0, dr("cveaf").ToString.ToEntero, CveCompraDetalle:=dr("CveCompraDetalle").ToString.ToEntero) Then
ErrorMovInv = True
Exit For
End If
Next
End If
End If
Next
End If
''ALMACEN NORMAL
Else
'OBTIENE ALMACENES
Dim x As Integer = 0
For Each Dr As DataRow In DtInv.Rows
If GvInv.Rows(x).FCCheckBox("cbInv").Checked And GvInv.Rows(x).FCTextBox("TbCantidad").Text.ToDecimal > 0 Then
Dim TmpDr As DataRow = TmpDT.Select($"Consec = {Dr("Consec").ToString.ToEntero}")(0)
TmpDr("CveAlmacen") = GvInv.Rows(x).FCDropDownList("ddlEAlmacen").SelectedValue.ToEntero
Dr("CveAlmacen") = GvInv.Rows(x).FCDropDownList("ddlEAlmacen").SelectedValue.ToEntero
Dr("Cantidad") = GvInv.Rows(x).FCTextBox("TbCantidad").Text.ToDouble
Else 'limpio el valor para que no truene en linq mas abajo
Dim TmpDr As DataRow = TmpDT.Select($"Consec = {Dr("Consec").ToString.ToEntero}")(0)
TmpDr("CveAlmacen") = 0
Dr("CveAlmacen") = 0
End If
x = x + 1
Next
Dim i As Integer = 0
Dim ListAlmacenes = (From CveAlmacen In DtInv.AsEnumerable() Where CveAlmacen.Field(Of Integer)("CveAlmacen") > 0 Select CveAlmacen.Field(Of Integer)("CveAlmacen")).Distinct().ToList
Dim indice = 0
Dim ImporteConcepto As Decimal = 0
If DdlTipoComprobante.SelectedValue = "Fac" Then
For Each tCveAlmacen As Integer In ListAlmacenes
If GvInv.Rows(indice).FCDropDownList("DdlRecibirInv").SelectedValue = "1" Then
Continue For
End If
indice += 1
Dim fecha As Date = TxtFecha.Text.ToDate
If Not UsuarioActual.Empresa.UsaAC Then fecha = Now
CveMovimientoInventario = ObjInventario.AddMovimiento(tCveAlmacen, 2, 1, fecha, 0, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCompra, -1, -1, -1, TipoCambio:=If(DdlMoneda.SelectedValue.ToEntero = 1, -1, TipoCambioGuardar), Modulo:="Comp/G2")
If CveMovimientoInventario <= 0 Then
ErrorMovInv = True
Else
Dim DtDetalle As New DataTable
Dim DtEquivalencias As DataTable
Dim CveProducto As Integer
Dim CantidadInv As Decimal
Dim PUInv As Decimal
Dim CveUnidad As Integer
Dim CostoIndirecto As Decimal
Dim tDescuento As Decimal = 0
ListaMovimientosAlmacen.Add(CveMovimientoInventario)
For Each Dr As DataRow In DtInv.Rows
CveProducto = Dr("CvePS").ToString.ToEntero
CveUnidad = Dr("CveUM").ToString.ToEntero
CantidadInv = Dr("Cantidad").ToString.ToDecimal
PUInv = Dr("PU").ToString.ToDecimal
tDescuento = Dr("Descuento").ToString.ToDecimal / CantidadInv
CostoIndirecto = Dr("CostoIndirectoAlmacen").ToString.ToDecimal
If Dr("CveMetodoInventario").ToString.ToEntero = 5 Then
'SI FUE POR SERIE LOTE
DtDetalle = DtDatosDetalle.FiltraParametros(String.Format("CvePS = {0}", Dr("CvePS")))
If DtDetalle.Rows.Count > 0 Then
For Each drr As DataRow In DtDetalle.Rows
If Not ObjInventario.AddMovimientoDetalle(CveMovimientoInventario, 1, Dr("CveUM").ToString.ToEntero, Dr("CvePS").ToString.ToEntero, Dr("PU").ToString.ToDecimal, -1, Serie:=drr("Serie").ToString, FechaCaducidad:=drr("FechaCaducidad").ToString.ToDate, CostoIndirecto:=Dr("CostoIndirectoAlmacen").ToString.ToDecimal, CveCompraDetalle:=Dr("CveCompraDetalle").ToString.ToEntero, CveOrdenCompraDetalle:=Dr("CveOrdenCompraDetalle").ToString.ToEntero) Then
ErrorMovInv = True
Exit For
End If
Next
End If
Else
'UNIDAD BASE - EQUIVALENCIAS - INVENTARIO
If UsuarioActual.CveEmpresa = 1 Then
DtEquivalencias = New DataTable
DtEquivalencias = GlobalDTProductosServiciosEquivalencias(CveProducto, -1, UsuarioActual.CveEmpresa)
Dim CveUnidadBase As Integer = DtEquivalencias.FiltroPrimeroValor("CveUM", "UnidadBase = 'True'").ToEntero
Dim drUMBase As DataRow = DtEquivalencias.FiltroPrimero("UnidadBase = 'True'")
'SI LA UNIDAD ACTUAL NO ES LA BASE SACA PROPORCION (EQUIVALENTE)
If CveUnidadBase <> CveUnidad Then
' LO QUE PUSE LO QUE VALE UNIDAD BASE LO QUE VALE UNIDAD SELECCIONADA
CantidadInv = Dr("Cantidad").ToString.ToDecimal * drUMBase("Cantidad").ToString.ToDecimal / DtEquivalencias.FiltraParametros(String.Format("CveUM = {0}", CveUnidad)).Rows(0)("Cantidad").ToString.ToDecimal
PUInv = PUInv * Dr("Cantidad").ToString.ToDecimal / CantidadInv
CostoIndirecto = CostoIndirecto * Dr("Cantidad").ToString.ToDecimal / CantidadInv
CveUnidad = CveUnidadBase
End If
End If
'si no es por serie lote
ImporteConcepto = If(DdlMoneda.SelectedValue.ToEntero = 1, PUInv, PUInv * TipoCambioGuardar) - If(DdlMoneda.SelectedValue.ToEntero = 1, tDescuento, tDescuento * TipoCambioGuardar)
ImporteConcepto = If(UsuarioActual.Empresa.UsaAC, ImporteConcepto * IVA, ImporteConcepto)
If Dr("CveAlmacen").ToString.ToEntero = tCveAlmacen Then
If Not ObjInventario.AddMovimientoDetalle(CveMovimientoInventario, CantidadInv, CveUnidad, Dr("CvePS").ToString.ToEntero, ImporteConcepto, -1, PUTC:=If(DdlMoneda.SelectedValue.ToEntero = 1, -1, Dr("PU").ToString.ToDecimal), CostoIndirecto:=CostoIndirecto, CveCompraDetalle:=Dr("CveCompraDetalle").ToString.ToEntero, CveOrdenCompraDetalle:=Dr("CveOrdenCompraDetalle").ToString.ToEntero) Then
ErrorMovInv = True
Exit For
End If
End If
End If
i = i + 1
Next
End If
Next
End If
End If
If AplicarCostoIndirecto(ObjInventario, ObjCompras) Then
ErrorMovInv = True
End If
End If
'*************************************************** P R I M E R A P A R T E C O M P R A S **************************************************************************************************************************************************************************************************************************************************************************************************
'P R E P O L I Z A S
Dim CveConceptoAfectacion As Integer = 5 'Proveedores
Dim CveConceptoOriginal As Integer
If CveTipoConcepto = 2 Then CveConceptoAfectacion = 305 'cuando es acreedor
If CveMoneda <> 1 Then
Select Case CveConceptoAfectacion
Case 5
CveConceptoAfectacion = 311
Case 305
CveConceptoAfectacion = 306
Case Else
End Select
End If
Dim CveConceptoAfectacionContado As Integer = 17 'Pago Proveedores
If CveTipoConcepto = 2 Then CveConceptoAfectacionContado = 308 'cuando es acreedor
If CveMoneda <> 1 Then
Select Case CveConceptoAfectacionContado
Case 17
CveConceptoAfectacionContado = 312
Case 308
CveConceptoAfectacionContado = 309
Case Else
End Select
End If
Dim CveConceptoCompra As Integer = 6 'Compra
Dim CveConceptoIVA As Integer = 14 'IVA Trasladado
Dim CveConceptoRetIVA As Integer = 15 'Ret IVA
Dim CveConceptoRetISR As Integer = 16 'Ret ISR
Dim CveConceptoDescuento As Integer = 24 'DSC
Dim CveConceptoRetIEPS As Integer = 25 'IEPS
Dim CveConceptoRetOtrosImpuestos As Integer = 27 'Otros Impuestos
Dim CveCreditoDetalle As Integer = -1
'Afectable con el tabpanel Contable
Dim CveProveedorLocal As Integer
Dim CveProveedorConcepto As Integer
Dim TipoCreditoInteres As Boolean = False
Dim ImporteIECredito As Decimal = 0
Dim SeContabiliza As Boolean = If(UsuarioActual.CveEmpresa.Contiene(119) AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ant"), False, True)
If RBLPago.SelectedValue = "1" Or RBLPago.SelectedValue = "3" Then
'Credito Proveedor
CveProveedorLocal = CveProveedor
CveProveedorConcepto = CveProveedor
Else
'cuando es contado
Select Case RBLContado.SelectedValue
Case "1", "6" 'Proveedores
CveProveedorLocal = CveProveedor
CveProveedorConcepto = CveProveedor
Case "2" ' F y E
CveProveedorLocal = CveProveedor
CveProveedorConcepto = CveProveedor
CveIE = DDlCheques.SelectedValue.ToEntero
Case "3" ' Doctos
CveProveedorConcepto = CveProveedor
If DdlTipoCredito.SelectedValue.ToEntero = 2 Then
CveProveedorLocal = CveProveedor
CveProveedorConcepto = CveProveedor
CveConceptoAfectacion = 59
CveCreditoDetalle = DdlCreditoDetalle.SelectedValue.ToEntero
ObjIE.UpdateCreditosDetalle(3, CveCreditoDetalle)
End If
Case "4" ' Deudores
CveProveedorLocal = CveProveedor
CveProveedorConcepto = DdlDeudor.SelectedValue.ToEntero
For Each row As GridViewRow In GvDeudores.Rows
If row.FCCheckBox("Chk").Checked Then
CveIE = row.DataKey("CveIE").ToString.ToEntero
Exit For
End If
Next
' CveConceptoAfectacionContado = 55
CveConceptoAfectacion = 37
Case "5" ' Acreedores
CveProveedorLocal = CveProveedor
CveProveedorConcepto = DdlAcreedor.SelectedValue.ToEntero
CveConceptoAfectacion = 41
If EmpresaPrueba Then
CveIE = If(DdlAcreedorDetalle.SelectedValue.ToEntero = -2, -1, DdlAcreedorDetalle.SelectedValue.ToEntero)
End If
End Select
End If
If RBLPago.SelectedValue.ToEntero = 4 Then
Dim TmpTotal As Decimal = TxtTotal.Text.ToDecimal
Dim TmpTotalCreditos As Decimal = 0
For Each GvRow As GridViewRow In GvCreditos.Rows
TmpTotalCreditos = TmpTotalCreditos + GvRow.FCTextBox("TxtCapital").Text.ToDecimal
TmpTotalCreditos = TmpTotalCreditos + GvRow.FCTextBox("TxtInteres").Text.ToDecimal
TmpTotalCreditos = TmpTotalCreditos + GvRow.FCTextBox("TxtAmbos").Text.ToDecimal
Next
If TmpTotalCreditos > TmpTotal Then
ErrorCredito = True
End If
For Each GvRow As GridViewRow In GvCreditos.Rows
Dim Capital As Decimal = GvRow.FCTextBox("TxtCapital").Text.Replace(",", "").ToDecimal
Dim Interes As Decimal = GvRow.FCTextBox("TxtInteres").Text.Replace(",", "").ToDecimal
Dim Ambos As Decimal = GvRow.FCTextBox("TxtAmbos").Text.Replace(",", "").ToDecimal
Dim CveCreditoDetalleTemp As Integer = GvRow.DataKey("CveCreditoDetalle").ToEntero
Dim CveCreditoTemp As Integer = GvRow.DataKey("CveCredito").ToEntero
Dim EstusTemp = GvRow.DataKey("Estatus").ToEntero
' Dim ImporteOpcionCompra As Decimal = GvRow.DataKey("ImporteOpcionCompra").ToDecimal
Dim Marcador As Decimal = GvRow.DataKey("Marcador").ToEntero
Dim CreditoEstatus As Integer = -1
If Capital > 0 Or Interes > 0 Or Ambos > 0 Then
If ObjIE.GetCreditosDetalle(CveCreditoTemp, -1) Then
Dim CveCompraCapital As Integer = -1
Dim CveCompraInteres As Integer = -1
' Dim ImporteIEMensualidad As Decimal = ObjIE.DtResultados.FiltroPrimeroValor("ImporteIE", $"CveCreditoDetalle = {CveCreditoDetalleTemp}").ToDecimal
CreditoEstatus = ObjIE.DtResultados.FiltroPrimeroValor("Estatus", $"CveCreditoDetalle = {CveCreditoDetalleTemp}").ToEntero
CveCompraCapital = ObjIE.DtResultados.FiltroPrimeroValor("CveCompra", $"CveCreditoDetalle = {CveCreditoDetalleTemp}").ToEntero
CveCompraInteres = ObjIE.DtResultados.FiltroPrimeroValor("CveCompraInteres", $"CveCreditoDetalle = {CveCreditoDetalleTemp}").ToEntero
CveCompraCapital = If(CveCompraCapital < 1, -1, CveCompraCapital)
CveCompraInteres = If(CveCompraInteres < 1, -1, CveCompraInteres)
TipoCreditoInteres = Boolean.Parse(ObjIE.DtResultados.FiltroPrimeroValor("TipoInteres", $"CveCreditoDetalle = {CveCreditoDetalleTemp}"))
ImporteIECredito = ObjIE.DtResultados.FiltroPrimeroValor("ImportePago", $"CveCreditoDetalle = {CveCreditoDetalleTemp}").ToDecimal
If Ambos > 0 Then
CveCompraCapital = CveCompra
CveCompraInteres = CveCompra
Capital = Ambos
Interes = Ambos
End If
If Capital > 0 Then
CveCompraCapital = CveCompra
End If
If Interes > 0 Then
CveCompraInteres = CveCompra
End If
If (CveCompraCapital > 0 And CveCompraInteres > 0) And EstusTemp = 2 Then
If EstusTemp = 2 Then
EstusTemp = 3
ElseIf EstusTemp = 1 Or EstusTemp = 4 Then
EstusTemp = 4
End If
ElseIf CveCompraCapital > 0 Or CveCompraInteres > 0 Then
If EstusTemp = 2 Then
EstusTemp = 2
ElseIf EstusTemp = 1 Or EstusTemp = 4 Then
EstusTemp = 4
End If
End If
If Not ObjIE.UpdateCreditosDetalle(CveCreditoDetalleTemp, "01/01/2000".ToDate, -1, -1, -1, -1, -1, -1, EstusTemp, CveCompra:=CveCompraCapital, CveCompraInteres:=CveCompraInteres, importeCapital:=Capital,
ImporteInteres:=Interes) Then
ErrorCredito = True
End If
Else
ErrorCredito = True
End If
End If
Next
End If
Dim TipoMovimientoCompra As Boolean = False
Dim TipoMovimientoImpuestos As Boolean = True
If DdlTipoComprobante.SelectedValue.Contiene("NC", "DEV") Then
CveConceptoAfectacion = 18 'Devolución del Proveedor (NC)
TipoMovimientoCompra = Not TipoMovimientoCompra
TipoMovimientoImpuestos = Not TipoMovimientoImpuestos
End If
If EmpresaPrueba Then 'Empresa Prueba
Dim PorcentajePagos As Decimal = 0
Dim sumaPagos As Decimal = 0
Dim tipoCambioActual As Decimal
Dim alertaContabilizacion As String = "Se enviaron correctamente las siguientes pólizas:<br><br>"
Dim idCuentaContabilizacion As Long = 1
Dim CveCuentaContabilizacion As Long = 1
Dim FechaMovimiento As Date = TxtFecha.Text.ToDate
Dim DT As DataTable = Nothing
Dim CuentasContablesInvalidas As New StringBuilder
Dim ConceptoPersonal As String = ""
Dim IdCtaIVAXAcreditar As Integer = 0
' Dim IdCtaIVAAcreditable As Integer = 0
Dim GuardoConcepto18 As Boolean = False
If GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=PorcentajeIVA).Rows.Count > 0 Then
IdCtaIVAXAcreditar = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=PorcentajeIVA).Rows(0)("IdCtaIVAXAcreditar").ToString.ToEntero
' IdCtaIVAAcreditable = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=PorcentajeIVA).Rows(0)("IdCtaIVAAcreditable").ToString.ToEntero
End If
'********************** Variables '**********************
'****** Pagos
'Bancos (30)
Dim importeBanco As Decimal = 0
If CveIE > 0 AndAlso RBLPago.SelectedValue.ToEntero = 2 AndAlso RBLContado.SelectedValue = "1" AndAlso (Not DivTarjeta.Visible Or DdlTarjeta.SelectedValue.ToEntero = -1) Then
importeBanco = TxtDocumentoImporte.Text.ToDecimal
sumaPagos += importeBanco
End If
'Caja Chica (30)
Dim importeCajaChica As Decimal = 0
If CveIE > 0 AndAlso RBLPago.SelectedValue.ToEntero = 2 AndAlso RBLContado.SelectedValue = "6" Then
importeCajaChica = TxtDocumentoImporteCaja.Text.ToDecimal
sumaPagos += importeCajaChica
End If
'Funcionarios y Empleados (29)
Dim importeFE As Decimal = 0
If CveIE > 0 AndAlso RBLPago.SelectedValue.ToEntero = 2 AndAlso RBLContado.SelectedValue = "2" Then
ViewState("CvePersonal") = DdlFuncionarioEmpleado.SelectedValue.ToEntero
ConceptoPersonal = DdlFuncionarioEmpleado.SelectedItem.ToString
importeFE = TxtDocumentoImporteFE.Text.ToDecimal
sumaPagos += importeFE
End If
'Deudores (37)
Dim importeDD As Decimal = 0
Dim OtrosGastosIngresos As Decimal = 0
If CveIE > 0 AndAlso RBLPago.SelectedValue.ToEntero = 2 AndAlso RBLContado.SelectedValue = "4" Then
ConceptoPersonal = DdlDeudor.SelectedItem.ToString
importeDD = TxtContadoDeudor.Text.ToDecimal
OtrosGastosIngresos = TxtDeudoresOtrosGastosIngresos.Text.ToDecimal
sumaPagos += importeDD
End If
'Acreedores (41) SinTarjeta
Dim importeAcreedores As Decimal = 0
If (CveIE > 0 Or DdlAcreedorDetalle.SelectedValue.ToEntero = -2) AndAlso RBLPago.SelectedValue.ToEntero = 2 AndAlso RBLContado.SelectedValue = "5" Then
ConceptoPersonal = DdlAcreedor.SelectedItem.ToString
importeAcreedores = TxtContadoAcreedor.Text.ToDecimal
sumaPagos += importeAcreedores
End If
'Acreedores (42) ConTarjeta
Dim importeAcreedoresTarjeta As Decimal = 0
If CveIE > 0 AndAlso RBLPago.SelectedValue.ToEntero = 2 AndAlso RBLContado.SelectedValue = "1" AndAlso DivTarjeta.Visible AndAlso DdlTarjeta.SelectedValue.ToEntero > 0 Then
ConceptoPersonal = DdlTarjeta.SelectedItem.ToString
importeAcreedoresTarjeta = TxtDocumentoImporte.Text.ToDecimal
sumaPagos += importeAcreedoresTarjeta
End If
'Creditos/Documentos (59)
Dim importeCreditos As Decimal = 0
Dim CveIECreditos = -1
If RBLPago.SelectedValue.ToEntero = 2 AndAlso RBLContado.SelectedValue = "3" AndAlso DdlTipoCredito.SelectedValue.ToEntero = 2 Then
If ObjIE.GetCreditosDetalle(DdlCredito.SelectedValue.ToEntero, -1) Then
CveIECreditos = ObjIE.DtResultados.FiltroPrimero($"CveCreditoDetalle = {DdlCreditoDetalle.SelectedValue.ToEntero}")("CveIE").ToString.ToEntero
End If
ConceptoPersonal = DdlCredito.SelectedItem.ToString
importeCreditos = TxtTotal.Text.ToDecimal
sumaPagos += importeCreditos
End If
PorcentajePagos = If(TxtTotal.Text.ToDecimal > 0, sumaPagos / TxtTotal.Text.ToDecimal, 0)
'****** Acreditables
'IVA Acreditable (19)
Dim importeIVAAcreditable As Decimal = 0
importeIVAAcreditable = TxtIVA.Text.ToDecimal * PorcentajePagos
'IEPS Acreditable (26)
Dim ImporteIEPSAcreditable As Decimal = 0
ImporteIEPSAcreditable = TxtIEPS.Text.ToDecimal * PorcentajePagos
'RetIVA Acrediable (22)
Dim importeRetIVAAcreditable As Decimal = 0
importeRetIVAAcreditable = TxtRetIVA.Text.ToDecimal * PorcentajePagos
'RetISR Acreditable (23)
Dim importeRetISRAcreditable As Decimal = 0
importeRetISRAcreditable = TxtRetISR.Text.ToDecimal * PorcentajePagos
'****** Movimientos Independientes
'Pago Proveedores (17)
Dim importePagoProv As Decimal = 0
importePagoProv = sumaPagos
'Proveedores (5)
Dim importeProv As Decimal = 0
importeProv = TxtTotal.Text.ToDecimal
'Nota de Credito (18)
Dim importeNC As Decimal = 0
If DdlTipoComprobante.SelectedValue.Contiene("NC", "DEV") Then
importeNC = TxtTotal.Text.ToDecimal
End If
'**************************************************************************************************************************
Dim TipoCambioCompra As Decimal = 1
TipoCambioCompra = GlobalTipoCambio(FechaMovimiento).ToString.ToDecimal
TipoCambioCompra = If(DivTC.Visible, TipoCambio, TipoCambioCompra)
If CveMonedaPago = 1 AndAlso DdlMoneda.SelectedValue.ToEntero = 1 Then
TipoCambioCompra = 1
End If
If DdlMoneda.SelectedValue.ToString.ToEntero = 2 Then
tipoCambioActual = GlobalTipoCambio(FechaMovimiento).ToString.ToDecimal
tipoCambioActual = If(DivTC.Visible, TipoCambio, tipoCambioActual)
Else
tipoCambioActual = 1
End If
'CASO ESPECIAL CREDITOS
If CveIECreditos > 0 Then
CveIE = CveIECreditos
'Dim CveIEProvisional = CveIE
End If
If ObjConta.GetPlantillaConceptos(UsuarioActual.CveEmpresa, CvePlantillaPrePoliza) Then
Dim DTPlatilla As New DataTable
DTPlatilla = ObjConta.DtResultados
For Each Row As DataRow In DTPlatilla.Rows
Dim CveSubProyectoInsertar As Integer = -1
Dim ConceptoContable As Integer = Row("CveConcepto").ToString.ToEntero
Dim TipoMovimiento As Boolean = If(Row("TipoMovto").ToString = "True", True, False)
Dim importeMovimiento As Decimal = 0
Dim IdCtaContable As Integer = 0
Dim Concepto As String = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, ConceptoContable, NombreProveedor, $"{TxtSerie.Text}-{TxtFolio.Text}", If(TxtDocumentoFolio.Visible, TxtDocumentoFolio.Text, If(TxtDocumentoFolioCaja.Visible, TxtDocumentoFolioCaja.Text, ConceptoPersonal)))
Dim importeMN As Decimal = 0
Dim Multiplicador As Integer = Row("Multiplicador").ToString.ToEntero ' If(Row("Multiplicador").ToString.ToEntero = 1, -1, 1)
Dim Referencia As String = $"{TxtSerie.Text}-{TxtFolio.Text}" ' concatenation interpolation
Dim PorcentajeImpuesto As Decimal = 0
CveConceptoOriginal = ConceptoContable
Select Case ConceptoContable
Case 17 'Pago Proveedores
If CveTipoConcepto = 2 Then ConceptoContable = 308 'cuando es acreedor
If CveMoneda <> 1 Then
Select Case ConceptoContable
Case 17
ConceptoContable = 312
Case 308
ConceptoContable = 309
Case Else
End Select
End If
importeMovimiento = importePagoProv
If CveMonedaPago = 2 AndAlso DdlMoneda.SelectedValue.ToEntero = 1 Then
importeMovimiento = importeMovimiento / TipoCambioCompra
End If
importeMN = importeMovimiento * TipoCambioCompra * Multiplicador
IdCtaContable = If(CveTipoConcepto = 2, CtaProveedorAcreedores, CtaProveedor)
If RBLPago.SelectedValue.ToEntero = 4 And EstatusCredito.Contiene(2, 102) Then 'SI ES CRÉDITO Y ESTA PAGADO
For Each Row2 As DataRow In TmpDT.Rows
importeMovimiento = TxtTotal.Text.ToDecimal 'TmpDT.SUM("Total", String.Format("ISNULL(TipoAF, 0) <> 2 And ISNULL(CveAlmacen, 0) = 0 And ISNULL(AplicaCostoIndirecto, 0) <> 1 And CveClasificacion = {0} And CveSubProyecto = {1} And ISNULL(CveTipoGasto, 0) = {2} Then", Row2("CveClasificacion").ToString.ToEntero, Row2("CveSubProyecto").ToString.ToEntero, Row2("CveTipoGasto").ToString.ToEntero)).ToString.ToDecimal
importeMN = importeMovimiento * tipoCambioActual * Multiplicador
'CLASIFICACION
If UsuarioActual.Empresa.TipoContabilidad = 2 AndAlso Row2("CveClasificacion").ToString.ToEntero > 0 Then
If ObjConta.GetRetCuenta(6, Row2("CveClasificacion").ToString.ToEntero, CveSubProyecto:=Row2("CveSubProyecto").ToString.ToEntero) Then
If ObjConta.DtResultados.Rows.Count > 0 AndAlso ObjConta.DtResultados.Rows(0)("IdCuentaGasto").ToString.ToEntero > 0 Then
IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaGasto").ToString.ToEntero
Else
IdCtaContable = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaGasto", String.Format("CveClasificacion = {0}", Row2("CveClasificacion"))).ToString.ToEntero
End If
End If
'AGREGA MOVIMIENTO
If importeMovimiento <> 0 Then
'Conta ContPAQ
If IdCtaContable = 0 Then
CuentasContablesInvalidas.Append("<br>" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 6))("ConceptoContable").ToString)
idCuentaContabilizacion = 0
End If
End If
End If
Next
Dim CveClasificacionDT As Integer = -1
Dim CveSubProyectoDT As Integer = -1
Dim CveTipoGastoDT As Integer = -1
If TmpDT.Rows.Count > 0 Then
CveClasificacionDT = TmpDT(0)("CveClasificacion").ToString.ToEntero
CveSubProyectoDT = TmpDT(0)("CveSubProyecto").ToString.ToEntero
CveTipoGastoDT = TmpDT(0)("CveTipoGasto").ToString.ToEntero
End If
Concepto = $"{NombreProveedor} {TxtSerie.Text} - {TxtFolio.Text}"
Dim ImporteSubCre As Decimal = TxtSubTotal.Text.ToDecimal
Dim ImporteSubCreMN As Decimal = TxtSubTotal.Text.ToDecimal * tipoCambioActual
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, ImporteSubCre, ImporteSubCreMN, 6, Referencia, Concepto, IdCtaContable, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveIE:=CveIE, CveCreditoDetalle:=CveCreditoDetalle, CveClasificacion:=CveClasificacionDT, CveSubProyecto:=CveSubProyectoDT, ImporteME:=If(tipoCambioActual = 1, 0, ImporteSubCre), CveTipoGasto:=CveTipoGastoDT, TipoCambio:=tipoCambioActual, Contabilizable:=SeContabiliza) Then
ErrorPrepoliza = True
End If
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, importeMovimiento, importeMN, 41, Referencia, Concepto, CtaProveedorAcreedores, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveIE:=CveIE, CveCreditoDetalle:=CveCreditoDetalle, CveClasificacion:=CveClasificacionDT, CveSubProyecto:=CveSubProyectoDT, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), CveTipoGasto:=CveTipoGastoDT, TipoCambio:=tipoCambioActual, Contabilizable:=SeContabiliza) Then
ErrorPrepoliza = True
End If
If importeMovimiento <> 0 Then
Dim Pago As New CompraPago
Pago.ImportePago = importeMovimiento
Pago.CveIE = CveIE
Pago.CveMonedaPago = 1
Pago.CveCompraAmortizacion = -1
Pago.CveCreditoDetalle = CveCreditoDetalle
'Pago.OtroGastoIngreso = OtrosGastosIngresos
ErrorMovtosCxP = AplicaPrePolizaPagoCompra(CompraActual, Pago, CvePrePoliza, ObjConta)
End If
'If TipoCreditoInteres Then
' Dim importeMovimientoIn As Decimal = ImporteIECredito - importeMovimiento
' Dim importeMNIn As Decimal = importeMovimientoIn * tipoCambioActual * Multiplicador
' If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, importeMovimientoIn, importeMNIn, 41, Referencia, Concepto, CtaProveedorAcreedores, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveIE:=CveIE, CveCreditoDetalle:=CveCreditoDetalle, CveClasificacion:=CveClasificacionDT, CveSubProyecto:=CveSubProyectoDT, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimientoIn), CveTipoGasto:=CveTipoGastoDT, TipoCambio:=tipoCambioActual, Contabilizable:=SeContabiliza) Then
' ErrorPrepoliza = True
' End If
' If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, importeMovimientoIn, importeMNIn, 50, Referencia, Concepto, ViewState("IdCtaContDocsXPagar").ToString.ToEntero(), CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveIE:=CveIE, CveCreditoDetalle:=CveCreditoDetalle, CveClasificacion:=CveClasificacionDT, CveSubProyecto:=CveSubProyectoDT, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimientoIn), CveTipoGasto:=CveTipoGastoDT, TipoCambio:=tipoCambioActual, Contabilizable:=SeContabiliza) Then
' ErrorPrepoliza = True
' End If
'End If
End If
importeMovimiento = 0 : importeMN = 0
If TipoCambioCompra > 1 AndAlso DdlMoneda.SelectedValue.ToEntero <> 1 Then Concepto += $" TC{TipoCambioCompra} ${importeMovimiento.FormatoNumero(2)}"
If TipoCambioCompra = 1 Or DdlMoneda.SelectedValue.ToEntero = 1 Then
IdCtaContable = CtaProveedor
importeMovimiento = importeMN
Else
IdCtaContable = CtaProveedorComplementaria
If importeMovimiento <> 0 AndAlso (IdCtaContable > 0) Then 'Cuando tiene complementaria lo dividimos en dos
Dim CveConceptoContableComplementaria As Integer = 206
If CveTipoConcepto = 2 Then CveConceptoContableComplementaria = 310 'cuando es acreedor
importeMN = importeMovimiento
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, importeMovimiento * TipoCambioCompra - importeMovimiento, Referencia, CveConceptoContableComplementaria, Concepto, FechaMovimiento, IdCtaContable, -1, CveIE, CveCompra:=CveCompra, CveProveedor:=CveProveedor, ImporteMX:=importeMovimiento * TipoCambioCompra - importeMovimiento, ImporteME:=importeMovimiento, Contabilizable:=SeContabiliza, TipoCambio:=TipoCambioCompra) Then
ErrorPrepoliza = True
End If
End If
IdCtaContable = CtaProveedorExtranjera
End If
Case 30 'Bancos
importeMovimiento = importeBanco + importeCajaChica 'Uno de los dos debe ser 0
If CveMonedaPago = 2 AndAlso DdlMoneda.SelectedValue.ToEntero = 1 Then
importeMovimiento = importeMovimiento / TCPago
End If
importeMN = importeMovimiento * TCPago * Multiplicador
If TCPago > 1 AndAlso CveMonedaPago <> 1 Then Concepto += $" TC{TCPago} ${importeMovimiento.FormatoNumero(2)}"
If TCPago = 1 Or CveMonedaPago = 1 Then
IdCtaContable = IdCuentaBancaria
Else
IdCtaContable = IdCuentaBancariaComplementaria
If importeMovimiento <> 0 AndAlso (IdCtaContable > 0) Then 'Cuando tiene complementaria lo dividimos en dos
importeMN = importeMovimiento
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, importeMovimiento * TCPago - importeMovimiento, Referencia, 204, Concepto, FechaMovimiento, IdCtaContable, -1, CveIE, CveProveedor:=CveProveedor, ImporteMX:=importeMovimiento * TCPago - importeMovimiento, ImporteME:=importeMovimiento, Contabilizable:=SeContabiliza, TipoCambio:=TCPago) Then
ErrorPrepoliza = True
End If
End If
IdCtaContable = IdCuentaBancaria
End If
If importeMovimiento <> 0 Then
Dim Pago As New CompraPago
Pago.ImportePago = importeMovimiento
Pago.CveIE = CveIE
Pago.CveMonedaPago = 1
Pago.CveCompraAmortizacion = -1
'Pago.CveConceptoPago = CveConceptoPago
ErrorMovtosCxP = AplicaPrePolizaPagoCompra(CompraActual, Pago, CvePrePoliza, ObjConta)
End If
Case 14 'IVA X Acreditar
importeMovimiento = CompraActual.IVA
importeMN = (importeMovimiento * tipoCambioActual * Multiplicador).RoundSQL
If tipoCambioActual > 1 Then Concepto += $" TC{tipoCambioActual} ${importeMovimiento.FormatoNumero(2)}"
PorcentajeImpuesto = PorcentajeIVA
IdCtaContable = If(IdCtaIVAXAcreditar > 0, IdCtaIVAXAcreditar, 0)
If chkImportacion.Checked Then
ConceptoContable = 287
End If
If UsuarioActual.Empresa.TipoContabilidad = 2 AndAlso ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) And Not IdCtaContable > 0 Then
If ObjConta.DtResultados.Rows.Count > 0 Then
IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaIVAxAcreditar").ToString.ToEntero
End If
End If
'si aplica NC sobre mov de almacen, el impuesto lo toma de la Factura.para la consideracion de mcia en tránsito
If ChkNCInvNC.Checked And CveMoneda > 1 AndAlso importeMovimiento > 0 Then
Dim diferenciaTransito As Decimal = 0
For Each Gvr As GridViewRow In GVNCInvAlmacen.Rows
If Gvr.FCTextBox("TxtCantidadNCInv").Text.ToDouble > 0 Then
'Dim DifTC As Decimal = tipoCambioActual - Gvr.DataKey("TipoCambio").ToDecimal
'diferenciaTransito = DifTC * (Gvr.DataKey("IVA").ToDecimal / Gvr.FCTextBox("TxtCantidadNCInv").Text.ToDecimal)
'diferenciaTransito += DifTC * (Gvr.DataKey("IEPSPS").ToDecimal / Gvr.FCTextBox("TxtCantidadNCInv").Text.ToDecimal)
importeMN = (Gvr.DataKey("IVA").ToDecimal.RoundSQL * Gvr.DataKey("TipoCambio").ToDecimal * Multiplicador).RoundSQL
'se registra por cada compra relacionada
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, importeMN, Referencia, 14, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveCompraAmortizacion:=Gvr.DataKey("CveCompra").ToEntero, CveProveedor:=CveProveedorConcepto, ImporteMX:=importeMN, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), TipoCambio:=Gvr.DataKey("TipoCambio").ToDecimal, PorcentajeImpuesto:=PorcentajeImpuesto, Contabilizable:=SeContabiliza) Then
ErrorPrepoliza = True
End If
End If
Next
importeMovimiento = 0
importeMN = 0
End If
Case 25 'IEPS X Acreditar
If Not DdlTipoComprobante.SelectedValue.Contiene("Ant") Then
CveSubProyectoInsertar = CveSubProyecto
importeMovimiento = CompraActual.IEPS
importeMN = Math.Round(importeMovimiento, 2) * tipoCambioActual * Multiplicador
If tipoCambioActual > 1 Then Concepto += $" TC{tipoCambioActual} ${importeMovimiento.FormatoNumero(2)}"
If UsuarioActual.Empresa.TipoContabilidad = 2 AndAlso ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then
If ObjConta.DtResultados.Rows.Count > 0 Then
IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaIEPSxAcreditar").ToString.ToEntero
End If
End If
End If
Case 15 'RetIVA X Acreditar Honorarios/Serv. Prof.
If Not DdlTipoComprobante.SelectedValue.Contiene("Ant") Then
If DdlRetIVAConcepto.Items.Count > 0 AndAlso DdlRetIVAConcepto.SelectedValue.ToEntero() > 0 Then
Dim Funcionalidad As Integer = 0
If DdlRetIVAConcepto.SelectedValue.ToEntero = 1 Then
Funcionalidad = 307
ConceptoContable = 15
ElseIf DdlRetIVAConcepto.SelectedValue.ToEntero = 2 Then
Funcionalidad = 309
ConceptoContable = 183
ElseIf DdlRetIVAConcepto.SelectedValue.ToEntero = 3 Then
Funcionalidad = 311
ConceptoContable = 185
ElseIf DdlRetIVAConcepto.SelectedValue.ToEntero = 4 Then
Funcionalidad = 313
ConceptoContable = 248
ElseIf DdlRetIVAConcepto.SelectedValue.ToEntero = 5 Then
Funcionalidad = 578
ConceptoContable = 285
ElseIf DdlRetIVAConcepto.SelectedValue.ToEntero = 6 Then
ConceptoContable = 333
End If
importeMovimiento = CompraActual.RetIVA
importeMN = (importeMovimiento * tipoCambioActual * Multiplicador).RoundSQL
If tipoCambioActual > 1 Then Concepto += $" TC{tipoCambioActual} ${importeMovimiento.FormatoNumero(2)}"
If UsuarioActual.Empresa.TipoContabilidad = 2 Then
If CtaProveedorRetIVA > 0 Then
IdCtaContable = CtaProveedorRetIVA
ElseIf UsuarioActual.Empresa.Funcionalidad(Funcionalidad).ToEntero > 0 Then
IdCtaContable = UsuarioActual.Empresa.Funcionalidad(Funcionalidad).ToEntero
Else
If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then
If ObjConta.DtResultados.Rows.Count > 0 Then
IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacion").ToString.ToEntero
End If
End If
End If
End If
End If
End If
Case 16 'Ret ISR X Acreditar
If Not DdlTipoComprobante.SelectedValue.Contiene("Ant") Then
If DdlRetISRConcepto.Items.Count > 0 AndAlso DdlRetISRConcepto.SelectedValue.ToEntero > 0 Then
Dim funcionalidad As Integer = 0
If DdlRetISRConcepto.SelectedValue.ToEntero = 1 Then
funcionalidad = 315
ConceptoContable = 16
ElseIf DdlRetISRConcepto.SelectedValue.ToEntero = 2 Then
funcionalidad = 317
ConceptoContable = 243
ElseIf DdlRetISRConcepto.SelectedValue.ToEntero = 3 Then
funcionalidad = 349
ConceptoContable = 327
End If
importeMovimiento = CompraActual.RetISR
importeMN = (importeMovimiento * tipoCambioActual * Multiplicador).RoundSQL
If tipoCambioActual > 1 Then Concepto += $" TC{tipoCambioActual} ${importeMovimiento.FormatoNumero(2)}"
If UsuarioActual.Empresa.TipoContabilidad = 2 Then
If CtaProveedorRetISR > 0 Then
IdCtaContable = CtaProveedorRetISR
ElseIf UsuarioActual.Empresa.Funcionalidad(funcionalidad).ToEntero > 0 Then
IdCtaContable = UsuarioActual.Empresa.Funcionalidad(funcionalidad).ToEntero
Else
If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then
If ObjConta.DtResultados.Rows.Count > 0 Then
IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacion").ToString.ToEntero
End If
End If
End If
End If
End If
End If
Case 64 'Ganancia
CveSubProyectoInsertar = CveSubProyecto
If CveSubProyectoInsertar <= 0 Then
ErrorPrepoliza = True
Alert("Concepto ganancia cambiaria sin sub proyecto", TipoMensaje.MsgAdvertencia)
End If
If TCPago > 0 AndAlso TCPago <> 1 AndAlso TxtFechaPago.Text <> TxtFecha.Text Then
If TipoCambioCompra > TCPago Then
ConceptoContable = 64
IdCtaContable = UsuarioActual.Empresa.IdCuentaGananciaCambiaria
TipoMovimiento = True
Else
ConceptoContable = 65
IdCtaContable = UsuarioActual.Empresa.IdCuentaPerdidaCambiaria
TipoMovimiento = False
End If
If TCPago <> TipoCambioCompra Then
importeMovimiento = Math.Abs(TCPago - TipoCambioCompra) * importePagoProv
importeMovimiento -= Math.Abs(TCPago - TipoCambioCompra) * importeIVAAcreditable
importeMovimiento += Math.Abs(TCPago - TipoCambioCompra) * importeRetIVAAcreditable
importeMovimiento += Math.Abs(TCPago - TipoCambioCompra) * importeRetISRAcreditable
importeMN = importeMovimiento
End If
Else
importeMovimiento = 0
End If
Case 6 'Compra
Dim AgregaMercanciaInventario As Boolean = UsuarioActual.Empresa.UsaInventarios AndAlso Not UsuarioActual.Empresa.Funcionalidad(126) = "1"
Dim RegistraConcepto225 As Boolean = UsuarioActual.Empresa.UsaInventarios AndAlso DdlTipoComprobante.SelectedValue.Contiene("NC", "DEV") AndAlso Not UsuarioActual.Empresa.Funcionalidad(126) = "1"
Dim Insertado205 As Boolean = False
If RBLPago.SelectedValue.ToEntero = 4 Then
Exit Select 'Es credito el concepto 6 se agrega en CASE 17
End If
Dim DifSubTotatles As Decimal = 0D
If CveCompraRefacturacion > 0 Then
DifSubTotatles = Math.Abs(SubTotalRefacturacion - TxtSubTotal2.Text.ToDecimal)
End If
If DifSubTotatles > 0 Or (Not CveCompraRefacturacion > 0 OrElse (ChkRefacNC.Checked)) Then
'AF TipoAF 2 Es para las compras
DT = TmpDT.FiltraParametros("ISNULL(TipoAF,0) = 2 And ISNULL(AplicaCostoIndirecto,0) <> 1 ")
If DT.Rows.Count > 0 AndAlso Not DdlTipoComprobante.SelectedValue.Contiene("NC", "DEV", "Ant") Then
For Each Row2 As DataRow In DT.Rows
importeMovimiento = If(ListaDocumentos IsNot Nothing AndAlso ListaDocumentos.Count > 0 AndAlso ArrAnticipos IsNot Nothing AndAlso ArrAnticipos.Count > 0 AndAlso TxtTotal.Text.ToDecimal = 0, Row2("ImporteSinImpuestos").ToString.ToDecimal, Row2("Total").ToString.ToDecimal)
importeMN = importeMovimiento * tipoCambioActual * Multiplicador
If UsuarioActual.Empresa.TipoContabilidad = 2 AndAlso ObjConta.GetRetCuenta(49, Row2("CveActivoFijo").ToString.ToEntero) Then
If ObjConta.DtResultados.Rows.Count > 0 Then
IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCtaContActivoFijo").ToString.ToEntero
End If
End If
If importeMovimiento <> 0 Then
'Conta ContPAQ
If IdCtaContable = 0 Then
CuentasContablesInvalidas.Append("<br>" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 49))("ConceptoContable").ToString)
idCuentaContabilizacion = 0
End If
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, importeMovimiento, Row2("CodAF").ToString, 49, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveActivoFijo:=Row2("CveActivoFijo").ToString.ToEntero, CveIE:=CveIE, CvePersonal:=CvePersonal, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMN, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), TipoCambio:=tipoCambioActual, Contabilizable:=SeContabiliza) Then
ErrorPrepoliza = True
End If
End If
Next
End If
'LIMPIA
importeMovimiento = 0
IdCtaContable = 0
'COSTO ALMACEN
Dim DtAlmacenes = GlobalDTAlmacen(UsuarioActual.CveEmpresa)
If UsuarioActual.Empresa.UsaInventarios AndAlso Not UsuarioActual.Empresa.Funcionalidad(126) = "1" Then
DT = TmpDT.FiltraParametros("ISNULL(TipoAF,0) <> 2 And ISNULL(CveAlmacen,0) > 0", "", {"CveAlmacen"})
'RECORREMOS PARA DETECTAR LA MODALIDAD DEL ALMACEN, EN CASO DE SER SOLO EXISTENCIA LIMPIAMOS CVEALMACEN
'SI LA COMPRA ES DE TIPO GASTO CON ALMACEN DEBE REGISTRAR MOVIMIENTO
Dim AlmacenSoloExistencia As Boolean = False
If DdlTipoCompra.SelectedValue <> "10" Then
For Each Dr As DataRow In DT.Rows
If DtAlmacenes.FiltroPrimeroValor("Modalidad", $"CveAlmacen = {Dr("CveAlmacen").ToString.ToEntero}").ToString = "Solo Existencia" Then
Dr("CveAlmacen") = 0
AlmacenSoloExistencia = True
End If
Dr.AcceptChanges()
Next
End If
DT.AcceptChanges()
DT = DT.FiltraParametros("ISNULL(CveAlmacen,0) > 0")
If DT.Rows.Count > 0 AndAlso Not DdlTipoComprobante.SelectedValue.Contiene("NC", "DEV", "Ant") Then
'SI ES GASTO CON ALMACEN
If DdlTipoCompra.SelectedValue = "10" Then
For Each RowDetalle As DataRow In TmpDT.FiltraParametros("ISNULL(TipoAF,0) <> 2 And ISNULL(CveAlmacen,0) > 0", "", {"CveAlmacen", "CveClasificacion", "CveSubProyecto"}).Rows
importeMovimiento = TmpDT.SUM(If(ListaDocumentos IsNot Nothing AndAlso ListaDocumentos.Count > 0 AndAlso ArrAnticipos IsNot Nothing AndAlso ArrAnticipos.Count > 0 AndAlso TxtTotal.Text.ToDecimal = 0, "ImporteSinImpuestos", "Total"), $"CveAlmacen = {RowDetalle("CveAlmacen")}").ToString.ToDecimal + TmpDT.SUM("CostoIndirectoAlmacen", $"CveAlmacen = {RowDetalle("CveAlmacen")}").ToString.ToDecimal 'Row2("Total").ToString.ToDecimal + Row2("CostoIndirectoAlmacen").ToString.ToDecimal
importeMN = importeMovimiento * tipoCambioActual * Multiplicador
If UsuarioActual.Empresa.TipoContabilidad = 2 Then
If ObjConta.GetRetCuenta(6, RowDetalle("CveClasificacion").ToString().ToEntero()) Then
If ObjConta.DtResultados.Rows.Count > 0 Then
IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaGasto").ToString.ToEntero
End If
End If
End If
If importeMN <> 0 Then
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, importeMN, Referencia, 6, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveIE:=CveIE, CvePersonal:=CvePersonal, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMN, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), TipoCambio:=tipoCambioActual,
CveClasificacion:=RowDetalle("CveClasificacion").ToString().ToEntero(), CveSubProyecto:=RowDetalle("CveSubProyecto").ToString().ToEntero(), Contabilizable:=SeContabiliza) Then
ErrorPrepoliza = True
End If
End If
Next
End If
For Each Row2 As DataRow In DT.Rows
importeMovimiento = TmpDT.SUM(If(ListaDocumentos IsNot Nothing AndAlso ListaDocumentos.Count > 0 AndAlso ArrAnticipos IsNot Nothing AndAlso ArrAnticipos.Count > 0 AndAlso TxtTotal.Text.ToDecimal = 0, "ImporteSinImpuestos", "Total"), $"CveAlmacen = {Row2("CveAlmacen")}").ToString.ToDecimal + TmpDT.SUM("CostoIndirectoAlmacen", $"CveAlmacen = {Row2("CveAlmacen")}").ToString.ToDecimal 'Row2("Total").ToString.ToDecimal + Row2("CostoIndirectoAlmacen").ToString.ToDecimal
importeMN = importeMovimiento * tipoCambioActual * Multiplicador
If UsuarioActual.Empresa.TipoContabilidad = 2 Then
If ObjConta.GetRetCuenta(68, GvInv.HeaderRow.FCDropDownList("ddlAlmacen").SelectedValue.ToString.ToEntero) Then
If ObjConta.DtResultados.Rows.Count > 0 Then
IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCtaContable").ToString.ToEntero
End If
End If
'Conta ContPAQ
If IdCtaContable = 0 Then
CuentasContablesInvalidas.Append("<br>" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 68))("ConceptoContable").ToString)
idCuentaContabilizacion = 0
End If
End If
If importeMN <> 0 Then
'SI ES GASTO CON ALMACEN NO DEBE CONTABILIZAR CONCEPTO 68
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, importeMN, Referencia, 68, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveIE:=CveIE, CvePersonal:=CvePersonal, CveMovimientoAlmacen:=CveMovimientoInventario, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMN, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), TipoCambio:=tipoCambioActual, Contabilizable:=If(DdlTipoCompra.SelectedValue = "10", False, SeContabiliza)) Then
ErrorPrepoliza = True
End If
'SI ES GASTO CON ALMACEN REGISTRA EL CONCEPTO 95
If DdlTipoCompra.SelectedValue = "10" Then
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, Not TipoMovimiento, importeMN, Referencia, 95, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveIE:=CveIE, CvePersonal:=CvePersonal, CveMovimientoAlmacen:=CveMovimientoInventario, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMN, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), TipoCambio:=tipoCambioActual, Contabilizable:=False) Then
ErrorPrepoliza = True
End If
End If
' si agrego en almacen, ya no se ocupa algun concepto puente
AgregaMercanciaInventario = False
End If
Next
End If
End If
'LIMPIA
importeMovimiento = 0
IdCtaContable = 0
'End If
Dim CostoIndirectoAcum176 As Decimal = 0
'INV [MERCANCIA RECIBIDA POR ADELANTADO (OC) | MERCANCIA PENDIENTE POR RECIBIR (COMPRA) ]
If AgregaMercanciaInventario AndAlso Not DdlTipoComprobante.SelectedValue.Contiene("NC", "DEV", "Ant") AndAlso CveConceptoContableAlmacen.Contiene(205, 176, 237, 240) Then
importeMovimiento = TmpDT.SUM(If(ListaDocumentos IsNot Nothing AndAlso ListaDocumentos.Count > 0 AndAlso ArrAnticipos IsNot Nothing AndAlso ArrAnticipos.Count > 0 AndAlso TxtTotal.Text.ToDecimal = 0, "ImporteSinImpuestos", "Total"), $"ISNULL(TipoAF,0) <> 2 And ISNULL(CveAlmacen,0) = 0 And (ISNULL(CveTipoPS,0) = 2 Or (ISNULL(CveTipoPS,0) = 1 And ISNULL(AplicaCostoIndirecto,0) = 1))").ToString.ToDecimal
importeMN = importeMovimiento * tipoCambioActual * Multiplicador
Dim ConceptoContabilizacion = 205
Dim ConceptoContabilizacionME = -1
Dim IdCtaContableME = -1
Dim ConceptoContabilizacionMEComp = -1
Dim IdCtaContableMEComp = -1
If OCVinculada Or CveConceptoContableAlmacen.Contiene(237, 240) Then
ConceptoContabilizacion = CveConceptoContableAlmacen
End If
Dim UsaComplementariaFleteImportaciones As Boolean = False
'DEBE METER EL CONCEPTO DE COMPRAS SI EL TIPO ES GASTO CON ALMACEN
If DdlTipoCompra.SelectedValue = "10" Then
ConceptoContabilizacion = 6
End If
Select Case ConceptoContabilizacion
Case 6
importeMovimiento = TmpDT.SUMD(If(ListaDocumentos IsNot Nothing AndAlso ListaDocumentos.Count > 0 AndAlso ArrAnticipos IsNot Nothing AndAlso ArrAnticipos.Count > 0 AndAlso TxtTotal.Text.ToDecimal = 0, "ImporteSinImpuestos", "Total"))
importeMN = importeMovimiento * tipoCambioActual * Multiplicador 'TIENE QUE TENER EL IMPORTEMN IGUAL AL IMPORTEMOVIMIENTO PORQUE NO TOMA EN CUENTA SI UN PRODUCTO ES TIPO SERVICIO
Case 176
ConceptoContabilizacionME = 228
ConceptoContabilizacionMEComp = 229
Case 205
ConceptoContabilizacionME = 230
ConceptoContabilizacionMEComp = 231
importeMovimiento = TmpDT.SUMD(If(ListaDocumentos IsNot Nothing AndAlso ListaDocumentos.Count > 0 AndAlso ArrAnticipos IsNot Nothing AndAlso ArrAnticipos.Count > 0 AndAlso TxtTotal.Text.ToDecimal = 0, "ImporteSinImpuestos", "Total"))
importeMN = importeMovimiento * tipoCambioActual * Multiplicador 'TIENE QUE TENER EL IMPORTEMN IGUAL AL IMPORTEMOVIMIENTO PORQUE NO TOMA EN CUENTA SI UN PRODUCTO ES TIPO SERVICIO
Case 237
ConceptoContabilizacionME = 238
ConceptoContabilizacionMEComp = 239
importeMovimiento = TmpDT.SUMD(If(ListaDocumentos IsNot Nothing AndAlso ListaDocumentos.Count > 0 AndAlso ArrAnticipos IsNot Nothing AndAlso ArrAnticipos.Count > 0 AndAlso TxtTotal.Text.ToDecimal = 0, "ImporteSinImpuestos", "Total"))
importeMN = importeMovimiento * tipoCambioActual * Multiplicador 'TIENE QUE TENER EL IMPORTEMN IGUAL AL IMPORTEMOVIMIENTO PORQUE NO TOMA EN CUENTA SI UN PRODUCTO ES TIPO SERVICIO
Case 240
ConceptoContabilizacionME = 241
ConceptoContabilizacionMEComp = 242
importeMovimiento = TmpDT.SUMD(If(ListaDocumentos IsNot Nothing AndAlso ListaDocumentos.Count > 0 AndAlso ArrAnticipos IsNot Nothing AndAlso ArrAnticipos.Count > 0 AndAlso TxtTotal.Text.ToDecimal = 0, "ImporteSinImpuestos", "Total"))
importeMN = importeMovimiento * tipoCambioActual * Multiplicador 'TIENE QUE TENER EL IMPORTEMN IGUAL AL IMPORTEMOVIMIENTO PORQUE NO TOMA EN CUENTA SI UN PRODUCTO ES TIPO SERVICIO
End Select
If UsuarioActual.Empresa.TipoContabilidad = 2 Then
If ConceptoContabilizacion = 6 Then
If ObjConta.GetRetCuenta(ConceptoContabilizacion, UsuarioActual.CveEmpresa) AndAlso ObjConta.DtResultados.Rows.Count > 0 Then
IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaGasto").ToString.ToEntero
End If
Else
If ObjConta.GetRetCuenta(ConceptoContabilizacion, UsuarioActual.CveEmpresa) AndAlso ObjConta.DtResultados.Rows.Count > 0 Then
IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCtaContable").ToString.ToEntero
End If
End If
If ObjConta.GetRetCuenta(ConceptoContabilizacionME, UsuarioActual.CveEmpresa) AndAlso ObjConta.DtResultados.Rows.Count > 0 Then
IdCtaContableME = ObjConta.DtResultados.Rows(0)("IdCtaContable").ToString.ToEntero
End If
If ObjConta.GetRetCuenta(ConceptoContabilizacionMEComp, UsuarioActual.CveEmpresa) AndAlso ObjConta.DtResultados.Rows.Count > 0 Then
IdCtaContableMEComp = ObjConta.DtResultados.Rows(0)("IdCtaContable").ToString.ToEntero
End If
End If
Dim CveMovimientoAlmacen As Integer = -1
'If importeMovimiento <> 0 Then
Select Case ConceptoContabilizacion
Case 176
Dim SumatoriaOCINV = 0.0D, Importe176 = 0.0D, ImporteME176 = 0.0D, ImporteMN176 = 0.0D, Importe228 = 0.0D, ImporteME228 = 0.0D, ImporteMN228 = 0.0D, Importe229 = 0.0D, ImporteME229 = 0.0D, ImporteMN229 = 0.0D, ImporteCI176 = 0.0D
Dim SumatoriaInventario As Decimal = 0
Dim TCO As Decimal = 1
For Each Dr As DataRow In TmpDT.FiltraParametros("ISNULL(TipoAF,0) <> 2 And ISNULL(CveAlmacen,0) = 0 And ISNULL(AplicaCostoIndirecto,0) <> 1 And ISNULL(CveTipoPS,0) = 2").Rows
If ObjOC.OrdenesCompraDetalleCostoPP(Dr("CveOrdenCompraDetalle").ToString.ToEntero) AndAlso ObjOC.DtResultados.Rows.Count >= 1 Then
Concepto = $"{NombreProveedor} {TxtSerie.Text} - {TxtFolio.Text} OC {ObjOC.DtResultados.FiltroPrimeroValor("Folio").ToString} Inv:{ObjOC.DtResultados.FiltroPrimeroValor("FolioAlmacen").ToString}"
Importe176 = ObjOC.DtResultados.FiltroPrimeroValor("Importe176").ToDecimal * Dr("Cantidad").ToString.ToDecimal : ImporteME176 = ObjOC.DtResultados.FiltroPrimeroValor("ImporteME176").ToDecimal * Dr("Cantidad").ToString.ToDecimal : ImporteMN176 = ObjOC.DtResultados.FiltroPrimeroValor("ImporteMN176").ToDecimal * Dr("Cantidad").ToString.ToDecimal
Importe228 = ObjOC.DtResultados.FiltroPrimeroValor("Importe228").ToDecimal * Dr("Cantidad").ToString.ToDecimal : ImporteME228 = ObjOC.DtResultados.FiltroPrimeroValor("ImporteME228").ToDecimal * Dr("Cantidad").ToString.ToDecimal : ImporteMN228 = ObjOC.DtResultados.FiltroPrimeroValor("ImporteMN228").ToDecimal * Dr("Cantidad").ToString.ToDecimal
Importe229 = ObjOC.DtResultados.FiltroPrimeroValor("Importe229").ToDecimal * Dr("Cantidad").ToString.ToDecimal : ImporteME229 = ObjOC.DtResultados.FiltroPrimeroValor("ImporteME229").ToDecimal * Dr("Cantidad").ToString.ToDecimal : ImporteMN229 = ObjOC.DtResultados.FiltroPrimeroValor("ImporteMN229").ToDecimal * Dr("Cantidad").ToString.ToDecimal
ImporteCI176 = ObjOC.DtResultados.FiltroPrimeroValor("ImporteCI176").ToDecimal
CveMovimientoAlmacen = ObjOC.DtResultados.FiltroPrimeroValor("CveMovimientoAlmacen").ToEntero
Dim TCAjuste As Decimal = ObjOC.DtResultados.FiltroPrimeroValor("TipoCambioAjuste").ToDecimal
'RMF. falta verificar el costo indirecto de la OC
If DdlMoneda.SelectedValue.ToEntero <> 1 Then
TCO = TxtTC.Text.ToDecimal
ImporteCI176 = ObjOC.DtResultados.FiltroPrimeroValor("ImporteCI228").ToDecimal
CostoIndirectoAcum176 += ImporteCI176
SumatoriaInventario += Importe228 + Importe229
'se considera costoindirecto, para que la factura tiene en un concepto tipo servicio
SumatoriaOCINV += (Dr(If(ListaDocumentos IsNot Nothing AndAlso ListaDocumentos.Count > 0 AndAlso ArrAnticipos IsNot Nothing AndAlso ArrAnticipos.Count > 0 AndAlso TxtTotal.Text.ToDecimal = 0, "ImporteSinImpuestos", "Total")).ToString.ToDecimal * tipoCambioActual) - (ImporteMN228 + ImporteMN229 - ImporteCI176)
If ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, Importe228, Referencia, ConceptoContabilizacionME, Concepto, FechaMovimiento, IdCtaContableME, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, ImporteMX:=ImporteMN228, ImporteME:=ImporteME228, CveOCDetalle:=Dr("CveOrdenCompraDetalle").ToString.ToEntero, TipoCambio:=TCAjuste, CveMovimientoAlmacen:=CveMovimientoAlmacen, Contabilizable:=SeContabiliza) Then
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, Importe229, Referencia, ConceptoContabilizacionMEComp, Concepto, FechaMovimiento, IdCtaContableMEComp, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, ImporteMX:=ImporteMN229, ImporteME:=ImporteME229, CveOCDetalle:=Dr("CveOrdenCompraDetalle").ToString.ToEntero, TipoCambio:=TCAjuste, CveMovimientoAlmacen:=CveMovimientoAlmacen, Contabilizable:=SeContabiliza) Then
ErrorPrepoliza = True
Exit For
End If
Else
ErrorPrepoliza = True
Exit For
End If
Else
CostoIndirectoAcum176 += ImporteCI176
SumatoriaInventario += Importe176
'se considera costoindirecto, para que la factura tiene en un concepto tipo servicio
SumatoriaOCINV += (Dr(If(ListaDocumentos IsNot Nothing AndAlso ListaDocumentos.Count > 0 AndAlso ArrAnticipos IsNot Nothing AndAlso ArrAnticipos.Count > 0 AndAlso TxtTotal.Text.ToDecimal = 0, "ImporteSinImpuestos", "Total")).ToString.ToDecimal * tipoCambioActual) - (ImporteMN176 - ImporteCI176)
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, Importe176, Referencia, ConceptoContabilizacion, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, ImporteMX:=ImporteMN176, ImporteME:=ImporteME176, CveOCDetalle:=Dr("CveOrdenCompraDetalle").ToString.ToEntero, CveMovimientoAlmacen:=CveMovimientoAlmacen, Contabilizable:=SeContabiliza) Then
ErrorPrepoliza = True
Exit For
End If
End If
Else
Alert("Ocurrió un error al procesar la mercancia recibida por adelantado. Por favor comuniquese con asistencia SIG", TipoMensaje.MsgError)
ErrorPrepoliza = True
Exit For
End If
Next
'obtengo si hay servicios
Dim CostosIndirectosTardados As Decimal = TmpDT.SUMD("Total", "ISNULL(TipoAF,0) <> 2 And ISNULL(CveAlmacen,0) = 0 And ISNULL(AplicaCostoIndirecto,0) <> 1 And ISNULL(CveTipoPS,0) = 1")
'consideracion, si la oc, se le agrego un servicio y este no se cargo en la entrada al almacen.
If CostoIndirectoAcum176 = 0 AndAlso CostosIndirectosTardados > 0 Then
CostosIndirectosTardados = CostosIndirectosTardados * TCO
End If
'calcula la diferencia entre lo recibido por la OC, considerando costos indirectos y lo que se ingresaria en la compra
SumatoriaOCINV = SumatoriaInventario - (TmpDT.SUMD("Total") * TCO).RoundSQL + CostosIndirectosTardados 'sumatoria de la factura
If SumatoriaOCINV.RoundSQL <> 0 Then
' se abona el costo, cambiamos su naturaleza
'SumatoriaOCINV = -SumatoriaOCINV
Dim CveClasificacionCostoOC = TmpDT.FiltroPrimeroValor("CveClasificacion", "ISNULL(TipoAF, 0) <> 2 And ISNULL(CveAlmacen, 0) = 0 And ISNULL(AplicaCostoIndirecto, 0) <> 1 And ISNULL(CveTipoPS, 0) = 2").ToEntero
Dim CveSubProyecto69 As Integer = TmpDT.MAX("CveSubProyecto").ToEntero
If CveSubProyecto69 <= 0 Then
Alert("Debe de asignar un sub proyecto o centro de costos", TipoMensaje.MsgAdvertencia)
ErrorPrepoliza = True
Exit For
End If
IdCtaContable = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaCostos", $"CveClasificacion = {CveClasificacionCostoOC}").ToString.ToEntero
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, SumatoriaOCINV, Referencia, 69, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveClasificacion:=CveClasificacionCostoOC, ImporteMX:=SumatoriaOCINV, TipoCambio:=tipoCambioActual, Contabilizable:=SeContabiliza, CveSubProyecto:=CveSubProyecto69) Then
ErrorPrepoliza = True
Exit For
End If
End If
Case 205, 237, 240
Insertado205 = True
Concepto = $"{NombreProveedor} {TxtSerie.Text} - {TxtFolio.Text}"
If DdlMoneda.SelectedValue.ToEntero <> 1 AndAlso UsaComplementariaFleteImportaciones Then
If ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContabilizacionME, Concepto, FechaMovimiento, IdCtaContableME, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, ImporteMX:=importeMovimiento, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), TipoCambio:=tipoCambioActual, Contabilizable:=SeContabiliza) Then
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, importeMN - importeMovimiento, Referencia, ConceptoContabilizacionMEComp, Concepto, FechaMovimiento, IdCtaContableMEComp, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, ImporteMX:=importeMN - importeMovimiento, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), TipoCambio:=tipoCambioActual, Contabilizable:=SeContabiliza) Then
ErrorPrepoliza = True
End If
Else
ErrorPrepoliza = True
End If
Else
If Not CveCompraRefacturacion > 0 Then
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, importeMN, Referencia, ConceptoContabilizacion, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, ImporteMX:=importeMN, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), TipoCambio:=tipoCambioActual, Contabilizable:=SeContabiliza) Then
ErrorPrepoliza = True
End If
End If
End If
Case 6
Concepto = $"{NombreProveedor} {TxtSerie.Text} - {TxtFolio.Text}"
For Each RowDetalle As DataRow In TmpDT.FiltraParametros("ISNULL(TipoAF,0) <> 2", "", {"CveClasificacion", "CveSubProyecto"}).Rows
If UsuarioActual.Empresa.TipoContabilidad = 2 AndAlso ObjConta.GetRetCuenta(6, RowDetalle("CveClasificacion").ToString().ToEntero()) Then
If ObjConta.DtResultados.Rows.Count > 0 Then
IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaGasto").ToString.ToEntero
End If
End If
If importeMN <> 0 Then
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, importeMN, Referencia, 6, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveIE:=CveIE, CvePersonal:=CvePersonal, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMN, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), TipoCambio:=tipoCambioActual,
CveClasificacion:=RowDetalle("CveClasificacion").ToString().ToEntero(), CveSubProyecto:=RowDetalle("CveSubProyecto").ToString().ToEntero(), Contabilizable:=SeContabiliza) Then
ErrorPrepoliza = True
End If
End If
Next
End Select
'End If
End If
'falta el registro de la NC cuando es
Dim RegistroCuentaPuente As Boolean = False
'NC CON PRODUCTOS - CUENTA PUENTE
If DdlTipoComprobante.SelectedValue = "NC" And DdlTipoCompra.SelectedValue.ToEntero = 9 Then
RegistraConcepto225 = True
End If
If RegistraConcepto225 Then
importeMovimiento = TmpDT.SUM(If(ListaDocumentos IsNot Nothing AndAlso ListaDocumentos.Count > 0 AndAlso ArrAnticipos IsNot Nothing AndAlso ArrAnticipos.Count > 0 AndAlso TxtTotal.Text.ToDecimal = 0, "ImporteSinImpuestos", "Total"), $"ISNULL(TipoAF,0) <> 2 And ISNULL(AplicaCostoIndirecto,0) <> 1 And ISNULL(CveTipoPS,0) = 2").ToString.ToDecimal
importeMN = importeMovimiento * tipoCambioActual * Multiplicador
'no es necesario, ya se está interpretandoe l usado como producto
'If UsuarioActual.Empresa.Funcionalidad(531) = "1" Then 'cuando es emp acumuladora
' Dim Valor As Decimal = 0
' For Each RowAcum As DataRow In GlobalDTAcumTamaños().FiltraParametros("CveEmpresa = 140").Rows
' Dim TotalTamanio = TmpDT.FiltroPrimeroValor("Total", $"CvePS={RowAcum("CvePSCargo")}").ToDecimal()
' If TotalTamanio > 0 Then
' Valor += TotalTamanio
' End If
' Next
' importeMovimiento += Valor
' importeMN = importeMovimiento * tipoCambioActual * Multiplicador
'End If
Dim ConceptoContabilizacionNC = 225
Dim CveMovimientoDevolucion As Integer = -1
'CUANDO NO SE RECIBE LA MERCANCIA EN COMPRAS, SE REGISTRA EL 225, SI SE ESTA REGISTRANDO LA DEVOLUCION EN ALMACEN, SE REGISTRA EL 68
If Devolucion IsNot Nothing AndAlso Devolucion.DebeRealizarDevolucion AndAlso Devolucion.CveMovimiento > 0 Then
ConceptoContabilizacionNC = 68
CveMovimientoDevolucion = Devolucion.CveMovimiento
End If
If UsuarioActual.Empresa.TipoContabilidad = 2 AndAlso ObjConta.GetRetCuenta(ConceptoContabilizacionNC, UsuarioActual.CveEmpresa) Then
If ObjConta.DtResultados.Rows.Count > 0 Then
IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCtaContable").ToString.ToEntero
End If
End If
Concepto = $"{NombreProveedor} {TxtSerie.Text} - {TxtFolio.Text}"
If importeMovimiento > 0 Or TxtTotal.Text.ToDecimal = 0 Then
RegistroCuentaPuente = True
Dim ImporteTransito As Decimal = 0
'Conta ContPAQ
If IdCtaContable = 0 Then
CuentasContablesInvalidas.Append("<br>" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 68))("ConceptoContable").ToString)
idCuentaContabilizacion = 0
End If
'SI ES GASTO DE ALMACEN NO DEBE CONTABILIZAR CONCEPTO 68
If DdlTipoCompra.SelectedValue = "10" AndAlso ConceptoContabilizacionNC = 68 Then
SeContabiliza = False
IdCtaContable = 0
End If
'se lleva saldo de Mercancía en tránsito
If ChkNCInvNC.Checked Then
For Each Gvr As GridViewRow In GVNCInv.Rows
If Gvr.FCTextBox("TxtCantidadNCInv").Text.ToDouble > 0 Then
If Not ObjCompras.ComprasDetalleDevolucionesAdd(Gvr.DataKey("CveCompraDetalle").ToEntero, CveCompra, Gvr.FCTextBox("TxtCantidadNCInv").Text.ToDouble, UsuarioActual.CveEmpresa) Then
ErrorMovInv = True
Exit For
End If
End If
Next
Dim diferenciaTransito As Decimal = 0
For Each Gvr As GridViewRow In GVNCInvAlmacen.Rows
If Gvr.FCTextBox("TxtCantidadNCInv").Text.ToDouble > 0 Then
Dim importeMNTemp As Decimal = 0
If Not ObjCompras.ComprasDetalleDevolucionesAdd(Gvr.DataKey("CveCompraDetalle").ToEntero, CveCompra, Gvr.FCTextBox("TxtCantidadNCInv").Text.ToDouble, UsuarioActual.CveEmpresa) Then
ErrorMovInv = True
Exit For
End If
Dim DifTC As Decimal = tipoCambioActual - Gvr.DataKey("TipoCambio").ToDecimal
'diferenciaTransito = DifTC * (Gvr.DataKey("IVA").ToDecimal / Gvr.FCTextBox("TxtCantidadNCInv").Text.ToDecimal)
'diferenciaTransito += DifTC * (Gvr.DataKey("IEPSPS").ToDecimal / Gvr.FCTextBox("TxtCantidadNCInv").Text.ToDecimal)
importeMNTemp = (Gvr.FCTextBox("TxtPU").Text.ToDecimal * Gvr.FCTextBox("TxtCantidadNCInv").Text.ToDecimal * Gvr.DataKey("TipoCambio").ToDecimal).RoundSQL
ImporteTransito += importeMNTemp
'se registra por cada compra relacionada
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, importeMNTemp, Referencia, ConceptoContabilizacionNC, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveCompraAmortizacion:=Gvr.DataKey("CveCompra").ToEntero, CveProveedor:=CveProveedorConcepto, ImporteMX:=importeMNTemp, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), TipoCambio:=Gvr.DataKey("TipoCambio").ToDecimal, CveMovimientoAlmacen:=CveMovimientoDevolucion, Contabilizable:=SeContabiliza) Then
ErrorPrepoliza = True
End If
End If
Next
'la diferencia se va aplicar sobre los
'Dim diferenciaTransito As Decimal = ImporteTransito - importeMN.RoundSQL
If diferenciaTransito <> 0 Then
Dim tCveCon As Integer = 65
IdCtaContable = UsuarioActual.Empresa.IdCuentaPerdidaCambiaria
If diferenciaTransito < 0 Then
tCveCon = 64
IdCtaContable = UsuarioActual.Empresa.IdCuentaGananciaCambiaria
End If
diferenciaTransito = Math.Abs(diferenciaTransito)
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, If(tCveCon = 64, True, False), diferenciaTransito, Referencia, tCveCon, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, ImporteMX:=diferenciaTransito, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), TipoCambio:=1, CveMovimientoAlmacen:=CveMovimientoDevolucion, Contabilizable:=SeContabiliza, CveSubProyecto:=CveSubProyecto) Then
ErrorPrepoliza = True
End If
End If
Else
Dim DiferenciaDevolucion As Decimal = importeMovimiento - TotalRealDevolucion
If TotalRealDevolucion <> 0 Then
If Math.Abs(DiferenciaDevolucion) > 0 Then
Dim CveSubProyecto69 As Integer = TmpDT.FiltroPrimeroValor("CveSubProyecto", "CveSubProyecto > 0 ").ToEntero
Dim CveClasificacion69 As Integer = TmpDT.FiltroPrimeroValor("CveClasificacion", "CveClasificacion > 0 ").ToEntero
Dim IdCtaContable69 As Integer = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaCostos", $"CveClasificacion = {CveClasificacion69}").ToString.ToEntero
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, DiferenciaDevolucion.RoundSQL(), Referencia, 69, Concepto, FechaMovimiento, IdCtaContable69, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, ImporteMX:=DiferenciaDevolucion, ImporteME:=If(tipoCambioActual = 1, 0, DiferenciaDevolucion), TipoCambio:=tipoCambioActual, CveMovimientoAlmacen:=CveMovimientoDevolucion, Contabilizable:=SeContabiliza, CveSubProyecto:=CveSubProyecto69, CveClasificacion:=CveClasificacion69) Then
ErrorPrepoliza = True
End If
End If
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, TotalRealDevolucion.RoundSQL(), Referencia, ConceptoContabilizacionNC, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, ImporteMX:=(TotalRealDevolucion * tipoCambioActual).RoundSQL(), ImporteME:=If(tipoCambioActual = 1, 0, TotalRealDevolucion).RoundSQL(), TipoCambio:=tipoCambioActual, CveMovimientoAlmacen:=CveMovimientoDevolucion, Contabilizable:=SeContabiliza) Then
ErrorPrepoliza = True
End If
Else
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, importeMovimiento.RoundSQL, Referencia, ConceptoContabilizacionNC, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, ImporteMX:=importeMovimiento * tipoCambioActual * Multiplicador, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), TipoCambio:=tipoCambioActual, CveMovimientoAlmacen:=CveMovimientoDevolucion, Contabilizable:=SeContabiliza) Then
ErrorPrepoliza = True
End If
End If
End If
End If
If UsuarioActual.CveEmpresa.Contiene(119) Then
Dim ContienePSNeteoBonif As Boolean = False
For Each Dr As DataRow In TmpDT.Rows
If Dr("CveClasificacion").ToString.ToEntero.Contiene(20319) Or DdlTipoCompra.SelectedValue.ToEntero = 11 Then 'clasificación de Bonificación, no se incluirá en el neteo
ContienePSNeteoBonif = True
Exit For
End If
Next
If ContienePSNeteoBonif Then
importeMovimiento = TmpDT.SUM(If(ListaDocumentos IsNot Nothing AndAlso ListaDocumentos.Count > 0 AndAlso ArrAnticipos IsNot Nothing AndAlso ArrAnticipos.Count > 0 AndAlso TxtTotal.Text.ToDecimal = 0, "ImporteSinImpuestos", "Total"), $"ISNULL(TipoAF,0) <> 2 And ISNULL(CveAlmacen,0) = 0 And ISNULL(AplicaCostoIndirecto,0) <> 1 AND CveClasificacion = 20319 ").ToString.ToDecimal
importeMN = importeMovimiento * tipoCambioActual * Multiplicador
Dim IdCtaContableDescCompra As Integer = UsuarioActual.Empresa.Funcionalidad(405).ToEntero
Dim CveSubProyecto259 As Integer = TmpDT.MAX("CveSubProyecto").ToEntero
If ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, importeMovimiento, Referencia, 259, Concepto, FechaMovimiento, IdCtaContableDescCompra, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, ImporteMX:=importeMN, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), TipoCambio:=tipoCambioActual, Contabilizable:=SeContabiliza, CveSubProyecto:=CveSubProyecto259) Then
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, -importeMovimiento, Referencia, 259, Concepto, FechaMovimiento, IdCtaContableDescCompra, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, ImporteMX:=-importeMN, ImporteME:=If(tipoCambioActual = 1, 0, -importeMovimiento), TipoCambio:=tipoCambioActual, Contabilizable:=SeContabiliza, CveSubProyecto:=CveSubProyecto259) Then
ErrorPrepoliza = True
End If
Else
ErrorPrepoliza = True
End If
End If
End If
End If
'ChkNCInvNC
If Not RegistroCuentaPuente AndAlso Not ChkNCInvNC.Checked Then
'GASTO
If UsuarioActual.CveEmpresa = 119 Then
DT = TmpDT
Else
DT = TmpDT.FiltraParametros("ISNULL(AplicaCostoIndirecto,0) <> 1")
End If
'RECORREMOS PARA DETECTAR LA MODALIDAD DEL ALMACEN, EN CASO DE SER SOLO EXISTENCIA LIMPIAMOS CVEALMACEN
If DdlTipoCompra.SelectedValue <> "10" Then
For Each Dr As DataRow In DT.Rows
If DtAlmacenes.FiltroPrimeroValor("Modalidad", $"CveAlmacen = {Dr("CveAlmacen").ToString.ToEntero}").ToString = "Solo Existencia" Then
Dr("CveAlmacen") = 0
End If
Dr.AcceptChanges()
Next
End If
DT.AcceptChanges()
DtAlmacenes.Dispose()
'QUITA 1-[MERCANCIA RECIBIDA POR ADELANTADO (OC) | MERCANCIA PENDIENTE POR RECIBIR (COMPRA)] 2-[NC CON PRODUCTOS]
If AgregaMercanciaInventario Then
DT = DT.FiltraParametros("ISNULL(CveTipoPS,0) <> 2")
End If
Dim DTDistinct = DT.Copy
If UsuarioActual.Empresa.Funcionalidad(126) = "1" Then
For Each drowdis As DataRow In DTDistinct.Rows
If drowdis("CveTipoGasto").ToString = "" Then
drowdis("CveTipoGasto") = 0
End If
If drowdis("TipoGasto").ToString.Trim = "" Then
drowdis("TipoGasto") = "ND"
End If
Next
DTDistinct = DTDistinct.FiltraParametros("ISNULL(TipoAF, 0) <> 2", "", {"CveClasificacion", "Clasificacion", "SubProyecto", "CveSubProyecto", "CveTipoGasto", "TipoGasto"})
Else
For Each drowdis As DataRow In DTDistinct.Rows
If drowdis("CveTipoGasto").ToString = "" Then
drowdis("CveTipoGasto") = 0
End If
If drowdis("TipoGasto").ToString.Trim = "" Then
drowdis("TipoGasto") = "ND"
End If
Next
DTDistinct.AcceptChanges()
DTDistinct = DTDistinct.FiltraParametros("ISNULL(TipoAF,0) <> 2 And ISNULL(CveAlmacen,0) = 0 And ISNULL(AplicaCostoIndirecto,0) <> 1", "", {"CveClasificacion", "Clasificacion", "SubProyecto", "CveSubProyecto", "CveTipoGasto", "TipoGasto"})
End If
'RMF, si es concepto relacionado a flete o importacion, no debe de afectar al gasto
If CveFlete > 0 OrElse CveImportacion > 0 OrElse (CveCompraRefacturacion > 0 AndAlso ChkRefacNC.Checked) Then
DTDistinct.Clear()
End If
Dim tTipoMovimiento As Boolean = TipoMovimiento
If DTDistinct.Rows.Count > 0 Then
For Each Row2 As DataRow In DTDistinct.Rows
tTipoMovimiento = TipoMovimiento
'DETERMINA IMPORTE
If UsuarioActual.Empresa.Funcionalidad(126) = "1" Then
importeMovimiento = DT.SUM(If(ListaDocumentos IsNot Nothing AndAlso ListaDocumentos.Count > 0 AndAlso ArrAnticipos IsNot Nothing AndAlso ArrAnticipos.Count > 0 AndAlso TxtTotal.Text.ToDecimal = 0, "ImporteSinImpuestos", "Total"), String.Format("ISNULL(TipoAF,0) <> 2 And CveClasificacion = {0} And CveSubProyecto = {1} And ISNULL(CveTipoGasto,0) = {2}", Row2("CveClasificacion").ToString.ToEntero, Row2("CveSubProyecto").ToString.ToEntero, Row2("CveTipoGasto").ToString.ToEntero)).ToString.ToDecimal
Else
importeMovimiento = DT.SUM(If(ListaDocumentos IsNot Nothing AndAlso ListaDocumentos.Count > 0 AndAlso ArrAnticipos IsNot Nothing AndAlso ArrAnticipos.Count > 0 AndAlso TxtTotal.Text.ToDecimal = 0, "ImporteSinImpuestos", "Total"), String.Format("ISNULL(TipoAF,0) <> 2 And ISNULL(CveAlmacen,0) = 0 And ISNULL(AplicaCostoIndirecto,0) <> 1 And CveClasificacion = {0} And CveSubProyecto = {1} And ISNULL(CveTipoGasto,0) = {2}", Row2("CveClasificacion").ToString.ToEntero, Row2("CveSubProyecto").ToString.ToEntero, Row2("CveTipoGasto").ToString.ToEntero)).ToString.ToDecimal
End If
'se debe de restar el costo indirecto, si se recibió por OC sobre el importe del gasto, por si ya está incuido
importeMovimiento = importeMovimiento - CostoIndirectoAcum176
importeMN = importeMovimiento * tipoCambioActual * Multiplicador '[IPP] EL 6 DEBE SER POSITIVO 27/AGOSTO/2018
'CLASIFICACION
If Row2("CveClasificacion").ToString.ToEntero > 0 AndAlso DdlTipoComprobante.SelectedValue = "Fac" Then
If UsuarioActual.Empresa.TipoContabilidad = 2 AndAlso ObjConta.GetRetCuenta(6, Row2("CveClasificacion").ToString.ToEntero, CveSubProyecto:=Row2("CveSubProyecto").ToString.ToEntero) Then
If ObjConta.DtResultados.Rows.Count > 0 AndAlso ObjConta.DtResultados.Rows(0)("IdCuentaGasto").ToString.ToEntero > 0 Then
IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaGasto").ToString.ToEntero
Else
IdCtaContable = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaGasto", String.Format("CveClasificacion = {0}", Row2("CveClasificacion"))).ToString.ToEntero
End If
End If
End If
'AGREGA MOVIMIENTO
If importeMovimiento.RoundSQL <> 0 Then
Dim tcvecon As Integer = 6
Dim tidctacon As Integer = 6
tidctacon = IdCtaContable
If DdlTipoComprobante.SelectedValue = "Ant" Then
tcvecon = 264
tidctacon = ViewState("CtaProveedorAnticipos").ToString.ToEntero
If DdlMoneda.SelectedValue = "2" Then
tidctacon = ViewState("CtaProveedorAnticiposExtranjera").ToString.ToEntero
End If
ElseIf DdlTipoComprobante.SelectedValue = "NC" Then
tcvecon = 259
tidctacon = UsuarioActual.Empresa.Funcionalidad(405).ToEntero
ElseIf UsuarioActual.CveEmpresa = 119 AndAlso Row2("CveClasificacion").ToString = "20473" Then
'CODIGO FIJO, SI ES LA CLASIFICACION DE "SEGURO/SERVICIO COSTO", SE ABONARÁ
tTipoMovimiento = True
importeMovimiento = -importeMovimiento
importeMN = -importeMN
End If
Dim usacomplementariaProveedor As Boolean = False
usacomplementariaProveedor = If(tipoCambioActual > 1, True, False)
If usacomplementariaProveedor AndAlso DdlTipoComprobante.SelectedValue = "Ant" Then
'importeMovimiento
Concepto = $"{NombreProveedor} {TxtSerie.Text} - {TxtFolio.Text}"
importeMN = tipoCambioActual * importeMovimiento - importeMovimiento
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, tTipoMovimiento, importeMovimiento, Referencia, 266, Concepto, FechaMovimiento, tidctacon, 0, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveIE:=CveIE, CveCreditoDetalle:=CveCreditoDetalle, CveClasificacion:=Row2("CveClasificacion").ToString.ToEntero, CveSubProyecto:=Row2("CveSubProyecto").ToString.ToEntero, ImporteMX:=importeMN, ImporteME:=importeMovimiento, CveTipoGasto:=Row2("CveTipoGasto").ToString.ToEntero, TipoCambio:=tipoCambioActual, Contabilizable:=SeContabiliza) Then
ErrorPrepoliza = True
End If
importeMN = importeMovimiento
End If
Concepto = $"{NombreProveedor} {TxtSerie.Text} - {TxtFolio.Text}"
If Not Insertado205 Then
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, tTipoMovimiento, importeMovimiento, Referencia, tcvecon, Concepto, FechaMovimiento, tidctacon, 0, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveIE:=CveIE, CveCreditoDetalle:=CveCreditoDetalle, CveClasificacion:=Row2("CveClasificacion").ToString.ToEntero, CveSubProyecto:=Row2("CveSubProyecto").ToString.ToEntero, ImporteMX:=importeMN, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), CveTipoGasto:=Row2("CveTipoGasto").ToString.ToEntero, TipoCambio:=tipoCambioActual, Contabilizable:=SeContabiliza) Then
ErrorPrepoliza = True
End If
End If
End If
Next
End If
End If
'LIMPIA
importeMovimiento = 0
IdCtaContable = 0
End If
Case 5 'Proveedores
If CveTipoConcepto = 2 Then ConceptoContable = 305 'cuando es acreedor
Dim UsaComplementaria As Boolean = True
If UsuarioActual.CveEmpresa.Contiene(13, 83) Then UsaComplementaria = False
If tipoCambioActual <> 1 Then
Select Case ConceptoContable
Case 5
ConceptoContable = 311
Case 305
ConceptoContable = 306
Case Else
End Select
End If
If Not DdlTipoComprobante.SelectedValue.Contiene("NC", "DEV") Then
importeMovimiento = importeProv
importeMN = importeMovimiento * tipoCambioActual * Multiplicador
If tipoCambioActual > 1 Then Concepto += $" TC{tipoCambioActual} ${importeMovimiento.FormatoNumero(2)}"
Dim CveConceptoContableComplementaria As Integer = 201
If CveTipoConcepto = 2 Then CveConceptoContableComplementaria = 307
If tipoCambioActual = 1 Then
IdCtaContable = If(CveTipoConcepto = 2, CtaProveedorAcreedores, CtaProveedor)
Else
IdCtaContable = CtaProveedorComplementaria
If importeMovimiento <> 0 AndAlso (IdCtaContable > 0 Or UsaComplementaria) Then 'Cuando tiene complementaria lo dividimos en dos Then
importeMN = importeMovimiento
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, 0, Referencia, CveConceptoContableComplementaria, Concepto, FechaMovimiento, IdCtaContable, -1, CveIE, CveCompra:=CveCompra, CveProveedor:=CveProveedor, ImporteMX:=importeMovimiento * tipoCambioActual - importeMovimiento, ImporteME:=importeMovimiento, TipoCambio:=tipoCambioActual, Contabilizable:=SeContabiliza) Then
ErrorPrepoliza = True
End If
End If
IdCtaContable = CtaProveedorExtranjera
End If
End If
Case 59 'Documentos
importeMovimiento = importeCreditos
importeMN = importeMovimiento * tipoCambioActual * Multiplicador
If UsuarioActual.Empresa.TipoContabilidad = 2 AndAlso ObjConta.GetRetCuenta(ConceptoContable, CveProveedor) Then
If ObjConta.DtResultados.Rows.Count > 0 Then
If ObjConta.DtResultados.Rows.Count > 0 Then
IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCtaContable").ToString.ToEntero
End If
End If
End If
Case 37 'Deudores
Dim CveConceptoContableDeoudor As Integer = If(RBLTipoDeudor.SelectedValue.ToEntero = 1, 37, 254)
For Each rw As GridViewRow In GvDeudores.Rows
If rw.FCCheckBox("Chk").Checked Then
importeMovimiento = rw.FCTextBox("TxtSaldoDeudor").Text.ToDecimal
OtrosGastosIngresos = rw.FCTextBox("TxtOtrosGastosIngresos").Text.ToDecimal
importeMN = (importeMovimiento * tipoCambioActual * Multiplicador).RoundSQL
Dim OtrosGastosIngresosMN As Decimal = (OtrosGastosIngresos * tipoCambioActual * Multiplicador).RoundSQL
Dim importeMNOtrosIngEgs As Decimal = ((importeMovimiento + OtrosGastosIngresos) * tipoCambioActual * Multiplicador).RoundSQL
IdCtaContable = CtaProveedorDeudores
Dim tCveProveedor As Integer = rw.DataKey("CveProveedor").ToEntero
'Conta ContPAQ
If CveConceptoContableDeoudor = 37 Then
If IdCtaContable = 0 Then
CuentasContablesInvalidas.Append("<br>" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", CveConceptoContableDeoudor))("ConceptoContable").ToString)
idCuentaContabilizacion = 0
End If
End If
If OtrosGastosIngresos = 0 Then
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, CveConceptoContableDeoudor, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=tCveProveedor, CveIE:=rw.DataKey("CveIE").ToString.ToEntero, CvePersonal:=CvePersonal, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMN, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), Contabilizable:=SeContabiliza) Then
ErrorPrepoliza = True : Exit For
End If
Else
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, If(TipoMovimiento, False, True), (importeMovimiento + OtrosGastosIngresos), Referencia, CveConceptoContableDeoudor, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=tCveProveedor, CveIE:=rw.DataKey("CveIE").ToString.ToEntero, CvePersonal:=CvePersonal, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMNOtrosIngEgs, ImporteME:=If(tipoCambioActual = 1, 0, (importeMovimiento + OtrosGastosIngresos)), Contabilizable:=SeContabiliza) Then
ErrorPrepoliza = True : Exit For
End If
End If
Dim Pago As New CompraPago With {
.ImportePago = importeMovimiento,
.CveIE = CveIE,
.CveMonedaPago = rw.DataKey("CveMoneda").ToEntero,
.OtroGastoIngreso = -OtrosGastosIngresos 'Se manda en negativo para no afectar en prepoliza, en funcion AplicaPrePolizaPagoCompra se mete en positivo por default
}
AplicaPrePolizaPagoCompra(CompraActual, Pago, CvePrePoliza, ObjConta)
End If
Next
'If RBLTipoDeudor.SelectedValue.ToEntero = 1 Then
' For Each rw As GridViewRow In GvDeudores.Rows
' If rw.FCCheckBox("Chk").Checked Then
' importeMovimiento = rw.FCTextBox("TxtSaldoDeudor").Text.ToDecimal
' OtrosGastosIngresos = rw.FCTextBox("TxtDeudoresOtrosGastosIngresos").Text.ToDecimal
' importeMN = (importeMovimiento * tipoCambioActual * Multiplicador).RoundSQL
' Dim OtrosGastosIngresosMN As Decimal = (OtrosGastosIngresos * tipoCambioActual * Multiplicador).RoundSQL
' IdCtaContable = CtaProveedorDeudores
' Dim tCveProveedor As Integer = rw.DataKey("CveProveedor").ToEntero
' 'Conta ContPAQ
' If IdCtaContable = 0 Then
' CuentasContablesInvalidas.Append("<br>" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString)
' idCuentaContabilizacion = 0
' End If
' If OtrosGastosIngresos = 0 Then
' If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=tCveProveedor, CveIE:=rw.DataKey("CveIE").ToString.ToEntero, CvePersonal:=CvePersonal, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMN, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), Contabilizable:=SeContabiliza) Then
' ErrorPrepoliza = True : Exit For
' End If
' Else
' If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, (importeMovimiento + OtrosGastosIngresos), Referencia, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=tCveProveedor, CveIE:=rw.DataKey("CveIE").ToString.ToEntero, CvePersonal:=CvePersonal, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMN, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), Contabilizable:=SeContabiliza) Then
' ErrorPrepoliza = True : Exit For
' End If
' End If
' Dim Pago As New CompraPago With {.ImportePago = importeMovimiento, .CveIE = CveIE, .CveMonedaPago = rw.DataKey("CveMoneda").ToEntero}
' AplicaPrePolizaPagoCompra(CompraActual, Pago, CvePrePoliza, ObjConta)
' End If
' Next
'Else
' For Each rw As GridViewRow In GvDeudores.Rows
' If rw.FCCheckBox("Chk").Checked Then
' importeMovimiento = rw.FCTextBox("TxtSaldoDeudor").Text.ToDecimal
' OtrosGastosIngresos = rw.FCTextBox("TxtDeudoresOtrosGastosIngresos").Text.ToDecimal
' importeMN = (importeMovimiento * tipoCambioActual * Multiplicador).RoundSQL
' Dim OtrosGastosIngresosMN As Decimal = (OtrosGastosIngresos * tipoCambioActual * Multiplicador).RoundSQL
' IdCtaContable = CtaProveedorDeudores
' Dim tCveProveedor As Integer = rw.DataKey("CveProveedor").ToEntero
' If OtrosGastosIngresos = 0 Then
' If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, 254, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=tCveProveedor, CveIE:=rw.DataKey("CveIE").ToString.ToEntero, CvePersonal:=CvePersonal, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMN, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), Contabilizable:=SeContabiliza) Then
' ErrorPrepoliza = True
' Exit For
' End If
' Else
' adasdasdasd
' If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, (importeMovimiento + OtrosGastosIngresos), Referencia, 254, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=tCveProveedor, CveIE:=rw.DataKey("CveIE").ToString.ToEntero, CvePersonal:=CvePersonal, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMN, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), Contabilizable:=SeContabiliza) Then
' ErrorPrepoliza = True
' Exit For
' End If
' End If
' Dim Pago As New CompraPago With {.ImportePago = importeMovimiento, .CveIE = CveIE, .CveMonedaPago = rw.DataKey("CveMoneda").ToEntero}
' AplicaPrePolizaPagoCompra(CompraActual, Pago, CvePrePoliza, ObjConta)
' End If
' Next
'End If
importeMovimiento = 0
OtrosGastosIngresos = 0
Case 41 'Acreedores
importeMovimiento = importeAcreedores
importeMN = importeMovimiento * tipoCambioActual * Multiplicador
IdCtaContable = CtaProveedorAcreedores
Case 42 'Acreedores
importeMovimiento = importeAcreedoresTarjeta
importeMN = importeMovimiento * tipoCambioActual * Multiplicador
IdCtaContable = CtaProveedorAcreedores
Case 18 'NC - Notas de Credito
importeMovimiento = importeNC
importeMN = importeMovimiento * tipoCambioActual * Multiplicador
If tipoCambioActual > 1 Then Concepto += $" TC{tipoCambioActual} ${importeMovimiento.FormatoNumero(2)}"
IdCtaContable = CtaProveedor
If DdlMoneda.SelectedValue.ToEntero <> 1 And UsuarioActual.CveEmpresa.Contiene(119) Then
IdCtaContable = CtaProveedorExtranjera
End If
If importeMovimiento <> 0 Then
GuardoConcepto18 = True
If DdlMoneda.SelectedValue.ToEntero <> 1 And UsuarioActual.CveEmpresa.Contiene(119, 158) Then
'PROVISION de NC
IdCtaContable = CtaProveedorExtranjera
Dim CveCon As Integer = ObtConceptoContableProvisionCompra(CveTipoConcepto, DdlTipoComprobante.SelectedValue, DdlMoneda.SelectedValue.ToEntero, False)
If ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, importeMovimiento, Referencia, CveCon, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CvePersonal:=CvePersonal, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMovimiento, ImporteME:=importeMovimiento, Contabilizable:=SeContabiliza) Then
IdCtaContable = CtaProveedorComplementaria
CveCon = ObtConceptoContableProvisionCompra(CveTipoConcepto, DdlTipoComprobante.SelectedValue, DdlMoneda.SelectedValue.ToEntero, True)
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, importeMN - importeMovimiento, Referencia, CveCon, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CvePersonal:=CvePersonal, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMN - importeMovimiento, ImporteME:=importeMovimiento, Contabilizable:=SeContabiliza, TipoCambio:=tipoCambioActual) Then
ErrorPrepoliza = True
Exit Select
End If
Else
ErrorPrepoliza = True
Exit Select
End If
'AMORTIZACIÓN EN EL REGISTRO
For Each Gvr As GridViewRow In GvFacturaNC.Rows
If Gvr.FCCheckBox("ChkFacturaNC").Checked Then
'Dim CvePrePolizaTemp = ObjConta.AddPrePolizas("Compras/Registrar-NC", If(EsContado And CvePlantillaPrePoliza = 1, 2, CvePlantillaPrePoliza), ImporteCompra, TxtTotal.Text.ToDouble, DdlMoneda.SelectedValue.ToEntero, TxtFecha.Text.ToDate, ConceptoPoliza, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, FolioFijo:=FolioFijo, ReglaFolioPoliza:=ObjCompras.ObtenerReglaFolio(DdlTipoTransaccion.SelectedValue, DdlTipoTransaccionCaja.SelectedValue, UsuarioActual.CveEmpresa), CveTipoPoliza:=ObjConta.ObtenerTipoPoliza(DdlTipoTransaccion.SelectedValue, DdlTipoTransaccionCaja.SelectedValue, UsuarioActual.CveEmpresa))
Dim importeMovimientoNC = Gvr.FCTextBox("TxtImporte").Text.ToDecimal
Dim TipoCambioFactura = Gvr.DataKey("TipoCambio").ToDecimal ' RMF. falta aplicar si está generada su TC de la última fluctuación
Dim importeMNNC = importeMovimientoNC * TipoCambioFactura * Multiplicador
Dim CveMonedaNC As Integer = If(TipoCambioFactura = 1, 1, 2)
IdCtaContable = CtaProveedorExtranjera
CveCon = ObtConceptoContableProvisionCompra(Gvr.DataKey("CveTipoConcepto").ToEntero, "NC", CveMonedaNC, False)
CompraActual.CveCompra = Gvr.DataKey("CveCompra").ToEntero
CompraActual.SerieFolio = Gvr.DataKey("SerieFolio")
Dim Pago As New CompraPago
Pago.ImportePago = importeMovimientoNC
Pago.CveMonedaPago = CveMonedaNC
Pago.CveCompraAmortizacion = CveCompra
Pago.CveConceptoPago = 272
Pago.Referencia = CompraActual.SerieFolio
Pago.TCPago = TipoCambioFactura
Pago.AplicaAcreditable = False
Pago.TipoPago = "NC"
ErrorMovtosCxP = AplicaPrePolizaPagoCompra(CompraActual, Pago, CvePrePoliza, ObjConta)
''CveCon = 272
'''PAGO A FACTURA POR NC
'If TipoCambioFactura > 1 Then CveCon = 304
'If ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, importeMovimientoNC, Referencia, CveCon, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=Gvr.DataKey("CveCompra").ToEntero, CveProveedor:=CveProveedorConcepto, CvePersonal:=CvePersonal, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMovimientoNC, ImporteME:=importeMovimientoNC, TipoCambio:=TipoCambioFactura, Contabilizable:=SeContabiliza, CveCompraAmortizacion:=CveCompra) Then
' Dim CveConceptoContableComplementaria As Integer = 206
' If Gvr.DataKey("CveTipoConcepto").ToEntero = 2 Then CveConceptoContableComplementaria = 310 'cuando es acreedor
' IdCtaContable = CtaProveedorComplementaria
' If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, importeMNNC - importeMovimientoNC, Referencia, CveConceptoContableComplementaria, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=Gvr.DataKey("CveCompra").ToEntero, CveProveedor:=CveProveedorConcepto, CvePersonal:=CvePersonal, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMNNC - importeMovimientoNC, ImporteME:=importeMovimientoNC, TipoCambio:=TipoCambioFactura, Contabilizable:=SeContabiliza, CveCompraAmortizacion:=CveCompra) Then
' ErrorPrepoliza = True
' Exit For
' End If
'Else
' ErrorPrepoliza = True
' Exit For
'End If
'importeMNNC = importeMovimientoNC * tipoCambioActual * Multiplicador
'IdCtaContable = CtaProveedorExtranjera
'If ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, importeMovimientoNC, Referencia, 60, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveCompraAmortizacion:=Gvr.DataKey("CveCompra").ToEntero, CveProveedor:=CveProveedorConcepto, CvePersonal:=CvePersonal, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMovimientoNC, ImporteME:=importeMovimientoNC, TipoCambio:=tipoCambioActual, Contabilizable:=SeContabiliza) Then
' IdCtaContable = CtaProveedorComplementaria
' If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, importeMNNC - importeMovimientoNC, Referencia, 235, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveCompraAmortizacion:=Gvr.DataKey("CveCompra").ToEntero, CveProveedor:=CveProveedorConcepto, CvePersonal:=CvePersonal, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMNNC - importeMovimientoNC, ImporteME:=importeMovimientoNC, TipoCambio:=tipoCambioActual, Contabilizable:=SeContabiliza) Then
' ErrorPrepoliza = True
' Exit For
' End If
'Else
' ErrorPrepoliza = True
' Exit For
' Exit For
'End If
'' FLUCTUACION CAMBIARIA
'If tipoCambioActual <> TipoCambioFactura AndAlso Not ChkNCInvNC.Checked Then ' que no se esté afectando mercancía en tránsto
' importeMovimiento = (importeMovimientoNC * TipoCambioFactura) - (importeMovimientoNC * tipoCambioActual)
' If importeMovimiento > 0 Then
' ConceptoContable = 64 : TipoMovimiento = True
' IdCtaContable = UsuarioActual.Empresa.IdCuentaGananciaCambiaria
' ElseIf importeMovimiento < 0 Then
' ConceptoContable = 65 : TipoMovimiento = False
' IdCtaContable = UsuarioActual.Empresa.IdCuentaPerdidaCambiaria
' End If
' importeMovimiento = importeMovimiento.Abs.RoundSQL()
' importeMN = importeMovimiento
' If importeMovimiento <> 0 Then
' If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, importeMovimiento, Concepto, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=importeMN, CvePrePolizaOriginal:=CvePrePoliza, ImporteME:=0, Contabilizable:=SeContabiliza, CveSubProyecto:=CveSubProyecto) Then
' ErrorPrepoliza = True
' Exit For
' End If
' End If
'End If
End If
Next
If ErrorPrepoliza Then
Exit Select
End If
Else
IdCtaContable = CtaProveedor
If ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CvePersonal:=CvePersonal, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMN, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), Contabilizable:=SeContabiliza) Then
For Each Gvr As GridViewRow In GvFacturaNC.Rows
If Gvr.FCCheckBox("ChkFacturaNC").Checked Then
'Dim CvePrePolizaTemp = ObjConta.AddPrePolizas("Compras/Registrar", If(EsContado And CvePlantillaPrePoliza = 1, 2, CvePlantillaPrePoliza), ImporteCompra, TxtTotal.Text.ToDouble, DdlMoneda.SelectedValue.ToEntero, TxtFecha.Text.ToDate, ConceptoPoliza, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, FolioFijo:=FolioFijo, ReglaFolioPoliza:=ObjCompras.ObtenerReglaFolio(DdlTipoTransaccion.SelectedValue, DdlTipoTransaccionCaja.SelectedValue, UsuarioActual.CveEmpresa), CveTipoPoliza:=ObjConta.ObtenerTipoPoliza(DdlTipoTransaccion.SelectedValue, DdlTipoTransaccionCaja.SelectedValue, UsuarioActual.CveEmpresa))
Dim importeMovimientoNC = Gvr.FCTextBox("TxtImporte").Text.ToDecimal
Dim importeMNNC = importeMovimientoNC * tipoCambioActual * Multiplicador
If ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, importeMovimientoNC, Referencia, 272, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=Gvr.DataKey("CveCompra").ToEntero, CveProveedor:=CveProveedorConcepto, CvePersonal:=CvePersonal, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMNNC, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimientoNC), CveCompraAmortizacion:=CveCompra, Contabilizable:=SeContabiliza) Then
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, Not TipoMovimiento, importeMovimientoNC, Referencia, 60, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveCompraAmortizacion:=Gvr.DataKey("CveCompra").ToEntero, CveProveedor:=CveProveedorConcepto, CvePersonal:=CvePersonal, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMNNC, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimientoNC), Contabilizable:=SeContabiliza) Then
ErrorPrepoliza = True
End If
Else
ErrorPrepoliza = True
End If
'ObjConta.PrePolizaUnificacion(CvePrePoliza, CvePrePolizaTemp)
End If
Next
End If
End If
End If
importeMovimiento = 0
Case 29 'Funcionarios y Empleados
importeMovimiento = importeFE
importeMN = importeMovimiento * tipoCambioActual * Multiplicador
If UsuarioActual.Empresa.TipoContabilidad = 2 AndAlso ObjConta.GetRetCuenta(ConceptoContable, CvePersonal) Then
If ObjConta.DtResultados.Rows.Count > 0 Then
IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCtaContPersonal").ToString.ToEntero
End If
End If
If importeMovimiento > 0 Then
Dim Pago As New CompraPago
If DDlCheques.SelectedValue.ToEntero > 0 Then
Pago.ImportePago = importeFE
Pago.CveIE = DDlCheques.SelectedValue.ToEntero
Pago.CvePersonal = CvePersonal
ErrorPrepoliza = AplicaPrePolizaPagoCompra(CompraActual, Pago, CvePrePoliza, ObjConta)
Else
Alert("Debe de seleccionar un cheque.", TipoMensaje.MsgAdvertencia)
ErrorPrepoliza = True
End If
End If
Case 21 'Anticipo
If ArrAnticipos.Count > 0 Then
Dim PorcentajeImpuestoAnticipo = PorcentajeIVA
For Each Ant As Compras_Compras.Anticipos In ArrAnticipos
TipoMovimiento = If(Row("TipoMovto").ToString = "True", True, False)
Dim ConceptoContableAnticipo, ConceptoContableAnticipoComplementaria As Integer
Dim CveCompraNC As Integer = CveCompra
Select Case Ant.TipoMovto
Case "NC", "DEV"
ConceptoContableAnticipo = 60
ConceptoContableAnticipoComplementaria = 235
CveCompraNC = Ant.CveCompra 'cuando es NC, se utiliza la clave de compra de la nota de credito
IdCtaContable = CtaProveedor
Case "Egsc"
ConceptoContableAnticipo = 21
IdCtaContable = CtaProveedorAnticipos
Case "DD"
ConceptoContableAnticipo = 37
IdCtaContable = CtaProveedorDeudores
Case "Ant"
ConceptoContableAnticipo = 265
ConceptoContableAnticipoComplementaria = 266
CveCompraNC = Ant.CveCompra
IdCtaContable = CtaProveedorAnticipos
End Select
importeMovimiento = Ant.Importe
importeMN = importeMovimiento * tipoCambioActual * Multiplicador
Dim ImporComisionAnticipo As Decimal = Ant.ImporteComision
Dim importeMNComision As Decimal = ImporComisionAnticipo * tipoCambioActual * Multiplicador
If importeMovimiento <> 0 Then
'Conta ContPAQ
If IdCtaContable = 0 Then
CuentasContablesInvalidas.Append("<br>" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString)
idCuentaContabilizacion = 0
End If
'AMORTIZACIÓN NC ESPECIAL COMPLEMENTARIA
If ConceptoContableAnticipo.Contiene(60) And DdlMoneda.SelectedValue.ToEntero <> 1 Then
Dim importeMovimientoNC = Ant.Importe
Dim importeMNNC = 0.0D
Dim TipoCambioNC = Ant.TCCompra
importeMNNC = importeMovimientoNC * TipoCambioNC * Multiplicador
IdCtaContable = CtaProveedorExtranjera
If ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, importeMovimientoNC, Referencia, 60, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=Ant.CveCompra, CveCompraAmortizacion:=CveCompra, CveProveedor:=CveProveedorConcepto, CvePersonal:=CvePersonal, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMovimientoNC, ImporteME:=importeMovimientoNC, TipoCambio:=TipoCambioNC, Contabilizable:=SeContabiliza) Then
IdCtaContable = CtaProveedorComplementaria
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, importeMNNC - importeMovimientoNC, Referencia, 235, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=Ant.CveCompra, CveCompraAmortizacion:=CveCompra, CveProveedor:=CveProveedorConcepto, CvePersonal:=CvePersonal, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMNNC - importeMovimientoNC, ImporteME:=importeMovimientoNC, TipoCambio:=TipoCambioNC, Contabilizable:=SeContabiliza) Then
ErrorPrepoliza = True
Exit For
End If
Else
ErrorPrepoliza = True
Exit For
End If
importeMNNC = importeMovimientoNC * tipoCambioActual * Multiplicador
IdCtaContable = CtaProveedorExtranjera
If ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, importeMovimientoNC, Referencia, 272, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveCompraAmortizacion:=Ant.CveCompra, CveProveedor:=CveProveedorConcepto, CvePersonal:=CvePersonal, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMovimientoNC, ImporteME:=importeMovimientoNC, TipoCambio:=tipoCambioActual, Contabilizable:=SeContabiliza) Then
Dim CveConceptoContableComplementaria As Integer = 206
If CveTipoConcepto = 2 Then CveConceptoContableComplementaria = 310 'cuando es acreedor
IdCtaContable = CtaProveedorComplementaria
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, importeMNNC - importeMovimientoNC, Referencia, CveConceptoContableComplementaria, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CvePersonal:=CvePersonal, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMNNC - importeMovimientoNC, ImporteME:=importeMovimientoNC, TipoCambio:=tipoCambioActual, Contabilizable:=SeContabiliza) Then
ErrorPrepoliza = True
Exit For
End If
Else
ErrorPrepoliza = True
Exit For
End If
' FLUCTUACION CAMBIARIA
If tipoCambioActual <> TipoCambioNC Then
importeMovimiento = (importeMovimientoNC * tipoCambioActual) - (importeMovimientoNC * TipoCambioNC)
If importeMovimiento > 0 Then
ConceptoContable = 64
TipoMovimiento = True
IdCtaContable = UsuarioActual.Empresa.IdCuentaGananciaCambiaria
ElseIf importeMovimiento < 0 Then
ConceptoContable = 65
TipoMovimiento = False
IdCtaContable = UsuarioActual.Empresa.IdCuentaPerdidaCambiaria
End If
importeMovimiento = importeMovimiento.Abs.RoundSQL()
importeMN = importeMovimiento
If importeMovimiento <> 0 Then
Dim CveSubProyecto6465 As Integer = TmpDT.FiltroPrimeroValor("CveSubProyecto", " CveSubProyecto > 0").ToEntero
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, importeMovimiento, Concepto, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveSubProyecto:=CveSubProyecto6465, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=importeMN, CvePrePolizaOriginal:=CvePrePoliza, ImporteME:=0, Contabilizable:=SeContabiliza) Then
ErrorPrepoliza = True
Exit For
End If
End If
End If
ElseIf ConceptoContableAnticipo.Contiene(265) And DdlMoneda.SelectedValue.ToEntero <> 1 Then
Dim importeMovimientoNC = Ant.Importe
Dim importeMNNC = 0.0D
Dim TipoCambioNC = Ant.TCCompra
importeMNNC = importeMovimientoNC * TipoCambioNC * Multiplicador
IdCtaContable = CtaProveedorAnticiposExtranjera
If ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, importeMovimientoNC, Referencia, 265, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=Ant.CveCompra, CveCompraAmortizacion:=CveCompra, CveProveedor:=CveProveedorConcepto, CvePersonal:=CvePersonal, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMovimientoNC, ImporteME:=importeMovimientoNC, TipoCambio:=TipoCambioNC, Contabilizable:=SeContabiliza) Then
IdCtaContable = CtaProveedorAnticiposComplementaria
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, importeMNNC - importeMovimientoNC, Referencia, 266, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=Ant.CveCompra, CveCompraAmortizacion:=CveCompra, CveProveedor:=CveProveedorConcepto, CvePersonal:=CvePersonal, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMNNC - importeMovimientoNC, ImporteME:=importeMovimientoNC, TipoCambio:=TipoCambioNC, Contabilizable:=SeContabiliza) Then
ErrorPrepoliza = True
Exit For
End If
Else
ErrorPrepoliza = True
Exit For
End If
If TxtTotal.Text.ToDouble > 0 AndAlso TieneAnticiposXML = False Then
importeMNNC = importeMovimientoNC * tipoCambioActual * Multiplicador
IdCtaContable = CtaProveedorExtranjera ' CtaProveedorAnticiposExtranjera
If ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, importeMovimientoNC, Referencia, 272, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CvePersonal:=CvePersonal, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMovimientoNC, ImporteME:=importeMovimientoNC, TipoCambio:=tipoCambioActual, CveCompraAmortizacion:=CveCompraNC, Contabilizable:=SeContabiliza) Then
Dim CveConceptoContableComplementaria As Integer = 206
If CveTipoConcepto = 2 Then CveConceptoContableComplementaria = 310 'cuando es acreedor
IdCtaContable = CtaProveedorExtranjera 'CtaProveedorAnticiposComplementaria
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, importeMNNC - importeMovimientoNC, Referencia, CveConceptoContableComplementaria, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CvePersonal:=CvePersonal, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMNNC - importeMovimientoNC, ImporteME:=importeMovimientoNC, TipoCambio:=tipoCambioActual, Contabilizable:=SeContabiliza) Then
ErrorPrepoliza = True
Exit For
End If
Else
ErrorPrepoliza = True
Exit For
End If
If Ant.TipoMovto.Contiene("Ant") Then
If importeMovimientoNC <> 0 Then
Dim Pago As New CompraPago
Pago.ImportePago = importeMovimientoNC
Pago.CveIE = Ant.CveIE
Pago.CveMonedaPago = 1
Pago.OtroGastoIngreso = ImporComisionAnticipo
ErrorMovtosCxP = AplicaPrePolizaPagoCompra(CompraActual, Pago, CvePrePoliza, ObjConta)
End If
End If
End If
Else
Dim usacomplementariaAnticipo As Boolean = False
usacomplementariaAnticipo = If(Ant.TCCompra > 1, True, False)
Dim TipoCambioAnt As Decimal = Ant.TCCompra
Dim ImporteAnt As Decimal = importeMovimiento
Dim ImporteAntMN As Decimal = ImporteAnt * TipoCambioAnt
If usacomplementariaAnticipo Then
IdCtaContable = CtaProveedorAnticiposComplementaria
ImporteAntMN = TipoCambioAnt * ImporteAnt - ImporteAnt
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, ImporteAnt, Referencia, 266, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompraNC, CveCompraAmortizacion:=CveCompra, CveProveedor:=CveProveedorConcepto, CvePersonal:=CvePersonal, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=ImporteAntMN, ImporteME:=ImporteAnt, TipoCambio:=TipoCambioAnt, Contabilizable:=SeContabiliza) Then
ErrorPrepoliza = True
Exit For
End If
ImporteAntMN = ImporteAnt
End If
If TipoCambioAnt > 1 Then
IdCtaContable = CtaProveedorAnticiposExtranjera
End If
'Agregamos el 21/37/60
'Dim ImporComisionAnticipo As Decimal = Ant.ImporteComision
'Dim importeMNComision As Decimal = ImporComisionAnticipo * tipoCambioActual * Multiplicador
If ImporComisionAnticipo = 0 Then
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, ImporteAnt, Referencia, ConceptoContableAnticipo, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompraNC, CveCompraAmortizacion:=CveCompra, CveProveedor:=CveProveedorLocal, CveIE:=Ant.CveIE, ImporteMX:=ImporteAntMN, ImporteME:=If(tipoCambioActual = 1, 0, ImporteAnt), TipoCambio:=TipoCambioAnt, Contabilizable:=SeContabiliza) Then
ErrorPrepoliza = True
End If
Else
Dim ImporteAntMNComision As Decimal = (ImporteAnt + ImporComisionAnticipo) * TipoCambioAnt
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, (ImporteAnt + ImporComisionAnticipo), Referencia, ConceptoContableAnticipo, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompraNC, CveCompraAmortizacion:=CveCompra, CveProveedor:=CveProveedorLocal, CveIE:=Ant.CveIE, ImporteMX:=ImporteAntMNComision, ImporteME:=If(tipoCambioActual = 1, 0, (ImporteAnt + ImporComisionAnticipo)), TipoCambio:=TipoCambioAnt, Contabilizable:=SeContabiliza) Then
ErrorPrepoliza = True
End If
End If
If TxtTotal.Text.ToDouble > 0 AndAlso TieneAnticiposXML = False Then
Dim Pago As New CompraPago
Pago.ImportePago = importeMovimiento
Pago.CveIE = Ant.CveIE
Pago.TCPago = Ant.TCCompra
Pago.CveMonedaPago = If(Ant.TCCompra > 1, 2, 1)
Pago.OtroGastoIngreso = ImporComisionAnticipo
ErrorPrepoliza = AplicaPrePolizaPagoCompra(CompraActual, Pago, CvePrePoliza, ObjConta)
End If
End If
'** PRUEBA CUANDO SE AMORTIZA NC ANTES DE QUE SE REGISTRE NO DEBE TENER CONCEPTO 19 ** JM 01/06/2017 SE HIZO ESTO PARA LA FACTURA HRFA-8012831 DE VIGILANCIA
'[IPP] NC NO DEBE REGISTRAR IMPUESTOS EN AMORTIZACIÓN 27/Agosto/2018
'If Not Ant.TipoMovto.Contiene("NC", "DEV") Then
' Dim Pago As New CompraPago
' Pago.ImportePago = importeMovimiento
' Pago.CveIE = Ant.CveIE
' Pago.CveMonedaPago = 1
' ErrorPrepoliza = AplicaPrePolizaPago(CompraActual, Pago, ObjConta)
'End If
End If
If UsuarioActual.CveEmpresa.Contiene(83) Then
'Unificacion de PrePolizas
If UsuarioActual.Empresa.Funcionalidad(219) = "1" Then
If Not ObjConta.PrePolizaUnificacion(Ant.CvePrePoliza, CvePrePoliza) Then
ErrorPrepoliza = True
Alert("No se pudo unificar la prepoliza", TipoMensaje.MsgError)
End If
End If
'Simplificacion de PrePolizas
If UsuarioActual.Empresa.Funcionalidad(220) <> "" Then
If Not ObjConta.UpdatePrePolizasDetalleBloquear(Ant.CvePrePoliza, False) Then
ErrorPrepoliza = True
Alert("No se pudo desbloquear los movimientos", TipoMensaje.MsgError)
End If
If Not ErrorPrepoliza AndAlso Not ObjConta.PrePolizaSimplificacion(Ant.CvePrePoliza, UsuarioActual.CveEmpresa) Then
ErrorPrepoliza = True
Alert("No se pudo simplificar los movimientos", TipoMensaje.MsgError)
End If
End If
End If
Next
importeMovimiento = 0
End If
End Select
If ErrorPrepoliza Then
Exit For
End If
'5, 305, 306, 311
If importeMovimiento <> 0 Or (CveConceptoOriginal = 5 AndAlso DdlTipoComprobante.SelectedValue.Contiene("Fac", "Ant")) Or (ConceptoContable.Contiene(18) AndAlso DdlTipoComprobante.SelectedValue.Contiene("NC", "DEV") AndAlso Not GuardoConcepto18) Then
'Conta ContPAQ
If IdCtaContable = 0 Then
CuentasContablesInvalidas.Append("<br>" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString)
idCuentaContabilizacion = 0
End If
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveSubProyecto:=CveSubProyectoInsertar, CveProveedor:=CveProveedorConcepto, CveIE:=CveIE, CvePersonal:=CvePersonal, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=Math.Round(importeMN, 2, MidpointRounding.AwayFromZero), ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), TipoCambio:=tipoCambioActual, PorcentajeImpuesto:=PorcentajeImpuesto, Contabilizable:=SeContabiliza) Then
ErrorPrepoliza = True
Exit For
End If
End If
Next
'EMPIEZA REFACTURACION
If Not ErrorPrepoliza AndAlso CveCompraRefacturacion > 0 Then
ErrorBitacora = GuardaRefacturacion(ObjCompras, ObjEventos, CvePrePoliza)
If ErrorBitacora Then
Alert("Ocurrió un error al hacer la Refacturación", TipoMensaje.MsgError)
End If
End If
'Simplificacion de PrePolizas
If Not ErrorPrepoliza AndAlso UsuarioActual.Empresa.Funcionalidad(220) <> "" Then
If Not ObjConta.PrePolizaSimplificacion(CvePrePoliza, UsuarioActual.CveEmpresa) Then
ErrorPrepolizaDescuadre = True
End If
End If
If Not ErrorPrepoliza AndAlso ObjConta.ValidacionPrePolizaCuadre(CvePrePoliza, 4) Then
If ObjConta.ValorPolizaDescuadre > 0 Then
GuardaLogAD($"Compras/Compras-Guardar | Error{ObjConta.MensajePolizaDescuadre} Diferencia{ObjConta.ValorDiferencia} | CvePrePoliza:{CvePrePoliza}", "LogPrePolizas")
ErrorPrepolizaDescuadre = True
End If
End If
'Conta ContPAQ
If ObjContaAC IsNot Nothing AndAlso Not ErrorPrepoliza AndAlso Not ErrorPrepolizaDescuadre AndAlso UsuarioActual.Empresa.Funcionalidad(200).ToString = "1" Then
If idCuentaContabilizacion > 0 Then
If ObjConta.ContabilizarPrePoliza(CvePrePoliza, UsuarioActual.CveUsuario, UsuarioActual.Empresa, ObjConta:=ObjContaAC) Then
' Alert(alertaContabilizacion, ModExtensiones.TipoMensaje.MsgInformacion)
IdPoliza = ObjConta.ContaIdPoliza
Else
ErrorPrepoliza = True
Alert($"Ocurrio un error al contabilizar {ObjConta.AlertaMensaje}", TipoMensaje.MsgAdvertencia)
End If
Else
Alert(String.Format("No se puede contabilizar la Prepoliza debido a que las siguientes cuentas son inválidas: <br>{0}", CuentasContablesInvalidas), TipoMensaje.MsgAdvertencia)
ErrorPrepoliza = True
End If
End If
End If
'' A N T I C I P O S
If UsuarioActual.Empresa.UsaAC Then
If ArrAnticipos.Count > 0 Then
Dim PorcentajePago As Decimal
Dim ConceptoRenglon As String
'si hay una diferencia entre lo amortizado y el total, se registra la diferencia a proveedores y los ivas por acreditar
If TxtTotal.Text.ToDouble - ImporteAnticipo > 0 Then
PorcentajePago = (TxtTotal.Text.ToDecimal - ImporteAnticipo) / TxtTotal.Text.ToDecimal
ConceptoRenglon = String.Format("GE Fact {0}-{1} {2}", TxtSerie.Text.Trim, TxtFolio.Text.Trim, DdlProveedor.SelectedItem.Text)
If Not ObjContaAC.AddMovimiento(IdPoliza, CtaProveedor, True, TxtTotal.Text.ToDouble - ImporteAnticipo, "", ConceptoRenglon, 0, TxtFechaPago.Text.ToDate, "") Then
ErrorACMEnsaje.Append(" - si hay una diferencia entre lo amortizado y el total, se registra la diferencia a proveedores y los ivas por acreditar ObjContaAC.AddMovimiento")
ErrorAC = True
End If
End If
'una vez amortizado, se generan los movimientos presupuestales
If ImporteAnticipo > 0 Then
PorcentajePago = ImporteAnticipo / TxtTotal.Text.ToDecimal
If ObjCompras.GetPresupuestosCompras(CveCompra) AndAlso ObjCompras.DtResultados.Rows.Count > 0 Then
'DtAC.Merge(ObjConta.DtResultados)
For Each dr As DataRow In ObjCompras.DtResultados.Rows
Total = dr("TotalPresupuesto").ToString.ToDecimal * PorcentajePago
If Total > 0 Then
'EJERCIDO
If True Then
ConceptoRenglon = String.Format("GE {0} F{1}-{2}", DdlProveedor.SelectedItem.Text, TxtSerie.Text, TxtFolio.Text)
If ObjContaAC.AddMovimiento(IdPoliza, dr("IdCuentaEjercido").ToString.ToEntero, False, MultiplicadorNC * Total, "", ConceptoRenglon, 0, TxtFechaPago.Text.ToDate, "") Then
'actualizo el idcuenta del presupuesto
If Not ObjContaAC.AddMovimiento(IdPoliza, dr("IdCuentaDevengado").ToString.ToEntero, True, MultiplicadorNC * Total, "", ConceptoRenglon, 0, TxtFechaPago.Text.ToDate, "") Then
TieneError = True
Exit For
End If
Else
TieneError = True
Exit For
End If
End If
'PAGADO
ConceptoRenglon = String.Format("GP {0} F{1}-{2}", DdlProveedor.SelectedItem.Text, TxtSerie.Text, TxtFolio.Text)
If ObjContaAC.AddMovimiento(IdPoliza, dr("IdCuentaPagado").ToString.ToEntero, False, MultiplicadorNC * Total, "", ConceptoRenglon, 0, TxtFechaPago.Text.ToDate, "") Then
'actualizo el idcuenta del presupuesto
If Not ObjContaAC.AddMovimiento(IdPoliza, dr("IdCuentaEjercido").ToString.ToEntero, True, MultiplicadorNC * Total, "", ConceptoRenglon, 0, TxtFechaPago.Text.ToDate, "") Then
TieneError = True
Exit For
End If
Else
TieneError = True
Exit For
End If
End If
Next
Else
ErrorACMEnsaje.Append(" - Error al obtener presupuestos ObjCompras.GetPresupuestosCompras")
ErrorAC = True
End If
End If
End If
End If
'' F U N C I O N A R I O S Y E M P L E A D O S
If RBLContado.SelectedValue = "2" AndAlso DdlFuncionarioEmpleado.SelectedValue.ToEntero > 0 Then
TxtDocumentoImporte.Text = TxtDocumentoImporteFE.Text
TxtDocumentoImporteCaja.Text = TxtDocumentoImporteFE.Text
End If
Else 'Empresa Prueba
If RBLPago.SelectedValue.ToEntero = 2 AndAlso (RBLContado.SelectedValue = "1" Or RBLContado.SelectedValue = "6") Then 'Contado - Bancos y Caja Chica
'se agrego un movimiento de pago
If CveIE > 0 Then
If ImporteCompra <> 0 Then
'inserto los movimientos de la conta para abonar al saldo
Dim Pago As New CompraPago
Pago.ImportePago = ImporteCompra
Pago.CveIE = CveIE
Pago.CveMonedaPago = 1
ErrorMovtosCxP = AplicaPrePolizaPagoCompra(CompraActual, Pago, CvePrePoliza, ObjConta)
End If
Else
ErrorMovtosIE = True
End If
End If
'movimiento de compra
'[IPP] PARCHE PROVISIONAL DE CLASIFICACION Y SUBPROYECTO [CveClasificacion:=TmpDT.FiltroPrimeroValor("CveClasificacion").ToString.ToEntero] [CveSubProyecto:=TmpDT.FiltroPrimeroValor("CveSubProyecto").ToString.ToEntero]
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimientoCompra, TxtSubTotal2.Text.ToDecimal, " ", CveConceptoCompra, " ", TxtFechaPago.Text.ToDate, 0, -1, CveClasificacion:=TmpDT.FiltroPrimeroValor("CveClasificacion").ToString.ToEntero, CveSubProyecto:=TmpDT.FiltroPrimeroValor("CveSubProyecto").ToString.ToEntero, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveIE:=CveIE, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=TxtSubTotal2.Text.ToDecimal) Then
ErrorMovtosCxP = True
End If
'Se agregan las CxP
If CveConceptoAfectacion = 37 Then
For Each rw As GridViewRow In GvDeudores.Rows
If rw.FCCheckBox("Chk").Checked Then
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, Not TipoMovimientoCompra, rw.FCTextBox("TxtSaldoDeudor").Text.ToDecimal, " ", CveConceptoAfectacion, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveIE:=rw.DataKey("CveIE").ToString.ToEntero, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=rw.FCTextBox("TxtSaldoDeudor").Text.ToDecimal) Then
ErrorMovtosCxP = True
End If
End If
Next
Else
If ImporteCompra > 0 AndAlso Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, Not TipoMovimientoCompra, ImporteCompra, " ", CveConceptoAfectacion, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveIE:=CveIE, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=ImporteCompra) Then
ErrorMovtosCxP = True
End If
End If
If CvePlantillaPrePoliza = 1 Or CvePlantillaPrePoliza = 60 Then
'Siempre: Se agrega IVA aunque sea cero
' If TxtIVA.Text.Replace(", ", "").Trim.ToDouble <> 0 Then
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, Not TipoMovimientoImpuestos, TxtIVA.Text.ToDecimal, " ", CveConceptoIVA, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveIE:=CveIE, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=TxtIVA.Text.ToDecimal) Then
ErrorMovtosIVA = True
End If
'End If
'Se agregan las Ret IVA
If TxtRetIVA.Text.ToDouble <> 0 Then
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimientoImpuestos, TxtRetIVA.Text.ToDecimal, " ", CveConceptoRetIVA, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveIE:=CveIE, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=TxtRetIVA.Text.ToDecimal) Then
ErrorMovtosRetIVA = True
End If
End If
'Se agregan las Ret ISR
If TxtRetISR.Text.ToDouble > 0 Then
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimientoImpuestos, TxtRetISR.Text.ToDecimal, " ", CveConceptoRetISR, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveIE:=CveIE, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=TxtRetISR.Text.ToDecimal) Then
ErrorMovtosRetISR = True
End If
End If
If TxtIEPS.Text.ToDouble > 0 Then
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimientoImpuestos, TxtIEPS.Text.ToDecimal, " ", CveConceptoRetIEPS, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveIE:=CveIE, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=TxtIEPS.Text.ToDecimal) Then
ErrorMovtosRetISR = True
End If
End If
If TxtOtrosImpuestos.Text.ToDouble <> 0 Then
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimientoImpuestos, TxtOtrosImpuestos.Text.ToDecimal, " ", CveConceptoRetOtrosImpuestos, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveIE:=CveIE, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=TxtOtrosImpuestos.Text.ToDecimal) Then
ErrorMovtosRetISR = True
End If
End If
End If
'' A N T I C I P O S
If ArrAnticipos.Count > 0 Then
Dim TotalIVA As Double = TxtIVA.Text.ToDouble
'Inserto otra poliza del mo
'Dim CvePrePolizaAnticipo As Integer = ObjConta.AddPrePolizas("Banc", 10, ImporteAnticipo, ImporteAnticipo, DdlMoneda.SelectedValue.ToEntero, TxtFecha.Text.ToDate, "", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa)
' CveConceptoAfectacion = 21 'Cancelacion Anticipo Proveedores
Dim PorcentajePago As Decimal
Dim CveConceptoAnt As Integer = 21
Dim CveCompraNC As Integer
For Each Ant As Compras_Compras.Anticipos In ArrAnticipos
CveCompraNC = CveCompra
Dim CveConceptoPago As Integer = 17
If CveTipoConcepto = 2 Then CveConceptoPago = 308 'cuando es acreedor
If CveMoneda > 1 Then
Select Case CveConceptoPago
Case 17
CveConceptoPago = 312
Case 308
CveConceptoPago = 309
Case Else
End Select
End If
Select Case Ant.TipoMovto
Case "NC", "DEV"
CveConceptoAnt = 60
CveCompraNC = Ant.CveCompra ' cuando es NC, se utiliza la clave de compra de la nota de credito
CveConceptoPago = 272
Case "Egsc"
CveConceptoAnt = 21
Case "DD"
CveConceptoAnt = 37
End Select
If ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, Ant.Importe, " ", CveConceptoAnt, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompraNC, CveCompraAmortizacion:=CveCompra, CveProveedor:=CveProveedorLocal, CveIE:=Ant.CveIE, ImporteMX:=Ant.Importe) Then
' ImporteAnticipo += Ant.Importe ' RESTO DEL IMPORTE POR SI QUEDA DIFERENCIA DE LA SUMA DE LOS ANTICIPOS Y EL PROVEEDOR TIENE QUE PAGAR
'movimiento de pago proveedor, --no se regisra porque no se registra el total de la compra como deuda del proveedor, solo lo que queda a deber
'si es l moviemiento es de amortizacion con descuento, no registra el pago, ya esta descontado
'If TieneAnticiposXML = False AndAlso Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimientoCompra, Ant.Importe, " ", CveConceptoPago, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveIE:=Ant.CveIE, ImporteMX:=Ant.Importe, CveCompraAmortizacion:=CveCompraNC) Then
' ErrorMovtosCxP = True
'End If
Dim Pago As New CompraPago
Pago.ImportePago = Ant.Importe
Pago.CveIE = Ant.CveIE
Pago.CveMonedaPago = 1
Pago.CveCompraAmortizacion = CveCompraNC
Pago.CveConceptoPago = CveConceptoPago
Pago.AplicaAcreditable = If(Ant.TipoMovto.Contiene("NC", "DEV"), False, True) 'SI ES NC, no se acredita
ErrorMovtosCxP = AplicaPrePolizaPagoCompra(CompraActual, Pago, CvePrePoliza, ObjConta)
Else
ErrorMovtosCxP = True
End If
Next
Dim ConceptoRenglon As String
'si hay una diferencia entre lo amortizado y el total, se registra la diferencia a proveedores y los ivas por acreditar
If TxtTotal.Text.ToDouble - ImporteAnticipo > 0 Then
PorcentajePago = (TxtTotal.Text.ToDecimal - ImporteAnticipo) / TxtTotal.Text.ToDecimal
If UsuarioActual.Empresa.UsaAC Then
If CtaProveedor > 0 Then
ConceptoRenglon = String.Format("GD Fact {0}-{1} {2}", TxtSerie.Text.Trim, TxtFolio.Text.Trim, DdlProveedor.SelectedItem.Text)
If Not ObjContaAC.AddMovimiento(IdPoliza, CtaProveedor, True, TxtTotal.Text.ToDouble - ImporteAnticipo, "", ConceptoRenglon, 0, TxtFechaPago.Text.ToDate, "") Then
ErrorAC = True
ErrorACMEnsaje.Append("- CtaProveedor > 0 ObjContaAC.AddMovimiento")
End If
Else
Alert(" - El proveedor no tiene cuenta contable.", TipoMensaje.MsgAdvertencia)
ErrorAC = True
End If
End If
End If
'una vez amortizado, se generan los movimientos presupuestales
If UsuarioActual.Empresa.UsaAC AndAlso ImporteAnticipo > 0 Then
PorcentajePago = ImporteAnticipo / TxtTotal.Text.ToDecimal
If ObjCompras.GetPresupuestosCompras(CveCompra) AndAlso ObjCompras.DtResultados.Rows.Count > 0 Then
'DtAC.Merge(ObjConta.DtResultados)
For Each dr As DataRow In ObjCompras.DtResultados.Rows
Total = dr("TotalPresupuesto").ToString.ToDecimal * PorcentajePago
If Total > 0 Then
'EJERCIDO
If True Then
ConceptoRenglon = String.Format("GE {0} F{1}-{2}", DdlProveedor.SelectedItem.Text, TxtSerie.Text, TxtFolio.Text)
If ObjContaAC.AddMovimiento(IdPoliza, dr("IdCuentaEjercido").ToString.ToEntero, False, MultiplicadorNC * Total, "", ConceptoRenglon, 0, TxtFechaPago.Text.ToDate, "") Then
'actualizo el idcuenta del presupuesto
If Not ObjContaAC.AddMovimiento(IdPoliza, dr("IdCuentaDevengado").ToString.ToEntero, True, MultiplicadorNC * Total, "", ConceptoRenglon, 0, TxtFechaPago.Text.ToDate, "") Then
TieneError = True
Exit For
End If
Else
TieneError = True
Exit For
End If
End If
'PAGADO
ConceptoRenglon = String.Format("GP {0} F{1}-{2}", DdlProveedor.SelectedItem.Text, TxtSerie.Text, TxtFolio.Text)
If ObjContaAC.AddMovimiento(IdPoliza, dr("IdCuentaPagado").ToString.ToEntero, False, MultiplicadorNC * Total, "", ConceptoRenglon, 0, TxtFechaPago.Text.ToDate, "") Then
'actualizo el idcuenta del presupuesto
If Not ObjContaAC.AddMovimiento(IdPoliza, dr("IdCuentaEjercido").ToString.ToEntero, True, MultiplicadorNC * Total, "", ConceptoRenglon, 0, TxtFechaPago.Text.ToDate, "") Then
TieneError = True
Exit For
End If
Else
TieneError = True
Exit For
End If
End If
Next
Else
ErrorACMEnsaje.Append("- Error al obtener presupuestos 2")
ErrorAC = True
End If
End If
End If
'' F U N C I O N A R I O S Y E M P L E A D O S
If RBLContado.SelectedValue = "2" AndAlso DdlFuncionarioEmpleado.SelectedValue.ToEntero > 0 Then
'Si es con funcionarios empleados Ya existe un registro en Bancos de Ingresos Egresos
TxtDocumentoImporte.Text = TxtDocumentoImporteFE.Text
TxtDocumentoImporteCaja.Text = TxtDocumentoImporteFE.Text
Dim ImportePagadoFE As Decimal = 0
Dim ImporteAPagarFE As Decimal = TxtDocumentoImporteFE.Text.ToDecimal
Dim ImportePagar As Decimal = ImporteAPagarFE
If CvePrePoliza > 0 Then
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, ImportePagar, ImportePagar, 29, " ", " ", 0, CveCompra:=CveCompra, CvePersonal:=DdlFuncionarioEmpleado.SelectedValue.ToEntero, CveProveedor:=CveProveedorLocal, CveIE:=CveIE) Then
ErrorMovtosCxP = True
End If
Dim Pago As New CompraPago
Pago.ImportePago = ImportePagar
Pago.CvePersonal = CvePersonal
Pago.CveIE = CveIE
Pago.CveMonedaPago = 1
ErrorMovtosCxP = AplicaPrePolizaPagoCompra(CompraActual, Pago, CvePrePoliza, ObjConta)
Else
ErrorMovtosCxP = True
End If
End If
End If 'Empresa Prueba
'************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************
'End If
Else
ErrorMovtosCxP = True
End If
End If
If HdnVCveOC.Value <> "-1" AndAlso HdnCveEstatusOC.Value <> "-1" Then
Dim ArrayCveOC As String() = HdnVCveOC.Value.Split(New Char() {","c})
Dim ArrayCveEstatusOC As String() = HdnCveEstatusOC.Value.Split(New Char() {","c})
If ArrayCveEstatusOC.Count = ArrayCveOC.Count Then
For i = 0 To ArrayCveEstatusOC.Count - 1
If Not ObjOC.UpdateOrdenCompraCompletada(ArrayCveEstatusOC(i).ToEntero, ArrayCveOC(i).ToEntero, UsuarioActual.CveUsuario, "Se vinculó Compra", CveCompra) Then
ErrorOC = True
Exit For
End If
Next
Else
ErrorOC = True
End If
End If
If ChkNCInvNC.Checked Then
For Each Gvr As GridViewRow In GVNCInv.Rows
If Gvr.FCTextBox("TxtCantidadNCInv").Text.ToDouble > 0 Then
If Not ObjCompras.ComprasDetalleDevolucionesAdd(Gvr.DataKey("CveCompraDetalle").ToEntero, CveCompra, Gvr.FCTextBox("TxtCantidadNCInv").Text.ToDouble, UsuarioActual.CveEmpresa) Then
ErrorMovInv = True
Exit For
End If
End If
Next
For Each Gvr As GridViewRow In GVNCInvAlmacen.Rows
If Gvr.FCTextBox("TxtCantidadNCInv").Text.ToDouble > 0 Then
If Not ObjCompras.ComprasDetalleDevolucionesAdd(Gvr.DataKey("CveCompraDetalle").ToEntero, CveCompra, Gvr.FCTextBox("TxtCantidadNCInv").Text.ToDouble, UsuarioActual.CveEmpresa) Then
ErrorMovInv = True
Exit For
End If
End If
Next
End If
'GUARDA BITACORA TIPO CAMBIO OC
If Not ErrorOC And TipoCambioOC > 0 Then
If Not ObjEventos.AddEventoBitacora(String.Format("La vinculación con la orden de compra fue con un tipo de cambio de ${0}", TipoCambioOC.ToString), "", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCompra:=CveCompra) Then
ErrorOC = True
End If
End If
'AGREGAR OTROS GASTOS A ORDEN DE CORTE
If CveOrdenCorte > 0 And UsuarioActual.CveEmpresa = 126 Then
If ObjCGame.AddCorteGasto(CveOrdenCorte, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, Now, 0, CveCompra) Then
If Not ObjCGame.AddCorteGastoDetalle(ObjCGame.CveCorteGasto, 32, 1, TxtSubTotal.Text.ToDouble()) Then
ErrorOtrosGastos = True
End If
Else
ErrorOtrosGastos = True
End If
End If
'CREDITO COMPRA
Dim CvePrePolizaCredito = 0
If RBLPago.SelectedValue.ToEntero = 2 AndAlso RBLContado.SelectedValue.ToEntero = 3 AndAlso DdlTipoCredito.SelectedValue.ToEntero = 1 AndAlso DdlCredito.SelectedValue.ToEntero > 0 Then
If Not ObjIE.UpdateCreditosCompra(DdlCredito.SelectedValue.ToEntero, CveCompra, UsuarioActual.CveEmpresa) Then
ErrorCreditosCompra = True
End If
If Not ErrorCreditosCompra Then
Dim CveConceptoPago As Integer = 17
If CveTipoConcepto = 2 Then CveConceptoPago = 308 'cuando es acreedor
If CveMoneda > 1 Then
Select Case CveConceptoPago
Case 17
CveConceptoPago = 312
Case 308
CveConceptoPago = 309
Case Else
End Select
End If
If ObjIE.GetCreditos(DdlCredito.SelectedValue.ToEntero, -1, -1, -1, -1, UsuarioActual.CveEmpresa) Then
CvePrePolizaCredito = ObjConta.AddPrePolizas("Compras/RegistrarCredito", -1, ObjIE.TotalFinanciado, ObjIE.TotalFinanciado, 1, TxtFecha.Text.ToDate, "Vinculación crédito con factura", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa)
If ObjConta.AddPrePolizasDetalle(CvePrePolizaCredito, False, ObjIE.TotalFinanciado.ToDecimal, "", CveConceptoPago, "Vinculación crédito con factura", TxtFecha.Text.ToDate, CtaProveedor, -1, CveProveedor:=CveProveedor, CveCompra:=CveCompra, ImporteMX:=ObjIE.TotalFinanciado.ToDecimal, CvePrePolizaOriginal:=CvePrePolizaCredito) Then
If Not ObjConta.AddPrePolizasDetalle(CvePrePolizaCredito, True, ObjIE.TotalFinanciado.ToDecimal, "", 50, "Vinculación crédito con factura", TxtFecha.Text.ToDate, CtaProveedor, -1, CveProveedor:=CveProveedor, CveCompra:=CveCompra, ImporteMX:=ObjIE.TotalFinanciado.ToDecimal, CvePrePolizaOriginal:=CvePrePolizaCredito) Then
ErrorCreditosCompra = True
End If
Else
ErrorCreditosCompra = True
End If
If Not ErrorCreditosCompra Then
ObjConta.PrePolizaUnificacion(CvePrePoliza, CvePrePolizaCredito)
End If
End If
End If
End If
'VALIDAR ERRORES
If ErrorAC OrElse ErrorPrepoliza OrElse ErrorPrepolizaDescuadre OrElse ErrorDetalles OrElse ErrorMovDev OrElse ErrorMovtosCxP OrElse ErrorMovtosRetIVA OrElse ErrorMovtosRetISR OrElse ErrorMovtosEstimaciones OrElse ErrorMovtosIE OrElse ErrorMovtosIVA OrElse ErrorMovInv OrElse TieneError OrElse ErrorAF OrElse ErrorOC OrElse ErrorBitacora OrElse ErrorAddAcarreos OrElse ErrorCreditosCompra Then
If ErrorDetalles Then
Alert("Ocurrió un Error al agregar un Producto o Servicio a la Factura.<br />Revise su factura y cualquier detalle comuníquese a Soporte Técnico", TipoMensaje.MsgAdvertencia)
ElseIf ErrorMovtosCxP Then
Alert("Ocurrió un Error al agregar las CxP.<br />Revise su factura y cualquier detalle comuníquese a Soporte Técnico", TipoMensaje.MsgAdvertencia)
ElseIf ErrorMovtosRetIVA Then
Alert("Ocurrió un Error al agregar las Retenciones de IVA.<br />Revise su factura y cualquier detalle comuníquese a Soporte Técnico", TipoMensaje.MsgAdvertencia)
ElseIf ErrorMovtosRetISR Then
Alert("Ocurrió un Error al agregar las Retenciones de ISR.<br />Revise su factura y cualquier detalle comuníquese a Soporte Técnico", TipoMensaje.MsgAdvertencia)
ElseIf ErrorMovtosEstimaciones Then
Alert("Ocurrió un Error al agregar las Estimaciones.<br />Revise su factura y cualquier detalle comuníquese a Soporte Técnico", TipoMensaje.MsgAdvertencia)
ElseIf ErrorMovtosIE Then
Alert("Ocurrió un Error al agregar el movimiento bancario.<br />Revise sus datos y cualquier detalle comuníquese a Soporte Técnico", TipoMensaje.MsgAdvertencia)
ElseIf ErrorMovtosIVA Then
Alert("Ocurrió un Error al agregar el IVA.<br />Revise su factura y cualquier detalle comuníquese a Soporte Técnico", TipoMensaje.MsgAdvertencia)
ElseIf ErrorMovInv Then
Alert("Ocurrió un Error al agregar el Producto o Servicio al Inventario.<br />Revise su factura y cualquier detalle comuníquese a Soporte Técnico", TipoMensaje.MsgAdvertencia)
ElseIf TieneError Then
Alert("El total de los IMPORTES del FINANCIAMIENTO debe ser mayor que 0 y menor o igual al total de la compra", TipoMensaje.MsgAdvertencia)
ElseIf ErrorAF Then
Alert("Error al actualizar la vinculacion del Activo Fijo", TipoMensaje.MsgAdvertencia)
ElseIf ErrorAC Then
Alert("Ocurrió un Error al insertar los movimientos contables.", TipoMensaje.MsgError)
GuardaLog($" Error Compras DESCRIPCIÓN DETALLADA {ErrorACMEnsaje.ToString} {vbCrLf} Usuario={UsuarioActual.CveUsuario}, Empresa={UsuarioActual.CveEmpresa}, CveFactura={CveFactura}, CveProveedor={CveProveedor}")
ElseIf ErrorPrepolizaDescuadre Then
Alert(ObjConta.MensajePolizaDescuadre, TipoMensaje.MsgError)
ElseIf ErrorPrepoliza Then
Alert("Ocurrió un Error al verificar los movimientos contables", TipoMensaje.MsgError)
ElseIf ErrorOC Then
Alert("Ocurrió un Error al vincular la Orden(es) de Compra. Por favor vuelva intentar.", TipoMensaje.MsgError)
ElseIf ErrorBitacora Then
Alert("Ocurrió un Error al guardar la refacturación.", TipoMensaje.MsgError)
ElseIf ErrorAddAcarreos Then
Alert("Ocurrio un Error al momento de agregar los acarreos.", TipoMensaje.MsgError)
ElseIf ErrorCreditosCompra Then
Alert("Ocurrió un Error al vincular la compra con el crédito.", TipoMensaje.MsgError)
ElseIf ErrorOtrosGastos Then
Alert("Ocurrió un Error al vincular la compra con la orden de corte.", TipoMensaje.MsgError)
ElseIf ErrorSATPS Then
Alert("Ocurrió un Error al actualizar el producto/servicio SAT.", TipoMensaje.MsgError)
ElseIf ErrorSaldosInvComp Then
Alert("Ocurrió un Error al validar la mercancía recibida por adelantado.", TipoMensaje.MsgError)
End If
ViewState("CveCompra") = -1
ObjCompras.RollBack()
If ObjContaAC IsNot Nothing Then ObjContaAC.RollBack()
CargaProveedor(CveProveedor, "-1")
Else
Dim MsgAccionAceptar As String = ""
Dim Msg As New StringBuilder
Msg.Append("La compra se registró correctamente")
'ACTUALIZA CVEFACTURA
If Request("CveFactura") IsNot Nothing Then
If Not ObjCompras.UpdateCompraFactura(CveCompra, Request("CveFactura").ToEntero, TxtSerie.Text.Trim, TxtFolio.Text.Trim) Then
TieneError = True
End If
If UsuarioActual.Empresa.UsaAC Then
MsgAccionAceptar = String.Format("window.opener.location.href = window.opener.location.href; window.open(""/Contabilidad/RegPoliza.aspx?IdPoliza={0}""); window.close();", IdPoliza)
Else
MsgAccionAceptar = "if (window.opener){window.opener.location.href = window.opener.location.href; window.close();}"
End If
Else
MsgAccionAceptar = "location.href =""Compras.aspx"""
End If
'CUANDO ES REEMBOLSO COMPROBACION Y CAJA CHICA
If UsuarioActual.CveEmpresa.Contiene(1, 119, 141) AndAlso TxtNumeroReembolso.Text.Trim <> "" AndAlso (DdlPersonalReembolso.SelectedValue.ToEntero > 0 Or DdlCuentaCajaChicaReembolso.SelectedValue.ToEntero > 0) Then
If ObjCompras.GetComprobacion(DdlPersonalReembolso.SelectedValue.ToEntero, DdlCuentaCajaChicaReembolso.SelectedValue.ToEntero, TxtNumeroReembolso.Text.Trim, UsuarioActual.CveEmpresa) Then
Dim CvePreComprobacion As Integer
If ObjCompras.DtResultados.Rows.Count = 0 Then
'sino existe, creamos la comprobacion
Dim tConcepto As String = If(DdlPersonalReembolso.SelectedValue.ToEntero > 0, DdlPersonalReembolso.SelectedItem.Text, DdlCuentaCajaChicaReembolso.SelectedItem.Text)
tConcepto = String.Format("{0}-{1}", tConcepto, TxtNumeroReembolso.Text.Trim)
CvePreComprobacion = ObjConta.AddPrePolizas("Compras Comproba", 1, 0, 0, 1, TxtFecha.Text.ToDate, tConcepto, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa)
If ObjCompras.AddComprobacion(DdlPersonalReembolso.SelectedValue.ToEntero, DdlCuentaCajaChicaReembolso.SelectedValue.ToEntero, TxtNumeroReembolso.Text.Trim, CvePreComprobacion, UsuarioActual.CveEmpresa) > 0 Then
End If
Else
'si ya existe, obtenemos la prepóliza
CvePreComprobacion = ObjCompras.DtResultados.FiltroPrimeroValor("CvePrePoliza").ToEntero
End If
ObjConta.PrePolizaUnificacion(CvePreComprobacion, CvePrePoliza)
End If
End If
'AJUSTA POLIZA
If IdPoliza > 0 Then
PolizaFolio = ObjContaAC.Folio
ObjContaAC.AjustaPoliza(IdPoliza)
Msg.AppendFormat("<br/><br/><a Class=""Texto"" target='_blank' href=""/Contabilidad/RegPoliza.aspx?IdPoliza={0}"">Ver Póliza</a>", IdPoliza)
End If
If CveMovimientoInventario > 0 Then
Dim TempParametros = Encripta(String.Format("OP=Alm&CveMovimiento={0}", CveMovimientoInventario))
Msg.AppendFormat("</br><a class=""Texto"" target='_blank' href=""/Inventarios/EntradasSalidas.aspx?CveMovimiento={0}"">Ver Movimiento de Almacen</a>", CveMovimientoInventario)
Msg.AppendFormat("</br><a class=""Texto"" target='_blank' href=""/Compras/PopUpVerFactura.aspx?P={0}"">Imprimir Entrada Almacen</a>", TempParametros)
End If
If Not ObjCompras.UpdateCompraPrePoliza(TxtFecha.Text.ToDate, PolizaFolio.ToString, IdPoliza, CvePrePoliza, CveCompra, 0) Then
TieneError = True
End If
If EntregaDirecta Then
Msg.AppendFormat($"</br><a class=""Texto"" target='_blank' href=""/Inventarios/RecepcionAlmacen.aspx?CveCompra={CveCompra}&ED=1"">Recibir mercancía de entrega directa.</a>")
End If
If UsuarioActual.Empresa.Funcionalidad(220) <> "" Then
If Not TieneError AndAlso Not ObjConta.PrePolizaSimplificacion(CvePrePoliza, UsuarioActual.CveEmpresa) Then
TieneError = True
Alert("No se pudo simplificar los movimientos", TipoMensaje.MsgError)
End If
End If
If Not TieneError Then
ObjCompras.Commit()
If ObjContaAC IsNot Nothing Then ObjContaAC.Commit()
Dim CveEvaluacionProveedor As Integer = -1
If Me.RequiereEvaluacion Then
Dim ObjPro As New ClsCompProveedores()
CveEvaluacionProveedor = ObjPro.AddEvaluacionProveedor(CveProveedor, CveCompra, Now, "", Me.CveUsuarioEvaluador, "", "", UsuarioActual.CveEmpresa)
ObjPro.Dispose()
End If
'ENVIO DE CORREO NOTIFICACION A VENDEDORES DE OC
MandaCorreoOCVendedores(CveCompra)
If Not ErrorMovInv Then
For Each intMovimientoAlmacen As Integer In ListaMovimientosAlmacen
MandaCorreoOCVendedoresRecepcionAlmacen(CveCompra, intMovimientoAlmacen)
Next
End If
If CveEvaluacionProveedor > 0 Then
Msg.Append("<br/><br/>El proveedor tiene evaluaciones pendientes<br/>")
Msg.Append("¿Desea realizar una evaluacion al proveedor?")
Msg.AppendFormat($"</br><a class=""Texto"" target='_blank' href=""/Compras/EvaluacionProveedor.aspx?CveEvaluacionProveedor={CveEvaluacionProveedor}"">Evaluar Proveedor.</a>")
End If
BtnGuardar.Enabled = False
UpFacturar.Update()
Alert(Msg.ToString, TipoMensaje.MsgInformacion, MsgAccionAceptar)
Else
ObjCompras.RollBack()
If ObjContaAC IsNot Nothing Then ObjContaAC.RollBack()
Alert("Ocurrio un error al guardar la compra. Por favor intente nuevamente.", TipoMensaje.MsgError)
End If
End If
Else
ObjCompras.RollBack()
If ObjContaAC IsNot Nothing Then ObjContaAC.RollBack()
Alert("Ocurrio un error al guardar la compra. Por favor intente nuevamente.", TipoMensaje.MsgError)
End If
Else
Alert("Debe seleccionar un Funcionario/Empleado o Caja Chica para Reembolsos. Por favor vuelva a intentar.", TipoMensaje.MsgError)
ObjCompras.RollBack()
If ObjContaAC IsNot Nothing Then ObjContaAC.RollBack()
End If
Else
Alert("Ocurrió un error al agregar el movimiento bancario.<br />Revise sus datos de pago y cualquier detalle comuníquese a Soporte Técnico", TipoMensaje.MsgAdvertencia)
ObjCompras.RollBack()
End If
End If
Catch ex As Exception
ObjCompras.RollBack()
If ObjContaAC IsNot Nothing Then ObjContaAC.RollBack()
Alert("Ocurrió un error al registrar la compra. Cualquier detalle comuníquese a Soporte Técnico", TipoMensaje.MsgError)
GuardaLog($"Ocurrió un error al registrar la compra. Cualquier detalle comuníquese a Soporte Técnico : {ex}")
ViewState("CveCompra") = -1
End Try
ObjAcar.Dispose()
ObjCompras.Dispose()
ObjConta.Dispose()
ObjIE.Dispose()
ObjInventario.Dispose()
ObjAF.Dispose()
ObjOC.Dispose()
ObjProveedores.Dispose()
ObjCGame.Dispose()
ObjProductosServicios.Dispose()
End If
End Sub
Private Function AjustaCombustibles() As Boolean
Dim Respuesta As Boolean = False
Dim IVADetalles As Decimal = TmpDT.SUMD("IVA", " IVA > 0 ")
Dim DiferenciaIVas As Decimal = TxtIVA.Text.ToDecimal - IVADetalles
If Not TmpDT.Columns.Contains("AplicaIEPS") Then
TmpDT.Columns.Add(New DataColumn("AplicaIEPS", GetType(Boolean)))
End If
If Not TmpDT.Columns.Contains("IEPSGrabaIVA") Then
TmpDT.Columns.Add(New DataColumn("IEPSGrabaIVA", GetType(Boolean)))
End If
For Each dRow As DataRow In TmpDT.Rows
Dim DttPS As DataTable = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=dRow("CvePS").ToString.ToEntero)
If DttPS IsNot Nothing AndAlso DttPS.Rows.Count > 0 Then
Dim DrPS As DataRow = DttPS.Rows(0)
dRow("AplicaIEPS") = Boolean.Parse(DrPS("AplicaIEPS").ToString)
dRow("IEPSGrabaIVA") = Boolean.Parse(DrPS("IEPSGrabaIVA").ToString)
Else
dRow("AplicaIEPS") = False
dRow("IEPSGrabaIVA") = False
End If
Next
Dim DTConsulta As New DataTable
DTConsulta = TmpDT.FiltraParametros(" AplicaIEPS = 'True' AND IEPSGrabaIVA = 'False' AND IVA > 0 ")
If DTConsulta.Rows.Count > 0 Then
Dim IndiceContador As Integer = 0
Dim IndiceUltimo As Integer = 0
Dim CantidadRegistroConIVA As Decimal
For Each dRow As DataRow In TmpDT.Rows
If Boolean.Parse(dRow("AplicaIEPS").ToString) And Boolean.Parse(dRow("IEPSGrabaIVA").ToString) = False And dRow("IVA").ToString.ToDecimal > 0 Then
IndiceUltimo = IndiceContador
CantidadRegistroConIVA = CantidadRegistroConIVA + 1
End If
IndiceContador = IndiceContador + 1
Next
IVADetalles = TmpDT.SUMD("IVA", " IVA > 0 ")
DiferenciaIVas = TxtIVA.Text.ToDecimal - IVADetalles
If Math.Abs(DiferenciaIVas) > 0.01D Then
If (TmpDT.Rows(IndiceUltimo)("IVA").ToString.ToDecimal + DiferenciaIVas) < 0 Then
Dim AjusteteDividido As Decimal = Math.Abs(DiferenciaIVas) / CantidadRegistroConIVA
For Each dRow As DataRow In TmpDT.Rows
If Boolean.Parse(dRow("AplicaIEPS").ToString) And Boolean.Parse(dRow("IEPSGrabaIVA").ToString) = False And dRow("IVA").ToString.ToDecimal > 0 Then
dRow("IVA") = dRow("IVA").ToString.ToDecimal - AjusteteDividido
End If
Next
Else
TmpDT.Rows(IndiceUltimo)("IVA") = TmpDT.Rows(IndiceUltimo)("IVA").ToString.ToDecimal + DiferenciaIVas
End If
TmpDT.AcceptChanges()
End If
End If
'Revalidacion de ajuste
IVADetalles = TmpDT.SUMD("IVA", " IVA > 0 ")
DiferenciaIVas = TxtIVA.Text.ToDecimal - IVADetalles
If Math.Abs(DiferenciaIVas) > 0.01D Then
Respuesta = False
If IVADetalles > 0 Then
For Each dRow As DataRow In TmpDT.Rows
If dRow("IVA").ToString.ToDecimal > 0 Then
dRow("IVA") = dRow("IVA").ToString.ToDecimal + DiferenciaIVas
TmpDT.AcceptChanges()
Respuesta = True
Exit For
End If
Next
Else
Alert("Los productos especificados en el listado no tienen asignado impuesto IVA, favor de realizar la corrección en el producto que aplique el impuesto.", TipoMensaje.MsgAdvertencia)
Respuesta = False
End If
Else
Respuesta = True
End If
If Respuesta Then
Dim IEPSPSDetalles As Decimal = TmpDT.SUMD("IEPSPS", " IEPSPS > 0 ")
Dim DiferenciaIEPSPS As Decimal = TxtIEPS.Text.ToDecimal - IEPSPSDetalles
Dim DTConsultaIEPSPS As New DataTable
DTConsultaIEPSPS = TmpDT.FiltraParametros(" AplicaIEPS = 'True'")
Dim IndiceContador As Integer = 0
Dim IndicePrimero As Integer = 0
For Each dRow As DataRow In TmpDT.Rows
If Boolean.Parse(dRow("AplicaIEPS").ToString) And dRow("IEPSPS").ToString.ToDecimal > 0 Then
IndicePrimero = IndiceContador
Exit For
End If
IndiceContador = IndiceContador + 1
Next
If DiferenciaIEPSPS.RoundAD(2) <> 0 Then
TmpDT.Rows(IndicePrimero)("IEPSPS") = TmpDT.Rows(IndicePrimero)("IEPSPS").ToString.ToDecimal + DiferenciaIEPSPS
TmpDT.AcceptChanges()
End If
For Each dRow As DataRow In TmpDT.Rows
If dRow("IEPSPSPorcentaje").ToString.ToDecimal > 0 AndAlso dRow("IEPSPS").ToString.ToDecimal = 0 Then
dRow("IEPSPSPorcentaje") = 0
End If
Next
TmpDT.AcceptChanges()
End If
Return Respuesta
End Function
Protected Sub TxtCodigo_TextChanged(sender As Object, e As System.EventArgs) Handles TxtCodigo.TextChanged
Dim ObjProveedores As New ClsCompProveedores()
Dim Codigo As String = "-1"
If TxtCodigo.Text.Trim <> String.Empty Then Codigo = TxtCodigo.Text.Trim
If Codigo <> "-1" Then
If ObjProveedores.GetProveedores(ClsCompProveedores.TipoConsulta.ParaUsoEnEmpresa, -1, Codigo, "-1", "-1", "-1", "-1", "-1", "-1", -1, UsuarioActual.CveEmpresa) Then
If ObjProveedores.DtResultados.Rows.Count > 0 Then
HdnCveProveedor.Value = ObjProveedores.CveProveedor.ToString
Else
Alert("No se encontró el Proveedor con el código: " & TxtCodigo.Text.Trim & ".", Extensiones.TipoMensaje.MsgAdvertencia)
End If
End If
ObjProveedores.Dispose()
BtnBuscarProveedor_Click(sender, e)
End If
End Sub
Protected Sub ImgSubProyecto_Click(sender As Object, e As EventArgs) Handles ImgSubProyecto.Click
DdlAsignarProyecto.SelectedValue = "-1"
CargaSubProyectoAsignado()
RegistraScript(String.Format("$('#{0}').modal('show');", "DivAplicaSubProyecto"))
End Sub
Protected Sub BtnEliminarCompra_Click(sender As Object, e As EventArgs) Handles BtnEliminarCompra.Click
Dim ObjAC As ClsContPAQi = Nothing
Dim Comp As New ClsCompras()
Dim ObjEventos As New ClsOIEventos(Comp.IniciaTransacSQL())
Dim ObjConta As New ClsContabilidad(Comp.IniciaTransacSQL())
Dim ErrorCompra = False
If (UsuarioActual.Empresa.UsaAC Or UsuarioActual.Empresa.UsaContabilidad) AndAlso IdPoliza > 0 AndAlso UsuarioActual.Empresa.TipoContabilidad = 2 Then
ObjAC = New ClsContPAQi(UsuarioActual.Empresa)
ObjAC.IniciaTransacSQL()
If Not ObjAC.RemovePoliza(IdPoliza) Then
ErrorCompra = True
End If
End If
If Not ErrorCompra Then
For Each gvr As GridViewRow In GvEB.Rows
If Not ObjEventos.RemoveEvento(gvr.DataKey("CveEvento").ToString.ToEntero, UsuarioActual.CveEmpresa) Then
ErrorCompra = True
Exit For
End If
Next
End If
If Not ErrorCompra Then
If Not ObjConta.UpdatePrePolizasDetalleBloquear(CvePrePoliza, False) Then
ErrorCompra = True
End If
End If
If Not ErrorCompra Then
If Not Comp.DeleteCompra(CveCompra, False) Then
ErrorCompra = True
End If
End If
If Not ErrorCompra Then
Alert("La Compra ha sido eliminada.", TipoMensaje.MsgInformacion, "document.location.href=""/Compras/Compras.aspx""")
If ObjAC IsNot Nothing Then ObjAC.Commit()
Comp.Commit()
Else
Alert("La Compra no ha sido eliminada.", TipoMensaje.MsgAdvertencia)
If ObjAC IsNot Nothing Then ObjAC.RollBack()
Comp.RollBack()
End If
If ObjAC IsNot Nothing Then ObjAC.Dispose()
Comp.Dispose()
ObjConta.Dispose()
End Sub
Protected Sub BtnAceptarAnticipos_Click(sender As Object, e As System.EventArgs) Handles BtnAceptarAnticipos.Click
If EstatusAlmacen = 1 Then
Alert("La compra encuentra pendiente de devolución de almacén, por lo cual no se puede amortizar el documento.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
'SI TIENE PENDIENTES POR RECIBIR EN ALMACEN, ESTOS PENDIENTES SE PUEDEN QUEMAR CON LAS NC APLICADAS
If CveCompra > 0 And GvInvMov.Rows.Count > 0 And ChkNCInv.Checked Then
CargaNCINV()
Else
GuardaAnticipos(Nothing, Nothing)
End If
End Sub
Private Sub GuardaAnticipos(ByRef ObjComprasParametro As ClsCompras, ByRef ObjContaParametro As ClsContabilidad)
Dim CveSubProyectoAnticipo As Integer = TmpDT.FiltroPrimeroValor("CveSubProyecto", "CveSubProyecto > 0").ToEntero
'SI YA VIENE LOS OBJETOS DE CLASE TOMA LOS DE PARAMETROS
Dim ObjCompra As ClsCompras
Dim ObjConta As ClsContabilidad
If ObjComprasParametro IsNot Nothing And ObjContaParametro IsNot Nothing Then
ObjCompra = ObjComprasParametro
ObjConta = ObjContaParametro
Else
ObjCompra = New ClsCompras
ObjConta = New ClsContabilidad(ObjCompra.IniciaTransacSQL)
End If
Dim Contador As Integer = 0
Dim Importe As Double = 0
Dim ErrorMovtosCxP As Integer = 0
Dim Fecha As Date
If ListaDocumentos Is Nothing And Not ListaDocumentos.Count > 0 Then
For Each gvr As GridViewRow In GVAnticipos.Rows
If gvr.FCCheckBox("Chk") IsNot Nothing AndAlso gvr.FCCheckBox("Chk").Checked Then
Contador += 1
'If gvr.DataKey("Fecha").ToDate > Fecha Then Fecha = gvr.DataKey("Fecha").ToDate 'guardo la fecha mayor
Importe += gvr.FCTextBox("TxtAnticipo").Text.ToDouble
If Math.Round(Importe, 2) - Math.Round(CompraSaldo, 2) > 0.01 Then gvr.FCTextBox("TxtAnticipo").Text = "" : gvr.FCCheckBox("Chk").Checked = False
End If
Next
Else
Contador = 1
End If
'If TxtFecha.Text.ToDate > Fecha Then Fecha = TxtFecha.Text.ToDate
Fecha = TxtFechaEjecucion.Text.ToDate
'Contador = 0
If Contador > 0 Then
If ListaDocumentos Is Nothing And Not ListaDocumentos.Count > 0 Then
If Math.Round(Importe, 2) - Math.Round(CompraSaldo, 2) > 0.01 Then
Alert("El Importe seleccionado excede al importe de la compra", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
End If
ArrAnticipos.Clear()
If CveCompra > 0 Then
Dim ObjContaAC As ClsContPAQi = Nothing
'INICIALIZA OBJETOS
If Not (ObjComprasParametro IsNot Nothing And ObjContaParametro IsNot Nothing) Then
ObjCompra = New ClsCompras
ObjConta = New ClsContabilidad(ObjCompra.IniciaTransacSQL)
End If
Dim CveCompraNC, IdCtaContable, IdCtaContableComp As Integer
Dim PorcentajePago As Decimal
Dim ConceptoPoliza As String = $"Amortización {NombreProveedor} - {TxtSerie.Text}-{TxtFolio.Text}"
Try
Dim CveIE As Integer = -1
Dim PorcentajeIVA As Decimal = TmpDT.MAX("IVAPorcentaje").ToDecimal
Dim CompraActual As New Compra
CompraActual.CveCompra = CveCompra
CompraActual.CveTipoConceptoProveedor = CveTipoConcepto
CompraActual.CveProveedor = CveProveedor
CompraActual.CveMoneda = DdlMoneda.SelectedValue.ToEntero
CompraActual.Fecha = TxtFecha.Text.ToDate
CompraActual.SerieFolio = TxtSerie.Text.Trim & "-" & TxtFolio.Text.Trim
CompraActual.ProveedorNombre = HplProveedor.Text
CompraActual.TC = TipoCambio
CompraActual.Total = TxtTotal.Text.ToDecimal
CompraActual.IVA = TxtIVA.Text.ToDecimal
CompraActual.IVADeducible = TxtIVA.Text.ToDecimal
CompraActual.IEPS = TxtIEPS.Text.ToDecimal
CompraActual.RetIVA = TxtRetIVA.Text.ToDecimal
CompraActual.RetISR = TxtRetISR.Text.ToDecimal
CompraActual.CveConceptoRetISR = DdlRetISRConcepto.SelectedValue.ToEntero
CompraActual.CveConceptoRetIVA = DdlRetIVAConcepto.SelectedValue.ToEntero
CompraActual.PorcentajeIVA = PorcentajeIVA
CompraActual.UsuarioActual = UsuarioActual
CompraActual.CveSubProyecto = TmpDT.FiltroPrimeroValor("CveSubProyecto", " CveSubProyecto > 0").ToEntero
CompraActual.IdCtaContableProv = CtaProveedor
CompraActual.IdCtaContableProvComplementaria = CtaProveedorComplementaria
CompraActual.EsImportacion = chkImportacion.Checked
Dim CvePrePolizaNueva As Integer = ObjConta.AddPrePolizas("Compras/Anticipos", 52, Importe, Importe, DdlMoneda.SelectedValue.ToEntero, Fecha, ConceptoPoliza, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa)
For Each gvr As GridViewRow In GVAnticipos.Rows
If gvr.FCCheckBox("Chk") IsNot Nothing AndAlso gvr.FCCheckBox("Chk").Checked Then
CveCompraNC = gvr.DataKey("CveCompra").ToEntero
If CvePrePoliza > 0 Then
Dim CveConceptoCompra As Integer = 60
Dim CveConceptoCompraComplementaria As Integer = 266
Dim TipoMovimientoCompra As Boolean = True
Dim CveMonedaAnticipo As Integer = gvr.DataKey("CveMoneda").ToEntero
Dim TipoCambioAnt As Decimal = gvr.DataKey("TCCompra").ToDecimal
Dim ImporteAnt As Decimal = gvr.FCTextBox("TxtAnticipo").Text.ToDecimal
Dim ImporComisionAnticipo As Decimal = gvr.FCTextBox("TxtComision").Text.ToDecimal
Dim Pago As New CompraPago
Pago.TipoPago = gvr.DataKey("TipoDocto")
Pago.ImportePago = ImporteAnt
Pago.OtroGastoIngreso = ImporComisionAnticipo
Pago.CveMonedaPago = CveMonedaAnticipo
Select Case gvr.DataKey("TipoDocto")
Case "NC", "DEV"
CveConceptoCompra = If(CveMonedaAnticipo = 1, 60, 60)
CveConceptoCompraComplementaria = 235
IdCtaContable = If(CveMonedaAnticipo = 1, CtaProveedor, CtaProveedorExtranjera)
IdCtaContableComp = CtaProveedorComplementaria
CveIE = -1
Pago.AplicaAcreditable = False
Case "Egsc"
CveConceptoCompra = If(CveMonedaAnticipo = 1, 21, 21)
CveConceptoCompraComplementaria = 266
IdCtaContable = If(CveMonedaAnticipo = 1, CtaProveedorAnticipos, CtaProveedorAnticiposExtranjera)
IdCtaContableComp = CtaProveedorAnticiposComplementaria
'vinculo la compra actual, y no la compra como si fuera nota de credito
CveCompraNC = -1
CveIE = gvr.DataKey("CveIE").ToEntero
CompraActual.IdCtaContableAnticipoProv = IdCtaContable
Case "DD"
CveConceptoCompra = If(CveMonedaAnticipo = 1, 37, 37)
IdCtaContable = CtaProveedorDeudores
'vinculo la compra actual, y no la compra como si fuera nota de credito
CveCompraNC = -1
CveIE = gvr.DataKey("CveIE").ToEntero
End Select
PorcentajePago = gvr.FCTextBox("TxtAnticipo").Text.ToDecimal / TxtTotal.Text.ToDecimal
If CveMonedaAnticipo > 1 Then
Dim ImporteAntMN As Decimal = TipoCambioAnt * ImporteAnt - ImporteAnt
If Not ObjConta.AddPrePolizasDetalle(CvePrePolizaNueva, TipoMovimientoCompra, ImporteAntMN, "", CveConceptoCompraComplementaria, "", TxtFechaPago.Text.ToDate, IdCtaContableComp, -1, CveCompra:=CveCompraNC, CveCompraAmortizacion:=CveCompra, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=ImporteAntMN, ImporteME:=If(TipoCambioAnt = 1, 0, ImporteAnt), TipoCambio:=TipoCambioAnt, CveSubProyecto:=CveSubProyectoAnticipo) Then
ErrorMovtosCxP = 1
End If
End If
Pago.CveIE = CveIE
Pago.CveCompraAmortizacion = CveCompraNC
AplicaPrePolizaPagoCompra(CompraActual, Pago, CvePrePolizaNueva, ObjConta)
End If
End If
Next
If ErrorMovtosCxP = 0 And CvePrePolizaNueva > 0 Then
If (UsuarioActual.Empresa.UsaAC Or UsuarioActual.Empresa.Funcionalidad(200).ToString = "1") AndAlso IdPoliza > 0 AndAlso UsuarioActual.Empresa.TipoContabilidad = 2 Then
If ObjContaAC Is Nothing Then
ObjContaAC = New ClsContPAQi(UsuarioActual.Empresa)
ObjContaAC.IniciaTransacSQL()
End If
If Not ObjConta.ContabilizarPrePoliza(CvePrePolizaNueva, UsuarioActual.CveUsuario, UsuarioActual.Empresa, MinFecha, "", ObjContaAC) Then
ErrorMovtosCxP = 3
End If
End If
End If
Select Case ErrorMovtosCxP
Case 0
If (UsuarioActual.Empresa.UsaAC Or UsuarioActual.Empresa.Funcionalidad(200).ToString = "1") AndAlso IdPoliza > 0 AndAlso UsuarioActual.Empresa.TipoContabilidad = 2 Then
If ObjContaAC IsNot Nothing Then
ObjContaAC.Commit()
End If
End If
Alert("El movimiento se aplicó correctamente.", TipoMensaje.MsgInformacion)
ObjCompra.Commit()
Dim dtnc As DataTable = Nothing
If ObjCompra.GetComprasNotasCredito(CveCompra, -1) Then
dtnc = ObjCompra.DtResultados
End If
GvAnticiposSel.DataSource = dtnc
GvAnticiposSel.DataBind()
LblAmortizacion.Text = (LblAmortizacion.Text.ToDouble + Importe).FormatoNumero
CompraSaldo = CompraSaldo - Importe
HdnCompraSaldo.Value = CompraSaldo.ToString
If CompraSaldo > 0 Then CargaAnticipos(CveProveedor)
If CveCompra > 0 Then VisualizaEstatusCompraSaldo(DdlTipoComprobante.SelectedValue, CompraSaldo.ToDecimal, TxtTotal.Text.ToDecimal)
UpAnticipos.Update()
UpPS.Update()
dtnc.Dispose()
Case 1
Alert("Ocurrió un error al amortizar la nota de crédito<br />Revise su factura y cualquier detalle comuníquese a Soporte Técnico", TipoMensaje.MsgAdvertencia)
ObjCompra.RollBack()
Case 2
Alert("Ocurrió un error al amortizar la nota de crédito<br />Revise su factura y cualquier detalle comuníquese a Soporte Técnico", TipoMensaje.MsgAdvertencia)
ObjCompra.RollBack()
Case 3
Alert("Ocurrió un error al contabilizar la la amortizacion del anticipo.", TipoMensaje.MsgAdvertencia)
If (UsuarioActual.Empresa.UsaAC Or UsuarioActual.Empresa.Funcionalidad(200).ToString = "1") AndAlso IdPoliza > 0 AndAlso UsuarioActual.Empresa.TipoContabilidad = 2 Then
If ObjContaAC IsNot Nothing Then
Try
ObjContaAC.RollBack()
Catch ex As Exception
End Try
End If
End If
ObjCompra.RollBack()
End Select
Catch ex As Exception
ObjCompra.RollBack()
End Try
If ObjContaAC IsNot Nothing Then
ObjContaAC.Dispose()
End If
ObjCompra.Dispose()
Else
'sino se ha guardado la compra, se registra temporal que anticpos van a cargarle
For Each gvr As GridViewRow In GVAnticipos.Rows
If gvr.FCCheckBox("Chk") IsNot Nothing AndAlso gvr.FCCheckBox("Chk").Checked Then
ArrAnticipos.Add(New Anticipos With {.CvePrePoliza = gvr.DataKey("CvePrePoliza").ToEntero, .CveIE = gvr.DataKey("CveIE").ToString.ToEntero, .CveCompra = gvr.DataKey("CveCompra").ToEntero, .Importe = gvr.FCTextBox("TxtAnticipo").Text.ToDecimal, .ImporteComision = gvr.FCTextBox("TxtComision").Text.ToDecimal, .TCCompra = gvr.DataKey("TCCompra").ToDecimal, .TipoMovto = gvr.DataKey("TipoDocto")})
End If
Next
Dim ImporteAnticipo As Decimal = 0
If ArrAnticipos.Count > 0 Then
For Each Ant As Compras_Compras.Anticipos In ArrAnticipos
ImporteAnticipo += Ant.Importe
Next
End If
LblAmortizacion.Text = ImporteAnticipo.FormatoNumero
LblAplicadoCompraAnt.Text = ImporteAnticipo.FormatoNumero
LblSaldoFactura.Text = (TxtTotal.Text.ToDecimal - ImporteAnticipo).ToString.FormatoNumero
UpPS.Update()
End If
RegistraScript(String.Format("$('#{0}').modal('hide');", "DivAnticipos"))
Else
Alert("No hay movimientos seleccionados para aplicar", TipoMensaje.MsgAdvertencia)
End If
UPPAnticiposSel.Update()
End Sub
Protected Sub ImgClasificacion_Click(sender As Object, e As EventArgs) Handles ImgClasificacion.Click
If CveCompra > 0 Then
Dim SiSelecciono As Boolean = False
For Each gvr As GridViewRow In GvPS.Rows
If gvr.FCCheckBox("CheckClasificacion").Checked = True Then
SiSelecciono = True
Exit For
End If
Next
If SiSelecciono = False Then
Alert("Tiene que seleccionar algun Producto o Servicio", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
DdlAplicaClasificacion.SelectedValue = "-1"
RegistraScript(String.Format("$('#{0}').modal('show');", "DivClasificacion"))
Else
RegistraScript(String.Format("$('#{0}').modal('show');", "DivClasificacion"))
End If
End Sub
Protected Sub BtnActualizar_Click(sender As Object, e As EventArgs) Handles BtnActualizar.Click
If CveFactura > 0 Then
If Not AjustaCombustibles() Then
Exit Sub
End If
End If
'VALIDA IMPORTES
If CveFactura > 0 Then 'SI NO VIENE DE FACTURA/XML NO VALIDA TOTALES
If Not ValidaTotalesGuardar() Then
Exit Sub
End If
End If
If DdlRembolsoCajaChica.SelectedValue.ToEntero() > 0 AndAlso DdlRembolsoPersonal.SelectedValue.ToEntero() > 0 Then
Alert("No se puede tener seleccionada una 'Caja Chica' y 'Personal/Empleado' a la vez", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
For Each Row As DataRow In TmpDT.Rows
If Row("CveSubProyecto").ToString.ToEntero <= 0 Then
Alert("No se ha completado la asignacion de proyectos en la compra. ", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
If Row("CveClasificacionActualizar").ToString.ToEntero <= 0 Then 'If NotHas117 AndAlso Row("CveClasificacionActualizar").ToString.ToEntero <= 0 Then
Alert("Hay productos que no tienen clasificación asignada.<br> Favor de asignarle una y darle guardar.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
If UsuarioActual.Empresa.Funcionalidad(527) = "1" Then
If Row("CveTipoGasto").ToString.ToEntero <= 0 Then
Alert("No se ha completado la asignacion de tipos de gasto en la compra.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
End If
Next
Dim ObjCompra As New ClsCompras
Dim ObjProveedores As New ClsCompProveedores(ObjCompra.IniciaTransacSQL())
Dim ObjInventario As New ClsInventarios(ObjCompra.IniciaTransacSQL)
Dim ObjContabilidad As New ClsContabilidad(ObjCompra.IniciaTransacSQL)
Dim ObjAF As New ClsAF(ObjCompra.IniciaTransacSQL)
Dim ObjContaAC As ClsContPAQi = Nothing
Dim Retorno As Boolean = True
Dim CveEstatusFactura As Integer = HdnCveEstatusFactura.Value.ToEntero
Dim MultiplicadorNC = If(DdlTipoComprobante.SelectedValue = "NC", -1, 1)
Dim ErrorAC = False
Dim IDPolizaComprometido = 0
If ChkProgramarPago.Checked AndAlso CveEstatusFactura = 1 Then
CveEstatusFactura = 2
End If
If Not ChkProgramarPago.Checked AndAlso CveEstatusFactura = 2 Then
CveEstatusFactura = 1
End If
Try
'Revisamos que los cambios hechos mantengan la interidad de los numeros
If HFDiferenciaCompra.Value = TxtTotal.Text Or CveFactura < 1 Or CveCompra < 1 Then
If IdPoliza > 0 Then
If Not ObjContabilidad.UpdatePrePolizasDetalleBloquear(CvePrePoliza, False) Then
Retorno = False
End If
If Not ObjContabilidad.UpdatePrePoliza(MinFecha, -1, -1, Nothing, CvePrePoliza, UsuarioActual.CveEmpresa, CveUsuarioModifico:=UsuarioActual.CveUsuario) Then
Retorno = False
End If
End If
'PORCENTAJE IVA
Dim PorcentajeIVA As Decimal = TmpDT.MAX("IVAPorcentaje").ToDecimal
Dim TmpCveRetIVAConcepto As Integer = If(CveRetIVAConceptoOriginal <> DdlRetIVAConcepto.SelectedValue.ToEntero, DdlRetIVAConcepto.SelectedValue.ToEntero, -1)
Dim TmpCveRetISRConcepto As Integer = If(CveRetISRConceptoOriginal <> DdlRetISRConcepto.SelectedValue.ToEntero, DdlRetISRConcepto.SelectedValue.ToEntero, -1)
If ObjCompra.UpdateCompra(TxtDescripcion.Text.Trim, TxtFolioSecundario.Text.Trim, TxtFechaPago.Text.ToDate, ChkAplicaNotaCredito.Checked, TxtObsFact.Text.Trim, CveEstatusFactura,
TxtDescuento.Text.ToDouble, TxtSubTotal.Text.ToDouble, TxtIVA.Text.ToDouble, TxtTotal.Text.ToDouble,
UsuarioActual.CveUsuario, CveCompra, CveCajaChica:=DdlRembolsoCajaChica.SelectedValue.ToEntero, CvePersonal:=DdlRembolsoPersonal.SelectedValue.ToEntero, CveProveedorSucursal:=If(DdlProveedorSucursal.SelectedValue.ToEntero > 0, DdlProveedorSucursal.SelectedValue.ToEntero, -1), PorcentajeIVA:=PorcentajeIVA, NumeroReembolso:=TxtRembolsoNumero.Text,
CveTipoCompra:=DdlTipoCompra.SelectedValue.ToEntero, NoDeducible:=EsNoDeducible, CveRetIVAConcepto:=TmpCveRetIVAConcepto, CveRetISRConcepto:=TmpCveRetISRConcepto) Then
If Not ComparaDatatables() Then
'Regeneramos el concepto 6 de PrePolizas
'If UsuarioActual.Empresa.Funcionalidad(207) = "1" Then
' If Not RegenerarPrePoliza(ObjContabilidad, ObjContaAC, 6, False, MultiplicadorNC) Then
' Retorno = False
' End If
'End If
If Not TmpDT.Columns.Contains("DesvicularAF") Then
TmpDT.Columns.Add("DesvicularAF", GetType(Boolean))
End If
For Each drowAF As DataRow In TmpDT.Rows
If drowAF("DesvicularAF").ToString <> "" AndAlso Boolean.Parse(drowAF("DesvicularAF").ToString) Then
If Not ObjAF.UpdateActivosFijosCompra(-1, drowAF("CveCompraDetalle").ToString.ToEntero, -1, 0, Now, Opcion:=2) Then
Retorno = False
End If
End If
Next
'If UsuarioActual.Empresa.Funcionalidad(207) = "1" Then
If Not ActualizarPrePoliza(ObjContabilidad, ObjCompra) Then
Retorno = False
End If
'End If
'---------------------------------------------------------------------------------------------------
''EMPIEZA: SI USA AC
If UsuarioActual.Empresa.UsaAC AndAlso IdPoliza > 0 Then
ObjContaAC = New ClsContPAQi(UsuarioActual.Empresa)
ObjContaAC.IniciaTransacSQL()
'ELIMINA TODOS LOS MOVIMIENTOS DE LA POLIZA
ObjContaAC.RemoveAllMovimientos(IdPoliza)
'INSERTA LOS NUEVOS MOVIMIENTOS DE LA POLIZA
If IdPoliza > 0 Then
Dim CuentaAbono As Integer
Dim Importe As Decimal = 0
Dim TotalDetalle As Decimal = 0
'CUENTA PROVEEDOR
If CtaProveedor <= 0 Then
If ObjContaAC.GetCuentas(-1, "021120000000000000", -1) Then
Dim drCuenta As DataRow = ObjContaAC.DtResultados.FiltroPrimero("")
If drCuenta IsNot Nothing Then
CuentaAbono = drCuenta("Id").ToString.ToEntero
Dim FolioProveedor = ObjContaAC.GetFolioProveedores("021120000000000000").ToString
ViewState("CtaProveedor") = ObjContaAC.AddCuenta(String.Format("02112{0}000000000", FolioProveedor.PadLeft(4, "0"c)), NombreProveedor, "D", 2, 0, 1, 0, "", 1, CuentaAbono)
ObjProveedores.UpdateProveedorIdCuentaAC(CveProveedor, CtaProveedor)
Else
ErrorAC = True
End If
Else
ErrorAC = True
End If
End If
Dim ConceptoRenglon As String = ""
If Not ErrorAC Then
Dim tTotalIVA, tTotalGral, tDiferenciaIVA, tIVA, tRetIVA, tRetISR As Decimal
Dim ipresup As Integer = 0
'COMIENZA: PRUEBA AGRUPACION CONCEPTOS
Dim Presup = From gvr As DataRow In TmpDT.Rows.Cast(Of DataRow)()
Group gvr By Grp = New With {
Key .CvePresupuestoEgreso = gvr("CvePresupuestoEgreso").ToString.ToEntero,
Key .CveActivoFijo = If(gvr("TipoAF").ToString.ToEntero = 2, gvr("CveActivoFijo").ToString.ToEntero, -1)
} Into Group
Select Grp.CvePresupuestoEgreso, Grp.CveActivoFijo,
TotalImporte = Group.Sum(Function(r) r("Total").ToString.ToDecimal)
Dim Fecha As Date = TxtFecha.Text.ToDate
'PresupuestoEgresos
Dim DtPresupuestosTemp As DataTable
Dim IdCuentaComprometido, IdCuentaPorEjercer, IdCuentaDevengado, IdCuentaMatriz As Integer
'Dim tTotalIVA, tTotalGral, tDiferenciaIVA, tIVA As Double
tTotalIVA = TxtIVA.Text.ToDecimal
tRetIVA = TxtRetIVA.Text.ToDecimal
tRetISR = TxtRetISR.Text.ToDecimal
'tTotalIVA = tTotalIVA - tRetIVA - tRetISR
tTotalGral = TxtTotal.Text.ToDecimal + tRetIVA + tRetISR ' EL TOTAL GENERAL DEBE DE SER EL SUBTOTAL + IVA, NO SE DEBEN DE INCLUIR LAS RETENCIONES, POR ESO SE RESTA
tDiferenciaIVA = tTotalIVA
tIVA = 0
ipresup = 0
'INVENTARIOS EN AC
Dim CuentaMatrizAlmacen As Integer
Dim ContadorInventario As Integer = GvInv.Rows.Cast(Of GridViewRow)().Count(Function(gvr) gvr.FCCheckBox("cbInv").Checked)
Dim CtaAlmacen As Integer
If ContadorInventario > 0 Then
Dim drr As DataRow = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimero(String.Format("CveAlmacen = {0}", GvInv.HeaderRow.FCDropDownList("ddlAlmacen").SelectedValue.ToString.ToEntero))
If drr IsNot Nothing Then
CtaAlmacen = drr("IdCtaContable").ToString.ToEntero
End If
End If
Dim DescuentoConIVA As Double
Dim tPorIVA As Decimal = tTotalIVA / (tTotalGral - tTotalIVA)
Dim tAjusteTotal As Decimal = 0
For Each grp In Presup
Importe = grp.TotalImporte
TotalDetalle += Importe
ipresup += 1
If Importe > 0 Then
'saco la proporcion de iva que le corresponde
tIVA = Math.Round(Importe * tPorIVA, 2)
tDiferenciaIVA -= tIVA
'identifico si es el ultimo registro, para ver si es necesario un ajuste
If ipresup = Presup.Count Then
If Math.Round(TotalDetalle - tTotalGral, 2) <= 0.01 AndAlso tDiferenciaIVA > 0 Then
tIVA += tDiferenciaIVA
End If
End If
'le sumo el iva al concepto
Importe += tIVA
'codigo Provisional, para cuand tenga descuento, solo tome el subtotal * el iva,RMF
If TxtDescuento.Text.ToDouble > 0 Then
Importe = grp.TotalImporte * (1 + tPorIVA)
End If
tAjusteTotal += Importe
'valido que la sumas de lo detalles no exceda al totalgeneral
If Math.Round(tAjusteTotal, 2) > tTotalGral Then
'le resto la diferencia
Importe -= (tAjusteTotal - tTotalGral)
End If
'Presupuesto Egresos
DtPresupuestosTemp = DtPresupuestos.FiltraParametros(String.Format("CvePresupuestoEgreso = {0}", grp.CvePresupuestoEgreso))
If DtPresupuestosTemp.Rows.Count <> 1 Then
ErrorAC = True
Exit For
End If
IdCuentaComprometido = DtPresupuestosTemp.Rows(0)("IdCuentaComprometido").ToString.ToEntero
IdCuentaPorEjercer = DtPresupuestosTemp.Rows(0)("IdCuentaPorEjercer").ToString.ToEntero
IdCuentaDevengado = DtPresupuestosTemp.Rows(0)("IdCuentaDevengado").ToString.ToEntero
IdCuentaMatriz = DtPresupuestosTemp.Rows(0)("IdCuentaMatriz").ToString.ToEntero
'COMPROMETIDO DEPENDIENTE SI EXISTE SU POLIZA
If IDPolizaComprometido = 0 Then
ConceptoRenglon = String.Format("GC Fact: {0}-{1} {2}", TxtSerie.Text.Trim, TxtFolio.Text.Trim, DdlProveedor.SelectedItem.Text)
If ObjContaAC.AddMovimiento(IdPoliza, IdCuentaComprometido, False, MultiplicadorNC * Importe, "", ConceptoRenglon, 0, Fecha, "") Then
If Not ObjContaAC.AddMovimiento(IdPoliza, IdCuentaPorEjercer, True, MultiplicadorNC * Importe, "", ConceptoRenglon, 0, Fecha, "") Then
ErrorAC = True
Exit For
End If
Else
ErrorAC = True
Exit For
End If
End If
ConceptoRenglon = String.Format("GD Fact: {0}-{1} {2}", TxtSerie.Text.Trim, TxtFolio.Text.Trim, DdlProveedor.SelectedItem.Text)
'DEVENGADO
If ObjContaAC.AddMovimiento(IdPoliza, IdCuentaDevengado, False, MultiplicadorNC * Importe, "", ConceptoRenglon, 0, Fecha, "") Then
If Not ObjContaAC.AddMovimiento(IdPoliza, IdCuentaComprometido, True, MultiplicadorNC * Importe, "", ConceptoRenglon, 0, Fecha, "") Then
ErrorAC = True
Exit For
End If
Else
ErrorAC = True
Exit For
End If
If ContadorInventario > 0 Then
Dim tImporte, ttIVA As Double
For Each gvr As GridViewRow In GvPS.Rows
'registra los movimientos del presupuesto asignado, para que no se duplique si hay varios presupeusto dentro de la compra
If gvr.DataKey("CvePresupuestoEgreso").ToEntero = grp.CvePresupuestoEgreso Then
'saco la proporcion de iva que le corresponde
tImporte = gvr.FCLiteral("LtlTotal").Text.ToDouble
ttIVA = Math.Round(tImporte * tTotalIVA / tTotalGral, 2)
' ' 'le sumo el iva al concepto
tImporte += ttIVA
End If
Next
CuentaMatrizAlmacen = CtaAlmacen
ElseIf grp.CveActivoFijo > 0 Then
Dim CtaAF = -1
Dim AF = ""
Dim CuentaInicial = -1
If ObjAF.GetActivosFijos(grp.CveActivoFijo, UsuarioActual.CveEmpresa, "-1", "-1", -1, -1, "-1", -1, -1, -1, -1, -1, "", -1, UsuarioActual.CveEmpresa) Then
CtaAF = ObjAF.Cuenta
AF = ObjAF.Descripcion
CuentaInicial = ObjAF.CuentaInicial
Else
ErrorAC = True
Exit For
End If
If Not CuentaInicial > 0 Then
CuentaInicial = 1241
End If
'CUENTA AF
If CtaAF <= 0 Then
If ObjContaAC.GetCuentas(-1, String.Format("0{0}0000000000000", CuentaInicial), -1) Then
Dim drCuenta As DataRow = ObjContaAC.DtResultados.FiltroPrimero("")
If drCuenta IsNot Nothing Then
CuentaAbono = drCuenta("Id").ToString.ToEntero
Dim FolioAF = ObjContaAC.GetFolioProveedores(String.Format("0{0}0000000000000", CuentaInicial)).ToString
CtaAF = ObjContaAC.AddCuenta(String.Format("0{0}{1}000000000", CuentaInicial, FolioAF.PadLeft(4, "0"c)), AF, "A", 2, 0, 1, 0, "", 1, CuentaAbono)
ObjAF.UpdateActivosFijosCuentaAC(grp.CveActivoFijo, CtaAF, UsuarioActual.CveUsuario)
Else
ErrorAC = True
End If
Else
ErrorAC = True
End If
End If
CuentaMatrizAlmacen = CtaAF
Else
CuentaMatrizAlmacen = IdCuentaMatriz
End If
''AFECTAR MATRIZ EGRESOS
If ObjContaAC.AddMovimiento(IdPoliza, CuentaMatrizAlmacen, False, MultiplicadorNC * Importe, "", ConceptoRenglon, 0, Fecha, "") Then
''VERIFICA SI TIENE DESCUENTO (AMORTIZACION)
If TxtDescuento.Text.ToDouble > 0 AndAlso CtaProveedorAnticipos > 0 Then
DescuentoConIVA = TxtDescuento.Text.ToDecimal * 1.16
'Valida que el descuento con iva cuadre en los totales
If Math.Abs(DescuentoConIVA - (Importe - TxtTotal.Text.ToDouble)) < 0.02 Then
DescuentoConIVA = Importe - TxtTotal.Text.ToDouble
ElseIf DescuentoConIVA <> (Importe - TxtTotal.Text.ToDecimal) Then
ErrorAC = True
Exit For
End If
'actualizo el idcuenta del presupuesto
If ObjContaAC.AddMovimiento(IdPoliza, CtaProveedor, True, MultiplicadorNC * (Importe - DescuentoConIVA), "", ConceptoRenglon, 0, Fecha, "") Then
'agrego a la cuenta contable anticipos
If Not ObjContaAC.AddMovimiento(IdPoliza, CtaProveedorAnticipos, True, MultiplicadorNC * DescuentoConIVA, "", ConceptoRenglon, 0, Fecha, "") Then
ErrorAC = True
Exit For
End If
Else
ErrorAC = True
Exit For
End If
Else
'actualizo el idcuenta del
End If
Else
ErrorAC = True
Exit For
End If
''TERMINA AFECTAR MATRIZ EGRESOS
Else
ErrorAC = True
Exit For
End If
Next
If Not ErrorAC Then
'registro un solo movimiento a proveedores
Importe = TxtTotal.Text.ToDecimal
If Not ObjContaAC.AddMovimiento(IdPoliza, CtaProveedor, True, MultiplicadorNC * Importe, "", ConceptoRenglon, 0, Fecha, "") Then
ErrorAC = True
End If
End If
If tRetISR > 0 Then
ConceptoRenglon = String.Format("GD Fact: {0}-{1} {2}", TxtSerie.Text.Trim, TxtFolio.Text.Trim, DdlProveedor.SelectedItem.Text)
If Not ObjContaAC.AddMovimiento(IdPoliza, CtaProveedorRetISR, True, MultiplicadorNC * tRetISR, "", ConceptoRenglon, 0, Fecha, "") Then
ErrorAC = True
End If
End If
End If
Else
ErrorAC = True
End If
'CUADRA LA POLIZA
ObjContaAC.AjustaPoliza(IdPoliza)
End If
''TERMINA: SI USA AC
'----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
If Not ErrorAC Then
Dim Cont As Integer = 0
Dim indiceTR = 0
For Each Row As DataRow In TmpDT.Rows
'actualizar las clasificaciones, que se hallan hecho
If Row("CveClasificacionActualizar").ToString.ToEntero > 0 Then
'REGISTRO EL PRODUCTO
Dim PSS As New ClsProductosServicios
If Not PSS.UpdateClasificacionPS(Row("CveClasificacionActualizar").ToString.ToEntero, UsuarioActual.CveUsuario, Row("CvePS").ToString.ToEntero) Then
Retorno = False
Exit For
End If
'Row("CvePS") = 20184 'PSS.DtResultados.FiltraParametros("PS = '" & Row("PS").ToString & "' AND CveEmpresa = " & UsuarioActual.CveEmpresa).Rows(0)("CvePS").ToString
PSS.Dispose()
End If
Dim CvePersonal = GvPersonal.Rows(Cont).FCDropDownList("DdlPersonalGv").SelectedValue.ToEntero
Dim Referencia = GvPersonal.Rows(Cont).FCTextBox("TxtReferencia").Text
Cont = Cont + 1
'Si es AF-INSUMO se guarda en CveActivoFIjo
Dim CveAF = If(Row("CveActivoFijo").ToString.ToEntero > 0 AndAlso Row("TipoAF").ToString.ToEntero = 1, Row("CveActivoFijo").ToString.ToEntero, -1)
'Si es AF-COMPRA se guarda en CveActivoFijoCompra
Dim CveAFCompra = If(Row("CveActivoFijo").ToString.ToEntero > 0 AndAlso Row("TipoAF").ToString.ToEntero = 2, Row("CveActivoFijo").ToString.ToEntero, -1)
If Row("CveCompraDetalle").ToString.ToEntero > 0 Then
If Not ObjCompra.UpdateCompraDetalle(Row("CvePS").ToString.ToEntero, Row("Cantidad").ToString.ToDouble, Row("PU").ToString.ToDouble, Row("IVA").ToString.ToDouble, Row("Total").ToString.ToDouble,
Row("Descuento").ToString.ToDouble, Row("Obs").ToString, Row("CveSubProyecto").ToString.ToEntero, Row("CvePresupuestoEgreso").ToString.ToEntero, CveAF, Row("CveCompraDetalle").ToString.ToEntero, CvePersonal:=CvePersonal, CveTipoGasto:=Row("CveTipoGasto").ToString.ToEntero, AF_Medida:=Row("AFMedida").ToString.ToEntero, AF_TipoMantenimiento:=Row("AFTipoMantenimiento").ToString.ToEntero, Referencia:=Referencia,
RetIVA:=Row("RetIVA").ToString.ToDouble, RetISR:=Row("RetISR").ToString.ToDouble, IEPSPS:=Row("IEPSPS").ToString.ToDouble, IEPSPSIVA:=Row("IEPSPSIVA").ToString.ToDouble,
IVAPorcentaje:=Row("IVAPorcentaje").ToString.ToDouble, RetIVAPorcentaje:=Row("RetIVAPorcentaje").ToString.ToDouble, RetISRPorcentaje:=Row("RetISRPorcentaje").ToString.ToDouble, IEPSPSPorcentaje:=Row("IEPSPSPorcentaje").ToString.ToDouble, IEPSPSIVAPorcentaje:=Row("IEPSPSIVAPorcentaje").ToString.ToDouble, NoDeducible:=If((Row("NoDeducible").ToString().ToUpper().Contiene("TRUE", "1")) AndAlso EsNoDeducible, True, False), CveContratoDetalle:=Row("CveContratoDetalle").ToString.ToEntero) Then
Retorno = False
Exit For
End If
Else
Dim TipoRecepcion As Integer = -1
If GvInv.Rows.Count > indiceTR Then
If GvInv.Rows(indiceTR).FCCheckBox("cbInv").Checked = True And GvInv.Rows(indiceTR).FCDropDownList("DdlRecibirInv").SelectedValue = "1" Then
TipoRecepcion = 1
ElseIf GvInv.Rows(indiceTR).FCCheckBox("cbInv").Checked = True And GvInv.Rows(indiceTR).FCDropDownList("DdlRecibirInv").SelectedValue = "0" Then
TipoRecepcion = 2
End If
End If
If Not ObjCompra.AddCompraDetalle(CveCompra, Row("CveUM").ToString.ToEntero, Row("CvePS").ToString.ToEntero, Row("CveSubProyecto").ToString.ToEntero, -1, CveAF,
Row("Cantidad").ToString.ToDecimal, Row("PU").ToString.ToDecimal, Row("IVA").ToString.ToDecimal, Row("Total").ToString.ToDecimal, Row("Descuento").ToString.ToDecimal,
Row("Obs").ToString, Row("CveOrdenCompraDetalle").ToString.ToEntero, TipoRecepcion, Row("CveContrato").ToString.ToEntero, Row("CvePresupuestoEgreso").ToString.ToEntero,
AplicaCostoIndirecto:=Row("AplicaCostoIndirecto").ToString.ToEntero, EstatusAlmacen:=Row("EntregaDirecta").ToString.ToEntero, CvePersonal:=CvePersonal,
CveTipoGasto:=Row("CveTipoGasto").ToString.ToEntero, AF_Medida:=Row("AFMedida").ToString.ToEntero, AF_TipoMantenimiento:=Row("AFTipoMantenimiento").ToString.ToEntero, Referencia:=Referencia, OtrosGastos:=Row("OtrosGastos").ToString.ToDecimal,
RetIVA:=Row("RetIVA").ToString.ToDecimal, RetISR:=Row("RetISR").ToString.ToDecimal, IEPSPS:=Row("IEPSPS").ToString.ToDecimal.RoundSQL, IEPSPSIVA:=Row("IEPSPSIVA").ToString.ToDecimal,
IVAPorcentaje:=Row("IVAPorcentaje").ToString.ToDecimal, RetIVAPorcentaje:=Row("RetIVAPorcentaje").ToString.ToDecimal, RetISRPorcentaje:=Row("RetISRPorcentaje").ToString.ToDecimal,
IEPSPSPorcentaje:=Row("IEPSPSPorcentaje").ToString.ToDecimal, IEPSPSIVAPorcentaje:=Row("IEPSPSIVAPorcentaje").ToString.ToDecimal, NoDeducible:=If((Row("NoDeducible").ToString().ToUpper().Contiene("TRUE", "1")) AndAlso EsNoDeducible, True, False),
CveContratoDetalle:=Row("CveContratoDetalle").ToString.ToEntero, CveCultivoCuadroDetalle:=Row("CveCultivoCuadroDetalle").ToString.ToEntero) Then
Retorno = False
Exit For
End If
End If
indiceTR = indiceTR + 1
'If Not ObjCompra.VerificaPrepolizas(UsuarioActual.CveEmpresa, CveCompra) Then
' Retorno = False
'End If
If Retorno Then
'AGREGA AF COMPRA - Cuando es Compra se guarda CveCompraDetalle en AF
If Row("TipoAF").ToString.ToEntero = 2 Then
If Not ObjAF.UpdateActivosFijosCompra(Row("CveActivoFijo").ToString.ToEntero, Row("CveCompraDetalle").ToString.ToEntero, Row("TipoAF").ToString.ToEntero, Row("Total").ToString.ToDouble, TxtFecha.Text.Trim.ToDate) Then
Retorno = False
Exit For
End If
End If
End If
Next
For Each item As String In ClavesBorradas
If item.ToEntero > 0 Then
If Not ObjCompra.DeleteCompraDetalle(item.ToEntero) Then
Retorno = False
End If
End If
Next
If Retorno Then
If (UsuarioActual.Empresa.UsaAC Or UsuarioActual.Empresa.Funcionalidad(200).ToString = "1") AndAlso IdPoliza > 0 AndAlso UsuarioActual.Empresa.TipoContabilidad = 2 Then
If ObjContaAC Is Nothing Then
ObjContaAC = New ClsContPAQi(UsuarioActual.Empresa)
ObjContaAC.IniciaTransacSQL()
End If
If Not ObjContabilidad.ContabilizarPrePoliza(CvePrePoliza, UsuarioActual.CveEmpresa, UsuarioActual.Empresa, MinFecha, String.Format("{0}-{1}", Serie, Folio), ObjContaAC, pIDPoliza:=ViewState("IdPoliza").ToString.ToEntero) Then
Retorno = False
End If
End If
End If
Else
Retorno = False
End If
'Retorno = True
'Alert("La Compra se actualizó correctamente.")
Else
If IdPoliza > 0 Then
If Not ObjContabilidad.UpdatePrePolizasDetalleBloquear(CvePrePoliza, True) Then
Retorno = False
End If
If Not ObjContabilidad.UpdatePrePoliza(MinFecha, -1, -1, IdPoliza, CvePrePoliza, UsuarioActual.CveEmpresa, CveUsuarioModifico:=UsuarioActual.CveUsuario) Then
Retorno = False
End If
End If
End If
If (TxtRembolsoNumero.Text.Trim.Length > 0 AndAlso IdPoliza <= 0) AndAlso (NumeroReembolsoOriginal.Trim <> TxtRembolsoNumero.Text.Trim) Then
'CUANDO ES REEMBOLSO COMPROBACION Y CAJA CHICA
If UsuarioActual.CveEmpresa.Contiene(1, 119, 141) AndAlso TxtRembolsoNumero.Text.Trim <> "" AndAlso (DdlRembolsoPersonal.SelectedValue.ToEntero > 0 Or DdlRembolsoCajaChica.SelectedValue.ToEntero > 0) Then
If ObjCompra.GetComprobacion(DdlRembolsoPersonal.SelectedValue.ToEntero, DdlRembolsoCajaChica.SelectedValue.ToEntero, TxtRembolsoNumero.Text.Trim, UsuarioActual.CveEmpresa) Then
Dim CvePreComprobacion As Integer
If ObjCompra.DtResultados.Rows.Count = 0 Then
'sino existe, creamos la comprobacion
Dim tConcepto As String = If(DdlRembolsoPersonal.SelectedValue.ToEntero > 0, DdlRembolsoPersonal.SelectedItem.Text, DdlRembolsoCajaChica.SelectedItem.Text)
tConcepto = String.Format("{0}-{1}", tConcepto, TxtRembolsoNumero.Text.Trim)
CvePreComprobacion = ObjContabilidad.AddPrePolizas("Compras Comproba", 1, 0, 0, 1, TxtFecha.Text.ToDate, tConcepto, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa)
If ObjCompra.AddComprobacion(DdlRembolsoPersonal.SelectedValue.ToEntero, DdlRembolsoCajaChica.SelectedValue.ToEntero, TxtRembolsoNumero.Text.Trim, CvePreComprobacion, UsuarioActual.CveEmpresa) > 0 Then
End If
Else
'si ya existe, obtenemos la prepóliza
CvePreComprobacion = ObjCompra.DtResultados.FiltroPrimeroValor("CvePrePoliza").ToEntero
End If
ObjContabilidad.PrePolizaUnificacion(CvePreComprobacion, CvePrePoliza)
End If
End If
End If
Else
Retorno = False
End If
Else
Alert("La compra no se puede actualizar debido a que los totales no son iguales, verifique sus cambios", TipoMensaje.MsgError)
End If
If Retorno AndAlso (CveRetIVAConceptoOriginal <> DdlRetIVAConcepto.SelectedValue.ToEntero OrElse CveRetISRConceptoOriginal <> DdlRetISRConcepto.SelectedValue.ToEntero) Then
Dim tCveConceptoIVA, tCveConceptoISR As Integer
If CveRetIVAConceptoOriginal <> DdlRetIVAConcepto.SelectedValue.ToEntero Then tCveConceptoIVA = DdlRetIVAConcepto.SelectedValue.ToEntero
If CveRetISRConceptoOriginal <> DdlRetISRConcepto.SelectedValue.ToEntero Then tCveConceptoISR = DdlRetISRConcepto.SelectedValue.ToEntero
If ObjCompra.UpdateComprasRetencionesUpdate(tCveConceptoIVA, tCveConceptoISR, CveCompra) Then
If tCveConceptoIVA > 0 Then CveRetIVAConceptoOriginal = tCveConceptoIVA
If tCveConceptoISR > 0 Then CveRetISRConceptoOriginal = tCveConceptoISR
Else
Retorno = False
Alert("Se presento un error al asignar el nuevo concepto de retención", TipoMensaje.MsgAdvertencia)
End If
End If
Catch ex As Exception
Alert("Ocurrió un error al actualizar la compra", TipoMensaje.MsgError)
ObjCompra.RollBack()
If ObjContaAC IsNot Nothing Then ObjContaAC.RollBack()
Finally
If Retorno Then
If ObjContabilidad.MensajePolizaDescuadre IsNot Nothing AndAlso ObjContabilidad.MensajePolizaDescuadre.ToString <> "" Then
Alert(ObjContabilidad.MensajePolizaDescuadre.ToString)
End If
ObjCompra.Commit()
If ObjContaAC IsNot Nothing Then ObjContaAC.Commit()
Dim Msg As New StringBuilder()
Msg.Append("La Compra se actualizó correctamente")
Alert(Msg.ToString())
Else
ObjCompra.RollBack()
If ObjContaAC IsNot Nothing Then ObjContaAC.RollBack()
Alert("Ocurrió un error al actualizar la compra, por favor vuelva a intentar.", TipoMensaje.MsgAdvertencia)
End If
If ObjContaAC IsNot Nothing Then ObjContaAC.Dispose()
End Try
ObjCompra.Dispose()
ObjProveedores.Dispose()
ObjInventario.Dispose()
ObjContabilidad.Dispose()
ObjAF.Dispose()
If ObjContaAC IsNot Nothing Then ObjContaAC.Dispose()
CargaGvBitacora()
UpBitacora.Update()
End Sub
Private Function ComparaDatatables() As Boolean
Dim NumRow As Integer = 0
For Each row1 As DataRow In TmpDT.Rows
Dim NumRow2 As Integer = 0
For Each row2 As DataRow In TmpDTOriginal.Rows
If NumRow2 = NumRow Then
If (row1("CveSubProyecto").ToString.ToEntero <> row2("CveSubProyecto").ToString.ToEntero) Or
(row1("CveClasificacion").ToString.ToEntero <> row2("CveClasificacion").ToString.ToEntero) Or
(row1("CveTipoGasto").ToString.ToEntero <> row2("CveTipoGasto").ToString.ToEntero) Or
(row1("Total").ToString.ToDouble <> row2("Total").ToString.ToDouble) Or
(row1("NoDeducible").ToString <> row2("NoDeducible").ToString) Or
(row1("CveActivoFijo").ToString.ToEntero <> row2("CveActivoFijo").ToString.ToEntero) Or
(row1("AFMedida").ToString.ToEntero <> row2("AFMedida").ToString.ToEntero) Or
(row1("TipoAF").ToString.ToEntero <> row2("TipoAF").ToString.ToEntero) Or
(row1("CvePS").ToString.ToEntero <> row2("CvePS").ToString.ToEntero) Then
Return False
End If
End If
NumRow2 += 1
Next
NumRow += 1
Next
Return True
End Function
Private Function ActualizarPrePoliza(ObjConta As ClsContabilidad, ObjCompra As ClsCompras) As Boolean
Dim Retorno = True, ErrorPrepoliza = False
Dim CvePlantillaPrePoliza As Integer
If DdlTipoComprobante.SelectedValue.Contiene("NC", "DEV") Then
CvePlantillaPrePoliza = 60
Else
CvePlantillaPrePoliza = 1
End If
Dim tIdContaProveedor As Integer = CtaProveedor
Dim ImporteAnticipo As Decimal = 0
If (ArrAnticipos.Count > 0 And CveCompra > 0) Or (ArrAnticipos.Count > 0 And UsuarioActual.Empresa.UsaAC) Then '-- ESTO SE QUITO - IPP - 04 NOVIMEBRE 2016
CvePlantillaPrePoliza = 52
'cuenta de anticipos
tIdContaProveedor = CtaProveedorAnticipos
For Each Ant As Compras_Compras.Anticipos In ArrAnticipos
ImporteAnticipo += Ant.Importe
Next
If Math.Round(ImporteAnticipo, 2) > TxtTotal.Text.ToDouble Then
Alert("El Importe seleccionado es mayor a la compra", TipoMensaje.MsgAdvertencia)
Return False
End If
End If
If RBLContado.SelectedValue = "2" AndAlso DdlFuncionarioEmpleado.SelectedValue.ToEntero > 0 Then
If EmpresaPrueba Then
If DdlTipoComprobante.SelectedValue.Contiene("NC", "DEV") Then
CvePlantillaPrePoliza = 60
Else
CvePlantillaPrePoliza = 1
End If
Else
CvePlantillaPrePoliza = 9
End If
End If
Dim CveMovimientoInventario As Integer = CveMovimientoAlmacen
Dim DT As DataTable
Dim tipoCambioActual, tipoCambioPago As Decimal
Dim FechaMovimiento As Date = TxtFecha.Text.ToDate
If DdlMoneda.SelectedValue.ToString.ToEntero = 2 Then
tipoCambioActual = GlobalTipoCambio(FechaMovimiento).ToString.ToDecimal
tipoCambioActual = If(DivTC.Visible Or TipoCambio > 0, TipoCambio, tipoCambioActual)
tipoCambioPago = GlobalTipoCambio(TxtFechaPago.Text.ToDate).ToString.ToDecimal
Else
tipoCambioActual = 1
tipoCambioPago = 1
End If
Dim DtPrePolizas As DataTable = Nothing
If ObjConta.GetPlantillaConceptos(UsuarioActual.CveEmpresa, CvePlantillaPrePoliza) Then
For Each Row As DataRow In ObjConta.DtResultados.Rows
Dim ConceptoContable = Row("CveConcepto").ToString.ToEntero
Dim TipoMovimiento As Boolean = If(Row("TipoMovto").ToString = "True", True, False)
Dim importeMovimiento As Decimal = 0
Dim IdCtaContable As Integer = 0
Dim importeMN As Decimal = 0
Dim Multiplicador As Integer = If(Row("Multiplicador").ToString.ToEntero = 1, 1, -1)
Dim Referencia As String = $"{TxtSerie.Text}-{TxtFolio.Text}" ' concatenation interpolation
Select Case ConceptoContable
Case 6
Dim CveProveedorConcepto As Integer = 0, CveIE As Integer = 0, CveCreditoDetalle As Integer = 0
Dim ConceptoPersonal As String = "", Concepto As String = ""
If Not ObjConta.GetPrePolizasDetalleCompra(CveCompra, UsuarioActual.CveEmpresa) Then
ErrorPrepoliza = True
Else
DtPrePolizas = ObjConta.DtResultados.FiltraParametros("CveConceptoContable IN (6,68,49,205,176)")
If DtPrePolizas.Rows.Count > 0 Then
CveProveedorConcepto = ObjConta.DtResultados.FiltraParametros("CveConceptoContable = 6 OR CveConceptoContable = 68 OR CveConceptoContable = 49 OR CveConceptoContable = 205 OR CveConceptoContable = 176").Rows(0)("CveProveedor").ToString.ToEntero
CveIE = ObjConta.DtResultados.FiltraParametros("CveConceptoContable = 6 OR CveConceptoContable = 68 OR CveConceptoContable = 49 OR CveConceptoContable = 205 OR CveConceptoContable = 176").Rows(0)("CveIE").ToString.ToEntero
CveCreditoDetalle = ObjConta.DtResultados.FiltraParametros("CveConceptoContable = 6 OR CveConceptoContable = 68 OR CveConceptoContable = 49 OR CveConceptoContable = 205 OR CveConceptoContable = 176").Rows(0)("CveCreditoDetalle").ToString.ToEntero
Concepto = ObjConta.DtResultados.FiltraParametros("CveConceptoContable = 6 OR CveConceptoContable = 68 OR CveConceptoContable = 49 OR CveConceptoContable = 205 OR CveConceptoContable = 176").Rows(0)("Concepto").ToString
End If
End If
If CveProveedorConcepto <= 0 Then
CveProveedorConcepto = DdlProveedor.SelectedValue.ToEntero
End If
If Not ErrorPrepoliza Then
For Each RowPrePoliza As DataRow In DtPrePolizas.FiltraParametros("", DistinctColumns:={"CvePrePoliza"}).Rows
Dim CvePrePoliza As Integer = RowPrePoliza("CvePrePoliza").ToString().ToEntero()
'Removemos los conceptos de la prepoliza
If Not ObjConta.RemovePrePolizasDetalle(CvePrePoliza, 6, CveCompra, 1) Then ErrorPrepoliza = True 'GASTO
If Not ObjConta.RemovePrePolizasDetalle(CvePrePoliza, 68, CveCompra, 1) Then ErrorPrepoliza = True 'ALMACEN
If Not ObjConta.RemovePrePolizasDetalle(CvePrePoliza, 49, CveCompra, 1) Then ErrorPrepoliza = True 'AF
If Not ObjConta.RemovePrePolizasDetalle(CvePrePoliza, 205, CveCompra, 1) Then ErrorPrepoliza = True 'PS YA RECIBIDO
If Not ObjConta.RemovePrePolizasDetalle(CvePrePoliza, 230, CveCompra, 1) Then ErrorPrepoliza = True 'PS YA RECIBIDO
If Not ObjConta.RemovePrePolizasDetalle(CvePrePoliza, 231, CveCompra, 1) Then ErrorPrepoliza = True 'PS YA RECIBIDO
If Not ObjConta.RemovePrePolizasDetalle(CvePrePoliza, 176, CveCompra, 1) Then ErrorPrepoliza = True 'PS NO RECIBIDO
If Not ObjConta.RemovePrePolizasDetalle(CvePrePoliza, 228, CveCompra, 1) Then ErrorPrepoliza = True 'PS NO RECIBIDO
If Not ObjConta.RemovePrePolizasDetalle(CvePrePoliza, 229, CveCompra, 1) Then ErrorPrepoliza = True 'PS NO RECIBIDO
'OBTIENE METODO DE CONTABILIZACIÓN AL GUARDAR
Dim ConceptoContabilizacionAlmacen = 0
If ObjCompra.GetCompras(CveCompra, "-1", "-1", -1, -1, UsuarioActual.CveEmpresa) AndAlso ObjCompra.DtResultados.Rows.Count > 0 Then
ConceptoContabilizacionAlmacen = ObjCompra.DtResultados.FiltroPrimeroValor("CveConceptoContableAlmacen").ToEntero
End If
'AF
DT = TmpDT.FiltraParametros("ISNULL(TipoAF,0) = 2")
If DT.Rows.Count > 0 AndAlso DdlTipoComprobante.SelectedValue <> "NC" Then
For Each Row2 As DataRow In DT.Rows
importeMovimiento = Row2("Total").ToString.ToDecimal
importeMN = importeMovimiento * tipoCambioActual * Multiplicador
If ObjConta.GetRetCuenta(49, Row2("CveActivoFijo").ToString.ToEntero) Then
If ObjConta.DtResultados.Rows.Count > 0 Then
IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCtaContActivoFijo").ToString.ToEntero
End If
End If
If importeMovimiento <> 0 Then
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, importeMovimiento, Row2("CodAF").ToString, 49, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveActivoFijo:=Row2("CveActivoFijo").ToString.ToEntero, CveIE:=CveIE, CvePersonal:=CvePersonal, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMN, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento)) Then
ErrorPrepoliza = True
End If
End If
Next
End If
'LIMPIA
importeMovimiento = 0
IdCtaContable = 0
'COSTO ALMACEN
Dim DtAlmacenes = GlobalDTAlmacen(UsuarioActual.CveEmpresa)
If UsuarioActual.Empresa.UsaInventarios AndAlso Not UsuarioActual.Empresa.Funcionalidad(126) = "1" And ConceptoContabilizacionAlmacen = 0 Then
DT = TmpDT.FiltraParametros("ISNULL(TipoAF,0) <> 2 AND ISNULL(CveAlmacen,0) > 0", "", {"CveAlmacen"})
'RECORREMOS PARA DETECTAR LA MODALIDAD DEL ALMACEN, EN CASO DE SER SOLO EXISTENCIA LIMPIAMOS CVEALMACEN
DT.AcceptChanges()
DT = DT.FiltraParametros("ISNULL(CveAlmacen,0) > 0")
If (DT.Rows.Count > 0) AndAlso Not DdlTipoComprobante.SelectedValue.Contiene("NC", "DEV", "Ant") Then
For Each Row2 As DataRow In DT.Rows
importeMovimiento = TmpDT.SUM("Total", $"CveAlmacen = {Row2("CveAlmacen")}").ToString.ToDecimal + TmpDT.SUM("CostoIndirectoAlmacen", $"CveAlmacen = {Row2("CveAlmacen")}").ToString.ToDecimal 'Row2("Total").ToString.ToDecimal + Row2("CostoIndirectoAlmacen").ToString.ToDecimal
importeMN = importeMovimiento * tipoCambioActual * Multiplicador
If ObjConta.GetRetCuenta(68, GvInv.HeaderRow.FCDropDownList("ddlAlmacen").SelectedValue.ToString.ToEntero) Then
If ObjConta.DtResultados.Rows.Count > 0 Then
IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCtaContable").ToString.ToEntero
End If
End If
If importeMovimiento <> 0 Then
Dim SeContabiliza As Boolean = True
'SI ES GASTO DE ALMACEN NO DEBE CONTABILIZAR CONCEPTO 68
If DdlTipoCompra.SelectedValue = "10" Then
SeContabiliza = False
IdCtaContable = 0
End If
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, 68, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveIE:=CveIE, CvePersonal:=CvePersonal, CveMovimientoAlmacen:=CveMovimientoInventario, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMN, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), Contabilizable:=SeContabiliza) Then
ErrorPrepoliza = True
End If
End If
Next
End If
End If
'LIMPIA
importeMovimiento = 0
IdCtaContable = 0
'INV [MERCANCIA RECIBIDA POR ADELANTADO (OC) | MERCANCIA PENDIENTE POR RECIBIR (COMPRA) ]
If UsuarioActual.Empresa.UsaInventarios And Not DdlTipoComprobante.SelectedValue.Contiene("NC", "DEV", "Ant") And Not UsuarioActual.Empresa.Funcionalidad(126) = "1" And ConceptoContabilizacionAlmacen.Contiene(176, 205) Then
importeMovimiento = TmpDT.SUM("Total", $"ISNULL(TipoAF,0) <> 2 AND ISNULL(AplicaCostoIndirecto,0) <> 1 AND CveTipoPS = 2").ToString.ToDecimal
importeMN = importeMovimiento * tipoCambioActual * Multiplicador
If ObjConta.GetRetCuenta(ConceptoContabilizacionAlmacen, UsuarioActual.CveEmpresa) Then
If ObjConta.DtResultados.Rows.Count > 0 Then
IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCtaContable").ToString.ToEntero
End If
End If
If importeMovimiento <> 0 Then
Concepto = $"{NombreProveedor} {TxtSerie.Text} - {TxtFolio.Text}"
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContabilizacionAlmacen, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, ImporteMX:=importeMN, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento)) Then
ErrorPrepoliza = True
End If
End If
End If
'NC CON PRODUCTOS - CUENTA PUENTE
If UsuarioActual.Empresa.UsaInventarios And Not DdlTipoComprobante.SelectedValue.Contiene("NC", "DEV", "Ant") And Not UsuarioActual.Empresa.Funcionalidad(126) = "1" And ConceptoContabilizacionAlmacen.Contiene(225) Then
importeMovimiento = TmpDT.SUM("Total", $"ISNULL(TipoAF,0) <> 2 AND ISNULL(AplicaCostoIndirecto,0) <> 1 AND CveTipoPS = 2").ToString.ToDecimal
importeMN = importeMovimiento * tipoCambioActual * Multiplicador
If ObjConta.GetRetCuenta(ConceptoContabilizacionAlmacen, UsuarioActual.CveEmpresa) Then
If ObjConta.DtResultados.Rows.Count > 0 Then
IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCtaContable").ToString.ToEntero
End If
End If
If importeMovimiento <> 0 Then
Concepto = $"{NombreProveedor} {TxtSerie.Text} - {TxtFolio.Text}"
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContabilizacionAlmacen, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, ImporteMX:=importeMN, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento)) Then
ErrorPrepoliza = True
End If
End If
End If
'GASTO
DT = TmpDT.Copy
'RECORREMOS PARA DETECTAR LA MODALIDAD DEL ALMACEN, EN CASO DE SER SOLO EXISTENCIA LIMPIAMOS CVEALMACEN
If DdlTipoCompra.SelectedValue <> "10" Then
For Each Dr As DataRow In DT.Rows
If DtAlmacenes.FiltroPrimeroValor("Modalidad", $"CveAlmacen = {Dr("CveAlmacen").ToString.ToEntero}").ToString = "Solo Existencia" Then
Dr("CveAlmacen") = 0
End If
Dr.AcceptChanges()
Next
End If
DT.AcceptChanges()
DtAlmacenes.Dispose()
'QUITA 1-[MERCANCIA RECIBIDA POR ADELANTADO (OC) | MERCANCIA PENDIENTE POR RECIBIR (COMPRA)] 2-[NC CON PRODUCTOS]
If UsuarioActual.Empresa.UsaInventarios And Not UsuarioActual.Empresa.Funcionalidad(126) = "1" And ConceptoContabilizacionAlmacen > 0 Then
DT = DT.FiltraParametros("CveTipoPS <> 2")
End If
Dim DTDistinct = DT.Copy
If UsuarioActual.Empresa.Funcionalidad(126) = "1" Then
DTDistinct = DTDistinct.FiltraParametros("ISNULL(TipoAF,0) <> 2", "", {"CveClasificacion", "Clasificacion", "SubProyecto", "CveSubProyecto", "CveTipoGasto", "TipoGasto"})
Else
DTDistinct = DTDistinct.FiltraParametros("ISNULL(TipoAF,0) <> 2 AND ISNULL(CveAlmacen,0) = 0 AND ISNULL(AplicaCostoIndirecto,0) <> 1", "", {"CveClasificacion", "Clasificacion", "SubProyecto", "CveSubProyecto", "CveTipoGasto", "TipoGasto"})
End If
If DTDistinct.Rows.Count > 0 Then
For Each Row2 As DataRow In DTDistinct.Rows
'DETERMINA IMPORTE
If UsuarioActual.Empresa.Funcionalidad(126) = "1" Then
importeMovimiento = DT.SUM("Total", String.Format("ISNULL(TipoAF,0) <> 2 AND CveClasificacion = {0} AND CveSubProyecto = {1} AND ISNULL(CveTipoGasto,0) = {2}", Row2("CveClasificacion").ToString.ToEntero, Row2("CveSubProyecto").ToString.ToEntero, Row2("CveTipoGasto").ToString.ToEntero)).ToString.ToDecimal
Else
importeMovimiento = DT.SUM("Total", String.Format("ISNULL(TipoAF,0) <> 2 AND ISNULL(CveAlmacen,0) = 0 AND ISNULL(AplicaCostoIndirecto,0) <> 1 AND CveClasificacion = {0} AND CveSubProyecto = {1} AND ISNULL(CveTipoGasto,0) = {2}", Row2("CveClasificacion").ToString.ToEntero, Row2("CveSubProyecto").ToString.ToEntero, Row2("CveTipoGasto").ToString.ToEntero)).ToString.ToDecimal
End If
importeMN = importeMovimiento * tipoCambioActual * Multiplicador
'CLASIFICACION
If Row2("CveClasificacion").ToString.ToEntero > 0 Then
If ObjConta.GetRetCuenta(6, Row2("CveClasificacion").ToString.ToEntero, CveSubProyecto:=Row2("CveSubProyecto").ToString.ToEntero) Then
If ObjConta.DtResultados.Rows.Count > 0 AndAlso ObjConta.DtResultados.Rows(0)("IdCuentaGasto").ToString.ToEntero > 0 Then
IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaGasto").ToString.ToEntero
Else
IdCtaContable = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaGasto", String.Format("CveClasificacion = {0}", Row2("CveClasificacion"))).ToString.ToEntero
End If
End If
End If
'AGREGA MOVIMIENTO
If importeMovimiento <> 0 AndAlso Not DdlTipoComprobante.SelectedValue.Contiene("NC", "DEV", "Ant") Then
Concepto = $"{NombreProveedor} {TxtSerie.Text} - {TxtFolio.Text}"
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, 6, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveIE:=CveIE, CveCreditoDetalle:=CveCreditoDetalle, CveClasificacion:=Row2("CveClasificacion").ToString.ToEntero, CveSubProyecto:=Row2("CveSubProyecto").ToString.ToEntero, ImporteMX:=importeMN, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), CveTipoGasto:=Row2("CveTipoGasto").ToString.ToEntero) Then
ErrorPrepoliza = True
End If
End If
Next
End If
'LIMPIA
importeMovimiento = 0
IdCtaContable = 0
Next
End If
'LIMPIA
importeMovimiento = 0
IdCtaContable = 0
' Case 5 'Proveedores
' Dim TieneConceptoProveedorAcreedor As Boolean = False
' Dim CveIE As Integer = -1
' 'If Not ObjConta.GetPrePolizasDetalleCompra(CveCompra, UsuarioActual.CveEmpresa) Then
' ' ErrorPrepoliza = True
' 'Else
' ' If ObjConta.DtResultados.FiltraParametros("CveConceptoContable IN (5,305)").Rows.Count > 0 Then
' ' TieneConceptoProveedorAcreedor = True
' ' CveIE = ObjConta.DtResultados.FiltraParametros("CveConceptoContable = 6 OR CveConceptoContable = 68 OR CveConceptoContable = 49 OR CveConceptoContable = 205 OR CveConceptoContable = 176").Rows(0)("CveIE").ToString.ToEntero
' ' End If
' 'End If
' If TieneConceptoProveedorAcreedor Then
' If CveTipoConcepto = 2 Then ConceptoContable = 305 'cuando es acreedor
' Dim UsaComplementaria As Boolean = True
' If tipoCambioActual <> 1 Then
' Select Case ConceptoContable
' Case 5
' ConceptoContable = 311
' Case 305
' ConceptoContable = 306
' Case Else
' End Select
' End If
' Dim importeProv As Decimal = 0
' importeProv = TxtTotal.Text.ToDecimal
' If Not DdlTipoComprobante.SelectedValue.Contiene("NC", "DEV") Then
' importeMovimiento = importeProv
' importeMN = importeMovimiento * tipoCambioActual * Multiplicador
' If tipoCambioActual > 1 Then Referencia += $" TC{tipoCambioActual} ${importeMovimiento.FormatoNumero(2)}"
' Dim CveConceptoContableComplementaria As Integer = 201
' If CveTipoConcepto = 2 Then CveConceptoContableComplementaria = 307
' If tipoCambioActual = 1 Then
' IdCtaContable = If(CveTipoConcepto = 2, CtaProveedorAcreedores, CtaProveedor)
' Dim Concepto = $"{NombreProveedor} {TxtSerie.Text} - {TxtFolio.Text}"
' If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveSubProyecto:=-1, CveProveedor:=CveProveedor, CveIE:=CveIE, CvePersonal:=CvePersonal, CveCreditoDetalle:=-1, ImporteMX:=Math.Round(importeMN, 2, MidpointRounding.AwayFromZero), ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), TipoCambio:=tipoCambioActual) Then
' ErrorPrepoliza = True
' Exit For
' End If
' Else
' IdCtaContable = CtaProveedorComplementaria
' If importeMovimiento <> 0 AndAlso (IdCtaContable > 0 Or UsaComplementaria) Then 'Cuando tiene complementaria lo dividimos en dos Then
' importeMN = importeMovimiento
' If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, 0, Referencia, CveConceptoContableComplementaria, Referencia, FechaMovimiento, IdCtaContable, -1, CveIE, CveCompra:=CveCompra, CveProveedor:=CveProveedor, ImporteMX:=importeMovimiento * tipoCambioActual - importeMovimiento, ImporteME:=importeMovimiento, TipoCambio:=tipoCambioActual) Then
' ErrorPrepoliza = True
' End If
' End If
' IdCtaContable = CtaProveedorExtranjera
' End If
' End If
' End If
End Select
Next
End If
If DtPrePolizas IsNot Nothing Then
For Each RowPrePoliza As DataRow In DtPrePolizas.FiltraParametros("", DistinctColumns:={"CvePrePoliza"}).Rows
If ObjConta.ValidacionPrePolizaCuadre(RowPrePoliza("CvePrePoliza").ToString().ToEntero(), 4) Then
If ObjConta.ValorPolizaDescuadre > 0 Then
ErrorPrepoliza = True
Alert("Error en validacion de prepoliza cuadre", TipoMensaje.MsgAdvertencia)
GuardaLogAD($"Compras/Compras-Actualizar | Error:{ObjConta.MensajePolizaDescuadre} Diferencia:{ObjConta.ValorDiferencia} | CvePrePoliza:{CvePrePoliza}", "LogPrePolizas")
Exit For
End If
End If
Next
End If
'VALIDAR PREPOLIZA DE COMPRA
If ObjConta.ValidacionPrePolizaCuadre(CvePrePoliza, 4) Then
If ObjConta.ValorPolizaDescuadre > 0 Then
ErrorPrepoliza = True
Alert("Error en validacion de prepoliza cuadre", TipoMensaje.MsgAdvertencia)
GuardaLogAD($"Compras/Compras-Actualizar | Error:{ObjConta.MensajePolizaDescuadre} Diferencia:{ObjConta.ValorDiferencia} | CvePrePoliza:{CvePrePoliza}", "LogPrePolizas")
End If
End If
If Not ErrorPrepoliza Then
Retorno = True
Else
Retorno = False
End If
Return Retorno
End Function
Protected Sub ImgActualizarProyecto_Click(sender As Object, e As EventArgs) Handles ImgActualizarProyecto.Click
'actualizo los proyectos
Dim Compra As New ClsCompras
Dim Retorno As Boolean = True
Compra.IniciaTransacSQL()
For Each Row As DataRow In TmpDT.Rows
If Not Compra.UpdateCompraDetalle(Row("CvePS").ToString.ToEntero, Row("Cantidad").ToString.ToDouble, Row("PU").ToString.ToDouble, Row("IVA").ToString.ToDouble, Row("Total").ToString.ToDouble,
Row("Descuento").ToString.ToDouble, Row("Observaciones").ToString, Row("CveSubProyecto").ToString.ToEntero, Row("CvePresupuestoEgreso").ToString.ToEntero, -2, Row("CveCompraDetalle").ToString.ToEntero, CveTipoGasto:=Row("CveTipoGasto").ToString.ToEntero) Then
Retorno = False
Exit For
End If
Next
If Retorno Then
Compra.Commit()
Alert("La Compra se actualizó correctamente.")
Else
Compra.RollBack()
End If
Compra.Dispose()
End Sub
Protected Sub BtnVerAmortizacion_Click(sender As Object, e As EventArgs) Handles BtnVerAmortizacion.Click
BtnVerAmortizacion.Visible = False
'BtnAmortizar.Visible = True
'activo el cuadro para amortizar
RBLPago.SelectedValue = "2" ' selecciono contado
PnlContado.Visible = True
PnlContadoBancos.Visible = False
RBLContado.Items.Clear()
RBLContado.Items.Add(New ListItem("Deudores", "4"))
RBLContado.SelectedValue = "4" 'selecciono deudores
PnlContadoDeudores.Visible = True
CargaDeudores()
End Sub
Protected Sub ImgAjusteSobreTotal_Click(sender As Object, e As ImageClickEventArgs) Handles ImgAjustaSobreTotal.Click
'realizo el ajuste de los productos
'total - iva
Dim Diferencia As Decimal = TxtTotal.Text.ToDecimal() - TxtIVA.Text.ToDecimal + TxtRetIVA.Text.ToDecimal + TxtRetISR.Text.ToDecimal - (TxtSubTotal2.Text.ToDecimal)
AjustaImporteUltimoConcepto(Diferencia)
BtnGuardar.Enabled = True
UpFacturar.Update()
End Sub
#End Region
#Region "CargaXML"
Private Function ValorXML(n As XmlNode, Campo As String, Optional Retorno As String = "") As String
Dim o As XmlNode = n.Attributes.Cast(Of XmlAttribute)().SingleOrDefault(Function(a) String.Compare(a.Name, Campo, True) = 0)
If o Is Nothing Then
Return Retorno
Else
Return o.Value
End If
End Function
Private Sub CargaComprobanteXML(XMLDoc As XmlDocument)
Dim nodo As XmlNode = XMLDoc.DocumentElement
_Serie = ValorXML(nodo, "serie")
If _Serie <> "" Then _Serie = _Serie
Version = ValorXML(nodo, "version")
_Folio = ValorXML(nodo, "folio")
_Fecha = ValorXML(nodo, "fecha")
SubTotal = ValorXML(nodo, "subTotal").ToDecimal
Total = ValorXML(nodo, "total").ToDecimal
Descuentos = ValorXML(nodo, "descuento").ToDecimal
_Moneda = ValorXML(nodo, "Moneda")
_TipoComprobante = ValorXML(nodo, "tipoDeComprobante")
TipoCambio = ValorXML(nodo, "TipoCambio", "1").ToDecimal
If Version = "3.3" Or Version = "4.0" Then
Dim drm As DataRow = GlobalDTVtaMetodoPago.FiltroPrimero(String.Format("ClaveMetodoPagoSAT = '{0}'", ValorXML(nodo, "MetodoPago")))
If drm IsNot Nothing Then
CveMetodoPago = drm("CveMetodoPago").ToString.ToEntero
MetodoPago = drm("MetodoPagoSAT").ToString
End If
End If
Dim namespaces As New XmlNamespaceManager(XMLDoc.NameTable)
Dim Prefijo As String = If(XMLDoc.DocumentElement.Prefix = "", "cfd", XMLDoc.DocumentElement.Prefix)
Dim cfdVer As String = ""
If Version = "3.2" Then
Prefijo = "cfd"
cfdVer = "http://www.sat.gob.mx/cfd/2"
ElseIf Version = "3.3" Then
cfdVer = "http://www.sat.gob.mx/cfd/3"
Else ' se considera que es la version 4.0
cfdVer = "http://www.sat.gob.mx/cfd/4"
End If
namespaces.AddNamespace(Prefijo, cfdVer)
namespaces.AddNamespace("tfd", "http://www.sat.gob.mx/TimbreFiscalDigital")
namespaces.AddNamespace("implocal", "http://www.sat.gob.mx/implocal")
namespaces.AddNamespace("registrofiscal", "http://www.sat.gob.mx/registrofiscal")
If _TipoComprobante.ToUpper = "E" And (Version = "3.3" Or Version = "4.0") Then
Dim UUIDS As String = ""
Dim UUIDSLista As New List(Of String)
Dim nodeCFDIRelacionados As XmlNode
nodeCFDIRelacionados = XMLDoc.SelectSingleNode(String.Format("//{0}:CfdiRelacionados", Prefijo), namespaces)
If nodeCFDIRelacionados IsNot Nothing Then
For Each CFDIRelacionados As XmlNode In nodeCFDIRelacionados
UUIDSLista.Add("" & CFDIRelacionados.Attributes("UUID").Value.ToString & "")
Next
End If
UUIDSList = UUIDSLista
End If
Dim node As XmlNode
node = XMLDoc.SelectSingleNode(String.Format("//{0}:Emisor", Prefijo), namespaces)
If node IsNot Nothing AndAlso node.ChildNodes.Count > 0 Then
EmisorRFC = ValorXML(node, "RFC")
End If
node = XMLDoc.SelectSingleNode(String.Format("//{0}:CfdiRelacionados", Prefijo), namespaces)
node = XMLDoc.SelectSingleNode(String.Format("//{0}:Receptor", Prefijo), namespaces)
If node IsNot Nothing AndAlso node.ChildNodes.Count > 0 Then
ReceptorRFC = ValorXML(node, "RFC")
End If
If UsuarioActual.CveEmpresa.Contiene(119, 7) Then
node = XMLDoc.SelectSingleNode(String.Format("//{0}:CfdiRelacionados", Prefijo), namespaces)
If node IsNot Nothing AndAlso node.ChildNodes.Count > 0 Then
If ValorXML(node, "TipoRelacion").ToString.Contiene("07") Then
Dim nodeDocumentosRelacionados As XmlNodeList = XMLDoc.SelectNodes(String.Format("//{0}:CfdiRelacionado", Prefijo), namespaces)
For Each documento As XmlNode In nodeDocumentosRelacionados
If documento.Attributes("UUID").Value <> "" Then
ListaDocumentos.Add(documento.Attributes("UUID").Value)
End If
TieneAnticiposXML = True
Next
End If
End If
End If
node = XMLDoc.SelectSingleNode(String.Format("//{0}:Impuestos", Prefijo), namespaces)
If node IsNot Nothing AndAlso node.ChildNodes.Count > 0 Then
Dim nodeRetenciones As XmlNodeList = XMLDoc.SelectNodes(String.Format("//{0}:Comprobante/{0}:Impuestos/{0}:Retenciones/{0}:Retencion", Prefijo), namespaces)
TotalRetenciones = ValorXML(node, "totalImpuestosRetenidos", "0").ToDecimal
If Version = "3.3" OrElse Version = "4.0" Then
For Each retencion As XmlNode In nodeRetenciones
If retencion.Attributes("Impuesto").Value = "002" Then RetencionIVA += retencion.Attributes("Importe").Value.ToDecimal
If retencion.Attributes("Impuesto").Value = "001" Then RetencionISR += retencion.Attributes("Importe").Value.ToDecimal
Next
GvOC1.Columns(6).Visible = True
GvOC2.Columns(4).Visible = True
Else
For Each retencion As XmlNode In nodeRetenciones
If retencion.Attributes("impuesto").Value = "IVA" Then RetencionIVA += retencion.Attributes("importe").Value.ToDecimal
If retencion.Attributes("impuesto").Value = "ISR" Then RetencionISR += retencion.Attributes("importe").Value.ToDecimal
Next
End If
SumaTotalRetenciones += RetencionIVA
SumaTotalRetenciones += RetencionISR
TotalTraslados = ValorXML(node, "totalImpuestosTrasladados", "0").ToDecimal
Dim nodeTraslados As XmlNodeList = XMLDoc.SelectNodes(String.Format("//{0}:Comprobante/{0}:Impuestos/{0}:Traslados/{0}:Traslado", Prefijo), namespaces)
If Version = "3.3" OrElse Version = "4.0" Then
For Each traslado As XmlNode In nodeTraslados
If traslado.Attributes("Importe") IsNot Nothing Then
If traslado.Attributes("Impuesto").Value = "002" Then TrasladoIVA += traslado.Attributes("Importe").Value.ToDecimal
If traslado.Attributes("Impuesto").Value = "003" Then TrasladoIEPS += traslado.Attributes("Importe").Value.ToDecimal
End If
Next
Else
For Each traslado As XmlNode In nodeTraslados
If traslado.Attributes("Importe") IsNot Nothing Then
If traslado.Attributes("impuesto").Value = "IVA" Then TrasladoIVA += traslado.Attributes("importe").Value.ToDecimal
If traslado.Attributes("impuesto").Value = "IEPS" Then TrasladoIEPS += traslado.Attributes("importe").Value.ToDecimal
End If
Next
End If
SumaTotalTraslados += TrasladoIVA
SumaTotalTraslados += TrasladoIEPS
End If
Dim nodeComp As XmlNode = XMLDoc.SelectSingleNode(String.Format("//{0}:Complemento", Prefijo), namespaces)
If node IsNot Nothing AndAlso node.ChildNodes.Count > 0 Then
Dim nodeTFD As XmlNode = nodeComp.SelectSingleNode(String.Format("//{0}:TimbreFiscalDigital", "tfd"), namespaces)
_TFDUUID = ValorXML(nodeTFD, "UUID", "")
Dim nodeRF As XmlNode = nodeComp.SelectSingleNode(String.Format("//{0}:CFDIRegistroFiscal ", "registrofiscal"), namespaces)
If nodeRF IsNot Nothing Then
_Folio = ValorXML(nodeRF, "folio").TrimStart("0"c)
End If
node = node.SelectSingleNode(String.Format("//{0}:ImpuestosLocales", "implocal"), namespaces)
If node IsNot Nothing AndAlso node.ChildNodes.Count > 0 Then
OtrosImpuestos = ValorXML(node, "TotaldeTraslados", "0").ToDecimal
'2022.06.04-- se quitan los datos de retenciones de impuestos locales, generan conflicto. RMF
'OtrosImpuestosRetenciones = ValorXML(node, "TotaldeRetenciones", "0").ToDecimal
End If
End If
End Sub
#End Region
#Region "GV'S"
Protected Sub GVAnticipos_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GVAnticipos.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
If e.Row.DBCampo("SerieFolio") = "" Then
e.Row.Cells(0).Text = ""
e.Row.Cells(5).Text = ""
e.Row.Cells(6).Text = ""
e.Row.Cells(0).Width = Unit.Pixel(150)
e.Row.CssClass = "Totales TextCenter"
Select Case e.Row.DBCampo("TipoDocto")
Case "Egsc"
e.Row.Cells(0).Text = "Egreso Por Comprobar"
Case "Ant"
e.Row.Cells(0).Text = "Anticipos"
Case "NC"
e.Row.Cells(0).Text = "Notas de crédito"
Case "DEV"
e.Row.Cells(0).Text = "Devolución"
End Select
ElseIf e.Row.DBCampo("CveProveedor") = "" Then
e.Row.Cells(0).Text = ""
e.Row.Cells(5).Text = ""
e.Row.Cells(6).Text = ""
e.Row.BackColor = Drawing.Color.LightGray
Else
If e.Row.DBCampo("Saldo").ToDouble < 0 Then e.Row.Cells(3).ForeColor = Drawing.Color.Red
If e.Row.DBCampo("Saldo").ToDouble = 0 Then e.Row.FCLiteral("LtlAnticipos").Text = ""
Dim ImporteAmortizacion As Decimal = If(ListaDocumentos IsNot Nothing AndAlso ListaDocumentos.Count > 0, TmpDT.SUMD("ImporteConImpuestos"), TxtTotal.Text.ToDecimal)
e.Row.FCCheckBox("Chk").Attributes.Add("onclick", String.Format("chkAnt(this,{0},{1},{2});", e.Row.FCTextBox("TxtAnticipo").ClientID, e.Row.DBCampo("Saldo"), If(CveCompra > 0, Saldo, ImporteAmortizacion), e.Row.DBCampo("CveMoneda").ToEntero, If(Not e.Row.DBCampo("TCCompra").ToDouble > 1, GlobalTipoCambio(e.Row.DBCampo("Fecha").ToDate), e.Row.DBCampo("TCCompra").ToDouble), DdlMoneda.SelectedValue.ToEntero)) 'SI ES UNA COMPRA NUEVA SE PONE EL TOTAL, SI NO EL SALDO
If UsuarioActual.Empresa.CveEmpresa.Contiene(13, 83) Then
e.Row.FCTextBox("TxtAnticipo").Attributes.Add("onKeyUp", String.Format("FnCambiaAnt({0},this,{1},{2},{3},{4},{5},{6});",
e.Row.FCCheckBox("Chk").ClientID,
e.Row.DBCampo("Saldo"),
If(CveCompra > 0, Saldo, ImporteAmortizacion), e.Row.DBCampo("CveMoneda").ToEntero,
If(Not e.Row.DBCampo("TCCompra").ToDouble > 1, GlobalTipoCambio(e.Row.DBCampo("Fecha").ToDate), e.Row.DBCampo("TCCompra").ToDouble),
DdlMoneda.SelectedValue.ToEntero,
e.Row.FCTextBox("TxtComision").ClientID)) 'SI ES UNA COMPRA NUEVA SE PONE EL TOTAL, SI NO EL SALDO
e.Row.FCTextBox("TxtComision").Attributes.Add("onKeyUp", String.Format("FnCambiaAnt({0},{6},{1},{2},{3},{4},{5},this);",
e.Row.FCCheckBox("Chk").ClientID,
e.Row.DBCampo("Saldo"),
If(CveCompra > 0, Saldo, ImporteAmortizacion),
e.Row.DBCampo("CveMoneda").ToEntero,
If(Not e.Row.DBCampo("TCCompra").ToDouble > 1, GlobalTipoCambio(e.Row.DBCampo("Fecha").ToDate), e.Row.DBCampo("TCCompra").ToDouble),
DdlMoneda.SelectedValue.ToEntero,
e.Row.FCTextBox("TxtAnticipo").ClientID))
Else
e.Row.FCTextBox("TxtAnticipo").Attributes.Add("onKeyUp", String.Format("FnCambiaAnt({0},this,{1},{2},{3},{4},{5});",
e.Row.FCCheckBox("Chk").ClientID,
e.Row.DBCampo("Saldo"),
If(CveCompra > 0, Saldo, ImporteAmortizacion), e.Row.DBCampo("CveMoneda").ToEntero,
If(Not e.Row.DBCampo("TCCompra").ToDouble > 1, GlobalTipoCambio(e.Row.DBCampo("Fecha").ToDate), e.Row.DBCampo("TCCompra").ToDouble),
DdlMoneda.SelectedValue.ToEntero,
e.Row.FCTextBox("TxtComision").ClientID)) 'SI ES UNA COMPRA NUEVA SE PONE EL TOTAL, SI NO EL SALDO
e.Row.FCTextBox("TxtComision").Attributes.Add("onKeyUp", String.Format("FnCambiaAnt({0},{6},{1},{2},{3},{4},{5},this);",
e.Row.FCCheckBox("Chk").ClientID,
e.Row.DBCampo("Saldo"),
If(CveCompra > 0, Saldo, ImporteAmortizacion),
e.Row.DBCampo("CveMoneda").ToEntero,
If(Not e.Row.DBCampo("TCCompra").ToDouble > 1, GlobalTipoCambio(e.Row.DBCampo("Fecha").ToDate), e.Row.DBCampo("TCCompra").ToDouble),
DdlMoneda.SelectedValue.ToEntero,
e.Row.FCTextBox("TxtAnticipo").ClientID))
End If
If ChkNCInv.Checked Then
e.Row.FCCheckBox("Chk").CssClass = "ChkAntNC"
End If
If ListaDocumentos IsNot Nothing AndAlso ListaDocumentos.Count > 0 Then
Dim Entro As Boolean = False
For Each Documento In ListaDocumentos
If e.Row.DBCampo("UUID").ToString = Documento Then
Entro = True
End If
Next
'permite vincular otro folio fiscal.
Entro = True
If Not Entro Then e.Row.FCCheckBox("Chk").Enabled = False
End If
End If
End If
End Sub
Protected Sub GvPS_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs) Handles GvPS.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
If Not (e.Row.RowState = DataControlRowState.Edit OrElse e.Row.RowState = 5) Then
If e.Row.RowIndex = 0 Then
If UsuarioActual.Empresa.UsaAC Then 'AndAlso (CveFactura > 0 Or CveCompra > 0)
e.Row.Cells(13).Width = Unit.Pixel(150)
e.Row.Cells(14).Width = Unit.Pixel(150)
e.Row.Cells(15).Width = Unit.Pixel(150)
e.Row.Cells(16).Width = Unit.Pixel(150)
e.Row.Cells(17).Width = Unit.Pixel(150)
e.Row.Cells(18).Width = Unit.Pixel(100)
End If
End If
'Permite la Regeneracion de las prepolizas
If e.Row.DBCampo("CveClasificacion") <> "" AndAlso e.Row.DBCampo("CveClasificacion").ToEntero > 0 Then
TmpDT.Rows(e.Row.RowIndex)("CveClasificacionActualizar") = e.Row.DBCampo("CveClasificacion")
End If
If CveCompra > 0 AndAlso UsuarioActual.TienePermisoProceso(104) AndAlso e.Row.FCCheckBox("CheckClasificacion") IsNot Nothing Then
e.Row.FCCheckBox("CheckClasificacion").Visible = True
End If
If UsuarioActual.TienePermisoProceso(117) Then
e.Row.FCLinkButton("imgE").Visible = False
End If
'El Eliminar solo debera aparecer cuando se registre manual la compra, cuando viene de una factura se desactiva, o cuando esta registrada la compra
If CveFactura = 0 Then 'CveCompra <= 0 And
e.Row.FCLinkButton("imgD").Visible = True
'If e.Row.FCImageButton("imgE") IsNot Nothing Then e.Row.FCImageButton("imgE").Visible = True
If e.Row.FCTextBox("TxtCantidadEdit") IsNot Nothing Then e.Row.FCTextBox("TxtCantidadEdit").Enabled = True
If e.Row.FCTextBox("TxtPrecioEdit") IsNot Nothing Then e.Row.FCTextBox("TxtPrecioEdit").Enabled = True
End If
'Dejar un PS para ver que hace esto y documentar.
If e.Row.DBCampo("CvePS") = "0" Then
e.Row.Cells(0).ToolTip = "Producto/Servicio NO Registrado"
e.Row.Cells(0).ID = String.Format("tr{0}", e.Row.RowIndex)
e.Row.Cells(0).ClientIDMode = ClientIDMode.Static
e.Row.Cells(0).Attributes.Add("onclick", String.Format("fnAltaPS('{0}','{1}',{2})", String.Format("tr{0}", e.Row.RowIndex), e.Row.DBCampo("PS").Replace("'", "&#39;").Replace(Chr(13), "").Replace(Chr(10), ""), e.Row.RowIndex))
If e.Row.FCTextBox("TxtPrecioEdit") IsNot Nothing Then e.Row.FCTextBox("TxtPrecioEdit").Enabled = False
If e.Row.FCTextBox("TxtCantidadEdit") IsNot Nothing Then e.Row.FCTextBox("TxtCantidadEdit").Enabled = False
End If
'VALIDA UNIDAD DE MEDIDA
If e.Row.DBCampo("CvePS").ToString.ToEntero > 0 Then
Dim DtEquivalencias As DataTable = GlobalDTProductosServiciosEquivalencias(e.Row.DBCampo("CvePS").ToString.ToEntero, e.Row.DBCampo("CveUM").ToString.ToEntero, UsuarioActual.CveEmpresa)
'SI UM NO ESTA REGISTRADA
If e.Row.DBCampo("CveUM").ToString.ToEntero <= 0 Then
e.Row.FCLabel("LtlUnidadMedida").Attributes.Add("onclick", $"FncUMEquivalencias(1,'{e.Row.DBCampo("UM").Replace("'", "")}',{e.Row.RowIndex},'{DtEquivalencias.FiltroPrimeroValor("UnidadMedida", "UnidadBase = 1")}','{e.Row.DBCampo("CveUnidadMedidaSAT")}','{e.Row.DBCampo("SATClaveUnidadMedida")}')")
e.Row.FCLabel("LtlUnidadMedida").CssClass = "label label-danger manita centrarUM"
e.Row.FCLabel("LtlUnidadMedida").Attributes.Add("data-toggle", "tooltip")
e.Row.FCLabel("LtlUnidadMedida").Attributes.Add("title", "Unidad de medida SIN registrar")
End If
'EQUIVALENCIA
If e.Row.DBCampo("CveUM").ToString.ToEntero > 0 And e.Row.DBCampo("CveTipoPS").ToString.ToEntero = 2 Then
If DtEquivalencias.FiltraParametros($"CveUM = {e.Row.DBCampo("CveUM").ToString.ToEntero}").Rows.Count > 0 Then
If Not DtEquivalencias.FiltraParametros($"CveUM = {e.Row.DBCampo("CveUM").ToString.ToEntero} AND UnidadBase = 1").Rows.Count > 0 Then
'UM NO BASE
e.Row.FCLinkButton("LBAplicarEquivalencia").Visible = True
'e.Row.FCLabel("LtlUnidadMedida").Attributes.Add("onclick", $"FncUMEquivalencias(2,'{e.Row.DBCampo("UM").Replace("'", "")}',{e.Row.RowIndex},'{DtEquivalencias.FiltroPrimeroValor("UnidadMedida", "UnidadBase = 1")}')")
e.Row.FCLabel("LtlUnidadMedida").CssClass = "label label-danger centrarUM"
e.Row.FCLabel("LtlUnidadMedida").Attributes.Add("data-toggle", "tooltip")
e.Row.FCLabel("LtlUnidadMedida").Attributes.Add("title", "Unidad de medida NO medida base")
End If
Else
'SIN EQUIVALENCIA
e.Row.FCLabel("LtlUnidadMedida").Attributes.Add("onclick", $"FncUMEquivalencias(3,'{e.Row.DBCampo("UM").Replace("'", "")}',{e.Row.RowIndex},'{DtEquivalencias.FiltroPrimeroValor("UnidadMedida", "UnidadBase = 1")}','{e.Row.DBCampo("CveUnidadMedidaSAT")}','{e.Row.DBCampo("SATClaveUnidadMedida")}')")
e.Row.FCLabel("LtlUnidadMedida").CssClass = "label label-danger manita centrarUM"
e.Row.FCLabel("LtlUnidadMedida").Attributes.Add("data-toggle", "tooltip")
e.Row.FCLabel("LtlUnidadMedida").Attributes.Add("title", "Unidad de medida SIN equivalencia")
End If
DtEquivalencias.Dispose()
End If
End If
If PermisoEdicionManual Then
If e.Row.FCTextBox("TxtPrecioEdit") IsNot Nothing Then e.Row.FCTextBox("TxtPrecioEdit").Enabled = True
End If
'Esconde Editar y Eliminar cuando tiene una OC Vinculada
If OCVinculada Then
e.Row.FCLinkButton("ImgE").Visible = False
e.Row.FCLinkButton("ImgD").Visible = False
End If
If CveCompra <= 0 AndAlso e.Row.DBCampo("CvePS").ToEntero > 0 AndAlso e.Row.DBCampo("IEPSPSPorcentaje").ToDouble > 0 Then
If GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=e.Row.DBCampo("CvePS").ToEntero).Rows.Count > 0 Then
Dim DrPS As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=e.Row.DBCampo("CvePS").ToEntero).Rows(0)
If DrPS IsNot Nothing Then
If DrPS("IEPSPorcentaje").ToString.ToDouble <> e.Row.DBCampo("IEPSPSPorcentaje").ToDouble Then
e.Row.CssClass = "danger"
e.Row.ToolTip = "El porcentaje de IEPS del producto no coincide con el especificado."
End If
End If
End If
End If
If e.Row.DBCampo("CvePS").ToEntero > 0 AndAlso e.Row.DBCampo("NoDeducible") = "True" Then
e.Row.FCLabel("LblIVAPorcentaje").ToolTip = "IVA NO Deducible"
e.Row.FCLabel("LblIVAPorcentaje").ForeColor = Drawing.Color.Red
End If
'CargaPresupuestosEgresos
If UsuarioActual.Empresa.UsaAC Then
e.Row.Cells(14).Visible = True
e.Row.Cells(15).Visible = True
e.Row.Cells(16).Visible = True
e.Row.Cells(17).Visible = True
e.Row.Cells(18).Visible = True
e.Row.FCDropDownList("DdlAC1").Items.Clear()
e.Row.FCDropDownList("DdlAC1").DataSource = DtPresupuestos.FiltraParametros("", DistinctColumns:={"CveProgramaOperativo", "ProgramaOperativo"})
e.Row.FCDropDownList("DdlAC1").DataBind()
e.Row.FCDropDownList("DdlAC1").SelectedValueExist(e.Row.DBCampo("CveProgramaOperativo"))
e.Row.FCDropDownList("DdlAC2").Items.Clear()
e.Row.FCDropDownList("DdlAC2").DataSource = DtPresupuestos.FiltraParametros("", DistinctColumns:={"CveUnidadAdministrativa", "UnidadAdministrativa"}, Orderby:="UnidadAdministrativa")
e.Row.FCDropDownList("DdlAC2").DataBind()
e.Row.FCDropDownList("DdlAC2").SelectedValueExist(e.Row.DBCampo("CveUnidadAdministrativa"))
e.Row.FCDropDownList("DdlAC3").Items.Clear()
e.Row.FCDropDownList("DdlAC3").DataSource = DtPresupuestos.FiltraParametros("", DistinctColumns:={"CveFuenteFinanciamiento", "FuenteFinanciamiento"}, Orderby:="FuenteFinanciamiento")
e.Row.FCDropDownList("DdlAC3").DataBind()
e.Row.FCDropDownList("DdlAC3").SelectedValueExist(e.Row.DBCampo("CveFuenteFinanciamiento"))
e.Row.FCDropDownList("DdlAC4").Items.Clear()
e.Row.FCDropDownList("DdlAC4").DataSource = DtPresupuestos.FiltraParametros("", DistinctColumns:={"CveTipoGasto", "TipoGasto"})
e.Row.FCDropDownList("DdlAC4").DataBind()
e.Row.FCDropDownList("DdlAC4").SelectedValueExist(e.Row.DBCampo("CveTipoGasto"))
e.Row.FCDropDownList("DdlAC5").Items.Clear()
e.Row.FCDropDownList("DdlAC5").Visible = True
e.Row.FCDropDownList("DdlAC5").DataSource = DtPresupuestos.FiltraParametros("", DistinctColumns:={"CveClasificacion", "CodigoClasificacion"}, Orderby:="CodigoClasificacion") 'GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltraParametros("Afectable = 1 ") 'DtPresupuestos.FiltraParametros("", DistinctColumns:={"CveClasificacion", "CodigoClasificacion"}, Orderby:="CodigoClasificacion")
e.Row.FCDropDownList("DdlAC5").DataBind()
e.Row.FCDropDownList("DdlAC5").SelectedValueExist(e.Row.DBCampo("CveClasificacionOG"))
'SI EL PRESUPUESTO DE EGRESOS VIENE DESDE LA OC, SE BLOQUEA PE
If e.Row.DBCampo("CveOrdenCompraDetalle").ToEntero > 0 AndAlso e.Row.DBCampo("CvePresupuestoEgreso").ToEntero > 0 Then
e.Row.Cells(14).Enabled = False
e.Row.Cells(15).Enabled = False
e.Row.Cells(16).Enabled = False
e.Row.Cells(17).Enabled = False
e.Row.Cells(18).Enabled = False
End If
Else
e.Row.Cells(14).Visible = False
e.Row.Cells(15).Visible = False
e.Row.Cells(16).Visible = False
e.Row.Cells(17).Visible = False
e.Row.Cells(18).Visible = False
End If
End If
If e.Row.DataKey("DifPSSat").ToEntero = 1 Then
e.Row.BackColor = Drawing.ColorTranslator.FromHtml("#EFD569") 'Drawing.Color.FromArgb(1, 227, 91, 90)'#e35b5a
e.Row.Attributes.Add("data-toggle", "tooltip")
e.Row.Attributes.Add("data-html", "true")
e.Row.Attributes.Add("title", String.Format("El código del producto del SAT no es igual al código del producto registrado. <br/>Código XML:{0} <br/> Código Sistema:{1} ", e.Row.DBCampo("ClaveProdServ"), e.Row.DBCampo("SATClavePS")))
End If
End If
End Sub
Protected Sub GvPS_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles GvPS.RowDeleting
Dim DbRow As DataRow = Nothing
DbRow = TmpDT.Rows(e.RowIndex)
'Dim TipoDescuento As Integer = -1
Dim Cantidad, PU, IVA, Descuento As Double
Cantidad = DbRow("Cantidad").ToString.ToDouble
PU = DbRow("PU").ToString.ToDouble
IVA = DbRow("IVA").ToString.ToDouble
'IVA = Math.Round((((TxtSubTotal.Text.ToDouble - (Cantidad * PU - Descuento)) * TxtIVA.Text.ToDouble) / TxtSubTotal.Text.ToDouble), 2)
Descuento = DbRow("Descuento").ToString.ToDouble
If CveCompra > 0 Then
ClavesBorradas.Add(DbRow("CveCompraDetalle").ToString.ToEntero)
End If
TmpDT.Rows.RemoveAt(e.RowIndex)
GvPS.DataSource = TmpDT
GvPS.DataBind()
CalculaTotales(True)
CargaGvInv()
CargaGVsAF()
CargaGvPersonal()
Alert("El Concepto ha sido eliminado correctamente", TipoMensaje.MsgInformacion)
End Sub
Private Sub GvDeudores_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvDeudores.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim total As Double = TxtTotal.Text.ToString.ToDouble
Dim saldo As Double = e.Row.DataKey("Saldo").ToDouble
e.Row.FCCheckBox("Chk").Attributes.Add("onclick", String.Format("ClickDeudorChk(this, ""{0}"", ""{1}"", ""{2}"",""{3}"")", e.Row.FCTextBox("TxtSaldoDeudor").ClientID, total, saldo, e.Row.FCTextBox("TxtOtrosGastosIngresos").ClientID))
e.Row.FCTextBox("TxtSaldoDeudor").Attributes.Add("onKeyUp", String.Format("AjustaTextboxDeudores(this);"))
Dim rv As RangeValidator = CType(e.Row.FindControl("RVSaldoDeudor"), RangeValidator)
If saldo > total Then
rv.MaximumValue = total.ToString
Else
rv.MaximumValue = saldo.ToString
End If
End If
End Sub
#End Region
#Region "METODOS"
Private Sub GeneraGlobalDT(data As Object)
GlobalDTPSSimplificado(UsuarioActual.CveEmpresa) = Nothing
GlobalDTProductosServiciosEquivalencias(-1, -1, UsuarioActual.CveEmpresa) = Nothing
End Sub
Private Function notienepresupuesto() As Boolean
Dim notienerecursos = False
Dim SinRecursos As New StringBuilder
SinRecursos.AppendFormat("No se cuenta con los Recursos Suficientes en los siguientes subproyectos ")
Dim subproyectosSr As New List(Of Integer)
Dim filtro As New StringBuilder
'me traigo los proyectos y subproyectos para traer presupuesots de la bd
Dim subproyectos As New List(Of Integer)
For Each Row As DataRow In TmpDT.FiltraParametros("", "", {"CveSubProyecto", "SubProyecto"}).Rows
Dim RowCon As DataRow = GlobalDTContratos(UsuarioActual.CveEmpresa).FiltroPrimero(String.Format("CveSubProyecto={0}", Row("CveSubProyecto")))
If Not IsNothing(RowCon) Then
filtro.AppendFormat(",{0}", Row("CveSubProyecto"))
subproyectos.Add(Row("CveSubProyecto").ToString.ToEntero)
End If
Next
'me traigo los presupuestos de la base de datos
Dim dtpresupuestos As New DataTable
Dim objContratos As New ClsContratos
If objContratos.GetContratosPresupuesto(filtro.ToString) Then
dtpresupuestos = objContratos.DtResultados
End If
objContratos.Dispose()
'resto los importes actuales a los presupuestos obtenidos de la bd
For Each dr As DataRow In TmpDT.Rows
Dim psclasificacion As String = String.Format("CveSubFamilia='{0}' AND CveSubProyecto={1}", GlobalDTPS(UsuarioActual.CveEmpresa).FiltroPrimero(String.Format("CvePS={0}", dr("CvePS").ToString.ToEntero))("CveSubFamilia").ToString, dr("CveSubProyecto").ToString)
If dtpresupuestos.Rows.Count > 0 AndAlso dtpresupuestos.Select(psclasificacion).Count > 0 Then
Dim rowpresupuesto As DataRow = dtpresupuestos.Select(psclasificacion)(0)
rowpresupuesto("Importe") = rowpresupuesto("Importe").ToString.ToDouble - dr("Total").ToString.ToDouble()
Else
If subproyectos.Contains(dr("CveSubProyecto").ToString.ToEntero) Then
notienerecursos = True
If Not subproyectosSr.Contains(dr("CveSubProyecto").ToString.ToEntero) Then
subproyectosSr.Add(dr("CveSubProyecto").ToString.ToEntero)
SinRecursos.AppendFormat(",{0}", dr("SubProyecto").ToString)
End If
End If
End If
Next
dtpresupuestos.AcceptChanges()
'
For Each rowpresupuesto As DataRow In dtpresupuestos.Rows
If (rowpresupuesto("Importe").ToString.ToDouble() < 0) Then
If Not subproyectosSr.Contains(rowpresupuesto("CveSubProyecto").ToString.ToEntero) Then
subproyectosSr.Add(rowpresupuesto("CveSubProyecto").ToString.ToEntero)
SinRecursos.AppendFormat(",{0}", rowpresupuesto("SubProyecto").ToString)
End If
notienerecursos = True
End If
Next
If (notienerecursos) Then
Alert(SinRecursos.ToString, TipoMensaje.MsgAdvertencia)
End If
dtpresupuestos.Dispose()
Return notienerecursos
End Function
Private Sub CreaDTConceptos()
DTConceptos = New DataTable
DTConceptos.Columns.Add("Consec", GetType(Integer))
DTConceptos.Columns.Add("Cantidad", GetType(Double))
DTConceptos.Columns.Add("UM", GetType(String))
DTConceptos.Columns.Add("CveClasificacion", GetType(Integer))
DTConceptos.Columns.Add("PS", GetType(String))
DTConceptos.Columns.Add("PU", GetType(Double))
DTConceptos.Columns.Add("Descuento", GetType(Double))
DTConceptos.Columns.Add("IVA", GetType(Double))
DTConceptos.Columns.Add("Total", GetType(Double))
DTConceptos.Columns.Add("Amortizacion", GetType(Double))
End Sub
Private Sub CreaDTCompras()
TmpDT = New DataTable
TmpDT.Columns.Add("Consec", GetType(Integer))
TmpDT.Columns.Add("Cantidad", GetType(Decimal))
TmpDT.Columns.Add("Codigo", GetType(String))
TmpDT.Columns.Add("CveUM", GetType(Integer))
TmpDT.Columns.Add("UM", GetType(String))
TmpDT.Columns.Add("CveClasificacion", GetType(Integer))
TmpDT.Columns.Add("Clasificacion", GetType(String))
TmpDT.Columns.Add("CveClasificacionActualizar", GetType(Integer))
TmpDT.Columns.Add("CvePS", GetType(Integer))
TmpDT.Columns.Add("PS", GetType(String))
TmpDT.Columns.Add("Obs", GetType(String))
TmpDT.Columns.Add("PU", GetType(Decimal))
TmpDT.Columns.Add("IVA", GetType(Decimal))
TmpDT.Columns.Add("IVAPorcentaje", GetType(Decimal))
TmpDT.Columns.Add("RetIVA", GetType(Decimal))
TmpDT.Columns.Add("RetIVAPorcentaje", GetType(Decimal))
TmpDT.Columns.Add("RetISR", GetType(Decimal))
TmpDT.Columns.Add("RetISRPorcentaje", GetType(Decimal))
TmpDT.Columns.Add("IEPSPS", GetType(Double))
TmpDT.Columns.Add("IEPSPSPorcentaje", GetType(Double))
TmpDT.Columns.Add("IEPSPSIVA", GetType(Double))
TmpDT.Columns.Add("IEPSPSIVAPorcentaje", GetType(Double))
TmpDT.Columns.Add("Descuento", GetType(Decimal))
TmpDT.Columns.Add("OtrosGastos", GetType(Decimal))
TmpDT.Columns.Add("Total", GetType(Decimal))
TmpDT.Columns.Add("AsientoContableCompras", GetType(Integer))
TmpDT.Columns.Add("IdCtaContCompras", GetType(Integer))
TmpDT.Columns.Add("Proyecto", GetType(String))
TmpDT.Columns.Add("CveProyecto", GetType(Integer))
TmpDT.Columns.Add("CveSubProyecto", GetType(Integer))
TmpDT.Columns.Add("CveContrato", GetType(Integer))
TmpDT.Columns.Add("SubProyecto", GetType(String))
'TmpDT.Columns.Add("CveEq", GetType(Integer))
TmpDT.Columns.Add("CveAlmacen", GetType(Integer))
TmpDT.Columns.Add("CvePersonal", GetType(String))
TmpDT.Columns.Add("Referencia", GetType(String))
'AC
TmpDT.Columns.Add("CveTipoGastoAC", GetType(Integer))
TmpDT.Columns.Add("CvePresupuestoEgreso", GetType(Integer))
TmpDT.Columns.Add("CveProgramaOperativo", GetType(Integer))
TmpDT.Columns.Add("CveUnidadAdministrativa", GetType(Integer))
TmpDT.Columns.Add("CveFuenteFinanciamiento", GetType(Integer))
TmpDT.Columns.Add("CveClasificacionOG", GetType(Integer))
TmpDT.Columns.Add("IdCuentaComprometido", GetType(Integer))
TmpDT.Columns.Add("IdCuentaPorEjercer", GetType(Integer))
TmpDT.Columns.Add("IdCuentaDevengado", GetType(Integer))
TmpDT.Columns.Add("IdCuentaMatriz", GetType(Integer))
'INVENTARIO SERIE/LOTE
TmpDT.Columns.Add("CveMetodoInventario", GetType(Integer))
TmpDT.Columns.Add("CveConcepto", GetType(Integer))
'AF
TmpDT.Columns.Add("CveActivoFijo", GetType(Integer))
TmpDT.Columns.Add("CodAF", GetType(String))
TmpDT.Columns.Add("TipoAF", GetType(Integer))
TmpDT.Columns.Add("AFMedida", GetType(Integer))
TmpDT.Columns.Add("AFTipoMantenimiento", GetType(Integer))
'PS
TmpDT.Columns.Add("CveTipoPS", GetType(Integer))
TmpDT.Columns.Add("CodigoPS", GetType(String))
TmpDT.Columns.Add("PSDescripcion", GetType(String))
'CAMPO ESPECIAL PARA GLUYAS - LEE EL DEL XML - A GLUYAS LE INTERESA EL CODIGO DEL PROVEEDOR
TmpDT.Columns.Add("PSCodigo", GetType(String))
'OC
TmpDT.Columns.Add("CveOrdenCompraDetalle", GetType(Integer))
TmpDT.Columns.Add("ProductoOC", GetType(String))
TmpDT.Columns.Add("CantidadF", GetType(Double))
'Consignaciones
TmpDT.Columns.Add("CveAlmacenConsignacion", GetType(Integer))
TmpDT.Columns.Add("NoConsignacion", GetType(Integer))
TmpDT.Columns.Add("CveConsignacion", GetType(Integer))
TmpDT.Columns.Add("HdnPS", GetType(String))
TmpDT.Columns.Add("HdnCvePS", GetType(String))
TmpDT.Columns.Add("HdnClasificacion", GetType(String))
TmpDT.Columns.Add("HdnCveClasificacion", GetType(String))
TmpDT.Columns.Add("HdnCveAlmacen", GetType(String))
'Fletes y Servicios
TmpDT.Columns.Add("AplicaCostoIndirecto", GetType(Integer))
TmpDT.Columns.Add("CostoIndirectoAlmacen", GetType(Decimal))
TmpDT.Columns.Add("CveCompraDetalle", GetType(Integer))
TmpDT.Columns.Add("EntregaDirecta", GetType(Integer))
'SAT
TmpDT.Columns.Add("CveSATPS", GetType(Integer))
TmpDT.Columns.Add("SATClaveProductoServicio", GetType(String))
TmpDT.Columns.Add("CveUnidadMedidaSAT", GetType(Integer))
TmpDT.Columns.Add("SATClaveUnidadMedida", GetType(String))
TmpDT.Columns.Add("CveSATPSActualizado", GetType(Integer))
'Tipo de Gasto
TmpDT.Columns.Add("CveTipoGasto", GetType(Integer))
TmpDT.Columns.Add("TipoGasto", GetType(String))
TmpDT.Columns.Add("ImporteSinImpuestos", GetType(Double))
TmpDT.Columns.Add("ImporteConImpuestos", GetType(Double))
TmpDT.Columns.Add("NoDeducible", GetType(Boolean))
TmpDT.Columns.Add("DifPSSat", GetType(Integer))
TmpDT.Columns.Add("CveContratoDetalle", GetType(Integer))
TmpDT.Columns.Add("CveCultivoCuadroDetalle", GetType(Integer))
TmpDT.Columns.Add("TemporadaCuadro", GetType(String))
TmpDTOriginal = New DataTable
TmpDTOriginal.Columns.Add("Consec", GetType(Integer))
TmpDTOriginal.Columns.Add("Cantidad", GetType(Decimal))
TmpDTOriginal.Columns.Add("Codigo", GetType(String))
TmpDTOriginal.Columns.Add("CveUM", GetType(Integer))
TmpDTOriginal.Columns.Add("UM", GetType(String))
TmpDTOriginal.Columns.Add("CveClasificacion", GetType(Integer))
TmpDTOriginal.Columns.Add("Clasificacion", GetType(String))
TmpDTOriginal.Columns.Add("CveClasificacionActualizar", GetType(Integer))
TmpDTOriginal.Columns.Add("CvePS", GetType(Integer))
TmpDTOriginal.Columns.Add("PS", GetType(String))
TmpDTOriginal.Columns.Add("Obs", GetType(String))
TmpDTOriginal.Columns.Add("PU", GetType(Decimal))
TmpDTOriginal.Columns.Add("IVA", GetType(Decimal))
TmpDTOriginal.Columns.Add("IVAPorcentaje", GetType(Decimal))
TmpDTOriginal.Columns.Add("RetIVA", GetType(Decimal))
TmpDTOriginal.Columns.Add("RetIVAPorcentaje", GetType(Decimal))
TmpDTOriginal.Columns.Add("RetISR", GetType(Decimal))
TmpDTOriginal.Columns.Add("RetISRPorcentaje", GetType(Decimal))
TmpDTOriginal.Columns.Add("IEPSPS", GetType(Double))
TmpDTOriginal.Columns.Add("IEPSPSPorcentaje", GetType(Double))
TmpDTOriginal.Columns.Add("IEPSPSIVA", GetType(Double))
TmpDTOriginal.Columns.Add("IEPSPSIVAPorcentaje", GetType(Double))
TmpDTOriginal.Columns.Add("Descuento", GetType(Decimal))
TmpDTOriginal.Columns.Add("OtrosGastos", GetType(Decimal))
TmpDTOriginal.Columns.Add("Total", GetType(Decimal))
TmpDTOriginal.Columns.Add("AsientoContableCompras", GetType(Integer))
TmpDTOriginal.Columns.Add("IdCtaContCompras", GetType(Integer))
TmpDTOriginal.Columns.Add("Proyecto", GetType(String))
TmpDTOriginal.Columns.Add("CveProyecto", GetType(Integer))
TmpDTOriginal.Columns.Add("CveSubProyecto", GetType(Integer))
TmpDTOriginal.Columns.Add("CveContrato", GetType(Integer))
TmpDTOriginal.Columns.Add("SubProyecto", GetType(String))
'TmpDTOriginal.Columns.Add("CveEq", GetType(Integer))
TmpDTOriginal.Columns.Add("CveAlmacen", GetType(Integer))
TmpDTOriginal.Columns.Add("CvePersonal", GetType(String))
TmpDTOriginal.Columns.Add("Referencia", GetType(String))
'AC
TmpDTOriginal.Columns.Add("CveTipoGastoAC", GetType(Integer))
TmpDTOriginal.Columns.Add("CvePresupuestoEgreso", GetType(Integer))
TmpDTOriginal.Columns.Add("CveProgramaOperativo", GetType(Integer))
TmpDTOriginal.Columns.Add("CveUnidadAdministrativa", GetType(Integer))
TmpDTOriginal.Columns.Add("CveFuenteFinanciamiento", GetType(Integer))
TmpDTOriginal.Columns.Add("CveClasificacionOG", GetType(Integer))
TmpDTOriginal.Columns.Add("IdCuentaComprometido", GetType(Integer))
TmpDTOriginal.Columns.Add("IdCuentaPorEjercer", GetType(Integer))
TmpDTOriginal.Columns.Add("IdCuentaDevengado", GetType(Integer))
TmpDTOriginal.Columns.Add("IdCuentaMatriz", GetType(Integer))
'INVENTARIO SERIE/LOTE
TmpDTOriginal.Columns.Add("CveMetodoInventario", GetType(Integer))
TmpDTOriginal.Columns.Add("CveConcepto", GetType(Integer))
'AF
TmpDTOriginal.Columns.Add("CveActivoFijo", GetType(Integer))
TmpDTOriginal.Columns.Add("CodAF", GetType(String))
TmpDTOriginal.Columns.Add("TipoAF", GetType(Integer))
TmpDTOriginal.Columns.Add("AFMedida", GetType(Integer))
TmpDTOriginal.Columns.Add("AFTipoMantenimiento", GetType(Integer))
'PS
TmpDTOriginal.Columns.Add("CveTipoPS", GetType(Integer))
TmpDTOriginal.Columns.Add("CodigoPS", GetType(String))
TmpDTOriginal.Columns.Add("PSDescripcion", GetType(String))
'CAMPO ESPECIAL PARA GLUYAS - LEE EL DEL XML - A GLUYAS LE INTERESA EL CODIGO DEL PROVEEDOR
TmpDTOriginal.Columns.Add("PSCodigo", GetType(String))
'OC
TmpDTOriginal.Columns.Add("CveOrdenCompraDetalle", GetType(Integer))
TmpDTOriginal.Columns.Add("ProductoOC", GetType(String))
TmpDTOriginal.Columns.Add("CantidadF", GetType(Double))
'Consignaciones
TmpDTOriginal.Columns.Add("CveAlmacenConsignacion", GetType(Integer))
TmpDTOriginal.Columns.Add("NoConsignacion", GetType(Integer))
TmpDTOriginal.Columns.Add("CveConsignacion", GetType(Integer))
TmpDTOriginal.Columns.Add("HdnPS", GetType(String))
TmpDTOriginal.Columns.Add("HdnCvePS", GetType(String))
TmpDTOriginal.Columns.Add("HdnClasificacion", GetType(String))
TmpDTOriginal.Columns.Add("HdnCveClasificacion", GetType(String))
TmpDTOriginal.Columns.Add("HdnCveAlmacen", GetType(String))
'Fletes y Servicios
TmpDTOriginal.Columns.Add("AplicaCostoIndirecto", GetType(Integer))
TmpDTOriginal.Columns.Add("CostoIndirectoAlmacen", GetType(Decimal))
TmpDTOriginal.Columns.Add("CveCompraDetalle", GetType(Integer))
TmpDTOriginal.Columns.Add("EntregaDirecta", GetType(Integer))
'SAT
TmpDTOriginal.Columns.Add("CveSATPS", GetType(Integer))
TmpDTOriginal.Columns.Add("SATClaveProductoServicio", GetType(String))
TmpDTOriginal.Columns.Add("CveUnidadMedidaSAT", GetType(Integer))
TmpDTOriginal.Columns.Add("SATClaveUnidadMedida", GetType(String))
TmpDTOriginal.Columns.Add("CveSATPSActualizado", GetType(Integer))
'Tipo de Gasto
TmpDTOriginal.Columns.Add("CveTipoGasto", GetType(Integer))
TmpDTOriginal.Columns.Add("TipoGasto", GetType(String))
TmpDTOriginal.Columns.Add("NoDeducible", GetType(Boolean))
TmpDTOriginal.Columns.Add("Importe", GetType(Double))
TmpDTOriginal.Columns.Add("CveContratoDetalle", GetType(Double))
TmpDTOriginal.Columns.Add("CveCultivoCuadroDetalle", GetType(Double))
TmpDTOriginal.Columns.Add("TemporadaCuadro", GetType(String))
End Sub
Protected Sub RecargaMaximum_Click(sender As Object, e As System.EventArgs)
CalculaTotales(True)
'RVDocumentoImporte.MaximumValue = (TxtSubTotal.Text.ToDouble - TxtDescuento.Text.ToDouble - LblAmortizacion.Text.Trim.ToDouble + TxtIVA.Text.ToDouble - TxtRetIVA.Text.ToDouble - TxtRetISR.Text.ToDouble).FormatoNumero(2)
'RVDocumentoImporteFE.MaximumValue = RVDocumentoImporte.MaximumValue
'RVDocumentoImporteCaja.MaximumValue = RVDocumentoImporte.MaximumValue
End Sub
Protected Sub AlmacenCambiaPS_Click(sender As Object, e As EventArgs) Handles AlmacenCambiaPS.Click
Dim correcto As Boolean = True
Dim x As Integer = 0
'Dim buid As New StringBuilder
For Each Dr As DataRow In TmpDT.Rows
Dim newps As Integer = GvInv.Rows(x).FCDropDownList("Ddlnewps").SelectedValue.ToEntero
If newps > 0 Then
'buid.Append(String.Format("{0} ---> {1},", Dr("CvePS").ToString, newps))
Dr("CvePS") = newps
'buid.Append(String.Format("{0} ---> {1},</br>", Dr("CvePS").ToString, newps))
Else 'limpio el valor para que no truene en linq mas abajo
correcto = False
Alert("Favor de asociar todos los productos o servicios", TipoMensaje.MsgAdvertencia)
Exit For
End If
x = x + 1
Next
x = 0
For Each Dr As DataRow In DtInv.Rows
Dim newps As Integer = GvInv.Rows(x).FCDropDownList("Ddlnewps").SelectedValue.ToEntero
If newps > 0 Then
'buid.Append(String.Format("{0} ---> {1},", Dr("CvePS").ToString, newps))
Dr("CvePS") = newps
'buid.Append(String.Format("{0} ---> {1},</br>", Dr("CvePS").ToString, newps))
Else 'limpio el valor para que no truene en linq mas abajo
correcto = False
Alert("Favor de asociar todos los productos o servicios", TipoMensaje.MsgAdvertencia)
Exit For
End If
x = x + 1
Next
TmpDT.AcceptChanges()
'Alert(buid.ToString)
If correcto Then
If Not CierrePeriodo Then
BtnGuardar.Visible = True
End If
UpFacturar.Update()
End If
End Sub
Private Sub SetValues()
'Dim um As New ClsUnidadesMedida
TxtFecha.Text = Now.ToShortDateString()
LblUsuarioCaptura.Text = UsuarioActual.Usuario
DdlProveedor.Attributes.Add("onclick", "CargaProveedores();")
'DdlFuncionarioEmpleado.Attributes.Add("onclick", "CargaFuncionariosEmpleados();")
TxtPrecio.Attributes.Add("onKeyUp ", "Recalcula();")
TxtCantidad.Attributes.Add("onKeyUp ", "Recalcula();")
TxtDescuentoModal.Attributes.Add("onKeyUp ", "Recalcula();")
TxtOtrosGastos.Attributes.Add("onKeyUp ", "Recalcula();")
'ImgAmort.Attributes.Add("onclick", "javascript:$('#DivDescP').show(1000); PosicionaObjeto(this.id,'DivDescP');") ' $get('LblTitulo1').style.display = 'none'; $get('LblTituloTipo1').style.display = 'none'; $get('LblTituloTipo2').style.display = ''; $get('LblPrecio1').style.display = 'none'; $get('LblTotalPS1').style.display = 'none'; $get('LblSubTotal1').style.display = 'none'; $get('LblAmort').style.display = ''; $get('BtnAplicarDescP').style.display = 'none'; $get('BtnAplicarDescG').style.display = ''; $get('TrMotivoDescuento').style.display = 'none';")
'If um.GetUnidadesMedida() Then
' GlobalDTUnidadesMedida = um.DtResultados
'End If
'um.Dispose()
'CargaEstatus()
CargaTiposAF()
CargaProyectoAsignado()
CargaClasificacionesComprobaciones()
CargaClasificaciones()
CargaPS(-1)
CreaDTCompras()
CargaMonedas()
CargarAlmacen()
'CreaDtAF()
'TabOC.Visible = False
'BORRAR OC
'Valores para Vinculacion OC
'If UsuarioActual.Empresa.MetodoOC = 1 Then GvOC2.Columns(2).Visible = False : tdSurtirOC.Visible = False Else GvOC2.Columns(0).Visible = False : tdFolioOC.Visible = False
CveAlmacenConsignacion = -1
CveConsignacion = -1
OCVinculada = False
TipoCambioOC = -1
EstatusAlmacen = -1
CreaDtDetalle()
CargarUMAlias()
End Sub
#End Region
#Region " ALGO DE AF QUE NUNCA SE USABA "
Protected Sub BtnOCAceptar_Click(sender As Object, e As EventArgs) Handles BtnOCAceptar.Click
'carga la OC
Dim CveOC As Integer = -1
For Each gvr As GridViewRow In GvOC.Rows
If gvr.FCCheckBox("Chk").Checked Then
CveOC = gvr.DataKey("CveOrdenCompra").ToEntero
Exit For
End If
Next
Dim dt As DataTable = Nothing
If CveOC > 0 Then
Dim OC As New ClsOC
If OC.GetOC(CveOC, UsuarioActual.CveEmpresa) Then
TxtOC.Text = OC.Folio.ToString
'RegistraScript(String.Format("$get('TxtOC').value = '{0}';tb_remove;", OC.Folio))
RegistraScript("tb_remove();")
If OC.GetOrdenesDetalle(CveOC) Then
dt = OC.DtResultados
End If
End If
OC.Dispose()
End If
End Sub
#End Region
#Region "Estimaciones"
'Private Sub CargaDatosEstimaciones(pCveProveedor As Integer)
' Dim Con As New ClsContratos
' If Con.GetEstimaciones(pCveProveedor, -1, -1, -1, -1, 0, UsuarioActual.CveEmpresa) Then
' GVEst.DataSource = Con.DtResultados
' GVEst.DataBind()
' End If
' UPEstimaciones.Update()
' Con.Dispose()
'End Sub
'Protected Sub GVEst_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GVEst.RowDataBound
' If e.Row.RowType = DataControlRowType.DataRow Then
' If e.Row.RowIndex = 0 Then
' e.Row.Cells(0).Width = Unit.Pixel(30)
' e.Row.Cells(1).Width = Unit.Pixel(30) 'Seccion
' e.Row.Cells(2).Width = Unit.Pixel(300) 'SubSeccion
' e.Row.Cells(3).Width = Unit.Pixel(100) 'Cantidad
' End If
' If e.Row.DBCampo("RazonSocial") = "" Then
' e.Row.CssClass = "Totales" : e.Row.Height = 25
' ElseIf e.Row.DBCampo("Contrato") = "" Then
' e.Row.CssClass = "SubTotales2" : e.Row.Height = 25
' ElseIf e.Row.DBCampo("Seccion") = "" Then
' e.Row.CssClass = "SubTotales" : e.Row.Height = 25
' ElseIf e.Row.DBCampo("Clasificacion") = "" Then
' e.Row.CssClass = "SubTotales3" : e.Row.Height = 25
' End If
' End If
'End Sub
#End Region
#Region " ALMACEN "
Private Sub CargaGvInv()
'SI ES CONSIGNACION NO LIMITA POR TIPO PS - PARA GLUYAS
If ChkConsignacion.Checked Then
DtInv = TmpDT.Copy
Else
DtInv = TmpDT.FiltraParametros(String.Format("CveTipoPS = 2")).Copy
End If
GvInv.DataSource = DtInv
GvInv.DataBind()
'If (GvInv.Rows.Count > 0) Then
' GvInv.UseAccessibleHeader = True
' GvInv.HeaderRow.TableSection = TableRowSection.TableHeader
' RegistraScript("OrdenarGVInv();")
'End If
InicializaCargaEvidenciaAlmacen()
'CARGA VALORES YA SELECCIONADOS DE CONSIGNACION
If ChkConsignacion.Checked Then
End If
UpINV.Update()
End Sub
Private Sub CargaFletesAgregados()
CreaDTServicios()
BtnFiltrar_Click(Nothing, Nothing)
End Sub
Protected Sub GVINV_RowEditing(sender As Object, e As GridViewEditEventArgs) Handles GvInv.RowEditing
CargaGvInv()
End Sub
Protected Sub GVINV_RowCancelingEdit(sender As Object, e As GridViewCancelEditEventArgs) Handles GvInv.RowCancelingEdit
CargaGvInv()
End Sub
Protected Sub GVINV_RowUpdating(sender As Object, e As GridViewUpdateEventArgs) Handles GvInv.RowUpdating
Dim Cantidad As Double = GvInv.Rows(e.RowIndex).FCTextBox("txtECantidad").Text.ToDouble
Dim CveUnidadMedida As Integer = GvInv.Rows(e.RowIndex).FCDropDownList("ddlEUnidad").SelectedValue.ToString.ToEntero
DtInv.Rows.Item(e.RowIndex)("Cantidad") = Cantidad
DtInv.Rows.Item(e.RowIndex)("CveUM") = CveUnidadMedida
CargaGvInv()
End Sub
Protected Sub GVINV_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvInv.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
'SI USA SERIE-LOTE INVENTARIO
If e.Row.DBCampo("CveMetodoInventario").ToString = "5" Then
e.Row.FCButton("BtnSerieLote").Visible = True
e.Row.FCButton("BtnSerieLote").CommandArgument = String.Format("{0}°{1}°{2}°{3}°{4}", e.Row.DBCampo("CvePS"), e.Row.DBCampo("CveUM"), e.Row.DBCampo("PU"), e.Row.DBCampo("PS"), e.Row.DBCampo("Cantidad"))
e.Row.FCTextBox("TbCantidad").Enabled = False
e.Row.FCCheckBox("cbInv").Enabled = False
Dim Contador = DtDatosDetalle.FiltraParametros(String.Format("CvePS = {0}", e.Row.DataKey("CvePS"))).Rows.Count
e.Row.FCTextBox("TbCantidad").Text = Contador.ToString
'e.Row.FCTextBox("TbCantidadF").Text = "0"
Else
e.Row.FCButton("BtnSerieLote").Visible = False
e.Row.FCTextBox("TbCantidad").Enabled = True
e.Row.FCTextBox("TbCantidad").Attributes.Add("onblur", String.Format("ValidarCantidad(this,{0})", e.Row.DBCampo("Cantidad")))
End If
'SIEMPRE ENABLED FALSE
e.Row.FCCheckBox("cbInv").Enabled = False
'si ya hay cargada una compra
If CveCompra > 0 AndAlso CveMovimientoAlmacen > 0 Then
If e.Row.DBCampo("AlmacenRegistrado").ToString = "1" Then
e.Row.FCCheckBox("cbInv").Checked = True
End If
e.Row.FCCheckBox("cbInv").Enabled = False
End If
'CONSIGNACIONES
If ChkConsignacion.Checked Then
e.Row.FCTextBox("TbCantidad").Enabled = False
e.Row.FCCheckBox("cbInv").Enabled = False
If Not OCVinculada Then
e.Row.Cells(3).Text = e.Row.DBCampo("PSCodigo").ToString
End If
Else
If e.Row.DBCampo("CveMetodoInventario").ToString = "5" Then
e.Row.FCTextBox("TbCantidad").Enabled = False
Else
e.Row.FCTextBox("TbCantidad").Enabled = True
End If
e.Row.FCCheckBox("cbInv").Enabled = False
End If
If UsuarioActual.Empresa.UsaAC Then
e.Row.FCCheckBox("cbInv").Enabled = False
End If
e.Row.FCDropDownList("ddlEAlmacen").DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1).FiltraParametros(If(DdlTipoCompra.SelectedValue.ToEntero = 9, "CveTipoAlmacen IN (21)", "CveTipoAlmacen IN (1,2,7,14,19)")) 'GlobalDTAlmacen(UsuarioActual.CveEmpresa)
e.Row.FCDropDownList("ddlEAlmacen").Items.Insert(0, New ListItem("Seleccione", "-1"))
e.Row.FCDropDownList("ddlEAlmacen").DataBind()
'e.Row.FCDropDownList("ddlEAlmacen").SelectedValue = If(e.Row.DBCampo("CveAlmacen").ToEntero <= 0, "-1", e.Row.DBCampo("CveAlmacen"))
If UsuarioActual.Empresa.UsaAC Then e.Row.FCDropDownList("ddlEAlmacen").Enabled = False
If UsuarioActual.Empresa.Funcionalidad(567) = "1" Then
If e.Row.FCDropDownList("ddlEAlmacen").Items.Count > 1 Then
e.Row.FCDropDownList("ddlEAlmacen").SelectedIndex = 1
e.Row.FCCheckBox("cbInv").Checked = True
ddlAlmacenConsignacion_SelectedIndexChanged(e.Row.FCDropDownList("ddlEAlmacen"), Nothing)
CambiaTotalDevengar(Nothing, Nothing)
End If
End If
If Not e.Row.DBCampo("CveMetodoInventario").ToString = "5" Then
e.Row.FCTextBox("TbCantidad").Attributes.Add("onblur", String.Format("ValidarCantidad(this,{0})", If(e.Row.DBCampo("CantidadF").ToString.ToDecimal > e.Row.DBCampo("Cantidad").ToString.ToDecimal, e.Row.DBCampo("Cantidad"), e.Row.DBCampo("CantidadF"))))
e.Row.FCTextBox("TbCantidad").Text = If(e.Row.DBCampo("CantidadF").ToString.ToDecimal > e.Row.DBCampo("Cantidad").ToString.ToDecimal, e.Row.DBCampo("Cantidad"), e.Row.DBCampo("CantidadF"))
End If
'e.Row.FCImageButton("btnImgDestino").Attributes.Add("onclick", "javascript:$('#DivAlmacen').show(500); PosicionaObjeto(this.id,'DivAlmacen'); CargarValores('" & e.Row.RowIndex & "','" & e.Row.DBCampo("Cantidad") & "','" & e.Row.DBCampo("PS").Replace("'", "\'") & "'); ")
' e.Row.FCImageButton("btnImgDestino").ID = e.Row.FCImageButton("btnImgDestino").ID.ToString + e.Row.RowIndex.ToString
'e.Row.Cells(6).ToolTip = "Enviar a otro Almacén."
If e.Row.DBCampo("Consec").ToEntero = 0 Then
e.Row.BackColor = Drawing.Color.PaleGreen
End If
If UsuarioActual.CveEmpresa = 66 Then
e.Row.FCDropDownList("DdlRecibirInv").Items.RemoveAt(1)
End If
'If isAlmacenistaGluyas() Then
' Dim dt As DataTable = Nothing
' dt = GlobalDTProductosServicios(UsuarioActual.CveEmpresa).FiltraParametros("CveTipoPS=2", "PS")
' e.Row.FCDropDownList("Ddlnewps").DataSource = dt 'GlobalDTAlmacen(UsuarioActual.CveEmpresa)
' e.Row.FCDropDownList("Ddlnewps").DataBind()
' e.Row.FCDropDownList("Ddlnewps").Items.Insert(0, New ListItem("Seleccione", "-1"))
' dt.Dispose()
'End If
'Consignaciones
If CveConsignacion > 0 Then
''CARGA ALMACEN CONSIGNACION
e.Row.FCDropDownList("ddlAlmacenConsignacion").DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, 4)
e.Row.FCDropDownList("ddlAlmacenConsignacion").DataBind()
If e.Row.DBCampo("CveAlmacenConsignacion").ToEntero > 0 Then
e.Row.FCDropDownList("ddlAlmacenConsignacion").SelectedValueExist(e.Row.DBCampo("CveAlmacenConsignacion"))
End If
''CARGA CONSIGNACIONES
e.Row.FCDropDownList("DdlVinculaConsignacion").DataSource = DtConsignaciones.FiltraParametros(String.Format("CveAlmacenSalida = {0} OR {0} = '-1'", e.Row.FCDropDownList("ddlAlmacenConsignacion").SelectedValue))
e.Row.FCDropDownList("DdlVinculaConsignacion").DataBind()
e.Row.FCDropDownList("DdlVinculaConsignacion").Items.Insert(0, New ListItem("Seleccione", "-1"))
If e.Row.DBCampo("NoConsignacion").ToEntero > 0 Then
e.Row.FCDropDownList("DdlVinculaConsignacion").SelectedValueExist(e.Row.DBCampo("NoConsignacion"))
e.Row.FCHiddenField("HdnNoConsignacion").Value = e.Row.DBCampo("NoConsignacion")
End If
If e.Row.DBCampo("CveConsignacion").ToEntero > 0 Then
e.Row.FCHiddenField("HdnCveConsignacion").Value = e.Row.DBCampo("CveConsignacion")
e.Row.FCHiddenField("HdnPS").Value = e.Row.DBCampo("HdnPS")
e.Row.FCHiddenField("HdnCvePS").Value = e.Row.DBCampo("HdnCvePS")
e.Row.FCHiddenField("HdnClasificacion").Value = e.Row.DBCampo("HdnClasificacion")
e.Row.FCHiddenField("HdnCveClasificacion").Value = e.Row.DBCampo("HdnCveClasificacion")
e.Row.FCHiddenField("HdnCveAlmacen").Value = e.Row.DBCampo("HdnCveAlmacen")
End If
e.Row.FCTextBox("TxtDividir").Visible = True
Else
e.Row.FCTextBox("TxtDividir").Visible = False
End If
If Not UsuarioActual.Empresa.UsaAC Then
e.Row.FCTextBox("TxtDividir").Attributes.Add("onkeyup", String.Format("FormatoMoneda(this);LimitaCantidad({0},this,'{1}');", e.Row.DBCampo("Cantidad"), e.Row.FCButton("BtnDividirCompra").ClientID))
e.Row.FCTextBox("TxtDividir").Text = ""
If e.Row.DBCampo("Cantidad").ToDouble > 0.02 Then
e.Row.FCButton("BtnDividirCompra").CommandArgument = e.Row.RowIndex.ToString
Else
e.Row.FCButton("BtnDividirCompra").Visible = False
e.Row.FCTextBox("TxtDividir").Visible = False
End If
End If
End If
'HEADER GvInv
If e.Row.RowType = DataControlRowType.Header Then
Dim StrAlmacenes As String = "CveTipoAlmacen IN (1,2,7,14,19)"
If UsuarioActual.CveUsuario.Contiene(1397, 1517, 1565) Then ' iliana, horacio, marco, RMF. 2017.03.13
StrAlmacenes = "CveTipoAlmacen IN (1,2,7,14,12,19)"
End If
If DdlTipoCompra.SelectedValue.ToEntero = 9 Then
StrAlmacenes = "CveTipoAlmacen IN (21)"
End If
If DdlTipoCompra.SelectedValue.ToEntero = 10 Then
StrAlmacenes = $"Modalidad = 0"
End If
e.Row.FCDropDownList("ddlAlmacen").DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1).FiltraParametros(StrAlmacenes) 'GlobalDTAlmacen(UsuarioActual.CveEmpresa)
e.Row.FCDropDownList("ddlAlmacen").Items.Insert(0, New ListItem("Seleccione", "-1"))
e.Row.FCDropDownList("ddlAlmacen").DataBind()
'si ya hay cargada una compra
If CveCompra > 0 AndAlso CveMovimientoAlmacen > 0 Then
e.Row.FCCheckBox("cbAll").Enabled = False
End If
''CARGA ALMACEN CONSIGNACION
e.Row.FCDropDownList("ddlAlmacenConsignacionGeneral").DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, 4)
e.Row.FCDropDownList("ddlAlmacenConsignacionGeneral").DataBind()
If UsuarioActual.Empresa.Funcionalidad(567) = "1" Then
If e.Row.FCDropDownList("ddlAlmacen").Items.Count > 1 Then
e.Row.FCDropDownList("ddlAlmacen").SelectedIndex = 1
e.Row.FCCheckBox("cbAll").Checked = True
cbAll_CheckedChanged(e.Row.FCCheckBox("cbAll"), Nothing)
ddlAlmacen_SelectedIndexChanged(e.Row.FCDropDownList("ddlAlmacen"), Nothing)
End If
End If
End If
End Sub
Protected Sub ddlAlmacen_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
Dim Ddl As DropDownList = CType(sender, DropDownList)
For i As Integer = 0 To GvInv.Rows.Count - 1
GvInv.Rows(i).FCDropDownList("ddlEAlmacen").SelectedValue = Ddl.SelectedValue
Next
InicializaCargaEvidenciaAlmacen()
End Sub
'Protected Sub btnAgregarEq_Click(sender As Object, e As EventArgs) Handles btnAceptar.Click
' Dim eq As New ClsProductosServicios
' Dim Unidad As String = TmpDT.Rows.Item(HdnEq.Value.ToEntero)("UM").ToString
' Dim CvePS As Integer = TmpDT.Rows.Item(HdnEq.Value.ToEntero)("CvePS").ToString.ToEntero
' Dim CveUM As Integer = TmpDT.Rows.Item(HdnEq.Value.ToEntero)("CveUM").ToString.ToEntero
' Dim PU As Double = TmpDT.Rows.Item(HdnEq.Value.ToEntero)("PU").ToString.ToDouble
' Dim tCve As Integer = 0
' Dim ErrorUM As Boolean = False
' If UsuarioActual.Empresa.UsaInventarios And CveUM = 0 Then
' Dim UM As New ClsUnidadesMedida
' tCve = UM.AddUnidadMedida(TmpDT.Rows.Item(HdnEq.Value.ToEntero)("UM").ToString, TmpDT.Rows.Item(HdnEq.Value.ToEntero)("UM").ToString, "", "", "", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1)
' If tCve > 0 Then
' TmpDT.Rows.Item(HdnEq.Value.ToEntero)("CveUM") = tCve
' Else
' ErrorUM = True
' End If
' End If
' If Not ErrorUM Then
' If eq.AddPSEquivalencias(CvePS, CveUM, txtCantidadEq.Text.ToDecimal, False, PU, UsuarioActual.CveUsuario) Then
' TmpDT.Rows.Item(HdnEq.Value.ToEntero)("CveEq") = 1
' End If
' End If
' GvPS.DataSource = TmpDT
' GvPS.DataBind()
' eq.Dispose()
' txtCantidadEq.Text = ""
'End Sub
'Protected Sub Enviar_Click(sender As Object, e As ImageClickEventArgs) Handles ImgAdd.Click
' If TbCantidadAlm.Text.ToDouble < DtInv.Rows.Item(hdnIndexInv.Value.ToEntero)("Cantidad").ToString.ToDouble And TbCantidadAlm.Text.ToDouble > 0 Then
' DtInv.Rows.Item(hdnIndexInv.Value.ToEntero)("Cantidad") = DtInv.Rows.Item(hdnIndexInv.Value.ToEntero)("Cantidad").ToString.ToDouble - TbCantidadAlm.Text.ToDouble
' AddDTEnvio(TbCantidadAlm.Text.ToDouble,
' DtInv.Rows.Item(hdnIndexInv.Value.ToEntero)("UM").ToString,
' DtInv.Rows.Item(hdnIndexInv.Value.ToEntero)("CveUM").ToString.ToEntero,
' DtInv.Rows.Item(hdnIndexInv.Value.ToEntero)("CvePS").ToString().ToEntero,
' DtInv.Rows.Item(hdnIndexInv.Value.ToEntero)("PS").ToString,
' DtInv.Rows.Item(hdnIndexInv.Value.ToEntero)("PU").ToString.ToDouble,
' ddlAlmacenAdd.SelectedValue.ToEntero, DtInv.Rows.Item(hdnIndexInv.Value.ToEntero)("CveEq").ToString.ToEntero)
' Else
' Alert("El campo cantidad es necesario que sea mayor que 0 y menor al registro seleccionado.")
' End If
' TbCantidadAlm.Text = ""
' ddlAlmacenAdd.SelectedIndex = 0
' UpINV.Update()
' ' Alert(TmpDT.Rows.Count.ToString)
'End Sub
Protected Sub cbAll_CheckedChanged(sender As Object, e As EventArgs)
For i As Integer = 0 To GvInv.Rows.Count - 1
GvInv.Rows(i).FCCheckBox("cbInv").Checked = GvInv.HeaderRow.FCCheckBox("cbAll").Checked
Next
CalculaTotalPorDevengar()
End Sub
Private Sub InicializaCargaEvidenciaAlmacen()
TableAlmacenEvidencia.Visible = False
If UsuarioActual.CveEmpresa = 13 Then
If GvInv.Rows.Count > 0 AndAlso GvInv.HeaderRow().FCDropDownList("ddlAlmacen").SelectedValue.ToEntero > 0 Then
Dim DrAlmacen = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimero(String.Format("CveAlmacen = {0}", GvInv.HeaderRow().FCDropDownList("ddlAlmacen").SelectedValue.ToEntero))
If DrAlmacen("CveTipoAlmacen").ToString = "7" Then
TableAlmacenEvidencia.Visible = True
End If
End If
End If
UpAlmacenEvidencia.Update()
End Sub
#End Region
#Region "PESTAÑA INFORMACION GENERAL DE BANCO IE"
Private Sub CargaTipoTransaccion()
DdlTipoTransaccion.DataSource = GlobalDTTipoTransacciones.FiltraParametros("Tipo = 'Egs'")
DdlTipoTransaccion.DataBind()
DdlTipoTransaccion.Items.Insert(0, New ListItem("Seleccione Tipo Movimiento", "-1"))
DdlTipoTransaccionCaja.DataSource = GlobalDTTipoTransacciones.FiltraParametros("Tipo = 'Egs'")
DdlTipoTransaccionCaja.DataBind()
DdlTipoTransaccionCaja.Items.Insert(0, New ListItem("Seleccione Tipo Movimiento", "-1"))
End Sub
Private Sub CargaCuentas()
DdlCuenta.Items.Clear()
DdlCuenta.DataSource = GlobalDTBancosCuentas(UsuarioActual.CveUsuario, CveEmpresa:=UsuarioActual.CveEmpresa).FiltraParametros(String.Format("CveTipoCuenta <> 1"))
DdlCuenta.DataBind()
DdlCuenta.Items.Insert(0, New ListItem("Seleccione", "-1"))
DdlCuentaCaja.Items.Clear()
DdlCuentaCaja.DataSource = GlobalDTBancosCuentas(UsuarioActual.CveUsuario, CveEmpresa:=UsuarioActual.CveEmpresa).FiltraParametros(String.Format("CveTipoCuenta = 1"))
DdlCuentaCaja.DataBind()
DdlCuentaCaja.Items.Insert(0, New ListItem("Seleccione", "-1"))
End Sub
#End Region
#Region "FINANCIAMIENTO - AC"
'Private Sub CreaDtAC()
' DtAC = New DataTable
' DtAC.Columns.Add("IdCuenta", GetType(String))
' DtAC.Columns.Add("Cuenta", GetType(String))
' DtAC.Columns.Add("Saldo", GetType(String))
'End Sub
'Protected Sub CargaGvAc(Optional datos As DataTable = Nothing)
' If UsuarioActual.Empresa.UsaAC Then
' GvAC.DataBind()
' GvAC.DataSource = If(datos IsNot Nothing, datos, DtAC)
' GvAC.DataBind()
' Dim Total As Double = GvAC.Rows.Cast(Of GridViewRow)().Sum(Function(gvr) gvr.DataKey("PorDevengar").ToDouble)
' Lbtotalsaldo.Text = Total.ToString.FormatoNumero
' UPPM.Update()
' PnlAC.Visible = True
' End If
'End Sub
'Protected Sub CargaAC()
' Dim Cont As New ClsContPAQi(UsuarioActual.Empresa)
' If Cont.GetACSaldos(UsuarioActual.Empresa.EjercicioActual, 2) Then
' DtAC = Cont.DtResultados.Copy.FiltraParametros("PorDevengar > 0")
' Else
' Alert("Ocurrio un error al cargar los Presupuestos. Por favor vuelva a cargar la pagina")
' End If
' Cont.Dispose()
'End Sub
'Protected Sub GvAC_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GvAC.RowDataBound
' If e.Row.RowType = DataControlRowType.DataRow Then
' e.Row.FCTextBox("TxtImporte").Attributes.Add("onkeyup", String.Format("ValidaImporte(this,{0});", e.Row.DBCampo("PorDevengar")))
' End If
'End Sub
#End Region
#Region "TAB - PERSONAL"
Private Sub CargaGvPersonal()
GvPersonal.DataSource = TmpDT
GvPersonal.DataBind()
UpGvPersonal.Update()
End Sub
Protected Sub DdlProyectoPersonal_SelectedIndexChanged(sender As Object, e As EventArgs)
Dim gvRow As GridViewRow = DirectCast((DirectCast(sender, DropDownList)).NamingContainer, GridViewRow)
Dim CveProyecto = If(gvRow.FCDropDownList("DdlProyectoPersonal").SelectedValue.ToEntero > 0, gvRow.FCDropDownList("DdlProyectoPersonal").SelectedValue.ToEntero, -1)
gvRow.FCDropDownList("DdlSubProyectoPersonal").Items.Clear()
If CveProyecto > 0 Or UsuarioActual.Empresa.Tipo_CentroCosto.Contiene(1, 2) Then
gvRow.FCDropDownList("DdlSubProyectoPersonal").DataSource = If(UsuarioActual.Empresa.Funcionalidad(102) = "1" AndAlso Not UsuarioActual.TienePermisoProceso(110), GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, CveProyecto, UsuarioActual.CveEmpresa, -1, 1), GlobalDTSubProyectos(CveProyecto, -1, UsuarioActual.CveEmpresa, 1))
End If
gvRow.FCDropDownList("DdlSubProyectoPersonal").DataBind()
gvRow.FCDropDownList("DdlSubProyectoPersonal").Items.Insert(0, New ListItem("Seleccione", "-1"))
End Sub
Protected Sub DdlSubProyectoPersonal_SelectedIndexChanged(sender As Object, e As EventArgs)
Dim gvRow As GridViewRow = DirectCast((DirectCast(sender, DropDownList)).NamingContainer, GridViewRow)
Dim CveProyecto = If(gvRow.FCDropDownList("DdlProyectoPersonal").SelectedValue.ToEntero > 0, gvRow.FCDropDownList("DdlProyectoPersonal").SelectedValue.ToEntero, -1)
Dim CveSubProyecto = If(gvRow.FCDropDownList("DdlSubProyectoPersonal").SelectedValue.ToEntero > 0, gvRow.FCDropDownList("DdlSubProyectoPersonal").SelectedValue.ToEntero, -1)
Dim dr1 As DataRow = TmpDT.Rows(gvRow.RowIndex)
dr1("CveProyecto") = CveProyecto
dr1("CveSubProyecto") = CveSubProyecto
dr1("Proyecto") = If(CveProyecto > 0, gvRow.FCDropDownList("DdlProyectoPersonal").SelectedItem.Text, "")
dr1("SubProyecto") = If(CveSubProyecto > 0, gvRow.FCDropDownList("DdlSubProyectoPersonal").SelectedItem.Text, "")
TmpDT.AcceptChanges()
GvPS.DataSource = TmpDT
GvPS.DataBind()
UpPS.Update()
End Sub
Private Sub DdlPersonalHeader_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlPersonalHeader.SelectedIndexChanged
For Each Gvr As GridViewRow In GvPersonal.Rows
Gvr.FCDropDownList("DdlPersonalGv").SelectedValue = DdlPersonalHeader.SelectedValue
Next
UpGvPersonal.Update()
End Sub
Private Sub CargaDdlPersonal()
'DdlPersonalGv.DataSource = GlobalDTRHPersonal(UsuarioActual.CveEmpresa)
'DdlPersonalGv.DataBind()
DdlPersonalHeader.DataSource = GlobalDTRHPersonal(UsuarioActual.CveEmpresa)
DdlPersonalHeader.DataBind()
UpGvPersonal.Update()
End Sub
Private Sub GvPersonal_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvPersonal.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
e.Row.FCDropDownList("DdlPersonalGv").DataSource = GlobalDTRHPersonal(UsuarioActual.CveEmpresa)
e.Row.FCDropDownList("DdlPersonalGv").DataBind()
If UsuarioActual.Empresa.Tipo_CentroCosto = 1 Or UsuarioActual.Empresa.Tipo_CentroCosto = 2 Then
e.Row.FCDropDownList("DdlSubProyectoPersonal").DataSource = If(UsuarioActual.Empresa.Funcionalidad(102) = "1" AndAlso Not UsuarioActual.TienePermisoProceso(110), GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, 1), GlobalDTSubProyectos(-1, -1, UsuarioActual.CveEmpresa, 1))
e.Row.FCDropDownList("DdlSubProyectoPersonal").Items.Insert(0, New ListItem("Seleccione", "-1"))
e.Row.FCDropDownList("DdlSubProyectoPersonal").DataBind()
e.Row.FCDropDownList("DdlProyectoPersonal").Visible = False
Else
e.Row.FCDropDownList("DdlProyectoPersonal").DataSource = If(UsuarioActual.Empresa.Funcionalidad(102) = "1" AndAlso Not UsuarioActual.TienePermisoProceso(110), GlobalDTProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1).FiltraParametros("", "", {"CveProyecto", "Proyecto"}), GlobalDTProyectos(UsuarioActual.CveEmpresa, -1).FiltraParametros("", "", {"CveProyecto", "Proyecto"}))
e.Row.FCDropDownList("DdlProyectoPersonal").Items.Insert(0, New ListItem("Seleccione", "-1"))
e.Row.FCDropDownList("DdlProyectoPersonal").DataBind()
e.Row.FCDropDownList("DdlProyectoPersonal").SelectedValueExist(e.Row.DBCampo("CveProyecto"))
If e.Row.DBCampo("CveProyecto").ToEntero > 0 Then
e.Row.FCDropDownList("DdlSubProyectoPersonal").DataSource =
If(UsuarioActual.Empresa.Funcionalidad(102) = "1" AndAlso Not UsuarioActual.TienePermisoProceso(110),
GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, e.Row.DBCampo("CveProyecto").ToEntero, UsuarioActual.CveEmpresa, -1, 1),
GlobalDTSubProyectos(e.Row.DBCampo("CveProyecto").ToEntero, -1, UsuarioActual.CveEmpresa, 1))
End If
e.Row.FCDropDownList("DdlSubProyectoPersonal").Items.Insert(0, New ListItem("Seleccione", "-1"))
e.Row.FCDropDownList("DdlSubProyectoPersonal").DataBind()
End If
e.Row.FCDropDownList("DdlSubProyectoPersonal").SelectedValueExist(e.Row.DBCampo("CveSubProyecto"))
If CveCompra > 0 Then
If e.Row.DBCampo("CvePersonal").ToEntero <> -1 And e.Row.DBCampo("CvePersonal") <> Nothing Then
e.Row.FCDropDownList("DdlPersonalGv").SelectedValue = e.Row.DBCampo("CvePersonal")
End If
If e.Row.DBCampo("Referencia").ToString <> "" And e.Row.DBCampo("Referencia") <> Nothing Then
e.Row.FCTextBox("TxtReferencia").Text = e.Row.DBCampo("Referencia")
End If
e.Row.FCTextBox("TxtDividir").Enabled = False
End If
e.Row.FCLinkButton("BtnDividirPersonal").Attributes.Add("onclick", String.Format("DividirPersonal('{0}');", e.Row.FCTextBox("TxtDividir").ClientID))
e.Row.FCLinkButton("BtnDividirPersonal").CommandArgument = e.Row.RowIndex.ToString
e.Row.FCTextBox("TxtDividir").Attributes.Add("onkeyup", String.Format("LimitaCantidad({0},this,'{1}');", e.Row.DBCampo("Cantidad"), e.Row.FCLinkButton("BtnDividirPersonal").ClientID))
End If
End Sub
Protected Sub DividirPersonal(sender As Object, e As EventArgs)
Dim index2 As Integer = 0
For Each Row As DataRow In TmpDT.Rows
If GvPersonal.Rows(index2).FCTextBox("TxtReferencia").Text <> "" Then
Row("Referencia") = GvPersonal.Rows(index2).FCTextBox("TxtReferencia").Text
End If
If GvPersonal.Rows(index2).FCDropDownList("DdlPersonalGv").SelectedValue <> "-1" Then
Row("CvePersonal") = GvPersonal.Rows(index2).FCDropDownList("DdlPersonalGv").SelectedValue
End If
index2 += 1
Next
'index2 = 0
'For Each Row As DataRow In TmpDT.Rows
' If GvAFCompras.Rows(index2).FCHiddenField("HdnCveAF").Value.ToEntero > 0 Then
' Row("CveActivoFijo") = GvAFCompras.Rows(index2).FCHiddenField("HdnCveAF").Value.ToEntero
' Row("CodAF") = GvAFCompras.Rows(index2).FCHiddenField("HdnCodAF").Value.ToString
' Row("TipoAF") = 1
' End If
' index2 += 1
'Next
'Dim Index As Integer = CType(sender, LinkButton).CommandArgument.ToString.ToEntero
Dim gvRow As GridViewRow = DirectCast((DirectCast(sender, LinkButton)).NamingContainer, GridViewRow)
Dim Index As Integer = gvRow.RowIndex
Dim Cantidad As String = HdnCantidadPersonal.Value
Dim dr1 As DataRow = TmpDT.Rows(Index)
Dim dr As DataRow = TmpDT.NewRow
dr.ItemArray = dr1.ItemArray
dr1("Cantidad") = (dr1("Cantidad").ToString.ToDouble - Cantidad.ToDouble)
dr1("Total") = dr1("PU").ToString.ToDouble * dr1("Cantidad").ToString.ToDouble
dr1("IVA") = Math.Round(dr1("IVAPorcentaje").ToString.ToDouble * dr1("Total").ToString.ToDouble, 6)
TmpDT.AcceptChanges()
dr("CvePersonal") = 0
dr("Referencia") = ""
dr("CveActivoFijo") = 0
dr("CodAF") = 0
dr("Cantidad") = Cantidad.ToDouble
dr("Total") = dr("PU").ToString.ToDouble * Cantidad.ToDouble
dr("IVA") = Math.Round(dr("IVAPorcentaje").ToString.ToDouble * dr("Total").ToString.ToDouble, 6)
TmpDT.Rows.InsertAt(dr, Index)
TmpDT.AcceptChanges()
index2 = 0
For Each Row As DataRow In TmpDT.Rows
Row("Consec") = index2
index2 += 1
Next
TmpDT.AcceptChanges()
CargaGvPersonal()
'TmpDT = DtAFInsumos.Copy
GvPS.DataSource = TmpDT
GvPS.DataBind()
UpPS.Update()
'Afecta GVINV y GvAF
CargaGvInv()
CargaGVsAF()
CalculaTotales(True)
index2 = 0
For Each Row As DataRow In TmpDT.Rows
If Row("Referencia").ToString <> "" Then
GvPersonal.Rows(index2).FCTextBox("TxtReferencia").Text = Row("Referencia").ToString
End If
If Row("CvePersonal").ToString <> "" Then
GvPersonal.Rows(index2).FCDropDownList("DdlPersonalGv").SelectedValue = Row("CvePersonal").ToString
End If
index2 += 1
Next
End Sub
#End Region
#Region "TAB - ACTIVOS FIJOS -AF"
Protected Sub CargarGvActivosFijos(sender As Object, e As EventArgs)
Tab.ActiveTabIndex = 3
If GvAFInsumos.Rows.Count > 0 Then
llenaDtsAF()
End If
CargaGVsAF()
End Sub
Protected Sub llenaDtsAF()
Dim index As Integer = 0
For Each Row As DataRow In TmpDT.Rows
If Row("TipoAF").ToString.ToEntero = 1 AndAlso GvAFInsumos.Rows(index).FCHiddenField("HdnCveAF").Value.ToEntero > 0 Then
Row("CveActivoFijo") = GvAFInsumos.Rows(index).FCHiddenField("HdnCveAF").Value.ToEntero
Row("CodAF") = If(GvAFInsumos.Rows(index).FCHiddenField("HdnCodAF").Value.ToString = "", "SN", GvAFInsumos.Rows(index).FCHiddenField("HdnCodAF").Value.ToString)
'Row("TipoAF") = 1
End If
index += 1
Next
index = 0
For Each Row As DataRow In TmpDT.Rows
If Row("TipoAF").ToString.ToEntero = 2 AndAlso GvAFCompras.Rows(index).FCHiddenField("HdnCveAF").Value.ToEntero > 0 Then
Row("CveActivoFijo") = GvAFCompras.Rows(index).FCHiddenField("HdnCveAF").Value.ToEntero
Row("CodAF") = If(GvAFCompras.Rows(index).FCHiddenField("HdnCodAF").Value.ToString = "", "SN", GvAFCompras.Rows(index).FCHiddenField("HdnCodAF").Value.ToString)
'Row("TipoAF") = 2
End If
index += 1
Next
End Sub
Private Sub CargaGVsAF()
GvAFInsumos.DataSource = TmpDT
GvAFInsumos.DataBind()
UPDatosAFInsumos.Update()
GvAFCompras.DataSource = TmpDT
GvAFCompras.DataBind()
UPDatosAFCompras.Update()
End Sub
Protected Sub GvAFCompras_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GvAFCompras.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim SinValor = True
If e.Row.DBCampo("TipoAF").ToEntero = 2 Then
If e.Row.DBCampo("CveActivoFijo").ToEntero > 0 Then
e.Row.FCTextBox("LblCodigo").Text = e.Row.DBCampo("CodAF").ToString
e.Row.FCHiddenField("HdnCveAF").Value = e.Row.DBCampo("CveActivoFijo").ToString
e.Row.FCHiddenField("HdnCodAF").Value = e.Row.DBCampo("CodAF").ToString
SinValor = False
End If
End If
If SinValor Then
e.Row.FCTextBox("LblCodigo").Text = ""
e.Row.FCHiddenField("HdnCveAF").Value = "0"
e.Row.FCHiddenField("HdnCodAF").Value = "0"
End If
'e.Row.FCButton("BtnDividirInsumo").Attributes.Add("onclick", String.Format("DividirInsumo('{0}');", e.Row.FCTextBox("TxtDividir").ClientID))
'e.Row.FCButton("BtnDividirInsumo").CommandArgument = e.Row.RowIndex.ToString
e.Row.FCHiddenField("HdnIndex").Value = e.Row.RowIndex.ToString
e.Row.FCHyperLink("HLBuscarAF").Attributes.Add("onclick", String.Format("LimpiaAF(2, '{0}');", e.Row.FCHiddenField("HdnCveConcepto").Value))
e.Row.FCHyperLink("HLBuscarAF").NavigateUrl = String.Format("javascript:AbrirVentana('/AF/PopUpBuscarAF.aspx?L={0}&H1={1}&H2={2}',730,450,'N');", e.Row.FCTextBox("LblCodigo").ClientID, e.Row.FCHiddenField("HdnCveAF").ClientID, e.Row.FCHiddenField("HdnCodAF").ClientID)
'e.Row.FCTextBox("TxtDividir").Attributes.Add("onkeyup", String.Format("LimitaCantidad({0},this,'{1}');", e.Row.DBCampo("Cantidad"), e.Row.FCButton("BtnDividirInsumo").ClientID))
e.Row.FCTextBox("LblCodigo").Attributes.Add("onkeyup", String.Format("LimpiaAF(2, '{0}'); EnterAFEdit(event,this,{1},{2},{3});", e.Row.FCHiddenField("HdnCveConcepto").Value, e.Row.FCHiddenField("HdnCveAF").ClientID, e.Row.FCHiddenField("HdnCodAF").ClientID, e.Row.RowIndex.ToString))
e.Row.FCTextBox("LblCodigo").Attributes.Add("onblur", String.Format("LimpiaAF(2, '{0}'); AFBlurEdit(this,{1},{2},{3});", e.Row.FCHiddenField("HdnCveConcepto").Value, e.Row.FCHiddenField("HdnCveAF").ClientID, e.Row.FCHiddenField("HdnCodAF").ClientID, e.Row.RowIndex.ToString))
End If
End Sub
Protected Sub GvAFInsumos_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GvAFInsumos.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim SinValor = True
If e.Row.DBCampo("TipoAF").ToEntero = 1 Then
If e.Row.DBCampo("CveActivoFijo").ToEntero > 0 Then
e.Row.FCTextBox("LblCodigo").Text = e.Row.DBCampo("CodAF").ToString
e.Row.FCLabel("LblValido").Attributes("display") = ""
e.Row.FCHiddenField("HdnCveAF").Value = e.Row.DBCampo("CveActivoFijo").ToString
e.Row.FCHiddenField("HdnCodAF").Value = e.Row.DBCampo("CodAF").ToString
SinValor = False
End If
End If
If SinValor Then
e.Row.FCTextBox("LblCodigo").Text = ""
e.Row.FCHiddenField("HdnCveAF").Value = "0"
e.Row.FCHiddenField("HdnCodAF").Value = "0"
e.Row.FCLabel("LblValido").Attributes("display") = "none"
End If
If e.Row.DBCampo("AFTipoMantenimiento").ToEntero > 0 Then
e.Row.FCDropDownList("DdlTipoMantemiento").SelectedValueExist(e.Row.DBCampo("AFTipoMantenimiento"))
End If
e.Row.FCButton("BtnDividirInsumo").Attributes.Add("onclick", String.Format("DividirInsumo('{0}');", e.Row.FCTextBox("TxtDividir").ClientID))
e.Row.FCButton("BtnDividirInsumo").CommandArgument = e.Row.RowIndex.ToString
e.Row.FCHiddenField("HdnIndex").Value = e.Row.RowIndex.ToString
e.Row.FCHyperLink("HLBuscarAF").Attributes.Add("onclick", String.Format("LimpiaAF(1, '{0}');", e.Row.FCHiddenField("HdnCveConcepto").Value))
e.Row.FCHyperLink("HLBuscarAF").NavigateUrl = String.Format("javascript:AbrirVentana('/AF/PopUpBuscarAF.aspx?L={0}&H1={1}&H2={2}',730,450,'N');", e.Row.FCTextBox("LblCodigo").ClientID, e.Row.FCHiddenField("HdnCveAF").ClientID, e.Row.FCHiddenField("HdnCodAF").ClientID)
e.Row.FCTextBox("TxtDividir").Attributes.Add("onkeyup", String.Format("LimitaCantidad({0},this,'{1}');", e.Row.DBCampo("Cantidad"), e.Row.FCButton("BtnDividirInsumo").ClientID))
e.Row.FCTextBox("LblCodigo").Attributes.Add("onkeyup", String.Format("LimpiaAF(1, '{0}'); EnterAFEdit(event,this,{1},{2},{3});", e.Row.FCHiddenField("HdnCveConcepto").Value, e.Row.FCHiddenField("HdnCveAF").ClientID, e.Row.FCHiddenField("HdnCodAF").ClientID, e.Row.RowIndex.ToString))
e.Row.FCTextBox("LblCodigo").Attributes.Add("onblur", String.Format("LimpiaAF(1, '{0}'); AFBlurEdit(this,{1},{2},{3});", e.Row.FCHiddenField("HdnCveConcepto").Value, e.Row.FCHiddenField("HdnCveAF").ClientID, e.Row.FCHiddenField("HdnCodAF").ClientID, e.Row.RowIndex.ToString))
e.Row.FCTextBox("TxtAFMedida").Attributes.Add("onblur", String.Format("AFInsumosMedida(this,{0});", e.Row.RowIndex))
End If
End Sub
Protected Sub BtnLimpiaAF_Click(sender As Object, e As EventArgs)
LimpiaAF(HdnTipoAF.Value.ToEntero, HdnCveConceptoAF.Value)
End Sub
Protected Sub LimpiaAF(TipoCompra As Integer, CveConcepto As String)
llenaDtsAF()
For Each Row As DataRow In TmpDT.Rows
If Row("CveConcepto").ToString = CveConcepto Then
Row("TipoAF") = TipoCompra
End If
Next
TmpDT.AcceptChanges()
llenaDtsAF()
CargaGVsAF()
For Each Row As DataRow In TmpDT.Rows
If Row("CveActivoFijo").ToString.ToEntero = 0 Then
Row("TipoAF") = DBNull.Value
End If
Next
TmpDT.AcceptChanges()
End Sub
Protected Sub DivirInsumo(sender As Object, e As EventArgs)
Dim index2 As Integer = 0
If Not TmpDT.Columns.Contains("Importe") Then
TmpDT.Columns.Add("Importe", GetType(Decimal))
End If
'LLena el AF vinculado para no perderlo
For Each Row As DataRow In TmpDT.Rows
If GvAFInsumos.Rows(index2).FCHiddenField("HdnCveAF").Value.ToEntero > 0 Then
Row("CveActivoFijo") = GvAFInsumos.Rows(index2).FCHiddenField("HdnCveAF").Value.ToEntero
Row("CodAF") = GvAFInsumos.Rows(index2).FCHiddenField("HdnCodAF").Value.ToString
Row("TipoAF") = 1
End If
index2 += 1
Next
index2 = 0
For Each Row As DataRow In TmpDT.Rows
If GvAFCompras.Rows(index2).FCHiddenField("HdnCveAF").Value.ToEntero > 0 Then
Row("CveActivoFijo") = GvAFCompras.Rows(index2).FCHiddenField("HdnCveAF").Value.ToEntero
Row("CodAF") = GvAFCompras.Rows(index2).FCHiddenField("HdnCodAF").Value.ToString
Row("TipoAF") = 1
End If
index2 += 1
Next
Dim Index As Integer = CType(sender, Button).CommandArgument.ToString.ToEntero
Dim Cantidad As String = HdnCantidadInsumo.Value
Dim dr1 As DataRow = TmpDT.Rows(Index)
Dim dr As DataRow = TmpDT.NewRow
dr.ItemArray = dr1.ItemArray
dr1("Cantidad") = (dr1("Cantidad").ToString.ToDouble - Cantidad.ToDouble)
dr1("Total") = dr1("PU").ToString.ToDouble * dr1("Cantidad").ToString.ToDecimal
dr1("IVA") = Math.Round(dr1("IVAPorcentaje").ToString.ToDecimal * dr1("Total").ToString.ToDecimal, 6)
dr1("IEPSPS") = Math.Round(dr1("IEPSPSPorcentaje").ToString.ToDecimal * dr1("Total").ToString.ToDecimal, 6)
TmpDT.AcceptChanges()
dr("CveCompraDetalle") = -1
dr("CveActivoFijo") = 0
dr("CodAF") = ""
dr("Cantidad") = Cantidad.ToDecimal
dr("Total") = dr("PU").ToString.ToDecimal * Cantidad.ToDecimal
'dr("Importe") = dr("Total")
dr("IVA") = Math.Round(dr("IVAPorcentaje").ToString.ToDecimal * dr("Total").ToString.ToDecimal, 6)
dr("IEPSPS") = Math.Round(dr("IEPSPSPorcentaje").ToString.ToDecimal * dr("Total").ToString.ToDecimal, 6)
TmpDT.Rows.InsertAt(dr, Index + 1)
For Index = 0 To TmpDT.Rows.Count - 1
TmpDT.Rows(Index)("Consec") = Index + 1
Next
CargaGVsAF()
'TmpDT = DtAFInsumos.Copy
GvPS.DataSource = TmpDT
GvPS.DataBind()
UpPS.Update()
'Afecta GVINV
CargaGvInv()
CargaGvPersonal()
End Sub
Protected Sub BtnVinculaAFEdit_Click(sender As Object, e As EventArgs)
Dim ObjAF As New ClsAF
Dim Index As Integer = HdnIndexTmpDT.Value.ToEntero()
If ObjAF.GetActivosFijos(-1, UsuarioActual.CveEmpresa, HdnCodAFEdit.Value, "-1", -1, -1, "-1", -1, -1, -1, -1, -1, "", -1, UsuarioActual.CveEmpresa) Then
If ObjAF.DtResultados.Rows.Count = 1 Then
'VERIFICAR QUE EL ACTIVO FIJO ESTE ACTIVO. que no este en baja, inactivo.
If HdnTipoAF.Value.ToEntero = 1 Then
GvAFInsumos.Rows(Index).FCHiddenField("HdnCveAF").Value = ObjAF.DtResultados.Rows(0)("CveActivoFijo").ToString
GvAFInsumos.Rows(Index).FCHiddenField("HdnCodAF").Value = ObjAF.DtResultados.Rows(0)("Codigo").ToString
RegistraScript(String.Format("MuestraCheckAF('{0}','');", GvAFInsumos.Rows(Index).FCLabel("LblValido").ClientID), "A2")
Try
TmpDT.Rows(Index)("CveActivoFijo") = ObjAF.DtResultados.Rows(0)("CveActivoFijo").ToString
TmpDT.AcceptChanges()
Catch ex As Exception
End Try
ElseIf HdnTipoAF.Value.ToEntero = 2 Then
GvAFCompras.Rows(Index).FCHiddenField("HdnCveAF").Value = ObjAF.DtResultados.Rows(0)("CveActivoFijo").ToString
GvAFCompras.Rows(Index).FCHiddenField("HdnCodAF").Value = ObjAF.DtResultados.Rows(0)("Codigo").ToString
RegistraScript(String.Format("MuestraCheckAF('{0}','');", GvAFCompras.Rows(Index).FCLabel("LblValido").ClientID), "A2")
Try
TmpDT.Rows(Index)("CveActivoFijo") = ObjAF.DtResultados.Rows(0)("CveActivoFijo").ToString
TmpDT.AcceptChanges()
Catch ex As Exception
End Try
End If
'COMENTADO IPP 15 JUNIO 2017
'RegistraScript(String.Format("EnterAFEditOK('{0}','{1}');", ObjAF.DtResultados.Rows(0)("CveActivoFijo").ToString, ObjAF.DtResultados.Rows(0)("Codigo").ToString))
LimpiaAF(HdnTipoAF.Value.ToEntero, HdnCveConceptoAF.Value)
Else
If HdnTipoAF.Value.ToEntero = 1 Then
GvAFInsumos.Rows(Index).FCHiddenField("HdnCveAF").Value = "-1"
GvAFInsumos.Rows(Index).FCHiddenField("HdnCodAF").Value = "-1"
RegistraScript(String.Format("MuestraCheckAF('{0}','none');", GvAFInsumos.Rows(Index).FCLabel("LblValido").ClientID), "A2")
Try
TmpDT.Rows(Index)("CveActivoFijo") = Nothing
TmpDT.AcceptChanges()
Catch ex As Exception
End Try
ElseIf HdnTipoAF.Value.ToEntero = 2 Then
GvAFCompras.Rows(Index).FCHiddenField("HdnCveAF").Value = "-1"
GvAFCompras.Rows(Index).FCHiddenField("HdnCodAF").Value = "-1"
RegistraScript(String.Format("MuestraCheckAF('{0}','none');", GvAFCompras.Rows(Index).FCLabel("LblValido").ClientID), "A2")
Try
TmpDT.Rows(Index)("CveActivoFijo") = Nothing
TmpDT.AcceptChanges()
Catch ex As Exception
End Try
End If
Alert("No se encontró un Activo Fijo con el código proporcionado.", TipoMensaje.MsgAdvertencia)
End If
End If
ObjAF.Dispose()
End Sub
Protected Sub DdlTipoMantemiento_SelectedIndexChanged(sender As Object, e As EventArgs)
Dim dr = TmpDT.Rows(CType(CType(sender, DropDownList).NamingContainer, GridViewRow).RowIndex)
dr("AFTipoMantenimiento") = CType(CType(sender, DropDownList).NamingContainer, GridViewRow).FCDropDownList("DdlTipoMantemiento").SelectedValue.ToEntero
End Sub
Protected Sub BtnAFMedida_Click(sender As Object, e As EventArgs)
TmpDT(HdnIndexTmpDT.Value.ToEntero)("AFMedida") = HdnTxtAFMedida.Value
End Sub
#End Region
#Region "TAB ALMACEN - INVENTARIOS ISRAEL PIÑA - 5 FEBRERO 2015"
Protected Sub CalculaTotalPorDevengar()
Dim total = TxtTotal.Text.ToDouble
For Each Gvr As GridViewRow In GvInv.Rows
If Gvr.FCCheckBox("cbInv").Checked = True And Gvr.FCDropDownList("DdlRecibirInv").SelectedValue = "1" Then
total -= Math.Round(Gvr.FCTextBox("TbCantidad").Text.ToDouble * Gvr.DataKey("PU").ToDouble, 4)
End If
Next
'LbTotalPorDevengar.Text = total.ToString.FormatoNumero
'UPPM.Update()
End Sub
Protected Sub CambiaTotalDevengar(sender As Object, e As EventArgs)
CalculaTotalPorDevengar()
End Sub
#End Region
#Region " AJUSTA IMPORTES "
Private Sub AjustaImporteUltimoConcepto(ImporteAjuste As Decimal, Optional EsCarga As Boolean = False)
If ImporteAjuste = 0 Then Exit Sub
Dim Amortizacion As Decimal = 0
If ListaDocumentos IsNot Nothing AndAlso ListaDocumentos.Count > 0 AndAlso ArrAnticipos IsNot Nothing AndAlso ArrAnticipos.Count > 0 Then
Amortizacion = LblAmortizacion.Text.ToDecimal
End If
If TmpDT.Rows.Count > 0 Then ' si hay movimientos y si esta afectando al total, que se haga el ajuste
Dim Indice As Integer = If(TmpDT.Rows(TmpDT.Rows.Count - 1)("CvePS").ToString = UsuarioActual.Empresa.Funcionalidad(112).ToString, TmpDT.Rows.Count - 2, TmpDT.Rows.Count - 1)
Dim tPU As Decimal
If TmpDT.Rows(Indice)("Cantidad").ToString.ToDecimal > 0 Then
tPU = ImporteAjuste / TmpDT.Rows(Indice)("Cantidad").ToString.ToDecimal
Else
tPU = 0
End If
If TmpDT.Rows(Indice)("PU").ToString.ToDecimal + tPU < 0 Then 'si es negativo, que tome el dato anterior
Indice = Indice - 1
If TmpDT.Rows(Indice)("Cantidad").ToString.ToDecimal > 0 Then
tPU = ImporteAjuste / TmpDT.Rows(Indice)("Cantidad").ToString.ToDecimal
Else
tPU = 0
End If
End If
TmpDT.Rows(Indice)("PU") = TmpDT.Rows(Indice)("PU").ToString.ToDecimal + tPU
TmpDT.Rows(Indice)("Total") = TmpDT.Rows(Indice)("Total").ToString.ToDecimal + ImporteAjuste
TmpDT.Rows(Indice)("IEPSPS") = (TmpDT.Rows(Indice)("Total").ToString.ToDecimal() * TmpDT.Rows(Indice)("IEPSPSPorcentaje").ToString.ToDecimal()).RoundAD(2)
'TmpDT.Rows(Indice)("IVA") = TmpDT.Rows(Indice)("PU").ToString.ToDecimal * TmpDT.Rows(Indice)("Cantidad").ToString.ToDecimal * TmpDT.Rows(Indice)("IVAPorcentaje").ToString.ToDecimal
TmpDT.Rows(Indice)("IVA") = (TmpDT.Rows(Indice)("PU").ToString.ToDecimal * TmpDT.Rows(Indice)("Cantidad").ToString.ToDecimal - TmpDT.Rows(Indice)("Descuento").ToString.ToDecimal) * TmpDT.Rows(Indice)("IVAPorcentaje").ToString.ToDecimal
'Row("IEPSPS") = Math.Round(IEPSPS, DecimalesPermitidos)
'Row("IEPSPSPorcentaje") = PorcentajeIEPS
TmpDT.AcceptChanges()
End If
SubTotal = TmpDT.SUMD("Total")
If Not EsCarga Then
Descuentos = TmpDT.SUMD("Descuento")
End If
TxtSubTotal.Text = (SubTotal + Descuentos).FormatoNumero()
TxtSubTotal2.Text = (SubTotal - Amortizacion).FormatoNumero
TxtDescuento.Text = Descuentos.FormatoNumero()
SubTotalConceptos = SubTotal
GvPS.DataSource = TmpDT : GvPS.DataBind()
End Sub
Protected Sub ImgAjustePorcentaje_Click(sender As Object, e As ImageClickEventArgs) Handles ImgAjustePorcentaje.Click
'realizo el ajuste de los productos
AjustaConceptos()
For Each Row As GridViewRow In GvPS.Rows
If UsuarioActual.TienePermisoProceso(143) Then
Row.FCLinkButton("ImgE").Visible = True
Row.FCLinkButton("ImgD").Visible = True
End If
Next
End Sub
Private Sub AjustaConceptos(Optional AjusteForzoso As Boolean = False)
'SE COMENTO POR PORCENTAJE DE DESCUENTO 0.00 - IPP 3 ENERO 2017
'If TxtAjustePorcentaje.Text.ToDecimal <> 0 Or AjusteForzoso Then
'End If
If TxtAjustePorcentaje.Text.ToDecimal <> 0 Then
For Each Dr As DataRow In TmpDT.Rows
'Dr("PU") = Dr("PU").ToString.ToDecimal * ((100 - TxtAjustePorcentaje.Text.ToDecimal) / 100)
Dim TotalAnterior = Dr("Total").ToString.ToDecimal
Dr("Total") = Dr("Total").ToString.ToDecimal * ((100 - TxtAjustePorcentaje.Text.ToDecimal) / 100)
Dr("Descuento") = TotalAnterior - Dr("Total").ToString.ToDecimal
Next
'TxtDescuento.Text = Descuentos.ToString
End If
'verifico las sumas
If TxtSubTotal2.Text.ToDecimal <> TmpDT.SUM("Total") Then
Dim i As Integer = TmpDT.Rows.Count - 1
'verifico si el ultimo dato, es diferente de cero, sino tomo el anterior
If TmpDT.Rows(i)("Total").ToString.ToDecimal <= 0 AndAlso i - 1 >= 0 Then i = i - 1
'sino se hizo el ajuste, lo aplico al ultimo registro la diferencia
'para ajustar el PU, de la diferencia la divido entre la cantidad
TmpDT.Rows(i)("PU") = TmpDT.Rows(i)("PU").ToString.ToDecimal + ((TxtSubTotal2.Text.ToDecimal - TmpDT.SUM("Total")) / TmpDT.Rows(i)("Cantidad").ToString.ToDecimal)
TmpDT.Rows(i)("Total") = TmpDT.Rows(i)("Total").ToString.ToDecimal + TxtSubTotal2.Text.ToDecimal - TmpDT.SUM("Total")
End If
TxtSubTotal.Text = (TmpDT.SUM("Total") + TmpDT.SUM("Descuento")).FormatoNumero
TxtSubTotal2.Text = TmpDT.SUM("Total").FormatoNumero
SubTotalOriginal = TmpDT.SUM("Total") + TmpDT.SUM("Descuento")
SubTotal2Original = TmpDT.SUM("Total")
BtnGuardar.Enabled = True
UpFacturar.Update()
PnlAjusteProductos.Visible = False
'habilito la busqueda de oc
ImgBtnBuscarOC.Visible = True
TxtOC.Enabled = True
UpParametros.Update()
GvPS.DataSource = TmpDT
GvPS.DataBind()
UpPS.Update()
End Sub
#End Region
#Region "DDL'S"
Protected Sub DdlCredito_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlCredito.SelectedIndexChanged
CargaCreditosDetalle(DdlCredito.SelectedValue.ToEntero)
CargaCreditosDisponibles()
End Sub
Protected Sub DdlDeudor_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlDeudor.SelectedIndexChanged
TxtContadoDeudor.Text = "0"
If DdlDeudor.SelectedValue.ToEntero > 0 Then
Dim Deudores As New ClsMovimientos
If RBLTipoDeudor.SelectedValue.ToEntero = 1 Then
If Deudores.GetDeudoresSaldosDetalle(DdlDeudor.SelectedValue.ToEntero, DdlMoneda.SelectedValue.ToEntero, UsuarioActual.CveEmpresa) Then
DtDeudoresDetalle = Deudores.DtResultados.FiltraParametros("CveProveedor > 0 AND Saldo > 0")
GvDeudores.DataSource = DtDeudoresDetalle
GvDeudores.DataBind()
End If
Else
If Deudores.GetDeudoresComisionesSaldosDetalle(DdlDeudor.SelectedValue.ToEntero, UsuarioActual.CveEmpresa) Then
DtDeudoresDetalle = Deudores.DtResultados.FiltraParametros("CveProveedor > 0 AND Saldo > 0")
GvDeudores.DataSource = DtDeudoresDetalle
GvDeudores.DataBind()
End If
End If
If CompraSaldo < TxtTotal.Text.ToDouble Then
RVContadoDeudor.MaximumValue = CompraSaldo.ToString
Else
RVContadoDeudor.MaximumValue = TxtTotal.Text
End If
UPDeudores.Update()
Deudores.Dispose()
TxtContadoDeudor.Attributes.Add("readonly", "readonly")
End If
End Sub
Protected Sub DdlAcreedor_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlAcreedor.SelectedIndexChanged
If DdlAcreedor.SelectedValue.ToEntero > 0 Then
Dim dr As DataRow
dr = DtAcreedores.FiltroPrimero(String.Format("CveProveedor = {0}", DdlAcreedor.SelectedValue))
If dr IsNot Nothing Then
Dim tSaldo As Decimal = dr("Saldo").ToString.ToDecimal
RVContadoAcreedor.MaximumValue = tSaldo.ToString
'si el saldo es mayor de la compra poner el valor de la compra sino el valor del saldo
TxtContadoAcreedor.Text = If(tSaldo > TxtTotal.Text.ToDecimal, TxtTotal.Text, tSaldo.ToString).FormatoNumero
LblDetalle.Visible = True
DdlAcreedorDetalle.Visible = True
Dim ObjMov As New ClsMovimientos
Dim ObjProveedor As New ClsCompProveedores()
If ObjMov.GetAcreedoresSaldosDetalles(-1, CveMoneda, UsuarioActual.CveEmpresa) Then
DdlAcreedorDetalle.DataSource = ObjMov.DtResultados.FiltraParametros(String.Format("CveProveedor = {0}", DdlAcreedor.SelectedValue))
DdlAcreedorDetalle.DataBind()
DdlAcreedorDetalle.Items.Insert(0, New ListItem("Seleccione Acreedor", "-1"))
UpContado.Update()
End If
If ObjProveedor.GetProveedores(ClsCompProveedores.TipoConsulta.ParaUsoEnEmpresa, DdlAcreedor.SelectedValue.ToEntero, "-1", "-1", "-1", "-1", "-1", "-1", "-1", 1, UsuarioActual.CveEmpresa) Then
ViewState("CtaProveedorAcreedores") = ObjProveedor.IdCtaContAcreedor
End If
ObjProveedor.Dispose()
ObjMov.Dispose()
End If
Else
TxtContadoAcreedor.Text = "0"
End If
End Sub
Protected Sub DdlPersonal_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlPersonal.SelectedIndexChanged
ViewState("CvePersonal") = DdlPersonal.SelectedValue
End Sub
Protected Sub DdlCajaChica_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlCajaChica.SelectedIndexChanged
ViewState("CveCajaChica") = DdlCajaChica.SelectedValue
End Sub
Protected Sub DdlTipoCredito_SelectedIndexChanged(sender As Object, e As EventArgs)
CargaCreditos()
Select Case DdlTipoCredito.SelectedValue.ToEntero
Case 1
DivCreditoMensualidad.Visible = False
Case 2
DivCreditoMensualidad.Visible = True
End Select
End Sub
Protected Sub DdlProveedor_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlProveedor.SelectedIndexChanged
ViewState("CveProveedor") = DdlProveedor.SelectedValue.ToEntero
HdnCveProveedor.Value = CveProveedor.ToString
CargaProveedor(HdnCveProveedor.Value.ToEntero, "-1", False)
If DdlPS.ddl.SelectedIndex > 0 Then
DdlPS_SelectedIndexChanged(sender, e)
DdlPS.Focus()
Else
TxtCantidad.Focus()
End If
If DdlProveedor.SelectedValue.ToEntero > 0 Then
ChkConsignacion.Enabled = True
Else
ChkConsignacion.Enabled = False
End If
If GlobalDTProveedorSucursales(DdlProveedor.SelectedValue.ToEntero, UsuarioActual.CveEmpresa).Rows.Count > 0 Then
RowProveedorSucursal.Visible = True
DdlProveedorSucursal.Items.Clear()
DdlProveedorSucursal.DataSource = GlobalDTProveedorSucursales(DdlProveedor.SelectedValue.ToEntero, UsuarioActual.CveEmpresa)
DdlProveedorSucursal.DataBind()
DdlProveedorSucursal.Items.Insert(0, New ListItem("Selecciona una Sucursal", "-1"))
DdlProveedorSucursal.Items.Insert(0, New ListItem("Matriz", "0"))
Else
DdlProveedorSucursal.Items.Clear()
DdlProveedorSucursal.Items.Insert(0, New ListItem("N/O", "-1"))
DdlProveedorSucursal.DataBind()
RowProveedorSucursal.Visible = False
End If
UpEstatus.Update()
UpTabs.Update()
End Sub
Protected Sub DdlCuenta_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlCuenta.SelectedIndexChanged
Dim Folio As Long
Dim dr As DataRow = GlobalDTBancosCuentas(UsuarioActual.CveUsuario, CveEmpresa:=UsuarioActual.CveEmpresa).FiltroPrimero("CveCuenta = " & DdlCuenta.SelectedValue)
If dr IsNot Nothing Then
CveMoneda = dr("CveMoneda").ToString.ToEntero
IdCuentaBancaria = dr("IdCtaContable").ToString.ToEntero
IdCuentaBancariaComplementaria = dr("IdCtaContableComplementaria").ToString.ToEntero
If dr("UsaTarjeta").ToString = "True" Then
CargaGridTarjetas()
Else
DivTarjeta.Visible = False
End If
End If
If UsuarioActual.Empresa.Funcionalidad(505) <> "1" Then
Dim Banco As New ClsBancos
Folio = Banco.GetNextFolio(DdlCuenta.SelectedValue.ToEntero, DdlTipoTransaccion.SelectedValue.ToEntero)
Banco.Dispose()
TxtDocumentoFolio.Text = Folio.ToString
End If
End Sub
Protected Sub DdlCuentaCaja_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlCuentaCaja.SelectedIndexChanged
Dim Folio As Long
Dim dr As DataRow = GlobalDTBancosCuentas(UsuarioActual.CveUsuario, CveEmpresa:=UsuarioActual.CveEmpresa).FiltroPrimero("CveCuenta = " & DdlCuentaCaja.SelectedValue)
If dr IsNot Nothing Then
CveMoneda = dr("CveMoneda").ToString.ToEntero
IdCuentaBancaria = dr("IdCtaContable").ToString.ToEntero
EstaAsociadoACajaChica = True
End If
If UsuarioActual.Empresa.Funcionalidad(505) <> "1" Then
Dim Banco As New ClsBancos
Folio = Banco.GetNextFolio(DdlCuentaCaja.SelectedValue.ToEntero, DdlTipoTransaccionCaja.SelectedValue.ToEntero)
Banco.Dispose()
TxtDocumentoFolioCaja.Text = Folio.ToString
End If
End Sub
Protected Sub DdlFuncionarioEmpleado_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlFuncionarioEmpleado.SelectedIndexChanged
If DdlFuncionarioEmpleado.SelectedValue.ToEntero > 0 Then
Dim ObjMovtos As New ClsMovimientos
RowCheque.Visible = True
ObjMovtos.GetEgresosSinComprobarPersonalDetalle(DdlFuncionarioEmpleado.SelectedValue.ToEntero, UsuarioActual.CveEmpresa)
DtCheques = ObjMovtos.DtResultados.FiltraParametros("CveIE > 0", "FechaDocumento, FolioFecha")
'Limpia Ddl Cheques
DDlCheques.Items.Clear()
If DtCheques.Rows.Count > 0 Then
DDlCheques.DataSource = DtCheques
End If
ObjMovtos.Dispose()
DDlCheques.DataBind()
EstaAsociadoAPersonal = True
DDlCheques_SelectedIndexChanged(DDlCheques, EventArgs.Empty)
Else
RowCheque.Visible = False
lblSaldoFE.Text = "0.00"
End If
End Sub
Protected Sub DDlCheques_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DDlCheques.SelectedIndexChanged
Dim saldo As Double = DtCheques.Rows(DDlCheques.SelectedIndex)("Saldo").ToString.ToDecimal
TxtDocumentoImporteFE.Text = If(saldo < TxtTotal.Text.ToDouble, saldo.FormatoNumero, TxtTotal.Text)
lblSaldoFE.Text = saldo.FormatoNumero
RVDocumentoImporteFE.MaximumValue = saldo.ToString
UPCondicionesPago.Update()
End Sub
#End Region
#Region "CHK'S"
Protected Sub RBLCajaChica_SelectedIndexChanged(sender As Object, e As EventArgs) Handles RBLCajaChica.SelectedIndexChanged
Select Case RBLCajaChica.SelectedValue
Case "1" : DdlCajaChica.Visible = False : DdlPersonal.Visible = True
Case "2" : DdlCajaChica.Visible = True : DdlPersonal.Visible = False
End Select
End Sub
Protected Sub ChkReembolso_CheckedChanged(sender As Object, e As EventArgs) Handles ChkReembolso.CheckedChanged
PnlReemb.Visible = ChkReembolso.Checked
End Sub
Protected Sub RBLPago_SelectedIndexChanged(sender As Object, e As EventArgs) Handles RBLPago.SelectedIndexChanged
CambiaTipoPago(True)
End Sub
Private Sub CambiaTipoPago(MostrarModal As Boolean)
DdlPersonalReembolso.Visible = False
DdlCuentaCajaChicaReembolso.Visible = False
Select Case RBLPago.SelectedValue
Case "1" 'Credito
PnlContado.Visible = False
If Not UsuarioActual.Empresa.UsaAC Then
TxtNumeroReembolso.Text = ""
tdNumeroReembolso.Visible = False
End If
EsContado = False
romCreditosTabla.Visible = False
Case "2" 'Contado
PnlContado.Visible = True
TxtNumeroReembolso.Text = ""
tdNumeroReembolso.Visible = False
RBLContado.Items(0).Enabled = True
RBLContado.Items(3).Enabled = True
RBLContado.Items(4).Enabled = True
RBLContado.Items(5).Enabled = True
If UsuarioActual.Empresa.CvePlataforma = 2 Then
RBLContado.Items.Clear()
RBLContado.Items.Insert(0, New ListItem("Bancos", "1"))
RBLContado.Items.Insert(1, New ListItem("Caja Chica", "6"))
RBLContado.Items.Insert(2, New ListItem("Deudores", "4"))
RBLContado.SelectedIndex = 0
'RBLContado.Items.Item(2).Enabled = False
'RBLContado.Items.Item(4).Enabled = False
'RBLContado.Items.Item(5).Enabled = False
End If
'If EmpresaPrueba Then
' RBLContado.Items(5).Enabled = False
'End If
EsContado = True
romCreditosTabla.Visible = False
Case "3" 'Reembolso/Comprobacion
PnlContado.Visible = True
''AGARRA VALORES DE SESSION PARA REEMBOLSO -- SI YA ESTA REGISTRADA LA COMPRA IGNORA DATOS DE REEMBOLSO
If Not CveCompra > 0 Then
If UsuarioActual.Sesion("Comp-NumeroReembolso") <> Nothing AndAlso UsuarioActual.Sesion("Comp-NumeroReembolso").ToString <> "" Then
'RBLPago.SelectedValue = "3" ' [IPP] SE COMENTO POR NO PODER MOSTRAR LO SELECCIONADO
'RBLPago_SelectedIndexChanged(RBLPago, EventArgs.Empty)
'CambiaTipoPago(False)
tdNumeroReembolso.Visible = True
TxtNumeroReembolso.Text = UsuarioActual.Sesion("Comp-NumeroReembolso").ToString
TxtDescripcion.Text = UsuarioActual.Sesion("Comp-Descripcion").ToString
If UsuarioActual.Sesion("Comp-CveFYE") <> Nothing AndAlso UsuarioActual.Sesion("Comp-CveFYE").ToString.ToEntero > 0 Then
RBLContado.SelectedValue = "2"
RBLContado_SelectedIndexChanged(RBLContado, EventArgs.Empty)
DdlPersonalReembolso.SelectedValueExist(UsuarioActual.Sesion("Comp-CveFYE").ToString)
ViewState("CvePersonal") = UsuarioActual.Sesion("Comp-CveFYE").ToString
Else
RBLContado.SelectedValue = "6"
End If
Else
UsuarioActual.Sesion("Comp-NumeroReembolso") = ""
UsuarioActual.Sesion("Comp-CveFYE") = ""
UsuarioActual.Sesion("Comp-Descripcion") = ""
TxtNumeroReembolso.Text = ""
tdNumeroReembolso.Visible = True
RBLContado.SelectedValue = "6"
End If
End If
RBLContado.Items(0).Enabled = False
RBLContado.Items(3).Enabled = True
RBLContado.Items(4).Enabled = True
RBLContado.Items(5).Enabled = False
EsContado = False
'Valida Proceso 118 para ROL Administrador - Si es REEMBOLSO: Selecciona FyE y Relacionado con UsuarioActual cuando tiene CvePersonal
If UsuarioActual.TienePermisoProceso(118) Then
RBLContado.SelectedValue = "2"
RBLContado.Items(1).Enabled = False
End If
Select Case RBLContado.SelectedValue
Case "2"
DdlPersonalReembolso.Visible = True
DivPersonalReembolso.Visible = True
Case "6"
DdlCuentaCajaChicaReembolso.Visible = True
End Select
romCreditosTabla.Visible = False
Case "4"
CargaCreditosDisponibles()
Exit Select
End Select
UpGvCreditos.Update()
If Not RBLPago.SelectedValue = "1" And MostrarModal And RBLPago.SelectedValue <> "4" Then
RegistraScript(String.Format("$('#{0}').modal('show');", "DivContadoModal"))
End If
LtlTituloPago.Text = If(EsContado, "Contado", "Reembolso")
DivContado.Visible = EsContado
DivReembolso.Visible = Not EsContado
CargaContado()
End Sub
Protected Sub RBLContado_SelectedIndexChanged(sender As Object, e As EventArgs) Handles RBLContado.SelectedIndexChanged
LblCheq.Text = RBLContado.SelectedItem.Text
CargaContado()
End Sub
Private Sub RBLTipoDeudor_SelectedIndexChanged(sender As Object, e As EventArgs) Handles RBLTipoDeudor.SelectedIndexChanged
GvDeudores.DataSource = Nothing
GvDeudores.DataBind()
UpContado.Update()
CargaDeudores()
End Sub
Private Sub CargaContado()
'ESCONDE TODO
PnlContadoBancos.Visible = False
PnlContadoFyE.Visible = False
PnlContadoCreditos.Visible = False
PnlContadoDeudores.Visible = False
PnlContadoAcreedores.Visible = False
PnlContadoCajaChica.Visible = False
DdlPersonalReembolso.Visible = False
DdlCuentaCajaChicaReembolso.Visible = False
If GvDeudores IsNot Nothing Then
GvDeudores.DataSource = Nothing
GvDeudores.DataBind()
UPDeudores.Update()
End If
'Reembolsos
If RBLPago.SelectedValue = "3" Then
Select Case RBLContado.SelectedValue
Case "2"
DdlPersonalReembolso.Visible = True
DivPersonalReembolso.Visible = True
Case "6"
DdlCuentaCajaChicaReembolso.Visible = True
End Select
'Valida Proceso 118 para ROL Administrador - Si es REEMBOLSO: Selecciona FyE y Relacionado con UsuarioActual cuando tiene CvePersonal
If UsuarioActual.TienePermisoProceso(118) Then
If UsuarioActual.CvePersonal > 0 Then
DdlPersonalReembolso.SelectedValueExist(UsuarioActual.CvePersonal.ToString)
ViewState("CvePersonal") = DdlPersonalReembolso.SelectedValue
End If
DdlPersonalReembolso.Enabled = False
End If
End If
'CONTADO
Select Case RBLContado.SelectedValue
Case "1" ' Bancos
PnlContadoBancos.Visible = True
TxtDocumentoImporte.Text = (TxtTotal.Text.ToDecimal - LblAmortizacion.Text.ToDecimal).FormatoNumero
ChkCreditoMultiple.Visible = False
RfvTxtNumeroReembolso.Enabled = False
TxtNumeroReembolso.Text = ""
TxtRembolsoNumero.Text = ""
Case "2" ' F y E
PnlContadoFyE.Visible = True
CargaFuncionariosEmpleados()
ChkCreditoMultiple.Visible = False
RfvTxtNumeroReembolso.Enabled = True
TxtRembolsoNumero.Text = ""
TxtNumeroReembolso.Text = ""
Case "3" ' Creditos
PnlContadoCreditos.Visible = True
ChkCreditoMultiple.Visible = True
CargaCreditos()
RfvTxtNumeroReembolso.Enabled = False
RfvTxtNumeroReembolso.Text = ""
TxtRembolsoNumero.Text = ""
Case "4" ' Deudores
PnlContadoDeudores.Visible = True
CargaDeudores()
ChkCreditoMultiple.Visible = False
RfvTxtNumeroReembolso.Enabled = False
TxtNumeroReembolso.Text = ""
TxtRembolsoNumero.Text = ""
Case "5" ' ACREEDORES
PnlContadoAcreedores.Visible = True
ChkCreditoMultiple.Visible = True
CargaAcreedores()
RfvTxtNumeroReembolso.Enabled = False
TxtNumeroReembolso.Text = ""
TxtRembolsoNumero.Text = ""
Case "6" ' Caja Chica
PnlContadoCajaChica.Visible = True
TxtDocumentoImporteCaja.Text = (TxtTotal.Text.ToDecimal - LblAmortizacion.Text.ToDecimal).FormatoNumero
ChkCreditoMultiple.Visible = False
RfvTxtNumeroReembolso.Enabled = True
TxtNumeroReembolso.Text = ""
TxtRembolsoNumero.Text = ""
End Select
UpContado.Update()
End Sub
Protected Sub BtnContado_Click(sender As Object, e As EventArgs)
TxtRembolsoNumero.Text = TxtNumeroReembolso.Text
If RBLContado.SelectedValue.ToEntero = 6 Then ' Caja chica
DdlFuncionarioEmpleado.SelectedValueExist(-1)
TxtDocumentoImporteFE.Text = ""
TextBox3.Text = ""
ViewState("CvePersonal") = -1
End If
If RBLContado.SelectedValue.ToEntero = 2 Then ' viaticos personal
DdlTipoTransaccionCaja.SelectedValueExist(-1)
DdlCuentaCajaChicaReembolso.SelectedValueExist(-1)
DdlCuentaCaja.SelectedValueExist(-1)
TxtDocumentoFolioCaja.Text = ""
TxtDocumentoImporteCaja.Text = ""
TxtDocumentoObservacionesCaja.Text = ""
ViewState("CveCajaChica") = -1
End If
RegistraScript(String.Format("$('#{0}').modal('hide');", "DivContadoModal"))
End Sub
Protected Sub RblRembolso_SelectedIndexChanged(sender As Object, e As EventArgs)
TrRembolsoCajaChica.Visible = False
TrRembolsoPersonal.Visible = False
DdlRembolsoCajaChica.SelectedValueExistInsert("-1", "Seleccione")
DdlRembolsoPersonal.SelectedValueExistInsert("-1", "Seleccione")
If RblRembolso.SelectedValue.ToEntero = 1 Then
TrRembolsoPersonal.Visible = True
ElseIf RblRembolso.SelectedValue.ToEntero = 2 Then
TrRembolsoCajaChica.Visible = True
End If
UPCondicionesPago.Update()
End Sub
#End Region
#Region "ARMONIZACION CONTABLE - AC - SIMPLIFICADO"
Private Sub CargaPresupuestosEgresos(Optional CargaTodo As Boolean = True)
'Seccion Grid
GvPS.Width = 1760
GvPS.Columns(13).Visible = True
GvPS.Columns(14).Visible = True
GvPS.Columns(15).Visible = True
GvPS.Columns(16).Visible = True
GvPS.Columns(17).Visible = True
GvPS.Columns(18).Visible = True
'Panel General
UpPresupuestosAC.Visible = True
DdlACGeneral1.Items.Clear()
DdlACGeneral1.DataSource = DtPresupuestos.FiltraParametros("", DistinctColumns:={"CveProgramaOperativo", "ProgramaOperativo"})
DdlACGeneral1.DataBind()
DdlACGeneral2.Items.Clear()
DdlACGeneral2.DataSource = DtPresupuestos.FiltraParametros("", DistinctColumns:={"CveUnidadAdministrativa", "UnidadAdministrativa"}, Orderby:="UnidadAdministrativa")
DdlACGeneral2.DataBind()
DdlACGeneral3.Items.Clear()
DdlACGeneral3.DataSource = DtPresupuestos.FiltraParametros("", DistinctColumns:={"CveFuenteFinanciamiento", "FuenteFinanciamiento"}, Orderby:="FuenteFinanciamiento")
DdlACGeneral3.DataBind()
DdlACGeneral4.Items.Clear()
DdlACGeneral4.DataSource = DtPresupuestos.FiltraParametros("", DistinctColumns:={"CveTipoGasto", "TipoGasto"})
DdlACGeneral4.DataBind()
DdlACGeneral5.Items.Clear()
DdlACGeneral5.DataSource = DtPresupuestos.FiltraParametros("", DistinctColumns:={"CveClasificacion", "CodigoClasificacion"}, Orderby:="CodigoClasificacion")
'RM 2020.05.19. se mostraran todas las partidas del presupuesto, no se limintan las 1%
'If UsuarioActual.CveEmpresa.Contiene(120) Then
' DdlACGeneral5.DataSource = DtPresupuestos.FiltraParametros("", DistinctColumns:={"CveClasificacion", "CodigoClasificacion"}, Orderby:="CodigoClasificacion")
'Else
' DdlACGeneral5.DataSource = DtPresupuestos.FiltraParametros("NOT CodigoCOG like '1%'", DistinctColumns:={"CveClasificacion", "CodigoClasificacion"}, Orderby:="CodigoClasificacion")
'End If
DdlACGeneral5.DataBind()
If CveCompra > 0 Then
RegistraScript("$get('DivPresupuestoEgresosGeneral').style.display = 'none';")
BtnVerPE.Visible = True
End If
If CargaTodo Then
CalculaSaldoACGeneral()
UpPresupuestosAC.Update()
End If
End Sub
Private Sub ConservaAC()
'Guarda valores AC en TmpDT
Dim Index = 0
For Each gvr As GridViewRow In GvPS.Rows
TmpDT.Rows(Index)("CveProgramaOperativo") = gvr.FCDropDownList("DdlAC1").SelectedValue.ToEntero
TmpDT.Rows(Index)("CveUnidadAdministrativa") = gvr.FCDropDownList("DdlAC2").SelectedValue.ToEntero
TmpDT.Rows(Index)("CveFuenteFinanciamiento") = gvr.FCDropDownList("DdlAC3").SelectedValue.ToEntero
TmpDT.Rows(Index)("CveTipoGastoAC") = gvr.FCDropDownList("DdlAC4").SelectedValue.ToEntero
TmpDT.Rows(Index)("CveClasificacionOG") = gvr.FCDropDownList("DdlAC5").SelectedValue.ToEntero
Index += 1
Next
End Sub
Protected Sub CompruebaSaldoAC(sender As Object, e As EventArgs)
ConservaAC()
CompruebaAgregar()
End Sub
Protected Sub CambiaACGeneral(sender As Object, e As EventArgs)
If ChkACGeneral.Checked Then
'CAMBIA LOS COMBOS DE TODOS LOS DETALLES DEL GRID
For Each gvr As GridViewRow In GvPS.Rows
'SI VIENE DESDE OC EL PE NO SE MUEVE
If Not gvr.DataKey("CveOrdenCompraDetalle").ToEntero > 0 Then
gvr.FCDropDownList("DdlAC1").SelectedValue = DdlACGeneral1.SelectedValue
gvr.FCDropDownList("DdlAC2").SelectedValue = DdlACGeneral2.SelectedValue
gvr.FCDropDownList("DdlAC3").SelectedValue = DdlACGeneral3.SelectedValue
gvr.FCDropDownList("DdlAC4").SelectedValue = DdlACGeneral4.SelectedValue
gvr.FCDropDownList("DdlAC5").SelectedValue = DdlACGeneral5.SelectedValue
End If
Next
ConservaAC()
CompruebaAgregar()
UpPS.Update()
End If
CalculaSaldoACGeneral()
UpPresupuestosAC.Update()
End Sub
Private Sub CalculaSaldoACGeneral()
Dim ContPaq As New ClsContPAQi(UsuarioActual.Empresa)
Dim DtPresupuestosTemp = DtPresupuestos.FiltraParametros(String.Format("CveProgramaOperativo = {0} and CveUnidadAdministrativa = {1} and CveFuenteFinanciamiento = {2} and CveTipoGasto= {3} and CveClasificacion = {4}", DdlACGeneral1.SelectedValue.ToString, DdlACGeneral2.SelectedValue.ToString, DdlACGeneral3.SelectedValue.ToString, DdlACGeneral4.SelectedValue.ToString, DdlACGeneral5.SelectedValue.ToString))
If DtPresupuestosTemp.Rows.Count > 0 Then
Dim IdCuenta = If(HdnVCveOC.Value <> "-1", DtPresupuestosTemp.Rows(0)("IdCuentaDevengado").ToString.ToEntero, DtPresupuestosTemp.Rows(0)("IdCuentaPorEjercer").ToString.ToEntero)
LbACGeneralSaldo.Text = ContPaq.GetSaldoCuenta(IdCuenta, 0, TxtFecha.Text.ToDate.Year).ToString.FormatoNumero(2)
Else
LbACGeneralSaldo.Text = "0.00"
End If
ContPaq.Dispose()
End Sub
Private Sub CargaHidendsAC()
Dim DtPresupuestosTemp As DataTable
Dim Filtro As New StringBuilder
For Each grid As GridViewRow In GvPS.Rows
Filtro.AppendFormat("CveProgramaOperativo = {0} and CveUnidadAdministrativa = {1} and CveFuenteFinanciamiento = {2} and CveTipoGasto= {3} and CveClasificacion = {4}", grid.FCDropDownList("DdlAC1").SelectedValue.ToString, grid.FCDropDownList("DdlAC2").SelectedValue.ToString, grid.FCDropDownList("DdlAC3").SelectedValue.ToString, grid.FCDropDownList("DdlAC4").SelectedValue.ToString, grid.FCDropDownList("DdlAC5").SelectedValue.ToString)
DtPresupuestosTemp = DtPresupuestos.FiltraParametros(Filtro.ToString)
Filtro.Clear()
If DtPresupuestosTemp.Rows.Count > 0 Then
TmpDT.Rows(grid.RowIndex)("CvePresupuestoEgreso") = DtPresupuestosTemp.Rows(0)("CvePresupuestoEgreso").ToString
TmpDT.Rows(grid.RowIndex)("IdCuentaComprometido") = DtPresupuestosTemp.Rows(0)("IdCuentaComprometido").ToString
TmpDT.Rows(grid.RowIndex)("IdCuentaPorEjercer") = DtPresupuestosTemp.Rows(0)("IdCuentaPorEjercer").ToString
TmpDT.Rows(grid.RowIndex)("IdCuentaDevengado") = DtPresupuestosTemp.Rows(0)("IdCuentaDevengado").ToString
TmpDT.Rows(grid.RowIndex)("IdCuentaMatriz") = DtPresupuestosTemp.Rows(0)("IdCuentaMatriz").ToString
Else
Alert("Ocurrió un error al vincular el Presupuesto de Egreso. Por favor intente de nuevo.", TipoMensaje.MsgAdvertencia)
End If
Next
End Sub
Private Sub CompruebaAgregar()
Dim ContPaq As New ClsContPAQi(UsuarioActual.Empresa)
Dim disponible As Double
Dim ErrorPresupuesto = False
Dim Conceptos As New StringBuilder
Dim Ddl1 As DropDownList
Dim Ddl2 As DropDownList
Dim Ddl3 As DropDownList
Dim Ddl4 As DropDownList
Dim Ddl5 As DropDownList
Dim Total As Double
Dim DtPresupuestosTemp As DataTable
Dim Filtro As New StringBuilder
For Each grid As GridViewRow In GvPS.Rows
Ddl1 = grid.FCDropDownList("DdlAC1")
Ddl2 = grid.FCDropDownList("DdlAC2")
Ddl3 = grid.FCDropDownList("DdlAC3")
Ddl4 = grid.FCDropDownList("DdlAC4")
Ddl5 = grid.FCDropDownList("DdlAC5")
Total = grid.Cells(8).ToString.ToDouble
Filtro.AppendFormat("CveProgramaOperativo = {0} and CveUnidadAdministrativa = {1} and CveFuenteFinanciamiento = {2} and CveTipoGasto= {3} and CveClasificacion = {4}", Ddl1.SelectedValue.ToString, Ddl2.SelectedValue.ToString, Ddl3.SelectedValue.ToString, Ddl4.SelectedValue.ToString, Ddl5.SelectedValue.ToString)
DtPresupuestosTemp = DtPresupuestos.FiltraParametros(Filtro.ToString)
Filtro.Clear()
If DtPresupuestosTemp IsNot Nothing AndAlso DtPresupuestosTemp.Rows.Count > 0 Then
disponible = ContPaq.GetSaldoCuenta(If(OCVinculada, DtPresupuestosTemp.Rows(0)("IdCuentaComprometido").ToString.ToEntero, DtPresupuestosTemp.Rows(0)("IdCuentaPorEjercer").ToString.ToEntero), 0, TxtFecha.Text.ToDate.Year)
If (disponible > 0 AndAlso disponible >= Total) Or DdlTipoComprobante.SelectedValue.Contiene("NC", "DEV") Then
'Alert("Si hay dinero: ")
TmpDT.Rows(grid.RowIndex)("CvePresupuestoEgreso") = DtPresupuestosTemp.Rows(0)("CvePresupuestoEgreso").ToString
TmpDT.Rows(grid.RowIndex)("IdCuentaComprometido") = DtPresupuestosTemp.Rows(0)("IdCuentaComprometido").ToString
TmpDT.Rows(grid.RowIndex)("IdCuentaPorEjercer") = DtPresupuestosTemp.Rows(0)("IdCuentaPorEjercer").ToString
TmpDT.Rows(grid.RowIndex)("IdCuentaDevengado") = DtPresupuestosTemp.Rows(0)("IdCuentaDevengado").ToString
TmpDT.Rows(grid.RowIndex)("IdCuentaMatriz") = DtPresupuestosTemp.Rows(0)("IdCuentaMatriz").ToString
grid.Cells(7).BackColor = Drawing.Color.Green
Else
'Alert("No hay presupuesto asignado", TipoMensaje.MsgAdvertencia)
Conceptos.AppendFormat("<br> #{0} - {1} - {2}", grid.RowIndex + 1, grid.DataKey("Clasificacion"), grid.DataKey("PS"))
grid.Cells(7).BackColor = Drawing.Color.Red
ErrorPresupuesto = True
End If
TmpDT.Rows(grid.RowIndex)("CvePresupuestoEgreso") = DtPresupuestosTemp.Rows(0)("CvePresupuestoEgreso").ToString
Else
TmpDT.Rows(grid.RowIndex)("CvePresupuestoEgreso") = "-1"
'Alert("No hay presupuesto asignado", TipoMensaje.MsgAdvertencia)
Conceptos.AppendFormat("<br> #{0} - {1} - {2}", grid.RowIndex + 1, grid.DataKey("Clasificacion"), grid.DataKey("PS"))
grid.Cells(7).BackColor = Drawing.Color.Red
ErrorPresupuesto = True
End If
Next
If ErrorPresupuesto Then
Alert(String.Format("No hay presupuesto asignado para los siguientes conceptos: {0}", Conceptos), TipoMensaje.MsgAdvertencia)
BtnGuardar.Enabled = False
Else
BtnGuardar.Enabled = True
End If
UpFacturar.Update()
ContPaq.Dispose()
End Sub
Private Sub GuardaAC()
Dim dr As DataRow
For Each gvr As GridViewRow In GvPS.Rows
dr = TmpDT.Rows(gvr.RowIndex)
dr("CveProgramaOperativo") = gvr.FCDropDownList("DdlAC1").SelectedValue.ToEntero
dr("CveUnidadAdministrativa") = gvr.FCDropDownList("DdlAC2").SelectedValue.ToEntero
dr("CveFuenteFinanciamiento") = gvr.FCDropDownList("DdlAC3").SelectedValue.ToEntero
dr("CveTipoGastoAC") = gvr.FCDropDownList("DdlAC4").SelectedValue.ToEntero
dr("CveClasificacionOG") = gvr.FCDropDownList("DdlAC5").SelectedValue.ToEntero
'dr("CvePresupuestoEgreso") = gvr.FCHiddenField("HdnCvePresupuestoEgreso").Value.ToString.ToEntero
Next
TmpDT.AcceptChanges()
End Sub
Protected Sub BtnCambiaFecha_Click(sender As Object, e As EventArgs)
CambiaEjercicioAC()
End Sub
Private Sub CambiaEjercicioAC(Optional CargaTodo As Boolean = True)
Dim Ejercicio = If(IsDate(TxtFecha.Text), Year(TxtFecha.Text.ToDate), UsuarioActual.Empresa.EjercicioActual)
If Ejercicio <> EjercicioAC Then
Dim AC As New ClsAC
If AC.GetPresupuestoEgresos(-1, True, Ejercicio, UsuarioActual.CveEmpresa, True) Then
DtPresupuestos = AC.DtResultados.Copy
CargaPresupuestosEgresos(CargaTodo)
ConservaAC()
GvPS.DataSource = TmpDT
GvPS.DataBind()
'CAMBIA LOS COMBOS DE TODOS LOS DETALLES DEL GRID
For Each gvr As GridViewRow In GvPS.Rows
gvr.FCDropDownList("DdlAC1").SelectedValue = DdlACGeneral1.SelectedValue
gvr.FCDropDownList("DdlAC2").SelectedValue = DdlACGeneral2.SelectedValue
gvr.FCDropDownList("DdlAC3").SelectedValue = DdlACGeneral3.SelectedValue
gvr.FCDropDownList("DdlAC4").SelectedValue = DdlACGeneral4.SelectedValue
gvr.FCDropDownList("DdlAC5").SelectedValue = DdlACGeneral5.SelectedValue
Next
If CargaTodo Then CompruebaAgregar()
UpPS.Update()
UpPresupuestosAC.Update()
Else
Alert("Ocurrio un error al cargar los Presupuestos. Por favor vuelva a cargar la página")
End If
AC.Dispose()
EjercicioAC = Ejercicio
End If
End Sub
#End Region
#Region "E V E N T O - B I T A C O R A"
Protected Sub GVEventoBitacora_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvEB.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
If e.Row.RowIndex = 0 Then
e.Row.Cells(0).Width = Unit.Pixel(200)
e.Row.Cells(1).Width = Unit.Pixel(200)
e.Row.Cells(2).Width = Unit.Pixel(100)
e.Row.Cells(3).Width = Unit.Pixel(500)
End If
If e.Row.DBCampo("Archivo").ToString <> "" Then
e.Row.FCLinkButton("LinkArchivo").Visible = True
e.Row.FCLinkButton("LinkArchivo").CommandArgument = String.Format("OI\{0}", e.Row.DBCampo("Archivo").ToString)
ScriptManager.GetCurrent(Me).RegisterPostBackControl(e.Row.FCLinkButton("LinkArchivo")) 'Registro un evento Postbacktrigger, que recargue toda la pagina para que funcione
End If
e.Row.Cells(3).HorizontalAlign = HorizontalAlign.Left
End If
End Sub
Protected Sub BtnGuardarEventoBitacora_Click(sender As Object, e As EventArgs) Handles BtnGuardarEventoBitacora.Click
Dim ObjEventoBitacora As New ClsOIEventos
Dim FileExtension As String = "-1"
Dim Filesgral As List(Of Archivo) = Anexo.getfiles().Archivos
Dim Filename As String = ""
For Each fileItem As Archivo In Filesgral
FileExtension = IO.Path.GetExtension(String.Format("{0}Temp\{1}", AppDomain.CurrentDomain.BaseDirectory, fileItem.filename)).Replace(".", "")
Filename = fileItem.filename
Next
If ObjEventoBitacora.AddEventoBitacora(TxtEventoDescripcion.Text.Trim, String.Format(".{0}", FileExtension), UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCompra:=CveCompra) Then
If Filename <> "" Then
Filename.FilesMove(String.Format("OI{0}", ObjEventoBitacora.CveEvento.ToString), String.Format("{0}OI", UsuarioActual.Empresa.Ruta), ConcatenarDirectorioBase:=False)
End If
GvEB.DataSource = ObjEventoBitacora.DtResultados
TxtEventoDescripcion.Text = ""
Anexo.Text = "[]"
Alert("La bitácora/observación se guardó correctamente", TipoMensaje.MsgInformacion)
RegistraScript("$('#ModalBitacora').modal('hide')", "hidemodal")
End If
ObjEventoBitacora.Dispose()
GvEB.DataBind()
UPEventoBitacora.Update()
CargaEventoBitacora()
UPAddEventoBitacora.Update()
End Sub
'Protected Sub CargarArchivo(ByVal sender As Object, ByVal e As AjaxControlToolkit.AsyncFileUploadEventArgs) Handles AFU.UploadedComplete
' If AFU.HasFile Then
' Dim UploadFolder As String = String.Format("{0}\Temp\", UsuarioActual.Empresa.Ruta)
' UploadFolder.DirectoryExistsCreate()
' Dim Extension As String = System.IO.Path.GetExtension(AFU.PostedFile.FileName)
' If File.Exists(String.Format("{0}{1}{2}", UploadFolder, UsuarioActual.CveUsuario.ToString, Extension)) Then File.Delete(String.Format("{0}{1}{2}", UploadFolder, UsuarioActual.CveUsuario.ToString, Extension))
' AFU.SaveAs(UploadFolder & UsuarioActual.CveUsuario.ToString & Extension)
' Session("FileUpload") = UploadFolder & UsuarioActual.CveUsuario.ToString & Extension
' Session("FileExtension") = Extension
' Session("FileFolder") = UploadFolder
' End If
'End Sub
Protected Sub DownloadFile(ByVal sender As Object, ByVal e As EventArgs)
Dim filePath As String = String.Format("{0}{1}", UsuarioActual.Empresa.Ruta, CType(sender, LinkButton).CommandArgument)
Dim Archivo As New System.IO.FileInfo(filePath)
HttpContext.Current.Response.Clear()
HttpContext.Current.Response.ClearContent()
HttpContext.Current.Response.ContentType = "application/octet-stream"
HttpContext.Current.Response.AppendHeader("Content-disposition", "attachment; filename=" + Path.GetFileName(filePath))
HttpContext.Current.Response.AddHeader("Content-Length", Archivo.Length.ToString())
HttpContext.Current.Response.TransmitFile(filePath)
HttpContext.Current.Response.Flush()
HttpContext.Current.Response.End()
Archivo = Nothing
End Sub
Private Sub CargaEventoBitacora()
Dim ObjEventoBitacora As New ClsOIEventos()
If ObjEventoBitacora.GetAgendaBitacora(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCompra:=CveCompra) Then
GvEB.DataSource = ObjEventoBitacora.DtResultados.FiltraParametros("CveTipoEvento = 6 OR CveTipoEvento = 2")
Else
GvEB.DataSource = Nothing
End If
ObjEventoBitacora.Dispose()
GvEB.DataBind()
End Sub
#End Region
#Region " C O N T A B I L I D A D "
Protected Sub BtnDescontabilizar_Click(sender As Object, e As EventArgs)
'Alert("Hola entre", TipoMensaje.MsgError)
'Exit Sub
Dim ObjConta As New ClsContabilidad
Dim Movimientos = ObjConta.GetMovimientosPoliza(IdPoliza, UsuarioActual.CveEmpresa)
'Verifica que solo exista 1 compra asociada
If Movimientos = 1 Then
EliminaPoliza()
Else
RegistraScript("ConfirmEliminarPolizaMultiple();")
End If
ObjConta.Dispose()
End Sub
Protected Sub LBContabilizarAC_Click(sender As Object, e As EventArgs)
Dim ObjContaAC = New ClsContPAQi(UsuarioActual.Empresa)
ObjContaAC.IniciaTransacSQL()
Dim ObjCompras As New ClsCompras
Dim ObjProveedores As New ClsCompProveedores(ObjCompras.IniciaTransacSQL())
Dim ObjAF As New ClsAF(ObjCompras.IniciaTransacSQL())
Dim ErrorAC = False
Dim IDPolizaComprometido = If(TxtOC.Text.Length > 0, 1, 0)
''EMPIEZA: SI USA AC
If UsuarioActual.Empresa.UsaAC Then
ObjContaAC = New ClsContPAQi(UsuarioActual.Empresa)
ObjContaAC.IniciaTransacSQL()
'ELIMINA TODOS LOS MOVIMIENTOS DE LA POLIZA
If IdPoliza > 0 Then
ObjContaAC.RemoveAllMovimientos(IdPoliza)
Else
Dim TotalPorDevengar = Math.Round(TxtTotal.Text.ToDouble, 2)
IdPoliza = ObjContaAC.AddPoliza(3, TxtDescripcion.Text.Trim, TotalPorDevengar, TotalPorDevengar, UsuarioActual.CveUsuario, TxtFecha.Text.ToDate)
End If
'INSERTA LOS NUEVOS MOVIMIENTOS DE LA POLIZA
If IdPoliza > 0 Then
Dim CuentaAbono As Integer
Dim Importe As Decimal = 0
Dim TotalDetalle As Decimal = 0
'CUENTA PROVEEDOR
If CtaProveedor <= 0 Then
If ObjContaAC.GetCuentas(-1, "021120000000000000", -1) Then
Dim drCuenta As DataRow = ObjContaAC.DtResultados.FiltroPrimero("")
If drCuenta IsNot Nothing Then
CuentaAbono = drCuenta("Id").ToString.ToEntero
Dim FolioProveedor = ObjContaAC.GetFolioProveedores("021120000000000000").ToString
ViewState("CtaProveedor") = ObjContaAC.AddCuenta(String.Format("02112{0}000000000", FolioProveedor.PadLeft(4, "0"c)), NombreProveedor, "D", 2, 0, 1, 0, "", 1, CuentaAbono)
ObjProveedores.UpdateProveedorIdCuentaAC(CveProveedor, CtaProveedor)
Else
ErrorAC = True
End If
Else
ErrorAC = True
End If
End If
Dim ConceptoRenglon As String = ""
If Not ErrorAC Then
Dim tTotalIVA, tTotalGral, tDiferenciaIVA, tIVA, tRetIVA, tRetISR As Decimal
Dim ipresup As Integer = 0
'COMIENZA: PRUEBA AGRUPACION CONCEPTOS
Dim Presup = From gvr As DataRow In TmpDT.Rows.Cast(Of DataRow)()
Group gvr By Grp = New With {
Key .CvePresupuestoEgreso = gvr("CvePresupuestoEgreso").ToString.ToEntero,
Key .CveActivoFijo = If(gvr("TipoAF").ToString.ToEntero = 2, gvr("CveActivoFijo").ToString.ToEntero, -1)
} Into Group
Select Grp.CvePresupuestoEgreso, Grp.CveActivoFijo,
TotalImporte = Group.Sum(Function(r) r("Total").ToString.ToDecimal)
Dim Fecha As Date = TxtFecha.Text.ToDate
'PresupuestoEgresos
Dim DtPresupuestosTemp As DataTable
Dim IdCuentaComprometido, IdCuentaPorEjercer, IdCuentaDevengado, IdCuentaMatriz As Integer
'Dim tTotalIVA, tTotalGral, tDiferenciaIVA, tIVA As Double
tTotalIVA = TxtIVA.Text.ToDecimal
tRetIVA = TxtRetIVA.Text.ToDecimal
tRetISR = TxtRetISR.Text.ToDecimal
'tTotalIVA = tTotalIVA - tRetIVA - tRetISR
tTotalGral = TxtTotal.Text.ToDecimal + tRetIVA + tRetISR ' EL TOTAL GENERAL DEBE DE SER EL SUBTOTAL + IVA, NO SE DEBEN DE INCLUIR LAS RETENCIONES, POR ESO SE RESTA
tDiferenciaIVA = tTotalIVA
tIVA = 0
ipresup = 0
'INVENTARIOS EN AC
Dim CuentaMatrizAlmacen As Integer
Dim ContadorInventario As Integer = GvInv.Rows.Cast(Of GridViewRow)().Count(Function(gvr) gvr.FCCheckBox("cbInv").Checked)
Dim CtaAlmacen As Integer
If ContadorInventario > 0 Then
Dim drr As DataRow = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimero(String.Format("CveAlmacen = {0}", GvInv.HeaderRow.FCDropDownList("ddlAlmacen").SelectedValue.ToString.ToEntero))
If drr IsNot Nothing Then
CtaAlmacen = drr("IdCtaContable").ToString.ToEntero
End If
End If
Dim DescuentoConIVA As Double
Dim tPorIVA As Decimal = tTotalIVA / (tTotalGral - tTotalIVA)
Dim tAjusteTotal As Decimal = 0
For Each grp In Presup
Importe = grp.TotalImporte
TotalDetalle += Importe
ipresup += 1
If Importe > 0 Then
'saco la proporcion de iva que le corresponde
tIVA = Math.Round(Importe * tPorIVA, 2)
tDiferenciaIVA -= tIVA
'identifico si es el ultimo registro, para ver si es necesario un ajuste
If ipresup = Presup.Count Then
If Math.Round(TotalDetalle - tTotalGral, 2) <= 0.01 AndAlso tDiferenciaIVA > 0 Then
tIVA += tDiferenciaIVA
End If
End If
'le sumo el iva al concepto
Importe += tIVA
'codigo Provisional, para cuand tenga descuento, solo tome el subtotal * el iva,RMF
If TxtDescuento.Text.ToDouble > 0 Then
Importe = grp.TotalImporte * (1 + tPorIVA)
End If
tAjusteTotal += Importe
'valido que la sumas de lo detalles no exceda al totalgeneral
If Math.Round(tAjusteTotal, 2) > tTotalGral Then
'le resto la diferencia
Importe -= (tAjusteTotal - tTotalGral)
End If
'Presupuesto Egresos
DtPresupuestosTemp = DtPresupuestos.FiltraParametros(String.Format("CvePresupuestoEgreso = {0}", grp.CvePresupuestoEgreso))
If DtPresupuestosTemp.Rows.Count <> 1 Then
ErrorAC = True
Exit For
End If
IdCuentaComprometido = DtPresupuestosTemp.Rows(0)("IdCuentaComprometido").ToString.ToEntero
IdCuentaPorEjercer = DtPresupuestosTemp.Rows(0)("IdCuentaPorEjercer").ToString.ToEntero
IdCuentaDevengado = DtPresupuestosTemp.Rows(0)("IdCuentaDevengado").ToString.ToEntero
IdCuentaMatriz = DtPresupuestosTemp.Rows(0)("IdCuentaMatriz").ToString.ToEntero
'COMPROMETIDO DEPENDIENTE SI EXISTE SU POLIZA
If IDPolizaComprometido = 0 Then
ConceptoRenglon = String.Format("GC Fact: {0}-{1} {2}", TxtSerie.Text.Trim, TxtFolio.Text.Trim, DdlProveedor.SelectedItem.Text)
If ObjContaAC.AddMovimiento(IdPoliza, IdCuentaComprometido, False, Importe, "", ConceptoRenglon, 0, Fecha, "") Then
If Not ObjContaAC.AddMovimiento(IdPoliza, IdCuentaPorEjercer, True, Importe, "", ConceptoRenglon, 0, Fecha, "") Then
ErrorAC = True
Exit For
End If
Else
ErrorAC = True
Exit For
End If
End If
ConceptoRenglon = String.Format("GD Fact: {0}-{1} {2}", TxtSerie.Text.Trim, TxtFolio.Text.Trim, DdlProveedor.SelectedItem.Text)
'DEVENGADO
If ObjContaAC.AddMovimiento(IdPoliza, IdCuentaDevengado, False, Importe, "", ConceptoRenglon, 0, Fecha, "") Then
If Not ObjContaAC.AddMovimiento(IdPoliza, IdCuentaComprometido, True, Importe, "", ConceptoRenglon, 0, Fecha, "") Then
ErrorAC = True
Exit For
End If
Else
ErrorAC = True
Exit For
End If
If ContadorInventario > 0 Then
Dim tImporte, ttIVA As Double
For Each gvr As GridViewRow In GvPS.Rows
'registra los movimientos del presupuesto asignado, para que no se duplique si hay varios presupeusto dentro de la compra
If gvr.DataKey("CvePresupuestoEgreso").ToEntero = grp.CvePresupuestoEgreso Then
'saco la proporcion de iva que le corresponde
tImporte = gvr.FCLiteral("LtlTotal").Text.ToDouble
ttIVA = Math.Round(tImporte * tTotalIVA / tTotalGral, 2)
tImporte += ttIVA
End If
Next
CuentaMatrizAlmacen = CtaAlmacen
ElseIf grp.CveActivoFijo > 0 Then
Dim CtaAF = -1
Dim AF = ""
Dim CuentaInicial = -1
If ObjAF.GetActivosFijos(grp.CveActivoFijo, UsuarioActual.CveEmpresa, "-1", "-1", -1, -1, "-1", -1, -1, -1, -1, -1, "", -1, UsuarioActual.CveEmpresa) Then
CtaAF = ObjAF.Cuenta
AF = ObjAF.Descripcion
CuentaInicial = ObjAF.CuentaInicial
Else
ErrorAC = True
Exit For
End If
If Not CuentaInicial > 0 Then
CuentaInicial = 1241
End If
'CUENTA AF
If CtaAF <= 0 Then
If ObjContaAC.GetCuentas(-1, String.Format("0{0}0000000000000", CuentaInicial), -1) Then
Dim drCuenta As DataRow = ObjContaAC.DtResultados.FiltroPrimero("")
If drCuenta IsNot Nothing Then
CuentaAbono = drCuenta("Id").ToString.ToEntero
Dim FolioAF = ObjContaAC.GetFolioProveedores(String.Format("0{0}0000000000000", CuentaInicial)).ToString
CtaAF = ObjContaAC.AddCuenta(String.Format("0{0}{1}000000000", CuentaInicial, FolioAF.PadLeft(4, "0"c)), AF, "A", 2, 0, 1, 0, "", 1, CuentaAbono)
ObjAF.UpdateActivosFijosCuentaAC(grp.CveActivoFijo, CtaAF, UsuarioActual.CveUsuario)
Else
ErrorAC = True
End If
Else
ErrorAC = True
End If
End If
CuentaMatrizAlmacen = CtaAF
Else
CuentaMatrizAlmacen = IdCuentaMatriz
End If
''AFECTAR MATRIZ EGRESOS
If ObjContaAC.AddMovimiento(IdPoliza, CuentaMatrizAlmacen, False, Importe, "", ConceptoRenglon, 0, Fecha, "") Then
''VERIFICA SI TIENE DESCUENTO (AMORTIZACION)
If TxtDescuento.Text.ToDouble > 0 AndAlso CtaProveedorAnticipos > 0 Then
DescuentoConIVA = TxtDescuento.Text.ToDecimal * 1.16
'Valida que el descuento con iva cuadre en los totales
If Math.Abs(DescuentoConIVA - (Importe - TxtTotal.Text.ToDouble)) < 0.02 Then
DescuentoConIVA = Importe - TxtTotal.Text.ToDouble
ElseIf DescuentoConIVA <> (Importe - TxtTotal.Text.ToDecimal) Then
ErrorAC = True
Exit For
End If
'actualizo el idcuenta del presupuesto
If ObjContaAC.AddMovimiento(IdPoliza, CtaProveedor, True, (Importe - DescuentoConIVA), "", ConceptoRenglon, 0, Fecha, "") Then
'agrego a la cuenta contable anticipos
If Not ObjContaAC.AddMovimiento(IdPoliza, CtaProveedorAnticipos, True, DescuentoConIVA, "", ConceptoRenglon, 0, Fecha, "") Then
ErrorAC = True
Exit For
End If
Else
ErrorAC = True
Exit For
End If
Else
'actualizo el idcuenta del
End If
Else
ErrorAC = True
Exit For
End If
''TERMINA AFECTAR MATRIZ EGRESOS
Else
ErrorAC = True
Exit For
End If
Next
If Not ErrorAC Then
'registro un solo movimiento a proveedores
Importe = TxtTotal.Text.ToDecimal
If Not ObjContaAC.AddMovimiento(IdPoliza, CtaProveedor, True, Importe, "", ConceptoRenglon, 0, Fecha, "") Then
ErrorAC = True
End If
End If
If tRetISR > 0 Then
ConceptoRenglon = String.Format("GD Fact: {0}-{1} {2}", TxtSerie.Text.Trim, TxtFolio.Text.Trim, DdlProveedor.SelectedItem.Text)
If Not ObjContaAC.AddMovimiento(IdPoliza, CtaProveedorRetISR, True, tRetISR, "", ConceptoRenglon, 0, Fecha, "") Then
ErrorAC = True
End If
End If
End If
Else
ErrorAC = True
End If
'CUADRA LA POLIZA
ObjContaAC.AjustaPoliza(IdPoliza)
End If
''TERMINA: SI USA AC
If Not ErrorAC Then
If Not ObjCompras.UpdateCompraPoliza(IdPoliza, CveCompra) Then
ErrorAC = True
End If
End If
If ErrorAC Then
Alert("Ocurrió un error al contabilizar la compra. Comuniquese con soporte.", TipoMensaje.MsgError)
ObjContaAC.RollBack()
ObjCompras.RollBack()
Else
ObjContaAC.Commit()
ObjCompras.Commit()
Alert("La Compra se contabilizó correctamente.", TipoMensaje.MsgInformacion)
HplCompraContabilizada.Text = "Si"
HplCompraContabilizada.NavigateUrl = String.Format("/Contabilidad/RegPoliza.aspx?IdPoliza={0}", IdPoliza)
LblCompraEstatus.ForeColor = Drawing.Color.Navy
trContabilizada.Visible = True
UpEstatus.Update()
End If
ObjContaAC.Dispose()
End Sub
Protected Sub BtnEliminarPoliza_Click(sender As Object, e As EventArgs)
EliminaPoliza()
End Sub
Private Sub EliminaPoliza()
Dim ObjAC As New ClsContPAQi(UsuarioActual.Empresa)
ObjAC.IniciaTransacSQL()
Dim ObjConta As New ClsContabilidad
ObjConta.IniciaTransacSQL()
Dim ErrorCompra = False
'Elimina la poliza
If (UsuarioActual.Empresa.UsaAC Or UsuarioActual.Empresa.UsaContabilidad) AndAlso IdPoliza > 0 Then
If Not ObjAC.RemovePoliza(IdPoliza) Then
ErrorCompra = True
End If
End If
'Desasocia la poliza
If Not ErrorCompra Then
If Not ObjConta.DesasociarPoliza(IdPoliza, UsuarioActual.CveEmpresa) Then
ErrorCompra = True
End If
End If
If Not ErrorCompra Then
If Not ObjConta.UpdatePrePolizasDetalleBloquear(CvePrePoliza, False) Then
ErrorCompra = True
End If
End If
If Not ErrorCompra Then
Alert("La poliza ha sido desvinculada y eliminada con exito.", TipoMensaje.MsgInformacion)
ObjAC.Commit()
ObjConta.Commit()
Else
Alert("Ocurrió un error al desvincular y/o eliminar la poliza. Por favor intente de nuevo ", TipoMensaje.MsgError)
ObjAC.RollBack()
ObjConta.RollBack()
End If
ObjAC.Dispose()
ObjConta.Dispose()
If Not ErrorCompra Then
CargaCompra()
End If
End Sub
#End Region
#Region " REEMBOLSOS NO USA AC "
Protected Sub DdlPersonal2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlPersonalReembolso.SelectedIndexChanged
ViewState("CvePersonal") = DdlPersonalReembolso.SelectedValue
If DdlPersonalReembolso.SelectedValue.ToEntero > 0 Then
EstaAsociadoAPersonal = True
End If
End Sub
Protected Sub DdlCajaChica2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlCuentaCajaChicaReembolso.SelectedIndexChanged
Dim dr As DataRow = GlobalDTBancosCuentas(UsuarioActual.CveUsuario, CveEmpresa:=UsuarioActual.CveEmpresa).FiltroPrimero("CveCuenta = " & DdlCuentaCajaChicaReembolso.SelectedValue)
If dr IsNot Nothing Then
CveMoneda = dr("CveMoneda").ToString.ToEntero
IdCuentaBancaria = dr("IdCtaContable").ToString.ToEntero
EstaAsociadoACajaChica = True
End If
ViewState("CveCajaChica") = DdlCuentaCajaChicaReembolso.SelectedValue
End Sub
#End Region
#Region " ALMACEN "
#End Region
#Region " CONSIGNACIONES "
Protected Sub ChkConsignacion_CheckedChanged(sender As Object, e As EventArgs)
If ChkConsignacion.Checked Then
'LiConsignacion.Visible = True
GvInv.Columns(7).Visible = True
GvInv.Columns(8).Visible = True
CargaConsignaciones2()
CargaGvInv()
GvInv.HeaderRow.FCCheckBox("cbAll").Checked = True
GvInv.HeaderRow.FCCheckBox("cbAll").Enabled = False
BtnVinculaConsignacion.Visible = True
BtnGuardar.Enabled = False
UpFacturar.Update()
Else
GvInv.Columns(7).Visible = False
GvInv.Columns(8).Visible = False
'LiConsignacion.Visible = False
CveConsignacion = -1
GvInv.HeaderRow.FCCheckBox("cbAll").Checked = False
GvInv.HeaderRow.FCCheckBox("cbAll").Enabled = True
BtnVinculaConsignacion.Visible = False
CargaGvInv()
BtnGuardar.Enabled = True
UpFacturar.Update()
End If
cbAll_CheckedChanged(GvInv.HeaderRow.FCCheckBox("cbAll"), EventArgs.Empty)
UpConsignaciones.Update()
End Sub
Private Sub CargaConsignaciones()
If DdlProveedor.SelectedValue.ToEntero > 0 Then
'Dim ObjInventarios As New ClsInventarios
'If ObjInventarios.GetConsignaciones2(-1, UsuarioActual.CveEmpresa) Then
' DdlConsignacion.DataSource = ObjInventarios.DtResultados.FiltraParametros(String.Format("CveProveedor = {0}", DdlProveedor.SelectedValue.ToEntero))
'Else
' DdlConsignacion.DataSource = Nothing
'End If
'ObjInventarios.Dispose()
'DdlConsignacion.DataBind()
'DdlConsignacion.Items.Insert(0, New ListItem("Seleccione", "-1"))
End If
End Sub
Private Sub CargaConsignaciones2()
Dim ObjInventarios As New ClsInventarios
Dim TieneError = False
CveConsignacion = -1
If ObjInventarios.GetConsignacionesDetalleProveedor(DdlProveedor.SelectedValue.ToEntero, UsuarioActual.CveEmpresa) Then
DtConsignaciones = ObjInventarios.DtResultados
Else
TieneError = True
End If
If DtConsignaciones IsNot Nothing AndAlso DtConsignaciones.Rows.Count > 0 Then
'CveConsignacion = DdlConsignacion.SelectedValue.ToEntero
CveConsignacion = 1
'CveAlmacenConsignacion = ObjInventarios.DtResultados.Rows(0)("CveAlmacen").ToString.ToEntero
End If
If TieneError Then
Alert("Ocurrió un error al cargar la consignación. Por favor vuelva a intentar.", TipoMensaje.MsgError)
DtConsignaciones = Nothing
End If
ObjInventarios.Dispose()
CargaGvInv()
End Sub
Protected Sub BtnVinculaConsignacion_Click(sender As Object, e As EventArgs)
Dim ObjInventarios As New ClsInventarios
Dim TieneError = False
CveConsignacion = -1
If ObjInventarios.GetConsignacionesDetalleProveedor(DdlProveedor.SelectedValue.ToEntero, UsuarioActual.CveEmpresa) Then
DtConsignaciones = ObjInventarios.DtResultados
Else
TieneError = True
End If
If DtConsignaciones.Rows.Count > 0 Then
'CveConsignacion = DdlConsignacion.SelectedValue.ToEntero
CveConsignacion = 1
CveAlmacenConsignacion = ObjInventarios.DtResultados.Rows(0)("CveAlmacen").ToString.ToEntero
End If
If TieneError Then
Alert("Ocurrió un error al cargar la consignación. Por favor vuelva a intentar.", TipoMensaje.MsgError)
DtConsignaciones = Nothing
End If
ObjInventarios.Dispose()
CargaGvInv()
'If DtConsignaciones IsNot Nothing Then
' GvConsignaciones.DataSource = DtConsignaciones
' GvConsignaciones.DataBind()
'End If
'UpConsignaciones.Update()
End Sub
Protected Sub GvConsignaciones_RowDataBound(sender As Object, e As GridViewRowEventArgs) 'Handles GvConsignaciones.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
e.Row.FCDropDownList("DdlVinculaConsignacion").DataSource = TmpDT
e.Row.FCDropDownList("DdlVinculaConsignacion").DataBind()
e.Row.FCDropDownList("DdlVinculaConsignacion").Items.Insert(0, New ListItem("Seleccione", "-1"))
End If
End Sub
Protected Sub DdlVinculaConsignacion_SelectedIndexChanged(sender As Object, e As EventArgs)
Dim Ddl As DropDownList = DirectCast(sender, DropDownList)
Dim gvr As GridViewRow = DirectCast(Ddl.BindingContainer, GridViewRow)
If Ddl.SelectedValue = "-1" Then
gvr.FCHiddenField("HdnPS").Value = "-1"
gvr.FCHiddenField("HdnCvePS").Value = "-1"
gvr.FCHiddenField("HdnClasificacion").Value = "-1"
gvr.FCHiddenField("HdnCveClasificacion").Value = "-1"
gvr.FCHiddenField("HdnCveAlmacen").Value = "-1"
gvr.FCHiddenField("HdnNoConsignacion").Value = "-1"
gvr.FCHiddenField("HdnCveConsignacion").Value = "-1"
'GUARDA VALORES POR UNA RECARGA (DIVISION DE CONCEPTO)
TmpDT.Rows(gvr.RowIndex)("CveAlmacenConsignacion") = "-1"
TmpDT.Rows(gvr.RowIndex)("NoConsignacion") = "-1"
TmpDT.Rows(gvr.RowIndex)("CveConsignacion") = "-1"
TmpDT.Rows(gvr.RowIndex)("HdnPS") = "-1"
TmpDT.Rows(gvr.RowIndex)("HdnCvePS") = "-1"
TmpDT.Rows(gvr.RowIndex)("HdnClasificacion") = "-1"
TmpDT.Rows(gvr.RowIndex)("HdnCveClasificacion") = "-1"
TmpDT.Rows(gvr.RowIndex)("HdnCveAlmacen") = "-1"
Exit Sub
End If
Dim Row = DtConsignaciones.Rows(Ddl.SelectedValue.ToEntero - 1)
'VALIDAMOS CANTIDAD
Dim Cantidad = Row("Cantidad").ToString.ToDecimal
For Each gvr1 As GridViewRow In GvInv.Rows
If gvr1.FCHiddenField("HdnNoConsignacion").Value.ToString = Ddl.SelectedValue Then
Cantidad = Cantidad - gvr1.DataKey("Cantidad").ToString.ToDecimal
End If
Next
If Cantidad - gvr.DataKey("Cantidad").ToString.ToDecimal < 0 Then
Ddl.SelectedValue = "-1"
gvr.FCHiddenField("HdnPS").Value = "-1"
gvr.FCHiddenField("HdnCvePS").Value = "-1"
gvr.FCHiddenField("HdnClasificacion").Value = "-1"
gvr.FCHiddenField("HdnCveClasificacion").Value = "-1"
gvr.FCHiddenField("HdnCveAlmacen").Value = "-1"
gvr.FCHiddenField("HdnNoConsignacion").Value = "-1"
gvr.FCHiddenField("HdnCveConsignacion").Value = "-1"
'GUARDA VALORES POR UNA RECARGA (DIVISION DE CONCEPTO)
TmpDT.Rows(gvr.RowIndex)("CveAlmacenConsignacion") = "-1"
TmpDT.Rows(gvr.RowIndex)("NoConsignacion") = "-1"
TmpDT.Rows(gvr.RowIndex)("CveConsignacion") = "-1"
TmpDT.Rows(gvr.RowIndex)("HdnPS") = "-1"
TmpDT.Rows(gvr.RowIndex)("HdnCvePS") = "-1"
TmpDT.Rows(gvr.RowIndex)("HdnClasificacion") = "-1"
TmpDT.Rows(gvr.RowIndex)("HdnCveClasificacion") = "-1"
TmpDT.Rows(gvr.RowIndex)("HdnCveAlmacen") = "-1"
Alert("El concepto que desea vincular excede la cantidad del inventario de consignación.", TipoMensaje.MsgAdvertencia)
Else
gvr.FCHiddenField("HdnPS").Value = Row("PS").ToString
gvr.FCHiddenField("HdnCvePS").Value = Row("CvePS").ToString
gvr.FCHiddenField("HdnClasificacion").Value = Row("Clasificacion").ToString
gvr.FCHiddenField("HdnCveClasificacion").Value = Row("CveClasificacion").ToString
gvr.FCHiddenField("HdnCveAlmacen").Value = Row("CveAlmacenSalida").ToString
gvr.FCHiddenField("HdnNoConsignacion").Value = Ddl.SelectedValue.ToEntero.ToString
gvr.FCHiddenField("HdnCveConsignacion").Value = Row("CveConsignacion").ToString
'GUARDA VALORES POR UNA RECARGA (DIVISION DE CONCEPTO)
TmpDT.Rows(gvr.RowIndex)("CveAlmacenConsignacion") = gvr.FCDropDownList("ddlAlmacenConsignacion").SelectedValue.ToEntero
TmpDT.Rows(gvr.RowIndex)("NoConsignacion") = Ddl.SelectedValue.ToEntero
TmpDT.Rows(gvr.RowIndex)("CveConsignacion") = Row("CveConsignacion").ToString
TmpDT.Rows(gvr.RowIndex)("HdnPS") = Row("PS").ToString
TmpDT.Rows(gvr.RowIndex)("HdnCvePS") = Row("CvePS").ToString
TmpDT.Rows(gvr.RowIndex)("HdnClasificacion") = Row("Clasificacion").ToString
TmpDT.Rows(gvr.RowIndex)("HdnCveClasificacion") = Row("CveClasificacion").ToString
TmpDT.Rows(gvr.RowIndex)("HdnCveAlmacen") = Row("CveAlmacenSalida").ToString
End If
End Sub
Protected Sub ddlAlmacenConsignacionGeneral_SelectedIndexChanged(sender As Object, e As EventArgs)
Dim DdlAlmacenConsignacionGeneral = CType(sender, DropDownList)
For Each gvr As GridViewRow In GvInv.Rows
gvr.FCDropDownList("ddlAlmacenConsignacion").SelectedValue = DdlAlmacenConsignacionGeneral.SelectedValue
gvr.FCDropDownList("ddlVinculaConsignacion").DataSource = DtConsignaciones.FiltraParametros(String.Format("CveAlmacenSalida = {0} OR {0} = '-1'", gvr.FCDropDownList("ddlAlmacenConsignacion").SelectedValue))
gvr.FCDropDownList("ddlVinculaConsignacion").DataBind()
gvr.FCDropDownList("ddlVinculaConsignacion").Items.Insert(0, New ListItem("Seleccione", "-1"))
Next
UpINV.Update()
End Sub
Protected Sub ddlAlmacenConsignacion_SelectedIndexChanged(sender As Object, e As EventArgs)
Dim DdlAlmacenConsignacion = CType(sender, DropDownList)
Dim DdlVinculaConsignacion = CType(CType(sender, DropDownList).NamingContainer, GridViewRow).FCDropDownList("DdlVinculaConsignacion")
''CARGA CONSIGNACIONES
DdlVinculaConsignacion.DataSource = DtConsignaciones.FiltraParametros(String.Format("CveAlmacenSalida = {0} OR {0} = '-1'", DdlAlmacenConsignacion.SelectedValue))
DdlVinculaConsignacion.DataBind()
DdlVinculaConsignacion.Items.Insert(0, New ListItem("Seleccione", "-1"))
UpINV.Update()
End Sub
Protected Sub BtnVinculaConsignacion_Click1(sender As Object, e As EventArgs)
'VALIDACIONES
For Each gvr As GridViewRow In GvInv.Rows
If gvr.FCDropDownList("DdlVinculaConsignacion").SelectedValue = "-1" Then
Alert("Debe vincular todos los conceptos para realizar la vinculación de consignación.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
Next
'CambiaPS
For Each gvr As GridViewRow In GvInv.Rows
TmpDT.Rows(gvr.RowIndex)("PS") = gvr.FCHiddenField("HdnPS").Value
TmpDT.Rows(gvr.RowIndex)("CvePS") = gvr.FCHiddenField("HdnCvePS").Value
TmpDT.Rows(gvr.RowIndex)("Clasificacion") = gvr.FCHiddenField("HdnClasificacion").Value
TmpDT.Rows(gvr.RowIndex)("CveClasificacion") = gvr.FCHiddenField("HdnCveClasificacion").Value
Next
GvPS.DataSource = TmpDT
GvPS.DataBind()
UpPS.Update()
'Bloqueamos todo para respetar cambios realizados
DtInv = TmpDT
ChkConsignacion.Enabled = False
BtnVinculaConsignacion.Enabled = False
UpConsignaciones.Update()
GvInv.Enabled = False
UpINV.Update()
GvInv.HeaderRow.FCCheckBox("cbAll").Checked = True
cbAll_CheckedChanged(GvInv.HeaderRow.FCCheckBox("cbAll"), EventArgs.Empty)
BtnGuardar.Enabled = True
UpFacturar.Update()
End Sub
#End Region
#Region " ***** Devoluciones INV ***** "
'*se envia true si hubo un error*'
Private Function guardardevolucion(ObjInventario As ClsInventarios, CveCompra As Integer, subtotal As Decimal, Fecha As Date) As MMensajeDevolucion
Dim TotalSumaPU As Decimal = 0
Dim ErrorMovInv As Boolean = False
Dim CveAlmacen As Integer = DdlAlmacenDevolucion.SelectedValue.ToEntero()
Dim subtotaldevolucion As Decimal = 0
Dim realizadevolucion As Boolean = False
Dim CveMovimientoEntrada As Integer = -1
'Calculo los subtotales para comparar con la NC
Dim Cantidad As Decimal
For Each Dr As GridViewRow In GVDevolucion.Rows
'CveAlmacen = Dr.DataKey("CveAlmacen").ToString.ToEntero
cantidad = Dr.FCTextBox("TxtCantidad").Text.ToDecimal
If cantidad > 0 Then
realizadevolucion = True
subtotaldevolucion += Dr.DataKey("PU").ToString.ToDecimal * cantidad
End If
Next
'si no esta vinculado a nc simplemente me lo brinco
If realizadevolucion Then
'si el subtotal es iwal a la nc lo guardo si no marco error
If subtotal > subtotaldevolucion - 1 AndAlso subtotal < subtotaldevolucion + 1 Then
CveMovimientoEntrada = ObjInventario.AddMovimiento(CveAlmacen, 13, 1, Fecha, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCompra, -1, -1, -1, Modulo:="Comp/G1")
If CveMovimientoEntrada <= 0 Then
ErrorMovInv = True
Else
Dim Acumulado As Decimal = 0
Dim PU As Decimal
Dim CantidadRenglones As Integer = 0
Dim ii As Integer = 0
For Each Dr As GridViewRow In GVDevolucion.Rows
If Dr.FCTextBox("TxtCantidad").Text.ToDouble > 0 Then
CantidadRenglones += 1
End If
Next
For Each Dr As GridViewRow In GVDevolucion.Rows
If Dr.FCTextBox("TxtCantidad").Text.ToDouble > 0 Then
Acumulado += (Dr.FCTextBox("TxtCantidad").Text.ToDecimal * Dr.DataKey("PU").ToString.ToDecimal)
PU = Dr.DataKey("PU").ToString.ToDecimal
ii += 1
If CantidadRenglones = ii Then
Dim dif As Decimal = subtotal - Acumulado
PU = (((Dr.FCTextBox("TxtCantidad").Text.ToDecimal * Dr.DataKey("PU").ToString.ToDecimal)) + dif) / Dr.FCTextBox("TxtCantidad").Text.ToDecimal
End If
If ObjInventario.GetExistenciasProducto(Dr.DataKey("CvePS").ToString.ToEntero, Dr.DataKey("CveUM").ToString.ToEntero, UsuarioActual.CveEmpresa, CveAlmacen,
FechaMovto:=TxtFecha.Text.ToDateTime.AddHours(Now.Hour).AddMinutes(Now.Minute).AddSeconds(Now.Second).ToString("yyyy/MM/dd HH:mm")) Then
Dim Existencia As Decimal = ObjInventario.DtResultados.FiltroPrimeroValor("ExistenciaFinal", String.Format("CveAlmacen = {0}", CveAlmacen)).ToDecimal
If Dr.FCTextBox("TxtCantidad").Text.ToDouble > Existencia Then
Alert($"No hay existencia suficiente del producto {Dr.DataKey("PS").ToString} en la fecha:{TxtFecha.Text}", TipoMensaje.MsgAdvertencia)
ErrorMovInv = True
Exit For
End If
Else
ErrorMovInv = True
Exit For
End If
If Not ObjInventario.AddMovimientoDetalle(CveMovimientoEntrada, Dr.FCTextBox("TxtCantidad").Text.ToDouble, Dr.DataKey("CveUM").ToString.ToEntero, Dr.DataKey("CvePS").ToString.ToEntero, PU, -1, CveMovimientoDetalleEntrada:=Dr.DataKey("CveMovimientoDetalle").ToString.ToEntero) Then
ErrorMovInv = True
Exit For
End If
End If
Next
End If
Else
ErrorMovInv = True
Alert("El Total de la NC debe ser igual al total de la devolucion", TipoMensaje.MsgAdvertencia)
End If
End If
If ObjInventario.GetMovimientosDetalle(CveMovimientoEntrada, UsuarioActual.CveEmpresa, -1, -1) Then
For Each drow As DataRow In ObjInventario.DtResultados.Rows
TotalSumaPU = TotalSumaPU + drow("Total").ToString.ToDecimal
Next
End If
Return New MMensajeDevolucion() With
{
.CveMovimiento = CveMovimientoEntrada,
.DebeRealizarDevolucion = realizadevolucion,
.TieneError = ErrorMovInv,
.Total = TotalSumaPU
}
End Function
Private Sub cargaddldevoluciones(CveProveedor As Integer, SubTotal As Double)
Dim objcompras As New ClsCompras()
If objcompras.GetCompraParaDevolucion(CveProveedor, UsuarioActual.CveEmpresa, SubTotal) Then
DDLDevolucion.Items.Clear()
DDLDevolucion.DataSource = objcompras.DtResultados
DDLDevolucion.DataBind()
DDLDevolucion.Items.Insert(0, New ListItem("Seleccione", "-1"))
End If
objcompras.Dispose()
UPDevolucion.Update()
End Sub
Protected Sub DDLDevolucion_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DDLDevolucion.SelectedIndexChanged
If DdlTipoComprobante.SelectedValue.Contiene("DEV") Then
DivAlmacenDev.Visible = True
End If
Dim objcompras As New ClsCompras()
If objcompras.GetCompraDetallealmacen(DDLDevolucion.SelectedValue.ToEntero) Then
GVDevolucion.DataSource = objcompras.DtResultados
GVDevolucion.DataBind()
End If
objcompras.Dispose()
Dim CveAlmacen As Integer = -1
For Each GvRow As GridViewRow In GVDevolucion.Rows
If GvRow.RowType = DataControlRowType.DataRow Then
CveAlmacen = GvRow.DataKey("CveAlmacen").ToString.ToEntero
End If
Next
DdlAlmacenDevolucion.SelectedValueExist(CveAlmacen)
UPDevolucion.Update()
End Sub
'Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
' cargaddldevoluciones(CveProveedor, TextBox1.Text.ToDouble)
'End Sub
'Protected Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
' Dim ObjInventario As New ClsInventarios()
' Dim cvecompra As Integer = 5221
' Dim subtotal As Double = TextBox1.Text.ToDouble
' guardardevolucion(ObjInventario, cvecompra, subtotal, Now.ToDate)
'End Sub
Protected Sub BtnVinculaDevolucion_Click(sender As Object, e As EventArgs)
Try
Dim subtotaldevolucion As Double = 0
Dim realizadevolucion As Boolean = False
'Calculo los subtotales para comparar con la NC
Dim cantidad As Double = 0.0
For Each Dr As GridViewRow In GVDevolucion.Rows
cantidad = Dr.FCTextBox("TxtCantidad").Text.ToDouble
If cantidad > 0 Then
realizadevolucion = True
subtotaldevolucion += Dr.DataKey("PU").ToString.ToDouble * cantidad
End If
Next
'si no esta vinculado a nc simplemente me lo brinco
If realizadevolucion Then
'si el subtotal es iwal a la nc lo guardo si no marco error
If TxtSubTotal2.Text.ToDouble > subtotaldevolucion - 1 AndAlso TxtSubTotal2.Text.ToDouble < subtotaldevolucion + 1 Then
VinculaDevolucion()
Else
Alert("El Total de la NC debe ser igual al total de la devolucion", TipoMensaje.MsgAdvertencia)
End If
Else
Alert("No se ha seleccionado nada para la devolución. Por favor rectifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia)
End If
Catch ex As Exception
OnError("Ocurrió un error al realizar la vinculación", ex)
End Try
End Sub
Private Sub VinculaDevolucion()
'LIMPIAR PARTIDAS DE LA COMPRA PARA AGREGAR NUEVAS
TmpDT.Clear()
Dim SubTotalCompra As Decimal = TxtSubTotal2.Text.ToDecimal()
Dim TotalCompra As Decimal = TxtTotal.Text.ToDecimal()
Dim IVACompra As Decimal = TxtIVA.Text.ToDecimal()
Dim IEPSCompra As Decimal = TxtIEPS.Text.ToDecimal()
Dim RetIVACompra As Decimal = TxtRetIVA.Text.ToDecimal()
Dim RetISRCompra As Decimal = TxtRetISR.Text.ToDecimal()
Dim Acumulado As Decimal = 0
'Dim TotalCalculable As Decimal = TotalCompra - IEPSCompra + RetIVACompra + RetISRCompra
Dim IVAPorcentajeCompra As Decimal = Math.Round((IVACompra / SubTotalCompra), 2)
Dim Contador As Integer = 0
Dim Consec As Integer = 0
For Each gvr As GridViewRow In GVDevolucion.Rows
If gvr.FCTextBox("TxtCantidad").Text.ToDecimal > 0 Then
Contador += 1
End If
Next
'Iteramos el GridView de la OC
For Each gvr As GridViewRow In GVDevolucion.Rows
If gvr.FCTextBox("TxtCantidad").Text.ToDecimal > 0 Then
Dim CvePS As Integer = gvr.DataKey("CvePS").ToString.ToEntero
Dim DrPS As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=CvePS).Rows(0)
Dim Cantidad As Decimal = gvr.FCTextBox("TxtCantidad").Text.ToDecimal
Dim CveUM As Integer = gvr.DataKey("CveUM").ToString.ToEntero
Dim UM As String = gvr.DataKey("UM").ToString
Dim CveClasificacion As Integer = gvr.DataKey("CveClasificacion").ToString.ToEntero
Dim Clasificacion As String = gvr.DataKey("Clasificacion").ToString
Dim PS As String = gvr.DataKey("PS").ToString
Dim CveTipoPS As Integer = gvr.DataKey("CveTipoPS").ToString.ToEntero
Dim CveSubProyectoContrato As String = "-1"
Dim CveProyecto As String = "-1"
Dim SubProyecto As String = "Seleccione"
Dim Proyecto As String = "Seleccione"
Dim Obs As String = ""
Dim PU As Decimal = gvr.DataKey("PU").ToString.ToDecimal
Dim Total As Decimal = gvr.FCTextBox("TxtTotalDevolucion").Text.ToDecimal
Dim IVA As Decimal = IVAPorcentajeCompra 'Math.Round(Total * IVAPorcentajeCompra, 2)
Dim Descuento As Decimal = 0
Acumulado += (PU * Cantidad)
Consec += 1
If Consec = Contador Then 'SubTotalCompra < Acumulado Then
'ajusta el valor
Dim dif As Decimal = SubTotalCompra - Acumulado
If dif <> 0 Then
PU = ((PU * Cantidad) + dif) / Cantidad
Total = Cantidad * PU
End If
End If
AddPS(Cantidad, CveUM, UM, CveClasificacion, Clasificacion, CvePS, PS, CveTipoPS, CveSubProyectoContrato, SubProyecto, Proyecto, CveProyecto, Obs, PU, Total, IVA, 0, 0, 0, 0, Descuento, -1, False)
End If
Next
AddPS2()
BtnGuardar.Enabled = True
If Not CierrePeriodo Then
BtnGuardar.Visible = True
End If
AlmacenCambiaPS.Visible = False
UpFacturar.Update()
TabGenerales.Enabled = True
Tab.ActiveTabIndex = 0
UpTabs.Update()
ImgClasificacion.Visible = False
LbAgregar.Visible = False
UpPSS.Update()
CargaGvInv()
GvPS.DataSource = TmpDT
GvPS.DataBind()
UpPS.Update()
CargaGVsAF()
CargaTipoCentroCostoOC()
GvOC1.DataSource = DTOCTemp
Dim DTCVEOCS As DataTable = DTOCTemp.FiltraParametros("", "", {"CveOrdenCompra"})
If DTCVEOCS IsNot Nothing AndAlso DTCVEOCS.Rows.Count > 1 Then
GvOC1.Columns(0).Visible = True
Else
GvOC1.Columns(0).Visible = False
End If
GvOC1.DataBind()
' TmpDT = OrdenarTablas("CvePS", DTOCTemp, TmpDT)
GvOC2.DataSource = TmpDT
GvOC2.DataBind()
UpGvOC1.Update()
NCDevolucion = True
''Bloquea cambio de proyecto
'DdlProyecto.Enabled = False
'DdlSubProyecto.Enabled = False
'UPPProyecto.Update()
'Bloquea cambio de OC ya que se concluyo alguna vinculacion
TxtOC.Enabled = False
ImgBtnBuscarOC.Visible = False
UpParametros.Update()
UpPSS.Update()
End Sub
#End Region
#Region " REFACTURACION "
Private Sub ValidaRefacturacion()
If Not CveCompra > 0 AndAlso DdlTipoComprobante.SelectedValue = "Fac" And UsuarioActual.Empresa.CvePlataforma <> 2 Then
VerRefacturacion.Visible = True
End If
End Sub
Protected Sub BtnRefacturacionVer_Click(sender As Object, e As EventArgs) Handles BtnRefacturacionVer.Click
Dim Opcion As Integer = 1
If UsuarioActual.CveEmpresa.Contiene(119, 1, 140) Then Opcion = 2
Dim ObjCompras As New ClsCompras
DdlRefacturacionFacturas.Items.Clear()
If ObjCompras.GetRefacturacion(CveProveedor, TxtSubTotal.Text.ToDecimal, TxtIVA.Text.ToDecimal, TxtTotal.Text.ToDecimal, Opcion, UsuarioActual.CveEmpresa) Then
DtRefacturacion = ObjCompras.DtResultados
DdlRefacturacionFacturas.DataSource = DtRefacturacion
Else
Alert("Ocurrió un error al obtener las facturas para refacturación. Por favor vuelva a intentar.", TipoMensaje.MsgError)
End If
ObjCompras.Dispose()
DivRefacturacion.Visible = True
DdlRefacturacionFacturas.DataBind()
DdlRefacturacionFacturas.SelectedValueExist(CveCompraRefacturacion)
DdlRefacturacionFacturas.Items.Insert(0, New ListItem("Seleccione", "-1"))
RegistraScript(String.Format("$('#{0}').modal('show')", DivRefacturacion.ClientID))
UpRefacturacion.Update()
End Sub
Private Sub DdlRefacturacionFacturas_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlRefacturacionFacturas.SelectedIndexChanged
SubTotalRefacturacion = 0.0D
If DdlRefacturacionFacturas.SelectedValue.ToEntero > 0 Then
Dim dr As DataRow = DtRefacturacion.FiltroPrimero(String.Format("CveCompra ={0}", DdlRefacturacionFacturas.SelectedValue))
If dr IsNot Nothing Then
HdnRefacturacionConcepto.Value = dr("CveConceptoContableAlmacen").ToString
ChkRefacturacionConAlmacen.Checked = If(dr("CveMovimientoAlmacen").ToString.ToEntero > 0, True, False)
SubTotalRefacturacion = dr("SubTotal").ToString.ToDecimal
End If
End If
End Sub
Protected Sub BtnRefacturacionAplicaFactura_Click(sender As Object, e As EventArgs) Handles BtnRefacturacionAplicaFactura.Click
TxtDescripcion.Text = String.Format("Refacturacion: {0}", DtRefacturacion.Rows(DdlRefacturacionFacturas.SelectedIndex - 1)("Descripcion"))
TxtFechaPago.Text = DtRefacturacion.Rows(DdlRefacturacionFacturas.SelectedIndex - 1)("FechaVencimiento").ToString.ToDate.ToShortDateString
For Each Dr As DataRow In TmpDT.Rows
Dr("CveSubProyecto") = DtRefacturacion.Rows(DdlRefacturacionFacturas.SelectedIndex - 1)("CveSubProyecto").ToString.ToEntero
Dr("SubProyecto") = DtRefacturacion.Rows(DdlRefacturacionFacturas.SelectedIndex - 1)("SubProyecto").ToString
Dr("CveProyecto") = DtRefacturacion.Rows(DdlRefacturacionFacturas.SelectedIndex - 1)("CveProyecto").ToString.ToEntero
Dr("Proyecto") = DtRefacturacion.Rows(DdlRefacturacionFacturas.SelectedIndex - 1)("Proyecto").ToString
Next
TrFacturaRefacturar.Visible = True
LtFacturaRefacturar.Text = DdlRefacturacionFacturas.SelectedItem.Text
CveCompraRefacturacion = DtRefacturacion.Rows(DdlRefacturacionFacturas.SelectedIndex - 1)("CveCompra").ToString.ToEntero
GvPS.DataSource = TmpDT
GvPS.DataBind()
'LIMPIA ALMACEN
For Each gvr As GridViewRow In GvInv.Rows
gvr.FCCheckBox("cbInv").Checked = False
Next
TabAlmacen.Enabled = False
UpRefacturacion.Update()
UpParametros.Update()
UpPS.Update()
UPCondicionesPago.Update()
UpTabs.Update()
RegistraScript(String.Format("$('#{0}').modal('hide')", DivRefacturacion.ClientID))
End Sub
Private Function GuardaRefacturacion(ByRef ObjCompra As ClsCompras, ByRef ObjEventos As ClsOIEventos, CvePrePoliza As Integer) As Boolean
Dim dr As DataRow = Nothing
Dim ErrorBitacora = False
Dim IdPolizaAnterior = -1
Dim TotalRefact As Decimal = 0
'SI NO TIENE POLIZA NI PAGOS NO HACE NADA
'If ObjCompra.GetCompras(CveCompraRefacturacion, "-1", "-1", -1, -1, UsuarioActual.CveEmpresa) Then
' If ObjCompra.DtResultados IsNot Nothing AndAlso ObjCompra.DtResultados.Rows.Count = 1 Then
' Dim drc As DataRow = ObjCompra.DtResultados.Rows(0)
' TotalRefact = drc("Total").ToString.ToDecimal
' If drc("IdPoliza").ToString.ToEntero <= 0 AndAlso drc("Saldo").ToString.ToDecimal = drc("Total").ToString.ToDecimal AndAlso drc("CveMovimiento").ToString.ToEntero <= 0 Then
' Alert("La factura a refacturar no esta contabilizada ni tiene pagos ni movimientos de almacen. No se puede refacturar, debera eliminar la factura anterior y agregar esta factura de forma normal.", TipoMensaje.MsgAdvertencia)
' Return True
' End If
' End If
'End If
'GUARDA ADJUNTOS Y LIGA EN BITACORA (RELACION DE FACTURA NUEVA Y VIEJA)
ErrorBitacora = GuardaRefacturacionBitacora(ObjCompra, ObjEventos)
If ObjCompra.GetCompras(CveCompraRefacturacion, "-1", "-1", -1, -1, UsuarioActual.CveEmpresa) Then
If ObjCompra.DtResultados IsNot Nothing AndAlso ObjCompra.DtResultados.Rows.Count > 0 Then
dr = ObjCompra.DtResultados.Rows(0)
IdPolizaAnterior = dr("IdPoliza").ToString.ToEntero
End If
End If
Dim Tipo As Integer = 1
If ChkRefacNC.Checked Then Tipo = 2
'CONTABILIZA REFACTURACION
If Not ObjCompra.Refacturacion(CveCompraRefacturacion, CveCompra, UsuarioActual.CveEmpresa, Tipo) Then
ErrorBitacora = True
End If
'Return True
Return ErrorBitacora
End Function
Private Function GuardaRefacturacionBitacora(ObjCompra As ClsCompras, ObjEventos As ClsOIEventos) As Boolean
Dim dr As DataRow = Nothing
Dim ErrorBitacora = False
Dim Archivo = ""
Dim Folio = ""
Dim Extension = ""
Dim Ruta = ""
'CARGA COMPRA REFACTURADA
If CveCompra > 0 AndAlso ObjCompra.GetCompras(CveCompraRefacturacion, "-1", "-1", -1, -1, UsuarioActual.CveEmpresa) Then
If ObjCompra.DtResultados IsNot Nothing AndAlso ObjCompra.DtResultados.Rows.Count > 0 Then
dr = ObjCompra.DtResultados.Rows(0)
'ADJUNTAMOS ARCHIVO XML
If Not ErrorBitacora Then
Archivo = String.Format("/Empresas/{0}/Compras/{1}/{2}", dr("CveEmpresa"), dr("RFC"), dr("XML"))
If File.Exists(Archivo) Then
Extension = Path.GetExtension(Archivo)
If Extension <> "" Then
If ObjEventos.AddEventoBitacora("XML de Refacturación:", Extension, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCompra:=CveCompra) Then
'OBTENEMOS RUTA DONDE GUARDAR | OPCIONAL: CREAMOS CARPETA
Ruta = String.Format("{0}OI", UsuarioActual.Empresa.Ruta)
Ruta.DirectoryExistsCreate()
'COPIAMOS EL ARCHIVO A OI
System.IO.File.Copy(Archivo, String.Format("{0}\OI{1}{2}", Ruta, ObjEventos.CveEvento.ToString, Extension))
Else
ErrorBitacora = True
End If
End If
End If
End If
'ADJUNTAMOS ARCHIVO PDF
If Not ErrorBitacora Then
Archivo = String.Format("/Empresas/{0}/Compras/{1}/{2}", dr("CveEmpresa"), dr("RFC"), dr("PDF"))
If File.Exists(Archivo) Then
Extension = Path.GetExtension(Archivo)
If Extension <> "" Then
If ObjEventos.AddEventoBitacora("PDF de Refacturación:", Extension, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCompra:=CveCompra) Then
'OBTENEMOS RUTA DONDE GUARDAR | OPCIONAL: CREAMOS CARPETA
Ruta = String.Format("{0}OI", UsuarioActual.Empresa.Ruta)
Ruta.DirectoryExistsCreate()
'COPIAMOS EL ARCHIVO A OI
System.IO.File.Copy(Archivo, String.Format("{0}\OI{1}{2}", Ruta, ObjEventos.CveEvento.ToString, Extension))
Else
ErrorBitacora = True
End If
End If
End If
End If
'LIGA AL FOLIO/COMPRA DE REFACTURACION
If Not ErrorBitacora Then
If Not ObjEventos.AddEventoBitacora(String.Format("Refacturación de: <a href=""/Compras/Compras.aspx?CveCompra={0}"" target=""_blank"">{1}</a>", CveCompraRefacturacion, dr("Folio").ToString), "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCompra:=CveCompra) Then
ErrorBitacora = True
End If
End If
End If
End If
'CARGA COMPRA ACTUAL
If Not ErrorBitacora Then
If ObjCompra.GetCompras(CveCompra, "-1", "-1", -1, -1, UsuarioActual.CveEmpresa) Then
If ObjCompra.DtResultados IsNot Nothing AndAlso ObjCompra.DtResultados.Rows.Count > 0 Then
dr = ObjCompra.DtResultados.Rows(0)
'ADJUNTAMOS ARCHIVO XML
If Not ErrorBitacora Then
Archivo = String.Format("/Empresas/{0}/Compras/{1}/{2}", dr("CveEmpresa"), dr("RFC"), dr("XML"))
If File.Exists(Archivo) Then
Extension = Path.GetExtension(Archivo)
If Extension <> "" Then
If ObjEventos.AddEventoBitacora("XML de Refacturación:", Extension, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCompra:=CveCompra) Then
'OBTENEMOS RUTA DONDE GUARDAR | OPCIONAL: CREAMOS CARPETA
Ruta = String.Format("{0}OI", UsuarioActual.Empresa.Ruta)
Ruta.DirectoryExistsCreate()
'COPIAMOS EL ARCHIVO A OI
System.IO.File.Copy(Archivo, String.Format("{0}\OI{1}{2}", Ruta, ObjEventos.CveEvento.ToString, Extension))
Else
ErrorBitacora = True
End If
End If
End If
End If
'ADJUNTAMOS ARCHIVO PDF
If Not ErrorBitacora Then
Archivo = String.Format("/Empresas/{0}/Compras/{1}/{2}", dr("CveEmpresa"), dr("RFC"), dr("PDF"))
If File.Exists(Archivo) Then
Extension = Path.GetExtension(Archivo)
If Extension <> "" Then
If ObjEventos.AddEventoBitacora("PDF de Refacturación:", Extension, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCompra:=CveCompra) Then
'OBTENEMOS RUTA DONDE GUARDAR | OPCIONAL: CREAMOS CARPETA
Ruta = String.Format("{0}OI", UsuarioActual.Empresa.Ruta)
Ruta.DirectoryExistsCreate()
'COPIAMOS EL ARCHIVO A OI
System.IO.File.Copy(Archivo, String.Format("{0}\OI{1}{2}", Ruta, ObjEventos.CveEvento.ToString, Extension))
Else
ErrorBitacora = True
End If
End If
End If
End If
'LIGA AL FOLIO/COMPRA EN REFACTURACION
If Not ErrorBitacora Then
If Not ObjEventos.AddEventoBitacora(String.Format("Refacturación en: <a href=""/Compras/Compras.aspx?CveCompra={0}"" target=""_blank"">{1}</a>", CveCompra, dr("Folio").ToString), "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCompra:=CveCompraRefacturacion) Then
ErrorBitacora = True
End If
End If
End If
End If
End If
Return ErrorBitacora
End Function
#End Region
#Region " CANCELAR COMPRA "
Private Sub ValidaCancelarCompra()
If UsuarioActual.TienePermisoProceso(140) Then
If CveMovimientoAlmacen > 0 And EstatusAlmacen = 2 Then
BtnCancelarCompra.Visible = True
Else
BtnCancelarCompra.Visible = True
End If
End If
End Sub
Protected Sub BtnCancelarCompra2_Click(sender As Object, e As EventArgs)
RegistraScript("$('#DivCancelarCompra').modal('hide');")
Dim ObjComprasComprobacion As New ClsCompras
If ObjComprasComprobacion.GetComprasPagosConciliados(CveCompra, UsuarioActual.CveEmpresa) Then
Dim TienePagosConciliados As Boolean = False
If ObjComprasComprobacion.DtResultados.Rows.Count > 0 Then
TienePagosConciliados = True
Dim PagosConciliados As New StringBuilder
For Each Drow As DataRow In ObjComprasComprobacion.DtResultados.Rows
PagosConciliados.AppendLine($"<a target='_blank' class='Texto' href=../Bancos/IE.aspx?CveIE={Drow("CveIE").ToString}>{Drow("Folio").ToString} </a> <br>")
Next
Alert($"La compra no se puede cancelar, tiene pagos conciliados: <br> {PagosConciliados.ToString}", TipoMensaje.MsgAdvertencia)
End If
If TienePagosConciliados Then
ObjComprasComprobacion.Dispose()
Exit Sub
End If
End If
ObjComprasComprobacion.Dispose()
Dim cvemovimientoentrada As Integer = -1
'DEVOLUCIÓN AUTOMATICA
If CheckDevAuto.Checked Then
Dim ErrorMovInv As Boolean = False
Dim folio As Integer
Dim fecha As Date = TxtFechaCancelacion.Text.ToDate
Dim importeconcepto As Decimal
Dim ObjInventario As New ClsInventarios
Dim ObjCompra As New ClsCompras
Dim tbmovs As DataTable = Nothing
Dim TmpDT As DataTable = Nothing
Dim TipoCambioGuardar As Decimal = 1
Dim tcvealmacen As Integer = 0
If ObjCompra.GetCompraDetalle(CveCompra) Then
If ObjCompra.DtResultados.Rows.Count > 0 Then
TmpDT = ObjCompra.DtResultados
End If
End If
If ObjInventario.GetInv_ComprasMov(CveCompra, UsuarioActual.CveEmpresa) Then
If ObjInventario.DtResultados.Rows.Count > 0 Then
tbmovs = ObjInventario.DtResultados
End If
End If
If DdlMoneda.SelectedValue.ToEntero > 1 Then
TipoCambioGuardar = If(DivTC.Visible, TxtTC.Text.ToDecimal, LblTC.Text.Substring(3).ToDecimal)
End If
TipoCambio = If(DivTC.Visible, TipoCambioGuardar, TipoCambio)
For Each dtMovs As DataRow In TmpDT.Rows
If TmpDT.Rows.Count > 0 Then
tcvealmacen = dtMovs("AlmacenRegistrado").ToString.ToEntero
Exit For
End If
Next
folio = ObjInventario.GetFolioSiguiente(13, UsuarioActual.CveEmpresa)
cvemovimientoentrada = ObjInventario.AddMovimiento(tcvealmacen, 13, 1, fecha, folio, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCompra, -1, -1, -1, TipoCambio:=If(DdlMoneda.SelectedValue.ToEntero = 1, -1, TipoCambioGuardar), Modulo:="Devolucion Automatica")
If cvemovimientoentrada <= 0 Then
ErrorMovInv = True
Else
For Each dr As DataRow In tbmovs.Rows
If dr("cvealmacen").ToString.ToEntero = tcvealmacen And dr("CveCompraDetalle").ToString.ToEntero <> -1 And dr("origen").ToString.ToEntero <> -1 And dr("Total").ToString.ToDecimal <> 0 Then
'hay que restarle descuento
importeconcepto = dr("Total").ToString.ToDecimal
If Not ObjInventario.AddMovimientoDetalle(cvemovimientoentrada, dr("cantidad").ToString.ToDouble, dr("cveum").ToString.ToEntero, dr("cveps").ToString.ToEntero, importeconcepto, -1, CveCompraDetalle:=dr("CveCompraDetalle").ToString.ToEntero, Serie:=dr("Serie").ToString) Then
ErrorMovInv = True
Exit Sub
End If
End If
Next
End If
If ErrorMovInv = True Then
ObjInventario.RollBack()
End If
ObjInventario.Dispose()
ObjCompra.Dispose()
End If
Dim ObjAC As ClsContPAQi = Nothing
If (UsuarioActual.Empresa.UsaAC Or UsuarioActual.Empresa.Funcionalidad(200).ToString = "1") AndAlso UsuarioActual.Empresa.TipoContabilidad = 2 Then
ObjAC = New ClsContPAQi(UsuarioActual.Empresa)
ObjAC.IniciaTransacSQL()
End If
Dim ObjCompras As New ClsCompras
Dim ObjContabilidad As New ClsContabilidad(ObjCompras.IniciaTransacSQL())
Dim ErrorCancelar = False
Dim IdPolizaNueva = -1
Dim FolioPolizaNueva = -1
Dim CvePrePolizaNueva = -1
Dim dt As DataTable
' MES ANTERIOR, MOVIMIENTOS CONTRARIOS (NEGATIVOS)
If True Then
'CREA POLIZA NEGATIVA
If IdPoliza > 0 AndAlso ObjAC IsNot Nothing AndAlso UsuarioActual.Empresa.UsaAC Then
If ObjAC.GetPoliza(IdPoliza, -1, -1, -1, -1) AndAlso ObjAC.DtResultados.Rows.Count > 0 Then
dt = ObjAC.DtResultados
IdPolizaNueva = ObjAC.AddPoliza(dt.Rows(0)("CodigoTipoPoliza").ToString.ToEntero, String.Format("Cancelacion: {0}", dt.Rows(0)("Concepto").ToString), 0, 0, UsuarioActual.CveUsuario, TxtFechaCancelacion.Text.ToDate)
If IdPolizaNueva > 0 Then
FolioPolizaNueva = ObjAC.Folio
For Each dr As DataRow In dt.Rows
If Not ObjAC.AddMovimiento(IdPolizaNueva, dr("IdCuenta").ToString.ToEntero, dr("TipoMovto").ToString = "True", dr("Importe").ToString.ToDecimal * -1, dr("Referencia").ToString, String.Format("Cancelacion: {0}", dt.Rows(0)("Concepto").ToString), dr("IdSegNeg").ToString.ToEntero, TxtFechaCancelacion.Text.ToDate, "") Then
ErrorCancelar = True : Exit For
End If
Next
'AJUSTA POLIZA
If Not ErrorCancelar Then
If Not ObjAC.AjustaPoliza(IdPolizaNueva) Then
ErrorCancelar = True
End If
End If
Else
ErrorCancelar = True
End If
Else
ErrorCancelar = True
End If
End If
'CREA PRE-POLIZA NEGATIVA
If DdlTipoComprobante.SelectedValue.Contiene("NC") Then
If ObjCompras.GetCancelarNC(CveCompra, UsuarioActual.CveEmpresa) Then
dt = ObjCompras.DtResultados
CvePrePolizaNueva = ObjContabilidad.AddPrePolizas("Compras/Cancelar", dt.Rows(0)("CvePlantillaPoliza").ToString.ToEntero, dt.Rows(0)("Cargos").ToString.ToDouble * -1, dt.Rows(0)("Abonos").ToString.ToDouble * -1, dt.Rows(0)("CveMoneda").ToString.ToEntero, TxtFechaCancelacion.Text.ToDate, String.Format("Cancelación: {0}", dt.Rows(0)("Concepto").ToString), UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa)
If CvePrePolizaNueva > 0 Then
For Each dr As DataRow In dt.Rows
If Not ObjContabilidad.AddPrePolizasDetalle(CvePrePolizaNueva, CBool(dr("TipoMovto").ToString), dr("Importe").ToString.ToDecimal * -1, dr("Referencia").ToString, dr("CveConceptoContable").ToString.ToEntero,
dr("Concepto").ToString, TxtFechaCancelacion.Text.ToDate, dr("IdCtaContable").ToString.ToEntero, dr("IdSegmentoNegocio").ToString.ToEntero, dr("CveIE").ToString.ToEntero,
dr("CveVenta").ToString.ToEntero, dr("CveCompra").ToString.ToEntero, dr("CveSubProyecto").ToString.ToEntero, dr("CveCliente").ToString.ToEntero, dr("CveProveedor").ToString.ToEntero, dr("CvePersonal").ToString.ToEntero,
dr("CveMovimientoAlmacen").ToString.ToEntero, dr("CveActivoFijo").ToString.ToEntero, -1, -1, dr("CveCreditoDetalle").ToString.ToEntero,
ImporteMX:=dr("Importe").ToString.ToDecimal * -1, ImporteME:=dr("Importe").ToString.ToDecimal * -1, CveTipoGasto:=dr("CveTipoGasto").ToString.ToEntero, CveClasificacion:=dr("CveClasificacion").ToString.ToEntero, CveOCDetalle:=dr("CveOCDetalle").ToString.ToEntero,
CveCompraAmortizacion:=dr("CveCompraAmortizacion").ToString.ToEntero) Then
ErrorCancelar = True
Exit For
End If
Next
Else
ErrorCancelar = True
End If
Else
ErrorCancelar = True
End If
Else
If CvePrePoliza > 0 Then
If ObjContabilidad.GetPrePolizasDetalle(CvePrePoliza, UsuarioActual.CveEmpresa) Then
dt = ObjContabilidad.DtResultados
CvePrePolizaNueva = ObjContabilidad.AddPrePolizas("Compras/Cancelar", dt.Rows(0)("CvePlantillaPoliza").ToString.ToEntero, dt.Rows(0)("Cargos").ToString.ToDouble * -1, dt.Rows(0)("Abonos").ToString.ToDouble * -1, dt.Rows(0)("CveMoneda").ToString.ToEntero, TxtFechaCancelacion.Text.ToDate, String.Format("Cancelación: {0}", dt.Rows(0)("Concepto").ToString), UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa)
If CvePrePolizaNueva > 0 Then
For Each dr As DataRow In dt.Rows
If Not ObjContabilidad.AddPrePolizasDetalle(CvePrePolizaNueva, CBool(dr("TipoMovto").ToString), dr("Importe").ToString.ToDecimal * -1, dr("Referencia").ToString, dr("CveConceptoContable").ToString.ToEntero,
dr("Concepto").ToString, TxtFechaCancelacion.Text.ToDate, dr("IdCtaContable").ToString.ToEntero, dr("IdSegmentoNegocio").ToString.ToEntero, dr("CveIE").ToString.ToEntero,
dr("CveVenta").ToString.ToEntero, dr("CveCompra").ToString.ToEntero, dr("CveSubProyecto").ToString.ToEntero, dr("CveCliente").ToString.ToEntero, dr("CveProveedor").ToString.ToEntero, dr("CvePersonal").ToString.ToEntero,
If(cvemovimientoentrada > 0, cvemovimientoentrada, dr("CveMovimientoAlmacen").ToString.ToEntero),
dr("CveActivoFijo").ToString.ToEntero, -1, -1, dr("CveCreditoDetalle").ToString.ToEntero,
ImporteMX:=dr("Importe").ToString.ToDecimal * -1, ImporteME:=dr("Importe").ToString.ToDecimal * -1,
CveTipoGasto:=dr("CveTipoGasto").ToString.ToEntero, CveClasificacion:=dr("CveClasificacion").ToString.ToEntero,
PorcentajeImpuesto:=dr("PorcentajeImpuesto").ToString.ToDecimal,
CveOCDetalle:=dr("CveOCDetalle").ToString.ToEntero) Then
ErrorCancelar = True
Exit For
End If
Next
Else
ErrorCancelar = True
End If
Else
ErrorCancelar = True
End If
End If
End If
'MES ACTUAL
Else
'LIMPIA POLIZA PONIENDO IMPORTE EN CEROS
If IdPoliza > 0 AndAlso ObjAC IsNot Nothing Then
If ObjAC.GetPoliza(IdPoliza, -1, -1, -1, -1) AndAlso ObjAC.DtResultados.Rows.Count > 0 Then
dt = ObjAC.DtResultados
For Each dr As DataRow In dt.Rows
If Not ObjAC.UpdateMovimiento(dr("Id").ToString.ToEntero, dr("IdCuenta").ToString.ToEntero, dr("TipoMovto").ToString = "1", 0, dr("Referencia").ToString, dr("Concepto").ToString, dr("IdSegNeg").ToString.ToEntero, dr("Fecha").ToString.ToDate) Then
ErrorCancelar = True : Exit For
End If
Next
'AJUSTA POLIZA
If Not ErrorCancelar Then
If Not ObjAC.AjustaPoliza(IdPoliza) Then
ErrorCancelar = True
End If
End If
Else
ErrorCancelar = True
End If
End If
'LIMPIA PRE-POLIZA PONIENDO IMPORTE EN CEROS
If CvePrePoliza > 0 Then
If ObjContabilidad.GetPrePolizasDetalle(CvePrePoliza, UsuarioActual.CveEmpresa) Then
dt = ObjContabilidad.DtResultados
For Each dr As DataRow In dt.Rows
If Not ObjContabilidad.UpdatePrePolizasDetalle(dr("CvePrePolizaDetalle").ToString.ToEntero, dr("Concepto").ToString, dr("CveSubProyecto").ToString.ToEntero, dr("IdCtaContable").ToString.ToEntero, CBool(dr("TipoMovto").ToString), 0, CveUsuarioModifico:=UsuarioActual.CveUsuario) Then
ErrorCancelar = True : Exit For
End If
Next
Else
ErrorCancelar = True
End If
End If
End If
'CANCELA COMPRA
If Not ErrorCancelar Then
If Not ObjCompras.UpdateEstatusCompra(CveCompra, -2) Then
ErrorCancelar = True
End If
End If
If Not ErrorCancelar Then
If ObjAC IsNot Nothing Then
ObjAC.Commit()
End If
ObjCompras.Commit()
Dim Msg As New StringBuilder
Msg.Append("La compra se cancelo correctamente.")
If IdPolizaNueva > 0 Then Msg.AppendFormat("<br/><br/><a class=""Texto"" target='_blank' href=""/Contabilidad/RegPoliza.aspx?IdPoliza={0}"">Ver Póliza de cancelación</a>", IdPolizaNueva)
Alert(Msg.ToString, TipoMensaje.MsgInformacion)
Else
If ObjAC IsNot Nothing Then
ObjAC.RollBack()
End If
ObjCompras.RollBack()
Alert("La compra no se pudo cancelar. Por favor vuelva a intentar.", TipoMensaje.MsgError)
End If
ObjCompras.Dispose()
If ObjAC IsNot Nothing Then
ObjAC.Dispose()
End If
End Sub
Private Sub btnProrateo_Click(sender As Object, e As EventArgs) Handles btnProrateo.Click, btnProrateo2.Click
Dim IvaOriginal As Double = TxtIVA.Text.ToDouble
Dim CuentaContable = DirectCast(sender, Button).CommandArgument.ToString
Select Case CuentaContable
Case "Compras"
StringProrrateo = UsuarioActual.Empresa.Funcionalidad(117)
Case "Nomina"
StringProrrateo = UsuarioActual.Empresa.Funcionalidad(303)
End Select
Dim porcentajes As String() = StringProrrateo.Split(New Char() {";"c})
Dim prtDT As DataTable = TmpDT.Copy
Dim GBSP As DataTable = GlobalDTSubProyectos(DdlProyecto.SelectedValue.ToString.ToEntero, CveEmpresa:=UsuarioActual.CveEmpresa)
TmpDT.Clear()
Dim subtotal As Decimal = TxtSubTotal.Text.ToDecimal
Dim subtotal2 As Decimal = TxtSubTotal2.Text.ToDecimal
Dim des As Decimal = TxtDescuento.Text.ToDecimal
Dim ivaa As Decimal = TxtIVA.Text.ToDecimal
TxtSubTotal.Text = "0.00"
TxtSubTotal2.Text = "0.00"
If CveFactura = 0 Then
TxtDescuento.Text = "0.00"
TxtIVA.Text = "0.00"
End If
For Each dr As DataRow In prtDT.Rows
Dim CveUM As Integer = dr("CveUM").ToString.ToEntero
Dim UM As String = dr("UM").ToString
Dim CveClasificacion As Integer = dr("CveClasificacion").ToString.ToEntero
Dim Clasificacion As String = dr("Clasificacion").ToString
Dim CvePS As Integer = dr("CvePS").ToString.ToEntero
Dim PS As String = dr("PS").ToString
Dim CveTipoPS As Integer = dr("CveTipoPS").ToString.ToEntero
Dim Proyecto As String = dr("Proyecto").ToString
Dim Obs As String = dr("Obs").ToString
Dim PU As Decimal = dr("PU").ToString.ToDecimal
Dim IVA As Decimal = dr("IVA").ToString.ToDecimal
Dim RetIVA As Decimal = dr("RetIVA").ToString.ToDecimal
Dim RetISR As Decimal = dr("RetISR").ToString.ToDecimal
Dim IEPSPS As Decimal = dr("IEPSPSPorcentaje").ToString.ToDecimal
Dim IEPSPSIVA As Decimal = If(dr("IEPSGrabaIVA").ToString = "True", dr("IEPSPorcentaje").ToString.ToDecimal, 0)
Dim Descuento As Decimal = dr("Descuento").ToString.ToDecimal
Dim CveOrdenCompraDetalle As Integer = dr("CveOrdenCompraDetalle").ToString.ToEntero
For Each cadena As String In porcentajes
Dim valores As String() = cadena.Split(New Char() {","c})
Dim Cantidad As Decimal = dr("Cantidad").ToString.ToDecimal * (valores(1).ToDecimal / 100)
Dim CveSubProyectoContrato As String = valores(0)
Dim CveProyecto As String = valores(0)
Dim Total As Decimal = Cantidad * PU
Dim drT As DataRow = GBSP.FiltroPrimero(String.Format("CveSubProyecto = {0} ", CveSubProyectoContrato))
Dim drq As DataRow = GBSP.FiltroPrimero(String.Format("CveProyecto = {0} ", CveProyecto))
Dim SubProyecto As String = drT("SubProyecto").ToString
AddPS(Cantidad, CveUM, UM, CveClasificacion, Clasificacion, CvePS, PS, CveTipoPS, CveSubProyectoContrato, SubProyecto, Proyecto, CveProyecto, Obs, PU, Total, IVA, RetIVA, RetISR, IEPSPS, IEPSPSIVA, Descuento, CveOrdenCompraDetalle:=CveOrdenCompraDetalle)
Next
Next
AddPS2()
AjustaImporteUltimoConcepto(subtotal2 - TmpDT.SUM("Total").ToString.ToDecimal)
TxtIVA.Text = IvaOriginal.ToString
CalculaTotales(True)
LbAgregar.Visible = False
UpPSS.Update()
prtDT = TmpDT.Copy
prtDT.Clear()
End Sub
Private Sub BtnValesCombustibleVer_Click(sender As Object, e As EventArgs) Handles BtnValesCombustibleVer.Click
Dim AF As New ClsAF
If AF.GetValesCombustible(-1, -1, -1, CveProveedor, -1, -1, -1, -1, -1, -1, -1, UsuarioActual.CveEmpresa, -1, -1) Then
GvVales.DataSource = AF.DtResultados
End If
AF.Dispose()
GvVales.DataBind()
DivValesCombustible.Visible = True
RegistraScript(String.Format("$('#{0}').modal('show')", DivValesCombustible.ClientID))
UPPValesCombustible.Update()
End Sub
#End Region
#Region " VALES COMBUSTIBLES "
Protected Sub BtnValesVincular_Click(sender As Object, e As EventArgs)
IdVale = New List(Of Integer)
For Each row As GridViewRow In GvVales.Rows
If row.FCCheckBox("ChkVale").Checked Then
IdVale.Add(row.DataKey("CveVale").ToEntero)
End If
Next
If IdVale.Count <= 0 Then
Alert("Debe elegir por lo menos un vale de combustible. Por favor rectifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia)
Else
Alert("Los vales selecciondos están listos para vincular")
RegistraScript(String.Format("$('#{0}').modal('hide')", DivValesCombustible.ClientID))
'For Each cve In IdVale
' Alert(cve.ToString)
'Next
End If
End Sub
#End Region
#Region " VINCULAR OC "
Private Sub InicializaOC()
'BORRAR OC
'TabOC.Visible = False
TabOC.Visible = False
EmpresasOC = New List(Of Integer)
''TODAS LAS EMPRESAS LO TIENEN Y LA 66 SOLO LOS USUARIOS DE ABAJO - EMPRESA QUE ESTE EN LA LISTA NO TENDRA NUEVO ESQUEMA
'If UsuarioActual.CveEmpresa = 66 AndAlso Not UsuarioActual.CveUsuario.Contiene(1434, 1436, 1337, 1440) Then
' EmpresasOC.Add(UsuarioActual.CveEmpresa)
'End If
'If Not EmpresasOC.Contains(UsuarioActual.CveEmpresa) Then
TabOC.Visible = True
'Else
'TabOC.Visible = True
'End If
If Not UsuarioActual.TienePermisoProceso(242) Then
DdlOCVinculaInv.Items.RemoveAt(2)
DdlOCVinculaInv.Items.RemoveAt(3)
End If
End Sub
Protected Sub BtnBuscarOC_Click(sender As Object, e As EventArgs) Handles BtnBuscarOC.Click
PopUpOC = False
CargaOC()
End Sub
Protected Sub CargaVOC(sender As Object, e As EventArgs)
PopUpOC = True
CargaOC()
End Sub
Private Sub CargaOC()
Dim EntregaDirecta = 0
DivOCSolicitudAnticipo.Visible = False
DivOCSolicitudAnticipoModal.Visible = False
If CveProveedor <= 0 Then
Alert("Debe de Seleccionar un proveedor")
Exit Sub
End If
'BANDERA DE SURTIDO
If UsuarioActual.Empresa.Funcionalidad(131).ToEntero > 0 Then
GvOC1.Columns(1).Visible = True
End If
Dim CvesOC = ""
If PopUpOC Then
CvesOC = HdnVCveOC.Value
End If
HdnVCveOC.Value = ""
HdnCveEstatusOC.Value = ""
Dim OC As New ClsOC
If PopUpOC Then
Dim ArrayCveOC As String() = CvesOC.Split(New Char() {","c})
For i As Integer = 0 To ArrayCveOC.Count - 1
If OC.GetOrdenesCompraRep("OC", -1, -1, -1, -1, MinFecha, MaxFecha, ArrayCveOC(i).ToEntero, CveProveedor, -1, -1, -1, UsuarioActual.CveEmpresa, -1) Then
If OC.DtResultados.FiltraParametros("TipoTermino = 3").Rows.Count = 1 Or DdlTipoComprobante.SelectedValue.Contiene("NC", "DEV") Then
HdnVCveOC.Value += String.Format("{0}{1}", If(HdnVCveOC.Value <> "", ",", ""), OC.DtResultados.Rows(0)("CveOrdenCompra").ToString)
HdnCveEstatusOC.Value += String.Format("{0}{1}", If(HdnCveEstatusOC.Value <> "", ",", ""), OC.DtResultados.Rows(0)("CveEstatusSiguiente").ToString)
EntregaDirecta += If(OC.DtResultados.Rows(0)("EntregaDirecta").ToString = "True", 1, 0)
End If
End If
Next
Else
Dim TextoErrorOC = ""
Dim ArrayCveOC As String() = TxtOC.Text.Split(New Char() {","c})
For i As Integer = 0 To ArrayCveOC.Count - 1
If OC.GetOrdenesCompraRep("OC", -1, -1, -1, -1, MinFecha, MaxFecha, -1, CveProveedor, ArrayCveOC(i).ToEntero, -1, -1, UsuarioActual.CveEmpresa, -1) Then
If OC.DtResultados.Rows.Count > 1 Then
TextoErrorOC += $"<br/>El folio <b>{ArrayCveOC(i).ToEntero}</b> no se pudo identificar."
End If
If OC.DtResultados.FiltraParametros("TipoTermino = 3").Rows.Count = 1 Or DdlTipoComprobante.SelectedValue.Contiene("NC", "DEV") Then
HdnVCveOC.Value += String.Format("{0}{1}", If(HdnVCveOC.Value <> "", ",", ""), OC.DtResultados.Rows(0)("CveOrdenCompra").ToString)
HdnCveEstatusOC.Value += String.Format("{0}{1}", If(HdnCveEstatusOC.Value <> "", ",", ""), OC.DtResultados.Rows(0)("CveEstatusSiguiente").ToString)
EntregaDirecta += If(OC.DtResultados.Rows(0)("EntregaDirecta").ToString = "True", 1, 0)
End If
End If
Next
If TextoErrorOC <> "" Then
Alert($"Las siguientes Ordenes de Compra no se pudieron vincular automaticamente: <br/>{TextoErrorOC} <br/><br/> Sera necesario vincular de manera manual mediante busqueda (lupia).", TipoMensaje.MsgAdvertencia)
TxtOC.Text = ""
Exit Sub
End If
End If
OC.Dispose()
PopUpOC = False
If HdnVCveOC.Value <> "" Then
If HdnCveEstatusOC.Value = "" Then
Alert("No se tiene especificado el siguiente estatus de la Orden(es) de Compra. Por favor verifique los estatus y vuelva a intentar.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
VinculaOC()
If EntregaDirecta > 0 Then
Alert("Se identificó una Orden de Compra con entrega directa, por lo cual no se podra recibir en almacén desde este modulo, para esto es necesario recibir la mercancía desde la Orden de Compra.", TipoMensaje.MsgAdvertencia)
TabAlmacen.Visible = False
DivOCEntregaDirecta.Visible = True
End If
BtnGuardar.Enabled = False
TxtOC.Enabled = False
ImgBtnBuscarOC.Enabled = False
UpFacturar.Update()
Else
Alert("No se encontro ninguna Orden de Compra con el folio especificado.", TipoMensaje.MsgAdvertencia)
End If
UPPOC.Update()
UpPS.Update()
End Sub
Protected Sub BtnVOC_Click(sender As Object, e As EventArgs)
VinculaOC()
End Sub
Private Sub VinculaOC()
If TxtOC.Text <> "" Then
'VARIABLES
Dim TextoObservaciones = ""
LtOCPromocion.Text = ""
IvaAcumulado = 0
DTOCTemp = New DataTable
'SI NO ES UNA COMPRA REGISTRADA = ENABLE FALSE TAB GENERALES, ACTIVE TAB OC
If Not CveCompra > 0 Then
TabGenerales.Enabled = False
Tab.ActiveTabIndex = 2
UpTabs.Update()
End If
'CARGAMOS LOS DATOS DE LAS OC
Dim ObjOC As New ClsOC
Dim ArrayCveOC As String() = HdnVCveOC.Value.Split(New Char() {","c})
Dim FoliosOCAnticipo = "", FoliosOCAnticipoIE = ""
Dim StrPromos As New StringBuilder
For Each CveOCItem As String In ArrayCveOC.Distinct
If ObjOC.GetOrdenesDetalle(CveOCItem.ToEntero) AndAlso ObjOC.DtResultados.Rows.Count > 0 Then
If IsNothing(DTOCTemp) Then
DTOCTemp = ObjOC.DtResultados.Copy
Else
DTOCTemp.Merge(ObjOC.DtResultados)
End If
IvaAcumulado += ObjOC.DtResultados.Rows(0)("IVA").ToString.ToDouble
TextoObservaciones += ObjOC.DtResultados.Rows(0)("Descripcion").ToString
If ObjOC.DtResultados.Rows.Count > 0 Then
''MONEDA DIFERENTE
If ObjOC.DtResultados.Rows(0)("CveMoneda").ToString.ToEntero <> DdlMoneda.SelectedValue.ToEntero Then
DivTipoCambioOC.Visible = True
TxtTipoCambioOC.Text = GlobalTipoCambio(TxtFecha.Text.ToDate).ToString
BtnVincularOCCompleta.Visible = False
BtnVincularOC.Visible = False
End If
''SOLICITUD DE ANTICIPO
If ObjOC.DtResultados.Rows(0)("CveIEAnticipo").ToString.ToEntero > 0 Then
FoliosOCAnticipo += $"{ObjOC.DtResultados.Rows(0)("FolioOC").ToString},"
FoliosOCAnticipoIE += $"{ObjOC.DtResultados.Rows(0)("FolioIEAnticipo").ToString},"
DivOCSolicitudAnticipo.Visible = True
DivOCSolicitudAnticipoModal.Visible = True
End If
'PROMOCIONES
Dim Promocion = ObjOC.DtResultados.Rows(0)("Promocion").ToString
If Not String.IsNullOrEmpty(Promocion) Then
Dim FolioOC = ObjOC.DtResultados.Rows(0)("FolioOC").ToString
StrPromos.Append($"<b>OC #{FolioOC}</b> {Promocion} <br/> ")
StrPromos.AppendLine()
End If
End If
Else
Alert("Ocurrio un Error al cargar la(s) Orden(es) de Compra", TipoMensaje.MsgError)
If DTOCTemp IsNot Nothing Then DTOCTemp.Rows.Clear()
TextoObservaciones = ""
Exit Sub
End If
Next
ObjOC.Dispose()
'MOVIMIENTOS DE ALMACÉN
Dim ObjInventarios As New ClsInventarios
Dim FoliosOCAlmacen = ""
For Each CveOCItem As String In ArrayCveOC.Distinct
If ObjInventarios.GetMovimientosOC(CveOCItem.ToEntero, UsuarioActual.CveEmpresa) Then
If ObjInventarios.DtResultados.Rows.Count > 0 Then
FoliosOCAlmacen = $"{ObjInventarios.DtResultados.FiltroPrimeroValor("FolioOC")},"
End If
Else
Alert("Ocurrió un error al cargar los movimientos de almacén de la orden de compra", TipoMensaje.MsgError)
ObjInventarios.Dispose()
Exit Sub
End If
Next
ObjInventarios.Dispose()
If FoliosOCAlmacen.Length > 0 Then
DivOCAlmacen.Visible = True
LtOCAlmacen.Text = FoliosOCAlmacen.Substring(0, FoliosOCAlmacen.Length - 1)
End If
'SI PUEDE RECIBIR POR OC Y COMPRA
' si usa almacen, si tiene activado que reciba por OC, y que si la compra tipo Proveedor. que lo muestre
If UsuarioActual.Empresa.UsaInventarios And UsuarioActual.Empresa.Funcionalidad(131).ToEntero > 0 AndAlso CveTipoConcepto = 1 Then
DivOCVinculaInv.Visible = True
End If
'TIPO CAMBIO
If CveCompra > 0 Then
DivTipoCambioOC.Visible = False
End If
DTOCTemp.Columns.Add("PUTC", GetType(Decimal))
DTOCTemp.Columns.Add("TotalTC", GetType(Decimal))
DTOCTemp.Columns.Add("DescuentoTC", GetType(Decimal))
DTOCTemp.Columns.Add("IVATC", GetType(Decimal))
DTOCTemp.Columns.Add("IEPSPSTC", GetType(Decimal))
DTOCTemp.Columns.Add("IEPSPSIVATC", GetType(Decimal))
DTOCTemp.Columns.Add("RetIVATC", GetType(Decimal))
DTOCTemp.Columns.Add("RetISRTC", GetType(Decimal))
DTOCTemp.Columns.Add("FolioAlmacen", GetType(String))
For Each Dr As DataRow In DTOCTemp.Rows
Dr("PUTC") = Dr("Importe")
Dr("DescuentoTC") = Dr("Descuento")
Dr("IVATC") = Dr("IVA")
Dr("IEPSPSTC") = Dr("IEPSPS")
Dr("IEPSPSIVATC") = Dr("IEPSPSIVA")
Dr("RetIVATC") = Dr("RetIVA")
Dr("RetISRTC") = Dr("RetISR")
Dr("TotalTC") = Dr("ImporteAjustadoDescuento")
Next
'DESCRIPCION DE OC CUANDO NO ES COMPRA REGISTRADA
If Not CveCompra > 0 Then TxtDescripcion.Text = TextoObservaciones
'SOLICITUD DE ANTICIPO
If DivOCSolicitudAnticipo.Visible And FoliosOCAnticipo.Length > 0 Then
LtSolicitudAnticipoFoliosOC.Text = $"La(s) siguiente(s) OC: {FoliosOCAnticipo.Substring(0, FoliosOCAnticipo.Length - 1)}. tienen vinculado un anticipo"
LtSolicitudAnticipoFoliosIE.Text = $" {FoliosOCAnticipoIE.Substring(0, FoliosOCAnticipoIE.Length - 1)}"
End If
'PROMOCIONES
LtOCPromocion.Text = StrPromos.ToString
If LtOCPromocion.Text.Length > 0 And UsuarioActual.CveEmpresa = 119 Then
DivOCPromocion.Visible = True
End If
'CARGA DATOS DE OC
CargaVinculacionOC(True)
End If
End Sub
Protected Sub DdlOCVinculaInv_SelectedIndexChanged(sender As Object, e As EventArgs)
CargaVinculacionOC()
End Sub
Private Sub CargaVinculacionOC(Optional CargaInicial As Boolean = False)
'FILTRAMOS SOLO PENDIENTES POR SURTIR
DTOCGV = DTOCTemp.FiltraParametros("CantidadPendienteVincular > 0", "CveOrdenCompra").Copy
'SI PUEDE RECIBIR POR OC Y COMPRA
If UsuarioActual.CveEmpresa.Contiene(119) Then
If UsuarioActual.Empresa.UsaInventarios And UsuarioActual.Empresa.Funcionalidad(131).ToEntero > 0 Then
Select Case DdlOCVinculaInv.SelectedValue.ToEntero
Case 176
DTOCGV = DTOCGV.FiltraParametros("((EstatusInventario IN (3,5) AND CveTipoPS = 2) OR CveTipoPS = 1)")
Case 205
DTOCGV = DTOCGV.FiltraParametros("(EstatusInventario IN (1,2) AND CveTipoPS = 2) OR CveTipoPS = 1")
End Select
End If
End If
If DTOCGV.MAX("IVAPorcentaje").ToDecimal <> TmpDT.MAX("IVAPorcentaje").ToDecimal Then
Alert("La orden de compra(s) tiene diferentes tasa de IVA.", TipoMensaje.MsgAdvertencia)
End If
If DTOCGV.Rows.Count = 0 Then
Alert("La orden de compra no tiene nada pendiente por vincular. En caso de ser Entrega Directa por favor verifique el estatus de facturación.", TipoMensaje.MsgAdvertencia)
End If
CargaGvsOC()
CargaTotalesOC()
'Diferencia permitida $ entre OC y Compra
Dim DiferenciaPermitida = 1
'VINCULACION TOTAL
If CargaInicial And DivTipoCambioOC.Visible = False Then
If LbTotalOC1.Text = LbTotalOC2.Text AndAlso (UsuarioActual.CveEmpresa.Contiene(1, 4, 7, 11, 12, 48, 13, 66, 72, 80, 145)) AndAlso CveCompra <= 0 Then
BtnVincularOCCompleta.Visible = Not DivTipoCambioOC.Visible
Else
BtnVincularOCCompleta.Visible = False
End If
Else
If LbTotalOC1.Text = LbTotalOC2.Text AndAlso (UsuarioActual.CveEmpresa.Contiene(1, 4, 7, 11, 12, 48, 13, 66, 72, 80, 145)) AndAlso CveCompra <= 0 Then
BtnVincularOCCompleta.Visible = Not DivTipoCambioOC.Visible
Else
BtnVincularOCCompleta.Visible = False
End If
End If
UpOC.Update()
' If DdlOCVinculaInv.SelectedValue.ToEntero.Contiene(237, 240) Then CargaModalFletesImportaciones()
End Sub
Private Sub CargaTipoCentroCostoOC()
If UsuarioActual.Empresa.Tipo_CentroCosto = 1 Then
GvOC1.Columns(5).HeaderText = "Sucursal"
ElseIf UsuarioActual.Empresa.Tipo_CentroCosto = 2 Then
GvOC1.Columns(5).HeaderText = "Proyecto"
ElseIf UsuarioActual.Empresa.Tipo_CentroCosto = 4 Then
GvOC1.Columns(5).HeaderText = "Sucursal <br/> Proyecto"
ElseIf UsuarioActual.Empresa.Tipo_CentroCosto = 5 Then
GvOC1.Columns(5).HeaderText = "Proyecto <br/> Sucursal"
End If
End Sub
Private Sub CargaGvsOC()
'SI ES MAS DE UNA OC ORDENA POR PRODUCTO
Dim ArrayCveOC As String() = HdnVCveOC.Value.Split(New Char() {","c})
DTOCGV = If(ArrayCveOC.Length > 1, DTOCGV.FiltraParametros("", "Producto"), DTOCGV)
CargaTipoCentroCostoOC()
GvOC1.DataSource = DTOCGV
GvOC1.DataBind()
Dim DTCVEOGV As DataTable = DTOCGV.FiltraParametros("", "", {"CveOrdenCompra"})
If DTCVEOGV.Rows.Count > 1 Then
GvOC1.Columns(0).Visible = True
Else
GvOC1.Columns(0).Visible = False
End If
Dim Cont As Integer = 0
For Each gvr As GridViewRow In GvOC1.Rows
RegistraScript($"CalculaTotalOCEdit('{ gvr.DataKey("PS").Replace("'", "").Replace(vbLf, " ").Replace(vbCrLf, " ") }', {gvr.DataKey("Cantidad").ToString.ToDouble}, {gvr.FCTextBox("TxtCantidad").ClientID}, {gvr.FCTextBox("TxtPU").ClientID}, {gvr.FCTextBox("TxtTotalOC1").ClientID}, {gvr.DataKey("IEPSPS").ToString.ToDouble},{gvr.FCHiddenField("HdnOC1IEPSImporte").ClientID}, {gvr.DataKey("IVA").ToString.ToDouble},{gvr.FCHiddenField("HdnOC1IVA").ClientID},{gvr.DataKey("RetIVA").ToString.ToDouble},{gvr.FCHiddenField("HdnOC1RetIVA").ClientID},{gvr.DataKey("RetISR").ToString.ToDouble},{gvr.FCHiddenField("HdnOC1RetISR").ClientID},{gvr.DataKey("IEPSPS").ToString.ToDouble},{gvr.FCHiddenField("HdnOC1IEPSIVA").ClientID},{gvr.DataKey("Descuento")},{gvr.FCHiddenField("HdnOC1Descuento").ClientID},{gvr.DataKey("IVAPorcentaje").ToString.ToDouble},{gvr.DataKey("RetIVAPorcentaje").ToString.ToDouble},{gvr.DataKey("RetISRPorcentaje").ToString.ToDouble},{gvr.DataKey("IEPSPSPorcentaje").ToString.ToDouble},{gvr.DataKey("IEPSPSIVAPorcentaje").ToString.ToDouble});", $"Gv{Cont}")
Cont += 1
Next
UpGvOC1.Update()
TmpDT = TmpDT.FiltraParametros("", "PU")
GvOC2.DataSource = TmpDT
GvOC2.DataBind()
UpGvOC2.Update()
End Sub
Protected Sub GvOC1_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvOC1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim JSCambiaScript = $"CalculaTotalOCEdit('{e.Row.DBCampo("PS").Replace("'", "").Replace(vbLf, " ").Replace(vbCrLf, " ")}', {e.Row.DBCampo("Cantidad").ToString.ToDouble}, {e.Row.FCTextBox("TxtCantidad").ClientID}, {e.Row.FCTextBox("TxtPU").ClientID}, {e.Row.FCTextBox("TxtTotalOC1").ClientID}, {e.Row.DBCampo("IEPSPS").ToString.ToDouble},{e.Row.FCHiddenField("HdnOC1IEPSImporte").ClientID}, {e.Row.DBCampo("IVA").ToString.ToDouble},{e.Row.FCHiddenField("HdnOC1IVA").ClientID},{e.Row.DBCampo("RetIVA").ToString.ToDouble},{e.Row.FCHiddenField("HdnOC1RetIVA").ClientID},{e.Row.DBCampo("RetISR").ToString.ToDouble},{e.Row.FCHiddenField("HdnOC1RetISR").ClientID},{e.Row.DBCampo("IEPSPS").ToString.ToDouble},{e.Row.FCHiddenField("HdnOC1IEPSIVA").ClientID},{e.Row.DBCampo("Descuento")},{e.Row.FCHiddenField("HdnOC1Descuento").ClientID},{e.Row.DBCampo("IVAPorcentaje").ToString.ToDouble},{e.Row.DBCampo("RetIVAPorcentaje").ToString.ToDouble},{e.Row.DBCampo("RetISRPorcentaje").ToString.ToDouble},{e.Row.DBCampo("IEPSPSPorcentaje").ToString.ToDouble},{e.Row.DBCampo("IEPSPSIVAPorcentaje").ToString.ToDouble});"
e.Row.FCTextBox("TxtCantidad").Attributes.Add("onkeyup", $"LimitaCantidadOC({e.Row.DBCampo("CantidadPendienteVincular")}, this);{JSCambiaScript}")
e.Row.FCTextBox("TxtPU").Attributes.Add("onkeyup", JSCambiaScript)
e.Row.FCTextBox("TxtCantidad").Attributes.Add("onblur", $"ValidaImporteCero('{e.Row.DBCampo("PS").Replace("'", "")}',{e.Row.FCTextBox("TxtCantidad").ClientID}, {e.Row.FCTextBox("TxtPU").ClientID});")
e.Row.FCTextBox("TxtPU").Attributes.Add("onblur", $"ValidaImporteCero('{e.Row.DBCampo("PS").Replace("'", "")}',{e.Row.FCTextBox("TxtCantidad").ClientID}, {e.Row.FCTextBox("TxtPU").ClientID});")
RegistraScript(JSCambiaScript)
If e.Row.DataKey("FolioREQ").ToString.Trim.Length > 0 Then
Dim LblOC As Label = e.Row.FCLabel("LblOC")
LblOC.Attributes.Add("data-toggle", "tooltip")
LblOC.Attributes.Add("data-placement", "top")
LblOC.Attributes.Add("title", "REQ: " & e.Row.DataKey("FolioREQ").ToString)
End If
If e.Row.DBCampo("CveTipoPS").ToEntero = 2 And UsuarioActual.Empresa.Funcionalidad(131).ToEntero > 0 Then
Select Case e.Row.DBCampo("EstatusInventario").ToEntero
Case 1
e.Row.FCLabel("LbEstatusInv").Text = "<i Class='fa fa-flag-o' aria-hidden='true'></i>"
e.Row.FCLabel("LbEstatusInv").ForeColor = Drawing.Color.Red
Case 2
e.Row.FCLabel("LbEstatusInv").Text = "<i Class='fa fa-flag-checkered' aria-hidden='true'></i>"
e.Row.FCLabel("LbEstatusInv").ForeColor = Drawing.Color.DarkOrange
Case 3
e.Row.FCLabel("LbEstatusInv").Text = "<i Class='fa fa-flag' aria-hidden='true'></i>"
e.Row.FCLabel("LbEstatusInv").ForeColor = Drawing.Color.Green
Case Else
e.Row.FCLabel("LbEstatusInv").Text = "ERR"
End Select
ElseIf e.Row.DBCampo("CveTipoPS").ToEntero = 1 And UsuarioActual.Empresa.Funcionalidad(131).ToEntero > 0 Then
e.Row.FCLabel("LbEstatusInv").Text = "NA"
End If
If Version = "3.3" Or Version = "4.0" Then
CargaPSSAT(e.Row.FCDropDownLost("DdlSATPS"))
If e.Row.DBCampo("CveSATPS").ToEntero > 0 Then
e.Row.FCDropDownLost("DdlSATPS").SelectedValue = e.Row.DBCampo("CveSATPS")
e.Row.FCDropDownLost("DdlSATPS").SelectedText = $"{e.Row.DBCampo("SATClaveProductoServicio")}"
End If
End If
End If
End Sub
Private Sub CargaPSSAT(Objeto As ADServerControl.Dropdownlost)
Objeto.setEsWebService(True)
Objeto.ddlWS.Attributes.Add("data-metodo", "getpssat")
End Sub
Private Sub CargaTotalesOC()
Dim TotalOC = 0.0D
For Each gvr As GridViewRow In GvOC1.Rows
TotalOC += gvr.FCTextBox("TxtTotalOC1").Text.ToDecimal
Next
'SUBTOTAL OC
LbSubTotalOC1Mod.Text = (TotalOC + DTOCGV.SUM("Descuento")).FormatoNumero
LbSubTotalOC1.Text = (TotalOC + DTOCGV.SUM("Descuento")).FormatoNumero
'SUBTOTAL2 OC
LbSubTotal2OC1Mod.Text = TotalOC.FormatoNumero
LbSubTotal2OC1.Text = TotalOC.FormatoNumero
'IVA OC
LbIVAOC1Mod.Text = (DTOCGV.SUM("IVA").ToString.ToDouble + DTOCGV.SUM("IEPSPSIVA").ToString.ToDouble).FormatoNumero
LbIVAOC1.Text = (DTOCGV.SUM("IVA").ToString.ToDouble + DTOCGV.SUM("IEPSPSIVA").ToString.ToDouble).FormatoNumero
'DESCUENTO OC
LbDescuentoOC1Mod.Text = DTOCGV.SUM("Descuento").FormatoNumero
LbDescuentoOC1.Text = DTOCGV.SUM("Descuento").FormatoNumero
If LbDescuentoOC1.Text.ToDecimal > 0 Then
TrDescuentosOC1.Visible = True
End If
'IEPS OC
LbIEPSOCMod1.Text = DTOCGV.SUM("IEPSPS").FormatoNumero
LbIEPSOC1.Text = DTOCGV.SUM("IEPSPS").FormatoNumero
If LbIEPSOC1.Text.ToDecimal > 0 Then
TrIEPSOC1.Visible = True
End If
'RET IVA OC
LblRetIVAOC1Mod.Text = DTOCGV.SUM("RetIVA").ToString.FormatoNumero
LblRetIVAOC1.Text = DTOCGV.SUM("RetIVA").ToString.FormatoNumero
If LblRetIVAOC1.Text.ToDecimal > 0 Then
TrRetIVAOC1.Visible = True
End If
'RET ISR OC
LblRetISROC1Mod.Text = DTOCGV.SUM("RetISR").ToString.FormatoNumero
LblRetISROC1.Text = DTOCGV.SUM("RetISR").ToString.FormatoNumero
If LblRetISROC1.Text.ToDecimal > 0 Then
TrRetISROC1.Visible = True
End If
'TOTAL OC
TotalOC = TotalOC + LbIVAOC1.Text.ToDecimal + LbIEPSOC1.Text.ToDecimal - LblRetIVAOC1.Text.ToDecimal - LblRetISROC1.Text.ToDecimal
LbTotalOC1.Text = TotalOC.FormatoNumero
LbTotalOC1Mod.Text = TotalOC.FormatoNumero
'SUBTOTAL COMPRA
LbSubTotalOC2.Text = TxtSubTotal.Text
'SUBTOTAL2 COMPRA
LblSubTotal2OC2.Text = TxtSubTotal2.Text
'IVA COMPRA
LbIVAOC2.Text = TxtIVA.Text
'IEPS COMPRA
LbIEPSOC2.Text = TxtIEPS.Text
If LbIEPSOC2.Text.ToDecimal > 0 Then
TrIEPSOC2.Visible = True
End If
'DESCUENTO COMPRA
LblDescuentoOC2.Text = TxtDescuento.Text
If LblDescuentoOC2.Text.ToDecimal > 0 Then
TrDescuentosOC2.Visible = True
End If
'RET IVA COMPRA
LblRetIVAOC2.Text = TxtRetIVA.Text
If LblRetIVAOC2.Text.ToDecimal > 0 Then
TrRetIVAOC2.Visible = True
End If
'RET ISR COMPRA
LblRetISROC2.Text = TxtRetISR.Text
If LblRetISROC2.Text.ToDecimal > 0 Then
TrRetISROC2.Visible = True
End If
'ANTICIPOS COMPRA
Dim ImporteAnticipo As Decimal = 0
If ArrAnticipos.Count > 0 Then
For Each Ant As Compras_Compras.Anticipos In ArrAnticipos
ImporteAnticipo += Ant.Importe
Next
End If
If ImporteAnticipo > 0 Then
TrAnticiposOC.Visible = True
LbAnticiposOC2.Text = ImporteAnticipo.ToString.FormatoNumero
End If
'TOTAL COMPRA
LbTotalOC2.Text = (TxtTotal.Text.ToDouble - ImporteAnticipo).FormatoNumero
'LbTotalOC2.Text = TxtTotal.Text
RegistraScript("CalculaTotalesOC();")
End Sub
Protected Sub BtnVincularOC_Click(sender As Object, e As EventArgs)
'If DdlOCVinculaInv.SelectedValue.ToEntero = 237 And Not CveFlete > 0 Then Alert("Necesita vincular un flete si selecciona Factura de Flete", TipoMensaje.MsgAdvertencia) : Exit Sub
'If DdlOCVinculaInv.SelectedValue.ToEntero = 240 And Not CveImportacion > 0 Then Alert("Necesita vincular una Importación si selecciona Factura de Importación", TipoMensaje.MsgAdvertencia) : Exit Sub
'If UsuarioActual.CveEmpresa = 119 And DdlTipoComprobante.SelectedValue = "Fac" Then
' If Not VerificarProductosCompraConOC() Then
' Exit Sub
' End If
'End If
Dim SubTotalGV = 0.0D
Dim Amortizacion As Decimal = TmpDT.SUMD("Total")
If ListaDocumentos IsNot Nothing AndAlso ListaDocumentos.Count > 0 AndAlso ArrAnticipos IsNot Nothing AndAlso ArrAnticipos.Count > 0 Then
Amortizacion = TmpDT.SUMD("ImporteSinImpuestos")
End If
Dim SubTotalCompra As Decimal = Amortizacion
Dim DiferenciaPermitida = 1
Dim Cont = 0
'Dim ProductosCodigoSATNoPermitidos As New StringBuilder("")
For Each gvr As GridViewRow In GvOC1.Rows
SubTotalGV += gvr.FCTextBox("TxtTotalOC1").Text.ToDecimal
If Cont = 0 Then DdlProveedorSucursal.SelectedValueExist(gvr.DataKey("CveProveedorSucursal").ToEntero())
Cont = 1
' If GvOC1.Columns(6).Visible Then
' Dim SatPS As String = gvr.FCDropDownLost("DdlSATPS").SelectedText()
' Dim NombreProducto As String = gvr.FCLabel("LbProductoServicio").Text
' If SatPS.Contains("01010101") Then
' ProductosCodigoSATNoPermitidos.AppendFormat("{0}</br>", NombreProducto)
' 'Dim mensajeAdvertencia As String = String.Format("Al vincular una Orden de Compra no se permiten productos con Producto/Servicio SAT igual a '{0}', revise el producto '{1}' en Orden(es) de Compra Vinculada(s)", SatPS, NombreProducto)
' 'Alert(mensajeAdvertencia, TipoMensaje.MsgAdvertencia)
' End If
' End If
Next
'If ProductosCodigoSATNoPermitidos.ToString.Length > 0 Then
' Dim mensajeAdvertencia As String = String.Format("No se permite vinculación de productos con código SAT '01010101', revise los productos:</br></br>{0}", ProductosCodigoSATNoPermitidos.ToString)
' Alert(mensajeAdvertencia, TipoMensaje.MsgAdvertencia)
' Exit Sub
'End If
If Math.Abs(SubTotalGV - SubTotalCompra) < DiferenciaPermitida Then
LbSubTotalDif.Visible = False
Vinculacion()
ElseIf Math.Abs(SubTotalGV - SubTotalCompra) > DiferenciaPermitida And LblAmortizacion.Text.ToDecimal > 0 Then '2020-06-08 Oscar Permitir vincular cuando hay amortizacion de NC
LbSubTotalDif.Visible = False
Vinculacion()
ElseIf Math.Abs(SubTotalGV - (SubTotalCompra - LbAnticiposOC2.Text.ToDecimal)) < DiferenciaPermitida Then
LbSubTotalDif.Visible = False
Vinculacion()
ElseIf Math.Abs(LbTotalOC1.Text.ToDecimal - (LbTotalOC2.Text.ToDecimal)) < DiferenciaPermitida Then
LbSubTotalDif.Visible = False
Vinculacion()
ElseIf Math.Abs(LbSubTotalOC2.Text.ToDecimal - (LbSubTotalOC1.Text.ToDecimal - LbAnticiposOC2.Text.ToDecimal)) < DiferenciaPermitida Then
LbSubTotalDif.Visible = False
Vinculacion()
Else
LbSubTotalDif.Visible = True
LbSubTotalDif.Text = (SubTotalCompra - SubTotalGV).FormatoNumero
Alert("Los SubTotales de la vinculación no coinciden. Rectifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia,,)
RegistraScript("CalculaTotalesOC();")
End If
UpEstatus.Update()
End Sub
Protected Sub BtnVincularOCCompleta_Click(sender As Object, e As EventArgs)
Vinculacion(True)
End Sub
Private Sub Vinculacion(Optional VinculacionCompleta As Boolean = False)
'SI PUEDE RECIBIR POR OC Y COMPRA
If UsuarioActual.CveEmpresa = 119 AndAlso UsuarioActual.Empresa.UsaInventarios And UsuarioActual.Empresa.Funcionalidad(131).ToEntero > 0 AndAlso CveTipoConcepto = 1 Then
If DdlOCVinculaInv.SelectedValue.ToEntero <= 0 Then
Alert("El campo <b>Tipo de recepción almacén</b> es necesario. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
End If
If Math.Abs(HdnIEPSModificadoOC.Value.ToDecimal - LbIEPSOC2.Text.ToDecimal) > 0.05 AndAlso UsuarioActual.CveEmpresa.Contiene(119) Then
Alert($"Hay una diferencia de IEPS entre la factura y la OC. Dif: {HdnIEPSModificadoOC.Value.ToDecimal - LbIEPSOC2.Text.ToDecimal}", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
'PSCodigo DE XML IP
Dim DtTemporalXML = TmpDT.Copy
Dim IndexTmpOriginal = 0
'Borramos el TmpDT
CreaDTCompras()
'Iteramos el GridView de la OC
Dim dr As DataRow
Dim Index = 0
Dim MensajeCostoCero As New StringBuilder
Dim TotalRows As Integer = 0
For Each gvr As GridViewRow In GvOC1.Rows
If gvr.FCTextBox("TxtCantidad").Text.ToDecimal > 0 Or VinculacionCompleta Then
TotalRows += 1
End If
Next
Dim TieneAmortizacion As Boolean = False
If ListaDocumentos IsNot Nothing AndAlso ListaDocumentos.Count > 0 AndAlso ArrAnticipos IsNot Nothing AndAlso ArrAnticipos.Count > 0 Then
TieneAmortizacion = True
End If
For Each gvr As GridViewRow In GvOC1.Rows
If gvr.FCTextBox("TxtCantidad").Text.ToDecimal > 0 Or VinculacionCompleta Then
dr = DTOCGV.Rows(gvr.RowIndex)
Dim Cantidad As Decimal = gvr.FCTextBox("TxtCantidad").Text.ToDecimal 'dr("Cantidad").ToString.ToDouble
Dim CantidadF As Decimal = gvr.DataKey("CantidadF").ToString.ToDecimal 'dr("Cantidad").ToString.ToDouble
Dim CveUM As Integer = dr("CveUM").ToString.ToEntero
Dim UM As String = dr("UM").ToString
Dim CveClasificacion As Integer = dr("CveClasificacion").ToString.ToEntero
Dim Clasificacion As String = dr("Clasificacion").ToString
Dim CvePS As Integer = dr("CvePS").ToString.ToEntero
Dim PS As String = dr("PS").ToString
Dim CveTipoPS As Integer = dr("CveTipoPS").ToString.ToEntero
Dim CveSubProyectoContrato As String = dr("CveSubProyecto").ToString
Dim CveProyecto As String = dr("CveProyecto").ToString
Dim SubProyecto As String = dr("SubProyecto").ToString
Dim Proyecto As String = dr("Proyecto").ToString
Dim Obs As String = dr("Obs").ToString
Dim PU As Decimal = gvr.FCTextBox("TxtPU").Text.ToDecimal
Dim tDescuento As Decimal = dr("Descuento").ToString.ToDecimal
Dim Total As Decimal = If(ListaDocumentos IsNot Nothing AndAlso ListaDocumentos.Count > 0 AndAlso ArrAnticipos IsNot Nothing AndAlso ArrAnticipos.Count > 0 AndAlso TxtTotal.Text.ToDecimal = 0, Math.Round((gvr.FCTextBox("TxtCantidad").Text.ToDecimal * gvr.FCTextBox("TxtPU").Text.ToDecimal) - (TxtDescuento.Text.ToDouble / TotalRows).ToDecimal, 2), Cantidad * PU - tDescuento) 'gvr.FCTextBox("TxtTotalOC1").Text.ToDecimal)
'Dim Total As Decimal = gvr.FCTextBox("TxtTotalOC1").Text.ToDecimal
'Dim IVA As Decimal = gvr.FCHiddenField("HdnOC1IVA").Value.ToDecimal
'Dim RetIVA As Double = gvr.FCHiddenField("HdnOC1RetIVA").Value.ToDecimal
'Dim RetISR As Double = gvr.FCHiddenField("HdnOC1RetISR").Value.ToDecimal
'Dim IEPSPS As Double = gvr.FCHiddenField("HdnOC1IEPSImporte").Value.ToDecimal
'Dim IEPSPSIVA As Double = gvr.FCHiddenField("HdnOC1IEPSIVA").Value.ToDecimal
Dim IVA As Decimal = dr("IVAPorcentaje").ToString.ToDecimal
Dim RetIVA As Decimal = dr("RetIVAPorcentaje").ToString.ToDecimal
Dim RetISR As Decimal = dr("RetISRPorcentaje").ToString.ToDecimal
Dim IEPSPS As Decimal = dr("IEPSPSPorcentaje").ToString.ToDecimal
Dim IEPSPSIVA As Decimal = dr("IEPSPSIVAPorcentaje").ToString.ToDecimal
Dim Descuento As Decimal = If(TieneAmortizacion, TxtDescuento.Text.ToDecimal / TotalRows, gvr.FCHiddenField("HdnOC1Descuento").Value.ToDecimal)
'Dim Descuento As Double = gvr.FCHiddenField("HdnOC1Descuento").Value.ToDecimal
Dim CveOrdenCompraDetalle As Integer = dr("CveOrdenCompraDetalle").ToString.ToEntero
Dim EntregaDirecta As Integer = dr("EntregaDirecta").ToString.ToEntero
Dim CveSATPS As Integer = gvr.FCDropDownLost("DdlSATPS").SelectedValue.ToEntero
Dim CveTipoGasto As Integer = dr("CveTipoGastoObra").ToString.ToEntero
Dim TipoGasto As String = dr("TipoGasto").ToString
Dim CveContratoDetalle As Integer = dr("CveContratoDetalle").ToString.ToEntero
Dim CveCultivoCuadroDetalle As Integer = dr("CveCultivoCuadroDetalle").ToString.ToEntero
Dim CveSATPSActualizado As Boolean = gvr.FCDropDownLost("DdlSATPS").SelectedValue.ToEntero <> dr("CveSATPS").ToString.ToEntero
'[IPP] PROVISIONAL PARA TIPO GASTO
If GlobalDTTiposGastos(UsuarioActual.CveEmpresa) IsNot Nothing AndAlso GlobalDTTiposGastos(UsuarioActual.CveEmpresa).Rows.Count = 1 Then
Dim DrTipoGasto = GlobalDTTiposGastos(UsuarioActual.CveEmpresa).FiltroPrimero("")
If DrTipoGasto IsNot Nothing Then
CveTipoGasto = DrTipoGasto("CveTipoGasto").ToString.ToEntero
TipoGasto = DrTipoGasto("TipoGasto").ToString
End If
End If
AddPS(Cantidad, CveUM, UM, CveClasificacion, Clasificacion, CvePS, PS, CveTipoPS, CveSubProyectoContrato, SubProyecto, Proyecto, CveProyecto, Obs, PU, Total, IVA, RetIVA, RetISR, IEPSPS, IEPSPSIVA, Descuento, CveOrdenCompraDetalle, False,
CantidadF:=CantidadF, EntregaDirecta:=EntregaDirecta, CveSATPS:=CveSATPS, CveTipoGasto:=CveTipoGasto, TipoGasto:=TipoGasto, CveContratoDetalle:=CveContratoDetalle, CveCultivoCuadroDetalle:=CveCultivoCuadroDetalle, CveSATPSActualizado:=CveSATPSActualizado)
'CARGA PE
Index = TmpDT.Rows.Count - 1
TmpDT.Rows(Index)("CvePresupuestoEgreso") = dr("CvePresupuestoEgreso").ToString.ToEntero
TmpDT.Rows(Index)("CveProgramaOperativo") = dr("CveProgramaOperativo").ToString.ToEntero
TmpDT.Rows(Index)("CveUnidadAdministrativa") = dr("CveUnidadAdministrativa").ToString.ToEntero
TmpDT.Rows(Index)("CveFuenteFinanciamiento") = dr("CveFuenteFinanciamiento").ToString.ToEntero
TmpDT.Rows(Index)("CveTipoGastoAC") = dr("CveTipoGasto").ToString.ToEntero
TmpDT.Rows(Index)("CveClasificacionOG") = dr("CveClasificacionOG").ToString.ToEntero
'TmpDT.Rows(Index)("PSCodigo") = DtTemporalXML.Rows(IndexTmpOriginal)("PSCodigo")
TmpDT.Rows(Index)("PSCodigo") = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=CvePS).FiltroPrimeroValor("PSCodigo", "").ToString
Dim CveAF As String = dr("CveActivoFijo").ToString
If CveAF <> "" AndAlso CveAF <> "-1" Then
TmpDT.Rows(Index)("CveActivoFijo") = CveAF.ToEntero
TmpDT.Rows(Index)("CodAF") = dr("CodigoAF").ToString
TmpDT.Rows(Index)("TipoAF") = 1
End If
'actualizo los movimientos registrados
DTOCGV.Rows(gvr.RowIndex)("CantidadPendienteVincular") = Cantidad
DTOCGV.Rows(gvr.RowIndex)("Importe") = PU
DTOCGV.Rows(gvr.RowIndex)("Total") = Total
End If
IndexTmpOriginal += 1
Next
AddPS2(False)
'AJUSTE DE REDONDEO O DIFERENCIA PERMITIDA DE IMPORTE
AjustaImporteUltimoConcepto((If(TieneAmortizacion, TmpDT.SUMD("ImporteSinImpuestos"), TxtSubTotal2.Text.ToDouble) + TxtOtrosImpuestos.Text.ToDouble).ToDecimal - If(TieneAmortizacion, TmpDT.SUM("ImporteSinImpuestos").ToString.ToDecimal, TmpDT.SUM("Total").ToString.ToDecimal))
'AjustaImporteUltimoConcepto(TxtSubTotal2.Text.ToDecimal + TxtOtrosImpuestos.Text.ToDecimal - (TmpDT.SUM("Total").ToString.ToDecimal))
BtnGuardar.Enabled = True
If Not CierrePeriodo Then
BtnGuardar.Visible = True
End If
AlmacenCambiaPS.Visible = False
UpFacturar.Update()
TabGenerales.Enabled = True
Tab.ActiveTabIndex = 0
UpTabs.Update()
ImgClasificacion.Visible = False
ImgSubProyecto.Visible = False
LbAgregar.Visible = False
OCVinculada = True
UpPSS.Update()
AsignaValoresOriginales(TxtSubTotal.Text.ToDouble, TxtSubTotal2.Text.ToDouble, TxtIVA.Text.ToDouble, TxtRetIVA.Text.ToDouble, TxtRetISR.Text.ToDouble, TxtTotal.Text.ToDouble)
If UsuarioActual.Empresa.Funcionalidad(562).ToEntero > 0 Then CargaGastosServicios(UsuarioActual.Empresa.Funcionalidad(562).ToEntero)
CargaGvInv()
GvPS.DataSource = TmpDT
GvPS.DataBind()
UpPS.Update()
CargaGVsAF()
CargaTipoCentroCostoOC()
GvOC1.DataSource = DTOCGV
GvOC1.DataBind()
Dim DTCVEOCS As DataTable = DTOCGV.FiltraParametros("", "", {"CveOrdenCompra"})
If DTCVEOCS.Rows.Count > 1 Then
GvOC1.Columns(0).Visible = True
Else
GvOC1.Columns(0).Visible = False
End If
GvOC2.DataSource = TmpDT
GvOC2.DataBind()
LbSubTotalOC1.Text = LbSubTotalOC2.Text
LbSubTotal2OC1.Text = LblSubTotal2OC2.Text
LbIVAOC1.Text = LbIVAOC2.Text
LbIEPSOC1.Text = LbIEPSOC2.Text
LblRetIVAOC1.Text = LblRetIVAOC2.Text
LblRetISROC1.Text = LblRetISROC2.Text
LbDescuentoOC1.Text = LblDescuentoOC2.Text
LbTotalOC1.Text = LbTotalOC2.Text
UpGvOC1.Update()
'Bloquea cambio de proyecto
DdlProyecto.Enabled = False
DdlSubProyecto.Enabled = False
DdlAsignarProyecto.Enabled = False
DdlAsignaSubProyecto.Enabled = False
UPPProyecto.Update()
'Bloquea cambio de OC ya que se concluyo alguna vinculacion
TxtOC.Enabled = False
UpParametros.Update()
'VERIFICA PE
If UsuarioActual.Empresa.UsaAC Then
CompruebaAgregar()
End If
CargaGvPersonal()
'ANTICIPO OC
If DivOCSolicitudAnticipo.Visible Then
RegistraScript("MuestraAnticipos();", "MuestaAnticiposOC")
UpAnticipos.Update()
End If
CalculaTotales()
CompraEstaVinculadaOC = True
End Sub
Private Sub VinculacionAsync(Optional VinculacionCompleta As Boolean = False)
'LIMPIAMOS TMPDT
CreaDTCompras()
Dim tasks As New List(Of Task)()
For Each gvr As GridViewRow In GvOC1.Rows
If gvr.FCTextBox("TxtCantidad").Text.ToDecimal > 0 Or VinculacionCompleta Then
tasks.Add(AgregaConceptoOC(DTOCGV.Rows(gvr.RowIndex), gvr))
End If
Next
Task.WaitAll(tasks.ToArray())
AddPS2(False)
'AJUSTE DE REDONDEO O DIFERENCIA PERMITIDA DE IMPORTE
AjustaImporteUltimoConcepto((TxtSubTotal2.Text.ToDouble - TmpDT.SUM("Total")).ToString.ToDecimal)
BtnGuardar.Enabled = True
If Not CierrePeriodo Then
BtnGuardar.Visible = True
End If
AlmacenCambiaPS.Visible = False
UpFacturar.Update()
TabGenerales.Enabled = True
Tab.ActiveTabIndex = 0
UpTabs.Update()
ImgClasificacion.Visible = False
ImgSubProyecto.Visible = False
LbAgregar.Visible = False
OCVinculada = True
UpPSS.Update()
AsignaValoresOriginales(TxtSubTotal.Text.ToDecimal, TxtSubTotal2.Text.ToDecimal, TxtIVA.Text.ToDecimal, TxtRetIVA.Text.ToDecimal, TxtRetISR.Text.ToDecimal, TxtTotal.Text.ToDecimal)
CargaGvInv()
GvPS.DataSource = TmpDT
GvPS.DataBind()
UpPS.Update()
CargaGVsAF()
CargaTipoCentroCostoOC()
GvOC1.DataSource = DTOCGV
GvOC1.DataBind()
Dim DTCVEOCS As DataTable = DTOCGV.FiltraParametros("", "", {"CveOrdenCompra"})
If DTCVEOCS.Rows.Count > 1 Then
GvOC1.Columns(0).Visible = True
Else
GvOC1.Columns(0).Visible = False
End If
GvOC2.DataSource = TmpDT
GvOC2.DataBind()
LbSubTotalOC1.Text = LbSubTotalOC2.Text
LbSubTotal2OC1.Text = LblSubTotal2OC2.Text
LbIVAOC1.Text = LbIVAOC2.Text
LbIEPSOC1.Text = LbIEPSOC2.Text
LblRetIVAOC1.Text = LblRetIVAOC2.Text
LblRetISROC1.Text = LblRetISROC2.Text
LbDescuentoOC1.Text = LblDescuentoOC2.Text
LbTotalOC1.Text = LbTotalOC2.Text
UpGvOC1.Update()
'Bloquea cambio de proyecto
DdlProyecto.Enabled = False
DdlSubProyecto.Enabled = False
DdlAsignarProyecto.Enabled = False
DdlAsignaSubProyecto.Enabled = False
UPPProyecto.Update()
'Bloquea cambio de OC ya que se concluyo alguna vinculacion
TxtOC.Enabled = False
UpParametros.Update()
'VERIFICA PE
If UsuarioActual.Empresa.UsaAC Then
CompruebaAgregar()
End If
CargaGvPersonal()
'ANTICIPO OC
If DivOCSolicitudAnticipo.Visible Then
RegistraScript("MuestraAnticipos();", "MuestaAnticiposOC")
UpAnticipos.Update()
End If
CalculaTotales()
End Sub
Private Function AgregaConceptoOC(dr As DataRow, gvr As GridViewRow) As Task
Return Task.Factory.StartNew(Sub() AgregaConceptoOCHilo(dr, gvr))
End Function
Private Sub AgregaConceptoOCHilo(dr As DataRow, gvr As GridViewRow)
Dim Cantidad As Decimal = gvr.FCTextBox("TxtCantidad").Text.ToDecimal
Dim CantidadF As Decimal = gvr.DataKey("CantidadF").ToString.ToDecimal
Dim CveUM As Integer = dr("CveUM").ToString.ToEntero
Dim UM As String = dr("UM").ToString
Dim CveClasificacion As Integer = dr("CveClasificacion").ToString.ToEntero
Dim Clasificacion As String = dr("Clasificacion").ToString
Dim CvePS As Integer = dr("CvePS").ToString.ToEntero
Dim PS As String = dr("PS").ToString
Dim CveTipoPS As Integer = dr("CveTipoPS").ToString.ToEntero
Dim CveSubProyectoContrato As String = dr("CveSubProyecto").ToString
Dim CveProyecto As String = dr("CveProyecto").ToString
Dim SubProyecto As String = dr("SubProyecto").ToString
Dim Proyecto As String = dr("Proyecto").ToString
Dim Obs As String = dr("Obs").ToString
Dim PU As Decimal = gvr.FCTextBox("TxtPU").Text.ToDecimal
Dim Total As Decimal = gvr.FCTextBox("TxtTotalOC1").Text.ToDecimal
Dim IVA As Decimal = dr("IVAPorcentaje").ToString.ToDecimal
Dim RetIVA As Decimal = dr("RetIVAPorcentaje").ToString.ToDecimal
Dim RetISR As Decimal = dr("RetISRPorcentaje").ToString.ToDecimal
Dim IEPSPS As Decimal = dr("IEPSPSPorcentaje").ToString.ToDecimal
Dim IEPSPSIVA As Decimal = dr("IEPSPSIVAPorcentaje").ToString.ToDecimal
Dim Descuento As Decimal = gvr.FCHiddenField("HdnOC1Descuento").Value.ToDecimal
Dim CveOrdenCompraDetalle As Integer = dr("CveOrdenCompraDetalle").ToString.ToEntero
Dim EntregaDirecta As Integer = dr("EntregaDirecta").ToString.ToEntero
Dim CveSATPS As Integer = gvr.FCDropDownLost("DdlSATPS").SelectedValue.ToEntero
Dim CveTipoGasto As Integer = -1
Dim TipoGasto As String = ""
'[IPP] PROVISIONAL PARA TIPO GASTO
If GlobalDTTiposGastos(UsuarioActual.CveEmpresa) IsNot Nothing AndAlso GlobalDTTiposGastos(UsuarioActual.CveEmpresa).Rows.Count = 1 Then
Dim DrTipoGasto = GlobalDTTiposGastos(UsuarioActual.CveEmpresa).FiltroPrimero("")
If DrTipoGasto IsNot Nothing Then
CveTipoGasto = DrTipoGasto("CveTipoGasto").ToString.ToEntero
TipoGasto = DrTipoGasto("TipoGasto").ToString
End If
End If
'AGREGA PS
Dim IndexVinculacionOC = AddPS(Cantidad, CveUM, UM, CveClasificacion, Clasificacion, CvePS, PS, CveTipoPS, CveSubProyectoContrato, SubProyecto, Proyecto, CveProyecto, Obs, PU, Total, IVA, RetIVA, RetISR, IEPSPS, IEPSPSIVA, Descuento, CveOrdenCompraDetalle, False, CantidadF:=CantidadF, EntregaDirecta:=EntregaDirecta, CveSATPS:=CveSATPS, CveTipoGasto:=CveTipoGasto, TipoGasto:=TipoGasto)
'CARGA PE
TmpDT.Rows(IndexVinculacionOC)("CvePresupuestoEgreso") = dr("CvePresupuestoEgreso").ToString.ToEntero
TmpDT.Rows(IndexVinculacionOC)("CveProgramaOperativo") = dr("CveProgramaOperativo").ToString.ToEntero
TmpDT.Rows(IndexVinculacionOC)("CveUnidadAdministrativa") = dr("CveUnidadAdministrativa").ToString.ToEntero
TmpDT.Rows(IndexVinculacionOC)("CveFuenteFinanciamiento") = dr("CveFuenteFinanciamiento").ToString.ToEntero
TmpDT.Rows(IndexVinculacionOC)("CveTipoGastoAC") = dr("CveTipoGasto").ToString.ToEntero
TmpDT.Rows(IndexVinculacionOC)("CveClasificacionOG") = dr("CveClasificacionOG").ToString.ToEntero
TmpDT.Rows(IndexVinculacionOC)("PSCodigo") = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=CvePS).FiltroPrimeroValor("PSCodigo", "").ToString
Dim CveAF As String = dr("CveActivoFijo").ToString
If CveAF <> "" AndAlso CveAF <> "-1" Then
TmpDT.Rows(IndexVinculacionOC)("CveActivoFijo") = CveAF.ToEntero
TmpDT.Rows(IndexVinculacionOC)("CodAF") = dr("CodigoAF").ToString
TmpDT.Rows(IndexVinculacionOC)("TipoAF") = 1
End If
'actualizo los movimientos registrados
DTOCGV.Rows(gvr.RowIndex)("CantidadPendienteVincular") = Cantidad
DTOCGV.Rows(gvr.RowIndex)("Importe") = PU
DTOCGV.Rows(gvr.RowIndex)("Total") = Total
End Sub
Protected Sub BtnTipoCambioOC_Click(sender As Object, e As EventArgs)
If TxtTipoCambioOC.Text.ToDecimal = 0 Then
Alert("El tipo de cambio debe ser mayor a cero. Por favor rectifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
For Each Dr As DataRow In DTOCTemp.Rows
'OC - COMPRA
'DOLARES A PESOS
If DdlMoneda.SelectedValue.ToEntero = 1 Then
Dr("Importe") = Dr("PUTC").ToString.ToDecimal * TxtTipoCambioOC.Text.ToDecimal
Dr("Descuento") = Dr("DescuentoTC").ToString.ToDecimal * TxtTipoCambioOC.Text.ToDecimal
Dr("IVA") = Dr("IVATC").ToString.ToDecimal * TxtTipoCambioOC.Text.ToDecimal
Dr("IEPSPS") = Dr("IEPSPSTC").ToString.ToDecimal * TxtTipoCambioOC.Text.ToDecimal
Dr("IEPSPSIVA") = Dr("IEPSPSIVATC").ToString.ToDecimal * TxtTipoCambioOC.Text.ToDecimal
Dr("RetIVA") = Dr("RetIVATC").ToString.ToDecimal * TxtTipoCambioOC.Text.ToDecimal
Dr("RetISR") = Dr("RetISRTC").ToString.ToDecimal * TxtTipoCambioOC.Text.ToDecimal
Dr("ImporteAjustadoDescuento") = Dr("TotalTC").ToString.ToDecimal * TxtTipoCambioOC.Text.ToDecimal
End If
'OC - COMPRA
'PESOS A DOLARES
If DdlMoneda.SelectedValue.ToEntero = 2 Then
Dr("Importe") = Dr("PUTC").ToString.ToDecimal / TxtTipoCambioOC.Text.ToDecimal
Dr("Descuento") = Dr("DescuentoTC").ToString.ToDecimal / TxtTipoCambioOC.Text.ToDecimal
Dr("IVA") = Dr("IVATC").ToString.ToDecimal / TxtTipoCambioOC.Text.ToDecimal
Dr("IEPSPS") = Dr("IEPSPSTC").ToString.ToDecimal / TxtTipoCambioOC.Text.ToDecimal
Dr("IEPSPSIVA") = Dr("IEPSPSIVATC").ToString.ToDecimal / TxtTipoCambioOC.Text.ToDecimal
Dr("RetIVA") = Dr("RetIVATC").ToString.ToDecimal / TxtTipoCambioOC.Text.ToDecimal
Dr("RetISR") = Dr("RetISRTC").ToString.ToDecimal / TxtTipoCambioOC.Text.ToDecimal
Dr("ImporteAjustadoDescuento") = Dr("TotalTC").ToString.ToDecimal / TxtTipoCambioOC.Text.ToDecimal
End If
Dr.AcceptChanges()
Next
TipoCambioOC = TxtTipoCambioOC.Text.ToDecimal
BtnVincularOC.Visible = True
CargaVinculacionOC()
End Sub
Protected Sub BtnDividirCompra_Click(sender As Object, e As EventArgs)
Dim Cantidad = CType(CType(sender, Button).NamingContainer, GridViewRow).FCTextBox("TxtDividir").Text.ToDecimal
If Cantidad < 0.1 Then
Exit Sub
End If
Dim dr = TmpDT.Rows(CType(CType(sender, Button).NamingContainer, GridViewRow).RowIndex)
Dim drNuevo = TmpDT.NewRow
drNuevo.ItemArray = dr.ItemArray
drNuevo("Cantidad") = Cantidad
drNuevo("Total") = drNuevo("Cantidad").ToString.ToEntero * drNuevo("PU").ToString.ToDecimal
dr("Cantidad") = dr("Cantidad").ToString.ToEntero - Cantidad
dr("Total") = dr("Cantidad").ToString.ToEntero * dr("PU").ToString.ToDecimal
TmpDT.Rows.InsertAt(drNuevo, CType(CType(sender, Button).NamingContainer, GridViewRow).RowIndex)
If TxtOC.Text.Trim <> "" Then
'If EmpresasOC.Contains(UsuarioActual.CveEmpresa) Then
' GvOC1.DataSource = TmpDT
' GvOC1.DataBind()
' UpGvOC1.Update()
'Else
GvOC2.DataSource = TmpDT
GvOC2.DataBind()
UpGvOC2.Update()
GvPS.DataSource = TmpDT
GvPS.DataBind()
UpPS.Update()
'End If
Else
GvPS.DataSource = TmpDT
GvPS.DataBind()
UpPS.Update()
End If
CargaGvInv()
End Sub
Protected Sub BtnAlertaPUCero_Click(sender As Object, e As EventArgs)
Dim Argumentos = HdnAlertaPUCero.Value.Split("|"c)
Dim PS = Argumentos(0)
Dim Cantidad = Argumentos(1)
'Alert($"El concepto tiene especificada una cantidad pero con costo de cero ($0).<br/<> br /<> b > En caso de vincular la OC de esta manera la cantidad especificada sera considerada como recibida.</b> <br/><br/> De ser correcto Continue o de lo contrario rectifique.", TipoMensaje.MsgAdvertencia)
Alert($"El concepto <b>{PS}</b> tiene especificada la cantidad <b>{Cantidad}</b> pero un costo de cero ($0). <br/><br/> <b>En caso de vincular la OC de esta manera la cantidad especificada sera considerada como recibida.</b> <br/><br/> De ser correcto Continue o de lo contrario rectifique.", TipoMensaje.MsgAdvertencia)
End Sub
#End Region
#Region "F L E T E S Y S E R V I C I O S"
Public Sub CreaDTFacturas()
Dim dt As New DataTable
dt.Columns.Add("CveCompra", Type.GetType("System.Int32"))
dt.Columns.Add("Folio", Type.GetType("System.String"))
dt.Columns.Add("Fecha", Type.GetType("System.String"))
DtFacturas = dt
End Sub
Public Sub CreaDTServicios()
Dim dt As New DataTable
dt.Columns.Add("Total", Type.GetType("System.Double"))
dt.Columns.Add("PS", Type.GetType("System.String"))
dt.Columns.Add("Consec", Type.GetType("System.Int32"))
dt.Columns.Add("CvePS", Type.GetType("System.Int32"))
DtServicios = dt
End Sub
Protected Sub LbServicios_Click(sender As Object, e As EventArgs)
RegistraScript("$('#DivFletesYServicios').modal();")
CreaDTFacturas()
CreaDTServicios()
End Sub
Protected Sub BtnFiltrar_Click(sender As Object, e As EventArgs)
'POR SI LLEGARA A TRONAR
If DtServicios Is Nothing Then CreaDTServicios()
DtServicios.Rows.Clear()
Dim objps As New ClsProductosServicios
Dim dr As DataRow
dvFacturas.Visible = False
GvFacturas.Visible = False
For Each DrGv As DataRow In TmpDT.Rows
If DrGv("CvePS").ToString.ToEntero > 0 Then
If objps.GetPS(DrGv("CvePS").ToString.ToEntero, -1, UsuarioActual.CveEmpresa) Then
If objps.DtResultados(0)("CveTipoPS").ToString.ToEntero = 1 Then
dr = DtServicios.NewRow()
dr("Consec") = DrGv("Consec").ToString.ToEntero
dr("Total") = DrGv("Total").ToString.ToDecimal
dr("CvePS") = DrGv("CvePS").ToString.ToEntero
dr("PS") = DrGv("PS").ToString
DtServicios.Rows.Add(dr)
End If
End If
End If
Next
'[IPP] COMENTADO - MIRAS DE ELIMINAR - 8/FEBRERO/2018
'For Each gvr As GridViewRow In GvPS.Rows
' If objps.GetPS(gvr.DataKey("CvePS").ToEntero, -1, UsuarioActual.CveEmpresa) Then
' If objps.DtResultados(0)("CveTipoPS").ToString.ToEntero = 1 Then
' dr = DtServicios.NewRow()
' dr("Consec") = gvr.FCLabel("LtlConsecutivo").Text.ToEntero
' dr("Total") = gvr.FCLiteral("LtlTotal").Text.ToDecimal
' dr("PS") = gvr.DataKey("PS").ToString
' DtServicios.Rows.Add(dr)
' End If
' End If
'Next
objps.Dispose()
If DtServicios.Rows.Count > 0 Then
GVServicios.DataSource = DtServicios
GVServicios.DataBind()
GVServicios.Visible = True
Else
GVServicios.DataSource = Nothing
GVServicios.DataBind()
End If
UpGVServicios.Update()
UpFacturas.Update()
UPGVFacturas.Update()
'If DdlTipo.SelectedValue.ToEntero = 1 Then
'ElseIf DdlTipo.SelectedValue.ToEntero = 2 Then
' GVServicios.Visible = False
' dvFacturas.Visible = True
' DdlProveedores.DataSource = GlobalDTCompProveedores(UsuarioActual.CveEmpresa)
' DdlProveedores.DataBind()
' DdlProveedores.Items.Insert(0, New ListItem("Seleccione", "-1"))
' UpFacturas.Update()
' UpGVServicios.Update()
'End If
End Sub
Public Sub CargaIndirectosServicios()
If DtServicios Is Nothing Then CreaDTServicios()
DtServicios.Rows.Clear()
Dim objps As New ClsProductosServicios
Dim dr As DataRow
dvFacturas.Visible = False
GvFacturas.Visible = False
For Each DrGv As DataRow In TmpDT.Rows
If DrGv("CvePS").ToString.ToEntero > 0 Then
If objps.GetPS(DrGv("CvePS").ToString.ToEntero, -1, UsuarioActual.CveEmpresa) Then
If objps.DtResultados(0)("CveTipoPS").ToString.ToEntero = 1 Then
dr = DtServicios.NewRow()
dr("Consec") = DrGv("Consec").ToString.ToEntero
dr("Total") = DrGv("Total").ToString.ToDecimal
dr("CvePS") = DrGv("CvePS").ToString.ToEntero
dr("PS") = DrGv("PS").ToString
DtServicios.Rows.Add(dr)
End If
End If
End If
Next
objps.Dispose()
If DtServicios.Rows.Count > 0 Then
GVServicios.DataSource = DtServicios
GVServicios.DataBind()
GVServicios.Visible = True
Else
GVServicios.DataSource = Nothing
GVServicios.DataBind()
End If
UpGVServicios.Update()
UpFacturas.Update()
UPGVFacturas.Update()
End Sub
Public Sub btnAgregarFlete_Click(sender As Object, e As EventArgs) Handles BtnAgregarFlete.Click
Dim ListaConsecutivas As New List(Of String) 'Almacena los consecutivos que pertenecen al almacen
Dim CostoIndirectoTotal As Decimal = 0 'Suma los costos indirectos calculados
Dim IndiceFila As Integer = 0 'Alamcena la fila actual iterada del TmpDT
Dim IndiceActualizar As Integer = -1 'Almacena el ultimo indice perteneciente a Almacen
TotalFlete = 0
TotalAlmacen = 0
'Obtenemos el total del flete y marcamos los conceptos que pertenecen a flete
For Each gvr As GridViewRow In GVServicios.Rows
If gvr.FCCheckBox("chkServicios").Checked Then
Dim Dtr As DataRow = TmpDT.Select($"Consec = {gvr.FCLabel("LblConsec").Text.ToEntero}")(0)
Dtr("AplicaCostoIndirecto") = 1
TotalFlete += Math.Round(gvr.FCLiteral("LtlTotalmodal").Text.ToDecimal, 2)
End If
Next
'Obtenemos el total del almacen y guardamos las consecutivas pertenecientes al mismo
For Each Dr As DataRow In DtInv.Rows
TotalAlmacen += Math.Round(Dr("Total").ToString.ToDecimal, 2)
ListaConsecutivas.Add(Dr("Consec").ToString)
Next
'Asignamos los costos indirectos y los indices
For Each Drt As DataRow In TmpDT.Rows
If ListaConsecutivas.Contains(Drt("Consec").ToString) Then
Dim CostoIndirecto As Decimal = CalculaCostoIndirectoFlete(Drt("Total").ToString.ToDecimal)
CostoIndirectoTotal += CostoIndirecto
Drt("CostoIndirectoAlmacen") = CostoIndirecto
Drt("OtrosGastos") = CostoIndirecto
IndiceActualizar = IndiceFila
End If
IndiceFila += 1
Next
'Si los costosindirectos no suman el total exacto del flete ajustamos el ultimo concepto
If CostoIndirectoTotal <> TotalFlete AndAlso IndiceActualizar >= 0 Then
Dim Diferencia = TotalFlete - CostoIndirectoTotal
TmpDT.Rows(IndiceActualizar)("CostoIndirectoAlmacen") = TmpDT.Rows(IndiceActualizar)("CostoIndirectoAlmacen").ToString.ToDouble + Diferencia
TmpDT.Rows(IndiceActualizar)("OtrosGastos") = TmpDT.Rows(IndiceActualizar)("OtrosGastos").ToString.ToDouble + Diferencia
End If
TmpDT.AcceptChanges()
CargaGvInv()
DdlTipoCompra.SelectedValueExist("8")
UpEstatus.Update()
''Marcamos todos los almacenes como check
'GvInv.HeaderRow.FCCheckBox("cbAll").Checked = True
'cbAll_CheckedChanged(Nothing, Nothing)
RegistraScript("$('#ModalFletesImportaciones').modal('hide');")
End Sub
Private Sub CargaGastosServicios(CvePS As Integer)
'POR SI LLEGARA A TRONAR
If DtServicios Is Nothing Then CreaDTServicios()
DtServicios.Rows.Clear()
Dim objps As New ClsProductosServicios
Dim dr As DataRow
dvFacturas.Visible = False
GvFacturas.Visible = False
For Each DrGv As DataRow In TmpDT.Rows
If DrGv("CvePS").ToString.ToEntero > 0 Then
If objps.GetPS(DrGv("CvePS").ToString.ToEntero, -1, UsuarioActual.CveEmpresa) Then
If objps.DtResultados IsNot Nothing AndAlso objps.DtResultados.Rows.Count > 0 AndAlso objps.DtResultados(0)("CveTipoPS").ToString.ToEntero = 1 Then
dr = DtServicios.NewRow()
dr("Consec") = DrGv("Consec").ToString.ToEntero
dr("Total") = DrGv("Total").ToString.ToDecimal
dr("CvePS") = DrGv("CvePS").ToString.ToEntero
dr("PS") = DrGv("PS").ToString
DtServicios.Rows.Add(dr)
End If
End If
End If
Next
'[IPP] COMENTADO - MIRAS DE ELIMINAR - 8/FEBRERO/2018
'For Each gvr As GridViewRow In GvPS.Rows
' If objps.GetPS(gvr.DataKey("CvePS").ToEntero, -1, UsuarioActual.CveEmpresa) Then
' If objps.DtResultados(0)("CveTipoPS").ToString.ToEntero = 1 Then
' dr = DtServicios.NewRow()
' dr("Consec") = gvr.FCLabel("LtlConsecutivo").Text.ToEntero
' dr("Total") = gvr.FCLiteral("LtlTotal").Text.ToDecimal
' dr("PS") = gvr.DataKey("PS").ToString
' DtServicios.Rows.Add(dr)
' End If
' End If
'Next
objps.Dispose()
If DtServicios.Rows.Count > 0 Then
GVServicios.DataSource = DtServicios
GVServicios.DataBind()
GVServicios.Visible = True
Else
GVServicios.DataSource = Nothing
GVServicios.DataBind()
End If
UpGVServicios.Update()
UpFacturas.Update()
UPGVFacturas.Update()
Dim ListaConsecutivas As New List(Of String) 'Almacena los consecutivos que pertenecen al almacen
Dim CostoIndirectoTotal As Decimal = 0 'Suma los costos indirectos calculados
Dim IndiceFila As Integer = 0 'Alamcena la fila actual iterada del TmpDT
Dim IndiceActualizar As Integer = -1 'Almacena el ultimo indice perteneciente a Almacen
TotalFlete = 0
TotalAlmacen = 0
If DtInv IsNot Nothing Then
'Obtenemos el total del almacen y guardamos las consecutivas pertenecientes al mismo
For Each Dr2 As DataRow In DtInv.Rows
TotalAlmacen += Math.Round(Dr2("Total").ToString.ToDecimal, 2)
ListaConsecutivas.Add(Dr2("Consec").ToString)
Next
End If
'sino hay producto en almacen para aplciarle un servicio, no se debe de amrcar como costo indirecto
'esto aplica cuando la factura solo trae un concepto, y es el de servicio
If TotalAlmacen = 0 Then Exit Sub
'Obtenemos el total del flete y marcamos los conceptos que pertenecen a flete
For Each gvr As GridViewRow In GVServicios.Rows
If gvr.DataKey("CvePS").ToEntero = CvePS Or gvr.FCCheckBox("chkServicios").Checked Then
Dim Dtr As DataRow = TmpDT.Select($"Consec = {gvr.FCLabel("LblConsec").Text.ToEntero}")(0)
Dtr("AplicaCostoIndirecto") = 1
TotalFlete += Math.Round(gvr.FCLiteral("LtlTotalmodal").Text.ToDecimal, 2)
gvr.FCCheckBox("chkServicios").Checked = True
End If
Next
UpGVServicios.Update()
If Not TotalFlete > 0 Then Exit Sub
'Asignamos los costos indirectos y los indices
For Each Drt As DataRow In TmpDT.Rows
If ListaConsecutivas.Contains(Drt("Consec").ToString) Then
Dim CostoIndirecto As Decimal = CalculaCostoIndirectoFlete(Drt("Total").ToString.ToDecimal)
CostoIndirectoTotal += CostoIndirecto
Drt("CostoIndirectoAlmacen") = CostoIndirecto
Drt("OtrosGastos") = CostoIndirecto
IndiceActualizar = IndiceFila
End If
IndiceFila += 1
Next
'Si los costosindirectos no suman el total exacto del flete ajustamos el ultimo concepto
If CostoIndirectoTotal <> TotalFlete AndAlso IndiceActualizar >= 0 Then
Dim Diferencia = TotalFlete - CostoIndirectoTotal
TmpDT.Rows(IndiceActualizar)("CostoIndirectoAlmacen") = TmpDT.Rows(IndiceActualizar)("CostoIndirectoAlmacen").ToString.ToDouble + Diferencia
TmpDT.Rows(IndiceActualizar)("OtrosGastos") = TmpDT.Rows(IndiceActualizar)("OtrosGastos").ToString.ToDouble + Diferencia
End If
TmpDT.AcceptChanges()
CargaGvInv()
DdlTipoCompra.SelectedValueExist("8")
UpEstatus.Update()
''Marcamos todos los almacenes como check
'GvInv.HeaderRow.FCCheckBox("cbAll").Checked = True
'cbAll_CheckedChanged(Nothing, Nothing)
End Sub
Protected Sub GVServicios_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GVServicios.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim TmpDr As DataRow = TmpDT.Select($"Consec = {e.Row.FCLabel("LblConsec").Text}")(0)
If TmpDr("AplicaCostoIndirecto").ToString = "1" Then
e.Row.FCCheckBox("chkServicios").Checked = True
e.Row.FCCheckBox("chkServicios").Enabled = Not CveCompra > 0
End If
End If
End Sub
Private Function CalculaCostoIndirectoFlete(ImporteAlmacen As Decimal) As Decimal
Dim CostoIndirecto As Decimal
CostoIndirecto = (ImporteAlmacen * TotalFlete) / TotalAlmacen
Return Math.Round(CostoIndirecto, 2)
End Function
Protected Sub BtnAgregaFactura_Click(sender As Object, e As EventArgs)
Dim ObjComp As New ClsCompras
If ObjComp.GetCompras(DdlFacturas.SelectedValue.ToEntero, "-1", DdlFacturas.SelectedItem.ToString, -1, -1, 1) Then
Dim dr As DataRow = DtFacturas.NewRow()
dr("CveCompra") = ObjComp.DtResultados(0)("CveCompra").ToString
dr("Folio") = ObjComp.DtResultados(0)("Folio").ToString
dr("Fecha") = ObjComp.DtResultados(0)("Fecha").ToString.ToDate.ToString("dd/MM/yyyy")
DtFacturas.Rows.Add(dr)
If GvFacturas.Visible = False Then
GvFacturas.Visible = True
End If
GvFacturas.DataSource = DtFacturas
GvFacturas.DataBind()
Else
Alert("No se encontró la factura", TipoMensaje.MsgAdvertencia)
End If
UPGVFacturas.Update()
ObjComp.Dispose()
End Sub
Protected Sub DdlProveedores_SelectedIndexChanged(sender As Object, e As EventArgs)
CargarFacturas()
End Sub
Private Sub CargarFacturas()
Dim objCompras As New ClsCompras
If objCompras.GetCompras(-1, "-1", "-1", DdlProveedores.SelectedValue.ToEntero, -1, UsuarioActual.CveEmpresa) Then
DdlFacturas.DataSource = objCompras.DtResultados
Else
DdlFacturas.DataSource = Nothing
Alert("No se encontraron folios con el proveedor seleccionado.", TipoMensaje.MsgAdvertencia)
End If
DdlFacturas.DataBind()
DdlFacturas.Items.Insert(0, New ListItem("Seleccione", "-1"))
objCompras.Dispose()
End Sub
Protected Sub GvFacturas_RowDeleting(sender As Object, e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles GvFacturas.RowDeleting
DtFacturas.Rows.RemoveAt(e.RowIndex)
GvFacturas.DataSource = DtFacturas
GvFacturas.DataBind()
UPGVFacturas.Update()
UpFacturas.Update()
End Sub
Public Sub ValidaFletesServicios()
If Not UsuarioActual.Empresa.Funcionalidad(562).ToEntero > 0 Then
dvFacturas.Visible = False
GvFacturas.Visible = False
GVServicios.Visible = False
End If
If UsuarioActual.Empresa.UsaInventarios And UsuarioActual.Empresa.CvePlataforma <> 2 Then
'liServicios.Visible = True
liFletesImportaciones.Visible = True
End If
End Sub
Public Function AplicarCostoIndirecto(ObjInv As ClsInventarios, ObjCompras As ClsCompras) As Boolean
Return False
Dim HayError As Boolean
Dim dtTemporal As New DataTable
dtTemporal = Nothing
If GvFacturas.Visible AndAlso GvFacturas.Rows.Count > 0 Then
Dim IdCompras = New List(Of Integer)
Dim TotalServicios As Decimal = 0
TotalServicios = TxtSubTotal.Text.ToString.ToDecimal
If TotalServicios > 0 Then
For Each row As GridViewRow In GvFacturas.Rows
IdCompras.Add(row.DataKey("CveCompra").ToEntero)
Next
For Each value As Integer In IdCompras
If ObjInv.GetMovimientosDetalle(-1, UsuarioActual.CveEmpresa, value) AndAlso ObjInv.DtResultados.Rows.Count > 0 Then
If dtTemporal Is Nothing Then
dtTemporal = ObjInv.DtResultados
Else
dtTemporal.Merge(ObjInv.DtResultados)
End If
End If
Next
'Dim DtProductos As New DataTable
' DtProductos = ObjInv.DtResultados.DefaultView.ToTable(True, "CveMovimiento", "CvePS", "Cantidad", "PU", "Total")
'Dim total As Decimal = 0
'For Each row As DataRow In DtProductos.Rows
' total = total + row("Total").ToString.ToDecimal
'Next
'If total > 0 Then
If dtTemporal IsNot Nothing Then
Dim TotalFacturas = dtTemporal.SUM("Total").ToString.ToDecimal
For Each row As DataRow In dtTemporal.Rows
Dim prorrateo As Decimal
prorrateo = (row("PU").ToString.ToDecimal * TotalServicios) / TotalFacturas
If Not ObjInv.UpdateCostoIndirectoMovimientoDetalle(row("CveMovimientoDetalle").ToString.ToEntero, prorrateo) Then
HayError = True
Exit For
End If
Next
End If
Else
Alert("El total de los servicios a vincular debe ser mayor a $0.00", TipoMensaje.MsgError)
Return True
End If
ElseIf GVServicios.Visible AndAlso GVServicios.Rows.Count > 0 Then
Dim Dtcompra As New DataTable
Dim TotalServicios As Decimal = 0
Dim chk As Boolean = False
For Each gvr As GridViewRow In GVServicios.Rows
If gvr.FCCheckBox("chkServicios").Checked Then
TotalServicios += gvr.FCLiteral("LtlTotalmodal").Text.ToDecimal
chk = True
End If
Next
If chk = False Then
Alert("Debe Seleccionar un Servicio", TipoMensaje.MsgInformacion)
Return False
Else
If ObjCompras.GetCompraDetalle(CveCompra) Then
If ObjInv.GetMovimientosDetalle(-1, UsuarioActual.CveEmpresa, CveCompra) Then
Dtcompra = ObjInv.DtResultados
Dim TotalProductos = Dtcompra.SUM("Total").ToString.ToDecimal
If TotalProductos > 0 Then
For Each row As DataRow In Dtcompra.Rows
Dim prorrateo As Decimal
prorrateo = (row("PU").ToString.ToDecimal * TotalServicios) / TotalProductos
If Not ObjInv.UpdateCostoIndirectoMovimientoDetalle(row("CveMovimientoDetalle").ToString.ToEntero, prorrateo) Then
HayError = True
Exit For
End If
Next
Else
Alert("No existen productos de inventario en esta factura", TipoMensaje.MsgError)
End If
End If
End If
End If
Else
Return False
End If
If HayError = True And ObjInv IsNot Nothing Then
Alert("Ocurrió un error al vincular un flete o servicio")
HayError = True
End If
Return HayError
End Function
Protected Sub BtnCancelar_Click(sender As Object, e As EventArgs)
'dvFacturas.Visible = False
'GvFacturas.Visible = False
'GVServicios.Visible = False
'UpFacturas.Update()
'UPGVFacturas.Update()
'UpGVServicios.Update()
End Sub
Protected Sub DdlTipoComprobante_SelectedIndexChanged(sender As Object, e As EventArgs)
If DdlTipoComprobante.SelectedValue.Contiene("NC", "DEV", "Ant") Then
If DdlTipoComprobante.SelectedValue = "NC" Then
DivReembolso.Visible = False
RBLPago.Items(2).Enabled = False
Else
DivReembolso.Visible = True
RBLPago.Items(2).Enabled = True
End If
ImgAnticiposPendientes.Visible = False
If DdlTipoComprobante.SelectedValue.Contiene("NC", "DEV") Then
paneldevolucion.Visible = True
Pnlalmaceninventarios.Visible = False
If DdlTipoComprobante.SelectedValue.Contiene("DEV") Then
DivAlmacenDev.Visible = True
End If
cargaddldevoluciones(CveProveedor, TxtSubTotal2.Text.ToDouble)
InicializaAplicaNCFact()
DivReembolso.Visible = False
RBLPago.Items(2).Enabled = False
UpPS.Update()
End If
End If
UPCondicionesPago.Update()
End Sub
#Region " ENVIA CORREO NOTICIACION - VENDEDOR "
Private Sub MandaCorreoOCVendedores(CveCompra As Integer)
'SI NO TIENE FUNCIONALIDAD DATOS DE VENTA EN OC
If Not UsuarioActual.Empresa.Funcionalidad(108) = "1" Then
Exit Sub
End If
Dim DTCorreos As New DataTable
Dim DTMovimientos As New DataTable
Dim strBody As New StringBuilder
Dim Asunto, Para, ArrayCC, Body As String
Dim ObjOC As New ClsOC
ObjOC.GetOrdenesCompraCorreo(CveCompra)
DTCorreos = ObjOC.DtResultados
ObjOC.GetOrdenesCompraMovimiento(CveCompra)
DTMovimientos = ObjOC.DtResultados
ObjOC.Dispose()
For Each row As DataRow In DTCorreos.Rows
strBody.Clear()
'SI DE UNA OC DE LA COMPRA NO SE RECIBIÓ NADA NO MANDA CORREO
If DTMovimientos.FiltraParametros($"CveOrdenCompra = {row("CveOrdenCompra")}").Rows.Count = 0 Then
Continue For
End If
strBody.Append("<html xmlns=""http: //www.w3.org/1999/xhtml""> ")
strBody.Append("<head> ")
strBody.Append(" <style type=""text/css""> ")
strBody.Append(" * {")
strBody.Append(" font-family: Verdana; ")
strBody.Append(" }")
strBody.Append(" body { ")
strBody.Append(" padding: 0px;")
strBody.Append(" margin: 0px; ")
strBody.Append(" } ")
strBody.Append(" p {")
strBody.Append(" font-size: 14px;")
strBody.Append(" }")
strBody.Append(" /*ESTILOS ESTANDAR DE TABLA*/")
strBody.Append(" table {")
strBody.Append(" font-size: 12px;")
strBody.Append(" }")
strBody.Append(" table tr{")
strBody.Append(" height:20px;")
strBody.Append(" }")
strBody.Append(" table .thead{")
strBody.Append(" background-color:#dddddd;")
strBody.Append(" text-align:center;")
strBody.Append(" vertical-align:middle;")
strBody.Append(" }")
strBody.Append(" table .tbody{")
strBody.Append(" background-color:#F7F6F3; ")
strBody.Append(" }")
strBody.Append(" </style> ")
strBody.Append("</head> ")
strBody.Append("<body>")
strBody.Append(" <h3> Vinculación de orden de compra a factura </h3>")
strBody.Append(" <p class=""mensaje"">")
strBody.AppendFormat(" Se ha vinculado la OC # <b>{0}</b> {1}.", row("Folio"), If(row("FolioREQ").ToString.Length > 0, $", relacionada a la(s) requisicion(es) # <b>{row("FolioREQ")}</b>", ""))
strBody.Append(" <br>")
strBody.Append(" Con los siguientes productos:")
strBody.Append(" </p>")
'DETALLES
strBody.Append(" <!-- DETALLES -->")
strBody.Append(" <table width=""700px"">")
strBody.Append(" <tr class=""thead"">")
strBody.Append(" <th style='width: 50px'>Cantidad</th>")
strBody.Append(" <th style='width: 100px'>UM</th>")
strBody.Append(" <th style='width: 100px'>Código</th>")
strBody.Append(" <th style='width: 450px'>Producto</th>")
strBody.Append(" </tr>")
For Each RowM As DataRow In DTMovimientos.FiltraParametros($"CveOrdenCompra = {row("CveOrdenCompra")}").Rows
strBody.AppendFormat(" <tr class=""tbody"">")
strBody.AppendFormat(" <td style='width:50px; text-align: right;'>{0}</td>", RowM("Cantidad").ToString.FormatoNumero)
strBody.AppendFormat(" <td style='width:100px;'>{0}</td>", RowM("UnidadMedida"))
strBody.AppendFormat(" <td style='width:100px;'>{0}</td>", RowM("Codigo"))
strBody.AppendFormat(" <td align='left' style='width:450px;'>{0}</td>", RowM("PS"))
strBody.AppendFormat(" </tr>")
Next
strBody.Append(" </table>")
strBody.Append("</body>")
strBody.Append("</html>")
'' ENVIO DEL CORREO
Asunto = "Vinculación de factura de OC "
Para = row("Correo").ToString
ArrayCC = ""
Body = strBody.ToString
Dim Mail As New ClsSisMail()
Mail.SendMail(ClsPaginas.EmpresaNotificaciones, Para, Asunto, Body, ArrayCC)
Next
End Sub
Private Sub MandaCorreoOCVendedoresRecepcionAlmacen(CveCompra As Integer, CveMovimiento As Integer)
'SI NO TIENE FUNCIONALIDAD DATOS DE VENTA EN OC
If Not UsuarioActual.Empresa.Funcionalidad(108) = "1" Then
Exit Sub
End If
Dim DTCorreos As New DataTable
Dim DTMovimientos As New DataTable
Dim strBody As New StringBuilder
Dim Asunto, Para, ArrayCC, Body As String
Dim ObjOC As New ClsOC
ObjOC.GetOrdenesCompraCorreo(CveCompra, CveMovimiento:=CveMovimiento)
DTCorreos = ObjOC.DtResultados
ObjOC.GetOrdenesCompraMovimiento(CveCompra, CveMovimiento:=CveMovimiento)
DTMovimientos = ObjOC.DtResultados
ObjOC.Dispose()
For Each row As DataRow In DTCorreos.Rows
strBody.Clear()
'SI DE UNA OC DE LA COMPRA NO SE RECIBIÓ NADA NO MANDA CORREO
If DTMovimientos.FiltraParametros($"CveOrdenCompra = {row("CveOrdenCompra")}").Rows.Count = 0 Then
Continue For
End If
strBody.Append("<html xmlns=""http: //www.w3.org/1999/xhtml""> ")
strBody.Append("<head> ")
strBody.Append(" <style type=""text/css""> ")
strBody.Append(" * {")
strBody.Append(" font-family: Verdana; ")
strBody.Append(" }")
strBody.Append(" body { ")
strBody.Append(" padding: 0px;")
strBody.Append(" margin: 0px; ")
strBody.Append(" } ")
strBody.Append(" p {")
strBody.Append(" font-size: 14px;")
strBody.Append(" }")
strBody.Append(" /*ESTILOS ESTANDAR DE TABLA*/")
strBody.Append(" table {")
strBody.Append(" font-size: 12px;")
strBody.Append(" }")
strBody.Append(" table tr{")
strBody.Append(" height:20px;")
strBody.Append(" }")
strBody.Append(" table .thead{")
strBody.Append(" background-color:#dddddd;")
strBody.Append(" text-align:center;")
strBody.Append(" vertical-align:middle;")
strBody.Append(" }")
strBody.Append(" table .tbody{")
strBody.Append(" background-color:#F7F6F3; ")
strBody.Append(" }")
strBody.Append(" </style> ")
strBody.Append("</head> ")
strBody.Append("<body>")
strBody.Append(" <h3> Notificación de recepción de material </h3>")
strBody.Append(" <p class=""mensaje"">")
strBody.AppendFormat(" Se confirma recepción de material en almacén <b>{0}</b> vinculado la OC # <b>{1}</b> {2}.", DTMovimientos.FiltroPrimeroValor("Almacen"), row("Folio").ToString, If(row("FolioREQ").ToString.Length > 0, $", relacionada a la(s) requisicion(es) # <b>{row("FolioREQ")}</b>", ""))
strBody.Append(" <br>")
strBody.Append(" Con los siguientes productos:")
strBody.Append(" </p>")
'DETALLES
strBody.Append(" <!-- DETALLES -->")
strBody.Append(" <table width=""700px"">")
strBody.Append(" <tr class=""thead"">")
strBody.Append(" <th style='width: 50px'>Cantidad</th>")
strBody.Append(" <th style='width: 100px'>UM</th>")
strBody.Append(" <th style='width: 100px'>Código</th>")
strBody.Append(" <th style='width: 450px'>Producto</th>")
strBody.Append(" </tr>")
For Each RowM As DataRow In DTMovimientos.FiltraParametros($"CveOrdenCompra = {row("CveOrdenCompra")}").Rows
strBody.AppendFormat(" <tr class=""tbody"">")
strBody.AppendFormat(" <td style='width:50px; text-align: right;'>{0}</td>", RowM("Cantidad").ToString.FormatoNumero)
strBody.AppendFormat(" <td style='width:100px;'>{0}</td>", RowM("UnidadMedida"))
strBody.AppendFormat(" <td style='width:100px;'>{0}</td>", RowM("Codigo"))
strBody.AppendFormat(" <td align='left' style='width:450px;'>{0}</td>", RowM("PS"))
strBody.AppendFormat(" </tr>")
Next
strBody.Append(" </table>")
strBody.Append("</body>")
strBody.Append("</html>")
'' ENVIO DEL CORREO
Asunto = "Recepción de Material de OC "
Para = row("Correo").ToString
ArrayCC = row("CorreoAsistente").ToString
Body = strBody.ToString
Dim Mail As New ClsSisMail()
Mail.SendMail(ClsPaginas.EmpresaNotificaciones, Para, Asunto, Body, ArrayCC)
Next
End Sub
'VIEJO - COMENTADO IPP 12 JULIO 2017
'Private Sub MandaCorreo(CveCompra As Integer)
' Dim ObjOC As New ClsOC
' Dim DTCorreos As New DataTable
' Dim DTFolios As New DataTable
' Dim strBody As New StringBuilder
' ObjOC.GetOrdenesCompraCorreo(CveCompra)
' DTCorreos = ObjOC.DtResultados
' ObjOC.GetComprasOC(CveCompra)
' DTFolios = ObjOC.DtResultados
' strBody.AppendFormat("Se ha vinculado la compra <b>{0}-{1}</b> a la siguiente OC", Serie, Folio)
' strBody.Append("<html xmlns=""http://www.w3.org/1999/xhtml""> ")
' strBody.Append("<head> ")
' strBody.Append("</head> ")
' strBody.Append("<body> ")
' 'Cargo el detalle
' strBody.Append(" <div style='width: 550px'> ")
' strBody.Append(" <fieldset> ")
' strBody.Append(" <legend>Ordenes de compra</legend> ")
' strBody.Append(" <table width=""550px""> <tr style='background-color:gray;color:White;font-family:Verdana;font-size:10px;text-align:center;vertical-align:middle;font-weight:bold;height:20px;text-decoration:none;'>
' <th scope='col' style='width: 50px'>Folio</th>
' <th scope='col' style='width: 50px'>Tipo</th>")
' For Each row As DataRow In DTCorreos.Rows
' Dim Asunto, Para, ArrayCC, Body As String
' Asunto = "Vinculación de Factura"
' Para = row("Correo").ToString
' ArrayCC = ""
' For Each RowM As DataRow In DTFolios.Rows
' strBody.AppendFormat("<tr class='Texto'><td style='width:50px;'>{0}</td><td style='width:50px;'>{1}</td></tr>", RowM("Folio").ToString, RowM("Tipo"))
' Next
' strBody.Append(" </table> ")
' strBody.Append(" </fieldset> ")
' strBody.Append(" </div> ")
' strBody.Append("</body></html>")
' Body = strBody.ToString
' ObjOC.Dispose()
' Dim Mail As New ClsSisMail()
' Mail.SendMail(ClsPaginas.EmpresaNotificaciones, Para, Asunto, Body, ArrayCC)
' Next
'End Sub
#End Region
#End Region
#Region " CIERRE PERIODO "
Private Function ValidaCierrePeriodo() As Boolean
'solo se permiten, mes actual, mes anterior <= #dias
Dim mesesTrans As Integer = DateDiff(DateInterval.Month, TxtFecha.Text.ToDate, Now).ToEntero
If mesesTrans = 0 OrElse (mesesTrans = 1 AndAlso Day(Now) <= UsuarioActual.Empresa.Funcionalidad(123).ToEntero) Then
Return True
End If
Return False
'Dim mesesTrans As Integer = DateDiff(DateInterval.Month, TxtFecha.Text.ToDate, Now).ToEntero
'If mesesTrans > 1 OrElse Day(Now) >= UsuarioActual.Empresa.Funcionalidad(123).ToEntero Then
' Return True
'End If
'Return False
End Function
#End Region
#Region " AGREGA POR SERIE/LOTE "
Private Sub CreaDtDetalle()
If DtDatosDetalle Is Nothing Then
DtDatosDetalle = New DataTable
DtDatosDetalle.Columns.Add("CvePS", GetType(Integer))
DtDatosDetalle.Columns.Add("CveUM", GetType(Integer))
DtDatosDetalle.Columns.Add("PU", GetType(Decimal))
DtDatosDetalle.Columns.Add("Serie", GetType(String))
DtDatosDetalle.Columns.Add("FechaCaducidad", GetType(String))
DtDatosDetalle.Columns.Add("CvePersonal", GetType(Integer))
End If
End Sub
Private Sub CargaSerie()
Dim AplicaCaducidad = False
If GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=CvePSSerieLote).Rows(0) IsNot Nothing Then
AplicaCaducidad = If(GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=CvePSSerieLote).Rows(0)("AplicaCaducidad").ToString = "True", True, False)
End If
If AplicaCaducidad Then
GvSerie.Columns(1).Visible = True
TdCaducidad1.Visible = True
TdCaducidad2.Visible = True
Else
GvSerie.Columns(1).Visible = False
TdCaducidad1.Visible = False
TdCaducidad2.Visible = False
End If
GvSerie.DataSource = DtDatosDetalle.FiltraParametros(String.Format("CvePS = {0}", CvePSSerieLote))
GvSerie.DataBind()
'VALIDA QUE SIGA AGREGANDO
If Not DtDatosDetalle.FiltraParametros(String.Format("CvePS = {0}", CvePSSerieLote)).Rows.Count < LbCantidadSerie.Text.ToEntero Then
BtnAgregarPS.Enabled = False
Else
BtnAgregarPS.Enabled = True
End If
'SI TIENE ENTRADA POR SERIE LOTE, BLOQUEAMOS CHECK Y TXTCANTIDAD
Dim Contador = 0
For Each Gvr As GridViewRow In GvInv.Rows
Gvr.FCTextBox("TbCantidad").Enabled = False
If Gvr.DataKey("CvePS").ToEntero = CvePSSerieLote Then
Contador = DtDatosDetalle.FiltraParametros(String.Format("CvePS = {0}", Gvr.DataKey("CvePS"))).Rows.Count
If DtDatosDetalle IsNot Nothing AndAlso Contador > 0 Then
Gvr.FCCheckBox("cbInv").Enabled = False
'Gvr.FCCheckBox("cbInv").Checked = True
Gvr.FCTextBox("TbCantidad").Enabled = False
Gvr.FCTextBox("TbCantidad").Text = Contador.ToString
Else
Gvr.FCCheckBox("cbInv").Enabled = False
Gvr.FCTextBox("TbCantidad").Enabled = False
Gvr.FCTextBox("TbCantidad").Text = "0"
End If
End If
Next
UpINV.Update()
UpSerie.Update()
TxtSerieLote.Focus()
RegistraScript(String.Format("$('#DivSerie').on('shown.bs.modal', function () {{$('#DivSerie').focus(); $('#{0}').trigger(jQuery.Event('keypress', {{which: 13}})); }});$('#DivSerie').modal('show'); ", TxtSerieLote.ClientID))
End Sub
Protected Sub BtnAgregarPS_Click(sender As Object, e As EventArgs)
Dim SerieLote = TxtSerieLote.Text.Replace(" ", String.Empty)
Dim AplicaCaducidad = False
Dim dr As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=CvePSSerieLote).FiltroPrimero("", "PS")
If dr IsNot Nothing Then AplicaCaducidad = dr("AplicaCaducidad").ToString = "True"
'VALIDA QUE LA SERIE NO SEA IGUAL AL CODIGO O CODIGOBARRAS
If SerieLote <> "" And (SerieLote = dr("Codigo").ToString.ToUpper Or SerieLote = dr("CodigoBarras").ToString.ToUpper) Then
Alert($"La serie indicada <b>{SerieLote}</b> coincide con el codigo o codigo de barras del producto. Por favor rectifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
Dim Row = DtDatosDetalle.NewRow
Row("CvePS") = CvePSSerieLote
Row("CveUM") = CveUMSerieLote
Row("PU") = PUSerieLote
Row("Serie") = SerieLote
Row("FechaCaducidad") = If(AplicaCaducidad, TxtFechaCaducidad.Text, MinFecha.ToShortDateString)
DtDatosDetalle.Rows.Add(Row)
TxtSerieLote.Text = ""
TxtFechaCaducidad.Text = Now.ToShortDateString
CargaSerie()
End Sub
Protected Sub BtnSerieLote_Click(sender As Object, e As EventArgs)
Dim Argumentos = CType(sender, Button).CommandArgument.Split("°"c)
LbProducto.Text = Argumentos(3)
LbCantidadSerie.Text = Argumentos(4)
CvePSSerieLote = Argumentos(0).ToEntero
CveUMSerieLote = Argumentos(1).ToEntero
PUSerieLote = Argumentos(2).ToDecimal
CargaSerie()
End Sub
Protected Sub GvSerie_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles GvSerie.RowDeleting
DtDatosDetalle.Rows.Remove(DtDatosDetalle.Rows(e.RowIndex))
CargaSerie()
End Sub
#End Region
#Region " TIPO CAMBIO "
Protected Sub DdlMoneda_SelectedIndexChanged(sender As Object, e As EventArgs)
CambiaMoneda()
If DdlProveedor.SelectedValue.ToEntero > 0 Then
CargaAnticipos(DdlProveedor.SelectedValue.ToEntero)
End If
End Sub
Private Sub CambiaMoneda(Optional RecargaTipoCambio As Boolean = True)
TxtFecha.Attributes.Remove("onblur")
If DdlMoneda.SelectedValue.ToEntero > 1 Then
TipoCambio = If(RecargaTipoCambio, GlobalTipoCambio(TxtFecha.Text.ToDate).ToDecimal, TipoCambio)
LblTC.Text = String.Format("TC: {0}", TipoCambio.ToString("N4"))
TxtTC.Text = TipoCambio.ToString("N4")
If UsuarioActual.Empresa.UsaAC Then
TxtFecha.Attributes.Add("onblur", "CambiaFecha();CambiaFechaTC();")
Else
TxtFecha.Attributes.Add("onblur", "CambiaFechaTC();")
End If
If CveCompra <= 0 Then 'And CveFactura <= 0 [IPP] 11Junio2018
DivTC.Visible = True
LblTC.Visible = False
Else
DivTC.Visible = False
LblTC.Visible = True
End If
Else
If UsuarioActual.CveEmpresa.Contiene({4, 7, 11, 12, 145}) Then
RegistraScript("$('#ModalPesos').modal('show');")
TxtConvertirPesos.Text = If(TipoCambio > 0, TipoCambio, GlobalTipoCambio(TxtFecha.Text.ToDate)).ToString.FormatoNumero
End If
TipoCambio = 1
LblTC.Text = ""
TxtTC.Text = ""
If UsuarioActual.Empresa.UsaAC Then
TxtFecha.Attributes.Add("onblur", "CambiaFecha()")
End If
End If
CargaCuentas()
End Sub
Protected Sub BtnCambiaFechaTC_Click(sender As Object, e As EventArgs)
LblTC.Text = GlobalTipoCambio(TxtFecha.Text.ToDate).ToString.FormatoNumero(4)
TxtTC.Text = GlobalTipoCambio(TxtFecha.Text.ToDate).ToString.FormatoNumero(4)
End Sub
#End Region
#Region " CONVERTIR PESOS "
Protected Sub BtnConvertirPesos_Click(sender As Object, e As EventArgs)
Dim TipoCambioTemp = TxtConvertirPesos.Text.ToDouble
If TipoCambioTemp <= 0 Then
Exit Sub
End If
For Each Dr As DataRow In TmpDT.Rows
Dr("PU") = Dr("PU").ToString.ToDecimal * TipoCambioTemp
Dr("IVA") = Dr("IVA").ToString.ToDecimal * TipoCambioTemp
Dr("RetIVA") = Dr("RetIVA").ToString.ToDecimal * TipoCambioTemp
Dr("RetISR") = Dr("RetISR").ToString.ToDecimal * TipoCambioTemp
Dr("IEPSPS") = Dr("IEPSPS").ToString.ToDecimal * TipoCambioTemp
Dr("Descuento") = Dr("Descuento").ToString.ToDecimal * TipoCambioTemp
Dr("OtrosGastos") = Dr("OtrosGastos").ToString.ToDecimal * TipoCambioTemp
Dim Total = (Dr("Cantidad").ToString.ToDecimal * Dr("PU").ToString.ToDecimal) - Dr("Descuento").ToString.ToDecimal + Dr("OtrosGastos").ToString.ToDecimal
Dr("Total") = Total
Next
GvPS.DataSource = TmpDT
GvPS.DataBind()
UpPS.Update()
TxtSubTotal.Text = (TmpDT.SUMD("Total") + TmpDT.SUMD("Descuento")).FormatoNumero
TxtSubTotal2.Text = TmpDT.SUMD("Total").FormatoNumero()
TxtIVA.Text = TmpDT.SUMD("IVA").FormatoNumero()
'IPP CAMBIADO - 5 DICIEMBRE 2016
'TxtTotal.Text = (TxtSubTotal2.Text.ToDouble + TxtIVA.Text.ToDouble).ToString.FormatoNumero.Replace(","c, "")
TxtTotal.Text = (TmpDT.SUMD("Total") + TmpDT.SUMD("IVA") + TmpDT.SUMD("IEPSPS") - TmpDT.SUMD("RetIVA") - TmpDT.SUMD("RetISR")).FormatoNumero
SubTotalOriginal = TxtSubTotal.Text.ToDouble
SubTotal2Original = TxtSubTotal2.Text.ToDouble
If TrDescuento.Visible Then TxtDescuento.Text = (TmpDT.SUMD("Descuento")).ToString.FormatoNumero
If TrRetIVA.Visible Then TxtRetIVA.Text = (TmpDT.SUMD("RetIVA")).ToString.FormatoNumero
If TrRetISR.Visible Then TxtRetISR.Text = (TmpDT.SUMD("RetISR")).ToString.FormatoNumero
If TrIEPS.Visible Then TxtIEPS.Text = (TmpDT.SUMD("IEPSPS")).ToString.FormatoNumero
If TrOtrosImpuestos.Visible Then TxtOtrosImpuestos.Text = (TmpDT.SUMD("OtrosGastos")).ToString.FormatoNumero
If TrRedondeo.Visible Then TxtRedondeo.Text = (TxtRedondeo.Text.ToDouble * TipoCambioTemp).ToString.FormatoNumero.Replace(","c, "")
If TxtSubTotal2.Text.ToDouble <> TmpDT.SUM("Total") Then
AjustaImporteUltimoConcepto((TxtSubTotal2.Text.ToDouble - TmpDT.SUM("Total")).ToString.ToDecimal)
End If
DdlMoneda.Enabled = False
RegistraScript("$('#ModalPesos').modal('hide');")
End Sub
#End Region
#Region " TOTALES: VALIDA Y CALCULA "
Private Sub AsignaValoresOriginales(SubTotal As Double, SubTotal2 As Double, IVA As Double, RetIVA As Double, RetISR As Double, Total As Double)
SubTotalOriginal = SubTotal
SubTotal2Original = SubTotal2
IVAOriginal = IVA
RetIVAOriginal = RetIVA
RetISROriginal = RetISR
TotalOriginal = Total
End Sub
Private Sub CalculaTotales(Optional CalculaIVA As Boolean = False, Optional EsNoDeducible As Boolean = False)
'VARIABLES DE CALCULO
Dim SubTotal, Descuentos, Amortizacion, IVA, SubTotal2, RetIVA, RetISR, IEPSPS, Total, SubTotalIVA, SubTotalIEPSIVA As Double
'SE ACTUALIZA EL IVA DEL DtDetalle SI ES QUE AHORA SE VA A TOMAR EN CUENTA EL IVA
'For Each Row As DataRow In TmpDT.Rows
' If CalculaIVA Then
' Row("IVA") = Row("IVAPorcentaje").ToString.ToDouble * Row("Total").ToString.ToDouble
' Else
' Row("IVA") = 0
' End If
'Next
'HACEMOS CALCULOS
SubTotalIVA = TmpDT.SUM("IVA")
SubTotalIEPSIVA = TmpDT.SUM("IEPSPSIVA")
SubTotal = TmpDT.SUM("Total") + TmpDT.SUM("Descuento")
RetIVA = TmpDT.SUM("RetIVA")
RetISR = TmpDT.SUM("RetISR")
IEPSPS = TmpDT.SUM("IEPSPS")
If CveCompra > 0 AndAlso CveFactura > 0 Then
IVA = TxtIVA.Text.ToDecimal
Else
IVA = If(TmpDT.SUM("IVA") > 0, SubTotalIVA + SubTotalIEPSIVA, 0)
End If
'If CalculaIVA Then IVA = TxtIVA.Text.ToDouble
Descuentos = TmpDT.SUM("Descuento")
'[IPP] SI YA ES COMPRA REGISTRADA NO CONSIDERA LA AMORTIZACIÓN PARA EL CALCULO DE TOTAL
If Not CveCompra > 0 Then
Amortizacion = LblAmortizacion.Text.Trim.ToDouble
End If
'RETENCIONES
Dim Retenciones = 0D
Retenciones = RetIVA.ToDecimal
Retenciones += RetISR.ToDecimal
SubTotal2 = SubTotal - Descuentos ' - Amortizacion '[IPP] COMENTADO CASO JAM 12653 CON NC 27122 | 23/MAYO/2018
Total = SubTotal2 + IVA + IEPSPS - Retenciones
'ASIGNAMOS VALORES A VISTA
If CveCompra > 0 Or CveFactura > 0 Or OCVinculada Then
TxtSubTotal.Text = SubTotal.ToString.FormatoNumero()
TxtSubTotal2.Text = SubTotal2.ToString.FormatoNumero()
TxtDescuento.Text = Descuentos.ToString.FormatoNumero()
If EsNoDeducible Then
TxtIVA.Text = IVA.ToString.FormatoNumero()
TxtRetIVA.Text = RetIVA.ToString.FormatoNumero()
If TxtRetIVA.Text.ToDouble > 0 Then TrRetIVA.Visible = True
TxtRetISR.Text = RetISR.ToString.FormatoNumero()
If TxtRetISR.Text.ToDouble > 0 Then TrRetISR.Visible = True
TxtIEPS.Text = IEPSPS.ToString.FormatoNumero()
If TxtIEPS.Text.ToDouble > 0 Then TrIEPS.Visible = True
End If
If TxtDescuento.Text.ToDouble > 0 Then TrDescuento.Visible = True
If ActualizaTotales And UsuarioActual.CveEmpresa = 72 Then TxtTotal.Text = Total.ToString.FormatoNumero()
Else
TxtSubTotal.Text = SubTotal.ToString.FormatoNumero()
TxtSubTotal2.Text = SubTotal2.ToString.FormatoNumero()
TxtIVA.Text = IVA.ToString.FormatoNumero()
TxtDescuento.Text = Descuentos.ToString.FormatoNumero()
If TxtDescuento.Text.ToDouble > 0 Then TrDescuento.Visible = True
TxtRetIVA.Text = RetIVA.ToString.FormatoNumero()
If TxtRetIVA.Text.ToDouble > 0 Then TrRetIVA.Visible = True
TxtRetISR.Text = RetISR.ToString.FormatoNumero()
If TxtRetISR.Text.ToDouble > 0 Then TrRetISR.Visible = True
TxtIEPS.Text = IEPSPS.ToString.FormatoNumero()
If TxtIEPS.Text.ToDouble > 0 Then TrIEPS.Visible = True
TxtTotal.Text = Total.ToString.FormatoNumero()
'VALORES PROPIEDAD
CompraSaldo = Total
HfTotalCompra.Value = Total.ToString
End If
'CUANDO SEA COMPRA, FACTURA O VENGA DE VINCULACIÓN OC NO SE MODIFICAN VALORES
'SE VERIFICA SI ALGUN DATO ES DIFERENTE PARA MOSTRAR COLUMNA CON VALORES ORIGINALES
If (CveCompra > 0 Or CveFactura > 0 Or OCVinculada) And Not EsNoDeducible Then
If SubTotal <> SubTotalOriginal Then
OriginalesVisible(True)
LbSubTotalOriginal.Text = SubTotalOriginal.ToString.FormatoNumero(2)
Else
OriginalesVisible(False)
End If
End If
If Not CveCompra > 0 Then 'cuando se está registrando manualmente y se va amortizar
LblSaldoFactura.Text = TxtTotal.Text.FormatoNumero
UpAnticipos.Update()
End If
LblRetIVA.Text = (If(SubTotal2 > 0, (RetIVA / SubTotal2), 0) * 100).FormatoNumero(3) + "%"
LblRetISR.Text = (If(SubTotal2 > 0, (RetISR / SubTotal2), 0) * 100).FormatoNumero(3)
'IMPORTES DE RESTRICCION
TxtDocumentoImporteFE.Text = Total.ToString.FormatoNumero(2)
RVDocumentoImporte.MaximumValue = Total.ToString.FormatoNumero(2)
RVDocumentoImporteFE.MaximumValue = RVDocumentoImporte.MaximumValue
RVDocumentoImporteCaja.MaximumValue = RVDocumentoImporte.MaximumValue
CargaRetIVAConcepto()
CargaRetISRConcepto()
Dim NumNoDed As Integer = TmpDT.COUNT("CvePS", "NoDeducible = True ")
If NumNoDed > 0 Then GvPS.Columns(11).Visible = True 'visualiza columnas de nodeducibles
If DdlTipoComprobante.SelectedValue.Contiene("NC", "DEV") And CveFactura <= 0 Then
InicializaAplicaNCFact()
End If
End Sub
Private Sub OriginalesVisible(Accion As Boolean)
tdT0.Visible = Accion
tdT1.Visible = Accion
tdT2.Visible = Accion
tdT3.Visible = Accion
tdT4.Visible = Accion
tdT5.Visible = Accion
tdT6.Visible = Accion
tdT7.Visible = Accion
tdT8.Visible = Accion
tdT9.Visible = Accion
tdT10.Visible = Accion
tdT11.Visible = Accion
End Sub
Private Function ValidaTotalesGuardar() As Boolean
Dim EsValido = True
'VALIDA IMPORTES
'VALIDA TOTAL CON LOS IMPORTES TOTALES
Dim TempSubTotal, TempDescuentos, TempIVA, TempSubTotal2, TempRetIVA, TempRetISR, TempTotal, DifTotales, TempIEPS As Double
Dim Amortizacion As Decimal = 0
Dim TieneAmortizacion As Boolean = False
If ListaDocumentos IsNot Nothing AndAlso ListaDocumentos.Count > 0 AndAlso ArrAnticipos IsNot Nothing AndAlso ArrAnticipos.Count > 0 Then
TieneAmortizacion = True
End If
If CveCompra < 0 AndAlso Not TieneAmortizacion Then
LblAmortizacion.Text = "0.00"
End If
If UsuarioActual.CveEmpresa = 119 AndAlso TieneAmortizacion Then
Amortizacion = LblAmortizacion.Text.Trim.ToDecimal
TxtSubTotal.Text = (TxtSubTotal.Text.ToDouble + Amortizacion).ToString
End If
TempSubTotal = TxtSubTotal.Text.ToDouble
SubTotalOriginal = TxtSubTotal.Text.ToDouble
SubTotal2Original = TxtSubTotal2.Text.ToDouble
TempDescuentos = TxtDescuento.Text.Trim.ToDouble + Amortizacion
TempSubTotal2 = TempSubTotal - TempDescuentos
TempIVA = TxtIVA.Text.ToDouble
TempIEPS = TxtIEPS.Text.ToDouble
TempRetIVA = TxtRetIVA.Text.ToDouble
TempRetISR = TxtRetISR.Text.ToDouble
TempTotal = Math.Round(TempSubTotal2 + TempIVA + TempIEPS - TempRetIVA - TempRetISR + TxtOtrosImpuestos.Text.ToDouble - Amortizacion, 2)
DifTotales = TxtTotal.Text.ToDouble - TempTotal
Dim DiferenciaPermitida = 0.6
If Math.Abs(DifTotales) > DiferenciaPermitida Then
Alert(String.Format("Los importes de los conceptos (Productos/Servicios) no cuadran con el total. Por favor verifique y vuelva a intentar.[{0}]", Math.Abs(DifTotales) - DiferenciaPermitida), TipoMensaje.MsgAdvertencia)
EsValido = False
ElseIf DifTotales <> 0 Then
TxtSubTotal2.Text = (TxtSubTotal2.Text.ToDouble + DifTotales).ToString
TxtSubTotal.Text = (TxtSubTotal.Text.ToDouble + DifTotales).ToString
SubTotalOriginal = TxtSubTotal.Text.ToDouble
SubTotal2Original = TxtSubTotal2.Text.ToDouble
End If
Dim DiferenciaSubtotales = 0.0D
If CveCompra > 0 Or CveFactura > 0 Or OCVinculada Then
If SubTotalOriginal = Nothing Then
SubTotalOriginal = 0
End If
If SubTotal2Original = Nothing Then
SubTotal2Original = 0
End If
DiferenciaSubtotales = SubTotal2Original.ToString.ToDecimal - TmpDT.SUM("Total").ToString.ToDecimal
'[IPP] PARCHE: Factura TELMEX para APH 12/ENERO/2018
If CveFactura = 286290 Then
DiferenciaSubtotales += TxtDescuento.Text.ToDecimal
End If
If Math.Abs(DiferenciaSubtotales) > 1 And Not EsNoDeducible Then
Alert("Los importes de los conceptos (Productos/Servicios) no cuadran con el total. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia)
EsValido = False
Else
AjustaImporteUltimoConcepto(DiferenciaSubtotales)
End If
Else
DiferenciaSubtotales = (TxtSubTotal2.Text.ToDouble - TmpDT.SUM("Total")).ToString.ToDecimal
If Math.Abs(DiferenciaSubtotales) > 1 Then
Alert("Los importes de los conceptos (Productos/Servicios) no cuadran con el total. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia)
EsValido = False
Else
AjustaImporteUltimoConcepto(DiferenciaSubtotales)
End If
End If
Return EsValido
End Function
Private Sub LnkAcarreo_Click(sender As Object, e As EventArgs) Handles LnkAcarreo.Click
VerificarAcarreo()
End Sub
Private Sub VerificarAcarreo()
RegistraScript(String.Format("$('#{0}').modal('show');", "divAddAcarreo"))
End Sub
Private Sub BtnAgregarAcarreo_Click(sender As Object, e As EventArgs) Handles BtnAgregarAcarreo.Click
tDTAcarreos.Clear()
TotAcarreos = 0
For Each Gvr As GridViewRow In GvAcarreo.Rows
If CType(Gvr.FindControl("ChkRow"), System.Web.UI.WebControls.CheckBox).Checked = True Then
Dim Row As DataRow = Nothing
Row = tDTAcarreos.NewRow
Row("CvePreEstimacion") = Gvr.DataKey("CvePreEstimacion")
Row("Importe") = Gvr.DataKey("Importe")
tDTAcarreos.Rows.Add(Row)
TotAcarreos = TotAcarreos + Gvr.DataKey("Importe").ToDouble
End If
Next
UpPS.Update()
RegistraScript(String.Format("$('#{0}').modal('hide');", "divAddAcarreo"))
End Sub
#End Region
#Region "Historial de Modificacion"
Private Sub CargaGvBitacora()
' COMENTADO POR IPP PARA SUBIR 5 ABRIL 2017
Dim ObjGral As New ClsGenerales()
If ObjGral.GetHistorialBitacora(-1, -1, -1, -1, -1, CveCompra, -1, UsuarioActual.CveEmpresa) Then
GvBitacora.DataSource = ObjGral.DtResultados
GvBitacora.DataBind()
End If
ObjGral.Dispose()
End Sub
#End Region
#Region " FLETES "
Private Sub CargaFletes()
If UsuarioActual.CveEmpresa <> 125 Or CveCompra > 0 Then
Exit Sub
End If
HLModalFletes.Visible = True
Dim ObjVentas As New ClsVentas
If ObjVentas.GetFletes(UsuarioActual.CveEmpresa) Then
GVFletes.DataSource = ObjVentas.DtResultados
GVFletes.DataBind()
End If
UpFletes.Update()
ObjVentas.Dispose()
End Sub
#End Region
#Region "I M P R I M I R D E S G L O S E"
Private Sub LnkExportaGv_Click(sender As Object, e As EventArgs) Handles LnkExportaGv.Click
Dim dt As New DataTable
dt.Columns.Add("Consecutivo", GetType(Integer))
dt.Columns.Add("Cantidad", GetType(Double))
dt.Columns.Add("PS", GetType(String))
dt.Columns.Add("Observacion", GetType(String))
dt.Columns.Add("UM", GetType(String))
dt.Columns.Add("Referencia", GetType(String))
dt.Columns.Add("Personal", GetType(String))
For Each Gv As GridViewRow In GvPersonal.Rows
Dim Row As DataRow = Nothing
Row = dt.NewRow()
Row("Consecutivo") = Gv.FCLabel("LtlConsecutivo").Text
Row("Cantidad") = Gv.FCLiteral("LtlCantidad").Text.ToDouble
Row("UM") = Gv.FCLabel("LtlUnidadMedida").Text
Row("PS") = Gv.FCHyperLink("HplPS").Text
Row("Observacion") = Gv.Cells(4).Text
Row("Referencia") = Gv.FCTextBox("TxtReferencia").Text
Row("Personal") = Gv.FCDropDownList("DdlPersonalGv").SelectedItem
dt.Rows.Add(Row)
Next
ExportToExcel(dt, "Desglose")
End Sub
#End Region
'DE AQUI PARA ABAJO SE ESTAN REORDENANDO REGIONES --- FAVOR DE SI SE MUEVE UNA COSITA O SE HACE UNA NUEVA FUNCION/METODO AGRUPARLO EN LA REGION CORRECTA O GENERAR UNA EN CASO DE NO EXISTIR
#Region " MODAL ADD PS - AGREGAR Y EDITAR PS (PARTIDA-CONCEPTO) "
Private Sub HabilitaEdicionManualAgregar()
If Not (CveCompra > 0 Or CveFactura > 0 Or OCVinculada) Then
DdlIVA.Enabled = True
TxtRetIVAModal.Enabled = True
TxtRetISRModal.Enabled = True
TxtIEPSModal.Enabled = True
End If
End Sub
Private Sub LnkAddPS_Click(sender As Object, e As EventArgs) Handles LnkAddPS.Click
Modalidad = "A"
LimpiaAgregar()
ChkAgregar.Checked = True
divagregrarotrops.Visible = True
UpPSS.Update()
RegistraScript(String.Format("$('#{0}').modal('show');", "divAddProducto"))
If chkImportacion.Checked Then
divImporteImportacion.Visible = True
divIVA.Visible = False
Else
divIVA.Visible = True
divImporteImportacion.Visible = False
End If
End Sub
Private Sub LimpiaAgregar()
'VALORES ESCONDIDOS
HdnUnidadMedida.Value = "-1"
LblUnidadMedida.Text = "UM"
HdnClasificacion.Value = "-1"
HdnPS.Value = "-1"
ViewState("IVAPS") = -1
ViewState("RetIVA") = -1
ViewState("RetISR") = -1
ViewState("IEPSPS") = -1
ViewState("IEPSPSIVA") = -1
ChkEsNoDeduciblePS.Checked = False
'FORMULARIO
TxtCantidad.Text = ""
DdlClasificacion.SelectedValueExist(-1)
CargaPS(-1)
If Not UsuarioActual.Empresa.Funcionalidad(105).ToString = "1" Then
DdlPS.SelectedValue = "-1"
Else
DdlPS.SelectedValue = ""
DdlPS.SelectedText = ""
End If
ddlUM.Items.Clear()
TxtObsPS.Text = ""
DdlProyecto.SelectedValueExist(-1)
CargaSubProyecto()
DdlSubProyecto.SelectedValueExist(-1)
DdlTipoGasto.SelectedValueExist(-1)
TxtPrecio.Text = ""
LblTotalPS.Text = ""
DdlIVA.SelectedValueExist("1")
DdlIVA.Enabled = If(CveCompra > 0 Or CveFactura > 0 Or OCVinculada, False, True)
TxtRetIVAModal.Text = ""
TxtRetISRModal.Text = ""
TxtIEPSModal.Text = ""
TxtDescuentoModal.Text = ""
TxtOtrosGastos.Text = ""
DivAddProductoAliasPS.Visible = False
LbAgregar.Text = "Agregar"
UPPClasificacion.Update()
UpPSS.Update()
End Sub
Public Sub Edit_Click(sender As Object, e As EventArgs)
Dim GvRow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow)
Con = GvRow.DataKey("Consec").ToEntero
Index = Con
'MODALIDAD UPDATE
Modalidad = "U"
LbAgregar.Text = "Actualizar"
H1.InnerText = "Actualizar Concepto"
DivAddProductoAliasPS.Visible = False
'CARGA VALROES DEL CONCEPTO
TxtCantidad.Text = GvRow.DataKey("Cantidad")
DdlClasificacion.SelectedValueExist(If(GvRow.DataKey("CveClasificacion") = "0", "-1", GvRow.DataKey("CveClasificacion")))
DdlClasificacionChange()
If GvRow.DataKey("CvePS") = "0" Then
If UsuarioActual.Empresa.Funcionalidad(105) = "1" Then
DdlPS.SelectedValue = GvRow.DataKey("CvePS")
DdlPS.SelectedText = GvRow.DataKey("PS")
Else
DdlPS.ddl.Items.Insert(0, New ListItem(GvRow.DataKey("PS"), "0"))
End If
'DivAddProductoAliasPS.Visible = True
Else
'Si el PS esta inactivo se lo inserto manual
If GlobalDTPSSimplificado(UsuarioActual.CveEmpresa, CveClasificacion:=DdlClasificacion.SelectedValue.ToEntero).FiltroPrimeroValor("CveEstado", $"CvePS = '{GvRow.DataKey("CvePS")}'") <> "True" Then
DdlPS.ddl.Items.Insert(0, New ListItem(GvRow.DataKey("PS"), "0"))
Else
DdlPS.SelectedValue = GvRow.DataKey("CvePS")
End If
If UsuarioActual.Empresa.Funcionalidad(105) = "1" Then
DdlPS.SelectedText = GvRow.DataKey("PS")
End If
End If
ddlUM.Items.Clear()
If UsuarioActual.Empresa.UsaInventarios Then
ddlUM.DataSource = GlobalDTProductosServiciosEquivalencias(GvRow.DataKey("CvePS").ToEntero, -1, UsuarioActual.CveEmpresa)
Else
ddlUM.DataSource = GlobalDTUnidadesMedida(UsuarioActual.CveEmpresa)
End If
ddlUM.Items.Insert(0, New ListItem("Seleccione", "-1"))
ddlUM.SelectedValue = "-1"
ddlUM.DataBind()
ddlUM.SelectedValueExist(GvRow.DataKey("CveUM"))
If ddlUM.SelectedValue <> GvRow.DataKey("CveUM") Then
ddlUM.Items.Insert(1, New ListItem(GvRow.DataKey("UM"), GvRow.DataKey("CveUM")))
ddlUM.SelectedValueExist(GvRow.DataKey("CveUM"))
End If
TxtObsPS.Text = GvRow.DataKey("Obs")
If UsuarioActual.Empresa.Tipo_CentroCosto <> 1 And UsuarioActual.Empresa.Tipo_CentroCosto <> 2 Then
DdlProyecto.SelectedValueExist(GvRow.DataKey("CveProyecto"))
Else
DdlProyecto.SelectedValueExist("-1")
End If
CargaSubProyecto()
'DdlProyecto.SelectedValueExist(GvRow.DataKey("CveProyecto"))
DdlSubProyecto.SelectedValueExist(GvRow.DataKey("CveSubProyecto"))
DdlSubProyecto_SelectedIndexChanged(Nothing, Nothing)
DdlTipoGasto.SelectedValueExist(GvRow.DataKey("CveTipoGasto"))
Dim PS As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=DdlPS.SelectedValue.ToEntero).FiltroPrimero("")
DdlIVA.Enabled = True
ChkEsNoDeduciblePS.Checked = If(GvRow.DataKey("NoDeducible").ToUpper().Contiene("TRUE", "1"), True, False)
If PS IsNot Nothing Then
If PS("IVA").ToString.ToEntero() <> -1 Then
' DdlIVA.Enabled = False
Else
'DdlIVA.Enabled = If(CveCompra > 0 Or CveFactura > 0 Or OCVinculada, False, True)
End If
End If
Select Case GvRow.DataKey("IVAPorcentaje").ToDouble
Case 0
DdlIVA.SelectedValue = "1"
Case 0.16
DdlIVA.SelectedValue = "1.16"
Case 0.08
DdlIVA.SelectedValue = "1.08"
End Select
'TxtIVAModal.Text = FormatoNumero(GvRow.DataKey("IVAPorcentaje").ToDouble * 100, 0)
TxtRetIVAModal.Text = FormatoNumero(GvRow.DataKey("RetIVAPorcentaje").ToDouble * 100, 0)
TxtRetISRModal.Text = FormatoNumero(GvRow.DataKey("RetISRPorcentaje").ToDouble * 100, 0)
TxtIEPSModal.Text = FormatoNumero(GvRow.DataKey("IEPSPSPorcentaje").ToDouble * 100, 0)
TxtPrecio.Text = GvRow.DataKey("PU").FormatoNumero(6)
TxtDescuentoModal.Text = GvRow.DataKey("Descuento").FormatoNumero(6)
TxtOtrosGastos.Text = GvRow.DataKey("OtrosGastos").FormatoNumero
LblTotalPS.Text = GvRow.DataKey("Total").FormatoNumero
'FUNCIONALIDAD DE SEGUIR AGREGANDO (NO CERRAR MODAL)
ChkAgregar.Checked = False
divagregrarotrops.Visible = False
DVModalAddPSChkDesvincularAF.Visible = False
Dim TipoAF As Integer = GvRow.DataKey("TipoAF").ToEntero
ChkModalDesvincularAF.Checked = False
If CveCompra > 0 AndAlso TipoAF = 2 Then
DVModalAddPSChkDesvincularAF.Visible = True
End If
DdlCultivosCuadro.SelectedValueExist(GvRow.DataKey("CveCultivoCuadroDetalle"))
UpPSS.Update()
RegistraScript("$('#divAddProducto').modal('show');")
End Sub
Protected Sub DdlClasificacion_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles DdlClasificacion.SelectedIndexChanged
DdlClasificacionChange()
End Sub
Private Sub DdlClasificacionChange()
CargaPS(DdlClasificacion.SelectedValue.ToEntero)
If UsuarioActual.Empresa.Funcionalidad(200) = "1" Then
Dim ObjConta As New ClsContabilidad
If ObjConta.GetRetCuenta(6, DdlClasificacion.SelectedValue.ToEntero) AndAlso ObjConta.DtResultados.Rows.Count > 0 AndAlso ObjConta.DtResultados.Rows(0)("IdCuentaGasto").ToString.ToEntero > 0 Then
Else
Alert("La clasificacion no tiene una cuenta contable asignada.", TipoMensaje.MsgAdvertencia)
End If
ObjConta.Dispose()
End If
UPPClasificacion.Update()
End Sub
Private Sub CargaPS(CveClasificacion As Integer)
DdlPS.setEsWebService(UsuarioActual.Empresa.Funcionalidad(105) = "1")
If UsuarioActual.Empresa.Funcionalidad(105) = "1" Then
DdlPS.ddlWS.Attributes.Add("data-cveclasificacion", DdlClasificacion.SelectedValue)
DdlPS.SelectedText = ""
DdlPS.SelectedValue = "-1"
Else
DdlPS.ddl.Items.Clear()
'DdlPS.ddl.DataSource = GlobalDTPSSimplificado(UsuarioActual.CveEmpresa, CveClasificacion:=CveClasificacion)
If UsuarioActual.TienePermisoProceso(300) Or UsuarioActual.TienePermisoProceso(301) Then
Dim DTTemp As New DataTable
DTTemp.Columns.Add("CvePS", GetType(Integer))
DTTemp.Columns.Add("PSCodigo", GetType(String))
DTTemp.Columns.Add("CveClasificacion", GetType(Integer))
For Each dRow As DataRow In GlobalDTPSSimplificado(UsuarioActual.CveEmpresa).Rows
For Each drowCla As DataRow In DTClasificacionesComprobaciones.Rows
If drowCla("CveClasificacion").ToString.ToEntero = dRow("CveClasificacion").ToString.ToEntero Then
Dim InRow As DataRow = DTTemp.NewRow
InRow("CvePS") = dRow("CvePS").ToString.ToEntero
InRow("PSCodigo") = dRow("PSCodigo").ToString
InRow("CveClasificacion") = dRow("CveClasificacion").ToString.ToEntero
DTTemp.Rows.Add(InRow)
End If
Next
Next
DdlPS.DataSource = If(CveClasificacion > 0, DTTemp.FiltraParametros($"CveClasificacion = {CveClasificacion}"), DTTemp)
Else
DdlPS.DataSource = If(CveClasificacion > 0, GlobalDTPSSimplificado(UsuarioActual.CveEmpresa).FiltraParametros($"CveClasificacion = {CveClasificacion}"), GlobalDTPSSimplificado(UsuarioActual.CveEmpresa))
End If
DdlPS.ddl.DataBind()
DdlPS.ddl.Items.Insert(0, New ListItem("Seleccione el Producto", "-1"))
End If
End Sub
Protected Sub DdlPS_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DdlPS.selectedindexchange
DdlPSChange()
End Sub
Protected Sub DdlSubProyecto_SelectedIndexChanged(sender As Object, e As EventArgs)
If Modalidad <> "U" Or Not CveFactura > 0 Then
DdlPSChange()
End If
If UsuarioActual.Empresa.Funcionalidad(590).ToString.ToEntero = 1 Then
GlobalDTCultivosCuadro(UsuarioActual.CveEmpresa) = Nothing
Dim extrafiltro = "Estatus=1 AND "
If Request("CveCompra") IsNot Nothing AndAlso IsNumeric(Request("CveCompra")) AndAlso Request("CveCompra").ToEntero > 0 Then
extrafiltro = ""
End If
DdlCultivosCuadro.Items.Clear()
DdlCultivosCuadro.DataSource = GlobalDTCultivosCuadro(UsuarioActual.CveEmpresa).FiltraParametros($"{extrafiltro} CveSubProyecto = {DdlSubProyecto.SelectedValue}", "TemporadaCuadro")
DdlCultivosCuadro.DataBind()
DdlCultivosCuadro.Items.Insert(0, New ListItem("Seleccione uno", "-1"))
End If
'If UsuarioActual.Empresa.CveEmpresa = 158 AndAlso DdlSubProyecto.SelectedValue.ToEntero > 0 AndAlso DdlSubProyecto.SelectedValue.ToEntero.Contiene(11881, 11882, 11886) Then
' RfvDdlCultivosCuadro.Visible = True
'Else
' RfvDdlCultivosCuadro.Visible = False
'End If
End Sub
Private Sub DdlPSChange()
If CveProveedor > 0 Then
If DdlPS.SelectedValue.ToEntero > 0 Then
Dim PS As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=DdlPS.SelectedValue.ToEntero).FiltroPrimero("")
If PS IsNot Nothing Then
HdnClasificacion.Value = PS("Clasificacion").ToString
HdnUnidadMedida.Value = PS("CveUM").ToString
HdnTipoPS.Value = PS("CveTipoPS").ToString
HdnPS.Value = PS("PS").ToString
LblUnidadMedida.Text = PS("UnidadMedida").ToString
ddlUM.Items.Clear()
If UsuarioActual.Empresa.UsaInventarios Then
ddlUM.DataSource = GlobalDTProductosServiciosEquivalencias(PS("CvePS").ToString.ToEntero, -1, UsuarioActual.CveEmpresa)
Else
ddlUM.DataSource = GlobalDTUnidadesMedida(UsuarioActual.CveEmpresa)
End If
ddlUM.Items.Insert(0, New ListItem("Seleccione", "-1"))
ddlUM.SelectedValue = "-1"
ddlUM.DataBind()
ddlUM.SelectedValueExist(PS("CveUnidadMedida").ToString)
'HdnIVAPS.Value = If(PS.Rows(0)("IVA").ToString = "-1", ViewState("IVA"), PS.Rows(0)("IVA").ToString).ToString
ViewState("IVAPS") = PS("IVA").ToString
If ViewState("IVAPS").ToString.ToEntero() = -1 Then
Dim Drr As DataRow = GlobalDTSubProyectos(-1, DdlSubProyecto.SelectedValue.ToEntero())(0)
ViewState("IVAPS") = Drr("IVA").ToString().ToDouble()
DdlProyecto.SelectedValueExist(Drr("CveProyecto"))
DdlIVA.Enabled = True
If Not Modalidad = "U" Then
Select Case ViewState("IVAPS").ToString().ToDouble
Case 0
DdlIVA.SelectedValue = "1"
Case 0.16
DdlIVA.SelectedValue = "1.16"
Case 0.08
DdlIVA.SelectedValue = "1.08"
End Select
End If
Else
'DdlIVA.SelectedValue = "1"
' DdlIVA.Enabled = False
End If
ViewState("RetIVA") = If(PS("RetIVA").ToString = "-1", ViewState("RetIVA"), PS("RetIVA").ToString).ToString
ViewState("RetISR") = If(PS("RetISR").ToString = "-1", ViewState("RetISR"), PS("RetISR").ToString).ToString
If TxtIEPSModal.Text = "" Then
TxtIEPSModal.Text = FormatoNumero(PS("IEPSPorcentaje").ToString.ToDecimal * 100, 0)
End If
ViewState("IEPSPSIVA") = If(PS("IEPSGrabaIVA").ToString = "True", PS("IEPSPorcentaje").ToString.ToDouble, 0)
'TxtIVAModal.Text = FormatoNumero(ViewState("IVAPS").ToString().ToDouble * 100, 0)
TxtRetIVAModal.Text = FormatoNumero(ViewState("RetIVA").ToString().ToDouble * 100, 0)
TxtRetISRModal.Text = FormatoNumero(ViewState("RetISR").ToString().ToDouble * 100, 0)
If (CveFactura > 0 Or CveCompra > 0) And TxtIEPS.Text.ToDecimal = 0 And PS("IEPSPorcentaje").ToString.ToDecimal > 0 Then
TxtIEPSModal.Text = "0"
Alert("El producto seleccionado contiene IEPS, pero el acumulado de la factura no contiene IEPS, por lo que no se agregara el impuesto.", TipoMensaje.MsgAdvertencia)
End If
UpIVA.Update()
If PS("CveClasificacion").ToString IsNot Nothing Then
DdlClasificacion.SelectedValueExist(PS("CveClasificacion").ToString)
Else
Alert("El Productos/Servicio no tiene asignada una Clasificación.")
End If
UPPUM.Update()
UpPSS.Update()
End If
Else
'SI ES UN PS NO REGISTRADO INSERTAMOS SELECCIONE
ddlUM.Items.Clear()
ddlUM.Items.Insert(0, New ListItem("Seleccione", "-1"))
ddlUM.SelectedValue = "-1"
End If
Else
Alert("Es necesario seleccionar el Proveedor al cual se le va a capturar.", TipoMensaje.MsgAdvertencia, "AbrirVentana(""/Compras/PopUpBuscarProveedor.aspx?Opt=Fact"", 800, 547, ""N"", ""PopUpBuscar"")")
End If
End Sub
Protected Sub DdlProyectoAsignado_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles DdlProyecto.SelectedIndexChanged
CargaSubProyecto()
End Sub
Private Sub CargaSubProyecto()
Dim CveProyecto = If(DdlProyecto.SelectedValue.ToEntero > 0, DdlProyecto.SelectedValue.ToEntero, -1)
DdlSubProyecto.Items.Clear()
'SI NO SE VE EL PROYECTO NO FILTRAR POR PROYECTO
If Not DdlProyecto.Visible Then
CveProyecto = -1
End If
DdlSubProyecto.DataSource = If(Not UsuarioActual.TienePermisoProceso(110), GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, CveProyecto, UsuarioActual.CveEmpresa, -1, 1), GlobalDTSubProyectos(CveProyecto, -1, UsuarioActual.CveEmpresa, 1))
DdlSubProyecto.DataBind()
DdlSubProyecto.Items.Insert(0, New ListItem("Seleccione", "-1"))
End Sub
Protected Sub LbAgregar_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles LbAgregar.Click
'VALIDACIONES
If Not DdlPS.SelectedValue.ToEntero > 0 Then
Alert("Es necesario seleccionar un Producto o Servicio registrado en el sistema.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
'If UsuarioActual.Empresa.Tipo_CentroCosto = 3 Or UsuarioActual.Empresa.Tipo_CentroCosto = 4 Or UsuarioActual.Empresa.Tipo_CentroCosto = 5 Then
' If Not DdlProyecto.SelectedValue.ToEntero > 0 Then
' Alert("Es necesario seleccionar un proyecto.", TipoMensaje.MsgAdvertencia)
' Exit Sub
' End If
'End If
If Not DdlSubProyecto.SelectedValue.ToEntero > 0 Then
Alert("Es necesario seleccionar un subproyecto.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
If Not CveProveedor > 0 Then
Alert("Es necesario seleccionar el proveedor al cual se le va a facturar.", TipoMensaje.MsgAdvertencia, "AbrirVentana('/Compras/PopUpBuscarProveedor.aspx?Opt=Fact', 800, 547, 'N', 'PopUpBuscar')")
Exit Sub
End If
If UsuarioActual.Empresa.Funcionalidad(527) = "1" Then
If Not DdlTipoGasto.SelectedValue.ToEntero > 0 Then
Alert("Es necesario seleccionar un tipo de gasto.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
End If
Select Case Modalidad
Case "A"
If Math.Round(DdlIVA.SelectedValue.ToDouble - 1, 2) <> TmpDT.MAX("IVAPorcentaje").ToDouble And TmpDT.MAX("IVAPorcentaje").ToDouble <> 0 And Math.Round(DdlIVA.SelectedValue.ToDouble - 1, 2) <> 0 And TmpDT.Rows.Count > 0 Then
Alert("No puede haber dos tipos de IVA en la compra.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
Case "U"
If Math.Round(DdlIVA.SelectedValue.ToDouble - 1, 2) <> TmpDT.FiltraParametros($"Consec <> {Index}").MAX("IVAPorcentaje").ToDouble And TmpDT.FiltraParametros($"Consec <> {Index}").MAX("IVAPorcentaje").ToDouble <> 0 And Math.Round(DdlIVA.SelectedValue.ToDouble - 1, 2) <> 0 And TmpDT.FiltraParametros($"Consec <> {Index}").Rows.Count > 0 Then
Alert("No puede haber dos tipos de IVA en la compra.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
End Select
Dim Total As Decimal = (TxtCantidad.Text.ToDecimal * TxtPrecio.Text.ToDecimal) - TxtDescuentoModal.Text.ToDecimal + TxtOtrosGastos.Text.ToDecimal
If UsuarioActual.Empresa.Funcionalidad(532) = "1" Then
Dim ObjCon As New ClsContratos
Dim CvePresupuesto As Integer = 0
Dim Autorizado As Double = 0
Dim Ejercido As Double = 0
If ObjCon.GetPresupuestos(-1, "-1", DdlSubProyecto.SelectedValue.ToEntero, 2, -1, UsuarioActual.CveEmpresa) Then
If ObjCon.DtResultados.Rows.Count > 0 Then
CvePresupuesto = ObjCon.DtResultados.Rows(0)("CvePresupuesto").ToString.ToEntero
If CvePresupuesto > 0 Then
If ObjCon.GetPresupuestosDetalle(CvePresupuesto, -1, UsuarioActual.CveEmpresa) Then
If ObjCon.DtResultados.FiltraParametros($"CveClasificacion = {DdlClasificacion.SelectedValue.ToEntero} AND CveTipoGasto = {DdlTipoGasto.SelectedValue.ToEntero} AND Importe > 0").Rows.Count > 0 Then
Autorizado = ObjCon.DtResultados.FiltraParametros($"CveClasificacion = {DdlClasificacion.SelectedValue.ToEntero} AND CveTipoGasto = {DdlTipoGasto.SelectedValue.ToEntero} AND Importe > 0").Rows(0)("Importe").ToString.ToDouble
End If
End If
If ObjCon.GetPresupuestosRep(CvePresupuesto, DdlTipoGasto.SelectedValue.ToEntero, 1, $"01/09/{DateTime.Now.Year - 1}".ToDate, Now, UsuarioActual.CveEmpresa, DdlProyecto.SelectedValue.ToEntero,
DdlSubProyecto.SelectedValue.ToEntero, UsuarioActual.CveUsuario, DdlClasificacion.SelectedValue.ToEntero) Then
If ObjCon.DtResultados.Rows.Count > 0 Then
Ejercido = ObjCon.DtResultados.Rows(0)("Ejercido").ToString.ToDouble
End If
End If
End If
End If
End If
ObjCon.Dispose()
If CvePresupuesto > 0 And Autorizado > 0 Then
Dim Diferencia As Double = (Ejercido + Total) - Autorizado
If Diferencia > 0 Then
Alert($"No hay presupuesto disponible en el subproyecto <b>{DdlSubProyecto.SelectedItem.Text}</b> con la clasificación <b>{DdlClasificacion.SelectedItem.Text}</b> y el tipo de gasto <b>{DdlTipoGasto.SelectedItem.Text}</b>. Se excede por <b>{Diferencia.FormatoNumero}</b>", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
End If
End If
ActualizaTotales = True
If UsuarioActual.Empresa.Funcionalidad(545) = "1" Then
Dim TieneError As Boolean = False
Dim dttemp As New DataTable '= GlobalDTContratos().FiltraParametros(String.Format("CveSubProyecto = {0}", DdlSubProyecto.SelectedValue.ToString))
dttemp.Columns.Add("CveSubProyecto", GetType(Integer))
dttemp.Columns.Add("CvePS", GetType(Integer))
dttemp.Columns.Add("Cantidad", GetType(Decimal))
dttemp.Columns.Add("PU", GetType(Decimal))
Dim DrPS = dttemp.NewRow
DrPS("CveSubProyecto") = DdlSubProyecto.SelectedValue.ToString.ToEntero
DrPS("CvePS") = DdlPS.SelectedValue.ToString.ToEntero
DrPS("Cantidad") = TxtCantidad.Text.Trim.ToDecimal
DrPS("PU") = TxtPrecio.Text.Trim.ToDecimal
dttemp.Rows.Add(DrPS)
Dim dtPSInvalidos As String = ValidarPSContrato(dttemp)
If dtPSInvalidos <> "" Then
TieneError = True
Alert(dtPSInvalidos, TipoMensaje.MsgAdvertencia)
Exit Sub
End If
End If
Dim DtpsTemp As DataTable = Nothing
Dim CveContratoDetalle As Integer = -1
Dim CveContrato As Integer = GlobalDTContratos(UsuarioActual.CveEmpresa, -1, DdlSubProyecto.SelectedValue.ToString.ToEntero).FiltroPrimeroValor("CveContrato").ToEntero
If CveContrato > 0 Then
Dim dttemp As New DataTable
dttemp.Columns.Add("CveSubProyecto", GetType(Integer))
dttemp.Columns.Add("CvePS", GetType(Integer))
Dim DrPS = dttemp.NewRow
DrPS("CveSubProyecto") = DdlSubProyecto.SelectedValue.ToString.ToEntero
DrPS("CvePS") = DdlPS.SelectedValue.ToString.ToEntero
dttemp.Rows.Add(DrPS)
DtpsTemp = GetPSContratoDetalle(CveContrato, dttemp)
If DtpsTemp IsNot Nothing AndAlso DtpsTemp.Rows.Count > 0 Then
CveContratoDetalle = DtpsTemp.FiltroPrimeroValor("CveContratoDetalle", String.Format("CvePS = {0}", DdlPS.SelectedValue.ToString.ToEntero)).ToEntero
End If
End If
'If dttemp IsNot Nothing AndAlso dttemp.Rows.Count > 0 Then
' Dim drContrato As DataRow = dttemp.Rows(0)
' If ObjContratos.GetContratosDetalle(drContrato("CveContrato").ToString.ToEntero) Then
' Dim dtContratodetalle As DataTable = ObjContratos.DtResultados.FiltraParametros(String.Format("CvePS = {0}", DdlPS.SelectedValue.ToString))
' If dtContratodetalle IsNot Nothing AndAlso dtContratodetalle.Rows.Count > 0 Then
' Dim drContratoDetalle As DataRow = dtContratodetalle(0)
' If Convert.ToBoolean(drContratoDetalle("LimitarCantidad")) Then
' If ObjContratos.GetReporteContratosAvancesDetalleControl(drContrato("CveContrato").ToString.ToEntero, UsuarioActual.CveEmpresa) Then
' Dim dtContratodetalleControl As DataTable = ObjContratos.DtResultados.FiltraParametros(String.Format("CvePS = {0}", DdlPS.SelectedValue.ToString))
' If dtContratodetalleControl IsNot Nothing AndAlso dtContratodetalleControl.Rows.Count > 0 Then
' Dim drContratoDetalleControl As DataRow = dtContratodetalleControl(0)
' If TxtCantidad.Text.Trim.ToDouble > drContratoDetalleControl("FaltanteCantidad").ToString.ToDouble Then
' Mensaje = String.Format("La cantidad del Producto/Servicio debe ser menor o igual a {0}", drContratoDetalleControl("FaltanteCantidad").ToString)
' TieneError = True
' End If
' Else
' Mensaje = "Este producto no pertenece al contrato seleccionado."
' TieneError = True
' End If
' Else
' Mensaje = "Error al consultar el contrato."
' End If
' End If
' Else
' Mensaje = "Este producto no pertenece al contrato seleccionado."
' TieneError = True
' End If
' Else
' Mensaje = "Error al consultar el contrato."
' End If
'End If
Select Case Modalidad
Case "A" 'ADD
Dim SATClavePS = -1
Dim PSRow = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=DdlPS.SelectedValue.ToEntero).FiltroPrimero("")
If PSRow IsNot Nothing Then
SATClavePS = PSRow("SATClavePS").ToString.ToEntero
End If
Dim IVA As Decimal
If chkImportacion.Checked Then
IVA = (txtImportacion.Text.Trim.ToDecimal / (TxtCantidad.Text.Trim.ToDecimal * TxtPrecio.Text.Trim.ToDecimal))
Else
IVA = Math.Round(DdlIVA.SelectedValue.ToDecimal - 1, 2)
End If
AddPS(TxtCantidad.Text.Trim.ToDecimal, ddlUM.SelectedValue.ToEntero, ddlUM.SelectedItem.Text, DdlClasificacion.SelectedValue.ToEntero, DdlClasificacion.SelectedItem.Text, DdlPS.SelectedValue.ToEntero, DdlPS.SelectedText, HdnTipoPS.Value.ToEntero,
DdlSubProyecto.SelectedValue.ToString, DdlSubProyecto.SelectedItem.Text, DdlProyecto.SelectedItem.Text, DdlProyecto.SelectedValue.ToString, TxtObsPS.Text.Trim, TxtPrecio.Text.Trim.ToDecimal, Total, IVA,
TxtRetIVAModal.Text.ToDecimal / 100, TxtRetISRModal.Text.ToDecimal / 100, TxtIEPSModal.Text.ToDecimal / 100, 0, TxtDescuentoModal.Text.ToDecimal, OtrosGastos:=TxtOtrosGastos.Text.ToDecimal, CveTipoGasto:=DdlTipoGasto.SelectedValue.ToEntero, TipoGasto:=DdlTipoGasto.SelectedItem.Text,
NoDeducible:=ChkEsNoDeduciblePS.Checked, CveSATPS:=SATClavePS, CveContratoDetalle:=CveContratoDetalle,
CveCultivoCuadroDetalle:=If(DdlCultivosCuadro.SelectedValue.ToEntero > 0, DdlCultivosCuadro.SelectedValue.ToEntero, -1), TemporadaCuadro:=If(DdlCultivosCuadro.SelectedValue.ToEntero > 0, DdlCultivosCuadro.SelectedItem.Text, ""))
AddPS2()
LimpiaAgregar()
If ChkAgregar.Checked = True And Modalidad = "A" Then
RegistraScript("displayToastr(1);", "display")
Else
RegistraScript(String.Format("$('#{0}').modal('hide');", "divAddProducto"))
End If
Case "U" 'UPDATE
UpdatePS(CveContratoDetalle)
Alert("Concepto actualizado Correctamente.", TipoMensaje.MsgInformacion)
RegistraScript(String.Format("$('#{0}').modal('hide');", "divAddProducto"))
End Select
ActualizaTotales = False
If UsuarioActual.Empresa.Funcionalidad(562).ToEntero > 0 Then CargaGastosServicios(UsuarioActual.Empresa.Funcionalidad(562).ToEntero)
If UsuarioActual.Empresa.UsaAC Then
CompruebaAgregar()
GuardaAC()
End If
If CveCompra > 0 AndAlso ChkModalDesvincularAF.Checked Then
If Not TmpDT.Columns.Contains("DesvicularAF") Then
TmpDT.Columns.Add("DesvicularAF", GetType(Boolean))
End If
Dim CveCompraDetalleDesvicnualarAF As Integer = TmpDT.FiltroPrimeroValor("CveCompraDetalle", $"Consec={Index}").ToEntero
'If ObjAF.UpdateActivosFijosCompra(-1, CveCompraDetalleDesvicnualarAF, -1, 0, Now, Opcion:=2) Then
For Each dRow As DataRow In TmpDT.Rows
If dRow("CveCompraDetalle").ToString.ToEntero = CveCompraDetalleDesvicnualarAF Then
dRow("TipoAF") = 0
dRow("CveActivoFijo") = 0
dRow("DesvicularAF") = True
End If
Next
TmpDT.AcceptChanges()
'Else
' Retorno = False
'End If
End If
UpPS.Update()
CargaGvPersonal()
MostrarOcultarColumnaIEPS()
End Sub
''' <summary>
''' Regresa el INDEX del row que acaba de agregar en el TMPDT
''' </summary>
''' <returns></returns>
Private Function AddPS(Cantidad As Decimal, CveUM As Integer, UM As String, CveClasificacion As Integer, Clasificacion As String, CvePS As Integer, PS As String, CveTipoPS As Integer, CveSubProyectoContrato As String, SubProyecto As String, Proyecto As String, CveProyecto As String,
Obs As String, PU As Decimal, Total As Decimal, IVA As Decimal, RetIVA As Decimal, RetISR As Decimal, IEPSPS As Decimal, IEPSPSIVA As Decimal, Descuento As Decimal, Optional CveOrdenCompraDetalle As Integer = -1, Optional TCalculaTotales As Boolean = True,
Optional PSCodigo As String = "-", Optional PSDescripcion As String = "-", Optional CantidadF As Double = -1, Optional EntregaDirecta As Integer = -1, Optional OtrosGastos As Decimal = 0,
Optional CveSATPS As Integer = -1, Optional CargaXml As Boolean = False, Optional CveTipoGasto As Integer = -1, Optional TipoGasto As String = "", Optional PorcentajeIVA As Decimal = 0,
Optional PorcentajeIEPS As Decimal = 0, Optional PorcentajeRetIVA As Decimal = 0, Optional PorcentajeRetISR As Decimal = 0, Optional NoDeducible As Boolean = False, Optional CveContratoDetalle As Integer = -1, Optional CveCultivoCuadroDetalle As Integer = -1,
Optional CveSATPSActualizado As Boolean = False, Optional TemporadaCuadro As String = "") As Integer
Dim Row As DataRow = Nothing
Row = TmpDT.NewRow()
Dim Retorno As Integer = 0
Dim CveContrato = -1
Dim CveSubProyecto = -1
Dim Valores As String()
''CONTRATOS
If CveSubProyectoContrato.Contains("|"c) Then
Valores = CveSubProyectoContrato.Split("|"c)
CveContrato = Valores(1).ToEntero
CveSubProyecto = Valores(0).ToEntero
Else
CveSubProyecto = CveSubProyectoContrato.ToEntero
End If
'DR PS
Dim DrPS As DataRow = Nothing
If CvePS > 0 Then
DrPS = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=CvePS).Rows(0)
End If
If DrPS IsNot Nothing Then
Row("PSCodigo") = If(PSCodigo = "", DrPS("PSCodigo").ToString, PSCodigo)
Row("CveMetodoInventario") = DrPS("Inv_CveMetodoInventario").ToString.ToEntero
Else
Row("PSCodigo") = PSCodigo
Row("CveMetodoInventario") = 0
End If
If Modalidad = "U" Then
Row("Consec") = Con
Else
Row("Consec") = TmpDT.Rows.Count + 1
End If
If (Version = "3.3" Or Version = "4.0") And CveSATPS > 0 Then
Dim DrPSSAT As DataRow = Nothing
If CargaXml Then
DrPSSAT = GlobalDTPSATPS("-1", CveSATPS.ToString).FiltroPrimero("")
'If GlobalDTPSATPS().FiltraParametros(String.Format("SATClavePS={0}", CveSATPS)).Rows.Count > 0 Then
' DrPSSAT = GlobalDTPSATPS().FiltraParametros(String.Format("SATClavePS={0}", CveSATPS)).Rows(0)
'End If
Else
DrPSSAT = GlobalDTPSATPS("-1", CveSATPS.ToString).FiltroPrimero("") '= GlobalDTPSATPS().FiltroPrimero(String.Format("SATClavePS={0}", CveSATPS))
'If GlobalDTPSATPS().FiltraParametros(String.Format("CveSATPS={0}", CveSATPS)).Rows.Count > 0 Then
' DrPSSAT = GlobalDTPSATPS().FiltraParametros(String.Format("CveSATPS={0}", CveSATPS)).Rows(0)
'End If
End If
If DrPSSAT IsNot Nothing Then
Row("SATClaveProductoServicio") = DrPSSAT("SATClaveProductoServicio").ToString
Row("CveSATPS") = DrPSSAT("CveSATPS").ToString
If CveSATPSActualizado Then
Row("CveSATPSActualizado") = 1
Else
Row("CveSATPSActualizado") = 0
End If
End If
End If
Try
If (DrPS("CvePSCargo").ToString <> "") Then 'si es un producto de usado. que se registre contablemente como alamcen(como producto)
CveTipoPS = 2
End If
Catch ex As Exception
End Try
Dim DecimalesPermitidos = 6
Row("CveConcepto") = TmpDT.Rows.Count + 1
Row("Cantidad") = Math.Round(Cantidad, DecimalesPermitidos)
Row("CantidadF") = If(CantidadF = -1, Math.Round(Cantidad, DecimalesPermitidos), Math.Round(CantidadF, DecimalesPermitidos))
Row("CveUM") = CveUM
Row("UM") = UM
Row("CveClasificacion") = CveClasificacion
Row("CveClasificacionActualizar") = CveClasificacion
Row("Clasificacion") = Clasificacion
Row("CvePS") = CvePS
Row("PS") = PS
Row("CveTipoPS") = CveTipoPS
Row("PSDescripcion") = PSDescripcion
Row("CveSubProyecto") = CveSubProyecto.ToEntero
Row("CveProyecto") = CveProyecto.ToEntero
Row("CveContrato") = CveContrato.ToEntero
Row("SubProyecto") = If(SubProyecto = "Seleccione", "Sin Sub Proyecto", SubProyecto)
Row("Proyecto") = If(Proyecto = "Seleccione", "Sin Proyecto", Proyecto)
Row("CveActivoFijo") = -1
Row("Obs") = Obs
Row("CveActivoFijo") = -1
Row("CodAF") = "-1"
Row("TipoAF") = -1
Row("CveOrdenCompraDetalle") = CveOrdenCompraDetalle
Row("EntregaDirecta") = EntregaDirecta
'If GlobalDTProductosServiciosEquivalencias(CvePS, CveUM).Rows.Count = 0 Then Row("CveEq") = 1 Else Row("CveEq") = 0
Row("NoDeducible") = NoDeducible
Row("PU") = Math.Round(PU, DecimalesPermitidos)
If CargaXml And (Version = "3.3" Or Version = "4.0") Then
If CveFactura > 0 And TxtIVA.Text.ToDecimal = 0 Then
Row("IVA") = 0
Row("IVAPorcentaje") = 0
Else
Row("IVA") = Math.Round(IVA, DecimalesPermitidos)
Row("IVAPorcentaje") = PorcentajeIVA
End If
Row("RetIVA") = Math.Round(RetIVA, DecimalesPermitidos)
Row("RetIVAPorcentaje") = PorcentajeRetIVA
Row("RetISR") = Math.Round(RetISR, DecimalesPermitidos)
Row("RetISRPorcentaje") = PorcentajeRetISR
Row("IEPSPS") = Math.Round(IEPSPS, DecimalesPermitidos)
Row("IEPSPSPorcentaje") = PorcentajeIEPS
Else
'If DdlIVA.SelectedValue.ToDouble = 0 Then Row("IVA") = 0 Else Row("IVA") = Math.Round(IVA * Total, DecimalesPermitidos)
If CveFactura > 0 And TxtIVA.Text.ToDecimal = 0 Then
Row("IVA") = 0
Row("IVAPorcentaje") = 0
Else
Row("IVA") = (IVA * Total).RoundSQL
Row("IVAPorcentaje") = IVA
End If
Row("RetIVA") = (RetIVA * Total).RoundSQL
Row("RetIVAPorcentaje") = RetIVA
Row("RetISR") = (RetISR * Total).RoundSQL
Row("RetISRPorcentaje") = RetISR
Row("IEPSPS") = (IEPSPS * Total).RoundSQL
Row("IEPSPSPorcentaje") = IEPSPS
End If
Row("ImporteConImpuestos") = (Row("Cantidad").ToString.ToDecimal * Row("PU").ToString.ToDecimal) + Row("IVA").ToString.ToDecimal + Row("IEPSPS").ToString.ToDecimal - (Row("RetIVA").ToString.ToDecimal + Row("RetISR").ToString.ToDecimal)
Row("ImporteSinImpuestos") = Row("Cantidad").ToString.ToDecimal * Row("PU").ToString.ToDecimal
Row("IEPSPSIVA") = Math.Round(IEPSPSIVA * Total, DecimalesPermitidos)
Row("IEPSPSIVAPorcentaje") = IEPSPSIVA
Row("Descuento") = Math.Round(Descuento, DecimalesPermitidos)
Row("OtrosGastos") = Math.Round(OtrosGastos, DecimalesPermitidos)
Row("Total") = Math.Round(Total, DecimalesPermitidos)
Row("CveTipoGasto") = CveTipoGasto
Row("TipoGasto") = If(CveTipoGasto > 0, TipoGasto, "")
Row("CveContratoDetalle") = CveContratoDetalle
Row("CveCultivoCuadroDetalle") = CveCultivoCuadroDetalle
Row("TemporadaCuadro") = TemporadaCuadro
If UsuarioActual.Empresa.UsaAC Then
Row("CveProgramaOperativo") = DdlACGeneral1.SelectedValue.ToEntero
Row("CveUnidadAdministrativa") = DdlACGeneral2.SelectedValue.ToEntero
Row("CveFuenteFinanciamiento") = DdlACGeneral3.SelectedValue.ToEntero
Row("CveTipoGastoAC") = DdlACGeneral4.SelectedValue.ToEntero
Row("CveClasificacionOG") = DdlACGeneral5.SelectedValue.ToEntero
End If
'Esta parte es para validar cuando la factura tenga ieps en o se asignara el ieps como una partida ya no se considere
If (CveFactura > 0 Or CveCompra > 0) And TxtIEPS.Text.ToDecimal = 0 Then
Row("IEPSPS") = 0
Row("IEPSPSPorcentaje") = 0
End If
TmpDT.Rows.Add(Row)
TmpDT.Rows.IndexOf(Row)
If TCalculaTotales Then
CalculaTotales(True)
End If
Return Retorno
End Function
Private Sub AddPS2(Optional pCalculaTotales As Boolean = True, Optional EsNoDeducible As Boolean = False)
Dim view As DataView = New DataView(TmpDT)
view.Sort = "Consec"
GvPS.DataSource = view
'GvPS.DataSource = TmpDT
GvPS.DataBind()
CargaGvInv()
If pCalculaTotales Then
CalculaTotales(True, EsNoDeducible)
End If
If CveCompra <= 0 And CveFactura <= 0 Then
CargaAnticipos(DdlProveedor.SelectedValue.ToEntero)
End If
End Sub
Private Sub UpdatePS(Optional CveContratoDetalle As Integer = -1)
Dim DrPS As DataRow = Nothing
Try
DrPS = TmpDT.Select($"Consec = {Index}")(0)
If DrPS Is Nothing Then
Alert("Ocurrió un error al editar el concepto.", TipoMensaje.MsgError)
Exit Sub
End If
Catch ex As Exception
Alert("Ocurrió un error al intentar editar el concepto.", TipoMensaje.MsgError)
Exit Sub
End Try
'BANDERA
Dim AplicaCalculaTotales = False
'DATOS GENERALES
DrPS("Obs") = TxtObsPS.Text.Trim
DrPS("Proyecto") = DdlProyecto.SelectedItem.Text
DrPS("CveProyecto") = DdlProyecto.SelectedValue.ToEntero
DrPS("SubProyecto") = DdlSubProyecto.SelectedItem.Text
DrPS("CveSubProyecto") = DdlSubProyecto.SelectedValue.ToEntero
DrPS("CveContratoDetalle") = CveContratoDetalle
'IMPORTES - [CANTIDAD Y PRECIO]
Dim Cantidad = DrPS("Cantidad").ToString.ToDouble
Dim PU = DrPS("PU").ToString.ToDouble
Dim Descuento = DrPS("Descuento").ToString.ToDouble
Dim OtrosGastos = DrPS("OtrosGastos").ToString.ToDouble
Dim Total = (Cantidad * PU) - Descuento + OtrosGastos
DrPS("NoDeducible") = ChkEsNoDeduciblePS.Checked
Dim ActualizarIva As Boolean = False
If Cantidad.RoundSQL(2) <> TxtCantidad.Text.Trim.ToDouble.RoundSQL(2) Or PU.RoundSQL(2) <> TxtPrecio.Text.Trim.ToDouble.RoundSQL(2) Then
ActualizarIva = True
End If
If Cantidad <> TxtCantidad.Text.Trim.ToDouble OrElse PU <> TxtPrecio.Text.Trim.ToDouble OrElse Descuento <> TxtDescuentoModal.Text.ToDouble OrElse OtrosGastos <> TxtOtrosGastos.Text.ToDouble Then
Cantidad = TxtCantidad.Text.Trim.ToDouble
PU = TxtPrecio.Text.Trim.ToDouble
Descuento = TxtDescuentoModal.Text.ToDouble
OtrosGastos = TxtOtrosGastos.Text.ToDouble
Total = (Cantidad * PU) - Descuento + OtrosGastos
DrPS("Cantidad") = Cantidad
DrPS("PU") = PU
DrPS("Descuento") = Descuento
DrPS("OtrosGastos") = OtrosGastos
DrPS("Total") = Total
AplicaCalculaTotales = True
End If
'PS - CLASIFICACION
If DdlPS.SelectedValue.ToEntero > 0 Then
Dim PSRow = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=DdlPS.SelectedValue.ToEntero).FiltroPrimero("")
If PSRow IsNot Nothing Then
Dim CveTipoPS As Integer = PSRow("CveTipoPS").ToString.ToEntero
If PSRow("CvePSCargo").ToString <> "" Then 'si es un producto de usado. que se registre contablemente como alamcen(como producto)
CveTipoPS = 2
End If
DrPS("CveClasificacion") = PSRow("CveClasificacion").ToString
DrPS("Clasificacion") = PSRow("Clasificacion").ToString
DrPS("CvePS") = DdlPS.SelectedValue
DrPS("PS") = PSRow("PS").ToString
DrPS("CveTipoPS") = CveTipoPS
DrPS("CveSATPS") = PSRow("CveSATPS").ToString.ToEntero
DrPS("SATClaveProductoServicio") = PSRow("SATClaveProductoServicio").ToString
DrPS("CveSATPSActualizado") = 0
'RESPETAR VALORES DE LA PANTALLA
'IVA = PSRow("IVA").ToString.ToDouble
'If IVA = -1 Then
' IVA = GlobalDTSubProyectos(-1, DdlSubProyecto.SelectedValue.ToEntero()).FiltroPrimeroValor("IVA").ToDouble
'End If
'RetIVA = If(PSRow("RetIVA").ToString = "-1", ViewState("RetIVA"), PSRow("RetIVA").ToString).ToString.ToDouble
'RetISR = If(PSRow("RetISR").ToString = "-1", ViewState("RetISR"), PSRow("RetISR").ToString).ToString.ToDouble
'IEPSPS = If(PSRow("IEPSPorcentaje").ToString = "-1", ViewState("IEPSPS"), PSRow("IEPSPorcentaje").ToString).ToString.ToDouble
'IEPSPSIVA = If(PSRow("IEPSGrabaIVA").ToString = "True", PSRow("IEPSPorcentaje").ToString.ToDouble, 0)
End If
End If
'UM
DrPS("CveUM") = ddlUM.SelectedValue.ToEntero
DrPS("UM") = ddlUM.SelectedItem.Text
'TIPO DE GASTO
DrPS("CveTipoGasto") = DdlTipoGasto.SelectedValue.ToEntero
DrPS("TipoGasto") = If(DdlTipoGasto.SelectedValue.ToEntero > 0, DdlTipoGasto.SelectedItem.Text, "")
If UsuarioActual.Empresa.Funcionalidad(562).ToEntero > 0 Then
DrPS("AplicaCostoIndirecto") = "0"
End If
'IMPUESTOS: SI ES COMPRA, FACUTRA O CON OC, NO MODIFICA IMPUESTOS!!
'Dim IVA = (TxtIVAModal.Text.ToDouble / 100)
Dim IVA = Math.Round(DdlIVA.SelectedValue.ToDecimal - 1, 2)
Dim RetISR = (TxtRetISRModal.Text.ToDecimal / 100)
Dim RetIVA = (TxtRetIVAModal.Text.ToDecimal / 100)
Dim IEPSPS = (TxtIEPSModal.Text.ToDecimal / 100)
Dim IEPSPSIVA = 0
'I f Not (CveCompra > 0 Or CveFactura > 0 Or OCVinculada) Then
'If DdlIVA.SelectedValue.ToDouble = 0 Then DrPS("IVA") = 0 Else DrPS("IVA") = IVA * Total
If CveFactura > 0 And TxtIVA.Text.ToDecimal = 0 Then
DrPS("IVA") = 0
DrPS("IVAPorcentaje") = 0
Else
If ActualizarIva Then
DrPS("IVA") = (IVA * Total).RoundSQL
End If
DrPS("IVAPorcentaje") = IVA
End If
DrPS("RetIVA") = (RetIVA * Total).RoundSQL
DrPS("RetIVAPorcentaje") = RetIVA
DrPS("RetISR") = RetISR * Total
DrPS("RetISRPorcentaje") = RetISR
DrPS("IEPSPS") = (IEPSPS * Total).RoundSQL
DrPS("IEPSPSPorcentaje") = IEPSPS
DrPS("IEPSPSIVA") = (IEPSPSIVA * Total).RoundSQL
DrPS("IEPSPSIVAPorcentaje") = IEPSPSIVA
DrPS("CveCultivoCuadroDetalle") = If(DdlCultivosCuadro.SelectedValue.ToEntero > 0, DdlCultivosCuadro.SelectedValue.ToEntero, -1)
DrPS("TemporadaCuadro") = If(DdlCultivosCuadro.SelectedValue.ToEntero > 0, DdlCultivosCuadro.SelectedItem.Text, "")
'Esta parte es para validar cuando la factura tenga ieps en o se asignara el ieps como una partida ya no se considere
If (CveFactura > 0 Or CveCompra > 0) And TxtIEPS.Text.ToDecimal = 0 Then
DrPS("IEPSPS") = 0
DrPS("IEPSPSPorcentaje") = 0
End If
AplicaCalculaTotales = True
'End If
TmpDT.AcceptChanges()
AddPS2(AplicaCalculaTotales)
CargaGvInv()
End Sub
#End Region
#Region " RECLASIFICA PARTIDAS - CLASIFICACION - SUBPROYECTO "
Private Sub CargaClasificaciones()
If UsuarioActual.Empresa.UsaAC Then
DdlClasificacion.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltraParametros(" Codigo = '' OR Codigo IS NULL ", Orderby:="Clasificacion")
DdlAplicaClasificacion.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltraParametros(" Codigo = '' OR Codigo IS NULL ", Orderby:="Clasificacion")
Else
DdlClasificacion.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltraParametros("", Orderby:="Clasificacion")
DdlAplicaClasificacion.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltraParametros("", Orderby:="Clasificacion")
If UsuarioActual.TienePermisoProceso(300) Or UsuarioActual.TienePermisoProceso(301) Then
DdlClasificacion.DataSource = DTClasificacionesComprobaciones.FiltraParametros("", Orderby:="Clasificacion")
DdlAplicaClasificacion.DataSource = DTClasificacionesComprobaciones.FiltraParametros("", Orderby:="Clasificacion")
End If
End If
DdlClasificacion.DataBind()
DdlAplicaClasificacion.DataBind()
End Sub
Private Sub BtnAplicarClasificacion_Click(sender As Object, e As EventArgs) Handles BtnAplicarClasificacion.Click
ReclasificaClasificacion()
End Sub
Protected Sub DdlAplicaClasificacion_SelectedIndexChanged(sender As Object, e As EventArgs)
ReclasificaClasificacion()
End Sub
Private Sub ReclasificaClasificacion()
If Not DdlAplicaClasificacion.SelectedValue.ToEntero > 0 Then
Exit Sub
End If
Dim ErrorPS = False
'Actualiza Clasificacion directamente a la DB cuando ya se tiene alguna clasificacion
'Solo cuando el PS ya esta registrado
If UsuarioActual.TienePermisoProceso(104) Then
Dim ObjPS As New ClsProductosServicios
For Each gvr As GridViewRow In GvPS.Rows
If gvr.FCCheckBox("CheckClasificacion").Checked AndAlso gvr.DataKey("CvePS").ToString.ToEntero > 0 Then
If Not ObjPS.UpdateClasificacionPS(DdlAplicaClasificacion.SelectedValue.ToEntero, UsuarioActual.CveUsuario, gvr.DataKey("CvePS").ToString.ToEntero) Then
ErrorPS = True
Exit For
End If
End If
Next
ObjPS.Dispose()
End If
If Not ErrorPS Then
Dim index = 0
For Each Dr As DataRow In TmpDT.Rows
If Dr("CvePS").ToString.ToEntero = 0 OrElse Dr("CveClasificacion").ToString.ToEntero <= 0 Then
'Dr("CveClasificacion") = DdlClasificacion.SelectedValue.ToEntero
Dr("Clasificacion") = DdlAplicaClasificacion.SelectedItem.Text
Dr("CveClasificacionActualizar") = DdlAplicaClasificacion.SelectedValue.ToEntero
ElseIf UsuarioActual.TienePermisoProceso(104) AndAlso GvPS.Rows(index).FCCheckBox("CheckClasificacion").Checked Then
Dr("Clasificacion") = DdlAplicaClasificacion.SelectedItem.Text
Dr("CveClasificacionActualizar") = DdlAplicaClasificacion.SelectedValue.ToEntero
End If
index += 1
Next
GvPS.DataSource = TmpDT
GvPS.DataBind()
UpPS.Update()
Alert("La Clasificacion ha sido aplicada correctamente.", TipoMensaje.MsgInformacion)
'Para validar AC
If UsuarioActual.Empresa.UsaAC Then
CompruebaAgregar()
End If
Else
Alert("Ocurrio un error al actualizar la Clasificación de los Productos/Servicios")
End If
End Sub
Protected Sub DdlAsignarProyecto_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles DdlAsignarProyecto.SelectedIndexChanged
CargaSubProyectoAsignado()
End Sub
Private Sub CargaProyectoAsignado()
DdlAsignarProyecto.Items.Clear()
DdlAsignarProyecto.DataSource = If(UsuarioActual.Empresa.Funcionalidad(102) = "1" AndAlso Not UsuarioActual.TienePermisoProceso(110), GlobalDTProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1).FiltraParametros("", "", {"CveProyecto", "Proyecto"}), GlobalDTProyectos(UsuarioActual.CveEmpresa, -1).FiltraParametros("", "", {"CveProyecto", "Proyecto"}))
DdlAsignarProyecto.DataBind()
DdlAsignarProyecto.Items.Insert(0, New ListItem("Seleccione", "-1"))
UpReclasificarSubProyecto.Update()
End Sub
Private Sub CargaSubProyectoAsignado()
DdlAsignaSubProyecto.Items.Clear()
If DdlAsignarProyecto.SelectedValue.ToEntero > 0 Then
DdlAsignaSubProyecto.DataSource = If(UsuarioActual.Empresa.Funcionalidad(102) = "1" AndAlso Not UsuarioActual.TienePermisoProceso(110), GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, DdlAsignarProyecto.SelectedValue.ToEntero, UsuarioActual.CveEmpresa, -1, 1), GlobalDTSubProyectos(DdlAsignarProyecto.SelectedValue.ToEntero, -1, UsuarioActual.CveEmpresa, 1))
End If
DdlAsignaSubProyecto.DataBind()
DdlAsignaSubProyecto.Items.Insert(0, New ListItem("Seleccione", "-1"))
UpReclasificarSubProyecto.Update()
End Sub
Protected Sub DdlAsignaSubProyecto_SelectedIndexChanged(sender As Object, e As EventArgs)
ReclasificaSubProyecto()
End Sub
Private Sub BtnAsignarSubProyecto_Click(sender As Object, e As EventArgs) Handles BtnAsignarSubProyecto.Click
ReclasificaSubProyecto()
End Sub
Private Sub ReclasificaSubProyecto()
If Not GvPS.Rows.Count > 0 Then
If CveCompra <> Nothing And CveCompra > 0 Then
Alert("No hay partidas para reclasificar el SubProyecto", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
End If
If Not DdlAsignaSubProyecto.SelectedValue.ToEntero > 0 Then
Exit Sub
End If
Dim CveSubProyecto As Integer
Dim CveProyecto As Integer
If DdlAsignaSubProyecto.SelectedValue.Contains("|") Then
CveSubProyecto = DdlAsignaSubProyecto.SelectedValue.Split("|"c)(0).ToString.ToEntero
Else
CveSubProyecto = DdlAsignaSubProyecto.SelectedValue.ToEntero()
End If
If DdlAsignarProyecto.SelectedValue.Contains("|") Then
CveProyecto = DdlAsignarProyecto.SelectedValue.Split("|"c)(0).ToString.ToEntero
Else
CveProyecto = DdlAsignarProyecto.SelectedValue.ToEntero()
End If
Dim CveContrato As Integer = GlobalDTContratos(UsuarioActual.CveEmpresa, -1, DdlAsignaSubProyecto.SelectedValue.ToEntero).FiltroPrimeroValor("CveContrato").ToEntero
Dim DtpsTemp As DataTable = Nothing
If CveContrato > 0 Then
DtpsTemp = GetPSContratoDetalle(CveContrato, TmpDT.FiltraParametros("", "", {"CveSubProyecto", "CvePS"}))
End If
For Each Dr As DataRow In TmpDT.Rows
Dr("CveProyecto") = CveProyecto
Dr("Proyecto") = If(CveSubProyecto = -1, "SE", DdlAsignarProyecto.SelectedItem.Text)
Dr("CveSubProyecto") = CveSubProyecto
Dr("SubProyecto") = If(CveSubProyecto = -1, "SE", DdlAsignaSubProyecto.SelectedItem.Text)
If DtpsTemp IsNot Nothing AndAlso DtpsTemp.Rows.Count > 0 Then
Dr("CveContratoDetalle") = DtpsTemp.FiltroPrimeroValor("CveContratoDetalle", String.Format("CvePS = {0}", Dr("CvePS"))).ToEntero
End If
Next
GvPS.DataSource = TmpDT.FiltraParametros("", "Consec")
GvPS.DataBind()
UpPS.Update()
CargaGvPersonal()
'Para validar AC
If UsuarioActual.Empresa.UsaAC Then
CompruebaAgregar()
End If
Alert("SubProyectos cambiados correctamente", TipoMensaje.ToastInformacion)
End Sub
Protected Sub DdlTipoGastoAsignar_SelectedIndexChanged(sender As Object, e As EventArgs)
If Not GvPS.Rows.Count > 0 Then
Alert("No hay partidas para reclasificar el tipo de gasto", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
If Not DdlTipoGastoAsignar.SelectedValue.ToEntero > 0 Then
Exit Sub
End If
If DdlTipoGastoAsignar.SelectedValue.ToEntero > 0 Then
For Each Dr As DataRow In TmpDT.Rows
Dr("CveTipoGasto") = DdlTipoGastoAsignar.SelectedValue.ToEntero
Dr("TipoGasto") = DdlTipoGastoAsignar.SelectedItem.Text
Next
GvPS.DataSource = TmpDT.FiltraParametros("", "Consec")
GvPS.DataBind()
UpPS.Update()
End If
If UsuarioActual.Empresa.UsaAC Then
CompruebaAgregar()
End If
Alert("Los tipos de gastos han sido cambiados correctamente", TipoMensaje.ToastInformacion)
End Sub
#End Region
#Region " PS ALIAS "
Protected Sub DdlPSAlias_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlPSAlias2.selectedindexchange
If Not DdlPSAlias2.SelectedValue = "" Then
Dim DrPS = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=DdlPSAlias2.SelectedValue.ToEntero).FiltroPrimero("")
If DrPS IsNot Nothing Then
DdlUnidadAlias.DataSource = GlobalDTProductosServiciosEquivalencias(DdlPSAlias2.SelectedValue.ToEntero, -1, UsuarioActual.CveEmpresa)
DdlUnidadAlias.DataBind()
HdnPSAliasCveClasificacion.Value = DrPS("CveClasificacion").ToString
HdnPSAliasClasificacion.Value = DrPS("Clasificacion").ToString
HdnPSAliasCveTipoPS.Value = DrPS("CveTipoPS").ToString
End If
End If
UpPSAlias.Update()
End Sub
Protected Sub BtnAddPSAlias_Click(sender As Object, e As EventArgs) Handles BtnAddPSAlias.Click
Dim CvePS As Integer = -1
Dim tPS As String = ""
CvePS = DdlPSAlias2.SelectedValue.ToEntero
tPS = DdlPSAlias2.SelectedText
If CvePS <= 0 Then
Alert("No se ha seleccionado el producto.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
Dim CveSubProyecto As Integer = TmpDT.Rows(HdnAliasInd.Value.ToEntero)("CveSubProyecto").ToString.ToEntero
Dim DtpsTemp As DataTable = Nothing
Dim CveContrato As Integer = GlobalDTContratos(UsuarioActual.CveEmpresa, -1, CveSubProyecto).FiltroPrimeroValor("CveContrato").ToEntero
If CveContrato > 0 Then
Dim dttemp As New DataTable
dttemp.Columns.Add("CveSubProyecto", GetType(Integer))
dttemp.Columns.Add("CvePS", GetType(Integer))
Dim DrPS = dttemp.NewRow
DrPS("CveSubProyecto") = CveSubProyecto
DrPS("CvePS") = CvePS
dttemp.Rows.Add(DrPS)
DtpsTemp = GetPSContratoDetalle(CveContrato, dttemp)
End If
Dim PS As New ClsProductosServicios
If PS.AddPSAlias(System.Web.HttpUtility.HtmlDecode(TxtPSAlias.Text.Trim), CvePS, ChkAliasFlexible.Checked, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa) Then
GlobalDTProductosServiciosAlias(UsuarioActual.CveEmpresa) = PS.DtResultados
TmpDT.Rows(HdnAliasInd.Value.ToEntero)("CvePS") = CvePS
TmpDT.Rows(HdnAliasInd.Value.ToEntero)("PS") = tPS
TmpDT.Rows(HdnAliasInd.Value.ToEntero)("CveUM") = DdlUnidadAlias.SelectedValue.ToEntero
TmpDT.Rows(HdnAliasInd.Value.ToEntero)("UM") = DdlUnidadAlias.SelectedItem.Text
TmpDT.Rows(HdnAliasInd.Value.ToEntero)("CveClasificacion") = HdnPSAliasCveClasificacion.Value.ToEntero
TmpDT.Rows(HdnAliasInd.Value.ToEntero)("Clasificacion") = HdnPSAliasClasificacion.Value
TmpDT.Rows(HdnAliasInd.Value.ToEntero)("Obs") = TxtPSAlias.Text.Trim
TmpDT.Rows(HdnAliasInd.Value.ToEntero)("CveSATPS") = HdnPSAliasCveSATPS.Value.ToEntero
TmpDT.Rows(HdnAliasInd.Value.ToEntero)("SATClaveProductoServicio") = HdnPSAliasSATClavePS.Value
TmpDT.Rows(HdnAliasInd.Value.ToEntero)("CveTipoPS") = HdnPSAliasCveTipoPS.Value.ToEntero
TmpDT.Rows(HdnAliasInd.Value.ToEntero)("CveSATPSActualizado") = 0
If DtpsTemp IsNot Nothing AndAlso DtpsTemp.Rows.Count > 0 Then
TmpDT.Rows(HdnAliasInd.Value.ToEntero)("CveContratoDetalle") = DtpsTemp.FiltroPrimeroValor("CveContratoDetalle", String.Format("CvePS = {0}", CvePS)).ToEntero
End If
'busco si el producto está en otros renglones QUE NO LO TENGAN ASIGNADO, LO VINCULE
For Each drt As DataRow In TmpDT.Select($"PS ='{TxtPSAlias.Text.Trim}' and ISNULL(CvePS,0) = 0")
drt("CvePS") = CvePS
drt("PS") = tPS
drt("CveUM") = DdlUnidadAlias.SelectedValue.ToEntero
drt("UM") = DdlUnidadAlias.SelectedItem.Text
drt("CveClasificacion") = HdnPSAliasCveClasificacion.Value.ToEntero
drt("Clasificacion") = HdnPSAliasClasificacion.Value
drt("Obs") = TxtPSAlias.Text.Trim
drt("CveSATPS") = HdnPSAliasCveSATPS.Value.ToEntero
drt("SATClaveProductoServicio") = HdnPSAliasSATClavePS.Value
drt("CveTipoPS") = HdnPSAliasCveTipoPS.Value
drt("CveSATPSActualizado") = 0
If DtpsTemp IsNot Nothing AndAlso DtpsTemp.Rows.Count > 0 Then
drt("CveContratoDetalle") = DtpsTemp.FiltroPrimeroValor("CveContratoDetalle", String.Format("CvePS = {0}", drt("CvePS"))).ToEntero
End If
Next
TmpDT.AcceptChanges()
GvPS.DataSource = TmpDT
GvPS.DataBind()
UpPS.Update()
CargaGvInv()
Alert("Registro actualizado con éxito.", TipoMensaje.MsgInformacion)
RegistraScript("$('#ModalPSAlias').modal('hide');", "ModalPSAliasHide")
End If
PS.Dispose()
End Sub
Private Sub RecargaGlobalEquivalencias()
'Dim Hilo As New System.Threading.Thread(AddressOf GeneraGlobalEquivalencias)
'Hilo.Start()
GeneraGlobalEquivalencias()
End Sub
Private Sub GeneraGlobalEquivalencias()
GlobalDTProductosServiciosEquivalencias(-1, -1, UsuarioActual.CveEmpresa) = Nothing
'Dim ObjPS = New ClsProductosServicios
'If ObjPS.GetPSEquivalencias(-1, -1) Then
' GlobalDTProductosServiciosEquivalencias(-1, -1, UsuarioActual.CveEmpresa) = ObjPS.DtResultados
'End If
'ObjPS.Dispose()
End Sub
#End Region
#Region " UM: ALIAS - EQUIVALENCIAS "
Private Sub CargarUMAlias()
DdlUMAlias.DataSource = GlobalDTUnidadesMedida(UsuarioActual.CveEmpresa)
DdlUMAlias.DataBind()
DdlUMAlias.Items.Insert(0, New ListItem("Seleccione", "-1"))
UpUMAlias.Update()
End Sub
Protected Sub DdlUMAlias_SelectedIndexChanged(sender As Object, e As EventArgs)
If GlobalDTProductosServiciosEquivalencias(TmpDT.Rows(HdnUMAliasInd.Value.ToEntero)("CvePS").ToString.ToEntero, DdlUMAlias.SelectedValue.ToEntero, UsuarioActual.CveEmpresa).Rows.Count > 0 Then
RegistraScript("$('#RowUMEquivalencia').addClass('hidden')", "RowUMEquivalenciaShow")
Else
RegistraScript("$('#RowUMEquivalencia').removeClass('hidden')", "RowUMEquivalenciaHide")
End If
RegistraScript("$('#RowUMAlias').removeClass('hidden');$('#LtUMAlias').text('Registrar Unidad de Medida Alias'); $('#BtnUMAlias').val('Registrar Alias'); SetTextEquivalencia(1);", "RowUMAliasHide")
End Sub
Protected Sub BtnUMAlias_Click(sender As Object, e As EventArgs)
Dim ObjUM As New ClsUnidadesMedida
Dim ObjPS As New ClsProductosServicios(ObjUM.IniciaTransacSQL())
Dim TieneError = False
Dim DtEquivalencia = GlobalDTProductosServiciosEquivalencias(TmpDT.Rows(HdnUMAliasInd.Value.ToEntero)("CvePS").ToString.ToEntero, -1, UsuarioActual.CveEmpresa)
Dim CveUM = -1
Dim UM = ""
Dim Equivalencia = 0.0
Select Case HdnUMAliasModalidad.Value.ToEntero
Case 1 'AGREGA ALIAS
If Not ObjUM.AddUnidadMedidaAlias(TxtUMAlias.Text.Trim, DdlUMAlias.SelectedValue.ToEntero, If(HdnUMAliasCveSATUM.Value.ToEntero > 0, HdnUMAliasCveSATUM.Value.ToEntero, -1)) Then
TieneError = True
End If
'SI NO TIENE EQUIVALENCIA DEL PS - AGREGA LA EQUIVALENCIA
If Not TieneError Then
If Not GlobalDTProductosServiciosEquivalencias(TmpDT.Rows(HdnUMAliasInd.Value.ToEntero)("CvePS").ToString.ToEntero, DdlUMAlias.SelectedValue.ToEntero, UsuarioActual.CveEmpresa).Rows.Count > 0 Then
If Not ObjPS.AddPSEquivalencias(TmpDT.Rows(HdnUMAliasInd.Value.ToEntero)("CvePS").ToString.ToEntero, DdlUMAlias.SelectedValue.ToEntero, TxtUMEquivalenciaCantidad.Text.ToDecimal, False, 0, UsuarioActual.CveUsuario) Then
TieneError = True
End If
End If
End If
'CveUM = DtEquivalencia.FiltroPrimeroValor("CveUM", "UnidadBase = 1").ToEntero
'UM = DtEquivalencia.FiltroPrimeroValor("UM", "UnidadBase = 1")
CveUM = DdlUMAlias.SelectedValue.ToEntero
UM = TxtUMAlias.Text.Trim
Equivalencia = TxtUMEquivalenciaCantidad.Text.ToDouble
Case 2
Case 3 'AGREGA EQUIVALENCIA
CveUM = DtEquivalencia.FiltroPrimeroValor("CveUM", "UnidadBase = 1").ToEntero
UM = DtEquivalencia.FiltroPrimeroValor("UM", "UnidadBase = 1")
Equivalencia = TxtUMEquivalenciaCantidad.Text.ToDouble
If Not TieneError Then
If Not ObjPS.AddPSEquivalencias(TmpDT.Rows(HdnUMAliasInd.Value.ToEntero)("CvePS").ToString.ToEntero, TmpDT.Rows(HdnUMAliasInd.Value.ToEntero)("CveUM").ToString.ToEntero, TxtUMEquivalenciaCantidad.Text.ToDecimal, False, 0, UsuarioActual.CveUsuario) Then
TieneError = True
End If
End If
Case 4 'AGREGA UNIDAD DE MEDIDA
CveUM = ObjUM.AddUnidadMedida(TxtUMAlias.Text.Trim, TxtUMAbreviatura.Text.Trim, "", "", "", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, If(HdnUMAliasCveSATUM.Value.ToEntero > 0, HdnUMAliasCveSATUM.Value.ToEntero, -1))
UM = TxtUMAlias.Text.Trim
Equivalencia = TxtUMEquivalenciaCantidad.Text.ToDouble
If Not CveUM > 0 Then
TieneError = True
End If
'AGREGA LA EQUIVALENCIA
If Not TieneError Then
If Not ObjPS.AddPSEquivalencias(TmpDT.Rows(HdnUMAliasInd.Value.ToEntero)("CvePS").ToString.ToEntero, CveUM, TxtUMEquivalenciaCantidad.Text.ToDecimal, False, 0, UsuarioActual.CveUsuario) Then
TieneError = True
End If
End If
'AGREGA ALIAS SI ES DIFERENTE EL TEXTO AL QUE VIENE EN EL XML
If Not TieneError And TxtUMAlias.Text.Trim <> HdnUMAlias.Value Then
If Not ObjUM.AddUnidadMedidaAlias(HdnUMAlias.Value, CveUM) Then
TieneError = True
End If
End If
'CveUM = DtEquivalencia.FiltroPrimeroValor("CveUM", "UnidadBase = 1").ToEntero
'UM = DtEquivalencia.FiltroPrimeroValor("UM", "UnidadBase = 1")
Case Else
End Select
If Not TieneError Then
ObjPS.Commit()
Alert("Unidad de medida actualizada correctamente.", TipoMensaje.MsgInformacion)
'ACTUALIZA DIRECTO DT
Dim Dr = TmpDT.Rows(HdnUMAliasInd.Value.ToEntero)
Dim CvePSModificado = Dr("CvePS").ToString.ToEntero
Dim CveUMModificada = Dr("CveUM").ToString.ToEntero
Dim UMModificada = Dr("UM").ToString
For Each DrUM As DataRow In TmpDT.Rows
If DrUM("CveUM").ToString.ToEntero = CveUMModificada And DrUM("UM").ToString = UMModificada Then
DrUM("CveUM") = CveUM
DrUM("UM") = UM
If Equivalencia > 0 Then
DrUM("Cantidad") = DrUM("Cantidad").ToString.ToDouble * Equivalencia
DrUM("PU") = DrUM("PU").ToString.ToDouble / Equivalencia
End If
TmpDT.AcceptChanges()
End If
Next
GvPS.DataSource = TmpDT
GvPS.DataBind()
UpPS.Update()
RegistraScript("$('#ModalUMAlias').modal('hide');", "ModalUMAliasHide")
DdlUMAlias.SelectedValue = "-1"
UpUMAlias.Update()
RecargaGlobalUM()
Else
ObjPS.RollBack()
Alert("Ocurrió un error al guardar la unidad de medida", TipoMensaje.MsgError)
End If
ObjPS.Dispose()
End Sub
Protected Sub LBAplicarEquivalencia_Click(sender As Object, e As EventArgs)
Dim Dr = TmpDT.Rows(CType(CType(sender, LinkButton).NamingContainer, GridViewRow).RowIndex)
Dim DtEquivalencia = GlobalDTProductosServiciosEquivalencias(Dr("CvePS").ToString.ToEntero, -1, UsuarioActual.CveEmpresa)
Dim Equivalencia = DtEquivalencia.FiltroPrimeroValor("Cantidad", $"CveUM = {Dr("CveUM")}").ToDouble
If Equivalencia > 0 Then
Dr("CveUM") = DtEquivalencia.FiltroPrimeroValor("CveUM", "UnidadBase = 1")
Dr("UM") = DtEquivalencia.FiltroPrimeroValor("UM", "UnidadBase = 1")
Dr("Cantidad") = Dr("Cantidad").ToString.ToDouble * Equivalencia
Dr("PU") = Math.Round(Dr("PU").ToString.ToDouble / Equivalencia, 6)
TmpDT.AcceptChanges()
GvPS.DataSource = TmpDT
GvPS.DataBind()
UpPS.Update()
Else
Alert("La cantidad de equivalencia de la unidad de medida debe ser mayor a 0", TipoMensaje.MsgAdvertencia)
End If
End Sub
Private Sub RecargaGlobalUM()
'Dim Hilo As New System.Threading.Thread(AddressOf GeneraGlobalUM)
'Hilo.Start()
GeneraGlobalUM()
End Sub
Private Sub GeneraGlobalUM()
GlobalDTProductosServiciosEquivalencias(-1, -1, UsuarioActual.CveEmpresa) = Nothing
GlobalDTUnidadesMedidaAlias(UsuarioActual.CveEmpresa) = Nothing
'Dim ObjPS = New ClsProductosServicios
'Dim OjbUM As New ClsUnidadesMedida
'If ObjPS.GetPSEquivalencias(-1, -1) Then
' GlobalDTProductosServiciosEquivalencias(-1, -1, UsuarioActual.CveEmpresa) = ObjPS.DtResultados
'End If
'If OjbUM.GetUnidadesMedidaAlias(-1) Then
' GlobalDTUnidadesMedidaAlias = OjbUM.DtResultados
'End If
'ObjPS.Dispose()
'OjbUM.Dispose()
End Sub
#End Region
#Region " COMPLEMENTOS PAGO "
Private Sub CargaComplementosPago()
Dim ObjCompras As New ClsCompras
If ObjCompras.GetCompraComplementoPago(CveCompra, UsuarioActual.CveEmpresa) Then
GvComplementoPagos.DataSource = ObjCompras.DtResultados
LnkCompleplementos.Visible = ObjCompras.DtResultados.Rows.Count > 0
Else
GvComplementoPagos.DataSource = Nothing
LnkCompleplementos.Visible = False
End If
If UsuarioActual.TienePermisoProceso(272) Then
GvComplementoPagos.Columns(5).Visible = True
End If
ObjCompras.Dispose()
GvComplementoPagos.DataBind()
UpComplementoPagos.Update()
End Sub
Protected Sub GvComplementoPagos_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvComplementoPagos.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
e.Row.Cells(3).Text = String.Format("<a class=""texto"" href=""/Compras/PopUpVerFactura.aspx?P={0}"" target=""_blank""><i class=""fa fa-ad-excel""></i></a>", Encripta(String.Format("OP=Fact&EXT=xml&CveFactura={0}&RFC={1}", e.Row.DBCampo("CveFactura"), e.Row.DBCampo(("RFCde").ToString.Replace("&", "%26%")))))
e.Row.Cells(4).Text = String.Format("<a class=""texto"" href=""/Compras/PopUpVerFactura.aspx?P={0}"" target=""_blank""><i class=""fa fa-ad-pdf""></i></a>", Encripta(String.Format("OP=Fact&EXT=pdf&CveFactura={0}&RFC={1}", e.Row.DBCampo("CveFactura"), e.Row.DBCampo("RFCde").ToString.Replace("&", "%26%"))))
End If
End Sub
#End Region
#Region " OTROS GASTOS "
Protected Sub LnkAddOtrosGastos_Click(sender As Object, e As EventArgs)
DdlOrdenCorte.SelectedIndex = 0
DdlOrdenCorte.SelectedValueExist(CveOrdenCorte)
UpOtrosGastos.Update()
RegistraScript("$('#DivOtrosGastos').modal();")
End Sub
Protected Sub BtnAddOtrosGastos_Click(sender As Object, e As EventArgs)
CveOrdenCorte = DdlOrdenCorte.SelectedValue.ToEntero()
RegistraScript("$('#DivOtrosGastos').modal('hide');")
End Sub
#End Region
'#Region " DROPDOWN IVA "
' 'Protected Sub DdlIVA_SelectedIndexChanged(sender As Object, e As EventArgs)
' ' CalculaTotales(True)
' 'End Sub
'#End Region
#Region " APLICA NC "
Private Sub InicializaAplicaNCFact()
HLAplicaNCFact.Visible = True
LblTotalNC.Text = TxtTotal.Text.FormatoNumero
CargaCuentasXPagar()
TabModoNC_ActiveTabChanged(TabModoNC, EventArgs.Empty)
End Sub
Private Sub CargaCuentasXPagar()
Dim ObjMovtos As New ClsMovimientos()
If ObjMovtos.GetCxPProveedor(CveProveedor, "-1", "-1", -1, -1, -1, -1, -1, -1, -1, -1, "-1", "-1") Then
GvFacturaNC.DataSource = ObjMovtos.DtResultados.FiltraParametros("Saldo > 0")
TmpCXP = ObjMovtos.DtResultados.FiltraParametros("Saldo > 0")
End If
ObjMovtos.Dispose()
GvFacturaNC.DataBind()
UpFacturaNC.Update()
End Sub
Protected Sub GvFacturaNC_RowDataBound(sender As Object, e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
If Not e.Row.DBCampo("CveCompra").ToEntero > 0 Then
e.Row.CssClass = "Totales"
e.Row.Cells(0).Text = ""
e.Row.Cells(4).Text = ""
Else
e.Row.FCTextBox("TxtImporte").Attributes.Add("onkeyup", $"LimitaCantidadNC({e.Row.DBCampo("Saldo").ToDouble},{TxtTotal.Text.ToDouble}, this);")
e.Row.FCCheckBox("ChkFacturaNC").Attributes.Add("onclick", $"FnCambiaFacturaNC({e.Row.DBCampo("Saldo").ToDouble},{e.Row.FCTextBox("TxtImporte").ClientID},{TxtTotal.Text.ToDouble},{LblAplicado.ClientID}, this);")
End If
End If
End Sub
#End Region
#Region " DEVOLUCION DE ALMACEN - DEVOLUCION AL PROVEEDOR "
Private Sub InicializaDevolucionAlmacen()
If Not GvInv.Rows.Count > 0 Or LblCompraEstatus.Text = "CANCELADA" Then
Exit Sub
End If
If CveCompra > 0 Then
'If CveVenta > 0 And DdlTipoComprobante.SelectedValue.Contiene({"Rem", "Ped"}) Then
If Not EstatusAlmacen = 2 Then
LiDevolucionAlmacen.Visible = True
End If
If EstatusAlmacen = 1 Then
HplDevv.Text = "<i class='fa fa-pencil'></i> Cancelar Devolución Almacén"
HplDevv.ToolTip = "¿Está seguro de Cancelar la Devolución de Almacén?"
Else
HplDevv.Text = "<i class='fa fa-pencil'></i> Solicitar Devolución Almacén"
HplDevv.ToolTip = "¿Está seguro de Solicitar la Devolución de Almacén?"
End If
End If
'UpInvDev.Update()
End Sub
Protected Sub LBDevolucionAlmacen_Click(sender As Object, e As EventArgs)
GvSolDev.DataSource = TmpDT
GvSolDev.DataBind()
RegistraScript("$('#DivDevolucion').modal('show');", "DivDevolucion")
UPPSolDev.Update()
End Sub
Private Sub GvSolDev_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvSolDev.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim ExistenciasAux As Decimal = e.Row.DataKey("Cantidad").ToDecimal
e.Row.FCRangeValidator("RVR").MaximumValue = ExistenciasAux.ToString
End If
End Sub
Protected Sub BtnDevolucion_Click(sender As Object, e As EventArgs)
Dim ObjCompras As New ClsCompras
Dim TieneError As Boolean = False
ObjCompras.IniciaTransacSQL()
If EstatusAlmacen = 0 Then
For Each gvr As GridViewRow In GvSolDev.Rows
If gvr.FCTextBox("TxtCant").Text.ToDecimal > 0 Then
'actualiza el estatus del detalle
ObjCompras.UpdateEstatusAlmacenDetalle(gvr.DataKey("CveCompraDetalle").ToEntero, 0, UsuarioActual.CveUsuario, CantidadDevolucion:=gvr.FCTextBox("TxtCant").Text.ToDecimal)
Else
ObjCompras.UpdateEstatusAlmacenDetalle(gvr.DataKey("CveCompraDetalle").ToEntero, 1, UsuarioActual.CveUsuario, CantidadDevolucion:=0)
End If
Next
End If
If ObjCompras.UpdateEstatusAlmacen(CveCompra, If(EstatusAlmacen = 1, 0, 1), UsuarioActual.CveUsuario) Then
EstatusAlmacen = If(EstatusAlmacen = 1, 0, 1)
Alert(If(EstatusAlmacen = 1, "La solicitud de devolución de almacen se guardo correctamente.", "La solicitud de almacen se canceló correctamente."))
End If
If Not TieneError Then
ObjCompras.Commit()
Else
ObjCompras.RollBack()
End If
ObjCompras.Dispose()
InicializaDevolucionAlmacen()
End Sub
'Protected Sub LBDevolucionAlmacen_Click(sender As Object, e As EventArgs)
' Dim ObjCompras As New ClsCompras
' If ObjCompras.UpdateEstatusAlmacen(CveCompra, If(EstatusAlmacen = 1, 0, 1)) Then
' EstatusAlmacen = If(EstatusAlmacen = 1, 0, 1)
' Alert(If(EstatusAlmacen = 1, "La solicitud de devolución de almacen se guardo correctamente.", "La solicitud de almacen se canceló correctamente."))
' End If
' ObjCompras.Dispose()
' InicializaDevolucionAlmacen()
'End Sub
Private Sub HabilitaNCInv()
If Not UsuarioActual.CveUsuario = 100 Then
If Not UsuarioActual.CveEmpresa.Contiene(72, 119, 80) Then
Exit Sub
End If
End If
If CveCompra > 0 And GvInvMov.Rows.Count > 0 Then
Dim ObjInventarios As New ClsInventarios
If ObjInventarios.RecepcionAlmacenGet(CveCompra, -1, -1, UsuarioActual.CveEmpresa, -1) AndAlso ObjInventarios.DtResultados.Rows.Count > 0 Then
DtPendientesAlmacen = ObjInventarios.DtResultados.FiltraParametros("CantidadF > 0").Copy
End If
ObjInventarios.Dispose()
If DtPendientesAlmacen IsNot Nothing AndAlso DtPendientesAlmacen.Rows.Count > 0 Then
ChkNCInv.Visible = True
GVNCInv.DataSource = DtPendientesAlmacen
GVNCInv.DataBind()
GVNCInvAlmacen.DataSource = DtPendientesAlmacen
GVNCInvAlmacen.DataBind()
End If
End If
End Sub
Protected Sub ChkNCInv_CheckedChanged(sender As Object, e As EventArgs)
CargaAnticipos(CveProveedor, If(ChkNCInv.Checked, "NC", "-1"))
UpAnticipos.Update()
End Sub
Private Sub CargaNCINV(Optional ShowAllPendientes As Boolean = False)
Dim SaldoAnticipo = 0.0
Dim CveCompras As String = ""
If ChkNCInvNC.Checked Then
If Not ShowAllPendientes Then
For Each gvr As GridViewRow In GvFacturaNC.Rows
If gvr.FCCheckBox("ChkFacturaNC") IsNot Nothing AndAlso gvr.FCCheckBox("ChkFacturaNC").Checked Then
SaldoAnticipo += gvr.FCTextBox("TxtImporte").Text.ToDouble
If CveCompras <> "" Then
CveCompras = $"{CveCompras},{gvr.DataKey("CveCompra").ToString}"
Else
CveCompras = gvr.DataKey("CveCompra").ToString
End If
End If
Next
End If
Else
For Each gvr As GridViewRow In GVAnticipos.Rows
If gvr.FCCheckBox("Chk") IsNot Nothing AndAlso gvr.FCCheckBox("Chk").Checked Then
SaldoAnticipo += gvr.FCTextBox("TxtAnticipo").Text.ToDouble
End If
Next
If SaldoAnticipo <= 0 Then
Alert("No hay movimientos seleccionados para aplicar", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
End If
LbNCInvSaldo.Text = SaldoAnticipo.FormatoNumero()
LbNCInvSaldoAlmacen.Text = SaldoAnticipo.FormatoNumero()
If ChkNCInvNC.Checked Then
Dim ObjInventarios As New ClsInventarios
If ObjInventarios.RecepcionAlmacenGet(-1, -1, CveProveedor, UsuarioActual.CveEmpresa, -1) AndAlso ObjInventarios.DtResultados.FiltraParametros($"CantidadF > 0").Rows.Count > 0 Then
DtPendientesAlmacen = ObjInventarios.DtResultados.FiltraParametros($"CantidadF > 0").Copy
End If
ObjInventarios.Dispose()
End If
If (DtPendientesAlmacen IsNot Nothing AndAlso DtPendientesAlmacen.Rows.Count > 0) Then
If ChkNCInvNC.Checked Then
GVNCInv.DataSource = DtPendientesAlmacen
GVNCInv.DataBind()
If Not String.IsNullOrEmpty(CveCompras) Then
DtPendientesAlmacen = DtPendientesAlmacen.FiltraParametros($"CveCompra IN ({CveCompras})")
End If
GVNCInvAlmacen.DataSource = DtPendientesAlmacen
GVNCInvAlmacen.DataBind()
End If
Else
If ChkNCInvNC.Checked Then
Alert("Niguna de las facturas seleccionadas cuenta con productos pendientes de darles entrada.", TipoMensaje.MsgAdvertencia)
ChkNCInvNC.Checked = False
UpChkNCInvNC.Update()
Exit Sub
Else
RegistraScript("$('#ModalNCConfirmación').modal('show');", "ModalNCInv")
End If
End If
UpNCInv.Update()
UpFacturaNC.Update()
End Sub
Protected Sub GVNCInv_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GVNCInv.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
'e.Row.FCCheckBox("cbInv").Attributes.Add("onclick", "FnCambiaInvNC(this);")
e.Row.FCTextBox("TxtCantidadNCInv").Attributes.Add("onkeyup", $"ValidarCantidad(this,{e.Row.DBCampo("CantidadF")});FnCambiaInvNC(this);")
End If
End Sub
Protected Sub GVNCInvAlmacen_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GVNCInvAlmacen.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
'e.Row.FCCheckBox("cbInv").Attributes.Add("onclick", "FnCambiaInvNC(this);")
e.Row.FCTextBox("TxtCantidadNCInv").Attributes.Add("onkeyup", $"ValidarCantidad(this,{e.Row.DBCampo("CantidadF")});FnCambiaInvNC(this);")
End If
End Sub
Protected Sub BtnNCInv_Click(sender As Object, e As EventArgs)
If ChkNCInvNC.Checked Then
RegistraScript("$('#ModalNCInv').modal('hide');", "ModalNCInv")
RegistraScript("$('#DivAnticipos').modal('hide');", "FacturaNC")
Exit Sub
End If
Dim Contador = 0
Dim CveCompraNC = -1
For Each gvr As GridViewRow In GVAnticipos.Rows
If gvr.FCCheckBox("Chk") IsNot Nothing AndAlso gvr.FCCheckBox("Chk").Checked Then
Contador += 1
CveCompraNC = gvr.DataKey("CveCompra").ToString.ToEntero
End If
Next
If Contador <> 1 Then
Alert("Debe seleccionar por lo menos una NC a aplicar.", TipoMensaje.MsgAdvertencia)
RegistraScript("$('#ModalNCInv').modal('hide');", "ModalNCInv")
RegistraScript("$('#DivAnticipos').modal('hide');", "ModalAnticipos")
Exit Sub
End If
If Not CveCompraNC > 0 Then
Alert("Ocurrió un error al guardar la cancelación de inventarios. Por favor comuniquese con asistencia SIG", TipoMensaje.MsgError)
Exit Sub
End If
Dim ObjCompras As New ClsCompras
Dim ObjConta As New ClsContabilidad(ObjCompras.IniciaTransacSQL)
Dim TieneError = False
For Each Gvr As GridViewRow In GVNCInv.Rows
If Gvr.FCTextBox("TxtCantidadNCInv").Text.ToDouble > 0 Then
If Not ObjCompras.ComprasDetalleDevolucionesAdd(Gvr.DataKey("CveCompraDetalle").ToEntero, CveCompraNC, Gvr.FCTextBox("TxtCantidadNCInv").Text.ToDouble, UsuarioActual.CveEmpresa) Then
TieneError = True
Exit For
End If
End If
Next
If Not TieneError Then
GuardaAnticipos(ObjCompras, ObjConta)
Else
ObjCompras.RollBack()
End If
ObjCompras.Dispose()
RegistraScript("$('#ModalNCInv').modal('hide');", "ModalNCInv")
RegistraScript("$('#DivAnticipos').modal('hide');", "ModalAnticipos")
End Sub
Protected Sub BtnNCConfirmacion_Click(sender As Object, e As EventArgs)
GuardaAnticipos(Nothing, Nothing)
End Sub
Protected Sub BtnNCInvAlmacen_Click(sender As Object, e As EventArgs)
'Dim ObjCompras As New ClsCompras
'Dim ObjConta As New ClsContabilidad(ObjCompras.IniciaTransacSQL)
'Dim TieneError = False
'For Each Gvr As GridViewRow In GVNCInvAlmacen.Rows
' If Gvr.FCTextBox("TxtCantidadNCInv").Text.ToDouble > 0 Then
' If Not ObjCompras.ComprasDetalleDevolucionesAdd(Gvr.DataKey("CveCompraDetalle").ToEntero, Gvr.DataKey("CveCompra").ToEntero, Gvr.FCTextBox("TxtCantidadNCInv").Text.ToDouble, UsuarioActual.CveEmpresa) Then
' TieneError = True
' Exit For
' End If
' End If
'Next
'If Not TieneError Then
' Alert("Se guardo la devolución correctamente", TipoMensaje.MsgInformacion)
' ObjCompras.Commit()
'Else
' Alert("Ocurrió un error al guardar la devolución", TipoMensaje.MsgError)
' ObjCompras.RollBack()
'End If
'ObjCompras.Dispose()
RegistraScript("$('#FacturaNC').modal('hide');", "ModalNCInv")
End Sub
#End Region
#Region " INVENTARIO: MOVIMIENTOS DE LA COMPRA "
Private Sub InventarioMov()
Dim ObjVentas As New ClsInventarios
If ObjVentas.GetInv_ComprasMov(CveCompra, UsuarioActual.CveEmpresa) Then
If ObjVentas.DtResultados.Rows.Count > 0 Then
GvInvMov.DataSource = ObjVentas.DtResultados
GvInvMov.Columns(3).Visible = ObjVentas.DtResultados.MAX("Serie", "Serie <> ''") <> ""
'GvInvMov.Columns(5).Visible = DtTemporal.MAX("Lote", "Lote <> ''") <> ""
'GvInvMov.Columns(6).Visible = DtTemporal.MAX("FechaCaducidad").ToDate > MinFecha
End If
End If
GvInvMov.DataBind()
GvInvMov.Visible = True
ObjVentas.Dispose()
UpINV.Update()
End Sub
Private Sub GvInvMov_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvInvMov.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
If e.Row.DBCampo("CvePS") = "" Then
e.Row.FCLiteral("LtlPS").Text = String.Format("<a Class=""Texto"" target='_blank' href=""/Inventarios/EntradasSalidas.aspx?CveMovimiento={0}"">Folio: {1} Fecha: {2} {3} {4}</a>", e.Row.DBCampo("CveMovimiento"), e.Row.DBCampo("Folio"), e.Row.DBCampo("Fecha").ToString.ToDate.ToShortDateString, e.Row.DBCampo("Almacen").ToString, e.Row.DBCampo("Concepto").ToString)
If e.Row.DataKey("Origen").ToEntero > 0 Then
e.Row.CssClass = "SubTotales"
Else
e.Row.BackColor = Drawing.Color.FromArgb(224, 130, 131)
e.Row.ForeColor = Drawing.Color.White
e.Row.Font.Bold = True
End If
Else
e.Row.Cells(3).HorizontalAlign = HorizontalAlign.Left
End If
End If
End Sub
Private Sub GvAcarreo_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvAcarreo.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
e.Row.FCLiteral("LtlImporte").Text = "$" + FormatNumber(e.Row.FCLiteral("LtlImporte").Text.ToDouble, 2, , , TriState.True)
End If
End Sub
#End Region
#Region " REGENERA PREPOLIZA "
Protected Sub BtnRegenerarPrePolizaAlmacen_Click(sender As Object, e As EventArgs)
'RegeneraPrePoliza()
Dim ObjCompra As New ClsCompras
Dim ObjContabilidad As New ClsContabilidad(ObjCompra.IniciaTransacSQL)
Dim Estatus = ActualizarPrePoliza(ObjContabilidad, ObjCompra)
If Estatus Then
ObjCompra.Commit()
Alert("La PrePoliza se regeneró correctamente.", TipoMensaje.MsgInformacion)
Else
ObjCompra.RollBack()
Alert("Ocurrió un error al regenerar la PrePoliza.", TipoMensaje.MsgError)
End If
ObjCompra.Dispose()
End Sub
Private Sub RegeneraPrePoliza()
'Alert($"CvePrePoliza de la compra: {CvePrePoliza}", TipoMensaje.MsgInformacion)
'MOVIMIENTOS DE ALMACEN DE LA COMPRA
Dim ObjInventarios As New ClsInventarios
Dim DtInv As New DataTable
If ObjInventarios.GetInv_ComprasMov(CveCompra, UsuarioActual.CveEmpresa) AndAlso ObjInventarios.DtResultados.Rows.Count > 0 Then
DtInv = ObjInventarios.DtResultados
End If
ObjInventarios.Dispose()
Dim DtTemporal = TmpDT.Copy
DtTemporal.Columns.Add("ImporteEnAlmacen", GetType(Decimal))
Dim ObjConta As New ClsContabilidad
ObjConta.IniciaTransacSQL()
Dim TieneError = True
'ELIMINA DETALLES DE [AF - INV - GASTO]
If ObjConta.RemovePrePolizasDetalle(CvePrePoliza, 49, CveCompra, 1) Then
If ObjConta.RemovePrePolizasDetalle(CvePrePoliza, 68, CveCompra, 1) Then
If ObjConta.RemovePrePolizasDetalle(CvePrePoliza, 6, CveCompra, 1) Then
TieneError = False
End If
End If
End If
'INGRESAMOS DETALLES
If Not TieneError Then
'CONFIGURACIONES
Dim CuentasContablesInvalidas As New StringBuilder
Dim IdCtaContable As Integer = 0
Dim CveProveedorConcepto = 0
Dim Concepto = $"{NombreProveedor} {TxtSerie.Text} - {TxtFolio.Text}"
Dim Multiplicador = If(DdlTipoComprobante.SelectedValue = "NC", -1, 1)
Dim ImporteMovimiento = 0.0D
Dim importeMN = 0.0D
Dim TipoCambioActual = 0.0D
Dim TipoCambioPago = 0.0D
Dim FechaMovimiento As Date = TxtFecha.Text.ToDate
'TIPO CAMBIO
If DdlMoneda.SelectedValue.ToString.ToEntero = 2 Then
TipoCambioActual = GlobalTipoCambio(FechaMovimiento).ToString.ToDecimal
TipoCambioPago = GlobalTipoCambio(TxtFechaPago.Text.ToDate).ToString.ToDecimal
Else
TipoCambioActual = 1
TipoCambioPago = 1
End If
'CTA PROVEEDOR
Select Case RBLContado.SelectedValue
Case "4" ' Deudores
CveProveedorConcepto = DdlDeudor.SelectedValue.ToEntero
Case "5" ' Acreedores
CveProveedorConcepto = DdlAcreedor.SelectedValue.ToEntero
Case Else ' Proveedores - F y E - Doctos
CveProveedorConcepto = CveProveedor
End Select
'INGRESA DETALLE DE AF(49) - TipoAF 2 es para las compras
Dim DT = DtTemporal.FiltraParametros("ISNULL(TipoAF,0) = 2")
If DT.Rows.Count > 0 AndAlso DdlTipoComprobante.SelectedValue <> "NC" Then
For Each Row2 As DataRow In DT.Rows
ImporteMovimiento = Row2("Total").ToString.ToDecimal * Multiplicador
importeMN = ImporteMovimiento * TipoCambioActual
If ObjConta.GetRetCuenta(49, Row2("CveActivoFijo").ToString.ToEntero) Then
If ObjConta.DtResultados.Rows.Count > 0 Then
IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCtaContActivoFijo").ToString.ToEntero
End If
End If
If ImporteMovimiento <> 0 Then
If IdCtaContable = 0 Then
CuentasContablesInvalidas.Append("<br>" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 49))("ConceptoContable").ToString)
End If
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, ImporteMovimiento, Row2("CodAF").ToString, 49, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveActivoFijo:=Row2("CveActivoFijo").ToString.ToEntero, ImporteMX:=importeMN, ImporteME:=If(TipoCambioActual = 1, 0, ImporteMovimiento)) Then
TieneError = True
End If
End If
Next
End If
ImporteMovimiento = 0
IdCtaContable = 0
'INGRESA DETALLE DE ALMACÉN(68)
Dim DtAlmacenes = GlobalDTAlmacen(UsuarioActual.CveEmpresa)
If UsuarioActual.Empresa.UsaInventarios AndAlso Not UsuarioActual.Empresa.Funcionalidad(126) = "1" Then
Dim CveMovimientoInventario = -1
Dim ModalidadAlmacen = -1
Dim DtMovtosAlmacen As New DataTable
DtMovtosAlmacen.Columns.Add("CveMovimiento", GetType(Integer))
DtMovtosAlmacen.Columns.Add("IdCtaContable", GetType(Integer))
DtMovtosAlmacen.Columns.Add("CveCuenta", GetType(Integer))
DtMovtosAlmacen.Columns.Add("Importe", GetType(Decimal))
If DtTemporal.FiltraParametros("ISNULL(TipoAF,0) <> 2").Rows.Count > 0 Then
For Each Row2 As DataRow In DtTemporal.FiltraParametros("ISNULL(TipoAF,0) <> 2").Rows
'VALIDAMOS TIPO ALMACEN DE LA COMPRA DETALLE - SI ES TIPO "SOLO EXISTENCIA" (0) SKIPEAMOS
ModalidadAlmacen = DtInv.MIN("ModalidadAlmacen", $"CveCompraDetalle = {Row2("CveCompraDetalle")}").ToEntero
If ModalidadAlmacen = 0 Then
Continue For
End If
CveMovimientoInventario = DtInv.MAX("CveMovimiento", $"CveCompraDetalle = {Row2("CveCompraDetalle")}").ToEntero
IdCtaContable = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCtaContable", $"CveAlmacen = {DtInv.MIN("CveAlmacen", $"CveCompraDetalle = {Row2("CveCompraDetalle")}")}").ToEntero
ImporteMovimiento = DtInv.SUM(If(DdlMoneda.SelectedValue = "1", "Total", "TotalExtranjero"), $"CveCompraDetalle = {Row2("CveCompraDetalle")}").ToDecimal
ImporteMovimiento = If(ImporteMovimiento > Row2("Total").ToString.ToDecimal, Row2("Total").ToString.ToDecimal, ImporteMovimiento) * Multiplicador
'VALIDA QUE CUANDO SEA DOLARES TENGA PUEXTRANJERO EN EL MOVTO DE ALMACEN
If DdlMoneda.SelectedValue = "2" And ImporteMovimiento = 0 And DtInv.SUM("Total", $"CveCompraDetalle = {Row2("CveCompraDetalle")}").ToDecimal > 0 Then
TieneError = True
Exit For
End If
Dim DrInv = DtMovtosAlmacen.NewRow
DrInv("CveMovimiento") = CveMovimientoInventario
DrInv("IdCtaContable") = IdCtaContable
DrInv("Importe") = ImporteMovimiento
DtMovtosAlmacen.Rows.Add(DrInv)
If ImporteMovimiento <> 0 Then
Row2("ImporteEnAlmacen") = ImporteMovimiento
End If
Next
For Each Row As DataRow In DtMovtosAlmacen.FiltraParametros("", "", {"CveMovimiento", "IdCtaContable"}).Rows
ImporteMovimiento = DtMovtosAlmacen.SUM("Importe", $"CveMovimiento = {Row("CveMovimiento").ToString.ToEntero} AND IdCtaContable = {Row("IdCtaContable").ToString.ToEntero}").ToString.ToDecimal
importeMN = ImporteMovimiento * TipoCambioActual
If ImporteMovimiento <> 0 Then
If IdCtaContable = 0 Then
CuentasContablesInvalidas.Append("<br>" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 68))("ConceptoContable").ToString)
End If
Dim SeContabiliza As Boolean = True
'SI ES GASTO DE ALMACEN NO DEBE CONTABILIZAR CONCEPTO 68
If DdlTipoCompra.SelectedValue = "10" Then
SeContabiliza = False
End If
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, ImporteMovimiento, Concepto, 68, Concepto, FechaMovimiento, Row("IdCtaContable").ToString.ToEntero, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveMovimientoAlmacen:=Row("CveMovimiento").ToString.ToEntero, ImporteMX:=importeMN, ImporteME:=If(TipoCambioActual = 1, 0, ImporteMovimiento), Contabilizable:=SeContabiliza) Then
TieneError = True
Exit For
End If
End If
Next
End If
End If
ImporteMovimiento = 0
IdCtaContable = 0
'INGRESA DETALLE DE GASTO(6)
DT = DtTemporal
'RECORREMOS PARA DETECTAR LA MODALIDAD DEL ALMACEN, EN CASO DE SER SOLO EXISTENCIA LIMPIAMOS CVEALMACEN
For Each Dr As DataRow In DT.Rows
Dr("CveAlmacen") = DtInv.MIN("ModalidadAlmacen", $"CveCompraDetalle = {Dr("CveCompraDetalle")}").ToEntero
Dr.AcceptChanges()
Next
DT.AcceptChanges()
If UsuarioActual.Empresa.Funcionalidad(126) = "1" Then
DT = DT.FiltraParametros("ISNULL(TipoAF,0) <> 2", "", {"CveClasificacion", "Clasificacion", "SubProyecto", "CveProyecto", "CveSubProyecto"})
Else
DT = DT.FiltraParametros("ISNULL(TipoAF,0) <> 2 AND ISNULL(CveAlmacen,0) = 0 AND ISNULL(AplicaCostoIndirecto,0) <> 1", "", {"CveClasificacion", "Clasificacion", "SubProyecto", "CveProyecto", "CveSubProyecto"})
End If
If DT.Rows.Count > 0 Then
Dim ImporteAlmacen = 0.0D
For Each Row2 As DataRow In DT.Rows
If UsuarioActual.Empresa.Funcionalidad(126) = "1" Then
ImporteMovimiento = DtTemporal.SUM("Total", String.Format("ISNULL(TipoAF,0) <> 2 AND CveClasificacion = {0} AND CveSubProyecto = {1}", Row2("CveClasificacion"), Row2("CveSubProyecto"))).ToString.ToDecimal
ImporteAlmacen = DtTemporal.SUM("ImporteEnAlmacen", String.Format("ISNULL(TipoAF,0) <> 2 AND CveClasificacion = {0} AND CveSubProyecto = {1}", Row2("CveClasificacion"), Row2("CveSubProyecto"))).ToString.ToDecimal
Else
ImporteMovimiento = DtTemporal.SUM("Total", String.Format("ISNULL(TipoAF,0) <> 2 AND ISNULL(CveAlmacen,0) = 0 AND ISNULL(AplicaCostoIndirecto,0) <> 1 AND CveClasificacion = {0} AND CveSubProyecto = {1}", Row2("CveClasificacion"), Row2("CveSubProyecto"))).ToString.ToDecimal
ImporteAlmacen = DtTemporal.SUM("ImporteEnAlmacen", String.Format("ISNULL(TipoAF,0) <> 2 AND CveClasificacion = {0} AND CveSubProyecto = {1}", Row2("CveClasificacion"), Row2("CveSubProyecto"))).ToString.ToDecimal
End If
ImporteMovimiento = (ImporteMovimiento - ImporteAlmacen) * Multiplicador
importeMN = ImporteMovimiento * TipoCambioActual
If Row2("CveClasificacion").ToString.ToEntero > 0 Then
If ObjConta.GetRetCuenta(6, Row2("CveClasificacion").ToString.ToEntero) Then
If ObjConta.DtResultados.Rows.Count > 0 AndAlso (ObjConta.DtResultados.Rows(0)("IdCuentaGasto").ToString.ToEntero > 0 Or ObjConta.DtResultados.Rows(0)("IdCuentaGastoSIG").ToString.ToEntero > 0) Then
IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaGasto").ToString.ToEntero
Else
IdCtaContable = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaGasto", String.Format("CveClasificacion = {0}", Row2("CveClasificacion"))).ToString.ToEntero
End If
End If
End If
Dim IdSegmentoNegocio As Integer = -1
Dim drT As DataRow = GlobalDTSubProyectos(-1, CveSubProyecto:=Row2("CveSubProyecto").ToString.ToEntero).FiltroPrimero(String.Format("CveSubProyecto = {0} ", Row2("CveSubProyecto")))
If drT IsNot Nothing Then
IdSegmentoNegocio = drT("IdSegNeg").ToString.ToEntero
End If
If ImporteMovimiento <> 0 Then
If IdCtaContable = 0 Then
CuentasContablesInvalidas.Append("<br>" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 6))("ConceptoContable").ToString)
End If
Dim tcvecon As Integer = 6
Dim tidctacon As Integer = 6
tidctacon = IdCtaContable
If DdlTipoComprobante.SelectedValue = "Ant" Then
tcvecon = 264
tidctacon = ViewState("CtaProveedorAnticipos").ToString.ToEntero
If DdlMoneda.SelectedValue = "2" Then
tidctacon = ViewState("CtaProveedorAnticiposExtranjera").ToString.ToEntero
End If
End If
Concepto = $"{NombreProveedor} {TxtSerie.Text} - {TxtFolio.Text}"
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, ImporteMovimiento, Concepto, tcvecon, Concepto, FechaMovimiento, IdCtaContable, IdSegmentoNegocio, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveClasificacion:=Row2("CveClasificacion").ToString.ToEntero, CveSubProyecto:=Row2("CveSubProyecto").ToString.ToEntero, ImporteMX:=importeMN, ImporteME:=If(TipoCambioActual = 1, 0, ImporteMovimiento)) Then
TieneError = True
End If
End If
Next
End If
End If
If Not TieneError Then
ObjConta.Commit()
Alert("La PrePoliza se regeneró correctamente.", TipoMensaje.MsgInformacion)
Else
ObjConta.RollBack()
Alert("Ocurrió un error al regenerar la PrePoliza. Por favor vuelva a intentar.", TipoMensaje.MsgError)
End If
ObjConta.Dispose()
End Sub
#End Region
#Region " ACTUALIZAR TIPO CAMBIO PREPOLIZA "
Private Sub InicializaActualizarTC()
If CveCompra > 0 And DdlMoneda.SelectedValue.ToEntero = 2 And CvePrePoliza > 0 Then
TxtActualizarTC_TCActual.Text = TipoCambio.FormatoNumero(4)
TxtActualizarTC_TCActualizar.Text = GlobalTipoCambio(TxtFecha.Text.ToDate).FormatoNumero(4)
HLModalActualizarTC.Visible = True
End If
End Sub
Protected Sub BtnActualizarTC_Click(sender As Object, e As EventArgs)
Dim ObjContabilidad As New ClsContabilidad
Dim ObjCompras As New ClsCompras(ObjContabilidad.IniciaTransacSQL())
Dim ObjEventos As New ClsOIEventos(ObjContabilidad.IniciaTransacSQL())
Dim TieneError = False
Dim MensajeError = ""
If ObjEventos.AddEventoBitacora($"Se actualizó el Tipo de Cambio de la compra. TC anterior: {TxtActualizarTC_TCActual.Text.FormatoNumero(4)} | TC actual: {TxtActualizarTC_TCActualizar.Text.FormatoNumero(4)}", "", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCompra:=CveCompra) Then
If ObjCompras.UpdateCompraTipoCambio(TxtActualizarTC_TCActualizar.Text.ToDouble, CveCompra, CvePrePoliza, UsuarioActual.CveEmpresa) Then
If Not ObjContabilidad.ReconstruirPP_Compra(CveCompra) Then
TieneError = True
MensajeError = "Ocurrió un error al actualizar el Tipo de Cambio al documento"
End If
Else
TieneError = True
MensajeError = "Ocurrió un error al actualizar el asiento contable"
End If
Else
TieneError = True
MensajeError = "Ocurrió un error al guardar el historal al actualizar el Tipo de Cambio al documento"
End If
If Not TieneError Then
ObjContabilidad.Commit()
Alert("Se actualizó correctamente el tipo de cambio del documento.", TipoMensaje.MsgInformacion)
RegistraScript("$('#ModalActualizarTC').modal('hide');")
Else
ObjContabilidad.RollBack()
Alert(MensajeError, TipoMensaje.MsgError)
End If
ObjContabilidad.Dispose()
End Sub
#End Region
#Region "PAQUETERIAS GUIAS"
Protected Sub LnkAgregarGuia_Click(sender As Object, e As EventArgs)
'' 25/05/2018 - Se agrega Link a Modulo Paqueterias Guias
RegistraScript(String.Format("AbrirVentana('/General/PopUpPaqueteriasGuias.aspx?CveCompra={0}',800,620);", CveCompra))
End Sub
#End Region
#Region "DEDUCCIONES IEPS / OTROS IMPUESTOS"
Protected Sub CargaProductos(Ddl As DropDownList, CvePS As Integer)
Ddl.DataSource = TmpDT
Ddl.DataBind()
Ddl.Items.Insert(0, New ListItem("Seleccione un concepto", "-1"))
Ddl.SelectedValueExist("-1")
If CvePS > 0 Then
Ddl.Items.Insert(1, New ListItem(GlobalDTPS(UsuarioActual.CveEmpresa, CvePS).FiltroPrimeroValor("PS"), CvePS.ToString))
End If
'Ddl.Items.Insert(1, New ListItem(Concepto, "-1"))
End Sub
Protected Sub BtnAgregarIEPS_Click(sender As Object, e As EventArgs)
TrasladoIEPS = TxtIEPS.Text.ToDecimal
OtrosImpuestos = TxtOtrosImpuestos.Text.ToDecimal
If ChkIEPS.Checked Then IEPSGasto = True
If ChkOtrosI.Checked Then OtrosImpuestosGasto = True
If IEPSGasto Or OtrosImpuestosGasto Then
'AGREGA IEPS COMO CONCEPTO
If IEPSGasto Then
Dim CvePS As Integer = DdlConceptoIEPS.SelectedValue.ToEntero
' If CvePS = -1 Then CvePS = UsuarioActual.Empresa.Funcionalidad(112).ToString.ToEntero
AgregarConceptoIEPS(TrasladoIEPS, CvePS)
TrasladoIEPS = 0
TxtIEPS.Text = 0.ToString.FormatoNumero
TrIEPS.Visible = False
For Each Dr As DataRow In TmpDT.Rows
Dr("IEPSPS") = 0
Dr("IEPSPSPorcentaje") = 0
Next
TmpDT.AcceptChanges()
End If
'AGREGA OTROS IMPUESTOS COMO CONCEPTO
If OtrosImpuestosGasto Then
Dim CvePS As Integer = DdlConceptoOI.SelectedValue.ToEntero
'If CvePS = -1 Then CvePS = UsuarioActual.Empresa.Funcionalidad(305).ToString.ToEntero
AgregarConceptoIEPS(OtrosImpuestos, CvePS)
OtrosImpuestos = 0
TxtOtrosImpuestos.Text = 0.ToString.FormatoNumero
TrOtrosImpuestos.Visible = False
End If
CargaGvPersonal()
UpPS.Update()
RegistraScript("$('#ModalIEPS').modal('hide');")
Else
Alert("Debe seleccionar al menos un impuesto", TipoMensaje.MsgAdvertencia)
End If
MostrarOcultarColumnaIEPS()
AddPS2()
End Sub
#End Region
#Region "C R E D I T O S"
Private Sub ChkCreditoMultiple_CheckedChanged(sender As Object, e As EventArgs) Handles ChkCreditoMultiple.CheckedChanged
If ChkCreditoMultiple.Checked Then
romCreditosTabla.Visible = True
Dim ObjBancos As New ClsBancos
If ObjBancos.GetCreditosDetalleCompras(UsuarioActual.CveEmpresa, CveProveedor, -1, -1, -1) Then
GvCreditos.DataSource = ObjBancos.DtResultados
Else
GvCreditos.DataSource = Nothing
End If
ObjBancos.Dispose()
GvCreditos.DataBind()
End If
End Sub
Private Sub GvCreditos_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvCreditos.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim TxtCapital As TextBox = e.Row.FCTextBox("TxtCapital")
Dim TxtInteres As TextBox = e.Row.FCTextBox("TxtInteres")
Dim TxtAmbos As TextBox = e.Row.FCTextBox("TxtAmbos")
Dim CveCreditoDetalle As Integer = e.Row.DataKey("CveCreditoDetalle").ToEntero
Dim CveCompraCapital As Integer = e.Row.DataKey("CveCompra").ToEntero
Dim CveCompraInteres As Integer = e.Row.DataKey("CveCompraInteres").ToEntero
If CveCompraCapital > 0 Then
TxtCapital.Enabled = False
TxtAmbos.Enabled = False
End If
If CveCompraInteres > 0 Then
TxtInteres.Enabled = False
TxtAmbos.Enabled = False
End If
TxtCapital.Attributes.Add("class", $"CsCreGlobal CsSelCapital{CveCreditoDetalle}")
TxtCapital.Attributes.Add("onkeyup", $"ValidaCredito(this,event,{CveCreditoDetalle},1)")
'TxtCapital.Attributes.Add("data-CD", CveCreditoDetalle.ToString)
TxtInteres.Attributes.Add("class", $"CsCreGlobal CsSelInteres{CveCreditoDetalle}")
TxtInteres.Attributes.Add("onkeyup", $"ValidaCredito(this,event,{CveCreditoDetalle},1)")
'TxtInteres.Attributes.Add("data-CD", CveCreditoDetalle.ToString)
TxtAmbos.Attributes.Add("class", $"CsCreGlobal CsSelAmbos{CveCreditoDetalle}")
TxtAmbos.Attributes.Add("onkeyup", $"ValidaCredito(this,event,{CveCreditoDetalle},2)")
'TxtAmbos.Attributes.Add("data-CD", CveCreditoDetalle.ToString)
End If
End Sub
Private Sub CargaCreditosDisponibles()
If RBLPago.SelectedValue.ToEntero = 4 Then
Dim ObjBancos As New ClsBancos
If ObjBancos.GetCreditosDetalleCompras(UsuarioActual.CveEmpresa, CveProveedor, -1, -1, -1) Then
GvCreditos.DataSource = ObjBancos.DtResultados
Else
GvCreditos.DataSource = Nothing
End If
ObjBancos.Dispose()
romCreditosTabla.Visible = True
GvCreditos.DataBind()
Else
romCreditosTabla.Visible = False
End If
UpGvCreditos.Update()
End Sub
#End Region
#Region "FLETES / IMPORTACIONES"
Private Sub CargaFolio()
Dim ObjFolios As New ClsGralFolios
If ObjFolios.GetFolios("FLE", UsuarioActual.CveEmpresa) Then
If ObjFolios.DtResultados.Rows.Count > 0 Then
LblFolioModalFletes.Text = ObjFolios.DtResultados(0)("FActual").ToString
BtnCrearFleteImportacion.Enabled = True
Else
Alert("Necesita registrar un folio de fletes", TipoMensaje.MsgAdvertencia)
BtnCrearFleteImportacion.Enabled = False
End If
End If
ObjFolios.Dispose()
End Sub
Protected Sub BtnGuardarModalFletesImportaciones_Click(sender As Object, e As EventArgs)
If DdlFleteImportacion.SelectedValue.ToEntero = 237 And Not DdlFletes.SelectedValue.ToEntero > 0 Then Alert("Tiene que seleccionar un flete", TipoMensaje.MsgAdvertencia) : Exit Sub
If DdlFleteImportacion.SelectedValue.ToEntero = 240 And Not DdlImportaciones.SelectedValue.ToEntero > 0 Then Alert("Tiene que seleccionar una importación", TipoMensaje.MsgAdvertencia) : Exit Sub
If DdlFletes.SelectedValue.ToEntero > 0 Then
Dim ObjInventario As New ClsInventarios
Dim Dr As DataRow = Nothing
If ObjInventario.GetFletes(UsuarioActual.CveEmpresa, DdlFletes.SelectedValue.ToEntero) Then
If ObjInventario.DtResultados.Rows.Count > 0 Then
Dr = ObjInventario.DtResultados.Rows(0)
End If
End If
'If Dr IsNot Nothing Then
' If Dr("CveCompra").ToString.ToEntero > 0 And RblFleteImportacionOpcion.SelectedValue.ToEntero = 1 Then
' Alert("Este flete ya tiene compra asignada", TipoMensaje.MsgAdvertencia)
' ObjInventario.Dispose()
' Exit Sub
' End If
'End If
ObjInventario.Dispose()
End If
If DdlFleteImportacion.SelectedValue.ToEntero = 237 Then DdlTipoCompra.SelectedValueExist("4") : UpEstatus.Update()
If DdlFleteImportacion.SelectedValue.ToEntero = 240 Then DdlTipoCompra.SelectedValueExist("5") : UpEstatus.Update()
CveImportacion = DdlImportaciones.SelectedValue.ToEntero
CveFlete = DdlFletes.SelectedValue.ToEntero
FleteImportacionOpcion = RblFleteImportacionOpcion.SelectedValue.ToEntero
CveConceptoContableAlmacen = DdlFleteImportacion.SelectedValue.ToEntero
If CveCompra > 0 AndAlso (CveImportacion > 0 Or CveFlete > 0) Then
Dim ObjCompras As New ClsCompras
Dim ObjConta As New ClsContabilidad(ObjCompras.IniciaTransacSQL)
Dim ObjInventario As New ClsInventarios(ObjCompras.IniciaTransacSQL)
Dim ErrorTrans As Boolean = False
Select Case CveConceptoContableAlmacen
Case 237
Select Case FleteImportacionOpcion
Case 1
If Not ObjInventario.AddFletesCompras(CveFlete, CveCompra) Then
ErrorTrans = True
End If
'''actualiza la compra para que no se surta en almacen. sino por el flete o importación
''If Not ObjCompras.UpdateEstatusAlmacen(CveCompra, 2) Then
'' ErrorTrans = True
''End If
Case 2
If Not ObjInventario.AddFleteDetalle(CveFlete, CveCompra) Then
ErrorTrans = True
End If
'actualiza la compra para que no se surta en almacen. sino por el flete o importación
If Not ObjCompras.UpdateEstatusAlmacen(CveCompra, 2, UsuarioActual.CveUsuario) Then
ErrorTrans = True
End If
End Select
Case 240
Select Case FleteImportacionOpcion
Case 1
If Not ObjCompras.AddImportacionCompra(CveImportacion, CveCompra) Then
ErrorTrans = True
End If
Case 2
If Not ObjCompras.AddImportacionDetalle(CveImportacion, CveCompra) Then
ErrorTrans = True
End If
'actualiza la compra para que no se surta en almacen. sino por el flete o importación
If Not ObjCompras.UpdateEstatusAlmacen(CveCompra, 2, UsuarioActual.CveUsuario) Then
ErrorTrans = True
End If
End Select
End Select
'Removemos los conceptos de la prepoliza
If Not ObjConta.RemovePrePolizasDetalle(CvePrePoliza, 6, CveCompra, 1) Then ErrorTrans = False 'GASTO
If Not ObjConta.RemovePrePolizasDetalle(CvePrePoliza, 68, CveCompra, 1) Then ErrorTrans = False 'ALMACEN
If Not ObjConta.RemovePrePolizasDetalle(CvePrePoliza, 49, CveCompra, 1) Then ErrorTrans = False 'AF
If Not ObjConta.RemovePrePolizasDetalle(CvePrePoliza, 205, CveCompra, 1) Then ErrorTrans = False 'PS YA RECIBIDO
If Not ObjConta.RemovePrePolizasDetalle(CvePrePoliza, 230, CveCompra, 1) Then ErrorTrans = False 'PS YA RECIBIDO
If Not ObjConta.RemovePrePolizasDetalle(CvePrePoliza, 231, CveCompra, 1) Then ErrorTrans = False 'PS YA RECIBIDO
If Not ObjConta.RemovePrePolizasDetalle(CvePrePoliza, 176, CveCompra, 1) Then ErrorTrans = False 'PS NO RECIBIDO
If Not ObjConta.RemovePrePolizasDetalle(CvePrePoliza, 228, CveCompra, 1) Then ErrorTrans = False 'PS NO RECIBIDO
If Not ObjConta.RemovePrePolizasDetalle(CvePrePoliza, 229, CveCompra, 1) Then ErrorTrans = False 'PS NO RECIBIDO
Dim ConceptoContabilizacion As Integer = CveConceptoContableAlmacen
Dim ConceptoContabilizacionME As Integer = -1
Dim ConceptoContabilizacionMEComp As Integer = -1
Dim importeMovimiento As Decimal = 0
Dim importeMN As Decimal = 0
Dim IdCtaContable As Integer = -1
Dim IdCtaContableME As Integer = -1
Dim IdCtaContableMEComp As Integer = -1
Dim tipoCambioActual As Decimal = 0
Dim Multiplicador = If(DdlTipoComprobante.SelectedValue = "NC", -1, 1)
If DdlMoneda.SelectedValue.ToString.ToEntero = 2 Then
tipoCambioActual = GlobalTipoCambio(TxtFecha.Text.ToDate).ToString.ToDecimal
tipoCambioActual = If(DivTC.Visible, TipoCambio, tipoCambioActual)
Else
tipoCambioActual = 1
End If
Select Case ConceptoContabilizacion
Case 237
ConceptoContabilizacionME = 238
ConceptoContabilizacionMEComp = 239
importeMovimiento = TmpDT.SUMD(If(ListaDocumentos IsNot Nothing AndAlso ListaDocumentos.Count > 0 AndAlso ArrAnticipos IsNot Nothing AndAlso ArrAnticipos.Count > 0 AndAlso TxtTotal.Text.ToDecimal = 0, "ImporteSinImpuestos", "Total"))
importeMN = importeMovimiento * tipoCambioActual * Multiplicador 'TIENE QUE TENER EL IMPORTEMN IGUAL AL IMPORTEMOVIMIENTO PORQUE NO TOMA EN CUENTA SI UN PRODUCTO ES TIPO SERVICIO
Case 240
ConceptoContabilizacionME = 241
ConceptoContabilizacionMEComp = 242
importeMovimiento = TmpDT.SUMD(If(ListaDocumentos IsNot Nothing AndAlso ListaDocumentos.Count > 0 AndAlso ArrAnticipos IsNot Nothing AndAlso ArrAnticipos.Count > 0 AndAlso TxtTotal.Text.ToDecimal = 0, "ImporteSinImpuestos", "Total"))
importeMN = importeMovimiento * tipoCambioActual * Multiplicador 'TIENE QUE TENER EL IMPORTEMN IGUAL AL IMPORTEMOVIMIENTO PORQUE NO TOMA EN CUENTA SI UN PRODUCTO ES TIPO SERVICIO
End Select
If ObjConta.GetRetCuenta(ConceptoContabilizacion, UsuarioActual.CveEmpresa) AndAlso ObjConta.DtResultados.Rows.Count > 0 Then
IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCtaContable").ToString.ToEntero
End If
If ObjConta.GetRetCuenta(ConceptoContabilizacionME, UsuarioActual.CveEmpresa) AndAlso ObjConta.DtResultados.Rows.Count > 0 Then
IdCtaContableME = ObjConta.DtResultados.Rows(0)("IdCtaContable").ToString.ToEntero
End If
If ObjConta.GetRetCuenta(ConceptoContabilizacionMEComp, UsuarioActual.CveEmpresa) AndAlso ObjConta.DtResultados.Rows.Count > 0 Then
IdCtaContableMEComp = ObjConta.DtResultados.Rows(0)("IdCtaContable").ToString.ToEntero
End If
Dim Concepto As String = $"{NombreProveedor} {TxtSerie.Text} - {TxtFolio.Text}"
If DdlMoneda.SelectedValue.ToEntero <> 1 Then
If ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, importeMovimiento, Concepto, ConceptoContabilizacionME, Concepto, TxtFecha.Text.ToDate, IdCtaContableME, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedor, ImporteMX:=importeMovimiento, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), TipoCambio:=tipoCambioActual) Then
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, importeMN - importeMovimiento, Concepto, ConceptoContabilizacionMEComp, Concepto, TxtFecha.Text.ToDate, IdCtaContableMEComp, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedor, ImporteMX:=importeMN - importeMovimiento, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), TipoCambio:=tipoCambioActual) Then
ErrorTrans = True
End If
Else
ErrorTrans = True
End If
Else
If importeMN <> 0 AndAlso Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, importeMN, Concepto, ConceptoContabilizacion, Concepto, TxtFecha.Text.ToDate, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedor, ImporteMX:=importeMN, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), TipoCambio:=tipoCambioActual) Then
ErrorTrans = True
End If
End If
If Not ErrorTrans Then
ObjCompras.Commit()
Else
ObjCompras.RollBack()
End If
ObjCompras.Dispose()
ObjConta.Dispose()
ObjInventario.Dispose()
End If
RegistraScript("$('#ModalFletesImportaciones').modal('hide')")
End Sub
Private Sub CargaModalFletesImportaciones()
TxtFechaModalImportacionesFletes.Text = Now.ToShortDateString
TxtDescripcionModalFletesImportacion.Text = ""
TxtPedimento.Text = ""
RblTipo.SelectedValue = "1"
RblFleteImportacionOpcion.SelectedValue = "1"
CargaCombosFletesImportaciones()
CambiaTipo()
DdlFletes.SelectedValueExist(CveFlete)
DdlImportaciones.SelectedValueExist(CveImportacion)
If FleteImportacionOpcion > 0 Then RblFleteImportacionOpcion.SelectedValue = FleteImportacionOpcion.ToString
RegistraScript("$('#ModalFletesImportaciones').modal()")
UpModalFletesImportaciones.Update()
End Sub
Protected Sub RblTipo_SelectedIndexChanged(sender As Object, e As EventArgs)
CambiaTipo()
UpModalFletesImportaciones.Update()
End Sub
Private Sub CambiaTipo()
Select Case RblTipo.SelectedValue.ToEntero
Case 1
DivVinculacion.Visible = True
DivCrear.Visible = False
Select Case DdlFleteImportacion.SelectedValue.ToEntero
Case 237
LblTitulo.Text = "Costo Indirecto"
DivFletes.Visible = True
DivImportaciones.Visible = False
Case 240
LblTitulo.Text = "Importación"
DivFletes.Visible = False
DivImportaciones.Visible = True
End Select
Case 2
DivVinculacion.Visible = False
DivCrear.Visible = True
Select Case DdlFleteImportacion.SelectedValue.ToEntero
Case 237
LblTitulo.Text = "Costo Indirecto"
DivLblFolio.Visible = True
DivPedimento.Visible = False
CargaFolio()
Case 240
LblTitulo.Text = "Importación"
DivLblFolio.Visible = False
DivPedimento.Visible = True
End Select
End Select
End Sub
Protected Sub BtnCrearFleteImportacion_Click(sender As Object, e As EventArgs)
Dim CveFlete As Integer = 0
Dim CveImportacion As Integer = 0
Select Case DdlFleteImportacion.SelectedValue.ToEntero
Case 237
Dim ObjInv As New ClsInventarios
If ObjInv.AddFlete(LblFolioModalFletes.Text, TxtDescripcionModalFletesImportacion.Text.Trim, TxtFechaModalImportacionesFletes.Text.ToDate, -1, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa) Then
CveFlete = ObjInv.CveFlete
Alert("Costo indirecto creado correctamente")
End If
ObjInv.Dispose()
Case 240
Dim ObjCompras As New ClsCompras
CveImportacion = ObjCompras.AddImportacion(TxtPedimento.Text.Trim, TxtDescripcionModalFletesImportacion.Text.Trim, CveProveedor, -1, TxtFechaModalImportacionesFletes.Text.ToDate, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa)
ObjCompras.Dispose()
If CveImportacion > 0 Then Alert("Importación creada correctamente")
End Select
If CveFlete > 0 Or CveImportacion > 0 Then
RblTipo.SelectedValue = "1"
CambiaTipo()
CargaCombosFletesImportaciones()
Select Case DdlFleteImportacion.SelectedValue.ToEntero
Case 237
DdlFletes.SelectedValueExist(CveFlete)
Case 240
DdlImportaciones.SelectedValueExist(CveImportacion)
End Select
TxtFechaModalImportacionesFletes.Text = Now.ToShortDateString
TxtDescripcionModalFletesImportacion.Text = ""
TxtPedimento.Text = ""
UpModalFletesImportaciones.Update()
End If
End Sub
Private Sub CargaCombosFletesImportaciones()
DdlFletes.Items.Clear()
DdlImportaciones.Items.Clear()
RblFleteImportacionOpcion.Items.Clear()
Dim ObjCompras As New ClsCompras
If ObjCompras.GetImportaciones(-1, -1, -1, "-1", "-1", UsuarioActual.CveEmpresa, CveEstatus:=0) Then
DdlImportaciones.DataSource = ObjCompras.DtResultados
DdlImportaciones.Items.Insert(0, New ListItem("Seleccione", "-1"))
End If
ObjCompras.Dispose()
Dim ObjInv As New ClsInventarios
If ObjInv.GetFletesRep(UsuarioActual.CveEmpresa, -1, "-1", -1, -1, -1, MinFecha, MaxFecha, TipoGasto:=1, CveEstatus:=0) Then
DdlFletes.DataSource = ObjInv.DtResultados.FiltraParametros("CveFlete > 0")
DdlFletes.Items.Insert(0, New ListItem("Seleccione", "-1"))
End If
'If ObjInv.GetFletes(UsuarioActual.CveEmpresa, OpcionInventario:=1) Then
' DdlFletes.DataSource = ObjInv.DtResultados
' DdlFletes.Items.Insert(0, New ListItem("Seleccione", "-1"))
'End If
ObjInv.Dispose()
DdlImportaciones.DataBind()
DdlFletes.DataBind()
If DdlTipoComprobante.SelectedValue = "NC" Then
RblFleteImportacionOpcion.Items.Insert(0, New ListItem("Gastos", "2"))
Else
RblFleteImportacionOpcion.Items.Insert(0, New ListItem("Productos", "1"))
RblFleteImportacionOpcion.Items.Insert(1, New ListItem("Gastos", "2"))
End If
End Sub
Private Sub LnkFletesImportaciones_Click(sender As Object, e As EventArgs) Handles LnkFletesImportaciones.Click
CargaModalFletesImportaciones()
End Sub
Protected Sub DdlFleteImportacion_SelectedIndexChanged1(sender As Object, e As EventArgs)
CambiaTipo()
UpModalFletesImportaciones.Update()
End Sub
#End Region
Private Function AjustarPrePolizaVinculacionOC(ByRef OC As ClsOC, ByRef OCBitacora As ClsOIEventos, ByRef ObjInventarios As ClsInventarios, ByRef ObjConta As ClsContabilidad, ByRef ObjAC As ClsContPAQi) As Boolean
'VARIABLES
Dim CveProveedorSucursal As Integer = -1
Dim CveProveedorContacto As Integer = -1
Dim Retorno As Boolean = True
Dim CveProveedor As Integer = -1
Dim GeneraReq = False
Dim IDPoliza As Integer = 0
Dim DtInvOC As New DataTable
Dim DtInvOCDiferencias As New DataTable 'Actualizado con diferencia
DtInvOCDiferencias.Columns.Add("CveOrdenCompra", GetType(Integer))
DtInvOCDiferencias.Columns.Add("CveOrdenCompraDetalle", GetType(Integer))
DtInvOCDiferencias.Columns.Add("Diferencia", GetType(Decimal))
DtInvOCDiferencias.Columns.Add("PUCompra", GetType(Decimal))
DtInvOCDiferencias.Columns.Add("CveMoneda", GetType(Integer))
DtInvOCDiferencias.Columns.Add("FolioOC", GetType(String))
DtInvOCDiferencias.Columns.Add("CveProveedor", GetType(Integer))
'DtInvOCDiferencias.Columns.Add("ImporteMovto", GetType(Double))
'DtInvOCDiferencias.Columns.Add("ImporteMovtoDLLS", GetType(Double))
DtInvOCDiferencias.Columns.Add("CveAlmacen", GetType(Integer))
DtInvOCDiferencias.Columns.Add("CveMovimiento", GetType(Integer))
DtInvOCDiferencias.Columns.Add("FolioAlmacen", GetType(String))
DtInvOCDiferencias.Columns.Add("TipoCambioAjuste", GetType(Double))
DtInvOCDiferencias.Columns.Add("ConceptoSalida", GetType(Integer))
DtInvOCDiferencias.Columns.Add("PS", GetType(String))
Dim dr2 As DataRow
For Each gvr As GridViewRow In GvOC1.Rows
If gvr.FCTextBox("TxtCantidad").Text.ToDecimal > 0 Then
dr2 = DTOCGV.Rows(gvr.RowIndex)
Dim diferencia As Decimal = (dr2("PU").ToString.ToDecimal - gvr.FCTextBox("TxtPU").Text.ToDecimal) * gvr.FCTextBox("TxtCantidad").Text.ToDecimal
Dim DrInvOCDiferencias As DataRow
If diferencia <> 0 Then
DrInvOCDiferencias = DtInvOCDiferencias.NewRow
DrInvOCDiferencias("CveOrdenCompra") = dr2("CveOrdenCompra").ToString.ToEntero
DrInvOCDiferencias("CveOrdenCompraDetalle") = dr2("CveOrdenCompraDetalle").ToString.ToEntero
DrInvOCDiferencias("Diferencia") = diferencia.RoundSQL()
DrInvOCDiferencias("PUCompra") = Math.Round(gvr.FCTextBox("TxtPU").Text.ToDecimal, 6)
DrInvOCDiferencias("CveMoneda") = dr2("CveMoneda").ToString.ToEntero
DrInvOCDiferencias("FolioOC") = dr2("FolioOC").ToString
DrInvOCDiferencias("CveProveedor") = dr2("CveProveedorOC").ToString.ToEntero
DrInvOCDiferencias("PS") = dr2("PS").ToString
DrInvOCDiferencias("FolioAlmacen") = dr2("FolioAlmacen").ToString
If DdlOCVinculaInv.SelectedValue.ToEntero.Contiene(205) Then
DrInvOCDiferencias("TipoCambioAjuste") = 0
DrInvOCDiferencias("CveAlmacen") = 0
DrInvOCDiferencias("CveMovimiento") = 0
DrInvOCDiferencias("ConceptoSalida") = 0
DtInvOCDiferencias.Rows.Add(DrInvOCDiferencias)
Else
If ObjInventarios.GetMovimientosOC(dr2("CveOrdenCompra").ToString.ToEntero, UsuarioActual.CveEmpresa) Then
DtInvOC = ObjInventarios.DtResultados.FiltraParametros($"CvePS > 0 AND CveOrdenCompraDetalle = {dr2("CveOrdenCompraDetalle").ToString.ToEntero}").Copy
End If
Dim drInv As DataRow = DtInvOC.FiltroPrimero("")
If drInv IsNot Nothing Then 'sino existe no hay problema, porque puede ser le producto un servicio
DrInvOCDiferencias("TipoCambioAjuste") = drInv("TipoCambioAjuste").ToString.ToDecimal
DrInvOCDiferencias("Diferencia") = ((gvr.FCTextBox("TxtPU").Text.ToDecimal * drInv("TipoCambioAjuste").ToString.ToDecimal) - drInv("PUOriginal").ToString.ToDecimal) * gvr.FCTextBox("TxtCantidad").Text.ToDecimal 'diferencia * drInv("TipoCambioAjuste").ToString.ToDecimal '
DrInvOCDiferencias("CveAlmacen") = drInv("CveAlmacen").ToString.ToEntero
DrInvOCDiferencias("CveMovimiento") = drInv("CveMovimiento").ToString.ToEntero
DrInvOCDiferencias("ConceptoSalida") = drInv("ConceptoSalida").ToString.ToEntero
DtInvOCDiferencias.Rows.Add(DrInvOCDiferencias)
End If
End If
End If
End If
Next
If DdlOCVinculaInv.SelectedValue.ToEntero.Contiene(205) Then
If DtInvOCDiferencias.Rows.Count > 0 Then
For Each DrDiferencias As DataRow In DtInvOCDiferencias.Rows
Dim CveOrdenCompra As Integer = DrDiferencias("CveOrdenCompra").ToString.ToEntero
Dim CveOCDetalle As Integer = DrDiferencias("CveOrdenCompraDetalle").ToString.ToEntero
Dim PUCompra As Decimal = DrDiferencias("PUCompra").ToString.ToDecimal
Dim DiferenciaInvOC As Decimal = DrDiferencias("Diferencia").ToString.ToDecimal
If DiferenciaInvOC.RoundSQL() <> 0 Then
If Not OC.UpdateOrdenCompraDetalleAjuste(CveOrdenCompra, CveOCDetalle, PUCompra, UsuarioActual.CveUsuario) Then
Retorno = False
Exit For
End If
End If
Next
End If
Else
'PREPOLIZA DE AJUSTE ALMACEN POR ADELANTADO
If DtInvOCDiferencias.Rows.Count > 0 Then
'VARIABLES
Dim CveOrdenCompra As Integer = -1
Dim DiferenciaInvOC = 0.0D
Dim CveMovimientoAlmacen = -1
Dim CveOCDetalle = -1
Dim CveAlmacen = -1
Dim IdCtaContableAlmacen As Integer = -1
Dim CveCuentaAlmacen As Integer = -1
Dim IdCtaContableRecepcionOC = -1
Dim IdCtaContableRecepcionOCME = -1
Dim IdCtaContableRecepcionOCComplementaria = -1
Dim IdCtaContableRecepcionOCER = -1
Dim IdCtaContableRecepcionOCERME = -1
Dim IdCtaContableRecepcionOCERComplementaria = -1
Dim Fecha As Date = TxtFecha.Text.ToDate
Dim CveProveedorInvOC As Integer = -1
Dim ProveedorNombre As String = ""
Dim SerieFolio As String = ""
Dim CvePrePoliza As Integer = -1
Dim ConceptoSalida = -1
Dim TCInvOC = 0.0D
Dim ImporteME = 0.0D
Dim ImporteMEComp = 0.0D
Dim SumatoriaMN = 0.0D
Dim SumatoriaME = 0.0D
Dim SumatoriaMEComp = 0.0D
Dim PUCompra = 0.0D
Dim CveMoneda As Integer = 1
Dim PS As String = ""
If ObjConta.GetRetCuenta(176, UsuarioActual.CveEmpresa) AndAlso ObjConta.DtResultados.Rows.Count > 0 Then
IdCtaContableRecepcionOC = ObjConta.DtResultados.FiltroPrimeroValor("IdCtaContable").ToEntero
End If
If ObjConta.GetRetCuenta(228, UsuarioActual.CveEmpresa) AndAlso ObjConta.DtResultados.Rows.Count > 0 Then
IdCtaContableRecepcionOCME = ObjConta.DtResultados.FiltroPrimeroValor("IdCtaContable").ToEntero
End If
If ObjConta.GetRetCuenta(229, UsuarioActual.CveEmpresa) AndAlso ObjConta.DtResultados.Rows.Count > 0 Then
IdCtaContableRecepcionOCComplementaria = ObjConta.DtResultados.FiltroPrimeroValor("IdCtaContable").ToEntero
End If
If ObjConta.GetRetCuenta(177, UsuarioActual.CveEmpresa) AndAlso ObjConta.DtResultados.Rows.Count > 0 Then
IdCtaContableRecepcionOCER = ObjConta.DtResultados.FiltroPrimeroValor("IdCtaContable").ToEntero
End If
If ObjConta.GetRetCuenta(232, UsuarioActual.CveEmpresa) AndAlso ObjConta.DtResultados.Rows.Count > 0 Then
IdCtaContableRecepcionOCERME = ObjConta.DtResultados.FiltroPrimeroValor("IdCtaContable").ToEntero
End If
If ObjConta.GetRetCuenta(233, UsuarioActual.CveEmpresa) AndAlso ObjConta.DtResultados.Rows.Count > 0 Then
IdCtaContableRecepcionOCERComplementaria = ObjConta.DtResultados.FiltroPrimeroValor("IdCtaContable").ToEntero
End If
'AJUSTES EN PREPOLIZA - SALIDA CONTABLE (CON SALIDA DE VENTA O SIN SALIDA)
For Each DrDiferencias As DataRow In DtInvOCDiferencias.FiltraParametros("ConceptoSalida IN (0,1)").Rows
CveOrdenCompra = DrDiferencias("CveOrdenCompra").ToString.ToEntero
CveOCDetalle = DrDiferencias("CveOrdenCompraDetalle").ToString.ToEntero
CveMoneda = DrDiferencias("CveMoneda").ToString.ToEntero
DiferenciaInvOC = DrDiferencias("Diferencia").ToString.ToDecimal.RoundSQL()
PUCompra = DrDiferencias("PUCompra").ToString.ToDecimal
PS = DrDiferencias("PS").ToString
Fecha = TxtFecha.Text.ToDate
SerieFolio = $"OC: {DrDiferencias("FolioOC").ToString}"
CveProveedor = DrDiferencias("CveProveedor").ToString.ToEntero
ProveedorNombre = GlobalDTCompProveedores(UsuarioActual.CveEmpresa).FiltroPrimeroValor("RazonSocial", $"CveProveedor = {CveProveedor}").ToString
Dim ConceptoPartida As String = String.Format("{0} OC: {1} Inv: {2}", ProveedorNombre, DrDiferencias("FolioOC"), DrDiferencias("FolioAlmacen"))
ConceptoSalida = DrDiferencias("ConceptoSalida").ToString.ToEntero
CveAlmacen = DrDiferencias("CveAlmacen").ToString.ToEntero
CveMovimientoAlmacen = DrDiferencias("CveMovimiento").ToString.ToEntero
TCInvOC = DrDiferencias("TipoCambioAjuste").ToString.ToDecimal
IdCtaContableAlmacen = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCtaContable", $"CveAlmacen = {DrDiferencias("CveAlmacen").ToString.ToEntero}").ToEntero
Dim CveClasificacionCostoOC = TmpDT.FiltroPrimeroValor("CveClasificacion", "ISNULL(TipoAF, 0) <> 2 And ISNULL(CveAlmacen, 0) = 0 And ISNULL(AplicaCostoIndirecto, 0) <> 1 And ISNULL(CveTipoPS, 0) = 2").ToEntero
Dim IdCtaContable69 As Integer = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaCostos", $"CveClasificacion = {CveClasificacionCostoOC}").ToString.ToEntero
Dim CveSubProyecto As Integer = TmpDT.MAX("CveSubProyecto").ToEntero
If DiferenciaInvOC.RoundSQL() <> 0 Then
If CveSubProyecto <= 0 Then
Alert("Debe de asignar un sub proyecto o centro de costos.", TipoMensaje.MsgAdvertencia)
Retorno = False
End If
CvePrePoliza = ObjConta.AddPrePolizas("Compras/OC-(OCAlmacen)", 74, DiferenciaInvOC, DiferenciaInvOC, 1, Fecha, ConceptoPartida, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa)
If CvePrePoliza > 0 Then
If CveMoneda = 2 Then
ImporteME = (DiferenciaInvOC / TCInvOC).RoundAD()
ImporteMEComp = ((ImporteME * TCInvOC) - ImporteME).RoundAD()
Dim DifImporte As Decimal = DiferenciaInvOC - (ImporteME + ImporteMEComp)
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, -DiferenciaInvOC, SerieFolio, 177, ConceptoPartida, Fecha, IdCtaContableRecepcionOCER, -1, CveProveedor:=CveProveedor, CveMovimientoAlmacen:=CveMovimientoAlmacen, CveOC:=CveOrdenCompra, ImporteMX:=-DiferenciaInvOC, CveOCDetalle:=CveOCDetalle, CveSubProyecto:=CveSubProyecto) Then
Retorno = False
Exit For
End If
If ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, ImporteME, SerieFolio, 228, ConceptoPartida, Fecha, IdCtaContableRecepcionOCME, -1, CveProveedor:=CveProveedor, CveMovimientoAlmacen:=CveMovimientoAlmacen, CveOC:=CveOrdenCompra, ImporteMX:=ImporteME, ImporteME:=ImporteME, TipoCambio:=TCInvOC, CveOCDetalle:=CveOCDetalle) Then
If ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, ImporteMEComp, SerieFolio, 229, ConceptoPartida, Fecha, IdCtaContableRecepcionOCComplementaria, -1, CveProveedor:=CveProveedor, CveMovimientoAlmacen:=CveMovimientoAlmacen, CveOC:=CveOrdenCompra, ImporteMX:=ImporteMEComp, ImporteME:=ImporteME, TipoCambio:=TCInvOC, CveOCDetalle:=CveOCDetalle) Then
If DifImporte <> 0 AndAlso Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, DifImporte, SerieFolio, 69, ConceptoPartida, Fecha, IdCtaContable69, -1, CveProveedor:=CveProveedor, CveMovimientoAlmacen:=CveMovimientoAlmacen, CveOC:=CveOrdenCompra, ImporteMX:=DifImporte, ImporteME:=DifImporte, TipoCambio:=TCInvOC, CveOCDetalle:=CveOCDetalle, CveClasificacion:=CveClasificacionCostoOC, CveSubProyecto:=CveSubProyecto) Then
Retorno = False
Exit For
End If
Else
Retorno = False
Exit For
End If
Else
Retorno = False
Exit For
End If
Else
'2018.11.24 se cambia concepto 177, de cargo a abono negativo., petición MALL
If ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, -DiferenciaInvOC, SerieFolio, If(ConceptoSalida = 0, 177, 177), ConceptoPartida, Fecha, IdCtaContableRecepcionOCER, -1, CveProveedor:=CveProveedor, CveMovimientoAlmacen:=CveMovimientoAlmacen, CveOC:=CveOrdenCompra, ImporteMX:=-DiferenciaInvOC, CveOCDetalle:=CveOCDetalle, CveSubProyecto:=CveSubProyecto) Then
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, DiferenciaInvOC, SerieFolio, 176, ConceptoPartida, Fecha, IdCtaContableRecepcionOC, -1, CveProveedor:=CveProveedor, CveMovimientoAlmacen:=CveMovimientoAlmacen, CveOC:=CveOrdenCompra, ImporteMX:=DiferenciaInvOC, CveOCDetalle:=CveOCDetalle) Then
Retorno = False
Exit For
End If
Else
Retorno = False
Exit For
End If
End If
If Not OC.UpdateOrdenCompraDetalleAjuste(CveOrdenCompra, CveOCDetalle, PUCompra, UsuarioActual.CveUsuario) Then
Retorno = False
Exit For
End If
If Retorno Then
If Not OCBitacora.AddEventoBitacora(String.Format("Se registró una póliza de ajuste por cambio de precio en producto: {0}", PS), "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveOC:=CveOrdenCompra) Then
Retorno = False
End If
End If
If UsuarioActual.Empresa.Funcionalidad(200) = "1" AndAlso ObjAC IsNot Nothing Then
If Not ObjConta.ContabilizarPrePoliza(CvePrePoliza, UsuarioActual.CveUsuario, UsuarioActual.Empresa, ObjConta:=ObjAC) Then
Retorno = False
End If
End If
End If
End If
Next
End If
End If
Return Retorno
End Function
#Region "A G R E G A R - P R O D U C T O S S E R V I C I O S"
Private Sub CargaDatosAgregarPS()
DdlClasificacionPS.Items.Clear()
If UsuarioActual.Empresa.UsaAC Then
DdlClasificacionPS.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa, UsoClasificacion:=If(UsuarioActual.Empresa.UsaContabilidad, -1, -1)).FiltraParametros(" Codigo = '' OR Codigo IS NULL ", Orderby:="Clasificacion")
Else
DdlClasificacionPS.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa, UsoClasificacion:=If(UsuarioActual.Empresa.UsaContabilidad, -1, -1)).FiltraParametros("", Orderby:="Clasificacion")
End If
DdlClasificacionPS.DataBind()
DdlClasificacionPS.Items.Insert(0, New ListItem("Seleccione", "-1"))
DdlUnidadMedida.Items.Clear()
DdlUnidadMedida.DataSource = GlobalDTUnidadesMedida(UsuarioActual.CveEmpresa)
DdlUnidadMedida.DataBind()
End Sub
Protected Sub BtnAgregarPSNuevo_Click(sender As Object, e As EventArgs)
Dim PS As New Modelos.MProductoServicio()
PS.Codigo = TxtCodigoPS.Text
PS.PS = TxtPS.Text
PS.CveUnidadMedida = DdlUnidadMedida.SelectedValue.ToEntero()
PS.CveClasificacion = DdlClasificacionPS.SelectedValue.ToEntero()
PS.CveTipoPS = DdlTipoPS.SelectedValue.ToEntero()
PS.AplicaParaVenta = True
PS.CveUsuario = UsuarioActual.CveUsuario
PS.CveEmpresa = UsuarioActual.CveEmpresa
Dim ObjPS As New ClsProductosServicios
If ObjPS.AddPSSimplificado(PS) > 0 Then
Alert("El P/S fue agregado correctamente.")
GeneraGlobalDT(Nothing)
End If
ObjPS.Dispose()
TxtPS.Text = ""
TxtCodigoPS.Text = ""
DdlUnidadMedida.SelectedValueExist(-1)
DdlClasificacionPS.SelectedValueExist(-1)
DdlTipoPS.SelectedValueExist(-1)
UpAgregarPS.Update()
RegistraScript("$('#DivAgregarPS').modal('hide');")
End Sub
#End Region
#Region "TIPO DE COMPRA"
Protected Sub DdlTipoCompra_SelectedIndexChanged(sender As Object, e As EventArgs)
If DdlTipoCompra.SelectedValue.ToEntero.Contiene(9, 10) Then 'Al seleccionar apoyo logístico se cargan los amancenes de devoculcion proveedor para dar entrada
CargaGvInv()
End If
End Sub
#End Region
Protected Sub BtnFacturaNC_Click(sender As Object, e As EventArgs)
If ChkNCInvNC.Checked Then
CargaNCINV(ShowAllPendientes:=False)
TabModoNC.ActiveTabIndex = 1
TabModoNC_ActiveTabChanged(TabModoNC, EventArgs.Empty)
UpFacturaNC.Update()
Else
RegistraScript("$('#FacturaNC').modal('hide');", "FacturaNC")
End If
End Sub
#Region "ES NO DEDUCIBLE"
Protected Sub ChkEsNoDeducible_CheckedChanged1(sender As Object, e As EventArgs)
If ChkEsNoDeducible.Checked Then
EsNoDeducible = True
dvNoDeducible.Visible = True
GvPS.Columns(11).Visible = True
UpEsNoDeduciblePS.Visible = True
Else
EsNoDeducible = False
dvNoDeducible.Visible = False
GvPS.Columns(11).Visible = False
UpEsNoDeduciblePS.Visible = False
End If
'DivEsNoDeducible.Visible = False
'For Each Dr As DataRow In TmpDT.Rows
' Dim Total As Double = Dr("IVA").ToString.ToDouble - (Dr("RetIVA").ToString.ToDouble + Dr("RetISR").ToString.ToDouble) + Dr("IEPSPS").ToString.ToDouble + Dr("IEPSPSIVA").ToString.ToDouble
' Dr("Total") = Dr("Total").ToString.ToDouble + Total
' Dr("PU") = Dr("Total").ToString.ToDouble / Dr("Cantidad").ToString.ToDouble
' Dr("IVA") = 0
' Dr("IVAPorcentaje") = 0
' Dr("RetIVA") = 0
' Dr("RetIVAPorcentaje") = 0
' Dr("RetISR") = 0
' Dr("RetISRPorcentaje") = 0
' Dr("IEPSPS") = 0
' Dr("IEPSPSPorcentaje") = 0
' Dr("IEPSPSIVA") = 0
' Dr("IEPSPSIVAPorcentaje") = 0
'Next
'TmpDT.AcceptChanges()
AddPS2(EsNoDeducible:=EsNoDeducible)
UpPS.Update()
End Sub
#End Region
Public Sub LnkDesVincularComplemento_Click(sender As Object, e As EventArgs)
Dim GvRow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow)
Dim CveFacturaComplemento As Integer = GvRow.DataKey("CveFactura").ToEntero
Dim ObjCompra As New ClsCompras
If ObjCompra.RemoveComplementoPagoDesVincular(CveFacturaComplemento, UsuarioActual.CveEmpresa) Then
RegistraScript("$('#ModalComplementoPagos').modal('hide');")
Alert("Complemento des vinculado correctamente.")
End If
ObjCompra.Dispose()
End Sub
Protected Sub LnkCompleplementos_Click(sender As Object, e As EventArgs)
'ModalComplementoPagos
CargaComplementosPago()
RegistraScript("$('#ModalComplementoPagos').modal('show');")
End Sub
Protected Sub ChkEsNoDeduciblePS_CheckedChanged(sender As Object, e As EventArgs)
Dim Chk As CheckBox = CType(sender, CheckBox)
Dim gvr As GridViewRow = CType(Chk.BindingContainer, GridViewRow)
For Each drt As DataRow In TmpDT.Select("Consec = " & gvr.RowIndex + 1)
drt("NoDeducible") = Chk.Checked
Next
TmpDT.AcceptChanges()
AddPS2(EsNoDeducible:=EsNoDeducible)
End Sub
Protected Sub LnkUpdateFechaPago_Click(sender As Object, e As EventArgs)
Dim ObjComp As New ClsCompras
Dim FechaPagoAnterior As String = ""
If ObjComp.GetCompras(CveCompra, "-1", "-1", -1, -1, UsuarioActual.CveEmpresa) Then
If ObjComp.DtResultados.Rows.Count > 0 Then
FechaPagoAnterior = ObjComp.DtResultados.Rows(0)("FechaVencimiento").ToString.ToDate.ToShortDateString
End If
End If
If FechaPagoAnterior = TxtFechaPago.Text Then
Alert("La fecha de pago seleccionada es igual que la anterior.", TipoMensaje.MsgAdvertencia)
ObjComp.Dispose()
Exit Sub
End If
If ObjComp.UpdateFechaVencimientoCompra(CveCompra, TxtFechaPago.Text.ToDate, UsuarioActual.CveEmpresa) Then
Alert("Fecha de pago actualizada correctamente.")
End If
ObjComp.Dispose()
End Sub
Protected Sub btnpruebas_Click(sender As Object, e As EventArgs)
Dim GuardaNoDeducibles As Boolean = False
If ChkEsNoDeducible.Checked Then
For Each Row As DataRow In TmpDT.Rows
If Row("NoDeducible").ToString().ToUpper().Contiene("TRUE", "1") Then
GuardaNoDeducibles = True
End If
Next
If GuardaNoDeducibles = False Then
Alert("Si la compra es No Deducible, mínimo se debe registrar un producto No Deducible", TipoMensaje.MsgAdvertencia)
Exit Sub
Else
Alert("todo bien!", TipoMensaje.MsgInformacion)
End If
End If
End Sub
#Region "PAGAR CON DIFERENTE MONEDA"
Protected Sub ChkPagarConPesos_CheckedChanged(sender As Object, e As EventArgs)
CargaAnticipos(CveProveedor)
UpAnticipos.Update()
End Sub
Protected Sub ChkPagarConDolares_CheckedChanged(sender As Object, e As EventArgs)
CargaAnticipos(CveProveedor)
UpAnticipos.Update()
End Sub
#End Region
Protected Sub LnkActivaIva6_Click(sender As Object, e As EventArgs)
TrRetIVA.Visible = True
TdRetIVAConcepto.Visible = True
TotalOriginal = TxtTotal.Text.ToDecimal
For Each dRow As DataRow In TmpDT.Rows
If dRow("CvePS").ToString.ToEntero <= 0 Then
Alert("Debe de asignar producto a todas las partidas", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
Next
If RetencionIVA = 0 And IVAOriginal > 0 Then
For Each dRow As DataRow In TmpDT.Rows
If dRow("CveTipoPS").ToString.ToEntero = 1 Then
'Dim InternalIVA As Decimal = 0D
Dim InternalRETIVA As Decimal = 0D
'InternalIVA = dRow("Cantidad").ToString.ToDecimal * dRow("PU").ToString.ToDecimal * 0.1D
InternalRETIVA = dRow("Cantidad").ToString.ToDecimal * dRow("PU").ToString.ToDecimal * 0.06D
'dRow("IVA") = InternalIVA
'dRow("IVAPorcentaje") = 0.1D
dRow("RetIVA") = InternalRETIVA
' dRow("IVAPorcentaje") = 0.1D
End If
Next
End If
TmpDT.AcceptChanges()
GvPS.DataSource = TmpDT
GvPS.DataBind()
DdlRetIVAConcepto.SelectedValueExist("5")
LblRetIVA.Text = "6.0%"
RetencionIVA = TmpDT.SUMD("RetIVA")
TxtRetIVA.Text = RetencionIVA.ToString("###,###,###.00")
'TrasladoIVA = TmpDT.SUMD("IVA")
'TxtIVA.Text = TrasladoIVA.ToString("###,###,###.00")
'Total = Total - RetencionIVA
TxtTotal.Text = (TxtTotal.Text.ToDecimal - RetencionIVA).ToString("###,###,###.00")
UpPS.Update()
'ValidacionesTotalesXml()
ValidaTotalesGuardar()
End Sub
Public Sub LblProveedor_OnClick(sender As Object, e As EventArgs) Handles LblProveedor.Click
If CveTipoConcepto = 1 Then
LblProveedor.Text = "Acreedor:"
CveTipoConcepto = 2
Else
LblProveedor.Text = "Proveedor:"
CveTipoConcepto = 1
End If
End Sub
Protected Sub RblGastosVincularCrear_Click(sender As Object, e As EventArgs)
Dim MostrarGastosServicios As Boolean = RblGastosVincularCrear.SelectedValue = "1"
DivGastosyServicios.Visible = MostrarGastosServicios
DivGastosyServiciosFooter.Visible = MostrarGastosServicios
If MostrarGastosServicios Then
CargaIndirectosServicios()
End If
DivVincularCrear.Visible = Not MostrarGastosServicios
DivVincularCrearFooter.Visible = Not MostrarGastosServicios
End Sub
Private Function VerificarProductosCompraConOC() As Boolean
Dim ProductosNoValidados As New StringBuilder()
Dim DtCompras As New DataTable()
DtCompras.Columns.Add("Cantidad", GetType(String))
DtCompras.Columns.Add("UM", GetType(String))
DtCompras.Columns.Add("PS", GetType(String))
DtCompras.Columns.Add("SATClaveProductoServicio", GetType(String))
DtCompras.Columns.Add("PU", GetType(String))
DtCompras.Columns.Add("Total", GetType(String))
For Each GvOC2Row As GridViewRow In GvOC2.Rows
Dim Cantidad As String = GvOC2Row.DataKey("Cantidad")
Dim UM As String = GvOC2Row.DataKey("UM")
Dim PS As String = GvOC2Row.DataKey("PS")
Dim SATClaveProductoServicio As String = GvOC2Row.DataKey("SATClaveProductoServicio")
Dim PU As String = (GvOC2Row.DataKey("Total").ToEntero / GvOC2Row.DataKey("Cantidad").ToEntero).ToString
Dim Total As String = GvOC2Row.DataKey("Total")
DtCompras.Rows.Add(Cantidad, UM, PS, SATClaveProductoServicio, PU, Total)
Next
For Each GvOCRow As GridViewRow In GvOC1.Rows
Dim TipoPS As String = GvOCRow.DataKey("CveTipoPS")
If TipoPS = "2" Then
Dim ProductoAisloadoString As String = ""
If CveFactura > 0 Then
ProductoAisloadoString = Regex.Replace(GvOCRow.DataKey("PS"), "^\d*\s-\s", "")
Else
ProductoAisloadoString = GvOCRow.DataKey("PS")
End If
Dim PSOC As String = ProductoAisloadoString
Dim CantidadOC As String = GvOCRow.DataKey("CantidadF")
Dim PrecioUnitarioOC As String = GvOCRow.DataKey("Importe")
Dim Filtro As String = String.Format("Cantidad = {0} AND PS = '{1}' AND PU = {2}", CantidadOC, PSOC, PrecioUnitarioOC)
Dim RenglonCompras As DataRow = DtCompras.FiltroPrimero(Filtro)
If RenglonCompras Is Nothing Then
Dim FiltroCantidad As String = String.Format("Cantidad = {0} AND PS = '{1}'", CantidadOC, PSOC)
Dim RenglonFiltroCantidad As DataRow = DtCompras.FiltroPrimero(FiltroCantidad)
If RenglonFiltroCantidad Is Nothing Then
ProductosNoValidados.AppendFormat("La Cantidad del producto '{0}' no coincide<br/>", PSOC)
End If
Dim FiltroPU As String = String.Format("PS = '{0}' AND PU = {1}", PSOC, PrecioUnitarioOC)
Dim RenglonFiltroPU As DataRow = DtCompras.FiltroPrimero(FiltroPU)
If RenglonFiltroPU Is Nothing Then
ProductosNoValidados.AppendFormat("El Precio Unitario del producto '{0}' no coincide<br/>", PSOC)
End If
ProductosNoValidados.Append("<br/>")
End If
End If
Next
If ProductosNoValidados.ToString().Length() > 0 Then
Dim AlertProductosNoValidados As String = String.Format("Los siguientes productos no se encuentran en la factura: <br/><br/>{0}", ProductosNoValidados.ToString)
Alert(AlertProductosNoValidados, TipoMensaje.MsgAdvertencia)
Return False
End If
Return True
End Function
Protected Sub TabModoNC_ActiveTabChanged(sender As Object, e As EventArgs)
Select Case TabModoNC.ActiveTabIndex
Case 0
BtnFacturaNC.Visible = True
BtnNCInvAlmacen.Visible = False
TabNCAlmacen.Enabled = False
Case 1
BtnFacturaNC.Visible = False
BtnNCInvAlmacen.Visible = True
TabNCAlmacen.Enabled = True
End Select
UpFooterFacturaNC.Update()
End Sub
Protected Sub LnkContratos_Click(sender As Object, e As EventArgs)
End Sub
Protected Sub DdlContratosObra_SelectedIndexChanged(sender As Object, e As EventArgs)
End Sub
#Region "Contratos Obra"
Protected Sub LnkAcontratos_Click(sender As Object, e As EventArgs)
DdlContratosObra.Items.Clear()
DdlContratosObra.DataSource = GlobalDTContratos(UsuarioActual.CveEmpresa).FiltraParametros(String.Format($"CveContratoTipo in (30,31) AND CveEmpresa = {UsuarioActual.CveEmpresa}"))
DdlContratosObra.DataBind()
DdlContratosObra.Items.Insert(0, New ListItem("Seleccione", "-1"))
DdlTipoGastoContrato.Items.Clear()
DdlTipoGastoContrato.DataSource = GlobalDTTiposGastos(UsuarioActual.CveEmpresa)
DdlTipoGastoContrato.DataBind()
DdlTipoGasto.Items.Insert(0, New ListItem("Seleccione", "-1"))
RegistraScript("$('#DivmodalContrato').modal('show')")
UpModalContrato.Update()
End Sub
Protected Sub DdlContratosCompras_SelectedIndexChanged(sender As Object, e As EventArgs)
If DdlContratosObra.SelectedValue.ToEntero > 0 Then
Dim ObjContratos As New ClsContratos()
If ObjContratos.GetContratosObraCompras(DdlContratosObra.SelectedValue.ToEntero, UsuarioActual.CveEmpresa) Then
If ObjContratos.DtResultados.Rows.Count > 0 Then
GvContratosControl.DataSource = ObjContratos.DtResultados
BtnAplicarContrato.Visible = True
divBusqueda.Visible = True
ChkContinualAgregandoControl.Visible = True
ChkContinualAgregandoControl.Checked = True
Else
GvContratosControl.DataSource = Nothing
BtnAplicarContrato.Visible = False
divBusqueda.Visible = False
ChkContinualAgregandoControl.Visible = False
ChkContinualAgregandoControl.Checked = False
End If
End If
ObjContratos.Dispose()
GvContratosControl.DataBind()
UpModalContrato.Update()
End If
End Sub
Protected Sub BtnAplicarContrato_Click(sender As Object, e As EventArgs)
Dim PorcentajeIVA As Decimal = TmpDT.MAX("IVAPorcentaje").ToDecimal
TmpDT.Rows.Clear()
Dim CveTipoGastoObra As Integer = DdlTipoGastoContrato.SelectedValue.ToEntero
Dim TipoGasto As String = DdlTipoGastoContrato.SelectedItem.Text
For Each GvRow As GridViewRow In GvContratosControl.Rows
Dim CveContratoDetalle As Integer = GvRow.DataKey("CveContratoDetalle").ToEntero
Dim Cantidad As Decimal = GvRow.FCTextBox("TxtCantidad").Text.ToDecimal
Dim CvePS As Integer = GvRow.DataKey("CvePS").ToEntero
Dim PS As String = GvRow.DataKey("PS")
Dim TotalPS As Decimal = GvRow.FCTextBox("TxtImporte").Text.ToDecimal
Dim PU As Decimal
If Cantidad > 0 Then PU = TotalPS / Cantidad
Dim CveUnidadMedida As Integer = GvRow.DataKey("CveUnidadMedida").ToEntero
Dim UMAbreviatura As String = GvRow.DataKey("Abreviatura").ToString
Dim SubProyecto As String = GvRow.DataKey("SubProyecto")
Dim CveSubProyecto As Integer = GvRow.DataKey("CveSubProyecto").ToEntero
Dim Proyecto As String = GvRow.DataKey("Proyecto")
Dim CveProyecto As Integer = GvRow.DataKey("CveProyecto").ToEntero
Dim RetISR As Decimal = GvRow.DataKey("RetISR").ToString.ToDecimal
Dim RetIVA As Decimal = GvRow.DataKey("RetIVA").ToString.ToDecimal
Dim IvaPS As Decimal = GvRow.DataKey("IVA").ToString.ToDecimal
If IvaPS = -1 Then
IvaPS = PorcentajeIVA
End If
IvaPS = IvaPS * TotalPS
Dim CveClasificacion As Integer = GvRow.DataKey("CveClasificacion").ToString.ToEntero
Dim Clasificacion As String = GvRow.DataKey("Clasificacion")
Dim IEPSPS As Decimal = GvRow.DataKey("IEPSPorcentaje").ToString.ToDecimal
Dim IEPSPSIVA As Decimal = If(GvRow.DataKey("IEPSGrabaIVA").ToString = "True", IEPSPS, 0)
If Cantidad > 0 Then
AddPS(Cantidad, CveUnidadMedida, UMAbreviatura, CveClasificacion, Clasificacion, CvePS, PS, 1, CveSubProyecto.ToString, SubProyecto, Proyecto, CveProyecto.ToString, "", PU, PU * Cantidad, PorcentajeIVA, RetIVA, RetISR, IEPSPS, IEPSPSIVA, 0, PorcentajeIVA:=PorcentajeIVA, CveContratoDetalle:=CveContratoDetalle,
CveTipoGasto:=CveTipoGastoObra, TipoGasto:=TipoGasto)
'ContratoObraAplciado = True
End If
Next
AddPS2()
If Not ChkContinualAgregandoControl.Checked Then
RegistraScript("$('#DivmodalContrato').modal('hide')")
End If
End Sub
Private Function ValidarPSContrato(DtPS As DataTable) As String
Dim Retorno As String = ""
Dim objContratos As New ClsContratos
Dim TempPS As String = JsonConvert.SerializeObject(DtPS).ToString
Dim MensajeProducto As String = ""
Dim MensajeCantidad As String = ""
Dim MensajeImporte As String = ""
If objContratos.ValidaPSContrato(TempPS) Then
If objContratos.DtResultados.Rows.Count > 0 Then
MensajeProducto = "Los siguientes productos no pertenece al contrato seleccionado: "
MensajeCantidad = "Los siguientes productos sobrepasan la cantidad faltante del contrato seleccionado: "
MensajeImporte = "Los siguientes productos sobrepasan los importes faltantes del contrato seleccionado: "
For Each dr As DataRow In objContratos.DtResultados.Rows
If dr("ProductoNoContratado").ToString.ToEntero = 1 Then
MensajeProducto += String.Format("<br/> {0}", dr("PS"))
ElseIf dr("CantidadSobrePasada").ToString.ToEntero = 1 Then
MensajeCantidad += String.Format("<br/> {0} - Cantidad maxima: {1}", dr("PS"), dr("FaltanteCantidad"))
ElseIf dr("ImporteSobrePasado").ToString.ToEntero = 1 Then
MensajeImporte += String.Format("<br/> {0} - Importe maximo: {1}", dr("PS"), dr("FaltanteImporte"))
End If
Next
End If
End If
objContratos.Dispose()
If MensajeProducto.Length > 64 Then
Retorno = MensajeProducto
ElseIf MensajeCantidad.Length > 84 Then
Retorno = MensajeCantidad
ElseIf MensajeImporte.Length > 86 Then
Retorno = MensajeImporte
Else
Retorno = ""
End If
Return Retorno
End Function
Private Function GetPSContratoDetalle(CveContrato As Integer, DtPS As DataTable) As DataTable
Dim ObjContratos As New ClsContratos
Dim DtpsTemp As DataTable = Nothing
If DtPS.MAX("CveSubProyecto", "CveSubProyecto IS NOT NULL").ToEntero > 0 AndAlso DtPS.MAX("CvePS", "CvePS IS NOT NULL").ToEntero > 0 Then
Dim TempPS As String = JsonConvert.SerializeObject(DtPS).ToString
If ObjContratos.GetPSContratoDetalle(CveContrato, TempPS) Then
DtpsTemp = ObjContratos.DtResultados
End If
ObjContratos.Dispose()
End If
Return DtpsTemp
End Function
#End Region
Protected Sub ChkMostrarTodos_CheckedChanged(sender As Object, e As EventArgs)
CargaNCINV(ShowAllPendientes:=True)
UpFacturaNC.Update()
UpMostrarTodos.Update()
End Sub
Private Sub ChkAliasFlexible_CheckedChanged(sender As Object, e As EventArgs) Handles ChkAliasFlexible.CheckedChanged
TxtPSAlias.Enabled = ChkAliasFlexible.Checked
End Sub
Protected Sub LnkActualziarFechadecompra_Click(sender As Object, e As EventArgs)
Dim ProcesoError As Boolean = True
If FechaCompraOriginal <> TxtFecha.Text.ToDate Then
Dim ObjCompra As New ClsCompras
ObjCompra.IniciaTransacSQL()
Dim ObjEventos As New ClsOIEventos(ObjCompra.IniciaTransacSQL())
If ObjEventos.AddEventoBitacora($"Cambio de Fecha de compra de { FechaCompraOriginal.ToString("dd/MM/yyyy")} a {TxtFecha.Text}", "", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCompra:=CveCompra) Then
ProcesoError = False
Else
ProcesoError = True
End If
If ProcesoError = False And ObjCompra.UpdateFechaCompra(CveCompra, TxtFecha.Text.ToDate, UsuarioActual.CveEmpresa) Then
ProcesoError = False
Else
ProcesoError = True
End If
If Not ProcesoError Then
ObjCompra.Commit()
FechaCompraOriginal = TxtFecha.Text.ToDate
Alert("Fecha Actualizada Correctamente.")
Else
ObjCompra.RollBack()
End If
ObjCompra.Dispose()
If Not ProcesoError Then
CargaEventoBitacora()
UPEventoBitacora.Update()
End If
End If
End Sub
Private Function ValidaSeleccionAnticipo() As Boolean
Dim Respuesta As Boolean = True
'If UsuarioActual.CveEmpresa.Contiene(13, 83) Then
' If GVAnticipos.Rows.Count > 0 Then
' For Each GVRow As GridViewRow In GVAnticipos.Rows
' If GVRow.FCCheckBox("Chk").Checked AndAlso GVRow.FCTextBox("TxtAnticipo").Text.ToDecimal > 0 Then
' Respuesta = True
' Exit For
' Else
' Respuesta = False
' End If
' Next
' Else
' Respuesta = True
' End If
'Else
' Respuesta = True
'End If
Return Respuesta
End Function
Private Sub NCSeleccionFacturasRelacionadas(UUIDSListRelacioandos As List(Of String))
If UUIDSListRelacioandos.Count > 0 Then
Dim SaldoNota As Decimal = TxtTotal.Text.ToDecimal
Dim SaldoNotaPorAplicar As Decimal = SaldoNota
Dim CountAplicacion As Integer = 0
Dim sbNoencontrados As New StringBuilder
For Each UUID As String In UUIDSListRelacioandos
UUID = UUID.ToUpper
Dim UUIDEncontrado As Boolean = False
For Each GvRow As GridViewRow In GvFacturaNC.Rows
Dim UUIDGv As String = GvRow.DataKey("UUID").Trim.ToUpper
If UUID.Trim.ToUpper = UUIDGv Then
UUIDEncontrado = True
Exit For
End If
Next
If Not UUIDEncontrado Then sbNoencontrados.Append($"{UUID}, <br/>")
Next
Dim TeminarAmortizacion As Boolean = False
For Each UUID As String In UUIDSListRelacioandos
For Each GvRow As GridViewRow In GvFacturaNC.Rows
If UUID.Trim.ToUpper = GvRow.DataKey("UUID").Trim.ToUpper Then
Dim SaldoFactura As Decimal = GvRow.DataKey("Saldo").ToDecimal
If SaldoFactura <= SaldoNotaPorAplicar Then
SaldoNotaPorAplicar = SaldoNotaPorAplicar - SaldoFactura
GvRow.FCTextBox("TxtImporte").Text = SaldoFactura.FormatoNumero
GvRow.FCCheckBox("ChkFacturaNC").Checked = True
Else
If SaldoFactura >= SaldoNotaPorAplicar Then
GvRow.FCTextBox("TxtImporte").Text = SaldoNotaPorAplicar.FormatoNumero
GvRow.FCCheckBox("ChkFacturaNC").Checked = True
SaldoNotaPorAplicar = 0
TeminarAmortizacion = True
Else
GvRow.FCTextBox("TxtImporte").Text = SaldoFactura.FormatoNumero
GvRow.FCCheckBox("ChkFacturaNC").Checked = True
SaldoNotaPorAplicar = SaldoNotaPorAplicar - SaldoFactura
TeminarAmortizacion = True
End If
End If
CountAplicacion = CountAplicacion + 1
Exit For
End If
If SaldoNotaPorAplicar <= 0 Then
TeminarAmortizacion = True
Exit For
End If
Next
If TeminarAmortizacion Then
Exit For
End If
Next
Dim TipoMensaje As TipoMensaje = TipoMensaje.ToastInformacion
TipoMensaje = If(sbNoencontrados.ToString.Length > 0 Or (SaldoNotaPorAplicar <> 0), TipoMensaje.ToastAdventencia, TipoMensaje)
Dim MsgSalida As String = ""
If sbNoencontrados.ToString.Length > 0 Then
MsgSalida = $"Folios Fiscales no encontradas o sin saldo: {sbNoencontrados } <br/><br/>"
End If
MsgSalida = $"{MsgSalida} Se seleccionó $ {(SaldoNota - SaldoNotaPorAplicar).FormatoNumero} de $ {SaldoNota.FormatoNumero} a {CountAplicacion} factura {If(CountAplicacion > 0, "s", "")}."
Alert(MsgSalida, TipoMensaje)
If CountAplicacion > 0 Then
BtnFacturaNC_Click(Nothing, Nothing)
End If
End If
End Sub
Private Function ObtConceptoContableProvisionCompra(CveTipoConcepto As Integer, TipoDocto As String, CveMoneda As Integer, Optional EsComplementaria As Boolean = False) As Integer
Dim Retorno As Integer = -1
If CveTipoConcepto = 1 Then ''PROVEEDOR
If EsComplementaria Then
Retorno = If(TipoDocto = "Fac", 201, 234)
Return Retorno
End If
If CveMoneda = 1 Then
Retorno = If(TipoDocto = "Fac", 5, 18)
Else
Retorno = If(TipoDocto = "Fac", 311, 341)
End If
Else ''ACREEDOR
If EsComplementaria Then
Retorno = If(TipoDocto = "Fac", -1, -1)
Return Retorno
End If
If CveMoneda = 1 Then
Retorno = If(TipoDocto = "Fac", 305, 323)
Else
Retorno = If(TipoDocto = "Fac", 306, 309)
End If
End If
Return Retorno
End Function
End Class
Public Class MMensajeDevolucion
Public Property CveMovimiento As Integer
Public Property TieneError As Boolean
Public Property DebeRealizarDevolucion As Boolean
Public Property Total As Decimal
End Class